1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <linux/loop.h>
9 #if HAVE_VALGRIND_MEMCHECK_H
10 #include <valgrind/memcheck.h>
13 #include "sd-daemon.h"
14 #include "sd-device.h"
18 #include "blkid-util.h"
19 #include "blockdev-util.h"
20 #include "btrfs-util.h"
21 #include "chattr-util.h"
22 #include "device-util.h"
23 #include "devnum-util.h"
26 #include "errno-util.h"
28 #include "fdisk-util.h"
30 #include "filesystems.h"
32 #include "fsck-util.h"
33 #include "glyph-util.h"
35 #include "home-util.h"
36 #include "homework-luks.h"
37 #include "homework-mount.h"
39 #include "keyring-util.h"
40 #include "memory-util.h"
41 #include "missing_magic.h"
43 #include "mkfs-util.h"
44 #include "mount-util.h"
45 #include "openssl-util.h"
46 #include "parse-util.h"
47 #include "path-util.h"
48 #include "process-util.h"
49 #include "random-util.h"
50 #include "resize-fs.h"
52 #include "sync-util.h"
53 #include "tmpfile-util.h"
54 #include "udev-util.h"
55 #include "user-util.h"
57 /* Round down to the nearest 4K size. Given that newer hardware generally prefers 4K sectors, let's align our
58 * partitions to that too. In the worst case we'll waste 3.5K per partition that way, but I think I can live
60 #define DISK_SIZE_ROUND_DOWN(x) ((x) & ~UINT64_C(4095))
62 /* Rounds up to the nearest 4K boundary. Returns UINT64_MAX on overflow */
63 #define DISK_SIZE_ROUND_UP(x) \
66 _x > UINT64_MAX - 4095U ? UINT64_MAX : (_x + 4095U) & ~UINT64_C(4095); \
69 /* How much larger will the image on disk be than the fs inside it, i.e. the space we pay for the GPT and
70 * LUKS2 envelope. (As measured on cryptsetup 2.4.1) */
71 #define GPT_LUKS2_OVERHEAD UINT64_C(18874368)
73 static int resize_image_loop(UserRecord
*h
, HomeSetup
*setup
, uint64_t old_image_size
, uint64_t new_image_size
, uint64_t *ret_image_size
);
75 int run_mark_dirty(int fd
, bool b
) {
79 /* Sets or removes the 'user.home-dirty' xattr on the specified file. We use this to detect when a
80 * home directory was not properly unmounted. */
84 r
= fd_verify_regular(fd
);
89 ret
= fsetxattr(fd
, "user.home-dirty", &x
, 1, XATTR_CREATE
);
90 if (ret
< 0 && errno
!= EEXIST
)
91 return log_debug_errno(errno
, "Could not mark home directory as dirty: %m");
96 return log_debug_errno(r
, "Failed to synchronize image before marking it clean: %m");
98 ret
= fremovexattr(fd
, "user.home-dirty");
99 if (ret
< 0 && !ERRNO_IS_XATTR_ABSENT(errno
))
100 return log_debug_errno(errno
, "Could not mark home directory as clean: %m");
105 return log_debug_errno(r
, "Failed to synchronize dirty flag to disk: %m");
110 int run_mark_dirty_by_path(const char *path
, bool b
) {
111 _cleanup_close_
int fd
= -EBADF
;
115 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
);
117 return log_debug_errno(errno
, "Failed to open %s to mark dirty or clean: %m", path
);
119 return run_mark_dirty(fd
, b
);
122 static int probe_file_system_by_fd(
125 sd_id128_t
*ret_uuid
) {
127 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
128 _cleanup_free_
char *s
= NULL
;
129 const char *fstype
= NULL
, *uuid
= NULL
;
137 b
= blkid_new_probe();
142 r
= blkid_probe_set_device(b
, fd
, 0, 0);
144 return errno_or_else(ENOMEM
);
146 (void) blkid_probe_enable_superblocks(b
, 1);
147 (void) blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_UUID
);
150 r
= blkid_do_safeprobe(b
);
151 if (r
== _BLKID_SAFEPROBE_ERROR
)
152 return errno_or_else(EIO
);
153 if (IN_SET(r
, _BLKID_SAFEPROBE_AMBIGUOUS
, _BLKID_SAFEPROBE_NOT_FOUND
))
156 assert(r
== _BLKID_SAFEPROBE_FOUND
);
158 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
162 (void) blkid_probe_lookup_value(b
, "UUID", &uuid
, NULL
);
166 r
= sd_id128_from_string(uuid
, &id
);
174 *ret_fstype
= TAKE_PTR(s
);
180 static int probe_file_system_by_path(const char *path
, char **ret_fstype
, sd_id128_t
*ret_uuid
) {
181 _cleanup_close_
int fd
= -EBADF
;
183 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
185 return negative_errno();
187 return probe_file_system_by_fd(fd
, ret_fstype
, ret_uuid
);
190 static int block_get_size_by_fd(int fd
, uint64_t *ret
) {
196 if (fstat(fd
, &st
) < 0)
199 if (!S_ISBLK(st
.st_mode
))
202 return RET_NERRNO(ioctl(fd
, BLKGETSIZE64
, ret
));
205 static int block_get_size_by_path(const char *path
, uint64_t *ret
) {
206 _cleanup_close_
int fd
= -EBADF
;
208 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
212 return block_get_size_by_fd(fd
, ret
);
215 static int run_fsck(const char *node
, const char *fstype
) {
222 r
= fsck_exists_for_fstype(fstype
);
224 return log_error_errno(r
, "Failed to check if fsck for file system %s exists: %m", fstype
);
226 log_warning("No fsck for file system %s installed, ignoring.", fstype
);
230 r
= safe_fork("(fsck)",
231 FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_STDOUT_TO_STDERR
|FORK_CLOSE_ALL_FDS
,
237 execlp("fsck", "fsck", "-aTl", node
, NULL
);
239 log_error_errno(errno
, "Failed to execute fsck: %m");
240 _exit(FSCK_OPERATIONAL_ERROR
);
243 exit_status
= wait_for_terminate_and_check("fsck", fsck_pid
, WAIT_LOG_ABNORMAL
);
246 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != 0) {
247 log_warning("fsck failed with exit status %i.", exit_status
);
249 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
250 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "File system is corrupted, refusing.");
252 log_warning("Ignoring fsck error.");
255 log_info("File system check completed.");
260 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(key_serial_t
, keyring_unlink
, -1);
262 static int upload_to_keyring(
264 const char *password
,
265 key_serial_t
*ret_key_serial
) {
267 _cleanup_free_
char *name
= NULL
;
273 /* If auto-shrink-on-logout is turned on, we need to keep the key we used to unlock the LUKS volume
274 * around, since we'll need it when automatically resizing (since we can't ask the user there
275 * again). We do this by uploading it into the kernel keyring, specifically the "session" one. This
276 * is done under the assumption systemd-homed gets its private per-session keyring (i.e. default
277 * service behaviour, given that KeyringMode=private is the default). It will survive between our
278 * systemd-homework invocations that way.
280 * If auto-shrink-on-logout is disabled we'll skip this step, to be frugal with sensitive data. */
282 if (user_record_auto_resize_mode(h
) != AUTO_RESIZE_SHRINK_AND_GROW
) { /* Won't need it */
284 *ret_key_serial
= -1;
288 name
= strjoin("homework-user-", h
->user_name
);
292 serial
= add_key("user", name
, password
, strlen(password
), KEY_SPEC_SESSION_KEYRING
);
297 *ret_key_serial
= serial
;
302 static int luks_try_passwords(
304 struct crypt_device
*cd
,
307 size_t *volume_key_size
,
308 key_serial_t
*ret_key_serial
) {
315 STRV_FOREACH(pp
, passwords
) {
316 size_t vks
= *volume_key_size
;
318 r
= sym_crypt_volume_key_get(
326 if (ret_key_serial
) {
327 /* If ret_key_serial is non-NULL, let's try to upload the password that
328 * worked, and return its serial. */
329 r
= upload_to_keyring(h
, *pp
, ret_key_serial
);
331 log_debug_errno(r
, "Failed to upload LUKS password to kernel keyring, ignoring: %m");
332 *ret_key_serial
= -1;
336 *volume_key_size
= vks
;
340 log_debug_errno(r
, "Password %zu didn't work for unlocking LUKS superblock: %m", (size_t) (pp
- passwords
));
346 static int luks_setup(
352 const char *cipher_mode
,
353 uint64_t volume_key_size
,
355 const PasswordCache
*cache
,
357 struct crypt_device
**ret
,
358 sd_id128_t
*ret_found_uuid
,
359 void **ret_volume_key
,
360 size_t *ret_volume_key_size
,
361 key_serial_t
*ret_key_serial
) {
363 _cleanup_(keyring_unlinkp
) key_serial_t key_serial
= -1;
364 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
365 _cleanup_(erase_and_freep
) void *vk
= NULL
;
376 r
= sym_crypt_init(&cd
, node
);
378 return log_error_errno(r
, "Failed to allocate libcryptsetup context: %m");
380 cryptsetup_enable_logging(cd
);
382 r
= sym_crypt_load(cd
, CRYPT_LUKS2
, NULL
);
384 return log_error_errno(r
, "Failed to load LUKS superblock: %m");
386 r
= sym_crypt_get_volume_key_size(cd
);
388 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine LUKS volume key size");
391 if (!sd_id128_is_null(uuid
) || ret_found_uuid
) {
394 s
= sym_crypt_get_uuid(cd
);
396 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has no UUID.");
398 r
= sd_id128_from_string(s
, &p
);
400 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has invalid UUID.");
402 /* Check that the UUID matches, if specified */
403 if (!sd_id128_is_null(uuid
) &&
404 !sd_id128_equal(uuid
, p
))
405 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has wrong UUID.");
408 if (cipher
&& !streq_ptr(cipher
, sym_crypt_get_cipher(cd
)))
409 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong cipher.");
411 if (cipher_mode
&& !streq_ptr(cipher_mode
, sym_crypt_get_cipher_mode(cd
)))
412 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong cipher mode.");
414 if (volume_key_size
!= UINT64_MAX
&& vks
!= volume_key_size
)
415 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong volume key size.");
422 FOREACH_POINTER(list
,
423 cache
? cache
->keyring_passswords
: NULL
,
424 cache
? cache
->pkcs11_passwords
: NULL
,
425 cache
? cache
->fido2_passwords
: NULL
,
427 r
= luks_try_passwords(h
, cd
, list
, vk
, &vks
, ret_key_serial
? &key_serial
: NULL
);
432 return log_error_errno(r
, "No valid password for LUKS superblock.");
434 return log_error_errno(r
, "Failed to unlock LUKS superblock: %m");
436 r
= sym_crypt_activate_by_volume_key(
440 discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
442 return log_error_errno(r
, "Failed to unlock LUKS superblock: %m");
444 log_info("Setting up LUKS device /dev/mapper/%s completed.", dm_name
);
448 if (ret_found_uuid
) /* Return the UUID actually found if the caller wants to know */
451 *ret_volume_key
= TAKE_PTR(vk
);
452 if (ret_volume_key_size
)
453 *ret_volume_key_size
= vks
;
455 *ret_key_serial
= TAKE_KEY_SERIAL(key_serial
);
460 static int make_dm_names(UserRecord
*h
, HomeSetup
*setup
) {
462 assert(h
->user_name
);
465 if (!setup
->dm_name
) {
466 setup
->dm_name
= strjoin("home-", h
->user_name
);
471 if (!setup
->dm_node
) {
472 setup
->dm_node
= path_join("/dev/mapper/", setup
->dm_name
);
480 static int acquire_open_luks_device(
485 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
490 assert(!setup
->crypt_device
);
492 r
= dlopen_cryptsetup();
496 r
= make_dm_names(h
, setup
);
500 r
= sym_crypt_init_by_name(&cd
, setup
->dm_name
);
501 if ((ERRNO_IS_NEG_DEVICE_ABSENT(r
) || r
== -EINVAL
) && graceful
)
504 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", setup
->dm_name
);
506 cryptsetup_enable_logging(cd
);
508 setup
->crypt_device
= TAKE_PTR(cd
);
512 static int luks_open(
515 const PasswordCache
*cache
,
516 sd_id128_t
*ret_found_uuid
,
517 void **ret_volume_key
,
518 size_t *ret_volume_key_size
) {
520 _cleanup_(erase_and_freep
) void *vk
= NULL
;
528 assert(!setup
->crypt_device
);
530 /* Opens a LUKS device that is already set up. Re-validates the password while doing so (which also
531 * provides us with the volume key, which we want). */
533 r
= acquire_open_luks_device(h
, setup
, /* graceful= */ false);
537 r
= sym_crypt_load(setup
->crypt_device
, CRYPT_LUKS2
, NULL
);
539 return log_error_errno(r
, "Failed to load LUKS superblock: %m");
541 r
= sym_crypt_get_volume_key_size(setup
->crypt_device
);
543 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine LUKS volume key size");
546 if (ret_found_uuid
) {
549 s
= sym_crypt_get_uuid(setup
->crypt_device
);
551 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has no UUID.");
553 r
= sd_id128_from_string(s
, &p
);
555 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has invalid UUID.");
563 FOREACH_POINTER(list
,
564 cache
? cache
->keyring_passswords
: NULL
,
565 cache
? cache
->pkcs11_passwords
: NULL
,
566 cache
? cache
->fido2_passwords
: NULL
,
568 r
= luks_try_passwords(h
, setup
->crypt_device
, list
, vk
, &vks
, NULL
);
573 return log_error_errno(r
, "No valid password for LUKS superblock.");
575 return log_error_errno(r
, "Failed to unlock LUKS superblock: %m");
577 log_info("Discovered used LUKS device /dev/mapper/%s, and validated password.", setup
->dm_name
);
579 /* This is needed so that crypt_resize() can operate correctly for pre-existing LUKS devices. We need
580 * to tell libcryptsetup the volume key explicitly, so that it is in the kernel keyring. */
581 r
= sym_crypt_activate_by_volume_key(setup
->crypt_device
, NULL
, vk
, vks
, CRYPT_ACTIVATE_KEYRING_KEY
);
583 return log_error_errno(r
, "Failed to upload volume key again: %m");
585 log_info("Successfully re-activated LUKS device.");
590 *ret_volume_key
= TAKE_PTR(vk
);
591 if (ret_volume_key_size
)
592 *ret_volume_key_size
= vks
;
597 static int fs_validate(
601 sd_id128_t
*ret_found_uuid
) {
603 _cleanup_free_
char *fstype
= NULL
;
604 sd_id128_t u
= SD_ID128_NULL
; /* avoid false maybe-unitialized warning */
610 r
= probe_file_system_by_path(dm_node
, &fstype
, &u
);
612 return log_error_errno(r
, "Failed to probe file system: %m");
614 /* Limit the set of supported file systems a bit, as protection against little tested kernel file
615 * systems. Also, we only support the resize ioctls for these file systems. */
616 if (!supported_fstype(fstype
))
617 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "Image contains unsupported file system: %s", strna(fstype
));
619 if (!sd_id128_is_null(uuid
) &&
620 !sd_id128_equal(uuid
, u
))
621 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "File system has wrong UUID.");
623 log_info("Probing file system completed (found %s).", fstype
);
625 *ret_fstype
= TAKE_PTR(fstype
);
627 if (ret_found_uuid
) /* Return the UUID actually found if the caller wants to know */
633 static int luks_validate(
636 sd_id128_t partition_uuid
,
637 sd_id128_t
*ret_partition_uuid
,
638 uint64_t *ret_offset
,
639 uint64_t *ret_size
) {
641 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
642 sd_id128_t found_partition_uuid
= SD_ID128_NULL
;
643 const char *fstype
= NULL
, *pttype
= NULL
;
644 blkid_loff_t offset
= 0, size
= 0;
654 b
= blkid_new_probe();
659 r
= blkid_probe_set_device(b
, fd
, 0, 0);
661 return errno_or_else(ENOMEM
);
663 (void) blkid_probe_enable_superblocks(b
, 1);
664 (void) blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
665 (void) blkid_probe_enable_partitions(b
, 1);
666 (void) blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
669 r
= blkid_do_safeprobe(b
);
670 if (r
== _BLKID_SAFEPROBE_ERROR
)
671 return errno_or_else(EIO
);
672 if (IN_SET(r
, _BLKID_SAFEPROBE_AMBIGUOUS
, _BLKID_SAFEPROBE_NOT_FOUND
))
675 assert(r
== _BLKID_SAFEPROBE_FOUND
);
677 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
678 if (streq_ptr(fstype
, "crypto_LUKS")) {
679 /* Directly a LUKS image */
681 *ret_size
= UINT64_MAX
; /* full disk */
682 *ret_partition_uuid
= SD_ID128_NULL
;
687 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
688 if (!streq_ptr(pttype
, "gpt"))
692 pl
= blkid_probe_get_partitions(b
);
694 return errno_or_else(ENOMEM
);
697 n
= blkid_partlist_numof_partitions(pl
);
699 return errno_or_else(EIO
);
701 for (int i
= 0; i
< n
; i
++) {
702 sd_id128_t id
= SD_ID128_NULL
;
706 pp
= blkid_partlist_get_partition(pl
, i
);
708 return errno_or_else(EIO
);
710 if (sd_id128_string_equal(blkid_partition_get_type_string(pp
), SD_GPT_USER_HOME
) <= 0)
713 if (!streq_ptr(blkid_partition_get_name(pp
), label
))
717 r
= blkid_partition_get_uuid_id128(pp
, &id
);
719 log_debug_errno(r
, "Failed to read partition UUID, ignoring: %m");
720 else if (!sd_id128_is_null(partition_uuid
) && !sd_id128_equal(id
, partition_uuid
))
726 offset
= blkid_partition_get_start(pp
);
727 size
= blkid_partition_get_size(pp
);
728 found_partition_uuid
= id
;
738 if ((uint64_t) offset
> UINT64_MAX
/ 512U)
742 if ((uint64_t) size
> UINT64_MAX
/ 512U)
745 *ret_offset
= offset
* 512U;
746 *ret_size
= size
* 512U;
747 *ret_partition_uuid
= found_partition_uuid
;
752 static int crypt_device_to_evp_cipher(struct crypt_device
*cd
, const EVP_CIPHER
**ret
) {
753 _cleanup_free_
char *cipher_name
= NULL
;
754 const char *cipher
, *cipher_mode
, *e
;
755 size_t key_size
, key_bits
;
756 const EVP_CIPHER
*cc
;
761 /* Let's find the right OpenSSL EVP_CIPHER object that matches the encryption settings of the LUKS
764 cipher
= sym_crypt_get_cipher(cd
);
766 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot get cipher from LUKS device.");
768 cipher_mode
= sym_crypt_get_cipher_mode(cd
);
770 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot get cipher mode from LUKS device.");
772 e
= strchr(cipher_mode
, '-');
774 cipher_mode
= strndupa_safe(cipher_mode
, e
- cipher_mode
);
776 r
= sym_crypt_get_volume_key_size(cd
);
778 return log_error_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(EINVAL
), "Cannot get volume key size from LUKS device.");
781 key_bits
= key_size
* 8;
782 if (streq(cipher_mode
, "xts"))
785 if (asprintf(&cipher_name
, "%s-%zu-%s", cipher
, key_bits
, cipher_mode
) < 0)
788 cc
= EVP_get_cipherbyname(cipher_name
);
790 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Selected cipher mode '%s' not supported, can't encrypt JSON record.", cipher_name
);
792 /* Verify that our key length calculations match what OpenSSL thinks */
793 r
= EVP_CIPHER_key_length(cc
);
794 if (r
< 0 || (uint64_t) r
!= key_size
)
795 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Key size of selected cipher doesn't meet our expectations.");
801 static int luks_validate_home_record(
802 struct crypt_device
*cd
,
804 const void *volume_key
,
805 PasswordCache
*cache
,
806 UserRecord
**ret_luks_home_record
) {
813 for (int token
= 0; token
< sym_crypt_token_max(CRYPT_LUKS2
); token
++) {
814 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
, *rr
= NULL
;
815 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
816 _cleanup_(user_record_unrefp
) UserRecord
*lhr
= NULL
;
817 _cleanup_free_
void *encrypted
= NULL
, *iv
= NULL
;
818 size_t decrypted_size
, encrypted_size
, iv_size
;
819 int decrypted_size_out1
, decrypted_size_out2
;
820 _cleanup_free_
char *decrypted
= NULL
;
821 const char *text
, *type
;
822 crypt_token_info state
;
823 JsonVariant
*jr
, *jiv
;
824 unsigned line
, column
;
825 const EVP_CIPHER
*cc
;
827 state
= sym_crypt_token_status(cd
, token
, &type
);
828 if (state
== CRYPT_TOKEN_INACTIVE
) /* First unconfigured token, give up */
830 if (IN_SET(state
, CRYPT_TOKEN_INTERNAL
, CRYPT_TOKEN_INTERNAL_UNKNOWN
, CRYPT_TOKEN_EXTERNAL
))
832 if (state
!= CRYPT_TOKEN_EXTERNAL_UNKNOWN
)
833 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected token state of token %i: %i", token
, (int) state
);
835 if (!streq(type
, "systemd-homed"))
838 r
= sym_crypt_token_json_get(cd
, token
, &text
);
840 return log_error_errno(r
, "Failed to read LUKS token %i: %m", token
);
842 r
= json_parse(text
, JSON_PARSE_SENSITIVE
, &v
, &line
, &column
);
844 return log_error_errno(r
, "Failed to parse LUKS token JSON data %u:%u: %m", line
, column
);
846 jr
= json_variant_by_key(v
, "record");
848 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "LUKS token lacks 'record' field.");
849 jiv
= json_variant_by_key(v
, "iv");
851 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "LUKS token lacks 'iv' field.");
853 r
= json_variant_unbase64(jr
, &encrypted
, &encrypted_size
);
855 return log_error_errno(r
, "Failed to base64 decode record: %m");
857 r
= json_variant_unbase64(jiv
, &iv
, &iv_size
);
859 return log_error_errno(r
, "Failed to base64 decode IV: %m");
861 r
= crypt_device_to_evp_cipher(cd
, &cc
);
864 if (iv_size
> INT_MAX
|| EVP_CIPHER_iv_length(cc
) != (int) iv_size
)
865 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "IV size doesn't match.");
867 context
= EVP_CIPHER_CTX_new();
871 if (EVP_DecryptInit_ex(context
, cc
, NULL
, volume_key
, iv
) != 1)
872 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize decryption context.");
874 decrypted_size
= encrypted_size
+ EVP_CIPHER_key_length(cc
) * 2;
875 decrypted
= new(char, decrypted_size
);
879 if (EVP_DecryptUpdate(context
, (uint8_t*) decrypted
, &decrypted_size_out1
, encrypted
, encrypted_size
) != 1)
880 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to decrypt JSON record.");
882 assert((size_t) decrypted_size_out1
<= decrypted_size
);
884 if (EVP_DecryptFinal_ex(context
, (uint8_t*) decrypted
+ decrypted_size_out1
, &decrypted_size_out2
) != 1)
885 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finish decryption of JSON record.");
887 assert((size_t) decrypted_size_out1
+ (size_t) decrypted_size_out2
< decrypted_size
);
888 decrypted_size
= (size_t) decrypted_size_out1
+ (size_t) decrypted_size_out2
;
890 if (memchr(decrypted
, 0, decrypted_size
))
891 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Inner NUL byte in JSON record, refusing.");
893 decrypted
[decrypted_size
] = 0;
895 r
= json_parse(decrypted
, JSON_PARSE_SENSITIVE
, &rr
, NULL
, NULL
);
897 return log_error_errno(r
, "Failed to parse decrypted JSON record, refusing.");
899 lhr
= user_record_new();
903 r
= user_record_load(lhr
, rr
, USER_RECORD_LOAD_EMBEDDED
|USER_RECORD_PERMISSIVE
);
905 return log_error_errno(r
, "Failed to parse user record: %m");
907 if (!user_record_compatible(h
, lhr
))
908 return log_error_errno(SYNTHETIC_ERRNO(EREMCHG
), "LUKS home record not compatible with host record, refusing.");
910 r
= user_record_authenticate(lhr
, h
, cache
, /* strict_verify= */ true);
913 assert(r
> 0); /* Insist that a password was verified */
915 *ret_luks_home_record
= TAKE_PTR(lhr
);
919 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Couldn't find home record in LUKS2 header, refusing.");
922 static int format_luks_token_text(
923 struct crypt_device
*cd
,
925 const void *volume_key
,
928 int r
, encrypted_size_out1
= 0, encrypted_size_out2
= 0, iv_size
, key_size
;
929 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
930 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
931 _cleanup_free_
void *iv
= NULL
, *encrypted
= NULL
;
932 size_t text_length
, encrypted_size
;
933 _cleanup_free_
char *text
= NULL
;
934 const EVP_CIPHER
*cc
;
941 r
= crypt_device_to_evp_cipher(cd
, &cc
);
945 key_size
= EVP_CIPHER_key_length(cc
);
946 iv_size
= EVP_CIPHER_iv_length(cc
);
949 iv
= malloc(iv_size
);
953 r
= crypto_random_bytes(iv
, iv_size
);
955 return log_error_errno(r
, "Failed to generate IV: %m");
958 context
= EVP_CIPHER_CTX_new();
962 if (EVP_EncryptInit_ex(context
, cc
, NULL
, volume_key
, iv
) != 1)
963 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize encryption context.");
965 r
= json_variant_format(hr
->json
, 0, &text
);
967 return log_error_errno(r
, "Failed to format user record for LUKS: %m");
969 text_length
= strlen(text
);
970 encrypted_size
= text_length
+ 2*key_size
- 1;
972 encrypted
= malloc(encrypted_size
);
976 if (EVP_EncryptUpdate(context
, encrypted
, &encrypted_size_out1
, (uint8_t*) text
, text_length
) != 1)
977 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to encrypt JSON record.");
979 assert((size_t) encrypted_size_out1
<= encrypted_size
);
981 if (EVP_EncryptFinal_ex(context
, (uint8_t*) encrypted
+ encrypted_size_out1
, &encrypted_size_out2
) != 1)
982 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finish encryption of JSON record. ");
984 assert((size_t) encrypted_size_out1
+ (size_t) encrypted_size_out2
<= encrypted_size
);
988 JSON_BUILD_PAIR("type", JSON_BUILD_CONST_STRING("systemd-homed")),
989 JSON_BUILD_PAIR("keyslots", JSON_BUILD_EMPTY_ARRAY
),
990 JSON_BUILD_PAIR("record", JSON_BUILD_BASE64(encrypted
, encrypted_size_out1
+ encrypted_size_out2
)),
991 JSON_BUILD_PAIR("iv", JSON_BUILD_BASE64(iv
, iv_size
))));
993 return log_error_errno(r
, "Failed to prepare LUKS JSON token object: %m");
995 r
= json_variant_format(v
, 0, ret
);
997 return log_error_errno(r
, "Failed to format encrypted user record for LUKS: %m");
1002 int home_store_header_identity_luks(
1005 UserRecord
*old_home
) {
1007 _cleanup_(user_record_unrefp
) UserRecord
*header_home
= NULL
;
1008 _cleanup_free_
char *text
= NULL
;
1013 if (!setup
->crypt_device
)
1016 assert(setup
->volume_key
);
1018 /* Let's store the user's identity record in the LUKS2 "token" header data fields, in an encrypted
1019 * fashion. Why that? If we'd rely on the record being embedded in the payload file system itself we
1020 * would have to mount the file system before we can validate the JSON record, its signatures and
1021 * whether it matches what we are looking for. However, kernel file system implementations are
1022 * generally not ready to be used on untrusted media. Hence let's store the record independently of
1023 * the file system, so that we can validate it first, and only then mount the file system. To keep
1024 * things simple we use the same encryption settings for this record as for the file system itself. */
1026 r
= user_record_clone(h
, USER_RECORD_EXTRACT_EMBEDDED
|USER_RECORD_PERMISSIVE
, &header_home
);
1028 return log_error_errno(r
, "Failed to determine new header record: %m");
1030 if (old_home
&& user_record_equal(old_home
, header_home
)) {
1031 log_debug("Not updating header home record.");
1035 r
= format_luks_token_text(setup
->crypt_device
, header_home
, setup
->volume_key
, &text
);
1039 for (int token
= 0; token
< sym_crypt_token_max(CRYPT_LUKS2
); token
++) {
1040 crypt_token_info state
;
1043 state
= sym_crypt_token_status(setup
->crypt_device
, token
, &type
);
1044 if (state
== CRYPT_TOKEN_INACTIVE
) /* First unconfigured token, we are done */
1046 if (IN_SET(state
, CRYPT_TOKEN_INTERNAL
, CRYPT_TOKEN_INTERNAL_UNKNOWN
, CRYPT_TOKEN_EXTERNAL
))
1047 continue; /* Not ours */
1048 if (state
!= CRYPT_TOKEN_EXTERNAL_UNKNOWN
)
1049 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected token state of token %i: %i", token
, (int) state
);
1051 if (!streq(type
, "systemd-homed"))
1054 r
= sym_crypt_token_json_set(setup
->crypt_device
, token
, text
);
1056 return log_error_errno(r
, "Failed to set JSON token for slot %i: %m", token
);
1058 /* Now, let's free the text so that for all further matching tokens we all crypt_json_token_set()
1059 * with a NULL text in order to invalidate the tokens. */
1064 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Didn't find any record token to update.");
1066 log_info("Wrote LUKS header user record.");
1071 int run_fitrim(int root_fd
) {
1072 struct fstrim_range range
= {
1076 /* If discarding is on, discard everything right after mounting, so that the discard setting takes
1077 * effect on activation. (Also, optionally, trim on logout) */
1079 assert(root_fd
>= 0);
1081 if (ioctl(root_fd
, FITRIM
, &range
) < 0) {
1082 if (ERRNO_IS_NOT_SUPPORTED(errno
) || errno
== EBADF
) {
1083 log_debug_errno(errno
, "File system does not support FITRIM, not trimming.");
1087 return log_warning_errno(errno
, "Failed to invoke FITRIM, ignoring: %m");
1090 log_info("Discarded unused %s.", FORMAT_BYTES(range
.len
));
1094 int run_fallocate(int backing_fd
, const struct stat
*st
) {
1097 assert(backing_fd
>= 0);
1099 /* If discarding is off, let's allocate the whole image before mounting, so that the setting takes
1100 * effect on activation */
1103 if (fstat(backing_fd
, &stbuf
) < 0)
1104 return log_error_errno(errno
, "Failed to fstat(): %m");
1109 if (!S_ISREG(st
->st_mode
))
1112 if (st
->st_blocks
>= DIV_ROUND_UP(st
->st_size
, 512)) {
1113 log_info("Backing file is fully allocated already.");
1117 if (fallocate(backing_fd
, FALLOC_FL_KEEP_SIZE
, 0, st
->st_size
) < 0) {
1119 if (ERRNO_IS_NOT_SUPPORTED(errno
)) {
1120 log_debug_errno(errno
, "fallocate() not supported on file system, ignoring.");
1124 if (ERRNO_IS_DISK_SPACE(errno
)) {
1125 log_debug_errno(errno
, "Not enough disk space to fully allocate home.");
1126 return -ENOSPC
; /* make recognizable */
1129 return log_error_errno(errno
, "Failed to allocate backing file blocks: %m");
1132 log_info("Allocated additional %s.",
1133 FORMAT_BYTES((DIV_ROUND_UP(st
->st_size
, 512) - st
->st_blocks
) * 512));
1137 int run_fallocate_by_path(const char *backing_path
) {
1138 _cleanup_close_
int backing_fd
= -EBADF
;
1140 backing_fd
= open(backing_path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
1142 return log_error_errno(errno
, "Failed to open '%s' for fallocate(): %m", backing_path
);
1144 return run_fallocate(backing_fd
, NULL
);
1147 static int lock_image_fd(int image_fd
, const char *ip
) {
1150 /* If the $SYSTEMD_LUKS_LOCK environment variable is set we'll take an exclusive BSD lock on the
1151 * image file, and send it to our parent. homed will keep it open to ensure no other instance of
1152 * homed (across the network or such) will also mount the file. */
1154 assert(image_fd
>= 0);
1157 r
= getenv_bool("SYSTEMD_LUKS_LOCK");
1161 return log_error_errno(r
, "Failed to parse $SYSTEMD_LUKS_LOCK environment variable: %m");
1165 if (flock(image_fd
, LOCK_EX
|LOCK_NB
) < 0) {
1167 if (errno
== EAGAIN
)
1168 log_error_errno(errno
, "Image file '%s' already locked, can't use.", ip
);
1170 log_error_errno(errno
, "Failed to lock image file '%s': %m", ip
);
1172 return errno
!= EAGAIN
? -errno
: -EADDRINUSE
; /* Make error recognizable */
1175 log_info("Successfully locked image file '%s'.", ip
);
1177 /* Now send it to our parent to keep safe while the home dir is active */
1178 r
= sd_pid_notify_with_fds(0, false, "SYSTEMD_LUKS_LOCK_FD=1", &image_fd
, 1);
1180 log_warning_errno(r
, "Failed to send LUKS lock fd to parent, ignoring: %m");
1185 static int open_image_file(
1187 const char *force_image_path
,
1188 struct stat
*ret_stat
) {
1190 _cleanup_close_
int image_fd
= -EBADF
;
1195 assert(h
|| force_image_path
);
1197 ip
= force_image_path
?: user_record_image_path(h
);
1199 image_fd
= open(ip
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
1201 return log_error_errno(errno
, "Failed to open image file %s: %m", ip
);
1203 if (fstat(image_fd
, &st
) < 0)
1204 return log_error_errno(errno
, "Failed to fstat() image file: %m");
1205 if (!S_ISREG(st
.st_mode
) && !S_ISBLK(st
.st_mode
))
1206 return log_error_errno(
1207 S_ISDIR(st
.st_mode
) ? SYNTHETIC_ERRNO(EISDIR
) : SYNTHETIC_ERRNO(EBADFD
),
1208 "Image file %s is not a regular file or block device: %m", ip
);
1210 /* Locking block devices doesn't really make sense, as this might interfere with
1211 * udev's workings, and these locks aren't network propagated anyway, hence not what
1212 * we are after here. */
1213 if (S_ISREG(st
.st_mode
)) {
1214 r
= lock_image_fd(image_fd
, ip
);
1222 return TAKE_FD(image_fd
);
1225 int home_setup_luks(
1227 HomeSetupFlags flags
,
1228 const char *force_image_path
,
1230 PasswordCache
*cache
,
1231 UserRecord
**ret_luks_home
) {
1233 sd_id128_t found_partition_uuid
, found_fs_uuid
= SD_ID128_NULL
, found_luks_uuid
= SD_ID128_NULL
;
1234 _cleanup_(user_record_unrefp
) UserRecord
*luks_home
= NULL
;
1235 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
1236 size_t volume_key_size
= 0;
1237 uint64_t offset
, size
;
1243 assert(user_record_storage(h
) == USER_LUKS
);
1245 r
= dlopen_cryptsetup();
1249 r
= make_dm_names(h
, setup
);
1253 /* Reuse the image fd if it has already been opened by an earlier step */
1254 if (setup
->image_fd
< 0) {
1255 setup
->image_fd
= open_image_file(h
, force_image_path
, &st
);
1256 if (setup
->image_fd
< 0)
1257 return setup
->image_fd
;
1258 } else if (fstat(setup
->image_fd
, &st
) < 0)
1259 return log_error_errno(errno
, "Failed to stat image: %m");
1261 if (FLAGS_SET(flags
, HOME_SETUP_ALREADY_ACTIVATED
)) {
1262 struct loop_info64 info
;
1265 if (!setup
->crypt_device
) {
1276 if (ret_luks_home
) {
1277 r
= luks_validate_home_record(setup
->crypt_device
, h
, volume_key
, cache
, &luks_home
);
1282 n
= sym_crypt_get_device_name(setup
->crypt_device
);
1284 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine backing device for DM %s.", setup
->dm_name
);
1287 r
= loop_device_open_from_path(n
, O_RDWR
, LOCK_UN
, &setup
->loop
);
1289 return log_error_errno(r
, "Failed to open loopback device %s: %m", n
);
1292 if (ioctl(setup
->loop
->fd
, LOOP_GET_STATUS64
, &info
) < 0) {
1293 _cleanup_free_
char *sysfs
= NULL
;
1295 if (!IN_SET(errno
, ENOTTY
, EINVAL
))
1296 return log_error_errno(errno
, "Failed to get block device metrics of %s: %m", n
);
1298 if (ioctl(setup
->loop
->fd
, BLKGETSIZE64
, &size
) < 0)
1299 return log_error_errno(r
, "Failed to read block device size of %s: %m", n
);
1301 if (fstat(setup
->loop
->fd
, &st
) < 0)
1302 return log_error_errno(r
, "Failed to stat block device %s: %m", n
);
1303 assert(S_ISBLK(st
.st_mode
));
1305 if (asprintf(&sysfs
, "/sys/dev/block/" DEVNUM_FORMAT_STR
"/partition", DEVNUM_FORMAT_VAL(st
.st_rdev
)) < 0)
1308 if (access(sysfs
, F_OK
) < 0) {
1309 if (errno
!= ENOENT
)
1310 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", sysfs
);
1314 _cleanup_free_
char *buffer
= NULL
;
1316 if (asprintf(&sysfs
, "/sys/dev/block/" DEVNUM_FORMAT_STR
"/start", DEVNUM_FORMAT_VAL(st
.st_rdev
)) < 0)
1319 r
= read_one_line_file(sysfs
, &buffer
);
1321 return log_error_errno(r
, "Failed to read partition start offset: %m");
1323 r
= safe_atou64(buffer
, &offset
);
1325 return log_error_errno(r
, "Failed to parse partition start offset: %m");
1327 if (offset
> UINT64_MAX
/ 512U)
1328 return log_error_errno(SYNTHETIC_ERRNO(E2BIG
), "Offset too large for 64 byte range, refusing.");
1333 #if HAVE_VALGRIND_MEMCHECK_H
1334 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
1337 offset
= info
.lo_offset
;
1338 size
= info
.lo_sizelimit
;
1341 found_partition_uuid
= found_fs_uuid
= SD_ID128_NULL
;
1343 log_info("Discovered used loopback device %s.", setup
->loop
->node
);
1345 if (setup
->root_fd
< 0) {
1346 setup
->root_fd
= open(user_record_home_directory(h
), O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
1347 if (setup
->root_fd
< 0)
1348 return log_error_errno(errno
, "Failed to open home directory: %m");
1351 _cleanup_free_
char *fstype
= NULL
, *subdir
= NULL
;
1354 /* When we aren't reopening the home directory we are allocating it fresh, hence the relevant
1355 * objects can't be allocated yet. */
1356 assert(setup
->root_fd
< 0);
1357 assert(!setup
->crypt_device
);
1358 assert(!setup
->loop
);
1360 ip
= force_image_path
?: user_record_image_path(h
);
1362 subdir
= path_join(HOME_RUNTIME_WORK_DIR
, user_record_user_name_and_realm(h
));
1366 r
= luks_validate(setup
->image_fd
, user_record_user_name_and_realm(h
), h
->partition_uuid
, &found_partition_uuid
, &offset
, &size
);
1368 return log_error_errno(r
, "Failed to validate disk label: %m");
1370 /* Everything before this point left the image untouched. We are now starting to make
1371 * changes, hence mark the image dirty */
1372 if (run_mark_dirty(setup
->image_fd
, true) > 0)
1373 setup
->do_mark_clean
= true;
1375 if (!user_record_luks_discard(h
)) {
1376 r
= run_fallocate(setup
->image_fd
, &st
);
1381 r
= loop_device_make(
1386 h
->luks_sector_size
== UINT64_MAX
? UINT32_MAX
: user_record_luks_sector_size(h
), /* if sector size is not specified, select UINT32_MAX, i.e. auto-probe */
1387 /* loop_flags= */ 0,
1391 log_error_errno(r
, "Loopback block device support is not available on this system.");
1392 return -ENOLINK
; /* make recognizable */
1395 return log_error_errno(r
, "Failed to allocate loopback context: %m");
1397 log_info("Setting up loopback device %s completed.", setup
->loop
->node
?: ip
);
1400 setup
->loop
->node
?: ip
,
1404 h
->luks_cipher_mode
,
1405 h
->luks_volume_key_size
,
1408 user_record_luks_discard(h
) || user_record_luks_offline_discard(h
),
1409 &setup
->crypt_device
,
1413 &setup
->key_serial
);
1417 setup
->undo_dm
= true;
1419 if (ret_luks_home
) {
1420 r
= luks_validate_home_record(setup
->crypt_device
, h
, volume_key
, cache
, &luks_home
);
1425 r
= fs_validate(setup
->dm_node
, h
->file_system_uuid
, &fstype
, &found_fs_uuid
);
1429 r
= run_fsck(setup
->dm_node
, fstype
);
1433 r
= home_unshare_and_mount(setup
->dm_node
, fstype
, user_record_luks_discard(h
), user_record_mount_flags(h
), h
->luks_extra_mount_options
);
1437 setup
->undo_mount
= true;
1439 setup
->root_fd
= open(subdir
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
1440 if (setup
->root_fd
< 0)
1441 return log_error_errno(errno
, "Failed to open home directory: %m");
1443 if (user_record_luks_discard(h
))
1444 (void) run_fitrim(setup
->root_fd
);
1446 setup
->do_offline_fallocate
= !(setup
->do_offline_fitrim
= user_record_luks_offline_discard(h
));
1449 if (!sd_id128_is_null(found_partition_uuid
))
1450 setup
->found_partition_uuid
= found_partition_uuid
;
1451 if (!sd_id128_is_null(found_luks_uuid
))
1452 setup
->found_luks_uuid
= found_luks_uuid
;
1453 if (!sd_id128_is_null(found_fs_uuid
))
1454 setup
->found_fs_uuid
= found_fs_uuid
;
1456 setup
->partition_offset
= offset
;
1457 setup
->partition_size
= size
;
1460 erase_and_free(setup
->volume_key
);
1461 setup
->volume_key
= TAKE_PTR(volume_key
);
1462 setup
->volume_key_size
= volume_key_size
;
1466 *ret_luks_home
= TAKE_PTR(luks_home
);
1471 static void print_size_summary(uint64_t host_size
, uint64_t encrypted_size
, const struct statfs
*sfs
) {
1474 log_info("Image size is %s, file system size is %s, file system payload size is %s, file system free is %s.",
1475 FORMAT_BYTES(host_size
),
1476 FORMAT_BYTES(encrypted_size
),
1477 FORMAT_BYTES((uint64_t) sfs
->f_blocks
* (uint64_t) sfs
->f_frsize
),
1478 FORMAT_BYTES((uint64_t) sfs
->f_bfree
* (uint64_t) sfs
->f_frsize
));
1481 static int home_auto_grow_luks(
1484 PasswordCache
*cache
) {
1491 if (!IN_SET(user_record_auto_resize_mode(h
), AUTO_RESIZE_GROW
, AUTO_RESIZE_SHRINK_AND_GROW
))
1494 assert(setup
->root_fd
>= 0);
1496 if (fstatfs(setup
->root_fd
, &sfs
) < 0)
1497 return log_error_errno(errno
, "Failed to statfs home directory: %m");
1499 if (!fs_can_online_shrink_and_grow(sfs
.f_type
)) {
1500 log_debug("Not auto-grow file system, since selected file system cannot do both online shrink and grow.");
1504 log_debug("Initiating auto-grow...");
1506 return home_resize_luks(
1508 HOME_SETUP_ALREADY_ACTIVATED
|
1509 HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES
|
1510 HOME_SETUP_RESIZE_DONT_SHRINK
|
1511 HOME_SETUP_RESIZE_DONT_UNDO
,
1517 int home_activate_luks(
1519 HomeSetupFlags flags
,
1521 PasswordCache
*cache
,
1522 UserRecord
**ret_home
) {
1524 _cleanup_(user_record_unrefp
) UserRecord
*new_home
= NULL
, *luks_home_record
= NULL
;
1525 uint64_t host_size
, encrypted_size
;
1526 const char *hdo
, *hd
;
1531 assert(user_record_storage(h
) == USER_LUKS
);
1535 r
= dlopen_cryptsetup();
1539 assert_se(hdo
= user_record_home_directory(h
));
1540 hd
= strdupa_safe(hdo
); /* copy the string out, since it might change later in the home record object */
1542 r
= home_get_state_luks(h
, setup
);
1546 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "Device mapper device %s already exists, refusing.", setup
->dm_node
);
1548 r
= home_setup_luks(
1558 r
= home_auto_grow_luks(h
, setup
, cache
);
1562 r
= block_get_size_by_fd(setup
->loop
->fd
, &host_size
);
1564 return log_error_errno(r
, "Failed to get loopback block device size: %m");
1566 r
= block_get_size_by_path(setup
->dm_node
, &encrypted_size
);
1568 return log_error_errno(r
, "Failed to get LUKS block device size: %m");
1581 r
= home_extend_embedded_identity(new_home
, h
, setup
);
1585 setup
->root_fd
= safe_close(setup
->root_fd
);
1587 r
= home_move_mount(user_record_user_name_and_realm(h
), hd
);
1591 setup
->undo_mount
= false;
1592 setup
->do_offline_fitrim
= false;
1594 loop_device_relinquish(setup
->loop
);
1596 r
= sym_crypt_deactivate_by_name(NULL
, setup
->dm_name
, CRYPT_DEACTIVATE_DEFERRED
);
1598 log_warning_errno(r
, "Failed to relinquish DM device, ignoring: %m");
1600 setup
->undo_dm
= false;
1601 setup
->do_offline_fallocate
= false;
1602 setup
->do_mark_clean
= false;
1603 setup
->do_drop_caches
= false;
1604 TAKE_KEY_SERIAL(setup
->key_serial
); /* Leave key in kernel keyring */
1606 log_info("Activation completed.");
1608 print_size_summary(host_size
, encrypted_size
, &sfs
);
1610 *ret_home
= TAKE_PTR(new_home
);
1614 int home_deactivate_luks(UserRecord
*h
, HomeSetup
*setup
) {
1615 bool we_detached
= false;
1621 /* Note that the DM device and loopback device are set to auto-detach, hence strictly speaking we
1622 * don't have to explicitly have to detach them. However, we do that nonetheless (in case of the DM
1623 * device), to avoid races: by explicitly detaching them we know when the detaching is complete. We
1624 * don't bother about the loopback device because unlike the DM device it doesn't have a fixed
1627 if (!setup
->crypt_device
) {
1628 r
= acquire_open_luks_device(h
, setup
, /* graceful= */ true);
1630 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", setup
->dm_name
);
1632 log_debug("LUKS device %s has already been detached.", setup
->dm_name
);
1635 if (setup
->crypt_device
) {
1636 log_info("Discovered used LUKS device %s.", setup
->dm_node
);
1638 cryptsetup_enable_logging(setup
->crypt_device
);
1640 r
= sym_crypt_deactivate_by_name(setup
->crypt_device
, setup
->dm_name
, 0);
1641 if (ERRNO_IS_NEG_DEVICE_ABSENT(r
) || r
== -EINVAL
)
1642 log_debug_errno(r
, "LUKS device %s is already detached.", setup
->dm_node
);
1644 return log_info_errno(r
, "LUKS device %s couldn't be deactivated: %m", setup
->dm_node
);
1646 log_info("LUKS device detaching completed.");
1651 (void) wait_for_block_device_gone(setup
, USEC_PER_SEC
* 30);
1652 setup
->undo_dm
= false;
1654 if (user_record_luks_offline_discard(h
))
1655 log_debug("Not allocating on logout.");
1657 (void) run_fallocate_by_path(user_record_image_path(h
));
1659 run_mark_dirty_by_path(user_record_image_path(h
), false);
1663 int home_trim_luks(UserRecord
*h
, HomeSetup
*setup
) {
1666 assert(setup
->root_fd
>= 0);
1668 if (!user_record_luks_offline_discard(h
)) {
1669 log_debug("Not trimming on logout.");
1673 (void) run_fitrim(setup
->root_fd
);
1677 static struct crypt_pbkdf_type
* build_good_pbkdf(struct crypt_pbkdf_type
*buffer
, UserRecord
*hr
) {
1681 bool benchmark
= user_record_luks_pbkdf_force_iterations(hr
) == UINT64_MAX
;
1683 *buffer
= (struct crypt_pbkdf_type
) {
1684 .hash
= user_record_luks_pbkdf_hash_algorithm(hr
),
1685 .type
= user_record_luks_pbkdf_type(hr
),
1686 .time_ms
= benchmark
? user_record_luks_pbkdf_time_cost_usec(hr
) / USEC_PER_MSEC
: 0,
1687 .iterations
= benchmark
? 0 : user_record_luks_pbkdf_force_iterations(hr
),
1688 .max_memory_kb
= user_record_luks_pbkdf_memory_cost(hr
) / 1024,
1689 .parallel_threads
= user_record_luks_pbkdf_parallel_threads(hr
),
1690 .flags
= benchmark
? 0 : CRYPT_PBKDF_NO_BENCHMARK
,
1696 static struct crypt_pbkdf_type
* build_minimal_pbkdf(struct crypt_pbkdf_type
*buffer
, UserRecord
*hr
) {
1700 /* For PKCS#11 derived keys (which are generated randomly and are of high quality already) we use a
1702 *buffer
= (struct crypt_pbkdf_type
) {
1703 .hash
= user_record_luks_pbkdf_hash_algorithm(hr
),
1704 .type
= CRYPT_KDF_PBKDF2
,
1712 static int luks_format(
1714 const char *dm_name
,
1717 const PasswordCache
*cache
,
1718 char **effective_passwords
,
1721 struct crypt_device
**ret
) {
1723 _cleanup_(user_record_unrefp
) UserRecord
*reduced
= NULL
;
1724 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1725 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
1726 struct crypt_pbkdf_type good_pbkdf
, minimal_pbkdf
;
1727 _cleanup_free_
char *text
= NULL
;
1728 size_t volume_key_size
;
1736 r
= sym_crypt_init(&cd
, node
);
1738 return log_error_errno(r
, "Failed to allocate libcryptsetup context: %m");
1740 cryptsetup_enable_logging(cd
);
1742 /* Normally we'd, just leave volume key generation to libcryptsetup. However, we can't, since we
1743 * can't extract the volume key from the library again, but we need it in order to encrypt the JSON
1744 * record. Hence, let's generate it on our own, so that we can keep track of it. */
1746 volume_key_size
= user_record_luks_volume_key_size(hr
);
1747 volume_key
= malloc(volume_key_size
);
1751 r
= crypto_random_bytes(volume_key
, volume_key_size
);
1753 return log_error_errno(r
, "Failed to generate volume key: %m");
1755 #if HAVE_CRYPT_SET_METADATA_SIZE
1756 /* Increase the metadata space to 4M, the largest LUKS2 supports */
1757 r
= sym_crypt_set_metadata_size(cd
, 4096U*1024U, 0);
1759 return log_error_errno(r
, "Failed to change LUKS2 metadata size: %m");
1762 build_good_pbkdf(&good_pbkdf
, hr
);
1763 build_minimal_pbkdf(&minimal_pbkdf
, hr
);
1765 r
= sym_crypt_format(
1768 user_record_luks_cipher(hr
),
1769 user_record_luks_cipher_mode(hr
),
1770 SD_ID128_TO_UUID_STRING(uuid
),
1773 &(struct crypt_params_luks2
) {
1775 .subsystem
= "systemd-home",
1776 .sector_size
= user_record_luks_sector_size(hr
),
1777 .pbkdf
= &good_pbkdf
,
1780 return log_error_errno(r
, "Failed to format LUKS image: %m");
1782 log_info("LUKS formatting completed.");
1784 STRV_FOREACH(pp
, effective_passwords
) {
1786 if (password_cache_contains(cache
, *pp
)) { /* is this a fido2 or pkcs11 password? */
1787 log_debug("Using minimal PBKDF for slot %i", slot
);
1788 r
= sym_crypt_set_pbkdf_type(cd
, &minimal_pbkdf
);
1790 log_debug("Using good PBKDF for slot %i", slot
);
1791 r
= sym_crypt_set_pbkdf_type(cd
, &good_pbkdf
);
1794 return log_error_errno(r
, "Failed to tweak PBKDF for slot %i: %m", slot
);
1796 r
= sym_crypt_keyslot_add_by_volume_key(
1804 return log_error_errno(r
, "Failed to set up LUKS password for slot %i: %m", slot
);
1806 log_info("Writing password to LUKS keyslot %i completed.", slot
);
1810 r
= sym_crypt_activate_by_volume_key(
1815 discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
1817 return log_error_errno(r
, "Failed to activate LUKS superblock: %m");
1819 log_info("LUKS activation by volume key succeeded.");
1821 r
= user_record_clone(hr
, USER_RECORD_EXTRACT_EMBEDDED
|USER_RECORD_PERMISSIVE
, &reduced
);
1823 return log_error_errno(r
, "Failed to prepare home record for LUKS: %m");
1825 r
= format_luks_token_text(cd
, reduced
, volume_key
, &text
);
1829 r
= sym_crypt_token_json_set(cd
, CRYPT_ANY_TOKEN
, text
);
1831 return log_error_errno(r
, "Failed to set LUKS JSON token: %m");
1833 log_info("Writing user record as LUKS token completed.");
1836 *ret
= TAKE_PTR(cd
);
1841 static int make_partition_table(
1843 uint32_t sector_size
,
1846 uint64_t *ret_offset
,
1848 sd_id128_t
*ret_disk_uuid
) {
1850 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*p
= NULL
, *q
= NULL
;
1851 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
1852 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1853 _cleanup_free_
char *disk_uuid_as_string
= NULL
;
1854 uint64_t offset
, size
, first_lba
, start
, last_lba
, end
;
1855 sd_id128_t disk_uuid
;
1863 t
= fdisk_new_parttype();
1867 r
= fdisk_parttype_set_typestr(t
, SD_GPT_USER_HOME_STR
);
1869 return log_error_errno(r
, "Failed to initialize partition type: %m");
1871 r
= fdisk_new_context_at(fd
, /* path= */ NULL
, /* read_only= */ false, sector_size
, &c
);
1873 return log_error_errno(r
, "Failed to open device: %m");
1875 r
= fdisk_create_disklabel(c
, "gpt");
1877 return log_error_errno(r
, "Failed to create GPT disk label: %m");
1879 p
= fdisk_new_partition();
1883 r
= fdisk_partition_set_type(p
, t
);
1885 return log_error_errno(r
, "Failed to set partition type: %m");
1887 r
= fdisk_partition_partno_follow_default(p
, 1);
1889 return log_error_errno(r
, "Failed to place partition at first free partition index: %m");
1891 first_lba
= fdisk_get_first_lba(c
); /* Boundary where usable space starts */
1892 assert(first_lba
<= UINT64_MAX
/512);
1893 start
= DISK_SIZE_ROUND_UP(first_lba
* 512); /* Round up to multiple of 4K */
1895 log_debug("Starting partition at offset %" PRIu64
, start
);
1897 if (start
== UINT64_MAX
)
1898 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Overflow while rounding up start LBA.");
1900 last_lba
= fdisk_get_last_lba(c
); /* One sector before boundary where usable space ends */
1901 assert(last_lba
< UINT64_MAX
/512);
1902 end
= DISK_SIZE_ROUND_DOWN((last_lba
+ 1) * 512); /* Round down to multiple of 4K */
1905 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Resulting partition size zero or negative.");
1907 r
= fdisk_partition_set_start(p
, start
/ 512);
1909 return log_error_errno(r
, "Failed to place partition at offset %" PRIu64
": %m", start
);
1911 r
= fdisk_partition_set_size(p
, (end
- start
) / 512);
1913 return log_error_errno(r
, "Failed to end partition at offset %" PRIu64
": %m", end
);
1915 r
= fdisk_partition_set_name(p
, label
);
1917 return log_error_errno(r
, "Failed to set partition name: %m");
1919 r
= fdisk_partition_set_uuid(p
, SD_ID128_TO_UUID_STRING(uuid
));
1921 return log_error_errno(r
, "Failed to set partition UUID: %m");
1923 r
= fdisk_add_partition(c
, p
, NULL
);
1925 return log_error_errno(r
, "Failed to add partition: %m");
1927 r
= fdisk_write_disklabel(c
);
1929 return log_error_errno(r
, "Failed to write disk label: %m");
1931 r
= fdisk_get_disklabel_id(c
, &disk_uuid_as_string
);
1933 return log_error_errno(r
, "Failed to determine disk label UUID: %m");
1935 r
= sd_id128_from_string(disk_uuid_as_string
, &disk_uuid
);
1937 return log_error_errno(r
, "Failed to parse disk label UUID: %m");
1939 r
= fdisk_get_partition(c
, 0, &q
);
1941 return log_error_errno(r
, "Failed to read created partition metadata: %m");
1943 assert(fdisk_partition_has_start(q
));
1944 offset
= fdisk_partition_get_start(q
);
1945 if (offset
> UINT64_MAX
/ 512U)
1946 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Partition offset too large.");
1948 assert(fdisk_partition_has_size(q
));
1949 size
= fdisk_partition_get_size(q
);
1950 if (size
> UINT64_MAX
/ 512U)
1951 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Partition size too large.");
1953 *ret_offset
= offset
* 512U;
1954 *ret_size
= size
* 512U;
1955 *ret_disk_uuid
= disk_uuid
;
1960 static bool supported_fs_size(const char *fstype
, uint64_t host_size
) {
1963 m
= minimal_size_by_fs_name(fstype
);
1964 if (m
== UINT64_MAX
)
1967 return host_size
>= m
;
1970 static int wait_for_devlink(const char *path
) {
1971 _cleanup_close_
int inotify_fd
= -EBADF
;
1975 /* let's wait for a device link to show up in /dev, with a timeout. This is good to do since we
1976 * return a /dev/disk/by-uuid/… link to our callers and they likely want to access it right-away,
1977 * hence let's wait until udev has caught up with our changes, and wait for the symlink to be
1980 until
= usec_add(now(CLOCK_MONOTONIC
), 45 * USEC_PER_SEC
);
1983 _cleanup_free_
char *dn
= NULL
;
1986 if (laccess(path
, F_OK
) < 0) {
1987 if (errno
!= ENOENT
)
1988 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", path
);
1990 return 0; /* Found it */
1992 if (inotify_fd
< 0) {
1993 /* We need to wait for the device symlink to show up, let's create an inotify watch for it */
1994 inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
1996 return log_error_errno(errno
, "Failed to allocate inotify fd: %m");
1999 r
= path_extract_directory(path
, &dn
);
2001 return log_error_errno(r
, "Failed to extract directory from device node path '%s': %m", path
);
2003 _cleanup_free_
char *ndn
= NULL
;
2005 log_info("Watching %s", dn
);
2007 if (inotify_add_watch(inotify_fd
, dn
, IN_CREATE
|IN_MOVED_TO
|IN_ONLYDIR
|IN_DELETE_SELF
|IN_MOVE_SELF
) < 0) {
2008 if (errno
!= ENOENT
)
2009 return log_error_errno(errno
, "Failed to add watch on %s: %m", dn
);
2013 r
= path_extract_directory(dn
, &ndn
);
2014 if (r
== -EADDRNOTAVAIL
) /* Arrived at the top? */
2017 return log_error_errno(r
, "Failed to extract directory from device node path '%s': %m", dn
);
2019 free_and_replace(dn
, ndn
);
2022 w
= now(CLOCK_MONOTONIC
);
2024 return log_error_errno(SYNTHETIC_ERRNO(ETIMEDOUT
), "Device link %s still hasn't shown up, giving up.", path
);
2026 r
= fd_wait_for_event(inotify_fd
, POLLIN
, until
- w
);
2027 if (ERRNO_IS_NEG_TRANSIENT(r
))
2030 return log_error_errno(r
, "Failed to watch inotify: %m");
2032 (void) flush_fd(inotify_fd
);
2036 static int calculate_initial_image_size(UserRecord
*h
, int image_fd
, const char *fstype
, uint64_t *ret
) {
2037 uint64_t upper_boundary
, lower_boundary
;
2041 assert(image_fd
>= 0);
2044 if (fstatfs(image_fd
, &sfs
) < 0)
2045 return log_error_errno(errno
, "statfs() on image failed: %m");
2047 upper_boundary
= DISK_SIZE_ROUND_DOWN((uint64_t) sfs
.f_bsize
* sfs
.f_bavail
);
2049 if (h
->disk_size
!= UINT64_MAX
)
2050 *ret
= MIN(DISK_SIZE_ROUND_DOWN(h
->disk_size
), upper_boundary
);
2051 else if (h
->disk_size_relative
== UINT64_MAX
) {
2053 if (upper_boundary
> UINT64_MAX
/ USER_DISK_SIZE_DEFAULT_PERCENT
)
2054 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Disk size too large.");
2056 *ret
= DISK_SIZE_ROUND_DOWN(upper_boundary
* USER_DISK_SIZE_DEFAULT_PERCENT
/ 100);
2058 log_info("Sizing home to %u%% of available disk space, which is %s.",
2059 USER_DISK_SIZE_DEFAULT_PERCENT
,
2060 FORMAT_BYTES(*ret
));
2062 *ret
= DISK_SIZE_ROUND_DOWN((uint64_t) ((double) upper_boundary
* (double) CLAMP(h
->disk_size_relative
, 0U, UINT32_MAX
) / (double) UINT32_MAX
));
2064 log_info("Sizing home to %" PRIu64
".%01" PRIu64
"%% of available disk space, which is %s.",
2065 (h
->disk_size_relative
* 100) / UINT32_MAX
,
2066 ((h
->disk_size_relative
* 1000) / UINT32_MAX
) % 10,
2067 FORMAT_BYTES(*ret
));
2070 lower_boundary
= minimal_size_by_fs_name(fstype
);
2071 if (lower_boundary
!= UINT64_MAX
) {
2072 assert(GPT_LUKS2_OVERHEAD
< UINT64_MAX
- lower_boundary
);
2073 lower_boundary
+= GPT_LUKS2_OVERHEAD
;
2075 if (lower_boundary
== UINT64_MAX
|| lower_boundary
< USER_DISK_SIZE_MIN
)
2076 lower_boundary
= USER_DISK_SIZE_MIN
;
2078 if (*ret
< lower_boundary
)
2079 *ret
= lower_boundary
;
2084 static int home_truncate(
2095 trunc
= user_record_luks_discard(h
);
2097 r
= fallocate(fd
, 0, 0, size
);
2098 if (r
< 0 && ERRNO_IS_NOT_SUPPORTED(errno
)) {
2099 /* Some file systems do not support fallocate(), let's gracefully degrade
2100 * (ZFS, reiserfs, …) and fall back to truncation */
2101 log_notice_errno(errno
, "Backing file system does not support fallocate(), falling back to ftruncate(), i.e. implicitly using non-discard mode.");
2107 r
= ftruncate(fd
, size
);
2110 if (ERRNO_IS_DISK_SPACE(errno
)) {
2111 log_debug_errno(errno
, "Not enough disk space to allocate home of size %s.", FORMAT_BYTES(size
));
2112 return -ENOSPC
; /* make recognizable */
2115 return log_error_errno(errno
, "Failed to truncate home image: %m");
2118 return !trunc
; /* Return == 0 if we managed to truncate, > 0 if we managed to allocate */
2121 int home_create_luks(
2124 const PasswordCache
*cache
,
2125 char **effective_passwords
,
2126 UserRecord
**ret_home
) {
2128 _cleanup_free_
char *subdir
= NULL
, *disk_uuid_path
= NULL
;
2129 uint64_t encrypted_size
,
2130 host_size
= 0, partition_offset
= 0, partition_size
= 0; /* Unnecessary initialization to appease gcc */
2131 _cleanup_(user_record_unrefp
) UserRecord
*new_home
= NULL
;
2132 sd_id128_t partition_uuid
, fs_uuid
, luks_uuid
, disk_uuid
;
2133 _cleanup_close_
int mount_fd
= -EBADF
;
2134 const char *fstype
, *ip
;
2137 _cleanup_strv_free_
char **extra_mkfs_options
= NULL
;
2140 assert(h
->storage
< 0 || h
->storage
== USER_LUKS
);
2142 assert(!setup
->temporary_image_path
);
2143 assert(setup
->image_fd
< 0);
2146 r
= dlopen_cryptsetup();
2150 assert_se(ip
= user_record_image_path(h
));
2152 fstype
= user_record_file_system_type(h
);
2153 if (!supported_fstype(fstype
))
2154 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "Unsupported file system type: %s", fstype
);
2156 r
= mkfs_exists(fstype
);
2158 return log_error_errno(r
, "Failed to check if mkfs binary for %s exists: %m", fstype
);
2160 if (h
->file_system_type
|| streq(fstype
, "ext4") || !supported_fstype("ext4"))
2161 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "mkfs binary for file system type %s does not exist.", fstype
);
2163 /* If the record does not explicitly declare a file system to use, and the compiled-in
2164 * default does not actually exist, than do an automatic fallback onto ext4, as the baseline
2165 * fs of Linux. We won't search for a working fs type here beyond ext4, i.e. nothing fancier
2166 * than a single, conservative fallback to baseline. This should be useful in minimal
2167 * environments where mkfs.btrfs or so are not made available, but mkfs.ext4 as Linux' most
2168 * boring, most basic fs is. */
2169 log_info("Formatting tool for compiled-in default file system %s not available, falling back to ext4 instead.", fstype
);
2173 if (sd_id128_is_null(h
->partition_uuid
)) {
2174 r
= sd_id128_randomize(&partition_uuid
);
2176 return log_error_errno(r
, "Failed to acquire partition UUID: %m");
2178 partition_uuid
= h
->partition_uuid
;
2180 if (sd_id128_is_null(h
->luks_uuid
)) {
2181 r
= sd_id128_randomize(&luks_uuid
);
2183 return log_error_errno(r
, "Failed to acquire LUKS UUID: %m");
2185 luks_uuid
= h
->luks_uuid
;
2187 if (sd_id128_is_null(h
->file_system_uuid
)) {
2188 r
= sd_id128_randomize(&fs_uuid
);
2190 return log_error_errno(r
, "Failed to acquire file system UUID: %m");
2192 fs_uuid
= h
->file_system_uuid
;
2194 r
= make_dm_names(h
, setup
);
2198 r
= access(setup
->dm_node
, F_OK
);
2200 if (errno
!= ENOENT
)
2201 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", setup
->dm_node
);
2203 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "Device mapper device %s already exists, refusing.", setup
->dm_node
);
2205 if (path_startswith(ip
, "/dev/")) {
2206 _cleanup_free_
char *sysfs
= NULL
;
2207 uint64_t block_device_size
;
2210 /* Let's place the home directory on a real device, i.e. a USB stick or such */
2212 setup
->image_fd
= open_image_file(h
, ip
, &st
);
2213 if (setup
->image_fd
< 0)
2214 return setup
->image_fd
;
2216 if (!S_ISBLK(st
.st_mode
))
2217 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Device is not a block device, refusing.");
2219 if (asprintf(&sysfs
, "/sys/dev/block/" DEVNUM_FORMAT_STR
"/partition", DEVNUM_FORMAT_VAL(st
.st_rdev
)) < 0)
2221 if (access(sysfs
, F_OK
) < 0) {
2222 if (errno
!= ENOENT
)
2223 return log_error_errno(errno
, "Failed to check whether %s exists: %m", sysfs
);
2225 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Operating on partitions is currently not supported, sorry. Please specify a top-level block device.");
2227 if (flock(setup
->image_fd
, LOCK_EX
) < 0) /* make sure udev doesn't read from it while we operate on the device */
2228 return log_error_errno(errno
, "Failed to lock block device %s: %m", ip
);
2230 if (ioctl(setup
->image_fd
, BLKGETSIZE64
, &block_device_size
) < 0)
2231 return log_error_errno(errno
, "Failed to read block device size: %m");
2233 if (h
->disk_size
== UINT64_MAX
) {
2235 /* If a relative disk size is requested, apply it relative to the block device size */
2236 if (h
->disk_size_relative
< UINT32_MAX
)
2237 host_size
= CLAMP(DISK_SIZE_ROUND_DOWN(block_device_size
* h
->disk_size_relative
/ UINT32_MAX
),
2238 USER_DISK_SIZE_MIN
, USER_DISK_SIZE_MAX
);
2240 host_size
= block_device_size
; /* Otherwise, take the full device */
2242 } else if (h
->disk_size
> block_device_size
)
2243 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE
), "Selected disk size larger than backing block device, refusing.");
2245 host_size
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
2247 if (!supported_fs_size(fstype
, LESS_BY(host_size
, GPT_LUKS2_OVERHEAD
)))
2248 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
),
2249 "Selected file system size too small for %s.", fstype
);
2251 /* After creation we should reference this partition by its UUID instead of the block
2252 * device. That's preferable since the user might have specified a device node such as
2253 * /dev/sdb to us, which might look very different when replugged. */
2254 if (asprintf(&disk_uuid_path
, "/dev/disk/by-uuid/" SD_ID128_UUID_FORMAT_STR
, SD_ID128_FORMAT_VAL(luks_uuid
)) < 0)
2257 if (user_record_luks_discard(h
) || user_record_luks_offline_discard(h
)) {
2258 /* If we want online or offline discard, discard once before we start using things. */
2260 if (ioctl(setup
->image_fd
, BLKDISCARD
, (uint64_t[]) { 0, block_device_size
}) < 0)
2261 log_full_errno(errno
== EOPNOTSUPP
? LOG_DEBUG
: LOG_WARNING
, errno
,
2262 "Failed to issue full-device BLKDISCARD on device, ignoring: %m");
2264 log_info("Full device discard completed.");
2267 _cleanup_free_
char *t
= NULL
;
2269 r
= mkdir_parents(ip
, 0755);
2271 return log_error_errno(r
, "Failed to create parent directory of %s: %m", ip
);
2273 r
= tempfn_random(ip
, "homework", &t
);
2275 return log_error_errno(r
, "Failed to derive temporary file name for %s: %m", ip
);
2277 setup
->image_fd
= open(t
, O_RDWR
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
2278 if (setup
->image_fd
< 0)
2279 return log_error_errno(errno
, "Failed to create home image %s: %m", t
);
2281 setup
->temporary_image_path
= TAKE_PTR(t
);
2283 r
= chattr_full(setup
->image_fd
, NULL
, FS_NOCOW_FL
|FS_NOCOMP_FL
, FS_NOCOW_FL
|FS_NOCOMP_FL
, NULL
, NULL
, CHATTR_FALLBACK_BITWISE
);
2284 if (r
< 0 && r
!= -ENOANO
) /* ENOANO → some bits didn't work; which we skip logging about because chattr_full() already debug logs about those flags */
2285 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
2286 "Failed to set file attributes on %s, ignoring: %m", setup
->temporary_image_path
);
2288 r
= calculate_initial_image_size(h
, setup
->image_fd
, fstype
, &host_size
);
2292 r
= resize_image_loop(h
, setup
, 0, host_size
, &host_size
);
2296 log_info("Allocating image file completed.");
2299 r
= make_partition_table(
2301 user_record_luks_sector_size(h
),
2302 user_record_user_name_and_realm(h
),
2310 log_info("Writing of partition table completed.");
2312 r
= loop_device_make(
2317 user_record_luks_sector_size(h
),
2322 if (r
== -ENOENT
) { /* this means /dev/loop-control doesn't exist, i.e. we are in a container
2323 * or similar and loopback bock devices are not available, return a
2324 * recognizable error in this case. */
2325 log_error_errno(r
, "Loopback block device support is not available on this system.");
2326 return -ENOLINK
; /* Make recognizable */
2329 return log_error_errno(r
, "Failed to set up loopback device for %s: %m", setup
->temporary_image_path
);
2332 log_info("Setting up loopback device %s completed.", setup
->loop
->node
?: ip
);
2334 r
= luks_format(setup
->loop
->node
,
2337 user_record_user_name_and_realm(h
),
2339 effective_passwords
,
2340 user_record_luks_discard(h
) || user_record_luks_offline_discard(h
),
2342 &setup
->crypt_device
);
2346 setup
->undo_dm
= true;
2348 r
= block_get_size_by_path(setup
->dm_node
, &encrypted_size
);
2350 return log_error_errno(r
, "Failed to get encrypted block device size: %m");
2352 log_info("Setting up LUKS device %s completed.", setup
->dm_node
);
2354 r
= mkfs_options_from_env("HOME", fstype
, &extra_mkfs_options
);
2356 return log_error_errno(r
, "Failed to determine mkfs command line options for '%s': %m", fstype
);
2358 r
= make_filesystem(setup
->dm_node
,
2360 user_record_user_name_and_realm(h
),
2363 user_record_luks_discard(h
),
2365 /* sector_size = */ 0,
2366 extra_mkfs_options
);
2370 log_info("Formatting file system completed.");
2372 r
= home_unshare_and_mount(setup
->dm_node
, fstype
, user_record_luks_discard(h
), user_record_mount_flags(h
), h
->luks_extra_mount_options
);
2376 setup
->undo_mount
= true;
2378 subdir
= path_join(HOME_RUNTIME_WORK_DIR
, user_record_user_name_and_realm(h
));
2382 /* Prefer using a btrfs subvolume if we can, fall back to directory otherwise */
2383 r
= btrfs_subvol_make_fallback(AT_FDCWD
, subdir
, 0700);
2385 return log_error_errno(r
, "Failed to create user directory in mounted image file: %m");
2387 setup
->root_fd
= open(subdir
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
2388 if (setup
->root_fd
< 0)
2389 return log_error_errno(errno
, "Failed to open user directory in mounted image file: %m");
2391 (void) home_shift_uid(setup
->root_fd
, NULL
, UID_NOBODY
, h
->uid
, &mount_fd
);
2393 if (mount_fd
>= 0) {
2394 /* If we have established a new mount, then we can use that as new root fd to our home directory. */
2395 safe_close(setup
->root_fd
);
2397 setup
->root_fd
= fd_reopen(mount_fd
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
);
2398 if (setup
->root_fd
< 0)
2399 return log_error_errno(setup
->root_fd
, "Unable to convert mount fd into proper directory fd: %m");
2401 mount_fd
= safe_close(mount_fd
);
2404 r
= home_populate(h
, setup
->root_fd
);
2408 r
= home_sync_and_statfs(setup
->root_fd
, &sfs
);
2412 r
= user_record_clone(h
, USER_RECORD_LOAD_MASK_SECRET
|USER_RECORD_LOG
|USER_RECORD_PERMISSIVE
, &new_home
);
2414 return log_error_errno(r
, "Failed to clone record: %m");
2416 r
= user_record_add_binding(
2419 disk_uuid_path
?: ip
,
2423 sym_crypt_get_cipher(setup
->crypt_device
),
2424 sym_crypt_get_cipher_mode(setup
->crypt_device
),
2425 luks_volume_key_size_convert(setup
->crypt_device
),
2431 return log_error_errno(r
, "Failed to add binding to record: %m");
2433 if (user_record_luks_offline_discard(h
)) {
2434 r
= run_fitrim(setup
->root_fd
);
2439 setup
->root_fd
= safe_close(setup
->root_fd
);
2441 r
= home_setup_undo_mount(setup
, LOG_ERR
);
2445 r
= home_setup_undo_dm(setup
, LOG_ERR
);
2449 setup
->loop
= loop_device_unref(setup
->loop
);
2451 if (!user_record_luks_offline_discard(h
)) {
2452 r
= run_fallocate(setup
->image_fd
, NULL
/* refresh stat() data */);
2457 /* Sync everything to disk before we move things into place under the final name. */
2458 if (fsync(setup
->image_fd
) < 0)
2459 return log_error_errno(r
, "Failed to synchronize image to disk: %m");
2462 /* Reread partition table if this is a block device */
2463 (void) ioctl(setup
->image_fd
, BLKRRPART
, 0);
2465 assert(setup
->temporary_image_path
);
2467 if (rename(setup
->temporary_image_path
, ip
) < 0)
2468 return log_error_errno(errno
, "Failed to rename image file: %m");
2470 setup
->temporary_image_path
= mfree(setup
->temporary_image_path
);
2472 /* If we operate on a file, sync the containing directory too. */
2473 r
= fsync_directory_of_file(setup
->image_fd
);
2475 return log_error_errno(r
, "Failed to synchronize directory of image file to disk: %m");
2477 log_info("Moved image file into place.");
2480 /* Let's close the image fd now. If we are operating on a real block device this will release the BSD
2481 * lock that ensures udev doesn't interfere with what we are doing */
2482 setup
->image_fd
= safe_close(setup
->image_fd
);
2485 (void) wait_for_devlink(disk_uuid_path
);
2487 log_info("Creation completed.");
2489 print_size_summary(host_size
, encrypted_size
, &sfs
);
2491 log_debug("GPT + LUKS2 overhead is %" PRIu64
" (expected %" PRIu64
")", host_size
- encrypted_size
, GPT_LUKS2_OVERHEAD
);
2493 *ret_home
= TAKE_PTR(new_home
);
2497 int home_get_state_luks(UserRecord
*h
, HomeSetup
*setup
) {
2503 r
= make_dm_names(h
, setup
);
2507 r
= access(setup
->dm_node
, F_OK
);
2508 if (r
< 0 && errno
!= ENOENT
)
2509 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", setup
->dm_node
);
2519 static int can_resize_fs(int fd
, uint64_t old_size
, uint64_t new_size
) {
2524 /* Filter out bogus requests early */
2525 if (old_size
== 0 || old_size
== UINT64_MAX
||
2526 new_size
== 0 || new_size
== UINT64_MAX
)
2527 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid resize parameters.");
2529 if ((old_size
& 511) != 0 || (new_size
& 511) != 0)
2530 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Resize parameters not multiple of 512.");
2532 if (fstatfs(fd
, &sfs
) < 0)
2533 return log_error_errno(errno
, "Failed to fstatfs() file system: %m");
2535 if (is_fs_type(&sfs
, BTRFS_SUPER_MAGIC
)) {
2537 if (new_size
< BTRFS_MINIMAL_SIZE
)
2538 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for btrfs (needs to be 256M at least.");
2540 /* btrfs can grow and shrink online */
2542 } else if (is_fs_type(&sfs
, XFS_SB_MAGIC
)) {
2544 if (new_size
< XFS_MINIMAL_SIZE
)
2545 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for xfs (needs to be 14M at least).");
2547 /* XFS can grow, but not shrink */
2548 if (new_size
< old_size
)
2549 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE
), "Shrinking this type of file system is not supported.");
2551 } else if (is_fs_type(&sfs
, EXT4_SUPER_MAGIC
)) {
2553 if (new_size
< EXT4_MINIMAL_SIZE
)
2554 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for ext4 (needs to be 1M at least).");
2556 /* ext4 can grow online, and shrink offline */
2557 if (new_size
< old_size
)
2558 return CAN_RESIZE_OFFLINE
;
2561 return log_error_errno(SYNTHETIC_ERRNO(ESOCKTNOSUPPORT
), "Resizing this type of file system is not supported.");
2563 return CAN_RESIZE_ONLINE
;
2566 static int ext4_offline_resize_fs(
2570 unsigned long flags
,
2571 const char *extra_mount_options
) {
2573 _cleanup_free_
char *size_str
= NULL
;
2574 bool re_open
= false, re_mount
= false;
2575 pid_t resize_pid
, fsck_pid
;
2579 assert(setup
->dm_node
);
2581 /* First, unmount the file system */
2582 if (setup
->root_fd
>= 0) {
2583 setup
->root_fd
= safe_close(setup
->root_fd
);
2587 if (setup
->undo_mount
) {
2588 r
= home_setup_undo_mount(setup
, LOG_ERR
);
2595 log_info("Temporary unmounting of file system completed.");
2597 /* resize2fs requires that the file system is force checked first, do so. */
2598 r
= safe_fork("(e2fsck)",
2599 FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_STDOUT_TO_STDERR
|FORK_CLOSE_ALL_FDS
,
2605 execlp("e2fsck" ,"e2fsck", "-fp", setup
->dm_node
, NULL
);
2607 log_error_errno(errno
, "Failed to execute e2fsck: %m");
2608 _exit(EXIT_FAILURE
);
2611 exit_status
= wait_for_terminate_and_check("e2fsck", fsck_pid
, WAIT_LOG_ABNORMAL
);
2612 if (exit_status
< 0)
2614 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != 0) {
2615 log_warning("e2fsck failed with exit status %i.", exit_status
);
2617 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
2618 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "File system is corrupted, refusing.");
2620 log_warning("Ignoring fsck error.");
2623 log_info("Forced file system check completed.");
2625 /* We use 512 sectors here, because resize2fs doesn't do byte sizes */
2626 if (asprintf(&size_str
, "%" PRIu64
"s", new_size
/ 512) < 0)
2629 /* Resize the thing */
2630 r
= safe_fork("(e2resize)",
2631 FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_WAIT
|FORK_STDOUT_TO_STDERR
|FORK_CLOSE_ALL_FDS
,
2637 execlp("resize2fs" ,"resize2fs", setup
->dm_node
, size_str
, NULL
);
2639 log_error_errno(errno
, "Failed to execute resize2fs: %m");
2640 _exit(EXIT_FAILURE
);
2643 log_info("Offline file system resize completed.");
2645 /* Re-establish mounts and reopen the directory */
2647 r
= home_mount_node(setup
->dm_node
, "ext4", discard
, flags
, extra_mount_options
);
2651 setup
->undo_mount
= true;
2655 setup
->root_fd
= open(HOME_RUNTIME_WORK_DIR
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
2656 if (setup
->root_fd
< 0)
2657 return log_error_errno(errno
, "Failed to reopen file system: %m");
2660 log_info("File system mounted again.");
2665 static int prepare_resize_partition(
2667 uint64_t partition_offset
,
2668 uint64_t old_partition_size
,
2669 sd_id128_t
*ret_disk_uuid
,
2670 struct fdisk_table
**ret_table
,
2671 struct fdisk_partition
**ret_partition
) {
2673 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2674 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
2675 _cleanup_free_
char *disk_uuid_as_string
= NULL
;
2676 struct fdisk_partition
*found
= NULL
;
2677 sd_id128_t disk_uuid
;
2678 size_t n_partitions
;
2682 assert(ret_disk_uuid
);
2685 assert((partition_offset
& 511) == 0);
2686 assert((old_partition_size
& 511) == 0);
2687 assert(UINT64_MAX
- old_partition_size
>= partition_offset
);
2689 if (partition_offset
== 0) {
2690 /* If the offset is at the beginning we assume no partition table, let's exit early. */
2691 log_debug("Not rewriting partition table, operating on naked device.");
2692 *ret_disk_uuid
= SD_ID128_NULL
;
2694 *ret_partition
= NULL
;
2698 r
= fdisk_new_context_at(fd
, /* path= */ NULL
, /* read_only= */ false, UINT32_MAX
, &c
);
2700 return log_error_errno(r
, "Failed to open device: %m");
2702 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2703 return log_error_errno(SYNTHETIC_ERRNO(ENOMEDIUM
), "Disk has no GPT partition table.");
2705 r
= fdisk_get_disklabel_id(c
, &disk_uuid_as_string
);
2707 return log_error_errno(r
, "Failed to acquire disk UUID: %m");
2709 r
= sd_id128_from_string(disk_uuid_as_string
, &disk_uuid
);
2711 return log_error_errno(r
, "Failed parse disk UUID: %m");
2713 r
= fdisk_get_partitions(c
, &t
);
2715 return log_error_errno(r
, "Failed to acquire partition table: %m");
2717 n_partitions
= fdisk_table_get_nents(t
);
2718 for (size_t i
= 0; i
< n_partitions
; i
++) {
2719 struct fdisk_partition
*p
;
2721 p
= fdisk_table_get_partition(t
, i
);
2723 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
2725 if (fdisk_partition_is_used(p
) <= 0)
2727 if (fdisk_partition_has_start(p
) <= 0 || fdisk_partition_has_size(p
) <= 0 || fdisk_partition_has_end(p
) <= 0)
2728 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found partition without a size.");
2730 if (fdisk_partition_get_start(p
) == partition_offset
/ 512U &&
2731 fdisk_partition_get_size(p
) == old_partition_size
/ 512U) {
2734 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
), "Partition found twice, refusing.");
2737 } else if (fdisk_partition_get_end(p
) > partition_offset
/ 512U)
2738 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Can't extend, not last partition in image.");
2742 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to find matching partition to resize.");
2744 *ret_disk_uuid
= disk_uuid
;
2745 *ret_table
= TAKE_PTR(t
);
2746 *ret_partition
= found
;
2751 static int get_maximum_partition_size(
2753 struct fdisk_partition
*p
,
2754 uint64_t *ret_maximum_partition_size
) {
2756 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2757 uint64_t start_lba
, start
, last_lba
, end
;
2762 assert(ret_maximum_partition_size
);
2764 r
= fdisk_new_context_at(fd
, /* path= */ NULL
, /* read_only= */ true, /* sector_size= */ UINT32_MAX
, &c
);
2766 return log_error_errno(r
, "Failed to create fdisk context: %m");
2768 start_lba
= fdisk_partition_get_start(p
);
2769 assert(start_lba
<= UINT64_MAX
/512);
2770 start
= start_lba
* 512;
2772 last_lba
= fdisk_get_last_lba(c
); /* One sector before boundary where usable space ends */
2773 assert(last_lba
< UINT64_MAX
/512);
2774 end
= DISK_SIZE_ROUND_DOWN((last_lba
+ 1) * 512); /* Round down to multiple of 4K */
2777 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Last LBA is before partition start.");
2779 *ret_maximum_partition_size
= DISK_SIZE_ROUND_DOWN(end
- start
);
2784 static int ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *userdata
) {
2789 switch (fdisk_ask_get_type(ask
)) {
2791 case FDISK_ASKTYPE_STRING
:
2792 result
= new(char, 37);
2796 fdisk_ask_string_set_result(ask
, sd_id128_to_uuid_string(*(sd_id128_t
*) userdata
, result
));
2800 log_debug("Unexpected question from libfdisk, ignoring.");
2806 static int apply_resize_partition(
2808 sd_id128_t disk_uuids
,
2809 struct fdisk_table
*t
,
2810 struct fdisk_partition
*p
,
2811 size_t new_partition_size
) {
2813 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2814 _cleanup_free_
void *two_zero_lbas
= NULL
;
2822 if (!t
) /* no partition table to apply, exit early */
2827 /* Before writing our partition patch the final size in */
2828 r
= fdisk_partition_size_explicit(p
, 1);
2830 return log_error_errno(r
, "Failed to enable explicit partition size: %m");
2832 r
= fdisk_partition_set_size(p
, new_partition_size
/ 512U);
2834 return log_error_errno(r
, "Failed to change partition size: %m");
2836 r
= probe_sector_size(fd
, &ssz
);
2838 return log_error_errno(r
, "Failed to determine current sector size: %m");
2840 two_zero_lbas
= malloc0(ssz
* 2);
2844 /* libfdisk appears to get confused by the existing PMBR. Let's explicitly flush it out. */
2845 n
= pwrite(fd
, two_zero_lbas
, ssz
* 2, 0);
2847 return log_error_errno(errno
, "Failed to wipe partition table: %m");
2848 if ((size_t) n
!= ssz
* 2)
2849 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Short write while wiping partition table.");
2851 r
= fdisk_new_context_at(fd
, /* path= */ NULL
, /* read_only= */ false, ssz
, &c
);
2853 return log_error_errno(r
, "Failed to open device: %m");
2855 r
= fdisk_create_disklabel(c
, "gpt");
2857 return log_error_errno(r
, "Failed to create GPT disk label: %m");
2859 r
= fdisk_apply_table(c
, t
);
2861 return log_error_errno(r
, "Failed to apply partition table: %m");
2863 r
= fdisk_set_ask(c
, ask_cb
, &disk_uuids
);
2865 return log_error_errno(r
, "Failed to set libfdisk query function: %m");
2867 r
= fdisk_set_disklabel_id(c
);
2869 return log_error_errno(r
, "Failed to change disklabel ID: %m");
2871 r
= fdisk_write_disklabel(c
);
2873 return log_error_errno(r
, "Failed to write disk label: %m");
2878 /* Always keep at least 16M free, so that we can safely log in and update the user record while doing so */
2879 #define HOME_MIN_FREE (16U*1024U*1024U)
2881 static int get_smallest_fs_size(int fd
, uint64_t *ret
) {
2882 uint64_t minsz
, needed
;
2888 /* Determines the minimal disk size we might be able to shrink the file system referenced by the fd to. */
2890 if (syncfs(fd
) < 0) /* let's sync before we query the size, so that the values returned are accurate */
2891 return log_error_errno(errno
, "Failed to synchronize home file system: %m");
2893 if (fstatfs(fd
, &sfs
) < 0)
2894 return log_error_errno(errno
, "Failed to statfs() home file system: %m");
2896 /* Let's determine the minimal file system size of the used fstype */
2897 minsz
= minimal_size_by_fs_magic(sfs
.f_type
);
2898 if (minsz
== UINT64_MAX
)
2899 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Don't know minimum file system size of file system type '%s' of home directory.", fs_type_to_string(sfs
.f_type
));
2901 if (minsz
< USER_DISK_SIZE_MIN
)
2902 minsz
= USER_DISK_SIZE_MIN
;
2904 if (sfs
.f_bfree
> sfs
.f_blocks
)
2905 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Detected amount of free blocks is greater than the total amount of file system blocks. Refusing.");
2907 /* Calculate how much disk space is currently in use. */
2908 needed
= sfs
.f_blocks
- sfs
.f_bfree
;
2909 if (needed
> UINT64_MAX
/ sfs
.f_bsize
)
2910 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "File system size out of range.");
2912 needed
*= sfs
.f_bsize
;
2914 /* Add some safety margin of free space we'll always keep */
2915 if (needed
> UINT64_MAX
- HOME_MIN_FREE
) /* Check for overflow */
2916 needed
= UINT64_MAX
;
2918 needed
+= HOME_MIN_FREE
;
2920 *ret
= DISK_SIZE_ROUND_UP(MAX(needed
, minsz
));
2924 static int get_largest_image_size(int fd
, const struct stat
*st
, uint64_t *ret
) {
2925 uint64_t used
, avail
, sum
;
2933 /* Determines the maximum file size we might be able to grow the image file referenced by the fd to. */
2935 r
= stat_verify_regular(st
);
2937 return log_error_errno(r
, "Image file is not a regular file, refusing: %m");
2940 return log_error_errno(errno
, "Failed to synchronize file system backing image file: %m");
2942 if (fstatfs(fd
, &sfs
) < 0)
2943 return log_error_errno(errno
, "Failed to statfs() image file: %m");
2945 used
= (uint64_t) st
->st_blocks
* 512;
2946 avail
= (uint64_t) sfs
.f_bsize
* sfs
.f_bavail
;
2948 if (avail
> UINT64_MAX
- used
)
2953 *ret
= DISK_SIZE_ROUND_DOWN(MIN(sum
, USER_DISK_SIZE_MAX
));
2957 static int resize_fs_loop(
2961 uint64_t old_fs_size
,
2962 uint64_t new_fs_size
,
2963 uint64_t *ret_fs_size
) {
2965 uint64_t current_fs_size
;
2966 unsigned n_iterations
= 0;
2971 assert(setup
->root_fd
>= 0);
2973 /* A bisection loop trying to find the closest size to what the user asked for. (Well, we bisect like
2974 * this only when we *shrink* the fs — if we grow the fs there's no need to bisect.) */
2976 current_fs_size
= old_fs_size
;
2977 for (uint64_t lower_boundary
= new_fs_size
, upper_boundary
= old_fs_size
, try_fs_size
= new_fs_size
;;) {
2982 /* Now resize the file system */
2983 if (resize_type
== CAN_RESIZE_ONLINE
) {
2984 r
= resize_fs(setup
->root_fd
, try_fs_size
, NULL
);
2986 if (!ERRNO_IS_DISK_SPACE(r
) || new_fs_size
> old_fs_size
) /* Not a disk space issue? Not trying to shrink? */
2987 return log_error_errno(r
, "Failed to resize file system: %m");
2989 log_debug_errno(r
, "Shrinking from %s to %s didn't work, not enough space for contained data.", FORMAT_BYTES(current_fs_size
), FORMAT_BYTES(try_fs_size
));
2992 log_debug("Successfully resized from %s to %s.", FORMAT_BYTES(current_fs_size
), FORMAT_BYTES(try_fs_size
));
2993 current_fs_size
= try_fs_size
;
2997 /* If we hit a disk space issue and are shrinking the fs, then maybe it helps to
2998 * increase the image size. */
3000 r
= ext4_offline_resize_fs(setup
, try_fs_size
, user_record_luks_discard(h
), user_record_mount_flags(h
), h
->luks_extra_mount_options
);
3004 /* For now, when we fail to shrink an ext4 image we'll not try again via the
3005 * bisection logic. We might add that later, but given this involves shelling out
3006 * multiple programs, it's a bit too cumbersome for my taste. */
3009 current_fs_size
= try_fs_size
;
3012 if (new_fs_size
> old_fs_size
) /* If we are growing we are done after one iteration */
3015 /* If we are shrinking then let's adjust our bisection boundaries and try again. */
3017 upper_boundary
= MIN(upper_boundary
, try_fs_size
);
3019 lower_boundary
= MAX(lower_boundary
, try_fs_size
);
3021 /* OK, this attempt to shrink didn't work. Let's try between the old size and what worked. */
3022 if (lower_boundary
>= upper_boundary
) {
3023 log_debug("Image can't be shrunk further (range to try is empty).");
3027 /* Let's find a new value to try half-way between the lower boundary and the upper boundary
3029 try_fs_size
= DISK_SIZE_ROUND_DOWN(lower_boundary
+ (upper_boundary
- lower_boundary
) / 2);
3030 if (try_fs_size
<= lower_boundary
|| try_fs_size
>= upper_boundary
) {
3031 log_debug("Image can't be shrunk further (remaining range to try too small).");
3036 log_debug("Bisection loop completed after %u iterations.", n_iterations
);
3039 *ret_fs_size
= current_fs_size
;
3044 static int resize_image_loop(
3047 uint64_t old_image_size
,
3048 uint64_t new_image_size
,
3049 uint64_t *ret_image_size
) {
3051 uint64_t current_image_size
;
3052 unsigned n_iterations
= 0;
3057 assert(setup
->image_fd
>= 0);
3059 /* A bisection loop trying to find the closest size to what the user asked for. (Well, we bisect like
3060 * this only when we *grow* the image — if we shrink the image then there's no need to bisect.) */
3062 current_image_size
= old_image_size
;
3063 for (uint64_t lower_boundary
= old_image_size
, upper_boundary
= new_image_size
, try_image_size
= new_image_size
;;) {
3068 r
= home_truncate(h
, setup
->image_fd
, try_image_size
);
3070 if (!ERRNO_IS_DISK_SPACE(r
) || new_image_size
< old_image_size
) /* Not a disk space issue? Not trying to grow? */
3073 log_debug_errno(r
, "Growing from %s to %s didn't work, not enough space on backing disk.", FORMAT_BYTES(current_image_size
), FORMAT_BYTES(try_image_size
));
3075 } else if (r
> 0) { /* Success: allocation worked */
3076 log_debug("Resizing from %s to %s via allocation worked successfully.", FORMAT_BYTES(current_image_size
), FORMAT_BYTES(try_image_size
));
3077 current_image_size
= try_image_size
;
3079 } else { /* Success, but through truncation, not allocation. */
3080 log_debug("Resizing from %s to %s via truncation worked successfully.", FORMAT_BYTES(old_image_size
), FORMAT_BYTES(try_image_size
));
3081 current_image_size
= try_image_size
;
3082 break; /* there's no point in the bisection logic if this was plain truncation and
3083 * not allocation, let's exit immediately. */
3086 if (new_image_size
< old_image_size
) /* If we are shrinking we are done after one iteration */
3089 /* If we are growing then let's adjust our bisection boundaries and try again */
3091 lower_boundary
= MAX(lower_boundary
, try_image_size
);
3093 upper_boundary
= MIN(upper_boundary
, try_image_size
);
3095 if (lower_boundary
>= upper_boundary
) {
3096 log_debug("Image can't be grown further (range to try is empty).");
3100 try_image_size
= DISK_SIZE_ROUND_DOWN(lower_boundary
+ (upper_boundary
- lower_boundary
) / 2);
3101 if (try_image_size
<= lower_boundary
|| try_image_size
>= upper_boundary
) {
3102 log_debug("Image can't be grown further (remaining range to try too small).");
3107 log_debug("Bisection loop completed after %u iterations.", n_iterations
);
3110 *ret_image_size
= current_image_size
;
3115 int home_resize_luks(
3117 HomeSetupFlags flags
,
3119 PasswordCache
*cache
,
3120 UserRecord
**ret_home
) {
3122 uint64_t old_image_size
, new_image_size
, old_fs_size
, new_fs_size
, crypto_offset
, crypto_offset_bytes
,
3123 new_partition_size
, smallest_fs_size
, resized_fs_size
;
3124 _cleanup_(user_record_unrefp
) UserRecord
*header_home
= NULL
, *embedded_home
= NULL
, *new_home
= NULL
;
3125 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*table
= NULL
;
3126 struct fdisk_partition
*partition
= NULL
;
3127 _cleanup_close_
int opened_image_fd
= -EBADF
;
3128 _cleanup_free_
char *whole_disk
= NULL
;
3129 int r
, resize_type
, image_fd
= -EBADF
;
3130 sd_id128_t disk_uuid
;
3131 const char *ip
, *ipo
;
3135 INTENTION_DONT_KNOW
= 0, /* These happen to match the return codes of CMP() */
3136 INTENTION_SHRINK
= -1,
3138 } intention
= INTENTION_DONT_KNOW
;
3141 assert(user_record_storage(h
) == USER_LUKS
);
3144 r
= dlopen_cryptsetup();
3148 assert_se(ipo
= user_record_image_path(h
));
3149 ip
= strdupa_safe(ipo
); /* copy out since original might change later in home record object */
3151 if (setup
->image_fd
< 0) {
3152 setup
->image_fd
= open_image_file(h
, NULL
, &st
);
3153 if (setup
->image_fd
< 0)
3154 return setup
->image_fd
;
3156 if (fstat(setup
->image_fd
, &st
) < 0)
3157 return log_error_errno(errno
, "Failed to stat image file %s: %m", ip
);
3160 image_fd
= setup
->image_fd
;
3162 if (S_ISBLK(st
.st_mode
)) {
3165 r
= block_get_whole_disk(st
.st_rdev
, &parent
);
3167 return log_error_errno(r
, "Failed to acquire whole block device for %s: %m", ip
);
3169 /* If we shall resize a file system on a partition device, then let's figure out the
3170 * whole disk device and operate on that instead, since we need to rewrite the
3171 * partition table to resize the partition. */
3173 log_info("Operating on partition device %s, using parent device.", ip
);
3175 opened_image_fd
= r
= device_open_from_devnum(S_IFBLK
, parent
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
, &whole_disk
);
3177 return log_error_errno(r
, "Failed to open whole block device for %s: %m", ip
);
3179 image_fd
= opened_image_fd
;
3181 if (fstat(image_fd
, &st
) < 0)
3182 return log_error_errno(errno
, "Failed to stat whole block device %s: %m", whole_disk
);
3184 log_info("Operating on whole block device %s.", ip
);
3186 if (ioctl(image_fd
, BLKGETSIZE64
, &old_image_size
) < 0)
3187 return log_error_errno(errno
, "Failed to determine size of original block device: %m");
3189 if (flock(image_fd
, LOCK_EX
) < 0) /* make sure udev doesn't read from it while we operate on the device */
3190 return log_error_errno(errno
, "Failed to lock block device %s: %m", ip
);
3192 new_image_size
= old_image_size
; /* we can't resize physical block devices */
3194 r
= stat_verify_regular(&st
);
3196 return log_error_errno(r
, "Image %s is not a block device nor regular file: %m", ip
);
3198 old_image_size
= st
.st_size
;
3200 /* Note an asymmetry here: when we operate on loopback files the specified disk size we get we
3201 * apply onto the loopback file as a whole. When we operate on block devices we instead apply
3202 * to the partition itself only. */
3204 if (FLAGS_SET(flags
, HOME_SETUP_RESIZE_MINIMIZE
)) {
3206 intention
= INTENTION_SHRINK
;
3208 uint64_t new_image_size_rounded
;
3210 new_image_size_rounded
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
3212 if (old_image_size
>= new_image_size_rounded
&& old_image_size
<= h
->disk_size
) {
3213 /* If exact match, or a match after we rounded down, don't do a thing */
3214 log_info("Image size already matching, skipping operation.");
3218 new_image_size
= new_image_size_rounded
;
3219 intention
= CMP(new_image_size
, old_image_size
); /* Is this a shrink */
3223 r
= home_setup_luks(
3229 FLAGS_SET(flags
, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES
) ? NULL
: &header_home
);
3233 if (!FLAGS_SET(flags
, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES
)) {
3234 r
= home_load_embedded_identity(h
, setup
->root_fd
, header_home
, USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL
, cache
, &embedded_home
, &new_home
);
3239 r
= home_maybe_shift_uid(h
, flags
, setup
);
3243 log_info("offset = %" PRIu64
", size = %" PRIu64
", image = %" PRIu64
, setup
->partition_offset
, setup
->partition_size
, old_image_size
);
3245 if ((UINT64_MAX
- setup
->partition_offset
) < setup
->partition_size
||
3246 setup
->partition_offset
+ setup
->partition_size
> old_image_size
)
3247 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Old partition doesn't fit in backing storage, refusing.");
3249 /* Get target partition information in here for new_partition_size calculation */
3250 r
= prepare_resize_partition(
3252 setup
->partition_offset
,
3253 setup
->partition_size
,
3260 if (S_ISREG(st
.st_mode
)) {
3261 uint64_t partition_table_extra
, largest_size
;
3263 partition_table_extra
= old_image_size
- setup
->partition_size
;
3265 r
= get_largest_image_size(setup
->image_fd
, &st
, &largest_size
);
3268 if (new_image_size
> largest_size
)
3269 new_image_size
= largest_size
;
3271 if (new_image_size
< partition_table_extra
)
3272 new_image_size
= partition_table_extra
;
3274 new_partition_size
= DISK_SIZE_ROUND_DOWN(new_image_size
- partition_table_extra
);
3276 assert(S_ISBLK(st
.st_mode
));
3278 if (FLAGS_SET(flags
, HOME_SETUP_RESIZE_MINIMIZE
)) {
3279 new_partition_size
= 0;
3280 intention
= INTENTION_SHRINK
;
3282 uint64_t new_partition_size_rounded
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
3284 if (h
->disk_size
== UINT64_MAX
&& partition
) {
3285 r
= get_maximum_partition_size(image_fd
, partition
, &new_partition_size_rounded
);
3290 if (setup
->partition_size
>= new_partition_size_rounded
&&
3291 setup
->partition_size
<= h
->disk_size
) {
3292 log_info("Partition size already matching, skipping operation.");
3296 new_partition_size
= new_partition_size_rounded
;
3297 intention
= CMP(new_partition_size
, setup
->partition_size
);
3301 if ((UINT64_MAX
- setup
->partition_offset
) < new_partition_size
||
3302 setup
->partition_offset
+ new_partition_size
> new_image_size
)
3303 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "New partition doesn't fit into backing storage, refusing.");
3305 crypto_offset
= sym_crypt_get_data_offset(setup
->crypt_device
);
3306 if (crypto_offset
> UINT64_MAX
/512U)
3307 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "LUKS2 data offset out of range, refusing.");
3308 crypto_offset_bytes
= (uint64_t) crypto_offset
* 512U;
3309 if (setup
->partition_size
<= crypto_offset_bytes
)
3310 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Weird, old crypto payload offset doesn't actually fit in partition size?");
3312 /* Make sure at least the LUKS header fit in */
3313 if (new_partition_size
<= crypto_offset_bytes
) {
3316 add
= DISK_SIZE_ROUND_UP(crypto_offset_bytes
) - new_partition_size
;
3317 new_partition_size
+= add
;
3318 if (S_ISREG(st
.st_mode
))
3319 new_image_size
+= add
;
3322 old_fs_size
= setup
->partition_size
- crypto_offset_bytes
;
3323 new_fs_size
= DISK_SIZE_ROUND_DOWN(new_partition_size
- crypto_offset_bytes
);
3325 r
= get_smallest_fs_size(setup
->root_fd
, &smallest_fs_size
);
3329 if (new_fs_size
< smallest_fs_size
) {
3332 add
= DISK_SIZE_ROUND_UP(smallest_fs_size
) - new_fs_size
;
3334 new_partition_size
+= add
;
3335 if (S_ISREG(st
.st_mode
))
3336 new_image_size
+= add
;
3339 if (new_fs_size
== old_fs_size
) {
3340 log_info("New file system size identical to old file system size, skipping operation.");
3344 if (FLAGS_SET(flags
, HOME_SETUP_RESIZE_DONT_GROW
) && new_fs_size
> old_fs_size
) {
3345 log_info("New file system size would be larger than old, but shrinking requested, skipping operation.");
3349 if (FLAGS_SET(flags
, HOME_SETUP_RESIZE_DONT_SHRINK
) && new_fs_size
< old_fs_size
) {
3350 log_info("New file system size would be smaller than old, but growing requested, skipping operation.");
3354 if (CMP(new_fs_size
, old_fs_size
) != intention
) {
3356 log_info("Shrink operation would enlarge file system, skipping operation.");
3358 assert(intention
> 0);
3359 log_info("Grow operation would shrink file system, skipping operation.");
3364 /* Before we start doing anything, let's figure out if we actually can */
3365 resize_type
= can_resize_fs(setup
->root_fd
, old_fs_size
, new_fs_size
);
3366 if (resize_type
< 0)
3368 if (resize_type
== CAN_RESIZE_OFFLINE
&& FLAGS_SET(flags
, HOME_SETUP_ALREADY_ACTIVATED
))
3369 return log_error_errno(SYNTHETIC_ERRNO(ETXTBSY
), "File systems of this type can only be resized offline, but is currently online.");
3371 log_info("Ready to resize image size %s %s %s, partition size %s %s %s, file system size %s %s %s.",
3372 FORMAT_BYTES(old_image_size
),
3373 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
),
3374 FORMAT_BYTES(new_image_size
),
3375 FORMAT_BYTES(setup
->partition_size
),
3376 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
),
3377 FORMAT_BYTES(new_partition_size
),
3378 FORMAT_BYTES(old_fs_size
),
3379 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
),
3380 FORMAT_BYTES(new_fs_size
));
3382 if (new_fs_size
> old_fs_size
) { /* → Grow */
3384 if (S_ISREG(st
.st_mode
)) {
3385 uint64_t resized_image_size
;
3387 /* Grow file size */
3388 r
= resize_image_loop(h
, setup
, old_image_size
, new_image_size
, &resized_image_size
);
3392 if (resized_image_size
== old_image_size
) {
3393 log_info("Couldn't change image size.");
3397 assert(resized_image_size
> old_image_size
);
3399 log_info("Growing of image file from %s to %s completed.", FORMAT_BYTES(old_image_size
), FORMAT_BYTES(resized_image_size
));
3401 if (resized_image_size
< new_image_size
) {
3404 /* If the growing we managed to do is smaller than what we wanted we need to
3405 * adjust the partition/file system sizes we are going for, too */
3406 sub
= new_image_size
- resized_image_size
;
3407 assert(new_partition_size
>= sub
);
3408 new_partition_size
-= sub
;
3409 assert(new_fs_size
>= sub
);
3413 new_image_size
= resized_image_size
;
3415 assert(S_ISBLK(st
.st_mode
));
3416 assert(new_image_size
== old_image_size
);
3419 /* Make sure loopback device sees the new bigger size */
3420 r
= loop_device_refresh_size(setup
->loop
, UINT64_MAX
, new_partition_size
);
3422 log_debug_errno(r
, "Device is not a loopback device, not refreshing size.");
3424 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
3426 log_info("Refreshing loop device size completed.");
3428 r
= apply_resize_partition(image_fd
, disk_uuid
, table
, partition
, new_partition_size
);
3432 log_info("Growing of partition completed.");
3434 if (S_ISBLK(st
.st_mode
) && ioctl(image_fd
, BLKRRPART
, 0) < 0)
3435 log_debug_errno(errno
, "BLKRRPART failed on block device, ignoring: %m");
3437 /* Tell LUKS about the new bigger size too */
3438 r
= sym_crypt_resize(setup
->crypt_device
, setup
->dm_name
, new_fs_size
/ 512U);
3440 return log_error_errno(r
, "Failed to grow LUKS device: %m");
3442 log_info("LUKS device growing completed.");
3446 if (!FLAGS_SET(flags
, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES
)) {
3447 r
= home_store_embedded_identity(new_home
, setup
->root_fd
, h
->uid
, embedded_home
);
3452 if (S_ISREG(st
.st_mode
)) {
3453 if (user_record_luks_discard(h
))
3454 /* Before we shrink, let's trim the file system, so that we need less space on disk during the shrinking */
3455 (void) run_fitrim(setup
->root_fd
);
3457 /* If discard is off, let's ensure all backing blocks are allocated, so that our resize operation doesn't fail half-way */
3458 r
= run_fallocate(image_fd
, &st
);
3465 /* Now try to resize the file system. The requested size might not always be possible, in which case
3466 * we'll try to get as close as we can get. The result is returned in 'resized_fs_size' */
3467 r
= resize_fs_loop(h
, setup
, resize_type
, old_fs_size
, new_fs_size
, &resized_fs_size
);
3471 if (resized_fs_size
== old_fs_size
) {
3472 log_info("Couldn't change file system size.");
3476 log_info("File system resizing from %s to %s completed.", FORMAT_BYTES(old_fs_size
), FORMAT_BYTES(resized_fs_size
));
3478 if (resized_fs_size
> new_fs_size
) {
3481 /* If the shrinking we managed to do is larger than what we wanted we need to adjust the partition/image sizes. */
3482 add
= resized_fs_size
- new_fs_size
;
3483 new_partition_size
+= add
;
3484 if (S_ISREG(st
.st_mode
))
3485 new_image_size
+= add
;
3488 new_fs_size
= resized_fs_size
;
3490 /* Immediately sync afterwards */
3491 r
= home_sync_and_statfs(setup
->root_fd
, NULL
);
3495 if (new_fs_size
< old_fs_size
) { /* → Shrink */
3497 /* Shrink the LUKS device now, matching the new file system size */
3498 r
= sym_crypt_resize(setup
->crypt_device
, setup
->dm_name
, new_fs_size
/ 512);
3500 return log_error_errno(r
, "Failed to shrink LUKS device: %m");
3502 log_info("LUKS device shrinking completed.");
3504 /* Refresh the loop devices size */
3505 r
= loop_device_refresh_size(setup
->loop
, UINT64_MAX
, new_partition_size
);
3507 log_debug_errno(r
, "Device is not a loopback device, not refreshing size.");
3509 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
3511 log_info("Refreshing loop device size completed.");
3513 if (S_ISREG(st
.st_mode
)) {
3514 /* Shrink the image file */
3515 if (ftruncate(image_fd
, new_image_size
) < 0)
3516 return log_error_errno(errno
, "Failed to shrink image file %s: %m", ip
);
3518 log_info("Shrinking of image file completed.");
3520 assert(S_ISBLK(st
.st_mode
));
3521 assert(new_image_size
== old_image_size
);
3524 r
= apply_resize_partition(image_fd
, disk_uuid
, table
, partition
, new_partition_size
);
3528 log_info("Shrinking of partition completed.");
3530 if (S_ISBLK(st
.st_mode
) && ioctl(image_fd
, BLKRRPART
, 0) < 0)
3531 log_debug_errno(errno
, "BLKRRPART failed on block device, ignoring: %m");
3533 } else { /* → Grow */
3534 if (!FLAGS_SET(flags
, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES
)) {
3535 r
= home_store_embedded_identity(new_home
, setup
->root_fd
, h
->uid
, embedded_home
);
3541 if (!FLAGS_SET(flags
, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES
)) {
3542 r
= home_store_header_identity_luks(new_home
, setup
, header_home
);
3546 r
= home_extend_embedded_identity(new_home
, h
, setup
);
3551 if (user_record_luks_discard(h
))
3552 (void) run_fitrim(setup
->root_fd
);
3554 r
= home_sync_and_statfs(setup
->root_fd
, &sfs
);
3558 if (!FLAGS_SET(flags
, HOME_SETUP_RESIZE_DONT_UNDO
)) {
3559 r
= home_setup_done(setup
);
3564 log_info("Resizing completed.");
3566 print_size_summary(new_image_size
, new_fs_size
, &sfs
);
3569 *ret_home
= TAKE_PTR(new_home
);
3574 int home_passwd_luks(
3576 HomeSetupFlags flags
,
3578 const PasswordCache
*cache
, /* the passwords acquired via PKCS#11/FIDO2 security tokens */
3579 char **effective_passwords
/* new passwords */) {
3581 size_t volume_key_size
, max_key_slots
, n_effective
;
3582 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
3583 struct crypt_pbkdf_type good_pbkdf
, minimal_pbkdf
;
3589 assert(user_record_storage(h
) == USER_LUKS
);
3592 r
= dlopen_cryptsetup();
3596 type
= sym_crypt_get_type(setup
->crypt_device
);
3598 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine crypto device type.");
3600 r
= sym_crypt_keyslot_max(type
);
3602 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine number of key slots.");
3605 r
= sym_crypt_get_volume_key_size(setup
->crypt_device
);
3607 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine volume key size.");
3608 volume_key_size
= (size_t) r
;
3610 volume_key
= malloc(volume_key_size
);
3615 FOREACH_POINTER(list
,
3616 cache
? cache
->keyring_passswords
: NULL
,
3617 cache
? cache
->pkcs11_passwords
: NULL
,
3618 cache
? cache
->fido2_passwords
: NULL
,
3621 r
= luks_try_passwords(h
, setup
->crypt_device
, list
, volume_key
, &volume_key_size
, NULL
);
3626 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY
), "Failed to unlock LUKS superblock with supplied passwords.");
3628 return log_error_errno(r
, "Failed to unlock LUKS superblock: %m");
3630 n_effective
= strv_length(effective_passwords
);
3632 build_good_pbkdf(&good_pbkdf
, h
);
3633 build_minimal_pbkdf(&minimal_pbkdf
, h
);
3635 for (size_t i
= 0; i
< max_key_slots
; i
++) {
3636 r
= sym_crypt_keyslot_destroy(setup
->crypt_device
, i
);
3637 if (r
< 0 && !IN_SET(r
, -ENOENT
, -EINVAL
)) /* Returns EINVAL or ENOENT if there's no key in this slot already */
3638 return log_error_errno(r
, "Failed to destroy LUKS password: %m");
3640 if (i
>= n_effective
) {
3642 log_info("Destroyed LUKS key slot %zu.", i
);
3646 if (password_cache_contains(cache
, effective_passwords
[i
])) { /* Is this a FIDO2 or PKCS#11 password? */
3647 log_debug("Using minimal PBKDF for slot %zu", i
);
3648 r
= sym_crypt_set_pbkdf_type(setup
->crypt_device
, &minimal_pbkdf
);
3650 log_debug("Using good PBKDF for slot %zu", i
);
3651 r
= sym_crypt_set_pbkdf_type(setup
->crypt_device
, &good_pbkdf
);
3654 return log_error_errno(r
, "Failed to tweak PBKDF for slot %zu: %m", i
);
3656 r
= sym_crypt_keyslot_add_by_volume_key(
3657 setup
->crypt_device
,
3661 effective_passwords
[i
],
3662 strlen(effective_passwords
[i
]));
3664 return log_error_errno(r
, "Failed to set up LUKS password: %m");
3666 log_info("Updated LUKS key slot %zu.", i
);
3668 /* If we changed the password, then make sure to update the copy in the keyring, so that
3669 * auto-rebalance continues to work. We only do this if we operate on an active home dir. */
3670 if (i
== 0 && FLAGS_SET(flags
, HOME_SETUP_ALREADY_ACTIVATED
))
3671 upload_to_keyring(h
, effective_passwords
[i
], NULL
);
3677 int home_lock_luks(UserRecord
*h
, HomeSetup
*setup
) {
3683 assert(setup
->root_fd
< 0);
3684 assert(!setup
->crypt_device
);
3686 r
= acquire_open_luks_device(h
, setup
, /* graceful= */ false);
3690 log_info("Discovered used LUKS device %s.", setup
->dm_node
);
3692 assert_se(p
= user_record_home_directory(h
));
3693 r
= syncfs_path(AT_FDCWD
, p
);
3694 if (r
< 0) /* Snake oil, but let's better be safe than sorry */
3695 return log_error_errno(r
, "Failed to synchronize file system %s: %m", p
);
3697 log_info("File system synchronized.");
3699 /* Note that we don't invoke FIFREEZE here, it appears libcryptsetup/device-mapper already does that on its own for us */
3701 r
= sym_crypt_suspend(setup
->crypt_device
, setup
->dm_name
);
3703 return log_error_errno(r
, "Failed to suspend cryptsetup device: %s: %m", setup
->dm_node
);
3705 log_info("LUKS device suspended.");
3709 static int luks_try_resume(
3710 struct crypt_device
*cd
,
3711 const char *dm_name
,
3719 STRV_FOREACH(pp
, password
) {
3720 r
= sym_crypt_resume_by_passphrase(
3727 log_info("Resumed LUKS device %s.", dm_name
);
3731 log_debug_errno(r
, "Password %zu didn't work for resuming device: %m", (size_t) (pp
- password
));
3737 int home_unlock_luks(UserRecord
*h
, HomeSetup
*setup
, const PasswordCache
*cache
) {
3743 assert(!setup
->crypt_device
);
3745 r
= acquire_open_luks_device(h
, setup
, /* graceful= */ false);
3749 log_info("Discovered used LUKS device %s.", setup
->dm_node
);
3752 FOREACH_POINTER(list
,
3753 cache
? cache
->pkcs11_passwords
: NULL
,
3754 cache
? cache
->fido2_passwords
: NULL
,
3756 r
= luks_try_resume(setup
->crypt_device
, setup
->dm_name
, list
);
3761 return log_error_errno(r
, "No valid password for LUKS superblock.");
3763 return log_error_errno(r
, "Failed to resume LUKS superblock: %m");
3765 log_info("LUKS device resumed.");
3769 static int device_is_gone(HomeSetup
*setup
) {
3770 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
3776 if (!setup
->dm_node
)
3779 if (stat(setup
->dm_node
, &st
) < 0) {
3780 if (errno
!= ENOENT
)
3781 return log_error_errno(errno
, "Failed to stat block device node %s: %m", setup
->dm_node
);
3786 r
= sd_device_new_from_stat_rdev(&d
, &st
);
3789 return log_error_errno(errno
, "Failed to allocate device object from block device node %s: %m", setup
->dm_node
);
3797 static int device_monitor_handler(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
3798 HomeSetup
*setup
= ASSERT_PTR(userdata
);
3801 if (!device_for_action(device
, SD_DEVICE_REMOVE
))
3804 /* We don't really care for the device object passed to us, we just check if the device node still
3807 r
= device_is_gone(setup
);
3810 if (r
> 0) /* Yay! we are done! */
3811 (void) sd_event_exit(sd_device_monitor_get_event(monitor
), 0);
3816 int wait_for_block_device_gone(HomeSetup
*setup
, usec_t timeout_usec
) {
3817 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*m
= NULL
;
3818 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
3823 /* So here's the thing: we enable "deferred deactivation" on our dm-crypt volumes. This means they
3824 * are automatically torn down once not used anymore (i.e. once unmounted). Which is great. It also
3825 * means that when we deactivate a home directory and try to tear down the volume that backs it, it
3826 * possibly is already torn down or in the process of being torn down, since we race against the
3827 * automatic tearing down. Which is fine, we handle errors from that. However, we lose the ability to
3828 * naturally wait for the tear down operation to complete: if we are not the ones who tear down the
3829 * device we are also not the ones who naturally block on that operation. Hence let's add some code
3830 * to actively wait for the device to go away, via sd-device. We'll call this whenever tearing down a
3831 * LUKS device, to ensure the device is really really gone before we proceed. Net effect: "homectl
3832 * deactivate foo && homectl activate foo" will work reliably, i.e. deactivation immediately followed
3833 * by activation will work. Also, by the time deactivation completes we can guarantee that all data
3834 * is sync'ed down to the lowest block layer as all higher levels are fully and entirely
3837 if (!setup
->dm_name
)
3840 assert(setup
->dm_node
);
3841 log_debug("Waiting until %s disappears.", setup
->dm_node
);
3843 r
= sd_event_new(&event
);
3845 return log_error_errno(r
, "Failed to allocate event loop: %m");
3847 r
= sd_device_monitor_new(&m
);
3849 return log_error_errno(r
, "Failed to allocate device monitor: %m");
3851 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
, "block", "disk");
3853 return log_error_errno(r
, "Failed to configure device monitor match: %m");
3855 r
= sd_device_monitor_attach_event(m
, event
);
3857 return log_error_errno(r
, "Failed to attach device monitor to event loop: %m");
3859 r
= sd_device_monitor_start(m
, device_monitor_handler
, setup
);
3861 return log_error_errno(r
, "Failed to start device monitor: %m");
3863 r
= device_is_gone(setup
);
3867 log_debug("%s has already disappeared before entering wait loop.", setup
->dm_node
);
3868 return 0; /* gone already */
3871 if (timeout_usec
!= USEC_INFINITY
) {
3872 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, timeout_usec
, 0, NULL
, NULL
);
3874 return log_error_errno(r
, "Failed to add timer event: %m");
3877 r
= sd_event_loop(event
);
3879 return log_error_errno(r
, "Failed to run event loop: %m");
3881 r
= device_is_gone(setup
);
3885 return log_error_errno(r
, "Device %s still around.", setup
->dm_node
);
3887 log_debug("Successfully waited until device %s disappeared.", setup
->dm_node
);
3891 int home_auto_shrink_luks(UserRecord
*h
, HomeSetup
*setup
, PasswordCache
*cache
) {
3896 assert(user_record_storage(h
) == USER_LUKS
);
3898 assert(setup
->root_fd
>= 0);
3900 if (user_record_auto_resize_mode(h
) != AUTO_RESIZE_SHRINK_AND_GROW
)
3903 if (fstatfs(setup
->root_fd
, &sfs
) < 0)
3904 return log_error_errno(errno
, "Failed to statfs home directory: %m");
3906 if (!fs_can_online_shrink_and_grow(sfs
.f_type
)) {
3907 log_debug("Not auto-shrinking file system, since selected file system cannot do both online shrink and grow.");
3911 r
= home_resize_luks(
3913 HOME_SETUP_ALREADY_ACTIVATED
|
3914 HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES
|
3915 HOME_SETUP_RESIZE_MINIMIZE
|
3916 HOME_SETUP_RESIZE_DONT_GROW
|
3917 HOME_SETUP_RESIZE_DONT_UNDO
,