1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <linux/loop.h>
11 #include "blkid-util.h"
12 #include "blockdev-util.h"
13 #include "btrfs-util.h"
14 #include "chattr-util.h"
16 #include "errno-util.h"
20 #include "fsck-util.h"
21 #include "home-util.h"
22 #include "homework-luks.h"
23 #include "homework-mount.h"
24 #include "id128-util.h"
26 #include "memory-util.h"
27 #include "missing_magic.h"
29 #include "mkfs-util.h"
30 #include "mount-util.h"
31 #include "openssl-util.h"
32 #include "parse-util.h"
33 #include "path-util.h"
34 #include "process-util.h"
35 #include "random-util.h"
36 #include "resize-fs.h"
37 #include "stat-util.h"
39 #include "tmpfile-util.h"
41 /* Round down to the nearest 1K size. Note that Linux generally handles block devices with 512 blocks only,
42 * but actually doesn't accept uneven numbers in many cases. To avoid any confusion around this we'll
43 * strictly round disk sizes down to the next 1K boundary. */
44 #define DISK_SIZE_ROUND_DOWN(x) ((x) & ~UINT64_C(1023))
46 int run_mark_dirty(int fd
, bool b
) {
50 /* Sets or removes the 'user.home-dirty' xattr on the specified file. We use this to detect when a
51 * home directory was not properly unmounted. */
55 r
= fd_verify_regular(fd
);
60 ret
= fsetxattr(fd
, "user.home-dirty", &x
, 1, XATTR_CREATE
);
61 if (ret
< 0 && errno
!= EEXIST
)
62 return log_debug_errno(errno
, "Could not mark home directory as dirty: %m");
67 return log_debug_errno(r
, "Failed to synchronize image before marking it clean: %m");
69 ret
= fremovexattr(fd
, "user.home-dirty");
70 if (ret
< 0 && errno
!= ENODATA
)
71 return log_debug_errno(errno
, "Could not mark home directory as clean: %m");
76 return log_debug_errno(r
, "Failed to synchronize dirty flag to disk: %m");
81 int run_mark_dirty_by_path(const char *path
, bool b
) {
82 _cleanup_close_
int fd
= -1;
86 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
);
88 return log_debug_errno(errno
, "Failed to open %s to mark dirty or clean: %m", path
);
90 return run_mark_dirty(fd
, b
);
93 static int probe_file_system_by_fd(
96 sd_id128_t
*ret_uuid
) {
98 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
99 _cleanup_free_
char *s
= NULL
;
100 const char *fstype
= NULL
, *uuid
= NULL
;
108 b
= blkid_new_probe();
113 r
= blkid_probe_set_device(b
, fd
, 0, 0);
115 return errno
> 0 ? -errno
: -ENOMEM
;
117 (void) blkid_probe_enable_superblocks(b
, 1);
118 (void) blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_UUID
);
121 r
= blkid_do_safeprobe(b
);
122 if (IN_SET(r
, -2, 1)) /* nothing found or ambiguous result */
125 return errno
> 0 ? -errno
: -EIO
;
127 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
131 (void) blkid_probe_lookup_value(b
, "UUID", &uuid
, NULL
);
135 r
= sd_id128_from_string(uuid
, &id
);
143 *ret_fstype
= TAKE_PTR(s
);
149 static int probe_file_system_by_path(const char *path
, char **ret_fstype
, sd_id128_t
*ret_uuid
) {
150 _cleanup_close_
int fd
= -1;
152 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
156 return probe_file_system_by_fd(fd
, ret_fstype
, ret_uuid
);
159 static int block_get_size_by_fd(int fd
, uint64_t *ret
) {
165 if (fstat(fd
, &st
) < 0)
168 if (!S_ISBLK(st
.st_mode
))
171 if (ioctl(fd
, BLKGETSIZE64
, ret
) < 0)
177 static int block_get_size_by_path(const char *path
, uint64_t *ret
) {
178 _cleanup_close_
int fd
= -1;
180 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
184 return block_get_size_by_fd(fd
, ret
);
187 static int run_fsck(const char *node
, const char *fstype
) {
194 r
= fsck_exists(fstype
);
196 return log_error_errno(r
, "Failed to check if fsck for file system %s exists: %m", fstype
);
198 log_warning("No fsck for file system %s installed, ignoring.", fstype
);
202 r
= safe_fork("(fsck)",
203 FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_STDOUT_TO_STDERR
|FORK_CLOSE_ALL_FDS
,
209 execl("/sbin/fsck", "/sbin/fsck", "-aTl", node
, NULL
);
211 log_error_errno(errno
, "Failed to execute fsck: %m");
212 _exit(FSCK_OPERATIONAL_ERROR
);
215 exit_status
= wait_for_terminate_and_check("fsck", fsck_pid
, WAIT_LOG_ABNORMAL
);
218 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != 0) {
219 log_warning("fsck failed with exit status %i.", exit_status
);
221 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
222 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "File system is corrupted, refusing.");
224 log_warning("Ignoring fsck error.");
227 log_info("File system check completed.");
232 static int luks_try_passwords(
233 struct crypt_device
*cd
,
236 size_t *volume_key_size
) {
243 STRV_FOREACH(pp
, passwords
) {
244 size_t vks
= *volume_key_size
;
246 r
= sym_crypt_volume_key_get(
254 *volume_key_size
= vks
;
258 log_debug_errno(r
, "Password %zu didn't work for unlocking LUKS superblock: %m", (size_t) (pp
- passwords
));
264 static int luks_setup(
269 const char *cipher_mode
,
270 uint64_t volume_key_size
,
272 const PasswordCache
*cache
,
274 struct crypt_device
**ret
,
275 sd_id128_t
*ret_found_uuid
,
276 void **ret_volume_key
,
277 size_t *ret_volume_key_size
) {
279 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
280 _cleanup_(erase_and_freep
) void *vk
= NULL
;
290 r
= sym_crypt_init(&cd
, node
);
292 return log_error_errno(r
, "Failed to allocate libcryptsetup context: %m");
294 cryptsetup_enable_logging(cd
);
296 r
= sym_crypt_load(cd
, CRYPT_LUKS2
, NULL
);
298 return log_error_errno(r
, "Failed to load LUKS superblock: %m");
300 r
= sym_crypt_get_volume_key_size(cd
);
302 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine LUKS volume key size");
305 if (!sd_id128_is_null(uuid
) || ret_found_uuid
) {
308 s
= sym_crypt_get_uuid(cd
);
310 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has no UUID.");
312 r
= sd_id128_from_string(s
, &p
);
314 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has invalid UUID.");
316 /* Check that the UUID matches, if specified */
317 if (!sd_id128_is_null(uuid
) &&
318 !sd_id128_equal(uuid
, p
))
319 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has wrong UUID.");
322 if (cipher
&& !streq_ptr(cipher
, sym_crypt_get_cipher(cd
)))
323 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong cipher.");
325 if (cipher_mode
&& !streq_ptr(cipher_mode
, sym_crypt_get_cipher_mode(cd
)))
326 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong cipher mode.");
328 if (volume_key_size
!= UINT64_MAX
&& vks
!= volume_key_size
)
329 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong volume key size.");
336 FOREACH_POINTER(list
, cache
->pkcs11_passwords
, cache
->fido2_passwords
, passwords
) {
337 r
= luks_try_passwords(cd
, list
, vk
, &vks
);
342 return log_error_errno(r
, "No valid password for LUKS superblock.");
344 return log_error_errno(r
, "Failed to unlocks LUKS superblock: %m");
346 r
= sym_crypt_activate_by_volume_key(
350 discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
352 return log_error_errno(r
, "Failed to unlock LUKS superblock: %m");
354 log_info("Setting up LUKS device /dev/mapper/%s completed.", dm_name
);
358 if (ret_found_uuid
) /* Return the UUID actually found if the caller wants to know */
361 *ret_volume_key
= TAKE_PTR(vk
);
362 if (ret_volume_key_size
)
363 *ret_volume_key_size
= vks
;
368 static int luks_open(
371 PasswordCache
*cache
,
372 struct crypt_device
**ret
,
373 sd_id128_t
*ret_found_uuid
,
374 void **ret_volume_key
,
375 size_t *ret_volume_key_size
) {
377 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
378 _cleanup_(erase_and_freep
) void *vk
= NULL
;
387 /* Opens a LUKS device that is already set up. Re-validates the password while doing so (which also
388 * provides us with the volume key, which we want). */
390 r
= sym_crypt_init_by_name(&cd
, dm_name
);
392 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
394 cryptsetup_enable_logging(cd
);
396 r
= sym_crypt_load(cd
, CRYPT_LUKS2
, NULL
);
398 return log_error_errno(r
, "Failed to load LUKS superblock: %m");
400 r
= sym_crypt_get_volume_key_size(cd
);
402 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine LUKS volume key size");
405 if (ret_found_uuid
) {
408 s
= sym_crypt_get_uuid(cd
);
410 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has no UUID.");
412 r
= sd_id128_from_string(s
, &p
);
414 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has invalid UUID.");
422 FOREACH_POINTER(list
, cache
->pkcs11_passwords
, cache
->fido2_passwords
, passwords
) {
423 r
= luks_try_passwords(cd
, list
, vk
, &vks
);
428 return log_error_errno(r
, "No valid password for LUKS superblock.");
430 return log_error_errno(r
, "Failed to unlocks LUKS superblock: %m");
432 log_info("Discovered used LUKS device /dev/mapper/%s, and validated password.", dm_name
);
434 /* This is needed so that crypt_resize() can operate correctly for pre-existing LUKS devices. We need
435 * to tell libcryptsetup the volume key explicitly, so that it is in the kernel keyring. */
436 r
= sym_crypt_activate_by_volume_key(cd
, NULL
, vk
, vks
, CRYPT_ACTIVATE_KEYRING_KEY
);
438 return log_error_errno(r
, "Failed to upload volume key again: %m");
440 log_info("Successfully re-activated LUKS device.");
447 *ret_volume_key
= TAKE_PTR(vk
);
448 if (ret_volume_key_size
)
449 *ret_volume_key_size
= vks
;
454 static int fs_validate(
458 sd_id128_t
*ret_found_uuid
) {
460 _cleanup_free_
char *fstype
= NULL
;
467 r
= probe_file_system_by_path(dm_node
, &fstype
, &u
);
469 return log_error_errno(r
, "Failed to probe file system: %m");
471 /* Limit the set of supported file systems a bit, as protection against little tested kernel file
472 * systems. Also, we only support the resize ioctls for these file systems. */
473 if (!supported_fstype(fstype
))
474 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "Image contains unsupported file system: %s", strna(fstype
));
476 if (!sd_id128_is_null(uuid
) &&
477 !sd_id128_equal(uuid
, u
))
478 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "File system has wrong UUID.");
480 log_info("Probing file system completed (found %s).", fstype
);
482 *ret_fstype
= TAKE_PTR(fstype
);
484 if (ret_found_uuid
) /* Return the UUID actually found if the caller wants to know */
490 static int make_dm_names(const char *user_name
, char **ret_dm_name
, char **ret_dm_node
) {
491 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
497 name
= strjoin("home-", user_name
);
501 node
= path_join("/dev/mapper/", name
);
505 *ret_dm_name
= TAKE_PTR(name
);
506 *ret_dm_node
= TAKE_PTR(node
);
510 static int luks_validate(
513 sd_id128_t partition_uuid
,
514 sd_id128_t
*ret_partition_uuid
,
515 uint64_t *ret_offset
,
516 uint64_t *ret_size
) {
518 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
519 sd_id128_t found_partition_uuid
= SD_ID128_NULL
;
520 const char *fstype
= NULL
, *pttype
= NULL
;
521 blkid_loff_t offset
= 0, size
= 0;
531 b
= blkid_new_probe();
536 r
= blkid_probe_set_device(b
, fd
, 0, 0);
538 return errno
> 0 ? -errno
: -ENOMEM
;
540 (void) blkid_probe_enable_superblocks(b
, 1);
541 (void) blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
542 (void) blkid_probe_enable_partitions(b
, 1);
543 (void) blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
546 r
= blkid_do_safeprobe(b
);
547 if (IN_SET(r
, -2, 1)) /* nothing found or ambiguous result */
550 return errno
> 0 ? -errno
: -EIO
;
552 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
553 if (streq_ptr(fstype
, "crypto_LUKS")) {
554 /* Directly a LUKS image */
556 *ret_size
= UINT64_MAX
; /* full disk */
557 *ret_partition_uuid
= SD_ID128_NULL
;
562 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
563 if (!streq_ptr(pttype
, "gpt"))
567 pl
= blkid_probe_get_partitions(b
);
569 return errno
> 0 ? -errno
: -ENOMEM
;
572 n
= blkid_partlist_numof_partitions(pl
);
574 return errno
> 0 ? -errno
: -EIO
;
576 for (int i
= 0; i
< n
; i
++) {
578 sd_id128_t id
= SD_ID128_NULL
;
582 pp
= blkid_partlist_get_partition(pl
, i
);
584 return errno
> 0 ? -errno
: -EIO
;
586 if (!streq_ptr(blkid_partition_get_type_string(pp
), "773f91ef-66d4-49b5-bd83-d683bf40ad16"))
589 if (!streq_ptr(blkid_partition_get_name(pp
), label
))
592 sid
= blkid_partition_get_uuid(pp
);
594 r
= sd_id128_from_string(sid
, &id
);
596 log_debug_errno(r
, "Couldn't parse partition UUID %s, weird: %m", sid
);
598 if (!sd_id128_is_null(partition_uuid
) && !sd_id128_equal(id
, partition_uuid
))
605 offset
= blkid_partition_get_start(pp
);
606 size
= blkid_partition_get_size(pp
);
607 found_partition_uuid
= id
;
617 if ((uint64_t) offset
> UINT64_MAX
/ 512U)
621 if ((uint64_t) size
> UINT64_MAX
/ 512U)
624 *ret_offset
= offset
* 512U;
625 *ret_size
= size
* 512U;
626 *ret_partition_uuid
= found_partition_uuid
;
631 static int crypt_device_to_evp_cipher(struct crypt_device
*cd
, const EVP_CIPHER
**ret
) {
632 _cleanup_free_
char *cipher_name
= NULL
;
633 const char *cipher
, *cipher_mode
, *e
;
634 size_t key_size
, key_bits
;
635 const EVP_CIPHER
*cc
;
640 /* Let's find the right OpenSSL EVP_CIPHER object that matches the encryption settings of the LUKS
643 cipher
= sym_crypt_get_cipher(cd
);
645 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot get cipher from LUKS device.");
647 cipher_mode
= sym_crypt_get_cipher_mode(cd
);
649 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot get cipher mode from LUKS device.");
651 e
= strchr(cipher_mode
, '-');
653 cipher_mode
= strndupa(cipher_mode
, e
- cipher_mode
);
655 r
= sym_crypt_get_volume_key_size(cd
);
657 return log_error_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(EINVAL
), "Cannot get volume key size from LUKS device.");
660 key_bits
= key_size
* 8;
661 if (streq(cipher_mode
, "xts"))
664 if (asprintf(&cipher_name
, "%s-%zu-%s", cipher
, key_bits
, cipher_mode
) < 0)
667 cc
= EVP_get_cipherbyname(cipher_name
);
669 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Selected cipher mode '%s' not supported, can't encrypt JSON record.", cipher_name
);
671 /* Verify that our key length calculations match what OpenSSL thinks */
672 r
= EVP_CIPHER_key_length(cc
);
673 if (r
< 0 || (uint64_t) r
!= key_size
)
674 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Key size of selected cipher doesn't meet our expectations.");
680 static int luks_validate_home_record(
681 struct crypt_device
*cd
,
683 const void *volume_key
,
684 PasswordCache
*cache
,
685 UserRecord
**ret_luks_home_record
) {
692 for (int token
= 0;; token
++) {
693 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
, *rr
= NULL
;
694 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
695 _cleanup_(user_record_unrefp
) UserRecord
*lhr
= NULL
;
696 _cleanup_free_
void *encrypted
= NULL
, *iv
= NULL
;
697 size_t decrypted_size
, encrypted_size
, iv_size
;
698 int decrypted_size_out1
, decrypted_size_out2
;
699 _cleanup_free_
char *decrypted
= NULL
;
700 const char *text
, *type
;
701 crypt_token_info state
;
702 JsonVariant
*jr
, *jiv
;
703 unsigned line
, column
;
704 const EVP_CIPHER
*cc
;
706 state
= sym_crypt_token_status(cd
, token
, &type
);
707 if (state
== CRYPT_TOKEN_INACTIVE
) /* First unconfigured token, give up */
709 if (IN_SET(state
, CRYPT_TOKEN_INTERNAL
, CRYPT_TOKEN_INTERNAL_UNKNOWN
, CRYPT_TOKEN_EXTERNAL
))
711 if (state
!= CRYPT_TOKEN_EXTERNAL_UNKNOWN
)
712 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected token state of token %i: %i", token
, (int) state
);
714 if (!streq(type
, "systemd-homed"))
717 r
= sym_crypt_token_json_get(cd
, token
, &text
);
719 return log_error_errno(r
, "Failed to read LUKS token %i: %m", token
);
721 r
= json_parse(text
, JSON_PARSE_SENSITIVE
, &v
, &line
, &column
);
723 return log_error_errno(r
, "Failed to parse LUKS token JSON data %u:%u: %m", line
, column
);
725 jr
= json_variant_by_key(v
, "record");
727 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "LUKS token lacks 'record' field.");
728 jiv
= json_variant_by_key(v
, "iv");
730 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "LUKS token lacks 'iv' field.");
732 r
= json_variant_unbase64(jr
, &encrypted
, &encrypted_size
);
734 return log_error_errno(r
, "Failed to base64 decode record: %m");
736 r
= json_variant_unbase64(jiv
, &iv
, &iv_size
);
738 return log_error_errno(r
, "Failed to base64 decode IV: %m");
740 r
= crypt_device_to_evp_cipher(cd
, &cc
);
743 if (iv_size
> INT_MAX
|| EVP_CIPHER_iv_length(cc
) != (int) iv_size
)
744 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "IV size doesn't match.");
746 context
= EVP_CIPHER_CTX_new();
750 if (EVP_DecryptInit_ex(context
, cc
, NULL
, volume_key
, iv
) != 1)
751 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize decryption context.");
753 decrypted_size
= encrypted_size
+ EVP_CIPHER_key_length(cc
) * 2;
754 decrypted
= new(char, decrypted_size
);
758 if (EVP_DecryptUpdate(context
, (uint8_t*) decrypted
, &decrypted_size_out1
, encrypted
, encrypted_size
) != 1)
759 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to decrypt JSON record.");
761 assert((size_t) decrypted_size_out1
<= decrypted_size
);
763 if (EVP_DecryptFinal_ex(context
, (uint8_t*) decrypted
+ decrypted_size_out1
, &decrypted_size_out2
) != 1)
764 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finish decryption of JSON record.");
766 assert((size_t) decrypted_size_out1
+ (size_t) decrypted_size_out2
< decrypted_size
);
767 decrypted_size
= (size_t) decrypted_size_out1
+ (size_t) decrypted_size_out2
;
769 if (memchr(decrypted
, 0, decrypted_size
))
770 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Inner NUL byte in JSON record, refusing.");
772 decrypted
[decrypted_size
] = 0;
774 r
= json_parse(decrypted
, JSON_PARSE_SENSITIVE
, &rr
, NULL
, NULL
);
776 return log_error_errno(r
, "Failed to parse decrypted JSON record, refusing.");
778 lhr
= user_record_new();
782 r
= user_record_load(lhr
, rr
, USER_RECORD_LOAD_EMBEDDED
|USER_RECORD_PERMISSIVE
);
784 return log_error_errno(r
, "Failed to parse user record: %m");
786 if (!user_record_compatible(h
, lhr
))
787 return log_error_errno(SYNTHETIC_ERRNO(EREMCHG
), "LUKS home record not compatible with host record, refusing.");
789 r
= user_record_authenticate(lhr
, h
, cache
, /* strict_verify= */ true);
792 assert(r
> 0); /* Insist that a password was verified */
794 *ret_luks_home_record
= TAKE_PTR(lhr
);
798 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Couldn't find home record in LUKS2 header, refusing.");
801 static int format_luks_token_text(
802 struct crypt_device
*cd
,
804 const void *volume_key
,
807 int r
, encrypted_size_out1
= 0, encrypted_size_out2
= 0, iv_size
, key_size
;
808 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
809 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
810 _cleanup_free_
void *iv
= NULL
, *encrypted
= NULL
;
811 size_t text_length
, encrypted_size
;
812 _cleanup_free_
char *text
= NULL
;
813 const EVP_CIPHER
*cc
;
820 r
= crypt_device_to_evp_cipher(cd
, &cc
);
824 key_size
= EVP_CIPHER_key_length(cc
);
825 iv_size
= EVP_CIPHER_iv_length(cc
);
828 iv
= malloc(iv_size
);
832 r
= genuine_random_bytes(iv
, iv_size
, RANDOM_BLOCK
);
834 return log_error_errno(r
, "Failed to generate IV: %m");
837 context
= EVP_CIPHER_CTX_new();
841 if (EVP_EncryptInit_ex(context
, cc
, NULL
, volume_key
, iv
) != 1)
842 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize encryption context.");
844 r
= json_variant_format(hr
->json
, 0, &text
);
846 return log_error_errno(r
, "Failed to format user record for LUKS: %m");
848 text_length
= strlen(text
);
849 encrypted_size
= text_length
+ 2*key_size
- 1;
851 encrypted
= malloc(encrypted_size
);
855 if (EVP_EncryptUpdate(context
, encrypted
, &encrypted_size_out1
, (uint8_t*) text
, text_length
) != 1)
856 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to encrypt JSON record.");
858 assert((size_t) encrypted_size_out1
<= encrypted_size
);
860 if (EVP_EncryptFinal_ex(context
, (uint8_t*) encrypted
+ encrypted_size_out1
, &encrypted_size_out2
) != 1)
861 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finish encryption of JSON record. ");
863 assert((size_t) encrypted_size_out1
+ (size_t) encrypted_size_out2
<= encrypted_size
);
867 JSON_BUILD_PAIR("type", JSON_BUILD_STRING("systemd-homed")),
868 JSON_BUILD_PAIR("keyslots", JSON_BUILD_EMPTY_ARRAY
),
869 JSON_BUILD_PAIR("record", JSON_BUILD_BASE64(encrypted
, encrypted_size_out1
+ encrypted_size_out2
)),
870 JSON_BUILD_PAIR("iv", JSON_BUILD_BASE64(iv
, iv_size
))));
872 return log_error_errno(r
, "Failed to prepare LUKS JSON token object: %m");
874 r
= json_variant_format(v
, 0, ret
);
876 return log_error_errno(r
, "Failed to format encrypted user record for LUKS: %m");
881 int home_store_header_identity_luks(
884 UserRecord
*old_home
) {
886 _cleanup_(user_record_unrefp
) UserRecord
*header_home
= NULL
;
887 _cleanup_free_
char *text
= NULL
;
892 if (!setup
->crypt_device
)
895 assert(setup
->volume_key
);
897 /* Let's store the user's identity record in the LUKS2 "token" header data fields, in an encrypted
898 * fashion. Why that? If we'd rely on the record being embedded in the payload file system itself we
899 * would have to mount the file system before we can validate the JSON record, its signatures and
900 * whether it matches what we are looking for. However, kernel file system implementations are
901 * generally not ready to be used on untrusted media. Hence let's store the record independently of
902 * the file system, so that we can validate it first, and only then mount the file system. To keep
903 * things simple we use the same encryption settings for this record as for the file system itself. */
905 r
= user_record_clone(h
, USER_RECORD_EXTRACT_EMBEDDED
|USER_RECORD_PERMISSIVE
, &header_home
);
907 return log_error_errno(r
, "Failed to determine new header record: %m");
909 if (old_home
&& user_record_equal(old_home
, header_home
)) {
910 log_debug("Not updating header home record.");
914 r
= format_luks_token_text(setup
->crypt_device
, header_home
, setup
->volume_key
, &text
);
919 crypt_token_info state
;
922 state
= sym_crypt_token_status(setup
->crypt_device
, token
, &type
);
923 if (state
== CRYPT_TOKEN_INACTIVE
) /* First unconfigured token, we are done */
925 if (IN_SET(state
, CRYPT_TOKEN_INTERNAL
, CRYPT_TOKEN_INTERNAL_UNKNOWN
, CRYPT_TOKEN_EXTERNAL
))
926 continue; /* Not ours */
927 if (state
!= CRYPT_TOKEN_EXTERNAL_UNKNOWN
)
928 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected token state of token %i: %i", token
, (int) state
);
930 if (!streq(type
, "systemd-homed"))
933 r
= sym_crypt_token_json_set(setup
->crypt_device
, token
, text
);
935 return log_error_errno(r
, "Failed to set JSON token for slot %i: %m", token
);
937 /* Now, let's free the text so that for all further matching tokens we all crypt_json_token_set()
938 * with a NULL text in order to invalidate the tokens. */
944 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Didn't find any record token to update.");
946 log_info("Wrote LUKS header user record.");
951 int run_fitrim(int root_fd
) {
952 struct fstrim_range range
= {
956 /* If discarding is on, discard everything right after mounting, so that the discard setting takes
957 * effect on activation. (Also, optionally, trim on logout) */
959 assert(root_fd
>= 0);
961 if (ioctl(root_fd
, FITRIM
, &range
) < 0) {
962 if (ERRNO_IS_NOT_SUPPORTED(errno
) || errno
== EBADF
) {
963 log_debug_errno(errno
, "File system does not support FITRIM, not trimming.");
967 return log_warning_errno(errno
, "Failed to invoke FITRIM, ignoring: %m");
970 log_info("Discarded unused %s.", FORMAT_BYTES(range
.len
));
974 int run_fitrim_by_path(const char *root_path
) {
975 _cleanup_close_
int root_fd
= -1;
977 root_fd
= open(root_path
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
);
979 return log_error_errno(errno
, "Failed to open file system '%s' for trimming: %m", root_path
);
981 return run_fitrim(root_fd
);
984 int run_fallocate(int backing_fd
, const struct stat
*st
) {
987 assert(backing_fd
>= 0);
989 /* If discarding is off, let's allocate the whole image before mounting, so that the setting takes
990 * effect on activation */
993 if (fstat(backing_fd
, &stbuf
) < 0)
994 return log_error_errno(errno
, "Failed to fstat(): %m");
999 if (!S_ISREG(st
->st_mode
))
1002 if (st
->st_blocks
>= DIV_ROUND_UP(st
->st_size
, 512)) {
1003 log_info("Backing file is fully allocated already.");
1007 if (fallocate(backing_fd
, FALLOC_FL_KEEP_SIZE
, 0, st
->st_size
) < 0) {
1009 if (ERRNO_IS_NOT_SUPPORTED(errno
)) {
1010 log_debug_errno(errno
, "fallocate() not supported on file system, ignoring.");
1014 if (ERRNO_IS_DISK_SPACE(errno
)) {
1015 log_debug_errno(errno
, "Not enough disk space to fully allocate home.");
1016 return -ENOSPC
; /* make recognizable */
1019 return log_error_errno(errno
, "Failed to allocate backing file blocks: %m");
1022 log_info("Allocated additional %s.",
1023 FORMAT_BYTES((DIV_ROUND_UP(st
->st_size
, 512) - st
->st_blocks
) * 512));
1027 int run_fallocate_by_path(const char *backing_path
) {
1028 _cleanup_close_
int backing_fd
= -1;
1030 backing_fd
= open(backing_path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
1032 return log_error_errno(errno
, "Failed to open '%s' for fallocate(): %m", backing_path
);
1034 return run_fallocate(backing_fd
, NULL
);
1037 int home_prepare_luks(
1039 bool already_activated
,
1040 const char *force_image_path
,
1041 PasswordCache
*cache
,
1043 UserRecord
**ret_luks_home
) {
1045 sd_id128_t found_partition_uuid
, found_luks_uuid
, found_fs_uuid
;
1046 _cleanup_(user_record_unrefp
) UserRecord
*luks_home
= NULL
;
1047 _cleanup_(loop_device_unrefp
) LoopDevice
*loop
= NULL
;
1048 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1049 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
1050 _cleanup_close_
int root_fd
= -1, image_fd
= -1;
1051 bool dm_activated
= false, mounted
= false;
1052 size_t volume_key_size
= 0;
1053 bool marked_dirty
= false;
1054 uint64_t offset
, size
;
1059 assert(setup
->dm_name
);
1060 assert(setup
->dm_node
);
1062 assert(user_record_storage(h
) == USER_LUKS
);
1064 r
= dlopen_cryptsetup();
1068 if (already_activated
) {
1069 struct loop_info64 info
;
1072 r
= luks_open(setup
->dm_name
,
1082 r
= luks_validate_home_record(cd
, h
, volume_key
, cache
, &luks_home
);
1086 n
= sym_crypt_get_device_name(cd
);
1088 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine backing device for DM %s.", setup
->dm_name
);
1090 r
= loop_device_open(n
, O_RDWR
, &loop
);
1092 return log_error_errno(r
, "Failed to open loopback device %s: %m", n
);
1094 if (ioctl(loop
->fd
, LOOP_GET_STATUS64
, &info
) < 0) {
1095 _cleanup_free_
char *sysfs
= NULL
;
1098 if (!IN_SET(errno
, ENOTTY
, EINVAL
))
1099 return log_error_errno(errno
, "Failed to get block device metrics of %s: %m", n
);
1101 if (ioctl(loop
->fd
, BLKGETSIZE64
, &size
) < 0)
1102 return log_error_errno(r
, "Failed to read block device size of %s: %m", n
);
1104 if (fstat(loop
->fd
, &st
) < 0)
1105 return log_error_errno(r
, "Failed to stat block device %s: %m", n
);
1106 assert(S_ISBLK(st
.st_mode
));
1108 if (asprintf(&sysfs
, "/sys/dev/block/%u:%u/partition", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
1111 if (access(sysfs
, F_OK
) < 0) {
1112 if (errno
!= ENOENT
)
1113 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", sysfs
);
1117 _cleanup_free_
char *buffer
= NULL
;
1119 if (asprintf(&sysfs
, "/sys/dev/block/%u:%u/start", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
1122 r
= read_one_line_file(sysfs
, &buffer
);
1124 return log_error_errno(r
, "Failed to read partition start offset: %m");
1126 r
= safe_atou64(buffer
, &offset
);
1128 return log_error_errno(r
, "Failed to parse partition start offset: %m");
1130 if (offset
> UINT64_MAX
/ 512U)
1131 return log_error_errno(SYNTHETIC_ERRNO(E2BIG
), "Offset too large for 64 byte range, refusing.");
1136 offset
= info
.lo_offset
;
1137 size
= info
.lo_sizelimit
;
1140 found_partition_uuid
= found_fs_uuid
= SD_ID128_NULL
;
1142 log_info("Discovered used loopback device %s.", loop
->node
);
1144 root_fd
= open(user_record_home_directory(h
), O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
1146 r
= log_error_errno(r
, "Failed to open home directory: %m");
1150 _cleanup_free_
char *fstype
= NULL
, *subdir
= NULL
;
1154 ip
= force_image_path
?: user_record_image_path(h
);
1156 subdir
= path_join("/run/systemd/user-home-mount/", user_record_user_name_and_realm(h
));
1160 image_fd
= open(ip
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
1162 return log_error_errno(errno
, "Failed to open image file %s: %m", ip
);
1164 if (fstat(image_fd
, &st
) < 0)
1165 return log_error_errno(errno
, "Failed to fstat() image file: %m");
1166 if (!S_ISREG(st
.st_mode
) && !S_ISBLK(st
.st_mode
))
1167 return log_error_errno(
1168 S_ISDIR(st
.st_mode
) ? SYNTHETIC_ERRNO(EISDIR
) : SYNTHETIC_ERRNO(EBADFD
),
1169 "Image file %s is not a regular file or block device: %m", ip
);
1171 r
= luks_validate(image_fd
, user_record_user_name_and_realm(h
), h
->partition_uuid
, &found_partition_uuid
, &offset
, &size
);
1173 return log_error_errno(r
, "Failed to validate disk label: %m");
1175 /* Everything before this point left the image untouched. We are now starting to make
1176 * changes, hence mark the image dirty */
1177 marked_dirty
= run_mark_dirty(image_fd
, true) > 0;
1179 if (!user_record_luks_discard(h
)) {
1180 r
= run_fallocate(image_fd
, &st
);
1185 r
= loop_device_make(image_fd
, O_RDWR
, offset
, size
, 0, &loop
);
1187 log_error_errno(r
, "Loopback block device support is not available on this system.");
1188 return -ENOLINK
; /* make recognizable */
1191 return log_error_errno(r
, "Failed to allocate loopback context: %m");
1193 log_info("Setting up loopback device %s completed.", loop
->node
?: ip
);
1195 r
= luks_setup(loop
->node
?: ip
,
1199 h
->luks_cipher_mode
,
1200 h
->luks_volume_key_size
,
1203 user_record_luks_discard(h
) || user_record_luks_offline_discard(h
),
1211 dm_activated
= true;
1213 r
= luks_validate_home_record(cd
, h
, volume_key
, cache
, &luks_home
);
1217 r
= fs_validate(setup
->dm_node
, h
->file_system_uuid
, &fstype
, &found_fs_uuid
);
1221 r
= run_fsck(setup
->dm_node
, fstype
);
1225 r
= home_unshare_and_mount(setup
->dm_node
, fstype
, user_record_luks_discard(h
), user_record_mount_flags(h
));
1231 root_fd
= open(subdir
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
1233 r
= log_error_errno(r
, "Failed to open home directory: %m");
1237 if (user_record_luks_discard(h
))
1238 (void) run_fitrim(root_fd
);
1240 setup
->image_fd
= TAKE_FD(image_fd
);
1241 setup
->do_offline_fallocate
= !(setup
->do_offline_fitrim
= user_record_luks_offline_discard(h
));
1242 setup
->do_mark_clean
= marked_dirty
;
1245 setup
->loop
= TAKE_PTR(loop
);
1246 setup
->crypt_device
= TAKE_PTR(cd
);
1247 setup
->root_fd
= TAKE_FD(root_fd
);
1248 setup
->found_partition_uuid
= found_partition_uuid
;
1249 setup
->found_luks_uuid
= found_luks_uuid
;
1250 setup
->found_fs_uuid
= found_fs_uuid
;
1251 setup
->partition_offset
= offset
;
1252 setup
->partition_size
= size
;
1253 setup
->volume_key
= TAKE_PTR(volume_key
);
1254 setup
->volume_key_size
= volume_key_size
;
1256 setup
->undo_mount
= mounted
;
1257 setup
->undo_dm
= dm_activated
;
1260 *ret_luks_home
= TAKE_PTR(luks_home
);
1266 (void) umount_verbose(LOG_ERR
, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW
);
1269 (void) sym_crypt_deactivate_by_name(cd
, setup
->dm_name
, 0);
1271 if (image_fd
>= 0 && marked_dirty
)
1272 (void) run_mark_dirty(image_fd
, false);
1277 static void print_size_summary(uint64_t host_size
, uint64_t encrypted_size
, struct statfs
*sfs
) {
1280 log_info("Image size is %s, file system size is %s, file system payload size is %s, file system free is %s.",
1281 FORMAT_BYTES(host_size
),
1282 FORMAT_BYTES(encrypted_size
),
1283 FORMAT_BYTES((uint64_t) sfs
->f_blocks
* (uint64_t) sfs
->f_frsize
),
1284 FORMAT_BYTES((uint64_t) sfs
->f_bfree
* (uint64_t) sfs
->f_frsize
));
1287 int home_activate_luks(
1289 PasswordCache
*cache
,
1290 UserRecord
**ret_home
) {
1292 _cleanup_(user_record_unrefp
) UserRecord
*new_home
= NULL
, *luks_home_record
= NULL
;
1293 _cleanup_(home_setup_undo
) HomeSetup setup
= HOME_SETUP_INIT
;
1294 uint64_t host_size
, encrypted_size
;
1295 const char *hdo
, *hd
;
1300 assert(user_record_storage(h
) == USER_LUKS
);
1303 r
= dlopen_cryptsetup();
1307 assert_se(hdo
= user_record_home_directory(h
));
1308 hd
= strdupa(hdo
); /* copy the string out, since it might change later in the home record object */
1310 r
= make_dm_names(h
->user_name
, &setup
.dm_name
, &setup
.dm_node
);
1314 r
= access(setup
.dm_node
, F_OK
);
1316 if (errno
!= ENOENT
)
1317 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", setup
.dm_node
);
1319 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "Device mapper device %s already exists, refusing.", setup
.dm_node
);
1321 r
= home_prepare_luks(
1331 r
= block_get_size_by_fd(setup
.loop
->fd
, &host_size
);
1333 return log_error_errno(r
, "Failed to get loopback block device size: %m");
1335 r
= block_get_size_by_path(setup
.dm_node
, &encrypted_size
);
1337 return log_error_errno(r
, "Failed to get LUKS block device size: %m");
1349 r
= home_extend_embedded_identity(new_home
, h
, &setup
);
1353 setup
.root_fd
= safe_close(setup
.root_fd
);
1355 r
= home_move_mount(user_record_user_name_and_realm(h
), hd
);
1359 setup
.undo_mount
= false;
1360 setup
.do_offline_fitrim
= false;
1362 loop_device_relinquish(setup
.loop
);
1364 r
= sym_crypt_deactivate_by_name(NULL
, setup
.dm_name
, CRYPT_DEACTIVATE_DEFERRED
);
1366 log_warning_errno(r
, "Failed to relinquish DM device, ignoring: %m");
1368 setup
.undo_dm
= false;
1369 setup
.do_offline_fallocate
= false;
1370 setup
.do_mark_clean
= false;
1372 log_info("Everything completed.");
1374 print_size_summary(host_size
, encrypted_size
, &sfs
);
1376 *ret_home
= TAKE_PTR(new_home
);
1380 int home_deactivate_luks(UserRecord
*h
) {
1381 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1382 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
1386 /* Note that the DM device and loopback device are set to auto-detach, hence strictly speaking we
1387 * don't have to explicitly have to detach them. However, we do that nonetheless (in case of the DM
1388 * device), to avoid races: by explicitly detaching them we know when the detaching is complete. We
1389 * don't bother about the loopback device because unlike the DM device it doesn't have a fixed
1392 r
= dlopen_cryptsetup();
1396 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
1400 r
= sym_crypt_init_by_name(&cd
, dm_name
);
1401 if (IN_SET(r
, -ENODEV
, -EINVAL
, -ENOENT
)) {
1402 log_debug_errno(r
, "LUKS device %s has already been detached.", dm_name
);
1403 we_detached
= false;
1405 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
1407 log_info("Discovered used LUKS device %s.", dm_node
);
1409 cryptsetup_enable_logging(cd
);
1411 r
= sym_crypt_deactivate_by_name(cd
, dm_name
, 0);
1412 if (IN_SET(r
, -ENODEV
, -EINVAL
, -ENOENT
)) {
1413 log_debug_errno(r
, "LUKS device %s is already detached.", dm_node
);
1414 we_detached
= false;
1416 return log_info_errno(r
, "LUKS device %s couldn't be deactivated: %m", dm_node
);
1418 log_info("LUKS device detaching completed.");
1423 if (user_record_luks_offline_discard(h
))
1424 log_debug("Not allocating on logout.");
1426 (void) run_fallocate_by_path(user_record_image_path(h
));
1428 run_mark_dirty_by_path(user_record_image_path(h
), false);
1432 int home_trim_luks(UserRecord
*h
) {
1435 if (!user_record_luks_offline_discard(h
)) {
1436 log_debug("Not trimming on logout.");
1440 (void) run_fitrim_by_path(user_record_home_directory(h
));
1444 static struct crypt_pbkdf_type
* build_good_pbkdf(struct crypt_pbkdf_type
*buffer
, UserRecord
*hr
) {
1448 *buffer
= (struct crypt_pbkdf_type
) {
1449 .hash
= user_record_luks_pbkdf_hash_algorithm(hr
),
1450 .type
= user_record_luks_pbkdf_type(hr
),
1451 .time_ms
= user_record_luks_pbkdf_time_cost_usec(hr
) / USEC_PER_MSEC
,
1452 .max_memory_kb
= user_record_luks_pbkdf_memory_cost(hr
) / 1024,
1453 .parallel_threads
= user_record_luks_pbkdf_parallel_threads(hr
),
1459 static struct crypt_pbkdf_type
* build_minimal_pbkdf(struct crypt_pbkdf_type
*buffer
, UserRecord
*hr
) {
1463 /* For PKCS#11 derived keys (which are generated randomly and are of high quality already) we use a
1465 *buffer
= (struct crypt_pbkdf_type
) {
1466 .hash
= user_record_luks_pbkdf_hash_algorithm(hr
),
1467 .type
= CRYPT_KDF_PBKDF2
,
1475 static int luks_format(
1477 const char *dm_name
,
1480 const PasswordCache
*cache
,
1481 char **effective_passwords
,
1484 struct crypt_device
**ret
) {
1486 _cleanup_(user_record_unrefp
) UserRecord
*reduced
= NULL
;
1487 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1488 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
1489 struct crypt_pbkdf_type good_pbkdf
, minimal_pbkdf
;
1490 _cleanup_free_
char *text
= NULL
;
1491 size_t volume_key_size
;
1500 r
= sym_crypt_init(&cd
, node
);
1502 return log_error_errno(r
, "Failed to allocate libcryptsetup context: %m");
1504 cryptsetup_enable_logging(cd
);
1506 /* Normally we'd, just leave volume key generation to libcryptsetup. However, we can't, since we
1507 * can't extract the volume key from the library again, but we need it in order to encrypt the JSON
1508 * record. Hence, let's generate it on our own, so that we can keep track of it. */
1510 volume_key_size
= user_record_luks_volume_key_size(hr
);
1511 volume_key
= malloc(volume_key_size
);
1515 r
= genuine_random_bytes(volume_key
, volume_key_size
, RANDOM_BLOCK
);
1517 return log_error_errno(r
, "Failed to generate volume key: %m");
1519 #if HAVE_CRYPT_SET_METADATA_SIZE
1520 /* Increase the metadata space to 4M, the largest LUKS2 supports */
1521 r
= sym_crypt_set_metadata_size(cd
, 4096U*1024U, 0);
1523 return log_error_errno(r
, "Failed to change LUKS2 metadata size: %m");
1526 build_good_pbkdf(&good_pbkdf
, hr
);
1527 build_minimal_pbkdf(&minimal_pbkdf
, hr
);
1529 r
= sym_crypt_format(
1532 user_record_luks_cipher(hr
),
1533 user_record_luks_cipher_mode(hr
),
1534 ID128_TO_UUID_STRING(uuid
),
1537 &(struct crypt_params_luks2
) {
1539 .subsystem
= "systemd-home",
1540 .sector_size
= 512U,
1541 .pbkdf
= &good_pbkdf
,
1544 return log_error_errno(r
, "Failed to format LUKS image: %m");
1546 log_info("LUKS formatting completed.");
1548 STRV_FOREACH(pp
, effective_passwords
) {
1550 if (strv_contains(cache
->pkcs11_passwords
, *pp
) ||
1551 strv_contains(cache
->fido2_passwords
, *pp
)) {
1552 log_debug("Using minimal PBKDF for slot %i", slot
);
1553 r
= sym_crypt_set_pbkdf_type(cd
, &minimal_pbkdf
);
1555 log_debug("Using good PBKDF for slot %i", slot
);
1556 r
= sym_crypt_set_pbkdf_type(cd
, &good_pbkdf
);
1559 return log_error_errno(r
, "Failed to tweak PBKDF for slot %i: %m", slot
);
1561 r
= sym_crypt_keyslot_add_by_volume_key(
1569 return log_error_errno(r
, "Failed to set up LUKS password for slot %i: %m", slot
);
1571 log_info("Writing password to LUKS keyslot %i completed.", slot
);
1575 r
= sym_crypt_activate_by_volume_key(
1580 discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
1582 return log_error_errno(r
, "Failed to activate LUKS superblock: %m");
1584 log_info("LUKS activation by volume key succeeded.");
1586 r
= user_record_clone(hr
, USER_RECORD_EXTRACT_EMBEDDED
|USER_RECORD_PERMISSIVE
, &reduced
);
1588 return log_error_errno(r
, "Failed to prepare home record for LUKS: %m");
1590 r
= format_luks_token_text(cd
, reduced
, volume_key
, &text
);
1594 r
= sym_crypt_token_json_set(cd
, CRYPT_ANY_TOKEN
, text
);
1596 return log_error_errno(r
, "Failed to set LUKS JSON token: %m");
1598 log_info("Writing user record as LUKS token completed.");
1601 *ret
= TAKE_PTR(cd
);
1606 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_context
*, fdisk_unref_context
, NULL
);
1607 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_partition
*, fdisk_unref_partition
, NULL
);
1608 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_parttype
*, fdisk_unref_parttype
, NULL
);
1609 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_table
*, fdisk_unref_table
, NULL
);
1611 static int make_partition_table(
1615 uint64_t *ret_offset
,
1617 sd_id128_t
*ret_disk_uuid
) {
1619 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*p
= NULL
, *q
= NULL
;
1620 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
1621 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1622 _cleanup_free_
char *path
= NULL
, *disk_uuid_as_string
= NULL
;
1623 uint64_t offset
, size
;
1624 sd_id128_t disk_uuid
;
1632 t
= fdisk_new_parttype();
1636 r
= fdisk_parttype_set_typestr(t
, "773f91ef-66d4-49b5-bd83-d683bf40ad16");
1638 return log_error_errno(r
, "Failed to initialize partition type: %m");
1640 c
= fdisk_new_context();
1644 if (asprintf(&path
, "/proc/self/fd/%i", fd
) < 0)
1647 r
= fdisk_assign_device(c
, path
, 0);
1649 return log_error_errno(r
, "Failed to open device: %m");
1651 r
= fdisk_create_disklabel(c
, "gpt");
1653 return log_error_errno(r
, "Failed to create GPT disk label: %m");
1655 p
= fdisk_new_partition();
1659 r
= fdisk_partition_set_type(p
, t
);
1661 return log_error_errno(r
, "Failed to set partition type: %m");
1663 r
= fdisk_partition_start_follow_default(p
, 1);
1665 return log_error_errno(r
, "Failed to place partition at beginning of space: %m");
1667 r
= fdisk_partition_partno_follow_default(p
, 1);
1669 return log_error_errno(r
, "Failed to place partition at first free partition index: %m");
1671 r
= fdisk_partition_end_follow_default(p
, 1);
1673 return log_error_errno(r
, "Failed to make partition cover all free space: %m");
1675 r
= fdisk_partition_set_name(p
, label
);
1677 return log_error_errno(r
, "Failed to set partition name: %m");
1679 r
= fdisk_partition_set_uuid(p
, ID128_TO_UUID_STRING(uuid
));
1681 return log_error_errno(r
, "Failed to set partition UUID: %m");
1683 r
= fdisk_add_partition(c
, p
, NULL
);
1685 return log_error_errno(r
, "Failed to add partition: %m");
1687 r
= fdisk_write_disklabel(c
);
1689 return log_error_errno(r
, "Failed to write disk label: %m");
1691 r
= fdisk_get_disklabel_id(c
, &disk_uuid_as_string
);
1693 return log_error_errno(r
, "Failed to determine disk label UUID: %m");
1695 r
= sd_id128_from_string(disk_uuid_as_string
, &disk_uuid
);
1697 return log_error_errno(r
, "Failed to parse disk label UUID: %m");
1699 r
= fdisk_get_partition(c
, 0, &q
);
1701 return log_error_errno(r
, "Failed to read created partition metadata: %m");
1703 assert(fdisk_partition_has_start(q
));
1704 offset
= fdisk_partition_get_start(q
);
1705 if (offset
> UINT64_MAX
/ 512U)
1706 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Partition offset too large.");
1708 assert(fdisk_partition_has_size(q
));
1709 size
= fdisk_partition_get_size(q
);
1710 if (size
> UINT64_MAX
/ 512U)
1711 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Partition size too large.");
1713 *ret_offset
= offset
* 512U;
1714 *ret_size
= size
* 512U;
1715 *ret_disk_uuid
= disk_uuid
;
1720 static bool supported_fs_size(const char *fstype
, uint64_t host_size
) {
1723 m
= minimal_size_by_fs_name(fstype
);
1724 if (m
== UINT64_MAX
)
1727 return host_size
>= m
;
1730 static int wait_for_devlink(const char *path
) {
1731 _cleanup_close_
int inotify_fd
= -1;
1735 /* let's wait for a device link to show up in /dev, with a timeout. This is good to do since we
1736 * return a /dev/disk/by-uuid/… link to our callers and they likely want to access it right-away,
1737 * hence let's wait until udev has caught up with our changes, and wait for the symlink to be
1740 until
= usec_add(now(CLOCK_MONOTONIC
), 45 * USEC_PER_SEC
);
1743 _cleanup_free_
char *dn
= NULL
;
1746 if (laccess(path
, F_OK
) < 0) {
1747 if (errno
!= ENOENT
)
1748 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", path
);
1750 return 0; /* Found it */
1752 if (inotify_fd
< 0) {
1753 /* We need to wait for the device symlink to show up, let's create an inotify watch for it */
1754 inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
1756 return log_error_errno(errno
, "Failed to allocate inotify fd: %m");
1759 dn
= dirname_malloc(path
);
1764 log_info("Watching %s", dn
);
1766 if (inotify_add_watch(inotify_fd
, dn
, IN_CREATE
|IN_MOVED_TO
|IN_ONLYDIR
|IN_DELETE_SELF
|IN_MOVE_SELF
) < 0) {
1767 if (errno
!= ENOENT
)
1768 return log_error_errno(errno
, "Failed to add watch on %s: %m", dn
);
1772 if (empty_or_root(dn
))
1775 dn
= dirname_malloc(dn
);
1778 w
= now(CLOCK_MONOTONIC
);
1780 return log_error_errno(SYNTHETIC_ERRNO(ETIMEDOUT
), "Device link %s still hasn't shown up, giving up.", path
);
1782 r
= fd_wait_for_event(inotify_fd
, POLLIN
, usec_sub_unsigned(until
, w
));
1784 return log_error_errno(r
, "Failed to watch inotify: %m");
1786 (void) flush_fd(inotify_fd
);
1790 static int calculate_disk_size(UserRecord
*h
, const char *parent_dir
, uint64_t *ret
) {
1798 if (h
->disk_size
!= UINT64_MAX
) {
1799 *ret
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
1803 if (statfs(parent_dir
, &sfs
) < 0)
1804 return log_error_errno(errno
, "statfs() on %s failed: %m", parent_dir
);
1806 m
= sfs
.f_bsize
* sfs
.f_bavail
;
1808 if (h
->disk_size_relative
== UINT64_MAX
) {
1810 if (m
> UINT64_MAX
/ USER_DISK_SIZE_DEFAULT_PERCENT
)
1811 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Disk size too large.");
1813 *ret
= DISK_SIZE_ROUND_DOWN(m
* USER_DISK_SIZE_DEFAULT_PERCENT
/ 100);
1815 log_info("Sizing home to %u%% of available disk space, which is %s.",
1816 USER_DISK_SIZE_DEFAULT_PERCENT
,
1817 FORMAT_BYTES(*ret
));
1819 *ret
= DISK_SIZE_ROUND_DOWN((uint64_t) ((double) m
* (double) h
->disk_size_relative
/ (double) UINT32_MAX
));
1821 log_info("Sizing home to %" PRIu64
".%01" PRIu64
"%% of available disk space, which is %s.",
1822 (h
->disk_size_relative
* 100) / UINT32_MAX
,
1823 ((h
->disk_size_relative
* 1000) / UINT32_MAX
) % 10,
1824 FORMAT_BYTES(*ret
));
1827 if (*ret
< USER_DISK_SIZE_MIN
)
1828 *ret
= USER_DISK_SIZE_MIN
;
1833 static int home_truncate(
1846 trunc
= user_record_luks_discard(h
);
1848 r
= fallocate(fd
, 0, 0, size
);
1849 if (r
< 0 && ERRNO_IS_NOT_SUPPORTED(errno
)) {
1850 /* Some file systems do not support fallocate(), let's gracefully degrade
1851 * (ZFS, reiserfs, …) and fall back to truncation */
1852 log_notice_errno(errno
, "Backing file system does not support fallocate(), falling back to ftruncate(), i.e. implicitly using non-discard mode.");
1858 r
= ftruncate(fd
, size
);
1861 if (ERRNO_IS_DISK_SPACE(errno
)) {
1862 log_error_errno(errno
, "Not enough disk space to allocate home.");
1863 return -ENOSPC
; /* make recognizable */
1866 return log_error_errno(errno
, "Failed to truncate home image %s: %m", path
);
1872 int home_create_luks(
1874 PasswordCache
*cache
,
1875 char **effective_passwords
,
1876 UserRecord
**ret_home
) {
1878 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
, *subdir
= NULL
, *disk_uuid_path
= NULL
, *temporary_image_path
= NULL
;
1879 uint64_t encrypted_size
,
1880 host_size
= 0, partition_offset
= 0, partition_size
= 0; /* Unnecessary initialization to appease gcc */
1881 bool image_created
= false, dm_activated
= false, mounted
= false;
1882 _cleanup_(user_record_unrefp
) UserRecord
*new_home
= NULL
;
1883 sd_id128_t partition_uuid
, fs_uuid
, luks_uuid
, disk_uuid
;
1884 _cleanup_(loop_device_unrefp
) LoopDevice
*loop
= NULL
;
1885 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1886 _cleanup_close_
int image_fd
= -1, root_fd
= -1;
1887 const char *fstype
, *ip
;
1892 assert(h
->storage
< 0 || h
->storage
== USER_LUKS
);
1895 r
= dlopen_cryptsetup();
1899 assert_se(ip
= user_record_image_path(h
));
1901 fstype
= user_record_file_system_type(h
);
1902 if (!supported_fstype(fstype
))
1903 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "Unsupported file system type: %s", fstype
);
1905 r
= mkfs_exists(fstype
);
1907 return log_error_errno(r
, "Failed to check if mkfs binary for %s exists: %m", fstype
);
1909 if (h
->file_system_type
|| streq(fstype
, "ext4") || !supported_fstype("ext4"))
1910 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "mkfs binary for file system type %s does not exist.", fstype
);
1912 /* If the record does not explicitly declare a file system to use, and the compiled-in
1913 * default does not actually exist, than do an automatic fallback onto ext4, as the baseline
1914 * fs of Linux. We won't search for a working fs type here beyond ext4, i.e. nothing fancier
1915 * than a single, conservative fallback to baseline. This should be useful in minimal
1916 * environments where mkfs.btrfs or so are not made available, but mkfs.ext4 as Linux' most
1917 * boring, most basic fs is. */
1918 log_info("Formatting tool for compiled-in default file system %s not available, falling back to ext4 instead.", fstype
);
1922 if (sd_id128_is_null(h
->partition_uuid
)) {
1923 r
= sd_id128_randomize(&partition_uuid
);
1925 return log_error_errno(r
, "Failed to acquire partition UUID: %m");
1927 partition_uuid
= h
->partition_uuid
;
1929 if (sd_id128_is_null(h
->luks_uuid
)) {
1930 r
= sd_id128_randomize(&luks_uuid
);
1932 return log_error_errno(r
, "Failed to acquire LUKS UUID: %m");
1934 luks_uuid
= h
->luks_uuid
;
1936 if (sd_id128_is_null(h
->file_system_uuid
)) {
1937 r
= sd_id128_randomize(&fs_uuid
);
1939 return log_error_errno(r
, "Failed to acquire file system UUID: %m");
1941 fs_uuid
= h
->file_system_uuid
;
1943 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
1947 r
= access(dm_node
, F_OK
);
1949 if (errno
!= ENOENT
)
1950 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", dm_node
);
1952 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "Device mapper device %s already exists, refusing.", dm_node
);
1954 if (path_startswith(ip
, "/dev/")) {
1955 _cleanup_free_
char *sysfs
= NULL
;
1956 uint64_t block_device_size
;
1959 /* Let's place the home directory on a real device, i.e. an USB stick or such */
1961 image_fd
= open(ip
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
1963 return log_error_errno(errno
, "Failed to open device %s: %m", ip
);
1965 if (fstat(image_fd
, &st
) < 0)
1966 return log_error_errno(errno
, "Failed to stat device %s: %m", ip
);
1967 if (!S_ISBLK(st
.st_mode
))
1968 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Device is not a block device, refusing.");
1970 if (asprintf(&sysfs
, "/sys/dev/block/%u:%u/partition", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
1972 if (access(sysfs
, F_OK
) < 0) {
1973 if (errno
!= ENOENT
)
1974 return log_error_errno(errno
, "Failed to check whether %s exists: %m", sysfs
);
1976 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Operating on partitions is currently not supported, sorry. Please specify a top-level block device.");
1978 if (flock(image_fd
, LOCK_EX
) < 0) /* make sure udev doesn't read from it while we operate on the device */
1979 return log_error_errno(errno
, "Failed to lock block device %s: %m", ip
);
1981 if (ioctl(image_fd
, BLKGETSIZE64
, &block_device_size
) < 0)
1982 return log_error_errno(errno
, "Failed to read block device size: %m");
1984 if (h
->disk_size
== UINT64_MAX
) {
1986 /* If a relative disk size is requested, apply it relative to the block device size */
1987 if (h
->disk_size_relative
< UINT32_MAX
)
1988 host_size
= CLAMP(DISK_SIZE_ROUND_DOWN(block_device_size
* h
->disk_size_relative
/ UINT32_MAX
),
1989 USER_DISK_SIZE_MIN
, USER_DISK_SIZE_MAX
);
1991 host_size
= block_device_size
; /* Otherwise, take the full device */
1993 } else if (h
->disk_size
> block_device_size
)
1994 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE
), "Selected disk size larger than backing block device, refusing.");
1996 host_size
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
1998 if (!supported_fs_size(fstype
, host_size
))
1999 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
),
2000 "Selected file system size too small for %s.", fstype
);
2002 /* After creation we should reference this partition by its UUID instead of the block
2003 * device. That's preferable since the user might have specified a device node such as
2004 * /dev/sdb to us, which might look very different when replugged. */
2005 if (asprintf(&disk_uuid_path
, "/dev/disk/by-uuid/" SD_ID128_UUID_FORMAT_STR
, SD_ID128_FORMAT_VAL(luks_uuid
)) < 0)
2008 if (user_record_luks_discard(h
) || user_record_luks_offline_discard(h
)) {
2009 /* If we want online or offline discard, discard once before we start using things. */
2011 if (ioctl(image_fd
, BLKDISCARD
, (uint64_t[]) { 0, block_device_size
}) < 0)
2012 log_full_errno(errno
== EOPNOTSUPP
? LOG_DEBUG
: LOG_WARNING
, errno
,
2013 "Failed to issue full-device BLKDISCARD on device, ignoring: %m");
2015 log_info("Full device discard completed.");
2018 _cleanup_free_
char *parent
= NULL
;
2020 parent
= dirname_malloc(ip
);
2024 r
= mkdir_p(parent
, 0755);
2026 return log_error_errno(r
, "Failed to create parent directory %s: %m", parent
);
2028 r
= calculate_disk_size(h
, parent
, &host_size
);
2032 if (!supported_fs_size(fstype
, host_size
))
2033 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Selected file system size too small for %s.", fstype
);
2035 r
= tempfn_random(ip
, "homework", &temporary_image_path
);
2037 return log_error_errno(r
, "Failed to derive temporary file name for %s: %m", ip
);
2039 image_fd
= open(temporary_image_path
, O_RDWR
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
2041 return log_error_errno(errno
, "Failed to create home image %s: %m", temporary_image_path
);
2043 image_created
= true;
2045 r
= chattr_fd(image_fd
, FS_NOCOW_FL
, FS_NOCOW_FL
, NULL
);
2047 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
2048 "Failed to set file attributes on %s, ignoring: %m", temporary_image_path
);
2050 r
= home_truncate(h
, image_fd
, temporary_image_path
, host_size
);
2054 log_info("Allocating image file completed.");
2057 r
= make_partition_table(
2059 user_record_user_name_and_realm(h
),
2067 log_info("Writing of partition table completed.");
2069 r
= loop_device_make(image_fd
, O_RDWR
, partition_offset
, partition_size
, 0, &loop
);
2071 if (r
== -ENOENT
) { /* this means /dev/loop-control doesn't exist, i.e. we are in a container
2072 * or similar and loopback bock devices are not available, return a
2073 * recognizable error in this case. */
2074 log_error_errno(r
, "Loopback block device support is not available on this system.");
2079 log_error_errno(r
, "Failed to set up loopback device for %s: %m", temporary_image_path
);
2083 r
= loop_device_flock(loop
, LOCK_EX
); /* make sure udev won't read before we are done */
2085 log_error_errno(r
, "Failed to take lock on loop device: %m");
2089 log_info("Setting up loopback device %s completed.", loop
->node
?: ip
);
2091 r
= luks_format(loop
->node
,
2094 user_record_user_name_and_realm(h
),
2096 effective_passwords
,
2097 user_record_luks_discard(h
) || user_record_luks_offline_discard(h
),
2103 dm_activated
= true;
2105 r
= block_get_size_by_path(dm_node
, &encrypted_size
);
2107 log_error_errno(r
, "Failed to get encrypted block device size: %m");
2111 log_info("Setting up LUKS device %s completed.", dm_node
);
2113 r
= make_filesystem(dm_node
, fstype
, user_record_user_name_and_realm(h
), fs_uuid
, user_record_luks_discard(h
));
2117 log_info("Formatting file system completed.");
2119 r
= home_unshare_and_mount(dm_node
, fstype
, user_record_luks_discard(h
), user_record_mount_flags(h
));
2125 subdir
= path_join("/run/systemd/user-home-mount/", user_record_user_name_and_realm(h
));
2131 /* Prefer using a btrfs subvolume if we can, fall back to directory otherwise */
2132 r
= btrfs_subvol_make_fallback(subdir
, 0700);
2134 log_error_errno(r
, "Failed to create user directory in mounted image file: %m");
2138 root_fd
= open(subdir
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
2140 r
= log_error_errno(errno
, "Failed to open user directory in mounted image file: %m");
2144 r
= home_populate(h
, root_fd
);
2148 r
= home_sync_and_statfs(root_fd
, &sfs
);
2152 r
= user_record_clone(h
, USER_RECORD_LOAD_MASK_SECRET
|USER_RECORD_LOG
|USER_RECORD_PERMISSIVE
, &new_home
);
2154 log_error_errno(r
, "Failed to clone record: %m");
2158 r
= user_record_add_binding(
2161 disk_uuid_path
?: ip
,
2165 sym_crypt_get_cipher(cd
),
2166 sym_crypt_get_cipher_mode(cd
),
2167 luks_volume_key_size_convert(cd
),
2173 log_error_errno(r
, "Failed to add binding to record: %m");
2177 if (user_record_luks_offline_discard(h
)) {
2178 r
= run_fitrim(root_fd
);
2183 root_fd
= safe_close(root_fd
);
2185 r
= umount_verbose(LOG_ERR
, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW
);
2191 r
= sym_crypt_deactivate_by_name(cd
, dm_name
, 0);
2193 log_error_errno(r
, "Failed to deactivate LUKS device: %m");
2200 dm_activated
= false;
2202 loop
= loop_device_unref(loop
);
2204 if (!user_record_luks_offline_discard(h
)) {
2205 r
= run_fallocate(image_fd
, NULL
/* refresh stat() data */);
2210 /* Sync everything to disk before we move things into place under the final name. */
2211 if (fsync(image_fd
) < 0) {
2212 r
= log_error_errno(r
, "Failed to synchronize image to disk: %m");
2217 (void) ioctl(image_fd
, BLKRRPART
, 0);
2219 /* If we operate on a file, sync the containing directory too. */
2220 r
= fsync_directory_of_file(image_fd
);
2222 log_error_errno(r
, "Failed to synchronize directory of image file to disk: %m");
2227 /* Let's close the image fd now. If we are operating on a real block device this will release the BSD
2228 * lock that ensures udev doesn't interfere with what we are doing */
2229 image_fd
= safe_close(image_fd
);
2231 if (temporary_image_path
) {
2232 if (rename(temporary_image_path
, ip
) < 0) {
2233 log_error_errno(errno
, "Failed to rename image file: %m");
2237 log_info("Moved image file into place.");
2241 (void) wait_for_devlink(disk_uuid_path
);
2243 log_info("Everything completed.");
2245 print_size_summary(host_size
, encrypted_size
, &sfs
);
2247 *ret_home
= TAKE_PTR(new_home
);
2251 /* Let's close all files before we unmount the file system, to avoid EBUSY */
2252 root_fd
= safe_close(root_fd
);
2255 (void) umount_verbose(LOG_WARNING
, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW
);
2258 (void) sym_crypt_deactivate_by_name(cd
, dm_name
, 0);
2260 loop
= loop_device_unref(loop
);
2263 (void) unlink(temporary_image_path
);
2268 int home_validate_update_luks(UserRecord
*h
, HomeSetup
*setup
) {
2269 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
2275 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
2279 r
= access(dm_node
, F_OK
);
2280 if (r
< 0 && errno
!= ENOENT
)
2281 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", dm_node
);
2283 free_and_replace(setup
->dm_name
, dm_name
);
2284 free_and_replace(setup
->dm_node
, dm_node
);
2294 static int can_resize_fs(int fd
, uint64_t old_size
, uint64_t new_size
) {
2299 /* Filter out bogus requests early */
2300 if (old_size
== 0 || old_size
== UINT64_MAX
||
2301 new_size
== 0 || new_size
== UINT64_MAX
)
2302 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid resize parameters.");
2304 if ((old_size
& 511) != 0 || (new_size
& 511) != 0)
2305 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Resize parameters not multiple of 512.");
2307 if (fstatfs(fd
, &sfs
) < 0)
2308 return log_error_errno(errno
, "Failed to fstatfs() file system: %m");
2310 if (is_fs_type(&sfs
, BTRFS_SUPER_MAGIC
)) {
2312 if (new_size
< BTRFS_MINIMAL_SIZE
)
2313 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for btrfs (needs to be 256M at least.");
2315 /* btrfs can grow and shrink online */
2317 } else if (is_fs_type(&sfs
, XFS_SB_MAGIC
)) {
2319 if (new_size
< XFS_MINIMAL_SIZE
)
2320 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for xfs (needs to be 14M at least).");
2322 /* XFS can grow, but not shrink */
2323 if (new_size
< old_size
)
2324 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE
), "Shrinking this type of file system is not supported.");
2326 } else if (is_fs_type(&sfs
, EXT4_SUPER_MAGIC
)) {
2328 if (new_size
< EXT4_MINIMAL_SIZE
)
2329 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for ext4 (needs to be 1M at least).");
2331 /* ext4 can grow online, and shrink offline */
2332 if (new_size
< old_size
)
2333 return CAN_RESIZE_OFFLINE
;
2336 return log_error_errno(SYNTHETIC_ERRNO(ESOCKTNOSUPPORT
), "Resizing this type of file system is not supported.");
2338 return CAN_RESIZE_ONLINE
;
2341 static int ext4_offline_resize_fs(HomeSetup
*setup
, uint64_t new_size
, bool discard
, unsigned long flags
) {
2342 _cleanup_free_
char *size_str
= NULL
;
2343 bool re_open
= false, re_mount
= false;
2344 pid_t resize_pid
, fsck_pid
;
2348 assert(setup
->dm_node
);
2350 /* First, unmount the file system */
2351 if (setup
->root_fd
>= 0) {
2352 setup
->root_fd
= safe_close(setup
->root_fd
);
2356 if (setup
->undo_mount
) {
2357 r
= umount_verbose(LOG_ERR
, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW
);
2361 setup
->undo_mount
= false;
2365 log_info("Temporary unmounting of file system completed.");
2367 /* resize2fs requires that the file system is force checked first, do so. */
2368 r
= safe_fork("(e2fsck)",
2369 FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_STDOUT_TO_STDERR
|FORK_CLOSE_ALL_FDS
,
2375 execlp("e2fsck" ,"e2fsck", "-fp", setup
->dm_node
, NULL
);
2377 log_error_errno(errno
, "Failed to execute e2fsck: %m");
2378 _exit(EXIT_FAILURE
);
2381 exit_status
= wait_for_terminate_and_check("e2fsck", fsck_pid
, WAIT_LOG_ABNORMAL
);
2382 if (exit_status
< 0)
2384 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != 0) {
2385 log_warning("e2fsck failed with exit status %i.", exit_status
);
2387 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
2388 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "File system is corrupted, refusing.");
2390 log_warning("Ignoring fsck error.");
2393 log_info("Forced file system check completed.");
2395 /* We use 512 sectors here, because resize2fs doesn't do byte sizes */
2396 if (asprintf(&size_str
, "%" PRIu64
"s", new_size
/ 512) < 0)
2399 /* Resize the thing */
2400 r
= safe_fork("(e2resize)",
2401 FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_WAIT
|FORK_STDOUT_TO_STDERR
|FORK_CLOSE_ALL_FDS
,
2407 execlp("resize2fs" ,"resize2fs", setup
->dm_node
, size_str
, NULL
);
2409 log_error_errno(errno
, "Failed to execute resize2fs: %m");
2410 _exit(EXIT_FAILURE
);
2413 log_info("Offline file system resize completed.");
2415 /* Re-establish mounts and reopen the directory */
2417 r
= home_mount_node(setup
->dm_node
, "ext4", discard
, flags
);
2421 setup
->undo_mount
= true;
2425 setup
->root_fd
= open("/run/systemd/user-home-mount", O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
2426 if (setup
->root_fd
< 0)
2427 return log_error_errno(errno
, "Failed to reopen file system: %m");
2430 log_info("File system mounted again.");
2435 static int prepare_resize_partition(
2437 uint64_t partition_offset
,
2438 uint64_t old_partition_size
,
2439 uint64_t new_partition_size
,
2440 sd_id128_t
*ret_disk_uuid
,
2441 struct fdisk_table
**ret_table
) {
2443 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2444 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
2445 _cleanup_free_
char *path
= NULL
, *disk_uuid_as_string
= NULL
;
2446 size_t n_partitions
;
2447 sd_id128_t disk_uuid
;
2452 assert(ret_disk_uuid
);
2455 assert((partition_offset
& 511) == 0);
2456 assert((old_partition_size
& 511) == 0);
2457 assert((new_partition_size
& 511) == 0);
2458 assert(UINT64_MAX
- old_partition_size
>= partition_offset
);
2459 assert(UINT64_MAX
- new_partition_size
>= partition_offset
);
2461 if (partition_offset
== 0) {
2462 /* If the offset is at the beginning we assume no partition table, let's exit early. */
2463 log_debug("Not rewriting partition table, operating on naked device.");
2464 *ret_disk_uuid
= SD_ID128_NULL
;
2469 c
= fdisk_new_context();
2473 if (asprintf(&path
, "/proc/self/fd/%i", fd
) < 0)
2476 r
= fdisk_assign_device(c
, path
, 0);
2478 return log_error_errno(r
, "Failed to open device: %m");
2480 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2481 return log_error_errno(SYNTHETIC_ERRNO(ENOMEDIUM
), "Disk has no GPT partition table.");
2483 r
= fdisk_get_disklabel_id(c
, &disk_uuid_as_string
);
2485 return log_error_errno(r
, "Failed to acquire disk UUID: %m");
2487 r
= sd_id128_from_string(disk_uuid_as_string
, &disk_uuid
);
2489 return log_error_errno(r
, "Failed parse disk UUID: %m");
2491 r
= fdisk_get_partitions(c
, &t
);
2493 return log_error_errno(r
, "Failed to acquire partition table: %m");
2495 n_partitions
= fdisk_table_get_nents(t
);
2496 for (size_t i
= 0; i
< n_partitions
; i
++) {
2497 struct fdisk_partition
*p
;
2499 p
= fdisk_table_get_partition(t
, i
);
2501 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
2503 if (fdisk_partition_is_used(p
) <= 0)
2505 if (fdisk_partition_has_start(p
) <= 0 || fdisk_partition_has_size(p
) <= 0 || fdisk_partition_has_end(p
) <= 0)
2506 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found partition without a size.");
2508 if (fdisk_partition_get_start(p
) == partition_offset
/ 512U &&
2509 fdisk_partition_get_size(p
) == old_partition_size
/ 512U) {
2512 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
), "Partition found twice, refusing.");
2514 /* Found our partition, now patch it */
2515 r
= fdisk_partition_size_explicit(p
, 1);
2517 return log_error_errno(r
, "Failed to enable explicit partition size: %m");
2519 r
= fdisk_partition_set_size(p
, new_partition_size
/ 512U);
2521 return log_error_errno(r
, "Failed to change partition size: %m");
2527 if (fdisk_partition_get_start(p
) < partition_offset
+ new_partition_size
/ 512U &&
2528 fdisk_partition_get_end(p
) >= partition_offset
/ 512)
2529 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Can't extend, conflicting partition found.");
2534 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to find matching partition to resize.");
2536 *ret_table
= TAKE_PTR(t
);
2537 *ret_disk_uuid
= disk_uuid
;
2542 static int ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *userdata
) {
2547 switch (fdisk_ask_get_type(ask
)) {
2549 case FDISK_ASKTYPE_STRING
:
2550 result
= new(char, 37);
2554 fdisk_ask_string_set_result(ask
, id128_to_uuid_string(*(sd_id128_t
*) userdata
, result
));
2558 log_debug("Unexpected question from libfdisk, ignoring.");
2564 static int apply_resize_partition(int fd
, sd_id128_t disk_uuids
, struct fdisk_table
*t
) {
2565 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2566 _cleanup_free_
void *two_zero_lbas
= NULL
;
2567 _cleanup_free_
char *path
= NULL
;
2573 if (!t
) /* no partition table to apply, exit early */
2576 two_zero_lbas
= malloc0(1024U);
2580 /* libfdisk appears to get confused by the existing PMBR. Let's explicitly flush it out. */
2581 n
= pwrite(fd
, two_zero_lbas
, 1024U, 0);
2583 return log_error_errno(errno
, "Failed to wipe partition table: %m");
2585 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Short write while wiping partition table.");
2587 c
= fdisk_new_context();
2591 if (asprintf(&path
, "/proc/self/fd/%i", fd
) < 0)
2594 r
= fdisk_assign_device(c
, path
, 0);
2596 return log_error_errno(r
, "Failed to open device: %m");
2598 r
= fdisk_create_disklabel(c
, "gpt");
2600 return log_error_errno(r
, "Failed to create GPT disk label: %m");
2602 r
= fdisk_apply_table(c
, t
);
2604 return log_error_errno(r
, "Failed to apply partition table: %m");
2606 r
= fdisk_set_ask(c
, ask_cb
, &disk_uuids
);
2608 return log_error_errno(r
, "Failed to set libfdisk query function: %m");
2610 r
= fdisk_set_disklabel_id(c
);
2612 return log_error_errno(r
, "Failed to change disklabel ID: %m");
2614 r
= fdisk_write_disklabel(c
);
2616 return log_error_errno(r
, "Failed to write disk label: %m");
2621 int home_resize_luks(
2623 bool already_activated
,
2624 PasswordCache
*cache
,
2626 UserRecord
**ret_home
) {
2628 uint64_t old_image_size
, new_image_size
, old_fs_size
, new_fs_size
, crypto_offset
, new_partition_size
;
2629 _cleanup_(user_record_unrefp
) UserRecord
*header_home
= NULL
, *embedded_home
= NULL
, *new_home
= NULL
;
2630 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*table
= NULL
;
2631 _cleanup_free_
char *whole_disk
= NULL
;
2632 _cleanup_close_
int image_fd
= -1;
2633 sd_id128_t disk_uuid
;
2634 const char *ip
, *ipo
;
2640 assert(user_record_storage(h
) == USER_LUKS
);
2644 r
= dlopen_cryptsetup();
2648 assert_se(ipo
= user_record_image_path(h
));
2649 ip
= strdupa(ipo
); /* copy out since original might change later in home record object */
2651 image_fd
= open(ip
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
2653 return log_error_errno(errno
, "Failed to open image file %s: %m", ip
);
2655 if (fstat(image_fd
, &st
) < 0)
2656 return log_error_errno(errno
, "Failed to stat image file %s: %m", ip
);
2657 if (S_ISBLK(st
.st_mode
)) {
2660 r
= block_get_whole_disk(st
.st_rdev
, &parent
);
2662 return log_error_errno(r
, "Failed to acquire whole block device for %s: %m", ip
);
2664 /* If we shall resize a file system on a partition device, then let's figure out the
2665 * whole disk device and operate on that instead, since we need to rewrite the
2666 * partition table to resize the partition. */
2668 log_info("Operating on partition device %s, using parent device.", ip
);
2670 r
= device_path_make_major_minor(st
.st_mode
, parent
, &whole_disk
);
2672 return log_error_errno(r
, "Failed to derive whole disk path for %s: %m", ip
);
2674 safe_close(image_fd
);
2676 image_fd
= open(whole_disk
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
2678 return log_error_errno(errno
, "Failed to open whole block device %s: %m", whole_disk
);
2680 if (fstat(image_fd
, &st
) < 0)
2681 return log_error_errno(errno
, "Failed to stat whole block device %s: %m", whole_disk
);
2682 if (!S_ISBLK(st
.st_mode
))
2683 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Whole block device %s is not actually a block device, refusing.", whole_disk
);
2685 log_info("Operating on whole block device %s.", ip
);
2687 if (ioctl(image_fd
, BLKGETSIZE64
, &old_image_size
) < 0)
2688 return log_error_errno(errno
, "Failed to determine size of original block device: %m");
2690 if (flock(image_fd
, LOCK_EX
) < 0) /* make sure udev doesn't read from it while we operate on the device */
2691 return log_error_errno(errno
, "Failed to lock block device %s: %m", ip
);
2693 new_image_size
= old_image_size
; /* we can't resize physical block devices */
2695 r
= stat_verify_regular(&st
);
2697 return log_error_errno(r
, "Image %s is not a block device nor regular file: %m", ip
);
2699 old_image_size
= st
.st_size
;
2701 /* Note an asymetry here: when we operate on loopback files the specified disk size we get we
2702 * apply onto the loopback file as a whole. When we operate on block devices we instead apply
2703 * to the partition itself only. */
2705 new_image_size
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
2706 if (new_image_size
== old_image_size
) {
2707 log_info("Image size already matching, skipping operation.");
2712 r
= home_prepare_luks(h
, already_activated
, whole_disk
, cache
, setup
, &header_home
);
2716 r
= home_load_embedded_identity(h
, setup
->root_fd
, header_home
, USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL
, cache
, &embedded_home
, &new_home
);
2720 log_info("offset = %" PRIu64
", size = %" PRIu64
", image = %" PRIu64
, setup
->partition_offset
, setup
->partition_size
, old_image_size
);
2722 if ((UINT64_MAX
- setup
->partition_offset
) < setup
->partition_size
||
2723 setup
->partition_offset
+ setup
->partition_size
> old_image_size
)
2724 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Old partition doesn't fit in backing storage, refusing.");
2726 if (S_ISREG(st
.st_mode
)) {
2727 uint64_t partition_table_extra
;
2729 partition_table_extra
= old_image_size
- setup
->partition_size
;
2730 if (new_image_size
<= partition_table_extra
)
2731 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "New size smaller than partition table metadata.");
2733 new_partition_size
= new_image_size
- partition_table_extra
;
2735 assert(S_ISBLK(st
.st_mode
));
2737 new_partition_size
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
2738 if (new_partition_size
== setup
->partition_size
) {
2739 log_info("Partition size already matching, skipping operation.");
2744 if ((UINT64_MAX
- setup
->partition_offset
) < new_partition_size
||
2745 setup
->partition_offset
+ new_partition_size
> new_image_size
)
2746 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "New partition doesn't fit into backing storage, refusing.");
2748 crypto_offset
= sym_crypt_get_data_offset(setup
->crypt_device
);
2749 if (setup
->partition_size
/ 512U <= crypto_offset
)
2750 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Weird, old crypto payload offset doesn't actually fit in partition size?");
2751 if (new_partition_size
/ 512U <= crypto_offset
)
2752 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "New size smaller than crypto payload offset?");
2754 old_fs_size
= (setup
->partition_size
/ 512U - crypto_offset
) * 512U;
2755 new_fs_size
= (new_partition_size
/ 512U - crypto_offset
) * 512U;
2757 /* Before we start doing anything, let's figure out if we actually can */
2758 resize_type
= can_resize_fs(setup
->root_fd
, old_fs_size
, new_fs_size
);
2759 if (resize_type
< 0)
2761 if (resize_type
== CAN_RESIZE_OFFLINE
&& already_activated
)
2762 return log_error_errno(SYNTHETIC_ERRNO(ETXTBSY
), "File systems of this type can only be resized offline, but is currently online.");
2764 log_info("Ready to resize image size %s → %s, partition size %s → %s, file system size %s → %s.",
2765 FORMAT_BYTES(old_image_size
),
2766 FORMAT_BYTES(new_image_size
),
2767 FORMAT_BYTES(setup
->partition_size
),
2768 FORMAT_BYTES(new_partition_size
),
2769 FORMAT_BYTES(old_fs_size
),
2770 FORMAT_BYTES(new_fs_size
));
2772 r
= prepare_resize_partition(
2774 setup
->partition_offset
,
2775 setup
->partition_size
,
2782 if (new_fs_size
> old_fs_size
) {
2784 if (S_ISREG(st
.st_mode
)) {
2785 /* Grow file size */
2786 r
= home_truncate(h
, image_fd
, ip
, new_image_size
);
2790 log_info("Growing of image file completed.");
2793 /* Make sure loopback device sees the new bigger size */
2794 r
= loop_device_refresh_size(setup
->loop
, UINT64_MAX
, new_partition_size
);
2796 log_debug_errno(r
, "Device is not a loopback device, not refreshing size.");
2798 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
2800 log_info("Refreshing loop device size completed.");
2802 r
= apply_resize_partition(image_fd
, disk_uuid
, table
);
2806 log_info("Growing of partition completed.");
2808 if (ioctl(image_fd
, BLKRRPART
, 0) < 0)
2809 log_debug_errno(errno
, "BLKRRPART failed on block device, ignoring: %m");
2811 /* Tell LUKS about the new bigger size too */
2812 r
= sym_crypt_resize(setup
->crypt_device
, setup
->dm_name
, new_fs_size
/ 512U);
2814 return log_error_errno(r
, "Failed to grow LUKS device: %m");
2816 log_info("LUKS device growing completed.");
2818 r
= home_store_embedded_identity(new_home
, setup
->root_fd
, h
->uid
, embedded_home
);
2822 if (S_ISREG(st
.st_mode
)) {
2823 if (user_record_luks_discard(h
))
2824 /* Before we shrink, let's trim the file system, so that we need less space on disk during the shrinking */
2825 (void) run_fitrim(setup
->root_fd
);
2827 /* If discard is off, let's ensure all backing blocks are allocated, so that our resize operation doesn't fail half-way */
2828 r
= run_fallocate(image_fd
, &st
);
2835 /* Now resize the file system */
2836 if (resize_type
== CAN_RESIZE_ONLINE
)
2837 r
= resize_fs(setup
->root_fd
, new_fs_size
, NULL
);
2839 r
= ext4_offline_resize_fs(setup
, new_fs_size
, user_record_luks_discard(h
), user_record_mount_flags(h
));
2841 return log_error_errno(r
, "Failed to resize file system: %m");
2843 log_info("File system resizing completed.");
2845 /* Immediately sync afterwards */
2846 r
= home_sync_and_statfs(setup
->root_fd
, NULL
);
2850 if (new_fs_size
< old_fs_size
) {
2852 /* Shrink the LUKS device now, matching the new file system size */
2853 r
= sym_crypt_resize(setup
->crypt_device
, setup
->dm_name
, new_fs_size
/ 512);
2855 return log_error_errno(r
, "Failed to shrink LUKS device: %m");
2857 log_info("LUKS device shrinking completed.");
2859 if (S_ISREG(st
.st_mode
)) {
2860 /* Shrink the image file */
2861 if (ftruncate(image_fd
, new_image_size
) < 0)
2862 return log_error_errno(errno
, "Failed to shrink image file %s: %m", ip
);
2864 log_info("Shrinking of image file completed.");
2867 /* Refresh the loop devices size */
2868 r
= loop_device_refresh_size(setup
->loop
, UINT64_MAX
, new_partition_size
);
2870 log_debug_errno(r
, "Device is not a loopback device, not refreshing size.");
2872 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
2874 log_info("Refreshing loop device size completed.");
2876 r
= apply_resize_partition(image_fd
, disk_uuid
, table
);
2880 log_info("Shrinking of partition completed.");
2882 if (ioctl(image_fd
, BLKRRPART
, 0) < 0)
2883 log_debug_errno(errno
, "BLKRRPART failed on block device, ignoring: %m");
2885 r
= home_store_embedded_identity(new_home
, setup
->root_fd
, h
->uid
, embedded_home
);
2890 r
= home_store_header_identity_luks(new_home
, setup
, header_home
);
2894 r
= home_extend_embedded_identity(new_home
, h
, setup
);
2898 if (user_record_luks_discard(h
))
2899 (void) run_fitrim(setup
->root_fd
);
2901 r
= home_sync_and_statfs(setup
->root_fd
, &sfs
);
2905 r
= home_setup_undo(setup
);
2909 log_info("Everything completed.");
2911 print_size_summary(new_image_size
, new_fs_size
, &sfs
);
2913 *ret_home
= TAKE_PTR(new_home
);
2917 int home_passwd_luks(
2920 PasswordCache
*cache
, /* the passwords acquired via PKCS#11/FIDO2 security tokens */
2921 char **effective_passwords
/* new passwords */) {
2923 size_t volume_key_size
, max_key_slots
, n_effective
;
2924 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
2925 struct crypt_pbkdf_type good_pbkdf
, minimal_pbkdf
;
2931 assert(user_record_storage(h
) == USER_LUKS
);
2934 r
= dlopen_cryptsetup();
2938 type
= sym_crypt_get_type(setup
->crypt_device
);
2940 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine crypto device type.");
2942 r
= sym_crypt_keyslot_max(type
);
2944 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine number of key slots.");
2947 r
= sym_crypt_get_volume_key_size(setup
->crypt_device
);
2949 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine volume key size.");
2950 volume_key_size
= (size_t) r
;
2952 volume_key
= malloc(volume_key_size
);
2957 FOREACH_POINTER(list
, cache
->pkcs11_passwords
, cache
->fido2_passwords
, h
->password
) {
2958 r
= luks_try_passwords(setup
->crypt_device
, list
, volume_key
, &volume_key_size
);
2963 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY
), "Failed to unlock LUKS superblock with supplied passwords.");
2965 return log_error_errno(r
, "Failed to unlocks LUKS superblock: %m");
2967 n_effective
= strv_length(effective_passwords
);
2969 build_good_pbkdf(&good_pbkdf
, h
);
2970 build_minimal_pbkdf(&minimal_pbkdf
, h
);
2972 for (size_t i
= 0; i
< max_key_slots
; i
++) {
2973 r
= sym_crypt_keyslot_destroy(setup
->crypt_device
, i
);
2974 if (r
< 0 && !IN_SET(r
, -ENOENT
, -EINVAL
)) /* Returns EINVAL or ENOENT if there's no key in this slot already */
2975 return log_error_errno(r
, "Failed to destroy LUKS password: %m");
2977 if (i
>= n_effective
) {
2979 log_info("Destroyed LUKS key slot %zu.", i
);
2983 if (strv_contains(cache
->pkcs11_passwords
, effective_passwords
[i
]) ||
2984 strv_contains(cache
->fido2_passwords
, effective_passwords
[i
])) {
2985 log_debug("Using minimal PBKDF for slot %zu", i
);
2986 r
= sym_crypt_set_pbkdf_type(setup
->crypt_device
, &minimal_pbkdf
);
2988 log_debug("Using good PBKDF for slot %zu", i
);
2989 r
= sym_crypt_set_pbkdf_type(setup
->crypt_device
, &good_pbkdf
);
2992 return log_error_errno(r
, "Failed to tweak PBKDF for slot %zu: %m", i
);
2994 r
= sym_crypt_keyslot_add_by_volume_key(
2995 setup
->crypt_device
,
2999 effective_passwords
[i
],
3000 strlen(effective_passwords
[i
]));
3002 return log_error_errno(r
, "Failed to set up LUKS password: %m");
3004 log_info("Updated LUKS key slot %zu.", i
);
3010 int home_lock_luks(UserRecord
*h
) {
3011 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
3012 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
3013 _cleanup_close_
int root_fd
= -1;
3019 assert_se(p
= user_record_home_directory(h
));
3020 root_fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
3022 return log_error_errno(errno
, "Failed to open home directory: %m");
3024 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
3028 r
= dlopen_cryptsetup();
3032 r
= sym_crypt_init_by_name(&cd
, dm_name
);
3034 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
3036 log_info("Discovered used LUKS device %s.", dm_node
);
3037 cryptsetup_enable_logging(cd
);
3039 if (syncfs(root_fd
) < 0) /* Snake oil, but let's better be safe than sorry */
3040 return log_error_errno(errno
, "Failed to synchronize file system %s: %m", p
);
3042 root_fd
= safe_close(root_fd
);
3044 log_info("File system synchronized.");
3046 /* Note that we don't invoke FIFREEZE here, it appears libcryptsetup/device-mapper already does that on its own for us */
3048 r
= sym_crypt_suspend(cd
, dm_name
);
3050 return log_error_errno(r
, "Failed to suspend cryptsetup device: %s: %m", dm_node
);
3052 log_info("LUKS device suspended.");
3056 static int luks_try_resume(
3057 struct crypt_device
*cd
,
3058 const char *dm_name
,
3067 STRV_FOREACH(pp
, password
) {
3068 r
= sym_crypt_resume_by_passphrase(
3075 log_info("Resumed LUKS device %s.", dm_name
);
3079 log_debug_errno(r
, "Password %zu didn't work for resuming device: %m", (size_t) (pp
- password
));
3085 int home_unlock_luks(UserRecord
*h
, PasswordCache
*cache
) {
3086 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
3087 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
3093 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
3097 r
= dlopen_cryptsetup();
3101 r
= sym_crypt_init_by_name(&cd
, dm_name
);
3103 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
3105 log_info("Discovered used LUKS device %s.", dm_node
);
3106 cryptsetup_enable_logging(cd
);
3109 FOREACH_POINTER(list
, cache
->pkcs11_passwords
, cache
->fido2_passwords
, h
->password
) {
3110 r
= luks_try_resume(cd
, dm_name
, list
);
3115 return log_error_errno(r
, "No valid password for LUKS superblock.");
3117 return log_error_errno(r
, "Failed to resume LUKS superblock: %m");
3119 log_info("LUKS device resumed.");