1 /* SPDX-License-Identifier: LGPL-2.1+ */
4 #include <linux/loop.h>
9 #include "blkid-util.h"
10 #include "blockdev-util.h"
11 #include "btrfs-util.h"
12 #include "chattr-util.h"
14 #include "errno-util.h"
18 #include "fsck-util.h"
19 #include "home-util.h"
20 #include "homework-luks.h"
21 #include "homework-mount.h"
22 #include "id128-util.h"
24 #include "memory-util.h"
25 #include "missing_magic.h"
27 #include "mount-util.h"
28 #include "openssl-util.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "process-util.h"
32 #include "random-util.h"
33 #include "resize-fs.h"
34 #include "stat-util.h"
36 #include "tmpfile-util.h"
38 /* Round down to the nearest 1K size. Note that Linux generally handles block devices with 512 blocks only,
39 * but actually doesn't accept uneven numbers in many cases. To avoid any confusion around this we'll
40 * strictly round disk sizes down to the next 1K boundary.*/
41 #define DISK_SIZE_ROUND_DOWN(x) ((x) & ~UINT64_C(1023))
43 static int probe_file_system_by_fd(
46 sd_id128_t
*ret_uuid
) {
48 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
49 _cleanup_free_
char *s
= NULL
;
50 const char *fstype
= NULL
, *uuid
= NULL
;
58 b
= blkid_new_probe();
63 r
= blkid_probe_set_device(b
, fd
, 0, 0);
65 return errno
> 0 ? -errno
: -ENOMEM
;
67 (void) blkid_probe_enable_superblocks(b
, 1);
68 (void) blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_UUID
);
71 r
= blkid_do_safeprobe(b
);
72 if (IN_SET(r
, -2, 1)) /* nothing found or ambiguous result */
75 return errno
> 0 ? -errno
: -EIO
;
77 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
81 (void) blkid_probe_lookup_value(b
, "UUID", &uuid
, NULL
);
85 r
= sd_id128_from_string(uuid
, &id
);
93 *ret_fstype
= TAKE_PTR(s
);
99 static int probe_file_system_by_path(const char *path
, char **ret_fstype
, sd_id128_t
*ret_uuid
) {
100 _cleanup_close_
int fd
= -1;
102 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
106 return probe_file_system_by_fd(fd
, ret_fstype
, ret_uuid
);
109 static int block_get_size_by_fd(int fd
, uint64_t *ret
) {
115 if (fstat(fd
, &st
) < 0)
118 if (!S_ISBLK(st
.st_mode
))
121 if (ioctl(fd
, BLKGETSIZE64
, ret
) < 0)
127 static int block_get_size_by_path(const char *path
, uint64_t *ret
) {
128 _cleanup_close_
int fd
= -1;
130 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
134 return block_get_size_by_fd(fd
, ret
);
137 static int run_fsck(const char *node
, const char *fstype
) {
144 r
= fsck_exists(fstype
);
146 return log_error_errno(r
, "Failed to check if fsck for file system %s exists: %m", fstype
);
148 log_warning("No fsck for file system %s installed, ignoring.", fstype
);
152 r
= safe_fork("(fsck)", FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_STDOUT_TO_STDERR
, &fsck_pid
);
157 execl("/sbin/fsck", "/sbin/fsck", "-aTl", node
, NULL
);
158 log_error_errno(errno
, "Failed to execute fsck: %m");
159 _exit(FSCK_OPERATIONAL_ERROR
);
162 exit_status
= wait_for_terminate_and_check("fsck", fsck_pid
, WAIT_LOG_ABNORMAL
);
165 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != 0) {
166 log_warning("fsck failed with exit status %i.", exit_status
);
168 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
169 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "File system is corrupted, refusing.");
171 log_warning("Ignoring fsck error.");
174 log_info("File system check completed.");
179 static int luks_try_passwords(
180 struct crypt_device
*cd
,
183 size_t *volume_key_size
) {
190 STRV_FOREACH(pp
, passwords
) {
191 size_t vks
= *volume_key_size
;
193 r
= crypt_volume_key_get(
201 *volume_key_size
= vks
;
205 log_debug_errno(r
, "Password %zu didn't work for unlocking LUKS superblock: %m", (size_t) (pp
- passwords
));
211 static int luks_setup(
216 const char *cipher_mode
,
217 uint64_t volume_key_size
,
219 char **pkcs11_decrypted_passwords
,
221 struct crypt_device
**ret
,
222 sd_id128_t
*ret_found_uuid
,
223 void **ret_volume_key
,
224 size_t *ret_volume_key_size
) {
226 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
227 _cleanup_(erase_and_freep
) void *vk
= NULL
;
236 r
= crypt_init(&cd
, node
);
238 return log_error_errno(r
, "Failed to allocate libcryptsetup context: %m");
240 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
242 r
= crypt_load(cd
, CRYPT_LUKS2
, NULL
);
244 return log_error_errno(r
, "Failed to load LUKS superblock: %m");
246 r
= crypt_get_volume_key_size(cd
);
248 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine LUKS volume key size");
251 if (!sd_id128_is_null(uuid
) || ret_found_uuid
) {
254 s
= crypt_get_uuid(cd
);
256 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has no UUID.");
258 r
= sd_id128_from_string(s
, &p
);
260 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has invalid UUID.");
262 /* Check that the UUID matches, if specified */
263 if (!sd_id128_is_null(uuid
) &&
264 !sd_id128_equal(uuid
, p
))
265 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has wrong UUID.");
268 if (cipher
&& !streq_ptr(cipher
, crypt_get_cipher(cd
)))
269 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong cipher.");
271 if (cipher_mode
&& !streq_ptr(cipher_mode
, crypt_get_cipher_mode(cd
)))
272 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong cipher mode.");
274 if (volume_key_size
!= UINT64_MAX
&& vks
!= volume_key_size
)
275 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock declares wrong volume key size.");
281 r
= luks_try_passwords(cd
, pkcs11_decrypted_passwords
, vk
, &vks
);
283 r
= luks_try_passwords(cd
, passwords
, vk
, &vks
);
285 return log_error_errno(r
, "No valid password for LUKS superblock.");
288 return log_error_errno(r
, "Failed to unlocks LUKS superblock: %m");
290 r
= crypt_activate_by_volume_key(
294 discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
296 return log_error_errno(r
, "Failed to unlock LUKS superblock: %m");
298 log_info("Setting up LUKS device /dev/mapper/%s completed.", dm_name
);
302 if (ret_found_uuid
) /* Return the UUID actually found if the caller wants to know */
305 *ret_volume_key
= TAKE_PTR(vk
);
306 if (ret_volume_key_size
)
307 *ret_volume_key_size
= vks
;
312 static int luks_open(
315 char **pkcs11_decrypted_passwords
,
316 struct crypt_device
**ret
,
317 sd_id128_t
*ret_found_uuid
,
318 void **ret_volume_key
,
319 size_t *ret_volume_key_size
) {
321 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
322 _cleanup_(erase_and_freep
) void *vk
= NULL
;
330 /* Opens a LUKS device that is already set up. Re-validates the password while doing so (which also
331 * provides us with the volume key, which we want). */
333 r
= crypt_init_by_name(&cd
, dm_name
);
335 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
337 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
339 r
= crypt_load(cd
, CRYPT_LUKS2
, NULL
);
341 return log_error_errno(r
, "Failed to load LUKS superblock: %m");
343 r
= crypt_get_volume_key_size(cd
);
345 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine LUKS volume key size");
348 if (ret_found_uuid
) {
351 s
= crypt_get_uuid(cd
);
353 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has no UUID.");
355 r
= sd_id128_from_string(s
, &p
);
357 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "LUKS superblock has invalid UUID.");
364 r
= luks_try_passwords(cd
, pkcs11_decrypted_passwords
, vk
, &vks
);
366 r
= luks_try_passwords(cd
, passwords
, vk
, &vks
);
368 return log_error_errno(r
, "No valid password for LUKS superblock.");
371 return log_error_errno(r
, "Failed to unlocks LUKS superblock: %m");
373 log_info("Discovered used LUKS device /dev/mapper/%s, and validated password.", dm_name
);
375 /* This is needed so that crypt_resize() can operate correctly for pre-existing LUKS devices. We need
376 * to tell libcryptsetup the volume key explicitly, so that it is in the kernel keyring. */
377 r
= crypt_activate_by_volume_key(cd
, NULL
, vk
, vks
, CRYPT_ACTIVATE_KEYRING_KEY
);
379 return log_error_errno(r
, "Failed to upload volume key again: %m");
381 log_info("Successfully re-activated LUKS device.");
388 *ret_volume_key
= TAKE_PTR(vk
);
389 if (ret_volume_key_size
)
390 *ret_volume_key_size
= vks
;
395 static int fs_validate(
399 sd_id128_t
*ret_found_uuid
) {
401 _cleanup_free_
char *fstype
= NULL
;
408 r
= probe_file_system_by_path(dm_node
, &fstype
, &u
);
410 return log_error_errno(r
, "Failed to probe file system: %m");
412 /* Limit the set of supported file systems a bit, as protection against little tested kernel file
413 * systems. Also, we only support the resize ioctls for these file systems. */
414 if (!supported_fstype(fstype
))
415 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "Image contains unsupported file system: %s", strna(fstype
));
417 if (!sd_id128_is_null(uuid
) &&
418 !sd_id128_equal(uuid
, u
))
419 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE
), "File system has wrong UUID.");
421 log_info("Probing file system completed (found %s).", fstype
);
423 *ret_fstype
= TAKE_PTR(fstype
);
425 if (ret_found_uuid
) /* Return the UUID actually found if the caller wants to know */
431 static int make_dm_names(const char *user_name
, char **ret_dm_name
, char **ret_dm_node
) {
432 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
438 name
= strjoin("home-", user_name
);
442 node
= path_join("/dev/mapper/", name
);
446 *ret_dm_name
= TAKE_PTR(name
);
447 *ret_dm_node
= TAKE_PTR(node
);
451 static int luks_validate(
454 sd_id128_t partition_uuid
,
455 sd_id128_t
*ret_partition_uuid
,
456 uint64_t *ret_offset
,
457 uint64_t *ret_size
) {
459 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
460 sd_id128_t found_partition_uuid
= SD_ID128_NULL
;
461 const char *fstype
= NULL
, *pttype
= NULL
;
462 blkid_loff_t offset
= 0, size
= 0;
472 b
= blkid_new_probe();
477 r
= blkid_probe_set_device(b
, fd
, 0, 0);
479 return errno
> 0 ? -errno
: -ENOMEM
;
481 (void) blkid_probe_enable_superblocks(b
, 1);
482 (void) blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
483 (void) blkid_probe_enable_partitions(b
, 1);
484 (void) blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
487 r
= blkid_do_safeprobe(b
);
488 if (IN_SET(r
, -2, 1)) /* nothing found or ambiguous result */
491 return errno
> 0 ? -errno
: -EIO
;
493 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
494 if (streq_ptr(fstype
, "crypto_LUKS")) {
495 /* Directly a LUKS image */
497 *ret_size
= UINT64_MAX
; /* full disk */
498 *ret_partition_uuid
= SD_ID128_NULL
;
503 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
504 if (!streq_ptr(pttype
, "gpt"))
508 pl
= blkid_probe_get_partitions(b
);
510 return errno
> 0 ? -errno
: -ENOMEM
;
513 n
= blkid_partlist_numof_partitions(pl
);
515 return errno
> 0 ? -errno
: -EIO
;
517 for (i
= 0; i
< n
; i
++) {
523 pp
= blkid_partlist_get_partition(pl
, i
);
525 return errno
> 0 ? -errno
: -EIO
;
527 if (!streq_ptr(blkid_partition_get_type_string(pp
), "773f91ef-66d4-49b5-bd83-d683bf40ad16"))
530 if (!streq_ptr(blkid_partition_get_name(pp
), label
))
533 sid
= blkid_partition_get_uuid(pp
);
535 r
= sd_id128_from_string(sid
, &id
);
537 log_debug_errno(r
, "Couldn't parse partition UUID %s, weird: %m", sid
);
539 if (!sd_id128_is_null(partition_uuid
) && !sd_id128_equal(id
, partition_uuid
))
546 offset
= blkid_partition_get_start(pp
);
547 size
= blkid_partition_get_size(pp
);
548 found_partition_uuid
= id
;
558 if ((uint64_t) offset
> UINT64_MAX
/ 512U)
562 if ((uint64_t) size
> UINT64_MAX
/ 512U)
565 *ret_offset
= offset
* 512U;
566 *ret_size
= size
* 512U;
567 *ret_partition_uuid
= found_partition_uuid
;
572 static int crypt_device_to_evp_cipher(struct crypt_device
*cd
, const EVP_CIPHER
**ret
) {
573 _cleanup_free_
char *cipher_name
= NULL
;
574 const char *cipher
, *cipher_mode
, *e
;
575 size_t key_size
, key_bits
;
576 const EVP_CIPHER
*cc
;
581 /* Let's find the right OpenSSL EVP_CIPHER object that matches the encryption settings of the LUKS
584 cipher
= crypt_get_cipher(cd
);
586 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot get cipher from LUKS device.");
588 cipher_mode
= crypt_get_cipher_mode(cd
);
590 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot get cipher mode from LUKS device.");
592 e
= strchr(cipher_mode
, '-');
594 cipher_mode
= strndupa(cipher_mode
, e
- cipher_mode
);
596 r
= crypt_get_volume_key_size(cd
);
598 return log_error_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(EINVAL
), "Cannot get volume key size from LUKS device.");
601 key_bits
= key_size
* 8;
602 if (streq(cipher_mode
, "xts"))
605 if (asprintf(&cipher_name
, "%s-%zu-%s", cipher
, key_bits
, cipher_mode
) < 0)
608 cc
= EVP_get_cipherbyname(cipher_name
);
610 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Selected cipher mode '%s' not supported, can't encrypt JSON record.", cipher_name
);
612 /* Verify that our key length calculations match what OpenSSL thinks */
613 r
= EVP_CIPHER_key_length(cc
);
614 if (r
< 0 || (uint64_t) r
!= key_size
)
615 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Key size of selected cipher doesn't meet our expectations.");
621 static int luks_validate_home_record(
622 struct crypt_device
*cd
,
624 const void *volume_key
,
625 char ***pkcs11_decrypted_passwords
,
626 UserRecord
**ret_luks_home_record
) {
633 for (token
= 0;; token
++) {
634 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
, *rr
= NULL
;
635 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
636 _cleanup_(user_record_unrefp
) UserRecord
*lhr
= NULL
;
637 _cleanup_free_
void *encrypted
= NULL
, *iv
= NULL
;
638 size_t decrypted_size
, encrypted_size
, iv_size
;
639 int decrypted_size_out1
, decrypted_size_out2
;
640 _cleanup_free_
char *decrypted
= NULL
;
641 const char *text
, *type
;
642 crypt_token_info state
;
643 JsonVariant
*jr
, *jiv
;
644 unsigned line
, column
;
645 const EVP_CIPHER
*cc
;
647 state
= crypt_token_status(cd
, token
, &type
);
648 if (state
== CRYPT_TOKEN_INACTIVE
) /* First unconfigured token, give up */
650 if (IN_SET(state
, CRYPT_TOKEN_INTERNAL
, CRYPT_TOKEN_INTERNAL_UNKNOWN
, CRYPT_TOKEN_EXTERNAL
))
652 if (state
!= CRYPT_TOKEN_EXTERNAL_UNKNOWN
)
653 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected token state of token %i: %i", token
, (int) state
);
655 if (!streq(type
, "systemd-homed"))
658 r
= crypt_token_json_get(cd
, token
, &text
);
660 return log_error_errno(r
, "Failed to read LUKS token %i: %m", token
);
662 r
= json_parse(text
, JSON_PARSE_SENSITIVE
, &v
, &line
, &column
);
664 return log_error_errno(r
, "Failed to parse LUKS token JSON data %u:%u: %m", line
, column
);
666 jr
= json_variant_by_key(v
, "record");
668 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "LUKS token lacks 'record' field.");
669 jiv
= json_variant_by_key(v
, "iv");
671 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "LUKS token lacks 'iv' field.");
673 r
= json_variant_unbase64(jr
, &encrypted
, &encrypted_size
);
675 return log_error_errno(r
, "Failed to base64 decode record: %m");
677 r
= json_variant_unbase64(jiv
, &iv
, &iv_size
);
679 return log_error_errno(r
, "Failed to base64 decode IV: %m");
681 r
= crypt_device_to_evp_cipher(cd
, &cc
);
684 if (iv_size
> INT_MAX
|| EVP_CIPHER_iv_length(cc
) != (int) iv_size
)
685 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "IV size doesn't match.");
687 context
= EVP_CIPHER_CTX_new();
691 if (EVP_DecryptInit_ex(context
, cc
, NULL
, volume_key
, iv
) != 1)
692 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize decryption context.");
694 decrypted_size
= encrypted_size
+ EVP_CIPHER_key_length(cc
) * 2;
695 decrypted
= new(char, decrypted_size
);
699 if (EVP_DecryptUpdate(context
, (uint8_t*) decrypted
, &decrypted_size_out1
, encrypted
, encrypted_size
) != 1)
700 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to decrypt JSON record.");
702 assert((size_t) decrypted_size_out1
<= decrypted_size
);
704 if (EVP_DecryptFinal_ex(context
, (uint8_t*) decrypted
+ decrypted_size_out1
, &decrypted_size_out2
) != 1)
705 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finish decryption of JSON record.");
707 assert((size_t) decrypted_size_out1
+ (size_t) decrypted_size_out2
< decrypted_size
);
708 decrypted_size
= (size_t) decrypted_size_out1
+ (size_t) decrypted_size_out2
;
710 if (memchr(decrypted
, 0, decrypted_size
))
711 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Inner NUL byte in JSON record, refusing.");
713 decrypted
[decrypted_size
] = 0;
715 r
= json_parse(decrypted
, JSON_PARSE_SENSITIVE
, &rr
, NULL
, NULL
);
717 return log_error_errno(r
, "Failed to parse decrypted JSON record, refusing.");
719 lhr
= user_record_new();
723 r
= user_record_load(lhr
, rr
, USER_RECORD_LOAD_EMBEDDED
);
725 return log_error_errno(r
, "Failed to parse user record: %m");
727 if (!user_record_compatible(h
, lhr
))
728 return log_error_errno(SYNTHETIC_ERRNO(EREMCHG
), "LUKS home record not compatible with host record, refusing.");
730 r
= user_record_authenticate(lhr
, h
, pkcs11_decrypted_passwords
, /* strict_verify= */ true);
733 assert(r
> 0); /* Insist that a password was verified */
735 *ret_luks_home_record
= TAKE_PTR(lhr
);
739 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Couldn't find home record in LUKS2 header, refusing.");
742 static int format_luks_token_text(
743 struct crypt_device
*cd
,
745 const void *volume_key
,
748 int r
, encrypted_size_out1
= 0, encrypted_size_out2
= 0, iv_size
, key_size
;
749 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
750 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
751 _cleanup_free_
void *iv
= NULL
, *encrypted
= NULL
;
752 size_t text_length
, encrypted_size
;
753 _cleanup_free_
char *text
= NULL
;
754 const EVP_CIPHER
*cc
;
761 r
= crypt_device_to_evp_cipher(cd
, &cc
);
765 key_size
= EVP_CIPHER_key_length(cc
);
766 iv_size
= EVP_CIPHER_iv_length(cc
);
769 iv
= malloc(iv_size
);
773 r
= genuine_random_bytes(iv
, iv_size
, RANDOM_BLOCK
);
775 return log_error_errno(r
, "Failed to generate IV: %m");
778 context
= EVP_CIPHER_CTX_new();
782 if (EVP_EncryptInit_ex(context
, cc
, NULL
, volume_key
, iv
) != 1)
783 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize encryption context.");
785 r
= json_variant_format(hr
->json
, 0, &text
);
787 return log_error_errno(r
, "Failed to format user record for LUKS: %m");
789 text_length
= strlen(text
);
790 encrypted_size
= text_length
+ 2*key_size
- 1;
792 encrypted
= malloc(encrypted_size
);
796 if (EVP_EncryptUpdate(context
, encrypted
, &encrypted_size_out1
, (uint8_t*) text
, text_length
) != 1)
797 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to encrypt JSON record.");
799 assert((size_t) encrypted_size_out1
<= encrypted_size
);
801 if (EVP_EncryptFinal_ex(context
, (uint8_t*) encrypted
+ encrypted_size_out1
, &encrypted_size_out2
) != 1)
802 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finish encryption of JSON record. ");
804 assert((size_t) encrypted_size_out1
+ (size_t) encrypted_size_out2
<= encrypted_size
);
808 JSON_BUILD_PAIR("type", JSON_BUILD_STRING("systemd-homed")),
809 JSON_BUILD_PAIR("keyslots", JSON_BUILD_EMPTY_ARRAY
),
810 JSON_BUILD_PAIR("record", JSON_BUILD_BASE64(encrypted
, encrypted_size_out1
+ encrypted_size_out2
)),
811 JSON_BUILD_PAIR("iv", JSON_BUILD_BASE64(iv
, iv_size
))));
813 return log_error_errno(r
, "Failed to prepare LUKS JSON token object: %m");
815 r
= json_variant_format(v
, 0, ret
);
817 return log_error_errno(r
, "Failed to format encrypted user record for LUKS: %m");
822 int home_store_header_identity_luks(
825 UserRecord
*old_home
) {
827 _cleanup_(user_record_unrefp
) UserRecord
*header_home
= NULL
;
828 _cleanup_free_
char *text
= NULL
;
833 if (!setup
->crypt_device
)
836 assert(setup
->volume_key
);
838 /* Let's store the user's identity record in the LUKS2 "token" header data fields, in an encrypted
839 * fashion. Why that? If we'd rely on the record being embedded in the payload file system itself we
840 * would have to mount the file system before we can validate the JSON record, its signatures and
841 * whether it matches what we are looking for. However, kernel file system implementations are
842 * generally not ready to be used on untrusted media. Hence let's store the record independently of
843 * the file system, so that we can validate it first, and only then mount the file system. To keep
844 * things simple we use the same encryption settings for this record as for the file system itself. */
846 r
= user_record_clone(h
, USER_RECORD_EXTRACT_EMBEDDED
, &header_home
);
848 return log_error_errno(r
, "Failed to determine new header record: %m");
850 if (old_home
&& user_record_equal(old_home
, header_home
)) {
851 log_debug("Not updating header home record.");
855 r
= format_luks_token_text(setup
->crypt_device
, header_home
, setup
->volume_key
, &text
);
860 crypt_token_info state
;
863 state
= crypt_token_status(setup
->crypt_device
, token
, &type
);
864 if (state
== CRYPT_TOKEN_INACTIVE
) /* First unconfigured token, we are done */
866 if (IN_SET(state
, CRYPT_TOKEN_INTERNAL
, CRYPT_TOKEN_INTERNAL_UNKNOWN
, CRYPT_TOKEN_EXTERNAL
))
867 continue; /* Not ours */
868 if (state
!= CRYPT_TOKEN_EXTERNAL_UNKNOWN
)
869 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected token state of token %i: %i", token
, (int) state
);
871 if (!streq(type
, "systemd-homed"))
874 r
= crypt_token_json_set(setup
->crypt_device
, token
, text
);
876 return log_error_errno(r
, "Failed to set JSON token for slot %i: %m", token
);
878 /* Now, let's free the text so that for all further matching tokens we all crypt_json_token_set()
879 * with a NULL text in order to invalidate the tokens. */
885 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Didn't find any record token to update.");
887 log_info("Wrote LUKS header user record.");
892 int run_fitrim(int root_fd
) {
893 char buf
[FORMAT_BYTES_MAX
];
894 struct fstrim_range range
= {
898 /* If discarding is on, discard everything right after mounting, so that the discard setting takes
899 * effect on activation. (Also, optionally, trim on logout) */
901 assert(root_fd
>= 0);
903 if (ioctl(root_fd
, FITRIM
, &range
) < 0) {
904 if (ERRNO_IS_NOT_SUPPORTED(errno
) || errno
== EBADF
) {
905 log_debug_errno(errno
, "File system does not support FITRIM, not trimming.");
909 return log_warning_errno(errno
, "Failed to invoke FITRIM, ignoring: %m");
912 log_info("Discarded unused %s.",
913 format_bytes(buf
, sizeof(buf
), range
.len
));
917 int run_fitrim_by_path(const char *root_path
) {
918 _cleanup_close_
int root_fd
= -1;
920 root_fd
= open(root_path
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
);
922 return log_error_errno(errno
, "Failed to open file system '%s' for trimming: %m", root_path
);
924 return run_fitrim(root_fd
);
927 int run_fallocate(int backing_fd
, const struct stat
*st
) {
928 char buf
[FORMAT_BYTES_MAX
];
931 assert(backing_fd
>= 0);
933 /* If discarding is off, let's allocate the whole image before mounting, so that the setting takes
934 * effect on activation */
937 if (fstat(backing_fd
, &stbuf
) < 0)
938 return log_error_errno(errno
, "Failed to fstat(): %m");
943 if (!S_ISREG(st
->st_mode
))
946 if (st
->st_blocks
>= DIV_ROUND_UP(st
->st_size
, 512)) {
947 log_info("Backing file is fully allocated already.");
951 if (fallocate(backing_fd
, FALLOC_FL_KEEP_SIZE
, 0, st
->st_size
) < 0) {
953 if (ERRNO_IS_NOT_SUPPORTED(errno
)) {
954 log_debug_errno(errno
, "fallocate() not supported on file system, ignoring.");
958 if (ERRNO_IS_DISK_SPACE(errno
)) {
959 log_debug_errno(errno
, "Not enough disk space to fully allocate home.");
960 return -ENOSPC
; /* make recognizable */
963 return log_error_errno(errno
, "Failed to allocate backing file blocks: %m");
966 log_info("Allocated additional %s.",
967 format_bytes(buf
, sizeof(buf
), (DIV_ROUND_UP(st
->st_size
, 512) - st
->st_blocks
) * 512));
971 int run_fallocate_by_path(const char *backing_path
) {
972 _cleanup_close_
int backing_fd
= -1;
974 backing_fd
= open(backing_path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
976 return log_error_errno(errno
, "Failed to open '%s' for fallocate(): %m", backing_path
);
978 return run_fallocate(backing_fd
, NULL
);
981 int home_prepare_luks(
983 bool already_activated
,
984 const char *force_image_path
,
985 char ***pkcs11_decrypted_passwords
,
987 UserRecord
**ret_luks_home
) {
989 sd_id128_t found_partition_uuid
, found_luks_uuid
, found_fs_uuid
;
990 _cleanup_(user_record_unrefp
) UserRecord
*luks_home
= NULL
;
991 _cleanup_(loop_device_unrefp
) LoopDevice
*loop
= NULL
;
992 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
993 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
994 bool dm_activated
= false, mounted
= false;
995 _cleanup_close_
int root_fd
= -1;
996 size_t volume_key_size
= 0;
997 uint64_t offset
, size
;
1002 assert(setup
->dm_name
);
1003 assert(setup
->dm_node
);
1005 assert(user_record_storage(h
) == USER_LUKS
);
1007 if (already_activated
) {
1008 struct loop_info64 info
;
1011 r
= luks_open(setup
->dm_name
,
1013 pkcs11_decrypted_passwords
? *pkcs11_decrypted_passwords
: NULL
,
1021 r
= luks_validate_home_record(cd
, h
, volume_key
, pkcs11_decrypted_passwords
, &luks_home
);
1025 n
= crypt_get_device_name(cd
);
1027 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine backing device for DM %s.", setup
->dm_name
);
1029 r
= loop_device_open(n
, O_RDWR
, &loop
);
1031 return log_error_errno(r
, "Failed to open loopback device %s: %m", n
);
1033 if (ioctl(loop
->fd
, LOOP_GET_STATUS64
, &info
) < 0) {
1034 _cleanup_free_
char *sysfs
= NULL
;
1037 if (!IN_SET(errno
, ENOTTY
, EINVAL
))
1038 return log_error_errno(errno
, "Failed to get block device metrics of %s: %m", n
);
1040 if (ioctl(loop
->fd
, BLKGETSIZE64
, &size
) < 0)
1041 return log_error_errno(r
, "Failed to read block device size of %s: %m", n
);
1043 if (fstat(loop
->fd
, &st
) < 0)
1044 return log_error_errno(r
, "Failed to stat block device %s: %m", n
);
1045 assert(S_ISBLK(st
.st_mode
));
1047 if (asprintf(&sysfs
, "/sys/dev/block/%u:%u/partition", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
1050 if (access(sysfs
, F_OK
) < 0) {
1051 if (errno
!= ENOENT
)
1052 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", sysfs
);
1056 _cleanup_free_
char *buffer
= NULL
;
1058 if (asprintf(&sysfs
, "/sys/dev/block/%u:%u/start", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
1061 r
= read_one_line_file(sysfs
, &buffer
);
1063 return log_error_errno(r
, "Failed to read partition start offset: %m");
1065 r
= safe_atou64(buffer
, &offset
);
1067 return log_error_errno(r
, "Failed to parse partition start offset: %m");
1069 if (offset
> UINT64_MAX
/ 512U)
1070 return log_error_errno(SYNTHETIC_ERRNO(E2BIG
), "Offset too large for 64 byte range, refusing.");
1075 offset
= info
.lo_offset
;
1076 size
= info
.lo_sizelimit
;
1079 found_partition_uuid
= found_fs_uuid
= SD_ID128_NULL
;
1081 log_info("Discovered used loopback device %s.", loop
->node
);
1083 root_fd
= open(user_record_home_directory(h
), O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
1085 r
= log_error_errno(r
, "Failed to open home directory: %m");
1089 _cleanup_free_
char *fstype
= NULL
, *subdir
= NULL
;
1090 _cleanup_close_
int fd
= -1;
1094 ip
= force_image_path
?: user_record_image_path(h
);
1096 subdir
= path_join("/run/systemd/user-home-mount/", user_record_user_name_and_realm(h
));
1100 fd
= open(ip
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
1102 return log_error_errno(errno
, "Failed to open image file %s: %m", ip
);
1104 if (fstat(fd
, &st
) < 0)
1105 return log_error_errno(errno
, "Failed to fstat() image file: %m");
1106 if (!S_ISREG(st
.st_mode
) && !S_ISBLK(st
.st_mode
))
1107 return log_error_errno(errno
, "Image file %s is not a regular file or block device: %m", ip
);
1109 r
= luks_validate(fd
, user_record_user_name_and_realm(h
), h
->partition_uuid
, &found_partition_uuid
, &offset
, &size
);
1111 return log_error_errno(r
, "Failed to validate disk label: %m");
1113 if (!user_record_luks_discard(h
)) {
1114 r
= run_fallocate(fd
, &st
);
1119 r
= loop_device_make(fd
, O_RDWR
, offset
, size
, 0, &loop
);
1121 log_error_errno(r
, "Loopback block device support is not available on this system.");
1122 return -ENOLINK
; /* make recognizable */
1125 return log_error_errno(r
, "Failed to allocate loopback context: %m");
1127 log_info("Setting up loopback device %s completed.", loop
->node
?: ip
);
1129 r
= luks_setup(loop
->node
?: ip
,
1133 h
->luks_cipher_mode
,
1134 h
->luks_volume_key_size
,
1136 pkcs11_decrypted_passwords
? *pkcs11_decrypted_passwords
: NULL
,
1137 user_record_luks_discard(h
) || user_record_luks_offline_discard(h
),
1145 dm_activated
= true;
1147 r
= luks_validate_home_record(cd
, h
, volume_key
, pkcs11_decrypted_passwords
, &luks_home
);
1151 r
= fs_validate(setup
->dm_node
, h
->file_system_uuid
, &fstype
, &found_fs_uuid
);
1155 r
= run_fsck(setup
->dm_node
, fstype
);
1159 r
= home_unshare_and_mount(setup
->dm_node
, fstype
, user_record_luks_discard(h
), user_record_mount_flags(h
));
1165 root_fd
= open(subdir
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
1167 r
= log_error_errno(r
, "Failed to open home directory: %m");
1171 if (user_record_luks_discard(h
))
1172 (void) run_fitrim(root_fd
);
1174 setup
->image_fd
= TAKE_FD(fd
);
1175 setup
->do_offline_fallocate
= !(setup
->do_offline_fitrim
= user_record_luks_offline_discard(h
));
1178 setup
->loop
= TAKE_PTR(loop
);
1179 setup
->crypt_device
= TAKE_PTR(cd
);
1180 setup
->root_fd
= TAKE_FD(root_fd
);
1181 setup
->found_partition_uuid
= found_partition_uuid
;
1182 setup
->found_luks_uuid
= found_luks_uuid
;
1183 setup
->found_fs_uuid
= found_fs_uuid
;
1184 setup
->partition_offset
= offset
;
1185 setup
->partition_size
= size
;
1186 setup
->volume_key
= TAKE_PTR(volume_key
);
1187 setup
->volume_key_size
= volume_key_size
;
1189 setup
->undo_mount
= mounted
;
1190 setup
->undo_dm
= dm_activated
;
1193 *ret_luks_home
= TAKE_PTR(luks_home
);
1199 (void) umount_verbose("/run/systemd/user-home-mount");
1202 (void) crypt_deactivate(cd
, setup
->dm_name
);
1207 static void print_size_summary(uint64_t host_size
, uint64_t encrypted_size
, struct statfs
*sfs
) {
1208 char buffer1
[FORMAT_BYTES_MAX
], buffer2
[FORMAT_BYTES_MAX
], buffer3
[FORMAT_BYTES_MAX
], buffer4
[FORMAT_BYTES_MAX
];
1212 log_info("Image size is %s, file system size is %s, file system payload size is %s, file system free is %s.",
1213 format_bytes(buffer1
, sizeof(buffer1
), host_size
),
1214 format_bytes(buffer2
, sizeof(buffer2
), encrypted_size
),
1215 format_bytes(buffer3
, sizeof(buffer3
), (uint64_t) sfs
->f_blocks
* (uint64_t) sfs
->f_frsize
),
1216 format_bytes(buffer4
, sizeof(buffer4
), (uint64_t) sfs
->f_bfree
* (uint64_t) sfs
->f_frsize
));
1219 int home_activate_luks(
1221 char ***pkcs11_decrypted_passwords
,
1222 UserRecord
**ret_home
) {
1224 _cleanup_(user_record_unrefp
) UserRecord
*new_home
= NULL
, *luks_home_record
= NULL
;
1225 _cleanup_(home_setup_undo
) HomeSetup setup
= HOME_SETUP_INIT
;
1226 uint64_t host_size
, encrypted_size
;
1227 const char *hdo
, *hd
;
1232 assert(user_record_storage(h
) == USER_LUKS
);
1235 assert_se(hdo
= user_record_home_directory(h
));
1236 hd
= strdupa(hdo
); /* copy the string out, since it might change later in the home record object */
1238 r
= make_dm_names(h
->user_name
, &setup
.dm_name
, &setup
.dm_node
);
1242 r
= access(setup
.dm_node
, F_OK
);
1244 if (errno
!= ENOENT
)
1245 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", setup
.dm_node
);
1247 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "Device mapper device %s already exists, refusing.", setup
.dm_node
);
1249 r
= home_prepare_luks(
1253 pkcs11_decrypted_passwords
,
1259 r
= block_get_size_by_fd(setup
.loop
->fd
, &host_size
);
1261 return log_error_errno(r
, "Failed to get loopback block device size: %m");
1263 r
= block_get_size_by_path(setup
.dm_node
, &encrypted_size
);
1265 return log_error_errno(r
, "Failed to get LUKS block device size: %m");
1271 pkcs11_decrypted_passwords
,
1277 r
= home_extend_embedded_identity(new_home
, h
, &setup
);
1281 setup
.root_fd
= safe_close(setup
.root_fd
);
1283 r
= home_move_mount(user_record_user_name_and_realm(h
), hd
);
1287 setup
.undo_mount
= false;
1288 setup
.do_offline_fitrim
= false;
1290 loop_device_relinquish(setup
.loop
);
1292 r
= dm_deferred_remove(setup
.dm_name
);
1294 log_warning_errno(r
, "Failed to relinquish DM device, ignoring: %m");
1296 setup
.undo_dm
= false;
1297 setup
.do_offline_fallocate
= false;
1299 log_info("Everything completed.");
1301 print_size_summary(host_size
, encrypted_size
, &sfs
);
1303 *ret_home
= TAKE_PTR(new_home
);
1307 int home_deactivate_luks(UserRecord
*h
) {
1308 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1309 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
1313 /* Note that the DM device and loopback device are set to auto-detach, hence strictly speaking we
1314 * don't have to explicitly have to detach them. However, we do that nonetheless (in case of the DM
1315 * device), to avoid races: by explicitly detaching them we know when the detaching is complete. We
1316 * don't bother about the loopback device because unlike the DM device it doesn't have a fixed
1319 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
1323 r
= crypt_init_by_name(&cd
, dm_name
);
1324 if (IN_SET(r
, -ENODEV
, -EINVAL
, -ENOENT
)) {
1325 log_debug_errno(r
, "LUKS device %s has already been detached.", dm_name
);
1326 we_detached
= false;
1328 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
1330 log_info("Discovered used LUKS device %s.", dm_node
);
1332 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
1334 r
= crypt_deactivate(cd
, dm_name
);
1335 if (IN_SET(r
, -ENODEV
, -EINVAL
, -ENOENT
)) {
1336 log_debug_errno(r
, "LUKS device %s is already detached.", dm_node
);
1337 we_detached
= false;
1339 return log_info_errno(r
, "LUKS device %s couldn't be deactivated: %m", dm_node
);
1341 log_info("LUKS device detaching completed.");
1346 if (user_record_luks_offline_discard(h
))
1347 log_debug("Not allocating on logout.");
1349 (void) run_fallocate_by_path(user_record_image_path(h
));
1354 int home_trim_luks(UserRecord
*h
) {
1357 if (!user_record_luks_offline_discard(h
)) {
1358 log_debug("Not trimming on logout.");
1362 (void) run_fitrim_by_path(user_record_home_directory(h
));
1366 static int run_mkfs(
1379 r
= mkfs_exists(fstype
);
1381 return log_error_errno(r
, "Failed to check if mkfs for file system %s exists: %m", fstype
);
1383 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "No mkfs for file system %s installed.", fstype
);
1385 r
= safe_fork("(mkfs)", FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_WAIT
|FORK_STDOUT_TO_STDERR
, NULL
);
1394 mkfs
= strjoina("mkfs.", fstype
);
1395 id128_to_uuid_string(uuid
, suuid
);
1397 if (streq(fstype
, "ext4"))
1402 "-O", "has_journal",
1404 "-E", discard
? "lazy_itable_init=1,discard" : "lazy_itable_init=1,nodiscard",
1406 else if (streq(fstype
, "btrfs")) {
1408 execlp(mkfs
, mkfs
, "-L", label
, "-U", suuid
, node
, NULL
);
1410 execlp(mkfs
, mkfs
, "-L", label
, "-U", suuid
, "--nodiscard", node
, NULL
);
1411 } else if (streq(fstype
, "xfs")) {
1414 j
= strjoina("uuid=", suuid
);
1416 execlp(mkfs
, mkfs
, "-L", label
, "-m", j
, "-m", "reflink=1", node
, NULL
);
1418 execlp(mkfs
, mkfs
, "-L", label
, "-m", j
, "-m", "reflink=1", "-K", node
, NULL
);
1420 log_error("Cannot make file system: %s", fstype
);
1421 _exit(EXIT_FAILURE
);
1424 log_error_errno(errno
, "Failed to execute %s: %m", mkfs
);
1425 _exit(EXIT_FAILURE
);
1431 static struct crypt_pbkdf_type
* build_good_pbkdf(struct crypt_pbkdf_type
*buffer
, UserRecord
*hr
) {
1435 *buffer
= (struct crypt_pbkdf_type
) {
1436 .hash
= user_record_luks_pbkdf_hash_algorithm(hr
),
1437 .type
= user_record_luks_pbkdf_type(hr
),
1438 .time_ms
= user_record_luks_pbkdf_time_cost_usec(hr
) / USEC_PER_MSEC
,
1439 .max_memory_kb
= user_record_luks_pbkdf_memory_cost(hr
) / 1024,
1440 .parallel_threads
= user_record_luks_pbkdf_parallel_threads(hr
),
1446 static struct crypt_pbkdf_type
* build_minimal_pbkdf(struct crypt_pbkdf_type
*buffer
, UserRecord
*hr
) {
1450 /* For PKCS#11 derived keys (which are generated randomly and are of high quality already) we use a
1452 *buffer
= (struct crypt_pbkdf_type
) {
1453 .hash
= user_record_luks_pbkdf_hash_algorithm(hr
),
1454 .type
= CRYPT_KDF_PBKDF2
,
1462 static int luks_format(
1464 const char *dm_name
,
1467 char **pkcs11_decrypted_passwords
,
1468 char **effective_passwords
,
1471 struct crypt_device
**ret
) {
1473 _cleanup_(user_record_unrefp
) UserRecord
*reduced
= NULL
;
1474 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1475 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
1476 struct crypt_pbkdf_type good_pbkdf
, minimal_pbkdf
;
1477 _cleanup_free_
char *text
= NULL
;
1478 size_t volume_key_size
;
1479 char suuid
[37], **pp
;
1487 r
= crypt_init(&cd
, node
);
1489 return log_error_errno(r
, "Failed to allocate libcryptsetup context: %m");
1491 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
1493 /* Normally we'd, just leave volume key generation to libcryptsetup. However, we can't, since we
1494 * can't extract the volume key from the library again, but we need it in order to encrypt the JSON
1495 * record. Hence, let's generate it on our own, so that we can keep track of it. */
1497 volume_key_size
= user_record_luks_volume_key_size(hr
);
1498 volume_key
= malloc(volume_key_size
);
1502 r
= genuine_random_bytes(volume_key
, volume_key_size
, RANDOM_BLOCK
);
1504 return log_error_errno(r
, "Failed to generate volume key: %m");
1506 #if HAVE_CRYPT_SET_METADATA_SIZE
1507 /* Increase the metadata space to 4M, the largest LUKS2 supports */
1508 r
= crypt_set_metadata_size(cd
, 4096U*1024U, 0);
1510 return log_error_errno(r
, "Failed to change LUKS2 metadata size: %m");
1513 build_good_pbkdf(&good_pbkdf
, hr
);
1514 build_minimal_pbkdf(&minimal_pbkdf
, hr
);
1516 r
= crypt_format(cd
,
1518 user_record_luks_cipher(hr
),
1519 user_record_luks_cipher_mode(hr
),
1520 id128_to_uuid_string(uuid
, suuid
),
1523 &(struct crypt_params_luks2
) {
1525 .subsystem
= "systemd-home",
1526 .sector_size
= 512U,
1527 .pbkdf
= &good_pbkdf
,
1530 return log_error_errno(r
, "Failed to format LUKS image: %m");
1532 log_info("LUKS formatting completed.");
1534 STRV_FOREACH(pp
, effective_passwords
) {
1536 if (strv_contains(pkcs11_decrypted_passwords
, *pp
)) {
1537 log_debug("Using minimal PBKDF for slot %i", slot
);
1538 r
= crypt_set_pbkdf_type(cd
, &minimal_pbkdf
);
1540 log_debug("Using good PBKDF for slot %i", slot
);
1541 r
= crypt_set_pbkdf_type(cd
, &good_pbkdf
);
1544 return log_error_errno(r
, "Failed to tweak PBKDF for slot %i: %m", slot
);
1546 r
= crypt_keyslot_add_by_volume_key(
1554 return log_error_errno(r
, "Failed to set up LUKS password for slot %i: %m", slot
);
1556 log_info("Writing password to LUKS keyslot %i completed.", slot
);
1560 r
= crypt_activate_by_volume_key(
1565 discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
1567 return log_error_errno(r
, "Failed to activate LUKS superblock: %m");
1569 log_info("LUKS activation by volume key succeeded.");
1571 r
= user_record_clone(hr
, USER_RECORD_EXTRACT_EMBEDDED
, &reduced
);
1573 return log_error_errno(r
, "Failed to prepare home record for LUKS: %m");
1575 r
= format_luks_token_text(cd
, reduced
, volume_key
, &text
);
1579 r
= crypt_token_json_set(cd
, CRYPT_ANY_TOKEN
, text
);
1581 return log_error_errno(r
, "Failed to set LUKS JSON token: %m");
1583 log_info("Writing user record as LUKS token completed.");
1586 *ret
= TAKE_PTR(cd
);
1591 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_context
*, fdisk_unref_context
);
1592 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_partition
*, fdisk_unref_partition
);
1593 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_parttype
*, fdisk_unref_parttype
);
1594 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_table
*, fdisk_unref_table
);
1596 static int make_partition_table(
1600 uint64_t *ret_offset
,
1602 sd_id128_t
*ret_disk_uuid
) {
1604 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*p
= NULL
, *q
= NULL
;
1605 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
1606 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1607 _cleanup_free_
char *path
= NULL
, *disk_uuid_as_string
= NULL
;
1608 uint64_t offset
, size
;
1609 sd_id128_t disk_uuid
;
1618 t
= fdisk_new_parttype();
1622 r
= fdisk_parttype_set_typestr(t
, "773f91ef-66d4-49b5-bd83-d683bf40ad16");
1624 return log_error_errno(r
, "Failed to initialize partition type: %m");
1626 c
= fdisk_new_context();
1630 if (asprintf(&path
, "/proc/self/fd/%i", fd
) < 0)
1633 r
= fdisk_assign_device(c
, path
, 0);
1635 return log_error_errno(r
, "Failed to open device: %m");
1637 r
= fdisk_create_disklabel(c
, "gpt");
1639 return log_error_errno(r
, "Failed to create GPT disk label: %m");
1641 p
= fdisk_new_partition();
1645 r
= fdisk_partition_set_type(p
, t
);
1647 return log_error_errno(r
, "Failed to set partition type: %m");
1649 r
= fdisk_partition_start_follow_default(p
, 1);
1651 return log_error_errno(r
, "Failed to place partition at beginning of space: %m");
1653 r
= fdisk_partition_partno_follow_default(p
, 1);
1655 return log_error_errno(r
, "Failed to place partition at first free partition index: %m");
1657 r
= fdisk_partition_end_follow_default(p
, 1);
1659 return log_error_errno(r
, "Failed to make partition cover all free space: %m");
1661 r
= fdisk_partition_set_name(p
, label
);
1663 return log_error_errno(r
, "Failed to set partition name: %m");
1665 r
= fdisk_partition_set_uuid(p
, id128_to_uuid_string(uuid
, uuids
));
1667 return log_error_errno(r
, "Failed to set partition UUID: %m");
1669 r
= fdisk_add_partition(c
, p
, NULL
);
1671 return log_error_errno(r
, "Failed to add partition: %m");
1673 r
= fdisk_write_disklabel(c
);
1675 return log_error_errno(r
, "Failed to write disk label: %m");
1677 r
= fdisk_get_disklabel_id(c
, &disk_uuid_as_string
);
1679 return log_error_errno(r
, "Failed to determine disk label UUID: %m");
1681 r
= sd_id128_from_string(disk_uuid_as_string
, &disk_uuid
);
1683 return log_error_errno(r
, "Failed to parse disk label UUID: %m");
1685 r
= fdisk_get_partition(c
, 0, &q
);
1687 return log_error_errno(r
, "Failed to read created partition metadata: %m");
1689 assert(fdisk_partition_has_start(q
));
1690 offset
= fdisk_partition_get_start(q
);
1691 if (offset
> UINT64_MAX
/ 512U)
1692 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Partition offset too large.");
1694 assert(fdisk_partition_has_size(q
));
1695 size
= fdisk_partition_get_size(q
);
1696 if (size
> UINT64_MAX
/ 512U)
1697 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Partition size too large.");
1699 *ret_offset
= offset
* 512U;
1700 *ret_size
= size
* 512U;
1701 *ret_disk_uuid
= disk_uuid
;
1706 static bool supported_fs_size(const char *fstype
, uint64_t host_size
) {
1709 m
= minimal_size_by_fs_name(fstype
);
1710 if (m
== UINT64_MAX
)
1713 return host_size
>= m
;
1716 static int wait_for_devlink(const char *path
) {
1717 _cleanup_close_
int inotify_fd
= -1;
1721 /* let's wait for a device link to show up in /dev, with a timeout. This is good to do since we
1722 * return a /dev/disk/by-uuid/… link to our callers and they likely want to access it right-away,
1723 * hence let's wait until udev has caught up with our changes, and wait for the symlink to be
1726 until
= usec_add(now(CLOCK_MONOTONIC
), 45 * USEC_PER_SEC
);
1729 _cleanup_free_
char *dn
= NULL
;
1732 if (laccess(path
, F_OK
) < 0) {
1733 if (errno
!= ENOENT
)
1734 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", path
);
1736 return 0; /* Found it */
1738 if (inotify_fd
< 0) {
1739 /* We need to wait for the device symlink to show up, let's create an inotify watch for it */
1740 inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
1742 return log_error_errno(errno
, "Failed to allocate inotify fd: %m");
1745 dn
= dirname_malloc(path
);
1750 log_info("Watching %s", dn
);
1752 if (inotify_add_watch(inotify_fd
, dn
, IN_CREATE
|IN_MOVED_TO
|IN_ONLYDIR
|IN_DELETE_SELF
|IN_MOVE_SELF
) < 0) {
1753 if (errno
!= ENOENT
)
1754 return log_error_errno(errno
, "Failed to add watch on %s: %m", dn
);
1758 if (empty_or_root(dn
))
1761 dn
= dirname_malloc(dn
);
1764 w
= now(CLOCK_MONOTONIC
);
1766 return log_error_errno(SYNTHETIC_ERRNO(ETIMEDOUT
), "Device link %s still hasn't shown up, giving up.", path
);
1768 r
= fd_wait_for_event(inotify_fd
, POLLIN
, usec_sub_unsigned(until
, w
));
1770 return log_error_errno(r
, "Failed to watch inotify: %m");
1772 (void) flush_fd(inotify_fd
);
1776 static int calculate_disk_size(UserRecord
*h
, const char *parent_dir
, uint64_t *ret
) {
1777 char buf
[FORMAT_BYTES_MAX
];
1785 if (h
->disk_size
!= UINT64_MAX
) {
1786 *ret
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
1790 if (statfs(parent_dir
, &sfs
) < 0)
1791 return log_error_errno(errno
, "statfs() on %s failed: %m", parent_dir
);
1793 m
= sfs
.f_bsize
* sfs
.f_bavail
;
1795 if (h
->disk_size_relative
== UINT64_MAX
) {
1797 if (m
> UINT64_MAX
/ USER_DISK_SIZE_DEFAULT_PERCENT
)
1798 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Disk size too large.");
1800 *ret
= DISK_SIZE_ROUND_DOWN(m
* USER_DISK_SIZE_DEFAULT_PERCENT
/ 100);
1802 log_info("Sizing home to %u%% of available disk space, which is %s.",
1803 USER_DISK_SIZE_DEFAULT_PERCENT
,
1804 format_bytes(buf
, sizeof(buf
), *ret
));
1806 *ret
= DISK_SIZE_ROUND_DOWN((uint64_t) ((double) m
* (double) h
->disk_size_relative
/ (double) UINT32_MAX
));
1808 log_info("Sizing home to %" PRIu64
".%01" PRIu64
"%% of available disk space, which is %s.",
1809 (h
->disk_size_relative
* 100) / UINT32_MAX
,
1810 ((h
->disk_size_relative
* 1000) / UINT32_MAX
) % 10,
1811 format_bytes(buf
, sizeof(buf
), *ret
));
1814 if (*ret
< USER_DISK_SIZE_MIN
)
1815 *ret
= USER_DISK_SIZE_MIN
;
1820 static int home_truncate(
1833 trunc
= user_record_luks_discard(h
);
1835 r
= fallocate(fd
, 0, 0, size
);
1836 if (r
< 0 && ERRNO_IS_NOT_SUPPORTED(errno
)) {
1837 /* Some file systems do not support fallocate(), let's gracefully degrade
1838 * (ZFS, reiserfs, …) and fall back to truncation */
1839 log_notice_errno(errno
, "Backing file system does not support fallocate(), falling back to ftruncate(), i.e. implicitly using non-discard mode.");
1845 r
= ftruncate(fd
, size
);
1848 if (ERRNO_IS_DISK_SPACE(errno
)) {
1849 log_error_errno(errno
, "Not enough disk space to allocate home.");
1850 return -ENOSPC
; /* make recognizable */
1853 return log_error_errno(errno
, "Failed to truncate home image %s: %m", path
);
1859 int home_create_luks(
1861 char **pkcs11_decrypted_passwords
,
1862 char **effective_passwords
,
1863 UserRecord
**ret_home
) {
1865 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
, *subdir
= NULL
, *disk_uuid_path
= NULL
, *temporary_image_path
= NULL
;
1866 uint64_t host_size
, encrypted_size
, partition_offset
, partition_size
;
1867 bool image_created
= false, dm_activated
= false, mounted
= false;
1868 _cleanup_(user_record_unrefp
) UserRecord
*new_home
= NULL
;
1869 sd_id128_t partition_uuid
, fs_uuid
, luks_uuid
, disk_uuid
;
1870 _cleanup_(loop_device_unrefp
) LoopDevice
*loop
= NULL
;
1871 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1872 _cleanup_close_
int image_fd
= -1, root_fd
= -1;
1873 const char *fstype
, *ip
;
1878 assert(h
->storage
< 0 || h
->storage
== USER_LUKS
);
1881 assert_se(ip
= user_record_image_path(h
));
1883 fstype
= user_record_file_system_type(h
);
1884 if (!supported_fstype(fstype
))
1885 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "Unsupported file system type: %s", h
->file_system_type
);
1887 if (sd_id128_is_null(h
->partition_uuid
)) {
1888 r
= sd_id128_randomize(&partition_uuid
);
1890 return log_error_errno(r
, "Failed to acquire partition UUID: %m");
1892 partition_uuid
= h
->partition_uuid
;
1894 if (sd_id128_is_null(h
->luks_uuid
)) {
1895 r
= sd_id128_randomize(&luks_uuid
);
1897 return log_error_errno(r
, "Failed to acquire LUKS UUID: %m");
1899 luks_uuid
= h
->luks_uuid
;
1901 if (sd_id128_is_null(h
->file_system_uuid
)) {
1902 r
= sd_id128_randomize(&fs_uuid
);
1904 return log_error_errno(r
, "Failed to acquire file system UUID: %m");
1906 fs_uuid
= h
->file_system_uuid
;
1908 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
1912 r
= access(dm_node
, F_OK
);
1914 if (errno
!= ENOENT
)
1915 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", dm_node
);
1917 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "Device mapper device %s already exists, refusing.", dm_node
);
1919 if (path_startswith(ip
, "/dev/")) {
1920 _cleanup_free_
char *sysfs
= NULL
;
1921 uint64_t block_device_size
;
1924 /* Let's place the home directory on a real device, i.e. an USB stick or such */
1926 image_fd
= open(ip
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
1928 return log_error_errno(errno
, "Failed to open device %s: %m", ip
);
1930 if (fstat(image_fd
, &st
) < 0)
1931 return log_error_errno(errno
, "Failed to stat device %s: %m", ip
);
1932 if (!S_ISBLK(st
.st_mode
))
1933 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Device is not a block device, refusing.");
1935 if (asprintf(&sysfs
, "/sys/dev/block/%u:%u/partition", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
1937 if (access(sysfs
, F_OK
) < 0) {
1938 if (errno
!= ENOENT
)
1939 return log_error_errno(errno
, "Failed to check whether %s exists: %m", sysfs
);
1941 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Operating on partitions is currently not supported, sorry. Please specify a top-level block device.");
1943 if (flock(image_fd
, LOCK_EX
) < 0) /* make sure udev doesn't read from it while we operate on the device */
1944 return log_error_errno(errno
, "Failed to lock block device %s: %m", ip
);
1946 if (ioctl(image_fd
, BLKGETSIZE64
, &block_device_size
) < 0)
1947 return log_error_errno(errno
, "Failed to read block device size: %m");
1949 if (h
->disk_size
== UINT64_MAX
) {
1951 /* If a relative disk size is requested, apply it relative to the block device size */
1952 if (h
->disk_size_relative
< UINT32_MAX
)
1953 host_size
= CLAMP(DISK_SIZE_ROUND_DOWN(block_device_size
* h
->disk_size_relative
/ UINT32_MAX
),
1954 USER_DISK_SIZE_MIN
, USER_DISK_SIZE_MAX
);
1956 host_size
= block_device_size
; /* Otherwise, take the full device */
1958 } else if (h
->disk_size
> block_device_size
)
1959 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE
), "Selected disk size larger than backing block device, refusing.");
1961 host_size
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
1963 if (!supported_fs_size(fstype
, host_size
))
1964 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Selected file system size too small for %s.", h
->file_system_type
);
1966 /* After creation we should reference this partition by its UUID instead of the block
1967 * device. That's preferable since the user might have specified a device node such as
1968 * /dev/sdb to us, which might look very different when replugged. */
1969 if (asprintf(&disk_uuid_path
, "/dev/disk/by-uuid/" SD_ID128_UUID_FORMAT_STR
, SD_ID128_FORMAT_VAL(luks_uuid
)) < 0)
1972 if (user_record_luks_discard(h
) || user_record_luks_offline_discard(h
)) {
1973 /* If we want online or offline discard, discard once before we start using things. */
1975 if (ioctl(image_fd
, BLKDISCARD
, (uint64_t[]) { 0, block_device_size
}) < 0)
1976 log_full_errno(errno
== EOPNOTSUPP
? LOG_DEBUG
: LOG_WARNING
, errno
,
1977 "Failed to issue full-device BLKDISCARD on device, ignoring: %m");
1979 log_info("Full device discard completed.");
1982 _cleanup_free_
char *parent
= NULL
;
1984 parent
= dirname_malloc(ip
);
1988 r
= mkdir_p(parent
, 0755);
1990 return log_error_errno(r
, "Failed to create parent directory %s: %m", parent
);
1992 r
= calculate_disk_size(h
, parent
, &host_size
);
1996 if (!supported_fs_size(fstype
, host_size
))
1997 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Selected file system size too small for %s.", h
->file_system_type
);
1999 r
= tempfn_random(ip
, "homework", &temporary_image_path
);
2001 return log_error_errno(r
, "Failed to derive temporary file name for %s: %m", ip
);
2003 image_fd
= open(temporary_image_path
, O_RDWR
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
2005 return log_error_errno(errno
, "Failed to create home image %s: %m", temporary_image_path
);
2007 image_created
= true;
2009 r
= chattr_fd(image_fd
, FS_NOCOW_FL
, FS_NOCOW_FL
, NULL
);
2011 log_warning_errno(r
, "Failed to set file attributes on %s, ignoring: %m", temporary_image_path
);
2013 r
= home_truncate(h
, image_fd
, temporary_image_path
, host_size
);
2017 log_info("Allocating image file completed.");
2020 r
= make_partition_table(
2022 user_record_user_name_and_realm(h
),
2030 log_info("Writing of partition table completed.");
2032 r
= loop_device_make(image_fd
, O_RDWR
, partition_offset
, partition_size
, 0, &loop
);
2034 if (r
== -ENOENT
) { /* this means /dev/loop-control doesn't exist, i.e. we are in a container
2035 * or similar and loopback bock devices are not available, return a
2036 * recognizable error in this case. */
2037 log_error_errno(r
, "Loopback block device support is not available on this system.");
2042 log_error_errno(r
, "Failed to set up loopback device for %s: %m", temporary_image_path
);
2046 r
= loop_device_flock(loop
, LOCK_EX
); /* make sure udev won't read before we are done */
2048 log_error_errno(r
, "Failed to take lock on loop device: %m");
2052 log_info("Setting up loopback device %s completed.", loop
->node
?: ip
);
2054 r
= luks_format(loop
->node
,
2057 user_record_user_name_and_realm(h
),
2058 pkcs11_decrypted_passwords
,
2059 effective_passwords
,
2060 user_record_luks_discard(h
) || user_record_luks_offline_discard(h
),
2066 dm_activated
= true;
2068 r
= block_get_size_by_path(dm_node
, &encrypted_size
);
2070 log_error_errno(r
, "Failed to get encrypted block device size: %m");
2074 log_info("Setting up LUKS device %s completed.", dm_node
);
2076 r
= run_mkfs(dm_node
, fstype
, user_record_user_name_and_realm(h
), fs_uuid
, user_record_luks_discard(h
));
2080 log_info("Formatting file system completed.");
2082 r
= home_unshare_and_mount(dm_node
, fstype
, user_record_luks_discard(h
), user_record_mount_flags(h
));
2088 subdir
= path_join("/run/systemd/user-home-mount/", user_record_user_name_and_realm(h
));
2094 /* Prefer using a btrfs subvolume if we can, fall back to directory otherwise */
2095 r
= btrfs_subvol_make_fallback(subdir
, 0700);
2097 log_error_errno(r
, "Failed to create user directory in mounted image file: %m");
2101 root_fd
= open(subdir
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
2103 r
= log_error_errno(errno
, "Failed to open user directory in mounted image file: %m");
2107 r
= home_populate(h
, root_fd
);
2111 r
= home_sync_and_statfs(root_fd
, &sfs
);
2115 r
= user_record_clone(h
, USER_RECORD_LOAD_MASK_SECRET
|USER_RECORD_LOG
, &new_home
);
2117 log_error_errno(r
, "Failed to clone record: %m");
2121 r
= user_record_add_binding(
2124 disk_uuid_path
?: ip
,
2128 crypt_get_cipher(cd
),
2129 crypt_get_cipher_mode(cd
),
2130 luks_volume_key_size_convert(cd
),
2136 log_error_errno(r
, "Failed to add binding to record: %m");
2140 if (user_record_luks_offline_discard(h
)) {
2141 r
= run_fitrim(root_fd
);
2146 root_fd
= safe_close(root_fd
);
2148 r
= umount_verbose("/run/systemd/user-home-mount");
2154 r
= crypt_deactivate(cd
, dm_name
);
2156 log_error_errno(r
, "Failed to deactivate LUKS device: %m");
2160 dm_activated
= false;
2162 loop
= loop_device_unref(loop
);
2164 if (!user_record_luks_offline_discard(h
)) {
2165 r
= run_fallocate(image_fd
, NULL
/* refresh stat() data */);
2171 (void) ioctl(image_fd
, BLKRRPART
, 0);
2173 /* Let's close the image fd now. If we are operating on a real block device this will release the BSD
2174 * lock that ensures udev doesn't interfere with what we are doing */
2175 image_fd
= safe_close(image_fd
);
2177 if (temporary_image_path
) {
2178 if (rename(temporary_image_path
, ip
) < 0) {
2179 log_error_errno(errno
, "Failed to rename image file: %m");
2183 log_info("Moved image file into place.");
2187 (void) wait_for_devlink(disk_uuid_path
);
2189 log_info("Everything completed.");
2191 print_size_summary(host_size
, encrypted_size
, &sfs
);
2193 *ret_home
= TAKE_PTR(new_home
);
2197 /* Let's close all files before we unmount the file system, to avoid EBUSY */
2198 root_fd
= safe_close(root_fd
);
2201 (void) umount_verbose("/run/systemd/user-home-mount");
2204 (void) crypt_deactivate(cd
, dm_name
);
2206 loop
= loop_device_unref(loop
);
2209 (void) unlink(temporary_image_path
);
2214 int home_validate_update_luks(UserRecord
*h
, HomeSetup
*setup
) {
2215 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
2221 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
2225 r
= access(dm_node
, F_OK
);
2226 if (r
< 0 && errno
!= ENOENT
)
2227 return log_error_errno(errno
, "Failed to determine whether %s exists: %m", dm_node
);
2229 free_and_replace(setup
->dm_name
, dm_name
);
2230 free_and_replace(setup
->dm_node
, dm_node
);
2240 static int can_resize_fs(int fd
, uint64_t old_size
, uint64_t new_size
) {
2245 /* Filter out bogus requests early */
2246 if (old_size
== 0 || old_size
== UINT64_MAX
||
2247 new_size
== 0 || new_size
== UINT64_MAX
)
2248 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid resize parameters.");
2250 if ((old_size
& 511) != 0 || (new_size
& 511) != 0)
2251 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Resize parameters not multiple of 512.");
2253 if (fstatfs(fd
, &sfs
) < 0)
2254 return log_error_errno(errno
, "Failed to fstatfs() file system: %m");
2256 if (is_fs_type(&sfs
, BTRFS_SUPER_MAGIC
)) {
2258 if (new_size
< BTRFS_MINIMAL_SIZE
)
2259 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for btrfs (needs to be 256M at least.");
2261 /* btrfs can grow and shrink online */
2263 } else if (is_fs_type(&sfs
, XFS_SB_MAGIC
)) {
2265 if (new_size
< XFS_MINIMAL_SIZE
)
2266 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for xfs (needs to be 14M at least).");
2268 /* XFS can grow, but not shrink */
2269 if (new_size
< old_size
)
2270 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE
), "Shrinking this type of file system is not supported.");
2272 } else if (is_fs_type(&sfs
, EXT4_SUPER_MAGIC
)) {
2274 if (new_size
< EXT4_MINIMAL_SIZE
)
2275 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "New file system size too small for ext4 (needs to be 1M at least).");
2277 /* ext4 can grow online, and shrink offline */
2278 if (new_size
< old_size
)
2279 return CAN_RESIZE_OFFLINE
;
2282 return log_error_errno(SYNTHETIC_ERRNO(ESOCKTNOSUPPORT
), "Resizing this type of file system is not supported.");
2284 return CAN_RESIZE_ONLINE
;
2287 static int ext4_offline_resize_fs(HomeSetup
*setup
, uint64_t new_size
, bool discard
, unsigned long flags
) {
2288 _cleanup_free_
char *size_str
= NULL
;
2289 bool re_open
= false, re_mount
= false;
2290 pid_t resize_pid
, fsck_pid
;
2294 assert(setup
->dm_node
);
2296 /* First, unmount the file system */
2297 if (setup
->root_fd
>= 0) {
2298 setup
->root_fd
= safe_close(setup
->root_fd
);
2302 if (setup
->undo_mount
) {
2303 r
= umount_verbose("/run/systemd/user-home-mount");
2307 setup
->undo_mount
= false;
2311 log_info("Temporary unmounting of file system completed.");
2313 /* resize2fs requires that the file system is force checked first, do so. */
2314 r
= safe_fork("(e2fsck)", FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_STDOUT_TO_STDERR
, &fsck_pid
);
2319 execlp("e2fsck" ,"e2fsck", "-fp", setup
->dm_node
, NULL
);
2320 log_error_errno(errno
, "Failed to execute e2fsck: %m");
2321 _exit(EXIT_FAILURE
);
2324 exit_status
= wait_for_terminate_and_check("e2fsck", fsck_pid
, WAIT_LOG_ABNORMAL
);
2325 if (exit_status
< 0)
2327 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != 0) {
2328 log_warning("e2fsck failed with exit status %i.", exit_status
);
2330 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
2331 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "File system is corrupted, refusing.");
2333 log_warning("Ignoring fsck error.");
2336 log_info("Forced file system check completed.");
2338 /* We use 512 sectors here, because resize2fs doesn't do byte sizes */
2339 if (asprintf(&size_str
, "%" PRIu64
"s", new_size
/ 512) < 0)
2342 /* Resize the thing */
2343 r
= safe_fork("(e2resize)", FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_LOG
|FORK_WAIT
|FORK_STDOUT_TO_STDERR
, &resize_pid
);
2348 execlp("resize2fs" ,"resize2fs", setup
->dm_node
, size_str
, NULL
);
2349 log_error_errno(errno
, "Failed to execute resize2fs: %m");
2350 _exit(EXIT_FAILURE
);
2353 log_info("Offline file system resize completed.");
2355 /* Re-establish mounts and reopen the directory */
2357 r
= home_mount_node(setup
->dm_node
, "ext4", discard
, flags
);
2361 setup
->undo_mount
= true;
2365 setup
->root_fd
= open("/run/systemd/user-home-mount", O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
2366 if (setup
->root_fd
< 0)
2367 return log_error_errno(errno
, "Failed to reopen file system: %m");
2370 log_info("File system mounted again.");
2375 static int prepare_resize_partition(
2377 uint64_t partition_offset
,
2378 uint64_t old_partition_size
,
2379 uint64_t new_partition_size
,
2380 sd_id128_t
*ret_disk_uuid
,
2381 struct fdisk_table
**ret_table
) {
2383 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2384 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
2385 _cleanup_free_
char *path
= NULL
, *disk_uuid_as_string
= NULL
;
2386 size_t n_partitions
, i
;
2387 sd_id128_t disk_uuid
;
2392 assert(ret_disk_uuid
);
2395 assert((partition_offset
& 511) == 0);
2396 assert((old_partition_size
& 511) == 0);
2397 assert((new_partition_size
& 511) == 0);
2398 assert(UINT64_MAX
- old_partition_size
>= partition_offset
);
2399 assert(UINT64_MAX
- new_partition_size
>= partition_offset
);
2401 if (partition_offset
== 0) {
2402 /* If the offset is at the beginning we assume no partition table, let's exit early. */
2403 log_debug("Not rewriting partition table, operating on naked device.");
2404 *ret_disk_uuid
= SD_ID128_NULL
;
2409 c
= fdisk_new_context();
2413 if (asprintf(&path
, "/proc/self/fd/%i", fd
) < 0)
2416 r
= fdisk_assign_device(c
, path
, 0);
2418 return log_error_errno(r
, "Failed to open device: %m");
2420 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2421 return log_error_errno(SYNTHETIC_ERRNO(ENOMEDIUM
), "Disk has no GPT partition table.");
2423 r
= fdisk_get_disklabel_id(c
, &disk_uuid_as_string
);
2425 return log_error_errno(r
, "Failed to acquire disk UUID: %m");
2427 r
= sd_id128_from_string(disk_uuid_as_string
, &disk_uuid
);
2429 return log_error_errno(r
, "Failed parse disk UUID: %m");
2431 r
= fdisk_get_partitions(c
, &t
);
2433 return log_error_errno(r
, "Failed to acquire partition table: %m");
2435 n_partitions
= fdisk_table_get_nents(t
);
2436 for (i
= 0; i
< n_partitions
; i
++) {
2437 struct fdisk_partition
*p
;
2439 p
= fdisk_table_get_partition(t
, i
);
2441 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
2443 if (fdisk_partition_is_used(p
) <= 0)
2445 if (fdisk_partition_has_start(p
) <= 0 || fdisk_partition_has_size(p
) <= 0 || fdisk_partition_has_end(p
) <= 0)
2446 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found partition without a size.");
2448 if (fdisk_partition_get_start(p
) == partition_offset
/ 512U &&
2449 fdisk_partition_get_size(p
) == old_partition_size
/ 512U) {
2452 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
), "Partition found twice, refusing.");
2454 /* Found our partition, now patch it */
2455 r
= fdisk_partition_size_explicit(p
, 1);
2457 return log_error_errno(r
, "Failed to enable explicit partition size: %m");
2459 r
= fdisk_partition_set_size(p
, new_partition_size
/ 512U);
2461 return log_error_errno(r
, "Failed to change partition size: %m");
2467 if (fdisk_partition_get_start(p
) < partition_offset
+ new_partition_size
/ 512U &&
2468 fdisk_partition_get_end(p
) >= partition_offset
/ 512)
2469 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Can't extend, conflicting partition found.");
2474 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to find matching partition to resize.");
2476 *ret_table
= TAKE_PTR(t
);
2477 *ret_disk_uuid
= disk_uuid
;
2482 static int ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *userdata
) {
2487 switch (fdisk_ask_get_type(ask
)) {
2489 case FDISK_ASKTYPE_STRING
:
2490 result
= new(char, 37);
2494 fdisk_ask_string_set_result(ask
, id128_to_uuid_string(*(sd_id128_t
*) userdata
, result
));
2498 log_debug("Unexpected question from libfdisk, ignoring.");
2504 static int apply_resize_partition(int fd
, sd_id128_t disk_uuids
, struct fdisk_table
*t
) {
2505 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2506 _cleanup_free_
void *two_zero_lbas
= NULL
;
2507 _cleanup_free_
char *path
= NULL
;
2513 if (!t
) /* no partition table to apply, exit early */
2516 two_zero_lbas
= malloc0(1024U);
2520 /* libfdisk appears to get confused by the existing PMBR. Let's explicitly flush it out. */
2521 n
= pwrite(fd
, two_zero_lbas
, 1024U, 0);
2523 return log_error_errno(errno
, "Failed to wipe partition table: %m");
2525 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Short write while wiping partition table.");
2527 c
= fdisk_new_context();
2531 if (asprintf(&path
, "/proc/self/fd/%i", fd
) < 0)
2534 r
= fdisk_assign_device(c
, path
, 0);
2536 return log_error_errno(r
, "Failed to open device: %m");
2538 r
= fdisk_create_disklabel(c
, "gpt");
2540 return log_error_errno(r
, "Failed to create GPT disk label: %m");
2542 r
= fdisk_apply_table(c
, t
);
2544 return log_error_errno(r
, "Failed to apply partition table: %m");
2546 r
= fdisk_set_ask(c
, ask_cb
, &disk_uuids
);
2548 return log_error_errno(r
, "Failed to set libfdisk query function: %m");
2550 r
= fdisk_set_disklabel_id(c
);
2552 return log_error_errno(r
, "Failed to change disklabel ID: %m");
2554 r
= fdisk_write_disklabel(c
);
2556 return log_error_errno(r
, "Failed to write disk label: %m");
2561 int home_resize_luks(
2563 bool already_activated
,
2564 char ***pkcs11_decrypted_passwords
,
2566 UserRecord
**ret_home
) {
2568 char buffer1
[FORMAT_BYTES_MAX
], buffer2
[FORMAT_BYTES_MAX
], buffer3
[FORMAT_BYTES_MAX
],
2569 buffer4
[FORMAT_BYTES_MAX
], buffer5
[FORMAT_BYTES_MAX
], buffer6
[FORMAT_BYTES_MAX
];
2570 uint64_t old_image_size
, new_image_size
, old_fs_size
, new_fs_size
, crypto_offset
, new_partition_size
;
2571 _cleanup_(user_record_unrefp
) UserRecord
*header_home
= NULL
, *embedded_home
= NULL
, *new_home
= NULL
;
2572 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*table
= NULL
;
2573 _cleanup_free_
char *whole_disk
= NULL
;
2574 _cleanup_close_
int image_fd
= -1;
2575 sd_id128_t disk_uuid
;
2576 const char *ip
, *ipo
;
2582 assert(user_record_storage(h
) == USER_LUKS
);
2586 assert_se(ipo
= user_record_image_path(h
));
2587 ip
= strdupa(ipo
); /* copy out since original might change later in home record object */
2589 image_fd
= open(ip
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
2591 return log_error_errno(errno
, "Failed to open image file %s: %m", ip
);
2593 if (fstat(image_fd
, &st
) < 0)
2594 return log_error_errno(errno
, "Failed to stat image file %s: %m", ip
);
2595 if (S_ISBLK(st
.st_mode
)) {
2598 r
= block_get_whole_disk(st
.st_rdev
, &parent
);
2600 return log_error_errno(r
, "Failed to acquire whole block device for %s: %m", ip
);
2602 /* If we shall resize a file system on a partition device, then let's figure out the
2603 * whole disk device and operate on that instead, since we need to rewrite the
2604 * partition table to resize the partition. */
2606 log_info("Operating on partition device %s, using parent device.", ip
);
2608 r
= device_path_make_major_minor(st
.st_mode
, parent
, &whole_disk
);
2610 return log_error_errno(r
, "Failed to derive whole disk path for %s: %m", ip
);
2612 safe_close(image_fd
);
2614 image_fd
= open(whole_disk
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
);
2616 return log_error_errno(errno
, "Failed to open whole block device %s: %m", whole_disk
);
2618 if (fstat(image_fd
, &st
) < 0)
2619 return log_error_errno(errno
, "Failed to stat whole block device %s: %m", whole_disk
);
2620 if (!S_ISBLK(st
.st_mode
))
2621 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
), "Whole block device %s is not actually a block device, refusing.", whole_disk
);
2623 log_info("Operating on whole block device %s.", ip
);
2625 if (ioctl(image_fd
, BLKGETSIZE64
, &old_image_size
) < 0)
2626 return log_error_errno(errno
, "Failed to determine size of original block device: %m");
2628 if (flock(image_fd
, LOCK_EX
) < 0) /* make sure udev doesn't read from it while we operate on the device */
2629 return log_error_errno(errno
, "Failed to lock block device %s: %m", ip
);
2631 new_image_size
= old_image_size
; /* we can't resize physical block devices */
2633 r
= stat_verify_regular(&st
);
2635 return log_error_errno(r
, "Image %s is not a block device nor regular file: %m", ip
);
2637 old_image_size
= st
.st_size
;
2639 /* Note an asymetry here: when we operate on loopback files the specified disk size we get we
2640 * apply onto the loopback file as a whole. When we operate on block devices we instead apply
2641 * to the partition itself only. */
2643 new_image_size
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
2644 if (new_image_size
== old_image_size
) {
2645 log_info("Image size already matching, skipping operation.");
2650 r
= home_prepare_luks(h
, already_activated
, whole_disk
, pkcs11_decrypted_passwords
, setup
, &header_home
);
2654 r
= home_load_embedded_identity(h
, setup
->root_fd
, header_home
, USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL
, pkcs11_decrypted_passwords
, &embedded_home
, &new_home
);
2658 log_info("offset = %" PRIu64
", size = %" PRIu64
", image = %" PRIu64
, setup
->partition_offset
, setup
->partition_size
, old_image_size
);
2660 if ((UINT64_MAX
- setup
->partition_offset
) < setup
->partition_size
||
2661 setup
->partition_offset
+ setup
->partition_size
> old_image_size
)
2662 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Old partition doesn't fit in backing storage, refusing.");
2664 if (S_ISREG(st
.st_mode
)) {
2665 uint64_t partition_table_extra
;
2667 partition_table_extra
= old_image_size
- setup
->partition_size
;
2668 if (new_image_size
<= partition_table_extra
)
2669 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "New size smaller than partition table metadata.");
2671 new_partition_size
= new_image_size
- partition_table_extra
;
2673 assert(S_ISBLK(st
.st_mode
));
2675 new_partition_size
= DISK_SIZE_ROUND_DOWN(h
->disk_size
);
2676 if (new_partition_size
== setup
->partition_size
) {
2677 log_info("Partition size already matching, skipping operation.");
2682 if ((UINT64_MAX
- setup
->partition_offset
) < new_partition_size
||
2683 setup
->partition_offset
+ new_partition_size
> new_image_size
)
2684 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "New partition doesn't fit into backing storage, refusing.");
2686 crypto_offset
= crypt_get_data_offset(setup
->crypt_device
);
2687 if (setup
->partition_size
/ 512U <= crypto_offset
)
2688 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Weird, old crypto payload offset doesn't actually fit in partition size?");
2689 if (new_partition_size
/ 512U <= crypto_offset
)
2690 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "New size smaller than crypto payload offset?");
2692 old_fs_size
= (setup
->partition_size
/ 512U - crypto_offset
) * 512U;
2693 new_fs_size
= (new_partition_size
/ 512U - crypto_offset
) * 512U;
2695 /* Before we start doing anything, let's figure out if we actually can */
2696 resize_type
= can_resize_fs(setup
->root_fd
, old_fs_size
, new_fs_size
);
2697 if (resize_type
< 0)
2699 if (resize_type
== CAN_RESIZE_OFFLINE
&& already_activated
)
2700 return log_error_errno(SYNTHETIC_ERRNO(ETXTBSY
), "File systems of this type can only be resized offline, but is currently online.");
2702 log_info("Ready to resize image size %s → %s, partition size %s → %s, file system size %s → %s.",
2703 format_bytes(buffer1
, sizeof(buffer1
), old_image_size
),
2704 format_bytes(buffer2
, sizeof(buffer2
), new_image_size
),
2705 format_bytes(buffer3
, sizeof(buffer3
), setup
->partition_size
),
2706 format_bytes(buffer4
, sizeof(buffer4
), new_partition_size
),
2707 format_bytes(buffer5
, sizeof(buffer5
), old_fs_size
),
2708 format_bytes(buffer6
, sizeof(buffer6
), new_fs_size
));
2710 r
= prepare_resize_partition(
2712 setup
->partition_offset
,
2713 setup
->partition_size
,
2720 if (new_fs_size
> old_fs_size
) {
2722 if (S_ISREG(st
.st_mode
)) {
2723 /* Grow file size */
2724 r
= home_truncate(h
, image_fd
, ip
, new_image_size
);
2728 log_info("Growing of image file completed.");
2731 /* Make sure loopback device sees the new bigger size */
2732 r
= loop_device_refresh_size(setup
->loop
, UINT64_MAX
, new_partition_size
);
2734 log_debug_errno(r
, "Device is not a loopback device, not refreshing size.");
2736 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
2738 log_info("Refreshing loop device size completed.");
2740 r
= apply_resize_partition(image_fd
, disk_uuid
, table
);
2744 log_info("Growing of partition completed.");
2746 if (ioctl(image_fd
, BLKRRPART
, 0) < 0)
2747 log_debug_errno(errno
, "BLKRRPART failed on block device, ignoring: %m");
2749 /* Tell LUKS about the new bigger size too */
2750 r
= crypt_resize(setup
->crypt_device
, setup
->dm_name
, new_fs_size
/ 512U);
2752 return log_error_errno(r
, "Failed to grow LUKS device: %m");
2754 log_info("LUKS device growing completed.");
2756 r
= home_store_embedded_identity(new_home
, setup
->root_fd
, h
->uid
, embedded_home
);
2760 if (S_ISREG(st
.st_mode
)) {
2761 if (user_record_luks_discard(h
))
2762 /* Before we shrink, let's trim the file system, so that we need less space on disk during the shrinking */
2763 (void) run_fitrim(setup
->root_fd
);
2765 /* If discard is off, let's ensure all backing blocks are allocated, so that our resize operation doesn't fail half-way */
2766 r
= run_fallocate(image_fd
, &st
);
2773 /* Now resize the file system */
2774 if (resize_type
== CAN_RESIZE_ONLINE
)
2775 r
= resize_fs(setup
->root_fd
, new_fs_size
, NULL
);
2777 r
= ext4_offline_resize_fs(setup
, new_fs_size
, user_record_luks_discard(h
), user_record_mount_flags(h
));
2779 return log_error_errno(r
, "Failed to resize file system: %m");
2781 log_info("File system resizing completed.");
2783 /* Immediately sync afterwards */
2784 r
= home_sync_and_statfs(setup
->root_fd
, NULL
);
2788 if (new_fs_size
< old_fs_size
) {
2790 /* Shrink the LUKS device now, matching the new file system size */
2791 r
= crypt_resize(setup
->crypt_device
, setup
->dm_name
, new_fs_size
/ 512);
2793 return log_error_errno(r
, "Failed to shrink LUKS device: %m");
2795 log_info("LUKS device shrinking completed.");
2797 if (S_ISREG(st
.st_mode
)) {
2798 /* Shrink the image file */
2799 if (ftruncate(image_fd
, new_image_size
) < 0)
2800 return log_error_errno(errno
, "Failed to shrink image file %s: %m", ip
);
2802 log_info("Shrinking of image file completed.");
2805 /* Refresh the loop devices size */
2806 r
= loop_device_refresh_size(setup
->loop
, UINT64_MAX
, new_partition_size
);
2808 log_debug_errno(r
, "Device is not a loopback device, not refreshing size.");
2810 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
2812 log_info("Refreshing loop device size completed.");
2814 r
= apply_resize_partition(image_fd
, disk_uuid
, table
);
2818 log_info("Shrinking of partition completed.");
2820 if (ioctl(image_fd
, BLKRRPART
, 0) < 0)
2821 log_debug_errno(errno
, "BLKRRPART failed on block device, ignoring: %m");
2823 r
= home_store_embedded_identity(new_home
, setup
->root_fd
, h
->uid
, embedded_home
);
2828 r
= home_store_header_identity_luks(new_home
, setup
, header_home
);
2832 r
= home_extend_embedded_identity(new_home
, h
, setup
);
2836 if (user_record_luks_discard(h
))
2837 (void) run_fitrim(setup
->root_fd
);
2839 r
= home_sync_and_statfs(setup
->root_fd
, &sfs
);
2843 r
= home_setup_undo(setup
);
2847 log_info("Everything completed.");
2849 print_size_summary(new_image_size
, new_fs_size
, &sfs
);
2851 *ret_home
= TAKE_PTR(new_home
);
2855 int home_passwd_luks(
2858 char **pkcs11_decrypted_passwords
, /* the passwords acquired via PKCS#11 security tokens */
2859 char **effective_passwords
/* new passwords */) {
2861 size_t volume_key_size
, i
, max_key_slots
, n_effective
;
2862 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
2863 struct crypt_pbkdf_type good_pbkdf
, minimal_pbkdf
;
2868 assert(user_record_storage(h
) == USER_LUKS
);
2871 type
= crypt_get_type(setup
->crypt_device
);
2873 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine crypto device type.");
2875 r
= crypt_keyslot_max(type
);
2877 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine number of key slots.");
2880 r
= crypt_get_volume_key_size(setup
->crypt_device
);
2882 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine volume key size.");
2883 volume_key_size
= (size_t) r
;
2885 volume_key
= malloc(volume_key_size
);
2889 r
= luks_try_passwords(setup
->crypt_device
, pkcs11_decrypted_passwords
, volume_key
, &volume_key_size
);
2891 r
= luks_try_passwords(setup
->crypt_device
, h
->password
, volume_key
, &volume_key_size
);
2893 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY
), "Failed to unlock LUKS superblock with supplied passwords.");
2896 return log_error_errno(r
, "Failed to unlocks LUKS superblock: %m");
2898 n_effective
= strv_length(effective_passwords
);
2900 build_good_pbkdf(&good_pbkdf
, h
);
2901 build_minimal_pbkdf(&minimal_pbkdf
, h
);
2903 for (i
= 0; i
< max_key_slots
; i
++) {
2904 r
= crypt_keyslot_destroy(setup
->crypt_device
, i
);
2905 if (r
< 0 && !IN_SET(r
, -ENOENT
, -EINVAL
)) /* Returns EINVAL or ENOENT if there's no key in this slot already */
2906 return log_error_errno(r
, "Failed to destroy LUKS password: %m");
2908 if (i
>= n_effective
) {
2910 log_info("Destroyed LUKS key slot %zu.", i
);
2914 if (strv_find(pkcs11_decrypted_passwords
, effective_passwords
[i
])) {
2915 log_debug("Using minimal PBKDF for slot %zu", i
);
2916 r
= crypt_set_pbkdf_type(setup
->crypt_device
, &minimal_pbkdf
);
2918 log_debug("Using good PBKDF for slot %zu", i
);
2919 r
= crypt_set_pbkdf_type(setup
->crypt_device
, &good_pbkdf
);
2922 return log_error_errno(r
, "Failed to tweak PBKDF for slot %zu: %m", i
);
2924 r
= crypt_keyslot_add_by_volume_key(
2925 setup
->crypt_device
,
2929 effective_passwords
[i
],
2930 strlen(effective_passwords
[i
]));
2932 return log_error_errno(r
, "Failed to set up LUKS password: %m");
2934 log_info("Updated LUKS key slot %zu.", i
);
2940 int home_lock_luks(UserRecord
*h
) {
2941 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
2942 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
2943 _cleanup_close_
int root_fd
= -1;
2949 assert_se(p
= user_record_home_directory(h
));
2950 root_fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
2952 return log_error_errno(errno
, "Failed to open home directory: %m");
2954 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
2958 r
= crypt_init_by_name(&cd
, dm_name
);
2960 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
2962 log_info("Discovered used LUKS device %s.", dm_node
);
2963 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
2965 if (syncfs(root_fd
) < 0) /* Snake oil, but let's better be safe than sorry */
2966 return log_error_errno(errno
, "Failed to synchronize file system %s: %m", p
);
2968 root_fd
= safe_close(root_fd
);
2970 log_info("File system synchronized.");
2972 /* Note that we don't invoke FIFREEZE here, it appears libcryptsetup/device-mapper already does that on its own for us */
2974 r
= crypt_suspend(cd
, dm_name
);
2976 return log_error_errno(r
, "Failed to suspend cryptsetup device: %s: %m", dm_node
);
2978 log_info("LUKS device suspended.");
2982 static int luks_try_resume(
2983 struct crypt_device
*cd
,
2984 const char *dm_name
,
2993 STRV_FOREACH(pp
, password
) {
2994 r
= crypt_resume_by_passphrase(
3001 log_info("Resumed LUKS device %s.", dm_name
);
3005 log_debug_errno(r
, "Password %zu didn't work for resuming device: %m", (size_t) (pp
- password
));
3011 int home_unlock_luks(UserRecord
*h
, char ***pkcs11_decrypted_passwords
) {
3012 _cleanup_free_
char *dm_name
= NULL
, *dm_node
= NULL
;
3013 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
3018 r
= make_dm_names(h
->user_name
, &dm_name
, &dm_node
);
3022 r
= crypt_init_by_name(&cd
, dm_name
);
3024 return log_error_errno(r
, "Failed to initialize cryptsetup context for %s: %m", dm_name
);
3026 log_info("Discovered used LUKS device %s.", dm_node
);
3027 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
3029 r
= luks_try_resume(cd
, dm_name
, pkcs11_decrypted_passwords
? *pkcs11_decrypted_passwords
: NULL
);
3031 r
= luks_try_resume(cd
, dm_name
, h
->password
);
3033 return log_error_errno(r
, "No valid password for LUKS superblock.");
3036 return log_error_errno(r
, "Failed to resume LUKS superblock: %m");
3038 log_info("LUKS device resumed.");