1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <linux/loop.h>
11 #if HAVE_VALGRIND_MEMCHECK_H
12 #include <valgrind/memcheck.h>
15 #include "sd-daemon.h"
17 #include "blkid-util.h"
18 #include "blockdev-util.h"
19 #include "btrfs-util.h"
20 #include "chattr-util.h"
23 #include "errno-util.h"
27 #include "fsck-util.h"
28 #include "home-util.h"
29 #include "homework-luks.h"
30 #include "homework-mount.h"
31 #include "id128-util.h"
33 #include "memory-util.h"
34 #include "missing_magic.h"
36 #include "mkfs-util.h"
37 #include "mount-util.h"
38 #include "openssl-util.h"
39 #include "parse-util.h"
40 #include "path-util.h"
41 #include "process-util.h"
42 #include "random-util.h"
43 #include "resize-fs.h"
44 #include "stat-util.h"
46 #include "sync-util.h"
47 #include "tmpfile-util.h"
49 /* Round down to the nearest 4K size. Given that newer hardware generally prefers 4K sectors, let's align our
50 * partitions to that too. In the worst case we'll waste 3.5K per partition that way, but I think I can live
52 #define DISK_SIZE_ROUND_DOWN(x) ((x) & ~UINT64_C(4095))
54 /* Rounds up to the nearest 4K boundary. Returns UINT64_MAX on overflow */
55 #define DISK_SIZE_ROUND_UP(x) \
58 _x > UINT64_MAX - 4095U ? UINT64_MAX : (_x + 4095U) & ~UINT64_C(4095); \
62 int run_mark_dirty(int fd
, bool b
) {
66 /* Sets or removes the 'user.home-dirty' xattr on the specified file. We use this to detect when a
67 * home directory was not properly unmounted. */
71 r
= fd_verify_regular(fd
);
76 ret
= fsetxattr(fd
, "user.home-dirty", &x
, 1, XATTR_CREATE
);
77 if (ret
< 0 && errno
!= EEXIST
)
78 return log_debug_errno(errno
, "Could not mark home directory as dirty: %m");
83 return log_debug_errno(r
, "Failed to synchronize image before marking it clean: %m");
85 ret
= fremovexattr(fd
, "user.home-dirty");
86 if (ret
< 0 && errno
!= ENODATA
)
87 return log_debug_errno(errno
, "Could not mark home directory as clean: %m");
92 return log_debug_errno(r
, "Failed to synchronize dirty flag to disk: %m");
97 int run_mark_dirty_by_path(const char *path
, bool b
) {
98 _cleanup_close_
int fd
= -1;
102 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
);
104 return log_debug_errno(errno
, "Failed to open %s to mark dirty or clean: %m", path
);
106 return run_mark_dirty(fd
, b
);
109 static int probe_file_system_by_fd(
112 sd_id128_t
*ret_uuid
) {
114 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
115 _cleanup_free_
char *s
= NULL
;
116 const char *fstype
= NULL
, *uuid
= NULL
;
124 b
= blkid_new_probe();
129 r
= blkid_probe_set_device(b
, fd
, 0, 0);
131 return errno
> 0 ? -errno
: -ENOMEM
;
133 (void) blkid_probe_enable_superblocks(b
, 1);
134 (void) blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_UUID
);
137 r
= blkid_do_safeprobe(b
);
138 if (IN_SET(r
, -2, 1)) /* nothing found or ambiguous result */
141 return errno
> 0 ? -errno
: -EIO
;
143 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
147 (void) blkid_probe_lookup_value(b
, "UUID", &uuid
, NULL
);
151 r
= sd_id128_from_string(uuid
, &id
);
159 *ret_fstype
= TAKE_PTR(s
);
165 static int probe_file_system_by_path(const char *path
, char **ret_fstype
, sd_id128_t
*ret_uuid
) {
166 _cleanup_close_
int fd
= -1;
168 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
172 return probe_file_system_by_fd(fd
, ret_fstype
, ret_uuid
);
175 static int block_get_size_by_fd(int fd
, uint64_t *ret
) {
181 if (fstat(fd
, &st
) < 0)
184 if (!S_ISBLK(st
.st_mode
))
187 if (ioctl(fd
, BLKGETSIZE64
, ret
) < 0)
193 static int block_get_size_by_path(const char *path
, uint64_t *ret
) {
194 _cleanup_close_
int fd
= -1;
196 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
200 return block_get_size_by_fd(fd
, ret
);
203 static int run_fsck(const char *node
, const char *fstype
) {
210 r
= fsck_exists(fstype
);
212 return log_error_errno(r
, "Failed to check if fsck for file system %s exists: %m", fstype
);
214 log_warning("No fsck for file system %s installed, ignoring.", fstype
);
218 r
= safe_fork("(fsck)",
219 FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_STDOUT_TO_STDERR
|FORK_CLOSE_ALL_FDS
,
225 execl("/sbin/fsck", "/sbin/fsck", "-aTl", node
, NULL
);
227 log_error_errno(errno
, "Failed to execute fsck: %m");
228 _exit(FSCK_OPERATIONAL_ERROR
);
231 exit_status
= wait_for_terminate_and_check("fsck", fsck_pid
, WAIT_LOG_ABNORMAL
);
234 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != 0) {
235 log_warning("fsck failed with exit status %i.", exit_status
);
237 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
238 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "File system is corrupted, refusing.");
240 log_warning("Ignoring fsck error.");
243 log_info("File system check completed.");
248 static int luks_try_passwords(
249 struct crypt_device
*cd
,
252 size_t *volume_key_size
) {
259 STRV_FOREACH(pp
, passwords
) {
260 size_t vks
= *volume_key_size
;
262 r
= sym_crypt_volume_key_get(
270 *volume_key_size
= vks
;
274 log_debug_errno(r
, "Password %zu didn't work for unlocking LUKS superblock: %m", (size_t) (pp
- passwords
));
280 static int luks_setup(
285 const char *cipher_mode
,
286 uint64_t volume_key_size
,
288 const PasswordCache
*cache
,
290 struct crypt_device
**ret
,
291 sd_id128_t
*ret_found_uuid
,
292 void **ret_volume_key
,
293 size_t *ret_volume_key_size
) {
295 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
296 _cleanup_(erase_and_freep
) void *vk
= NULL
;
306 r
= sym_crypt_init(&cd
, node
);
308 return log_error_errno(r
, "Failed to allocate libcryptsetup context: %m");
310 cryptsetup_enable_logging(cd
);
312 r
= sym_crypt_load(cd
, CRYPT_LUKS2
, NULL
);
314 return log_error_errno(r
, "Failed to load LUKS superblock: %m");
316 r
= sym_crypt_get_volume_key_size(cd
);
318 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine LUKS volume key size");
321 if (!sd_id128_is_null(uuid
) || ret_found_uuid
) {
324 s
= sym_crypt_get_uuid(cd
);
326 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has no UUID.");
328 r
= sd_id128_from_string(s
, &p
);
330 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has invalid UUID.");
332 /* Check that the UUID matches, if specified */
333 if (!sd_id128_is_null(uuid
) &&
334 !sd_id128_equal(uuid
, p
))
335 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has wrong UUID.");
338 if (cipher
&& !streq_ptr(cipher
, sym_crypt_get_cipher(cd
)))
339 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong cipher.");
341 if (cipher_mode
&& !streq_ptr(cipher_mode
, sym_crypt_get_cipher_mode(cd
)))
342 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong cipher mode.");
344 if (volume_key_size
!= UINT64_MAX
&& vks
!= volume_key_size
)
345 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong volume key size.");
352 FOREACH_POINTER(list
, cache
->pkcs11_passwords
, cache
->fido2_passwords
, passwords
) {
353 r
= luks_try_passwords(cd
, list
, vk
, &vks
);
358 return log_error_errno(r
, "No valid password for LUKS superblock.");
360 return log_error_errno(r
, "Failed to unlocks LUKS superblock: %m");
362 r
= sym_crypt_activate_by_volume_key(
366 discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
368 return log_error_errno(r
, "Failed to unlock LUKS superblock: %m");
370 log_info("Setting up LUKS device /dev/mapper/%s completed.", dm_name
);
374 if (ret_found_uuid
) /* Return the UUID actually found if the caller wants to know */
377 *ret_volume_key
= TAKE_PTR(vk
);
378 if (ret_volume_key_size
)
379 *ret_volume_key_size
= vks
;
384 static int luks_open(
387 PasswordCache
*cache
,
388 struct crypt_device
**ret
,
389 sd_id128_t
*ret_found_uuid
,
390 void **ret_volume_key
,
391 size_t *ret_volume_key_size
) {
393 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
394 _cleanup_(erase_and_freep
) void *vk
= NULL
;
403 /* Opens a LUKS device that is already set up. Re-validates the password while doing so (which also
404 * provides us with the volume key, which we want). */
406 r
= sym_crypt_init_by_name(&cd
, dm_name
);
408 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
410 cryptsetup_enable_logging(cd
);
412 r
= sym_crypt_load(cd
, CRYPT_LUKS2
, NULL
);
414 return log_error_errno(r
, "Failed to load LUKS superblock: %m");
416 r
= sym_crypt_get_volume_key_size(cd
);
418 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine LUKS volume key size");
421 if (ret_found_uuid
) {
424 s
= sym_crypt_get_uuid(cd
);
426 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has no UUID.");
428 r
= sd_id128_from_string(s
, &p
);
430 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has invalid UUID.");
438 FOREACH_POINTER(list
, cache
->pkcs11_passwords
, cache
->fido2_passwords
, passwords
) {
439 r
= luks_try_passwords(cd
, list
, vk
, &vks
);
444 return log_error_errno(r
, "No valid password for LUKS superblock.");
446 return log_error_errno(r
, "Failed to unlocks LUKS superblock: %m");
448 log_info("Discovered used LUKS device /dev/mapper/%s, and validated password.", dm_name
);
450 /* This is needed so that crypt_resize() can operate correctly for pre-existing LUKS devices. We need
451 * to tell libcryptsetup the volume key explicitly, so that it is in the kernel keyring. */
452 r
= sym_crypt_activate_by_volume_key(cd
, NULL
, vk
, vks
, CRYPT_ACTIVATE_KEYRING_KEY
);
454 return log_error_errno(r
, "Failed to upload volume key again: %m");
456 log_info("Successfully re-activated LUKS device.");
463 *ret_volume_key
= TAKE_PTR(vk
);
464 if (ret_volume_key_size
)
465 *ret_volume_key_size
= vks
;
470 static int fs_validate(
474 sd_id128_t
*ret_found_uuid
) {
476 _cleanup_free_
char *fstype
= NULL
;
483 r
= probe_file_system_by_path(dm_node
, &fstype
, &u
);
485 return log_error_errno(r
, "Failed to probe file system: %m");
487 /* Limit the set of supported file systems a bit, as protection against little tested kernel file
488 * systems. Also, we only support the resize ioctls for these file systems. */
489 if (!supported_fstype(fstype
))
490 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "Image contains unsupported file system: %s", strna(fstype
));
492 if (!sd_id128_is_null(uuid
) &&
493 !sd_id128_equal(uuid
, u
))
494 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "File system has wrong UUID.");
496 log_info("Probing file system completed (found %s).", fstype
);
498 *ret_fstype
= TAKE_PTR(fstype
);
500 if (ret_found_uuid
) /* Return the UUID actually found if the caller wants to know */
506 static int make_dm_names(const char *user_name
, char **ret_dm_name
, char **ret_dm_node
) {
507 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
513 name
= strjoin("home-", user_name
);
517 node
= path_join("/dev/mapper/", name
);
521 *ret_dm_name
= TAKE_PTR(name
);
522 *ret_dm_node
= TAKE_PTR(node
);
526 static int luks_validate(
529 sd_id128_t partition_uuid
,
530 sd_id128_t
*ret_partition_uuid
,
531 uint64_t *ret_offset
,
532 uint64_t *ret_size
) {
534 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
535 sd_id128_t found_partition_uuid
= SD_ID128_NULL
;
536 const char *fstype
= NULL
, *pttype
= NULL
;
537 blkid_loff_t offset
= 0, size
= 0;
547 b
= blkid_new_probe();
552 r
= blkid_probe_set_device(b
, fd
, 0, 0);
554 return errno
> 0 ? -errno
: -ENOMEM
;
556 (void) blkid_probe_enable_superblocks(b
, 1);
557 (void) blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
558 (void) blkid_probe_enable_partitions(b
, 1);
559 (void) blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
562 r
= blkid_do_safeprobe(b
);
563 if (IN_SET(r
, -2, 1)) /* nothing found or ambiguous result */
566 return errno
> 0 ? -errno
: -EIO
;
568 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
569 if (streq_ptr(fstype
, "crypto_LUKS")) {
570 /* Directly a LUKS image */
572 *ret_size
= UINT64_MAX
; /* full disk */
573 *ret_partition_uuid
= SD_ID128_NULL
;
578 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
579 if (!streq_ptr(pttype
, "gpt"))
583 pl
= blkid_probe_get_partitions(b
);
585 return errno
> 0 ? -errno
: -ENOMEM
;
588 n
= blkid_partlist_numof_partitions(pl
);
590 return errno
> 0 ? -errno
: -EIO
;
592 for (int i
= 0; i
< n
; i
++) {
594 sd_id128_t id
= SD_ID128_NULL
;
598 pp
= blkid_partlist_get_partition(pl
, i
);
600 return errno
> 0 ? -errno
: -EIO
;
602 if (!streq_ptr(blkid_partition_get_type_string(pp
), "773f91ef-66d4-49b5-bd83-d683bf40ad16"))
605 if (!streq_ptr(blkid_partition_get_name(pp
), label
))
608 sid
= blkid_partition_get_uuid(pp
);
610 r
= sd_id128_from_string(sid
, &id
);
612 log_debug_errno(r
, "Couldn't parse partition UUID %s, weird: %m", sid
);
614 if (!sd_id128_is_null(partition_uuid
) && !sd_id128_equal(id
, partition_uuid
))
621 offset
= blkid_partition_get_start(pp
);
622 size
= blkid_partition_get_size(pp
);
623 found_partition_uuid
= id
;
633 if ((uint64_t) offset
> UINT64_MAX
/ 512U)
637 if ((uint64_t) size
> UINT64_MAX
/ 512U)
640 *ret_offset
= offset
* 512U;
641 *ret_size
= size
* 512U;
642 *ret_partition_uuid
= found_partition_uuid
;
647 static int crypt_device_to_evp_cipher(struct crypt_device
*cd
, const EVP_CIPHER
**ret
) {
648 _cleanup_free_
char *cipher_name
= NULL
;
649 const char *cipher
, *cipher_mode
, *e
;
650 size_t key_size
, key_bits
;
651 const EVP_CIPHER
*cc
;
656 /* Let's find the right OpenSSL EVP_CIPHER object that matches the encryption settings of the LUKS
659 cipher
= sym_crypt_get_cipher(cd
);
661 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot get cipher from LUKS device.");
663 cipher_mode
= sym_crypt_get_cipher_mode(cd
);
665 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot get cipher mode from LUKS device.");
667 e
= strchr(cipher_mode
, '-');
669 cipher_mode
= strndupa_safe(cipher_mode
, e
- cipher_mode
);
671 r
= sym_crypt_get_volume_key_size(cd
);
673 return log_error_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(EINVAL
), "Cannot get volume key size from LUKS device.");
676 key_bits
= key_size
* 8;
677 if (streq(cipher_mode
, "xts"))
680 if (asprintf(&cipher_name
, "%s-%zu-%s", cipher
, key_bits
, cipher_mode
) < 0)
683 cc
= EVP_get_cipherbyname(cipher_name
);
685 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Selected cipher mode '%s' not supported, can't encrypt JSON record.", cipher_name
);
687 /* Verify that our key length calculations match what OpenSSL thinks */
688 r
= EVP_CIPHER_key_length(cc
);
689 if (r
< 0 || (uint64_t) r
!= key_size
)
690 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Key size of selected cipher doesn't meet our expectations.");
696 static int luks_validate_home_record(
697 struct crypt_device
*cd
,
699 const void *volume_key
,
700 PasswordCache
*cache
,
701 UserRecord
**ret_luks_home_record
) {
708 for (int token
= 0; token
< sym_crypt_token_max(CRYPT_LUKS2
); token
++) {
709 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
, *rr
= NULL
;
710 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
711 _cleanup_(user_record_unrefp
) UserRecord
*lhr
= NULL
;
712 _cleanup_free_
void *encrypted
= NULL
, *iv
= NULL
;
713 size_t decrypted_size
, encrypted_size
, iv_size
;
714 int decrypted_size_out1
, decrypted_size_out2
;
715 _cleanup_free_
char *decrypted
= NULL
;
716 const char *text
, *type
;
717 crypt_token_info state
;
718 JsonVariant
*jr
, *jiv
;
719 unsigned line
, column
;
720 const EVP_CIPHER
*cc
;
722 state
= sym_crypt_token_status(cd
, token
, &type
);
723 if (state
== CRYPT_TOKEN_INACTIVE
) /* First unconfigured token, give up */
725 if (IN_SET(state
, CRYPT_TOKEN_INTERNAL
, CRYPT_TOKEN_INTERNAL_UNKNOWN
, CRYPT_TOKEN_EXTERNAL
))
727 if (state
!= CRYPT_TOKEN_EXTERNAL_UNKNOWN
)
728 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected token state of token %i: %i", token
, (int) state
);
730 if (!streq(type
, "systemd-homed"))
733 r
= sym_crypt_token_json_get(cd
, token
, &text
);
735 return log_error_errno(r
, "Failed to read LUKS token %i: %m", token
);
737 r
= json_parse(text
, JSON_PARSE_SENSITIVE
, &v
, &line
, &column
);
739 return log_error_errno(r
, "Failed to parse LUKS token JSON data %u:%u: %m", line
, column
);
741 jr
= json_variant_by_key(v
, "record");
743 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "LUKS token lacks 'record' field.");
744 jiv
= json_variant_by_key(v
, "iv");
746 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "LUKS token lacks 'iv' field.");
748 r
= json_variant_unbase64(jr
, &encrypted
, &encrypted_size
);
750 return log_error_errno(r
, "Failed to base64 decode record: %m");
752 r
= json_variant_unbase64(jiv
, &iv
, &iv_size
);
754 return log_error_errno(r
, "Failed to base64 decode IV: %m");
756 r
= crypt_device_to_evp_cipher(cd
, &cc
);
759 if (iv_size
> INT_MAX
|| EVP_CIPHER_iv_length(cc
) != (int) iv_size
)
760 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "IV size doesn't match.");
762 context
= EVP_CIPHER_CTX_new();
766 if (EVP_DecryptInit_ex(context
, cc
, NULL
, volume_key
, iv
) != 1)
767 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize decryption context.");
769 decrypted_size
= encrypted_size
+ EVP_CIPHER_key_length(cc
) * 2;
770 decrypted
= new(char, decrypted_size
);
774 if (EVP_DecryptUpdate(context
, (uint8_t*) decrypted
, &decrypted_size_out1
, encrypted
, encrypted_size
) != 1)
775 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to decrypt JSON record.");
777 assert((size_t) decrypted_size_out1
<= decrypted_size
);
779 if (EVP_DecryptFinal_ex(context
, (uint8_t*) decrypted
+ decrypted_size_out1
, &decrypted_size_out2
) != 1)
780 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finish decryption of JSON record.");
782 assert((size_t) decrypted_size_out1
+ (size_t) decrypted_size_out2
< decrypted_size
);
783 decrypted_size
= (size_t) decrypted_size_out1
+ (size_t) decrypted_size_out2
;
785 if (memchr(decrypted
, 0, decrypted_size
))
786 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Inner NUL byte in JSON record, refusing.");
788 decrypted
[decrypted_size
] = 0;
790 r
= json_parse(decrypted
, JSON_PARSE_SENSITIVE
, &rr
, NULL
, NULL
);
792 return log_error_errno(r
, "Failed to parse decrypted JSON record, refusing.");
794 lhr
= user_record_new();
798 r
= user_record_load(lhr
, rr
, USER_RECORD_LOAD_EMBEDDED
|USER_RECORD_PERMISSIVE
);
800 return log_error_errno(r
, "Failed to parse user record: %m");
802 if (!user_record_compatible(h
, lhr
))
803 return log_error_errno(SYNTHETIC_ERRNO(EREMCHG
), "LUKS home record not compatible with host record, refusing.");
805 r
= user_record_authenticate(lhr
, h
, cache
, /* strict_verify= */ true);
808 assert(r
> 0); /* Insist that a password was verified */
810 *ret_luks_home_record
= TAKE_PTR(lhr
);
814 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Couldn't find home record in LUKS2 header, refusing.");
817 static int format_luks_token_text(
818 struct crypt_device
*cd
,
820 const void *volume_key
,
823 int r
, encrypted_size_out1
= 0, encrypted_size_out2
= 0, iv_size
, key_size
;
824 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
825 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
826 _cleanup_free_
void *iv
= NULL
, *encrypted
= NULL
;
827 size_t text_length
, encrypted_size
;
828 _cleanup_free_
char *text
= NULL
;
829 const EVP_CIPHER
*cc
;
836 r
= crypt_device_to_evp_cipher(cd
, &cc
);
840 key_size
= EVP_CIPHER_key_length(cc
);
841 iv_size
= EVP_CIPHER_iv_length(cc
);
844 iv
= malloc(iv_size
);
848 r
= genuine_random_bytes(iv
, iv_size
, RANDOM_BLOCK
);
850 return log_error_errno(r
, "Failed to generate IV: %m");
853 context
= EVP_CIPHER_CTX_new();
857 if (EVP_EncryptInit_ex(context
, cc
, NULL
, volume_key
, iv
) != 1)
858 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize encryption context.");
860 r
= json_variant_format(hr
->json
, 0, &text
);
862 return log_error_errno(r
, "Failed to format user record for LUKS: %m");
864 text_length
= strlen(text
);
865 encrypted_size
= text_length
+ 2*key_size
- 1;
867 encrypted
= malloc(encrypted_size
);
871 if (EVP_EncryptUpdate(context
, encrypted
, &encrypted_size_out1
, (uint8_t*) text
, text_length
) != 1)
872 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to encrypt JSON record.");
874 assert((size_t) encrypted_size_out1
<= encrypted_size
);
876 if (EVP_EncryptFinal_ex(context
, (uint8_t*) encrypted
+ encrypted_size_out1
, &encrypted_size_out2
) != 1)
877 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finish encryption of JSON record. ");
879 assert((size_t) encrypted_size_out1
+ (size_t) encrypted_size_out2
<= encrypted_size
);
883 JSON_BUILD_PAIR("type", JSON_BUILD_STRING("systemd-homed")),
884 JSON_BUILD_PAIR("keyslots", JSON_BUILD_EMPTY_ARRAY
),
885 JSON_BUILD_PAIR("record", JSON_BUILD_BASE64(encrypted
, encrypted_size_out1
+ encrypted_size_out2
)),
886 JSON_BUILD_PAIR("iv", JSON_BUILD_BASE64(iv
, iv_size
))));
888 return log_error_errno(r
, "Failed to prepare LUKS JSON token object: %m");
890 r
= json_variant_format(v
, 0, ret
);
892 return log_error_errno(r
, "Failed to format encrypted user record for LUKS: %m");
897 int home_store_header_identity_luks(
900 UserRecord
*old_home
) {
902 _cleanup_(user_record_unrefp
) UserRecord
*header_home
= NULL
;
903 _cleanup_free_
char *text
= NULL
;
908 if (!setup
->crypt_device
)
911 assert(setup
->volume_key
);
913 /* Let's store the user's identity record in the LUKS2 "token" header data fields, in an encrypted
914 * fashion. Why that? If we'd rely on the record being embedded in the payload file system itself we
915 * would have to mount the file system before we can validate the JSON record, its signatures and
916 * whether it matches what we are looking for. However, kernel file system implementations are
917 * generally not ready to be used on untrusted media. Hence let's store the record independently of
918 * the file system, so that we can validate it first, and only then mount the file system. To keep
919 * things simple we use the same encryption settings for this record as for the file system itself. */
921 r
= user_record_clone(h
, USER_RECORD_EXTRACT_EMBEDDED
|USER_RECORD_PERMISSIVE
, &header_home
);
923 return log_error_errno(r
, "Failed to determine new header record: %m");
925 if (old_home
&& user_record_equal(old_home
, header_home
)) {
926 log_debug("Not updating header home record.");
930 r
= format_luks_token_text(setup
->crypt_device
, header_home
, setup
->volume_key
, &text
);
934 for (int token
= 0; token
< sym_crypt_token_max(CRYPT_LUKS2
); token
++) {
935 crypt_token_info state
;
938 state
= sym_crypt_token_status(setup
->crypt_device
, token
, &type
);
939 if (state
== CRYPT_TOKEN_INACTIVE
) /* First unconfigured token, we are done */
941 if (IN_SET(state
, CRYPT_TOKEN_INTERNAL
, CRYPT_TOKEN_INTERNAL_UNKNOWN
, CRYPT_TOKEN_EXTERNAL
))
942 continue; /* Not ours */
943 if (state
!= CRYPT_TOKEN_EXTERNAL_UNKNOWN
)
944 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected token state of token %i: %i", token
, (int) state
);
946 if (!streq(type
, "systemd-homed"))
949 r
= sym_crypt_token_json_set(setup
->crypt_device
, token
, text
);
951 return log_error_errno(r
, "Failed to set JSON token for slot %i: %m", token
);
953 /* Now, let's free the text so that for all further matching tokens we all crypt_json_token_set()
954 * with a NULL text in order to invalidate the tokens. */
959 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Didn't find any record token to update.");
961 log_info("Wrote LUKS header user record.");
966 int run_fitrim(int root_fd
) {
967 struct fstrim_range range
= {
971 /* If discarding is on, discard everything right after mounting, so that the discard setting takes
972 * effect on activation. (Also, optionally, trim on logout) */
974 assert(root_fd
>= 0);
976 if (ioctl(root_fd
, FITRIM
, &range
) < 0) {
977 if (ERRNO_IS_NOT_SUPPORTED(errno
) || errno
== EBADF
) {
978 log_debug_errno(errno
, "File system does not support FITRIM, not trimming.");
982 return log_warning_errno(errno
, "Failed to invoke FITRIM, ignoring: %m");
985 log_info("Discarded unused %s.", FORMAT_BYTES(range
.len
));
989 int run_fitrim_by_path(const char *root_path
) {
990 _cleanup_close_
int root_fd
= -1;
992 root_fd
= open(root_path
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
);
994 return log_error_errno(errno
, "Failed to open file system '%s' for trimming: %m", root_path
);
996 return run_fitrim(root_fd
);
999 int run_fallocate(int backing_fd
, const struct stat
*st
) {
1002 assert(backing_fd
>= 0);
1004 /* If discarding is off, let's allocate the whole image before mounting, so that the setting takes
1005 * effect on activation */
1008 if (fstat(backing_fd
, &stbuf
) < 0)
1009 return log_error_errno(errno
, "Failed to fstat(): %m");
1014 if (!S_ISREG(st
->st_mode
))
1017 if (st
->st_blocks
>= DIV_ROUND_UP(st
->st_size
, 512)) {
1018 log_info("Backing file is fully allocated already.");
1022 if (fallocate(backing_fd
, FALLOC_FL_KEEP_SIZE
, 0, st
->st_size
) < 0) {
1024 if (ERRNO_IS_NOT_SUPPORTED(errno
)) {
1025 log_debug_errno(errno
, "fallocate() not supported on file system, ignoring.");
1029 if (ERRNO_IS_DISK_SPACE(errno
)) {
1030 log_debug_errno(errno
, "Not enough disk space to fully allocate home.");
1031 return -ENOSPC
; /* make recognizable */
1034 return log_error_errno(errno
, "Failed to allocate backing file blocks: %m");
1037 log_info("Allocated additional %s.",
1038 FORMAT_BYTES((DIV_ROUND_UP(st
->st_size
, 512) - st
->st_blocks
) * 512));
1042 int run_fallocate_by_path(const char *backing_path
) {
1043 _cleanup_close_
int backing_fd
= -1;
1045 backing_fd
= open(backing_path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
1047 return log_error_errno(errno
, "Failed to open '%s' for fallocate(): %m", backing_path
);
1049 return run_fallocate(backing_fd
, NULL
);
1052 static int lock_image_fd(int image_fd
, const char *ip
) {
1055 /* If the $SYSTEMD_LUKS_LOCK environment variable is set we'll take an exclusive BSD lock on the
1056 * image file, and send it to our parent. homed will keep it open to ensure no other instance of
1057 * homed (across the network or such) will also mount the file. */
1059 r
= getenv_bool("SYSTEMD_LUKS_LOCK");
1063 return log_error_errno(r
, "Failed to parse $SYSTEMD_LUKS_LOCK environment variable: %m");
1067 if (fstat(image_fd
, &st
) < 0)
1068 return log_error_errno(errno
, "Failed to stat image file: %m");
1069 if (S_ISBLK(st
.st_mode
)) {
1070 /* Locking block devices doesn't really make sense, as this might interfear with
1071 * udev's workings, and these locks aren't network propagated anyway, hence not what
1072 * we are after here. */
1073 log_debug("Not locking image file '%s', since it's a block device.", ip
);
1076 r
= stat_verify_regular(&st
);
1078 return log_error_errno(r
, "Image file to lock is not a regular file: %m");
1080 if (flock(image_fd
, LOCK_EX
|LOCK_NB
) < 0) {
1082 if (errno
== EWOULDBLOCK
)
1083 log_error_errno(errno
, "Image file '%s' already locked, can't use.", ip
);
1085 log_error_errno(errno
, "Failed to lock image file '%s': %m", ip
);
1087 return errno
!= EWOULDBLOCK
? -errno
: -EADDRINUSE
; /* Make error recognizable */
1090 log_info("Successfully locked image file '%s'.", ip
);
1092 /* Now send it to our parent to keep safe while the home dir is active */
1093 r
= sd_pid_notify_with_fds(0, false, "SYSTEMD_LUKS_LOCK_FD=1", &image_fd
, 1);
1095 log_warning_errno(r
, "Failed to send LUKS lock fd to parent, ignoring: %m");
1101 int home_prepare_luks(
1103 bool already_activated
,
1104 const char *force_image_path
,
1105 PasswordCache
*cache
,
1107 UserRecord
**ret_luks_home
) {
1109 sd_id128_t found_partition_uuid
, found_luks_uuid
, found_fs_uuid
;
1110 _cleanup_(user_record_unrefp
) UserRecord
*luks_home
= NULL
;
1111 _cleanup_(loop_device_unrefp
) LoopDevice
*loop
= NULL
;
1112 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1113 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
1114 _cleanup_close_
int root_fd
= -1, image_fd
= -1;
1115 bool dm_activated
= false, mounted
= false;
1116 size_t volume_key_size
= 0;
1117 bool marked_dirty
= false;
1118 uint64_t offset
, size
;
1123 assert(setup
->dm_name
);
1124 assert(setup
->dm_node
);
1126 assert(user_record_storage(h
) == USER_LUKS
);
1128 r
= dlopen_cryptsetup();
1132 if (already_activated
) {
1133 struct loop_info64 info
;
1136 r
= luks_open(setup
->dm_name
,
1146 r
= luks_validate_home_record(cd
, h
, volume_key
, cache
, &luks_home
);
1150 n
= sym_crypt_get_device_name(cd
);
1152 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine backing device for DM %s.", setup
->dm_name
);
1154 r
= loop_device_open(n
, O_RDWR
, &loop
);
1156 return log_error_errno(r
, "Failed to open loopback device %s: %m", n
);
1158 if (ioctl(loop
->fd
, LOOP_GET_STATUS64
, &info
) < 0) {
1159 _cleanup_free_
char *sysfs
= NULL
;
1162 if (!IN_SET(errno
, ENOTTY
, EINVAL
))
1163 return log_error_errno(errno
, "Failed to get block device metrics of %s: %m", n
);
1165 if (ioctl(loop
->fd
, BLKGETSIZE64
, &size
) < 0)
1166 return log_error_errno(r
, "Failed to read block device size of %s: %m", n
);
1168 if (fstat(loop
->fd
, &st
) < 0)
1169 return log_error_errno(r
, "Failed to stat block device %s: %m", n
);
1170 assert(S_ISBLK(st
.st_mode
));
1172 if (asprintf(&sysfs
, "/sys/dev/block/%u:%u/partition", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
1175 if (access(sysfs
, F_OK
) < 0) {
1176 if (errno
!= ENOENT
)
1177 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", sysfs
);
1181 _cleanup_free_
char *buffer
= NULL
;
1183 if (asprintf(&sysfs
, "/sys/dev/block/%u:%u/start", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
1186 r
= read_one_line_file(sysfs
, &buffer
);
1188 return log_error_errno(r
, "Failed to read partition start offset: %m");
1190 r
= safe_atou64(buffer
, &offset
);
1192 return log_error_errno(r
, "Failed to parse partition start offset: %m");
1194 if (offset
> UINT64_MAX
/ 512U)
1195 return log_error_errno(SYNTHETIC_ERRNO(E2BIG
), "Offset too large for 64 byte range, refusing.");
1200 #if HAVE_VALGRIND_MEMCHECK_H
1201 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
1204 offset
= info
.lo_offset
;
1205 size
= info
.lo_sizelimit
;
1208 found_partition_uuid
= found_fs_uuid
= SD_ID128_NULL
;
1210 log_info("Discovered used loopback device %s.", loop
->node
);
1212 root_fd
= open(user_record_home_directory(h
), O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
1214 r
= log_error_errno(errno
, "Failed to open home directory: %m");
1218 _cleanup_free_
char *fstype
= NULL
, *subdir
= NULL
;
1222 ip
= force_image_path
?: user_record_image_path(h
);
1224 subdir
= path_join("/run/systemd/user-home-mount/", user_record_user_name_and_realm(h
));
1228 image_fd
= open(ip
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
1230 return log_error_errno(errno
, "Failed to open image file %s: %m", ip
);
1232 if (fstat(image_fd
, &st
) < 0)
1233 return log_error_errno(errno
, "Failed to fstat() image file: %m");
1234 if (!S_ISREG(st
.st_mode
) && !S_ISBLK(st
.st_mode
))
1235 return log_error_errno(
1236 S_ISDIR(st
.st_mode
) ? SYNTHETIC_ERRNO(EISDIR
) : SYNTHETIC_ERRNO(EBADFD
),
1237 "Image file %s is not a regular file or block device: %m", ip
);
1239 r
= lock_image_fd(image_fd
, ip
);
1243 r
= luks_validate(image_fd
, user_record_user_name_and_realm(h
), h
->partition_uuid
, &found_partition_uuid
, &offset
, &size
);
1245 return log_error_errno(r
, "Failed to validate disk label: %m");
1247 /* Everything before this point left the image untouched. We are now starting to make
1248 * changes, hence mark the image dirty */
1249 marked_dirty
= run_mark_dirty(image_fd
, true) > 0;
1251 if (!user_record_luks_discard(h
)) {
1252 r
= run_fallocate(image_fd
, &st
);
1257 r
= loop_device_make(image_fd
, O_RDWR
, offset
, size
, 0, &loop
);
1259 log_error_errno(r
, "Loopback block device support is not available on this system.");
1260 return -ENOLINK
; /* make recognizable */
1263 return log_error_errno(r
, "Failed to allocate loopback context: %m");
1265 log_info("Setting up loopback device %s completed.", loop
->node
?: ip
);
1267 r
= luks_setup(loop
->node
?: ip
,
1271 h
->luks_cipher_mode
,
1272 h
->luks_volume_key_size
,
1275 user_record_luks_discard(h
) || user_record_luks_offline_discard(h
),
1283 dm_activated
= true;
1285 r
= luks_validate_home_record(cd
, h
, volume_key
, cache
, &luks_home
);
1289 r
= fs_validate(setup
->dm_node
, h
->file_system_uuid
, &fstype
, &found_fs_uuid
);
1293 r
= run_fsck(setup
->dm_node
, fstype
);
1297 r
= home_unshare_and_mount(setup
->dm_node
, fstype
, user_record_luks_discard(h
), user_record_mount_flags(h
));
1303 root_fd
= open(subdir
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
1305 r
= log_error_errno(errno
, "Failed to open home directory: %m");
1309 if (user_record_luks_discard(h
))
1310 (void) run_fitrim(root_fd
);
1312 setup
->image_fd
= TAKE_FD(image_fd
);
1313 setup
->do_offline_fallocate
= !(setup
->do_offline_fitrim
= user_record_luks_offline_discard(h
));
1314 setup
->do_mark_clean
= marked_dirty
;
1317 setup
->loop
= TAKE_PTR(loop
);
1318 setup
->crypt_device
= TAKE_PTR(cd
);
1319 setup
->root_fd
= TAKE_FD(root_fd
);
1320 setup
->found_partition_uuid
= found_partition_uuid
;
1321 setup
->found_luks_uuid
= found_luks_uuid
;
1322 setup
->found_fs_uuid
= found_fs_uuid
;
1323 setup
->partition_offset
= offset
;
1324 setup
->partition_size
= size
;
1325 setup
->volume_key
= TAKE_PTR(volume_key
);
1326 setup
->volume_key_size
= volume_key_size
;
1328 setup
->undo_mount
= mounted
;
1329 setup
->undo_dm
= dm_activated
;
1332 *ret_luks_home
= TAKE_PTR(luks_home
);
1338 (void) umount_verbose(LOG_ERR
, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW
);
1341 (void) sym_crypt_deactivate_by_name(cd
, setup
->dm_name
, 0);
1343 if (image_fd
>= 0 && marked_dirty
)
1344 (void) run_mark_dirty(image_fd
, false);
1349 static void print_size_summary(uint64_t host_size
, uint64_t encrypted_size
, struct statfs
*sfs
) {
1352 log_info("Image size is %s, file system size is %s, file system payload size is %s, file system free is %s.",
1353 FORMAT_BYTES(host_size
),
1354 FORMAT_BYTES(encrypted_size
),
1355 FORMAT_BYTES((uint64_t) sfs
->f_blocks
* (uint64_t) sfs
->f_frsize
),
1356 FORMAT_BYTES((uint64_t) sfs
->f_bfree
* (uint64_t) sfs
->f_frsize
));
1359 int home_activate_luks(
1361 PasswordCache
*cache
,
1362 UserRecord
**ret_home
) {
1364 _cleanup_(user_record_unrefp
) UserRecord
*new_home
= NULL
, *luks_home_record
= NULL
;
1365 _cleanup_(home_setup_undo
) HomeSetup setup
= HOME_SETUP_INIT
;
1366 uint64_t host_size
, encrypted_size
;
1367 const char *hdo
, *hd
;
1372 assert(user_record_storage(h
) == USER_LUKS
);
1375 r
= dlopen_cryptsetup();
1379 assert_se(hdo
= user_record_home_directory(h
));
1380 hd
= strdupa_safe(hdo
); /* copy the string out, since it might change later in the home record object */
1382 r
= home_get_state_luks(h
, &setup
);
1386 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "Device mapper device %s already exists, refusing.", setup
.dm_node
);
1388 r
= home_prepare_luks(
1398 r
= block_get_size_by_fd(setup
.loop
->fd
, &host_size
);
1400 return log_error_errno(r
, "Failed to get loopback block device size: %m");
1402 r
= block_get_size_by_path(setup
.dm_node
, &encrypted_size
);
1404 return log_error_errno(r
, "Failed to get LUKS block device size: %m");
1416 r
= home_extend_embedded_identity(new_home
, h
, &setup
);
1420 setup
.root_fd
= safe_close(setup
.root_fd
);
1422 r
= home_move_mount(user_record_user_name_and_realm(h
), hd
);
1426 setup
.undo_mount
= false;
1427 setup
.do_offline_fitrim
= false;
1429 loop_device_relinquish(setup
.loop
);
1431 r
= sym_crypt_deactivate_by_name(NULL
, setup
.dm_name
, CRYPT_DEACTIVATE_DEFERRED
);
1433 log_warning_errno(r
, "Failed to relinquish DM device, ignoring: %m");
1435 setup
.undo_dm
= false;
1436 setup
.do_offline_fallocate
= false;
1437 setup
.do_mark_clean
= false;
1439 log_info("Everything completed.");
1441 print_size_summary(host_size
, encrypted_size
, &sfs
);
1443 *ret_home
= TAKE_PTR(new_home
);
1447 int home_deactivate_luks(UserRecord
*h
) {
1448 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1449 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
1453 /* Note that the DM device and loopback device are set to auto-detach, hence strictly speaking we
1454 * don't have to explicitly have to detach them. However, we do that nonetheless (in case of the DM
1455 * device), to avoid races: by explicitly detaching them we know when the detaching is complete. We
1456 * don't bother about the loopback device because unlike the DM device it doesn't have a fixed
1459 r
= dlopen_cryptsetup();
1463 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
1467 r
= sym_crypt_init_by_name(&cd
, dm_name
);
1468 if (IN_SET(r
, -ENODEV
, -EINVAL
, -ENOENT
)) {
1469 log_debug_errno(r
, "LUKS device %s has already been detached.", dm_name
);
1470 we_detached
= false;
1472 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
1474 log_info("Discovered used LUKS device %s.", dm_node
);
1476 cryptsetup_enable_logging(cd
);
1478 r
= sym_crypt_deactivate_by_name(cd
, dm_name
, 0);
1479 if (IN_SET(r
, -ENODEV
, -EINVAL
, -ENOENT
)) {
1480 log_debug_errno(r
, "LUKS device %s is already detached.", dm_node
);
1481 we_detached
= false;
1483 return log_info_errno(r
, "LUKS device %s couldn't be deactivated: %m", dm_node
);
1485 log_info("LUKS device detaching completed.");
1490 if (user_record_luks_offline_discard(h
))
1491 log_debug("Not allocating on logout.");
1493 (void) run_fallocate_by_path(user_record_image_path(h
));
1495 run_mark_dirty_by_path(user_record_image_path(h
), false);
1499 int home_trim_luks(UserRecord
*h
) {
1502 if (!user_record_luks_offline_discard(h
)) {
1503 log_debug("Not trimming on logout.");
1507 (void) run_fitrim_by_path(user_record_home_directory(h
));
1511 static struct crypt_pbkdf_type
* build_good_pbkdf(struct crypt_pbkdf_type
*buffer
, UserRecord
*hr
) {
1515 *buffer
= (struct crypt_pbkdf_type
) {
1516 .hash
= user_record_luks_pbkdf_hash_algorithm(hr
),
1517 .type
= user_record_luks_pbkdf_type(hr
),
1518 .time_ms
= user_record_luks_pbkdf_time_cost_usec(hr
) / USEC_PER_MSEC
,
1519 .max_memory_kb
= user_record_luks_pbkdf_memory_cost(hr
) / 1024,
1520 .parallel_threads
= user_record_luks_pbkdf_parallel_threads(hr
),
1526 static struct crypt_pbkdf_type
* build_minimal_pbkdf(struct crypt_pbkdf_type
*buffer
, UserRecord
*hr
) {
1530 /* For PKCS#11 derived keys (which are generated randomly and are of high quality already) we use a
1532 *buffer
= (struct crypt_pbkdf_type
) {
1533 .hash
= user_record_luks_pbkdf_hash_algorithm(hr
),
1534 .type
= CRYPT_KDF_PBKDF2
,
1542 static int luks_format(
1544 const char *dm_name
,
1547 const PasswordCache
*cache
,
1548 char **effective_passwords
,
1551 struct crypt_device
**ret
) {
1553 _cleanup_(user_record_unrefp
) UserRecord
*reduced
= NULL
;
1554 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1555 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
1556 struct crypt_pbkdf_type good_pbkdf
, minimal_pbkdf
;
1557 _cleanup_free_
char *text
= NULL
;
1558 size_t volume_key_size
;
1567 r
= sym_crypt_init(&cd
, node
);
1569 return log_error_errno(r
, "Failed to allocate libcryptsetup context: %m");
1571 cryptsetup_enable_logging(cd
);
1573 /* Normally we'd, just leave volume key generation to libcryptsetup. However, we can't, since we
1574 * can't extract the volume key from the library again, but we need it in order to encrypt the JSON
1575 * record. Hence, let's generate it on our own, so that we can keep track of it. */
1577 volume_key_size
= user_record_luks_volume_key_size(hr
);
1578 volume_key
= malloc(volume_key_size
);
1582 r
= genuine_random_bytes(volume_key
, volume_key_size
, RANDOM_BLOCK
);
1584 return log_error_errno(r
, "Failed to generate volume key: %m");
1586 #if HAVE_CRYPT_SET_METADATA_SIZE
1587 /* Increase the metadata space to 4M, the largest LUKS2 supports */
1588 r
= sym_crypt_set_metadata_size(cd
, 4096U*1024U, 0);
1590 return log_error_errno(r
, "Failed to change LUKS2 metadata size: %m");
1593 build_good_pbkdf(&good_pbkdf
, hr
);
1594 build_minimal_pbkdf(&minimal_pbkdf
, hr
);
1596 r
= sym_crypt_format(
1599 user_record_luks_cipher(hr
),
1600 user_record_luks_cipher_mode(hr
),
1601 ID128_TO_UUID_STRING(uuid
),
1604 &(struct crypt_params_luks2
) {
1606 .subsystem
= "systemd-home",
1607 .sector_size
= 512U,
1608 .pbkdf
= &good_pbkdf
,
1611 return log_error_errno(r
, "Failed to format LUKS image: %m");
1613 log_info("LUKS formatting completed.");
1615 STRV_FOREACH(pp
, effective_passwords
) {
1617 if (strv_contains(cache
->pkcs11_passwords
, *pp
) ||
1618 strv_contains(cache
->fido2_passwords
, *pp
)) {
1619 log_debug("Using minimal PBKDF for slot %i", slot
);
1620 r
= sym_crypt_set_pbkdf_type(cd
, &minimal_pbkdf
);
1622 log_debug("Using good PBKDF for slot %i", slot
);
1623 r
= sym_crypt_set_pbkdf_type(cd
, &good_pbkdf
);
1626 return log_error_errno(r
, "Failed to tweak PBKDF for slot %i: %m", slot
);
1628 r
= sym_crypt_keyslot_add_by_volume_key(
1636 return log_error_errno(r
, "Failed to set up LUKS password for slot %i: %m", slot
);
1638 log_info("Writing password to LUKS keyslot %i completed.", slot
);
1642 r
= sym_crypt_activate_by_volume_key(
1647 discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
1649 return log_error_errno(r
, "Failed to activate LUKS superblock: %m");
1651 log_info("LUKS activation by volume key succeeded.");
1653 r
= user_record_clone(hr
, USER_RECORD_EXTRACT_EMBEDDED
|USER_RECORD_PERMISSIVE
, &reduced
);
1655 return log_error_errno(r
, "Failed to prepare home record for LUKS: %m");
1657 r
= format_luks_token_text(cd
, reduced
, volume_key
, &text
);
1661 r
= sym_crypt_token_json_set(cd
, CRYPT_ANY_TOKEN
, text
);
1663 return log_error_errno(r
, "Failed to set LUKS JSON token: %m");
1665 log_info("Writing user record as LUKS token completed.");
1668 *ret
= TAKE_PTR(cd
);
1673 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_context
*, fdisk_unref_context
, NULL
);
1674 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_partition
*, fdisk_unref_partition
, NULL
);
1675 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_parttype
*, fdisk_unref_parttype
, NULL
);
1676 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_table
*, fdisk_unref_table
, NULL
);
1678 static int make_partition_table(
1682 uint64_t *ret_offset
,
1684 sd_id128_t
*ret_disk_uuid
) {
1686 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*p
= NULL
, *q
= NULL
;
1687 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
1688 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1689 _cleanup_free_
char *path
= NULL
, *disk_uuid_as_string
= NULL
;
1690 uint64_t offset
, size
, first_lba
, start
, last_lba
, end
;
1691 sd_id128_t disk_uuid
;
1699 t
= fdisk_new_parttype();
1703 r
= fdisk_parttype_set_typestr(t
, "773f91ef-66d4-49b5-bd83-d683bf40ad16");
1705 return log_error_errno(r
, "Failed to initialize partition type: %m");
1707 c
= fdisk_new_context();
1711 if (asprintf(&path
, "/proc/self/fd/%i", fd
) < 0)
1714 r
= fdisk_assign_device(c
, path
, 0);
1716 return log_error_errno(r
, "Failed to open device: %m");
1718 r
= fdisk_create_disklabel(c
, "gpt");
1720 return log_error_errno(r
, "Failed to create GPT disk label: %m");
1722 p
= fdisk_new_partition();
1726 r
= fdisk_partition_set_type(p
, t
);
1728 return log_error_errno(r
, "Failed to set partition type: %m");
1730 r
= fdisk_partition_partno_follow_default(p
, 1);
1732 return log_error_errno(r
, "Failed to place partition at first free partition index: %m");
1734 first_lba
= fdisk_get_first_lba(c
); /* Boundary where usable space starts */
1735 assert(first_lba
<= UINT64_MAX
/512);
1736 start
= DISK_SIZE_ROUND_UP(first_lba
* 512); /* Round up to multiple of 4K */
1738 if (start
== UINT64_MAX
)
1739 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Overflow while rounding up start LBA.");
1741 last_lba
= fdisk_get_last_lba(c
); /* One sector before boundary where usable space ends */
1742 assert(last_lba
< UINT64_MAX
/512);
1743 end
= DISK_SIZE_ROUND_DOWN((last_lba
+ 1) * 512); /* Round down to multiple of 4K */
1746 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Resulting partition size zero or negative.");
1748 r
= fdisk_partition_set_start(p
, start
/ 512);
1750 return log_error_errno(r
, "Failed to place partition at offset %" PRIu64
": %m", start
);
1752 r
= fdisk_partition_set_size(p
, (end
- start
) / 512);
1754 return log_error_errno(r
, "Failed to end partition at offset %" PRIu64
": %m", end
);
1756 r
= fdisk_partition_set_name(p
, label
);
1758 return log_error_errno(r
, "Failed to set partition name: %m");
1760 r
= fdisk_partition_set_uuid(p
, ID128_TO_UUID_STRING(uuid
));
1762 return log_error_errno(r
, "Failed to set partition UUID: %m");
1764 r
= fdisk_add_partition(c
, p
, NULL
);
1766 return log_error_errno(r
, "Failed to add partition: %m");
1768 r
= fdisk_write_disklabel(c
);
1770 return log_error_errno(r
, "Failed to write disk label: %m");
1772 r
= fdisk_get_disklabel_id(c
, &disk_uuid_as_string
);
1774 return log_error_errno(r
, "Failed to determine disk label UUID: %m");
1776 r
= sd_id128_from_string(disk_uuid_as_string
, &disk_uuid
);
1778 return log_error_errno(r
, "Failed to parse disk label UUID: %m");
1780 r
= fdisk_get_partition(c
, 0, &q
);
1782 return log_error_errno(r
, "Failed to read created partition metadata: %m");
1784 assert(fdisk_partition_has_start(q
));
1785 offset
= fdisk_partition_get_start(q
);
1786 if (offset
> UINT64_MAX
/ 512U)
1787 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Partition offset too large.");
1789 assert(fdisk_partition_has_size(q
));
1790 size
= fdisk_partition_get_size(q
);
1791 if (size
> UINT64_MAX
/ 512U)
1792 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Partition size too large.");
1794 *ret_offset
= offset
* 512U;
1795 *ret_size
= size
* 512U;
1796 *ret_disk_uuid
= disk_uuid
;
1801 static bool supported_fs_size(const char *fstype
, uint64_t host_size
) {
1804 m
= minimal_size_by_fs_name(fstype
);
1805 if (m
== UINT64_MAX
)
1808 return host_size
>= m
;
1811 static int wait_for_devlink(const char *path
) {
1812 _cleanup_close_
int inotify_fd
= -1;
1816 /* let's wait for a device link to show up in /dev, with a timeout. This is good to do since we
1817 * return a /dev/disk/by-uuid/… link to our callers and they likely want to access it right-away,
1818 * hence let's wait until udev has caught up with our changes, and wait for the symlink to be
1821 until
= usec_add(now(CLOCK_MONOTONIC
), 45 * USEC_PER_SEC
);
1824 _cleanup_free_
char *dn
= NULL
;
1827 if (laccess(path
, F_OK
) < 0) {
1828 if (errno
!= ENOENT
)
1829 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", path
);
1831 return 0; /* Found it */
1833 if (inotify_fd
< 0) {
1834 /* We need to wait for the device symlink to show up, let's create an inotify watch for it */
1835 inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
1837 return log_error_errno(errno
, "Failed to allocate inotify fd: %m");
1840 dn
= dirname_malloc(path
);
1845 log_info("Watching %s", dn
);
1847 if (inotify_add_watch(inotify_fd
, dn
, IN_CREATE
|IN_MOVED_TO
|IN_ONLYDIR
|IN_DELETE_SELF
|IN_MOVE_SELF
) < 0) {
1848 if (errno
!= ENOENT
)
1849 return log_error_errno(errno
, "Failed to add watch on %s: %m", dn
);
1853 if (empty_or_root(dn
))
1856 dn
= dirname_malloc(dn
);
1859 w
= now(CLOCK_MONOTONIC
);
1861 return log_error_errno(SYNTHETIC_ERRNO(ETIMEDOUT
), "Device link %s still hasn't shown up, giving up.", path
);
1863 r
= fd_wait_for_event(inotify_fd
, POLLIN
, usec_sub_unsigned(until
, w
));
1865 return log_error_errno(r
, "Failed to watch inotify: %m");
1867 (void) flush_fd(inotify_fd
);
1871 static int calculate_disk_size(UserRecord
*h
, const char *parent_dir
, uint64_t *ret
) {
1879 if (h
->disk_size
!= UINT64_MAX
) {
1880 *ret
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
1884 if (statfs(parent_dir
, &sfs
) < 0)
1885 return log_error_errno(errno
, "statfs() on %s failed: %m", parent_dir
);
1887 m
= sfs
.f_bsize
* sfs
.f_bavail
;
1889 if (h
->disk_size_relative
== UINT64_MAX
) {
1891 if (m
> UINT64_MAX
/ USER_DISK_SIZE_DEFAULT_PERCENT
)
1892 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Disk size too large.");
1894 *ret
= DISK_SIZE_ROUND_DOWN(m
* USER_DISK_SIZE_DEFAULT_PERCENT
/ 100);
1896 log_info("Sizing home to %u%% of available disk space, which is %s.",
1897 USER_DISK_SIZE_DEFAULT_PERCENT
,
1898 FORMAT_BYTES(*ret
));
1900 *ret
= DISK_SIZE_ROUND_DOWN((uint64_t) ((double) m
* (double) h
->disk_size_relative
/ (double) UINT32_MAX
));
1902 log_info("Sizing home to %" PRIu64
".%01" PRIu64
"%% of available disk space, which is %s.",
1903 (h
->disk_size_relative
* 100) / UINT32_MAX
,
1904 ((h
->disk_size_relative
* 1000) / UINT32_MAX
) % 10,
1905 FORMAT_BYTES(*ret
));
1908 if (*ret
< USER_DISK_SIZE_MIN
)
1909 *ret
= USER_DISK_SIZE_MIN
;
1914 static int home_truncate(
1927 trunc
= user_record_luks_discard(h
);
1929 r
= fallocate(fd
, 0, 0, size
);
1930 if (r
< 0 && ERRNO_IS_NOT_SUPPORTED(errno
)) {
1931 /* Some file systems do not support fallocate(), let's gracefully degrade
1932 * (ZFS, reiserfs, …) and fall back to truncation */
1933 log_notice_errno(errno
, "Backing file system does not support fallocate(), falling back to ftruncate(), i.e. implicitly using non-discard mode.");
1939 r
= ftruncate(fd
, size
);
1942 if (ERRNO_IS_DISK_SPACE(errno
)) {
1943 log_error_errno(errno
, "Not enough disk space to allocate home.");
1944 return -ENOSPC
; /* make recognizable */
1947 return log_error_errno(errno
, "Failed to truncate home image %s: %m", path
);
1953 int home_create_luks(
1955 PasswordCache
*cache
,
1956 char **effective_passwords
,
1957 UserRecord
**ret_home
) {
1959 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
, *subdir
= NULL
, *disk_uuid_path
= NULL
, *temporary_image_path
= NULL
;
1960 uint64_t encrypted_size
,
1961 host_size
= 0, partition_offset
= 0, partition_size
= 0; /* Unnecessary initialization to appease gcc */
1962 bool image_created
= false, dm_activated
= false, mounted
= false;
1963 _cleanup_(user_record_unrefp
) UserRecord
*new_home
= NULL
;
1964 sd_id128_t partition_uuid
, fs_uuid
, luks_uuid
, disk_uuid
;
1965 _cleanup_(loop_device_unrefp
) LoopDevice
*loop
= NULL
;
1966 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1967 _cleanup_close_
int image_fd
= -1, root_fd
= -1;
1968 const char *fstype
, *ip
;
1973 assert(h
->storage
< 0 || h
->storage
== USER_LUKS
);
1976 r
= dlopen_cryptsetup();
1980 assert_se(ip
= user_record_image_path(h
));
1982 fstype
= user_record_file_system_type(h
);
1983 if (!supported_fstype(fstype
))
1984 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "Unsupported file system type: %s", fstype
);
1986 r
= mkfs_exists(fstype
);
1988 return log_error_errno(r
, "Failed to check if mkfs binary for %s exists: %m", fstype
);
1990 if (h
->file_system_type
|| streq(fstype
, "ext4") || !supported_fstype("ext4"))
1991 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "mkfs binary for file system type %s does not exist.", fstype
);
1993 /* If the record does not explicitly declare a file system to use, and the compiled-in
1994 * default does not actually exist, than do an automatic fallback onto ext4, as the baseline
1995 * fs of Linux. We won't search for a working fs type here beyond ext4, i.e. nothing fancier
1996 * than a single, conservative fallback to baseline. This should be useful in minimal
1997 * environments where mkfs.btrfs or so are not made available, but mkfs.ext4 as Linux' most
1998 * boring, most basic fs is. */
1999 log_info("Formatting tool for compiled-in default file system %s not available, falling back to ext4 instead.", fstype
);
2003 if (sd_id128_is_null(h
->partition_uuid
)) {
2004 r
= sd_id128_randomize(&partition_uuid
);
2006 return log_error_errno(r
, "Failed to acquire partition UUID: %m");
2008 partition_uuid
= h
->partition_uuid
;
2010 if (sd_id128_is_null(h
->luks_uuid
)) {
2011 r
= sd_id128_randomize(&luks_uuid
);
2013 return log_error_errno(r
, "Failed to acquire LUKS UUID: %m");
2015 luks_uuid
= h
->luks_uuid
;
2017 if (sd_id128_is_null(h
->file_system_uuid
)) {
2018 r
= sd_id128_randomize(&fs_uuid
);
2020 return log_error_errno(r
, "Failed to acquire file system UUID: %m");
2022 fs_uuid
= h
->file_system_uuid
;
2024 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
2028 r
= access(dm_node
, F_OK
);
2030 if (errno
!= ENOENT
)
2031 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", dm_node
);
2033 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "Device mapper device %s already exists, refusing.", dm_node
);
2035 if (path_startswith(ip
, "/dev/")) {
2036 _cleanup_free_
char *sysfs
= NULL
;
2037 uint64_t block_device_size
;
2040 /* Let's place the home directory on a real device, i.e. an USB stick or such */
2042 image_fd
= open(ip
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
2044 return log_error_errno(errno
, "Failed to open device %s: %m", ip
);
2046 if (fstat(image_fd
, &st
) < 0)
2047 return log_error_errno(errno
, "Failed to stat device %s: %m", ip
);
2048 if (!S_ISBLK(st
.st_mode
))
2049 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Device is not a block device, refusing.");
2051 if (asprintf(&sysfs
, "/sys/dev/block/%u:%u/partition", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
2053 if (access(sysfs
, F_OK
) < 0) {
2054 if (errno
!= ENOENT
)
2055 return log_error_errno(errno
, "Failed to check whether %s exists: %m", sysfs
);
2057 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Operating on partitions is currently not supported, sorry. Please specify a top-level block device.");
2059 if (flock(image_fd
, LOCK_EX
) < 0) /* make sure udev doesn't read from it while we operate on the device */
2060 return log_error_errno(errno
, "Failed to lock block device %s: %m", ip
);
2062 if (ioctl(image_fd
, BLKGETSIZE64
, &block_device_size
) < 0)
2063 return log_error_errno(errno
, "Failed to read block device size: %m");
2065 if (h
->disk_size
== UINT64_MAX
) {
2067 /* If a relative disk size is requested, apply it relative to the block device size */
2068 if (h
->disk_size_relative
< UINT32_MAX
)
2069 host_size
= CLAMP(DISK_SIZE_ROUND_DOWN(block_device_size
* h
->disk_size_relative
/ UINT32_MAX
),
2070 USER_DISK_SIZE_MIN
, USER_DISK_SIZE_MAX
);
2072 host_size
= block_device_size
; /* Otherwise, take the full device */
2074 } else if (h
->disk_size
> block_device_size
)
2075 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE
), "Selected disk size larger than backing block device, refusing.");
2077 host_size
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
2079 if (!supported_fs_size(fstype
, host_size
))
2080 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
),
2081 "Selected file system size too small for %s.", fstype
);
2083 /* After creation we should reference this partition by its UUID instead of the block
2084 * device. That's preferable since the user might have specified a device node such as
2085 * /dev/sdb to us, which might look very different when replugged. */
2086 if (asprintf(&disk_uuid_path
, "/dev/disk/by-uuid/" SD_ID128_UUID_FORMAT_STR
, SD_ID128_FORMAT_VAL(luks_uuid
)) < 0)
2089 if (user_record_luks_discard(h
) || user_record_luks_offline_discard(h
)) {
2090 /* If we want online or offline discard, discard once before we start using things. */
2092 if (ioctl(image_fd
, BLKDISCARD
, (uint64_t[]) { 0, block_device_size
}) < 0)
2093 log_full_errno(errno
== EOPNOTSUPP
? LOG_DEBUG
: LOG_WARNING
, errno
,
2094 "Failed to issue full-device BLKDISCARD on device, ignoring: %m");
2096 log_info("Full device discard completed.");
2099 _cleanup_free_
char *parent
= NULL
;
2101 parent
= dirname_malloc(ip
);
2105 r
= mkdir_p(parent
, 0755);
2107 return log_error_errno(r
, "Failed to create parent directory %s: %m", parent
);
2109 r
= calculate_disk_size(h
, parent
, &host_size
);
2113 if (!supported_fs_size(fstype
, host_size
))
2114 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Selected file system size too small for %s.", fstype
);
2116 r
= tempfn_random(ip
, "homework", &temporary_image_path
);
2118 return log_error_errno(r
, "Failed to derive temporary file name for %s: %m", ip
);
2120 image_fd
= open(temporary_image_path
, O_RDWR
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
2122 return log_error_errno(errno
, "Failed to create home image %s: %m", temporary_image_path
);
2124 image_created
= true;
2126 r
= chattr_fd(image_fd
, FS_NOCOW_FL
, FS_NOCOW_FL
, NULL
);
2128 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
2129 "Failed to set file attributes on %s, ignoring: %m", temporary_image_path
);
2131 r
= home_truncate(h
, image_fd
, temporary_image_path
, host_size
);
2135 log_info("Allocating image file completed.");
2138 r
= make_partition_table(
2140 user_record_user_name_and_realm(h
),
2148 log_info("Writing of partition table completed.");
2150 r
= loop_device_make(image_fd
, O_RDWR
, partition_offset
, partition_size
, 0, &loop
);
2152 if (r
== -ENOENT
) { /* this means /dev/loop-control doesn't exist, i.e. we are in a container
2153 * or similar and loopback bock devices are not available, return a
2154 * recognizable error in this case. */
2155 log_error_errno(r
, "Loopback block device support is not available on this system.");
2160 log_error_errno(r
, "Failed to set up loopback device for %s: %m", temporary_image_path
);
2164 r
= loop_device_flock(loop
, LOCK_EX
); /* make sure udev won't read before we are done */
2166 log_error_errno(r
, "Failed to take lock on loop device: %m");
2170 log_info("Setting up loopback device %s completed.", loop
->node
?: ip
);
2172 r
= luks_format(loop
->node
,
2175 user_record_user_name_and_realm(h
),
2177 effective_passwords
,
2178 user_record_luks_discard(h
) || user_record_luks_offline_discard(h
),
2184 dm_activated
= true;
2186 r
= block_get_size_by_path(dm_node
, &encrypted_size
);
2188 log_error_errno(r
, "Failed to get encrypted block device size: %m");
2192 log_info("Setting up LUKS device %s completed.", dm_node
);
2194 r
= make_filesystem(dm_node
, fstype
, user_record_user_name_and_realm(h
), fs_uuid
, user_record_luks_discard(h
));
2198 log_info("Formatting file system completed.");
2200 r
= home_unshare_and_mount(dm_node
, fstype
, user_record_luks_discard(h
), user_record_mount_flags(h
));
2206 subdir
= path_join("/run/systemd/user-home-mount/", user_record_user_name_and_realm(h
));
2212 /* Prefer using a btrfs subvolume if we can, fall back to directory otherwise */
2213 r
= btrfs_subvol_make_fallback(subdir
, 0700);
2215 log_error_errno(r
, "Failed to create user directory in mounted image file: %m");
2219 root_fd
= open(subdir
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
2221 r
= log_error_errno(errno
, "Failed to open user directory in mounted image file: %m");
2225 r
= home_populate(h
, root_fd
);
2229 r
= home_sync_and_statfs(root_fd
, &sfs
);
2233 r
= user_record_clone(h
, USER_RECORD_LOAD_MASK_SECRET
|USER_RECORD_LOG
|USER_RECORD_PERMISSIVE
, &new_home
);
2235 log_error_errno(r
, "Failed to clone record: %m");
2239 r
= user_record_add_binding(
2242 disk_uuid_path
?: ip
,
2246 sym_crypt_get_cipher(cd
),
2247 sym_crypt_get_cipher_mode(cd
),
2248 luks_volume_key_size_convert(cd
),
2254 log_error_errno(r
, "Failed to add binding to record: %m");
2258 if (user_record_luks_offline_discard(h
)) {
2259 r
= run_fitrim(root_fd
);
2264 root_fd
= safe_close(root_fd
);
2266 r
= umount_verbose(LOG_ERR
, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW
);
2272 r
= sym_crypt_deactivate_by_name(cd
, dm_name
, 0);
2274 log_error_errno(r
, "Failed to deactivate LUKS device: %m");
2281 dm_activated
= false;
2283 loop
= loop_device_unref(loop
);
2285 if (!user_record_luks_offline_discard(h
)) {
2286 r
= run_fallocate(image_fd
, NULL
/* refresh stat() data */);
2291 /* Sync everything to disk before we move things into place under the final name. */
2292 if (fsync(image_fd
) < 0) {
2293 r
= log_error_errno(r
, "Failed to synchronize image to disk: %m");
2298 (void) ioctl(image_fd
, BLKRRPART
, 0);
2300 /* If we operate on a file, sync the containing directory too. */
2301 r
= fsync_directory_of_file(image_fd
);
2303 log_error_errno(r
, "Failed to synchronize directory of image file to disk: %m");
2308 /* Let's close the image fd now. If we are operating on a real block device this will release the BSD
2309 * lock that ensures udev doesn't interfere with what we are doing */
2310 image_fd
= safe_close(image_fd
);
2312 if (temporary_image_path
) {
2313 if (rename(temporary_image_path
, ip
) < 0) {
2314 log_error_errno(errno
, "Failed to rename image file: %m");
2318 log_info("Moved image file into place.");
2322 (void) wait_for_devlink(disk_uuid_path
);
2324 log_info("Everything completed.");
2326 print_size_summary(host_size
, encrypted_size
, &sfs
);
2328 *ret_home
= TAKE_PTR(new_home
);
2332 /* Let's close all files before we unmount the file system, to avoid EBUSY */
2333 root_fd
= safe_close(root_fd
);
2336 (void) umount_verbose(LOG_WARNING
, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW
);
2339 (void) sym_crypt_deactivate_by_name(cd
, dm_name
, 0);
2341 loop
= loop_device_unref(loop
);
2344 (void) unlink(temporary_image_path
);
2349 int home_get_state_luks(UserRecord
*h
, HomeSetup
*setup
) {
2350 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
2356 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
2360 r
= access(dm_node
, F_OK
);
2361 if (r
< 0 && errno
!= ENOENT
)
2362 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", dm_node
);
2364 free_and_replace(setup
->dm_name
, dm_name
);
2365 free_and_replace(setup
->dm_node
, dm_node
);
2375 static int can_resize_fs(int fd
, uint64_t old_size
, uint64_t new_size
) {
2380 /* Filter out bogus requests early */
2381 if (old_size
== 0 || old_size
== UINT64_MAX
||
2382 new_size
== 0 || new_size
== UINT64_MAX
)
2383 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid resize parameters.");
2385 if ((old_size
& 511) != 0 || (new_size
& 511) != 0)
2386 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Resize parameters not multiple of 512.");
2388 if (fstatfs(fd
, &sfs
) < 0)
2389 return log_error_errno(errno
, "Failed to fstatfs() file system: %m");
2391 if (is_fs_type(&sfs
, BTRFS_SUPER_MAGIC
)) {
2393 if (new_size
< BTRFS_MINIMAL_SIZE
)
2394 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for btrfs (needs to be 256M at least.");
2396 /* btrfs can grow and shrink online */
2398 } else if (is_fs_type(&sfs
, XFS_SB_MAGIC
)) {
2400 if (new_size
< XFS_MINIMAL_SIZE
)
2401 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for xfs (needs to be 14M at least).");
2403 /* XFS can grow, but not shrink */
2404 if (new_size
< old_size
)
2405 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE
), "Shrinking this type of file system is not supported.");
2407 } else if (is_fs_type(&sfs
, EXT4_SUPER_MAGIC
)) {
2409 if (new_size
< EXT4_MINIMAL_SIZE
)
2410 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for ext4 (needs to be 1M at least).");
2412 /* ext4 can grow online, and shrink offline */
2413 if (new_size
< old_size
)
2414 return CAN_RESIZE_OFFLINE
;
2417 return log_error_errno(SYNTHETIC_ERRNO(ESOCKTNOSUPPORT
), "Resizing this type of file system is not supported.");
2419 return CAN_RESIZE_ONLINE
;
2422 static int ext4_offline_resize_fs(HomeSetup
*setup
, uint64_t new_size
, bool discard
, unsigned long flags
) {
2423 _cleanup_free_
char *size_str
= NULL
;
2424 bool re_open
= false, re_mount
= false;
2425 pid_t resize_pid
, fsck_pid
;
2429 assert(setup
->dm_node
);
2431 /* First, unmount the file system */
2432 if (setup
->root_fd
>= 0) {
2433 setup
->root_fd
= safe_close(setup
->root_fd
);
2437 if (setup
->undo_mount
) {
2438 r
= umount_verbose(LOG_ERR
, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW
);
2442 setup
->undo_mount
= false;
2446 log_info("Temporary unmounting of file system completed.");
2448 /* resize2fs requires that the file system is force checked first, do so. */
2449 r
= safe_fork("(e2fsck)",
2450 FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_STDOUT_TO_STDERR
|FORK_CLOSE_ALL_FDS
,
2456 execlp("e2fsck" ,"e2fsck", "-fp", setup
->dm_node
, NULL
);
2458 log_error_errno(errno
, "Failed to execute e2fsck: %m");
2459 _exit(EXIT_FAILURE
);
2462 exit_status
= wait_for_terminate_and_check("e2fsck", fsck_pid
, WAIT_LOG_ABNORMAL
);
2463 if (exit_status
< 0)
2465 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != 0) {
2466 log_warning("e2fsck failed with exit status %i.", exit_status
);
2468 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
2469 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "File system is corrupted, refusing.");
2471 log_warning("Ignoring fsck error.");
2474 log_info("Forced file system check completed.");
2476 /* We use 512 sectors here, because resize2fs doesn't do byte sizes */
2477 if (asprintf(&size_str
, "%" PRIu64
"s", new_size
/ 512) < 0)
2480 /* Resize the thing */
2481 r
= safe_fork("(e2resize)",
2482 FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_WAIT
|FORK_STDOUT_TO_STDERR
|FORK_CLOSE_ALL_FDS
,
2488 execlp("resize2fs" ,"resize2fs", setup
->dm_node
, size_str
, NULL
);
2490 log_error_errno(errno
, "Failed to execute resize2fs: %m");
2491 _exit(EXIT_FAILURE
);
2494 log_info("Offline file system resize completed.");
2496 /* Re-establish mounts and reopen the directory */
2498 r
= home_mount_node(setup
->dm_node
, "ext4", discard
, flags
);
2502 setup
->undo_mount
= true;
2506 setup
->root_fd
= open("/run/systemd/user-home-mount", O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
2507 if (setup
->root_fd
< 0)
2508 return log_error_errno(errno
, "Failed to reopen file system: %m");
2511 log_info("File system mounted again.");
2516 static int prepare_resize_partition(
2518 uint64_t partition_offset
,
2519 uint64_t old_partition_size
,
2520 uint64_t new_partition_size
,
2521 sd_id128_t
*ret_disk_uuid
,
2522 struct fdisk_table
**ret_table
) {
2524 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2525 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
2526 _cleanup_free_
char *path
= NULL
, *disk_uuid_as_string
= NULL
;
2527 size_t n_partitions
;
2528 sd_id128_t disk_uuid
;
2533 assert(ret_disk_uuid
);
2536 assert((partition_offset
& 511) == 0);
2537 assert((old_partition_size
& 511) == 0);
2538 assert((new_partition_size
& 511) == 0);
2539 assert(UINT64_MAX
- old_partition_size
>= partition_offset
);
2540 assert(UINT64_MAX
- new_partition_size
>= partition_offset
);
2542 if (partition_offset
== 0) {
2543 /* If the offset is at the beginning we assume no partition table, let's exit early. */
2544 log_debug("Not rewriting partition table, operating on naked device.");
2545 *ret_disk_uuid
= SD_ID128_NULL
;
2550 c
= fdisk_new_context();
2554 if (asprintf(&path
, "/proc/self/fd/%i", fd
) < 0)
2557 r
= fdisk_assign_device(c
, path
, 0);
2559 return log_error_errno(r
, "Failed to open device: %m");
2561 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2562 return log_error_errno(SYNTHETIC_ERRNO(ENOMEDIUM
), "Disk has no GPT partition table.");
2564 r
= fdisk_get_disklabel_id(c
, &disk_uuid_as_string
);
2566 return log_error_errno(r
, "Failed to acquire disk UUID: %m");
2568 r
= sd_id128_from_string(disk_uuid_as_string
, &disk_uuid
);
2570 return log_error_errno(r
, "Failed parse disk UUID: %m");
2572 r
= fdisk_get_partitions(c
, &t
);
2574 return log_error_errno(r
, "Failed to acquire partition table: %m");
2576 n_partitions
= fdisk_table_get_nents(t
);
2577 for (size_t i
= 0; i
< n_partitions
; i
++) {
2578 struct fdisk_partition
*p
;
2580 p
= fdisk_table_get_partition(t
, i
);
2582 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
2584 if (fdisk_partition_is_used(p
) <= 0)
2586 if (fdisk_partition_has_start(p
) <= 0 || fdisk_partition_has_size(p
) <= 0 || fdisk_partition_has_end(p
) <= 0)
2587 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found partition without a size.");
2589 if (fdisk_partition_get_start(p
) == partition_offset
/ 512U &&
2590 fdisk_partition_get_size(p
) == old_partition_size
/ 512U) {
2593 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
), "Partition found twice, refusing.");
2595 /* Found our partition, now patch it */
2596 r
= fdisk_partition_size_explicit(p
, 1);
2598 return log_error_errno(r
, "Failed to enable explicit partition size: %m");
2600 r
= fdisk_partition_set_size(p
, new_partition_size
/ 512U);
2602 return log_error_errno(r
, "Failed to change partition size: %m");
2608 if (fdisk_partition_get_start(p
) < partition_offset
+ new_partition_size
/ 512U &&
2609 fdisk_partition_get_end(p
) >= partition_offset
/ 512)
2610 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Can't extend, conflicting partition found.");
2615 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to find matching partition to resize.");
2617 *ret_table
= TAKE_PTR(t
);
2618 *ret_disk_uuid
= disk_uuid
;
2623 static int ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *userdata
) {
2628 switch (fdisk_ask_get_type(ask
)) {
2630 case FDISK_ASKTYPE_STRING
:
2631 result
= new(char, 37);
2635 fdisk_ask_string_set_result(ask
, id128_to_uuid_string(*(sd_id128_t
*) userdata
, result
));
2639 log_debug("Unexpected question from libfdisk, ignoring.");
2645 static int apply_resize_partition(int fd
, sd_id128_t disk_uuids
, struct fdisk_table
*t
) {
2646 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2647 _cleanup_free_
void *two_zero_lbas
= NULL
;
2648 _cleanup_free_
char *path
= NULL
;
2654 if (!t
) /* no partition table to apply, exit early */
2657 two_zero_lbas
= malloc0(1024U);
2661 /* libfdisk appears to get confused by the existing PMBR. Let's explicitly flush it out. */
2662 n
= pwrite(fd
, two_zero_lbas
, 1024U, 0);
2664 return log_error_errno(errno
, "Failed to wipe partition table: %m");
2666 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Short write while wiping partition table.");
2668 c
= fdisk_new_context();
2672 if (asprintf(&path
, "/proc/self/fd/%i", fd
) < 0)
2675 r
= fdisk_assign_device(c
, path
, 0);
2677 return log_error_errno(r
, "Failed to open device: %m");
2679 r
= fdisk_create_disklabel(c
, "gpt");
2681 return log_error_errno(r
, "Failed to create GPT disk label: %m");
2683 r
= fdisk_apply_table(c
, t
);
2685 return log_error_errno(r
, "Failed to apply partition table: %m");
2687 r
= fdisk_set_ask(c
, ask_cb
, &disk_uuids
);
2689 return log_error_errno(r
, "Failed to set libfdisk query function: %m");
2691 r
= fdisk_set_disklabel_id(c
);
2693 return log_error_errno(r
, "Failed to change disklabel ID: %m");
2695 r
= fdisk_write_disklabel(c
);
2697 return log_error_errno(r
, "Failed to write disk label: %m");
2702 int home_resize_luks(
2704 bool already_activated
,
2705 PasswordCache
*cache
,
2707 UserRecord
**ret_home
) {
2709 uint64_t old_image_size
, new_image_size
, old_fs_size
, new_fs_size
, crypto_offset
, new_partition_size
;
2710 _cleanup_(user_record_unrefp
) UserRecord
*header_home
= NULL
, *embedded_home
= NULL
, *new_home
= NULL
;
2711 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*table
= NULL
;
2712 _cleanup_free_
char *whole_disk
= NULL
;
2713 _cleanup_close_
int image_fd
= -1;
2714 sd_id128_t disk_uuid
;
2715 const char *ip
, *ipo
;
2721 assert(user_record_storage(h
) == USER_LUKS
);
2725 r
= dlopen_cryptsetup();
2729 assert_se(ipo
= user_record_image_path(h
));
2730 ip
= strdupa_safe(ipo
); /* copy out since original might change later in home record object */
2732 image_fd
= open(ip
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
2734 return log_error_errno(errno
, "Failed to open image file %s: %m", ip
);
2736 if (fstat(image_fd
, &st
) < 0)
2737 return log_error_errno(errno
, "Failed to stat image file %s: %m", ip
);
2738 if (S_ISBLK(st
.st_mode
)) {
2741 r
= block_get_whole_disk(st
.st_rdev
, &parent
);
2743 return log_error_errno(r
, "Failed to acquire whole block device for %s: %m", ip
);
2745 /* If we shall resize a file system on a partition device, then let's figure out the
2746 * whole disk device and operate on that instead, since we need to rewrite the
2747 * partition table to resize the partition. */
2749 log_info("Operating on partition device %s, using parent device.", ip
);
2751 r
= device_path_make_major_minor(st
.st_mode
, parent
, &whole_disk
);
2753 return log_error_errno(r
, "Failed to derive whole disk path for %s: %m", ip
);
2755 safe_close(image_fd
);
2757 image_fd
= open(whole_disk
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
2759 return log_error_errno(errno
, "Failed to open whole block device %s: %m", whole_disk
);
2761 if (fstat(image_fd
, &st
) < 0)
2762 return log_error_errno(errno
, "Failed to stat whole block device %s: %m", whole_disk
);
2763 if (!S_ISBLK(st
.st_mode
))
2764 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Whole block device %s is not actually a block device, refusing.", whole_disk
);
2766 log_info("Operating on whole block device %s.", ip
);
2768 if (ioctl(image_fd
, BLKGETSIZE64
, &old_image_size
) < 0)
2769 return log_error_errno(errno
, "Failed to determine size of original block device: %m");
2771 if (flock(image_fd
, LOCK_EX
) < 0) /* make sure udev doesn't read from it while we operate on the device */
2772 return log_error_errno(errno
, "Failed to lock block device %s: %m", ip
);
2774 new_image_size
= old_image_size
; /* we can't resize physical block devices */
2776 uint64_t new_image_size_rounded
;
2778 r
= stat_verify_regular(&st
);
2780 return log_error_errno(r
, "Image %s is not a block device nor regular file: %m", ip
);
2782 old_image_size
= st
.st_size
;
2784 /* Note an asymetry here: when we operate on loopback files the specified disk size we get we
2785 * apply onto the loopback file as a whole. When we operate on block devices we instead apply
2786 * to the partition itself only. */
2788 new_image_size_rounded
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
2790 if (old_image_size
== h
->disk_size
||
2791 old_image_size
== new_image_size_rounded
) {
2792 /* If exact match, or a match after we rounded down, don't do a thing */
2793 log_info("Image size already matching, skipping operation.");
2797 new_image_size
= new_image_size_rounded
;
2800 r
= home_prepare_luks(h
, already_activated
, whole_disk
, cache
, setup
, &header_home
);
2804 r
= home_load_embedded_identity(h
, setup
->root_fd
, header_home
, USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL
, cache
, &embedded_home
, &new_home
);
2808 log_info("offset = %" PRIu64
", size = %" PRIu64
", image = %" PRIu64
, setup
->partition_offset
, setup
->partition_size
, old_image_size
);
2810 if ((UINT64_MAX
- setup
->partition_offset
) < setup
->partition_size
||
2811 setup
->partition_offset
+ setup
->partition_size
> old_image_size
)
2812 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Old partition doesn't fit in backing storage, refusing.");
2814 if (S_ISREG(st
.st_mode
)) {
2815 uint64_t partition_table_extra
;
2817 partition_table_extra
= old_image_size
- setup
->partition_size
;
2818 if (new_image_size
<= partition_table_extra
)
2819 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "New size smaller than partition table metadata.");
2821 new_partition_size
= DISK_SIZE_ROUND_DOWN(new_image_size
- partition_table_extra
);
2823 uint64_t new_partition_size_rounded
;
2825 assert(S_ISBLK(st
.st_mode
));
2827 new_partition_size_rounded
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
2829 if (h
->disk_size
== setup
->partition_size
||
2830 new_partition_size_rounded
== setup
->partition_size
) {
2831 log_info("Partition size already matching, skipping operation.");
2835 new_partition_size
= new_partition_size_rounded
;
2838 if ((UINT64_MAX
- setup
->partition_offset
) < new_partition_size
||
2839 setup
->partition_offset
+ new_partition_size
> new_image_size
)
2840 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "New partition doesn't fit into backing storage, refusing.");
2842 crypto_offset
= sym_crypt_get_data_offset(setup
->crypt_device
);
2843 if (setup
->partition_size
/ 512U <= crypto_offset
)
2844 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Weird, old crypto payload offset doesn't actually fit in partition size?");
2845 if (new_partition_size
/ 512U <= crypto_offset
)
2846 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "New size smaller than crypto payload offset?");
2848 old_fs_size
= (setup
->partition_size
/ 512U - crypto_offset
) * 512U;
2849 new_fs_size
= DISK_SIZE_ROUND_DOWN((new_partition_size
/ 512U - crypto_offset
) * 512U);
2851 /* Before we start doing anything, let's figure out if we actually can */
2852 resize_type
= can_resize_fs(setup
->root_fd
, old_fs_size
, new_fs_size
);
2853 if (resize_type
< 0)
2855 if (resize_type
== CAN_RESIZE_OFFLINE
&& already_activated
)
2856 return log_error_errno(SYNTHETIC_ERRNO(ETXTBSY
), "File systems of this type can only be resized offline, but is currently online.");
2858 log_info("Ready to resize image size %s → %s, partition size %s → %s, file system size %s → %s.",
2859 FORMAT_BYTES(old_image_size
),
2860 FORMAT_BYTES(new_image_size
),
2861 FORMAT_BYTES(setup
->partition_size
),
2862 FORMAT_BYTES(new_partition_size
),
2863 FORMAT_BYTES(old_fs_size
),
2864 FORMAT_BYTES(new_fs_size
));
2866 r
= prepare_resize_partition(
2868 setup
->partition_offset
,
2869 setup
->partition_size
,
2876 if (new_fs_size
> old_fs_size
) {
2878 if (S_ISREG(st
.st_mode
)) {
2879 /* Grow file size */
2880 r
= home_truncate(h
, image_fd
, ip
, new_image_size
);
2884 log_info("Growing of image file completed.");
2887 /* Make sure loopback device sees the new bigger size */
2888 r
= loop_device_refresh_size(setup
->loop
, UINT64_MAX
, new_partition_size
);
2890 log_debug_errno(r
, "Device is not a loopback device, not refreshing size.");
2892 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
2894 log_info("Refreshing loop device size completed.");
2896 r
= apply_resize_partition(image_fd
, disk_uuid
, table
);
2900 log_info("Growing of partition completed.");
2902 if (S_ISBLK(st
.st_mode
) && ioctl(image_fd
, BLKRRPART
, 0) < 0)
2903 log_debug_errno(errno
, "BLKRRPART failed on block device, ignoring: %m");
2905 /* Tell LUKS about the new bigger size too */
2906 r
= sym_crypt_resize(setup
->crypt_device
, setup
->dm_name
, new_fs_size
/ 512U);
2908 return log_error_errno(r
, "Failed to grow LUKS device: %m");
2910 log_info("LUKS device growing completed.");
2912 r
= home_store_embedded_identity(new_home
, setup
->root_fd
, h
->uid
, embedded_home
);
2916 if (S_ISREG(st
.st_mode
)) {
2917 if (user_record_luks_discard(h
))
2918 /* Before we shrink, let's trim the file system, so that we need less space on disk during the shrinking */
2919 (void) run_fitrim(setup
->root_fd
);
2921 /* If discard is off, let's ensure all backing blocks are allocated, so that our resize operation doesn't fail half-way */
2922 r
= run_fallocate(image_fd
, &st
);
2929 /* Now resize the file system */
2930 if (resize_type
== CAN_RESIZE_ONLINE
) {
2931 r
= resize_fs(setup
->root_fd
, new_fs_size
, NULL
);
2933 return log_error_errno(r
, "Failed to resize file system: %m");
2935 r
= ext4_offline_resize_fs(setup
, new_fs_size
, user_record_luks_discard(h
), user_record_mount_flags(h
));
2940 log_info("File system resizing completed.");
2942 /* Immediately sync afterwards */
2943 r
= home_sync_and_statfs(setup
->root_fd
, NULL
);
2947 if (new_fs_size
< old_fs_size
) {
2949 /* Shrink the LUKS device now, matching the new file system size */
2950 r
= sym_crypt_resize(setup
->crypt_device
, setup
->dm_name
, new_fs_size
/ 512);
2952 return log_error_errno(r
, "Failed to shrink LUKS device: %m");
2954 log_info("LUKS device shrinking completed.");
2956 if (S_ISREG(st
.st_mode
)) {
2957 /* Shrink the image file */
2958 if (ftruncate(image_fd
, new_image_size
) < 0)
2959 return log_error_errno(errno
, "Failed to shrink image file %s: %m", ip
);
2961 log_info("Shrinking of image file completed.");
2964 /* Refresh the loop devices size */
2965 r
= loop_device_refresh_size(setup
->loop
, UINT64_MAX
, new_partition_size
);
2967 log_debug_errno(r
, "Device is not a loopback device, not refreshing size.");
2969 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
2971 log_info("Refreshing loop device size completed.");
2973 r
= apply_resize_partition(image_fd
, disk_uuid
, table
);
2977 log_info("Shrinking of partition completed.");
2979 if (S_ISBLK(st
.st_mode
) && ioctl(image_fd
, BLKRRPART
, 0) < 0)
2980 log_debug_errno(errno
, "BLKRRPART failed on block device, ignoring: %m");
2982 r
= home_store_embedded_identity(new_home
, setup
->root_fd
, h
->uid
, embedded_home
);
2987 r
= home_store_header_identity_luks(new_home
, setup
, header_home
);
2991 r
= home_extend_embedded_identity(new_home
, h
, setup
);
2995 if (user_record_luks_discard(h
))
2996 (void) run_fitrim(setup
->root_fd
);
2998 r
= home_sync_and_statfs(setup
->root_fd
, &sfs
);
3002 r
= home_setup_undo(setup
);
3006 log_info("Everything completed.");
3008 print_size_summary(new_image_size
, new_fs_size
, &sfs
);
3010 *ret_home
= TAKE_PTR(new_home
);
3014 int home_passwd_luks(
3017 PasswordCache
*cache
, /* the passwords acquired via PKCS#11/FIDO2 security tokens */
3018 char **effective_passwords
/* new passwords */) {
3020 size_t volume_key_size
, max_key_slots
, n_effective
;
3021 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
3022 struct crypt_pbkdf_type good_pbkdf
, minimal_pbkdf
;
3028 assert(user_record_storage(h
) == USER_LUKS
);
3031 r
= dlopen_cryptsetup();
3035 type
= sym_crypt_get_type(setup
->crypt_device
);
3037 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine crypto device type.");
3039 r
= sym_crypt_keyslot_max(type
);
3041 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine number of key slots.");
3044 r
= sym_crypt_get_volume_key_size(setup
->crypt_device
);
3046 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine volume key size.");
3047 volume_key_size
= (size_t) r
;
3049 volume_key
= malloc(volume_key_size
);
3054 FOREACH_POINTER(list
, cache
->pkcs11_passwords
, cache
->fido2_passwords
, h
->password
) {
3055 r
= luks_try_passwords(setup
->crypt_device
, list
, volume_key
, &volume_key_size
);
3060 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY
), "Failed to unlock LUKS superblock with supplied passwords.");
3062 return log_error_errno(r
, "Failed to unlocks LUKS superblock: %m");
3064 n_effective
= strv_length(effective_passwords
);
3066 build_good_pbkdf(&good_pbkdf
, h
);
3067 build_minimal_pbkdf(&minimal_pbkdf
, h
);
3069 for (size_t i
= 0; i
< max_key_slots
; i
++) {
3070 r
= sym_crypt_keyslot_destroy(setup
->crypt_device
, i
);
3071 if (r
< 0 && !IN_SET(r
, -ENOENT
, -EINVAL
)) /* Returns EINVAL or ENOENT if there's no key in this slot already */
3072 return log_error_errno(r
, "Failed to destroy LUKS password: %m");
3074 if (i
>= n_effective
) {
3076 log_info("Destroyed LUKS key slot %zu.", i
);
3080 if (strv_contains(cache
->pkcs11_passwords
, effective_passwords
[i
]) ||
3081 strv_contains(cache
->fido2_passwords
, effective_passwords
[i
])) {
3082 log_debug("Using minimal PBKDF for slot %zu", i
);
3083 r
= sym_crypt_set_pbkdf_type(setup
->crypt_device
, &minimal_pbkdf
);
3085 log_debug("Using good PBKDF for slot %zu", i
);
3086 r
= sym_crypt_set_pbkdf_type(setup
->crypt_device
, &good_pbkdf
);
3089 return log_error_errno(r
, "Failed to tweak PBKDF for slot %zu: %m", i
);
3091 r
= sym_crypt_keyslot_add_by_volume_key(
3092 setup
->crypt_device
,
3096 effective_passwords
[i
],
3097 strlen(effective_passwords
[i
]));
3099 return log_error_errno(r
, "Failed to set up LUKS password: %m");
3101 log_info("Updated LUKS key slot %zu.", i
);
3107 int home_lock_luks(UserRecord
*h
) {
3108 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
3109 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
3110 _cleanup_close_
int root_fd
= -1;
3116 assert_se(p
= user_record_home_directory(h
));
3117 root_fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
3119 return log_error_errno(errno
, "Failed to open home directory: %m");
3121 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
3125 r
= dlopen_cryptsetup();
3129 r
= sym_crypt_init_by_name(&cd
, dm_name
);
3131 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
3133 log_info("Discovered used LUKS device %s.", dm_node
);
3134 cryptsetup_enable_logging(cd
);
3136 if (syncfs(root_fd
) < 0) /* Snake oil, but let's better be safe than sorry */
3137 return log_error_errno(errno
, "Failed to synchronize file system %s: %m", p
);
3139 root_fd
= safe_close(root_fd
);
3141 log_info("File system synchronized.");
3143 /* Note that we don't invoke FIFREEZE here, it appears libcryptsetup/device-mapper already does that on its own for us */
3145 r
= sym_crypt_suspend(cd
, dm_name
);
3147 return log_error_errno(r
, "Failed to suspend cryptsetup device: %s: %m", dm_node
);
3149 log_info("LUKS device suspended.");
3153 static int luks_try_resume(
3154 struct crypt_device
*cd
,
3155 const char *dm_name
,
3164 STRV_FOREACH(pp
, password
) {
3165 r
= sym_crypt_resume_by_passphrase(
3172 log_info("Resumed LUKS device %s.", dm_name
);
3176 log_debug_errno(r
, "Password %zu didn't work for resuming device: %m", (size_t) (pp
- password
));
3182 int home_unlock_luks(UserRecord
*h
, PasswordCache
*cache
) {
3183 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
3184 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
3190 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
3194 r
= dlopen_cryptsetup();
3198 r
= sym_crypt_init_by_name(&cd
, dm_name
);
3200 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
3202 log_info("Discovered used LUKS device %s.", dm_node
);
3203 cryptsetup_enable_logging(cd
);
3206 FOREACH_POINTER(list
, cache
->pkcs11_passwords
, cache
->fido2_passwords
, h
->password
) {
3207 r
= luks_try_resume(cd
, dm_name
, list
);
3212 return log_error_errno(r
, "No valid password for LUKS superblock.");
3214 return log_error_errno(r
, "Failed to resume LUKS superblock: %m");
3216 log_info("LUKS device resumed.");