]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/home/homework-luks.c
core: reduce scope of variants
[thirdparty/systemd.git] / src / home / homework-luks.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <libfdisk.h>
4 #include <linux/loop.h>
5 #include <poll.h>
6 #include <sys/file.h>
7 #include <sys/ioctl.h>
8 #include <sys/mount.h>
9 #include <sys/xattr.h>
10
11 #include "blkid-util.h"
12 #include "blockdev-util.h"
13 #include "btrfs-util.h"
14 #include "chattr-util.h"
15 #include "dm-util.h"
16 #include "errno-util.h"
17 #include "fd-util.h"
18 #include "fileio.h"
19 #include "fs-util.h"
20 #include "fsck-util.h"
21 #include "home-util.h"
22 #include "homework-luks.h"
23 #include "homework-mount.h"
24 #include "id128-util.h"
25 #include "io-util.h"
26 #include "memory-util.h"
27 #include "missing_magic.h"
28 #include "mkdir.h"
29 #include "mkfs-util.h"
30 #include "mount-util.h"
31 #include "openssl-util.h"
32 #include "parse-util.h"
33 #include "path-util.h"
34 #include "process-util.h"
35 #include "random-util.h"
36 #include "resize-fs.h"
37 #include "stat-util.h"
38 #include "strv.h"
39 #include "tmpfile-util.h"
40
41 /* Round down to the nearest 1K size. Note that Linux generally handles block devices with 512 blocks only,
42 * but actually doesn't accept uneven numbers in many cases. To avoid any confusion around this we'll
43 * strictly round disk sizes down to the next 1K boundary.*/
44 #define DISK_SIZE_ROUND_DOWN(x) ((x) & ~UINT64_C(1023))
45
46 int run_mark_dirty(int fd, bool b) {
47 char x = '1';
48 int r, ret;
49
50 /* Sets or removes the 'user.home-dirty' xattr on the specified file. We use this to detect when a
51 * home directory was not properly unmounted. */
52
53 assert(fd >= 0);
54
55 r = fd_verify_regular(fd);
56 if (r < 0)
57 return r;
58
59 if (b) {
60 ret = fsetxattr(fd, "user.home-dirty", &x, 1, XATTR_CREATE);
61 if (ret < 0 && errno != EEXIST)
62 return log_debug_errno(errno, "Could not mark home directory as dirty: %m");
63
64 } else {
65 r = fsync_full(fd);
66 if (r < 0)
67 return log_debug_errno(r, "Failed to synchronize image before marking it clean: %m");
68
69 ret = fremovexattr(fd, "user.home-dirty");
70 if (ret < 0 && errno != ENODATA)
71 return log_debug_errno(errno, "Could not mark home directory as clean: %m");
72 }
73
74 r = fsync_full(fd);
75 if (r < 0)
76 return log_debug_errno(r, "Failed to synchronize dirty flag to disk: %m");
77
78 return ret >= 0;
79 }
80
81 int run_mark_dirty_by_path(const char *path, bool b) {
82 _cleanup_close_ int fd = -1;
83
84 assert(path);
85
86 fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY);
87 if (fd < 0)
88 return log_debug_errno(errno, "Failed to open %s to mark dirty or clean: %m", path);
89
90 return run_mark_dirty(fd, b);
91 }
92
93 static int probe_file_system_by_fd(
94 int fd,
95 char **ret_fstype,
96 sd_id128_t *ret_uuid) {
97
98 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
99 _cleanup_free_ char *s = NULL;
100 const char *fstype = NULL, *uuid = NULL;
101 sd_id128_t id;
102 int r;
103
104 assert(fd >= 0);
105 assert(ret_fstype);
106 assert(ret_uuid);
107
108 b = blkid_new_probe();
109 if (!b)
110 return -ENOMEM;
111
112 errno = 0;
113 r = blkid_probe_set_device(b, fd, 0, 0);
114 if (r != 0)
115 return errno > 0 ? -errno : -ENOMEM;
116
117 (void) blkid_probe_enable_superblocks(b, 1);
118 (void) blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_UUID);
119
120 errno = 0;
121 r = blkid_do_safeprobe(b);
122 if (IN_SET(r, -2, 1)) /* nothing found or ambiguous result */
123 return -ENOPKG;
124 if (r != 0)
125 return errno > 0 ? -errno : -EIO;
126
127 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
128 if (!fstype)
129 return -ENOPKG;
130
131 (void) blkid_probe_lookup_value(b, "UUID", &uuid, NULL);
132 if (!uuid)
133 return -ENOPKG;
134
135 r = sd_id128_from_string(uuid, &id);
136 if (r < 0)
137 return r;
138
139 s = strdup(fstype);
140 if (!s)
141 return -ENOMEM;
142
143 *ret_fstype = TAKE_PTR(s);
144 *ret_uuid = id;
145
146 return 0;
147 }
148
149 static int probe_file_system_by_path(const char *path, char **ret_fstype, sd_id128_t *ret_uuid) {
150 _cleanup_close_ int fd = -1;
151
152 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
153 if (fd < 0)
154 return -errno;
155
156 return probe_file_system_by_fd(fd, ret_fstype, ret_uuid);
157 }
158
159 static int block_get_size_by_fd(int fd, uint64_t *ret) {
160 struct stat st;
161
162 assert(fd >= 0);
163 assert(ret);
164
165 if (fstat(fd, &st) < 0)
166 return -errno;
167
168 if (!S_ISBLK(st.st_mode))
169 return -ENOTBLK;
170
171 if (ioctl(fd, BLKGETSIZE64, ret) < 0)
172 return -errno;
173
174 return 0;
175 }
176
177 static int block_get_size_by_path(const char *path, uint64_t *ret) {
178 _cleanup_close_ int fd = -1;
179
180 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
181 if (fd < 0)
182 return -errno;
183
184 return block_get_size_by_fd(fd, ret);
185 }
186
187 static int run_fsck(const char *node, const char *fstype) {
188 int r, exit_status;
189 pid_t fsck_pid;
190
191 assert(node);
192 assert(fstype);
193
194 r = fsck_exists(fstype);
195 if (r < 0)
196 return log_error_errno(r, "Failed to check if fsck for file system %s exists: %m", fstype);
197 if (r == 0) {
198 log_warning("No fsck for file system %s installed, ignoring.", fstype);
199 return 0;
200 }
201
202 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_LOG|FORK_STDOUT_TO_STDERR, &fsck_pid);
203 if (r < 0)
204 return r;
205 if (r == 0) {
206 /* Child */
207 execl("/sbin/fsck", "/sbin/fsck", "-aTl", node, NULL);
208 log_error_errno(errno, "Failed to execute fsck: %m");
209 _exit(FSCK_OPERATIONAL_ERROR);
210 }
211
212 exit_status = wait_for_terminate_and_check("fsck", fsck_pid, WAIT_LOG_ABNORMAL);
213 if (exit_status < 0)
214 return exit_status;
215 if ((exit_status & ~FSCK_ERROR_CORRECTED) != 0) {
216 log_warning("fsck failed with exit status %i.", exit_status);
217
218 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
219 return log_error_errno(SYNTHETIC_ERRNO(EIO), "File system is corrupted, refusing.");
220
221 log_warning("Ignoring fsck error.");
222 }
223
224 log_info("File system check completed.");
225
226 return 1;
227 }
228
229 static int luks_try_passwords(
230 struct crypt_device *cd,
231 char **passwords,
232 void *volume_key,
233 size_t *volume_key_size) {
234
235 char **pp;
236 int r;
237
238 assert(cd);
239
240 STRV_FOREACH(pp, passwords) {
241 size_t vks = *volume_key_size;
242
243 r = crypt_volume_key_get(
244 cd,
245 CRYPT_ANY_SLOT,
246 volume_key,
247 &vks,
248 *pp,
249 strlen(*pp));
250 if (r >= 0) {
251 *volume_key_size = vks;
252 return 0;
253 }
254
255 log_debug_errno(r, "Password %zu didn't work for unlocking LUKS superblock: %m", (size_t) (pp - passwords));
256 }
257
258 return -ENOKEY;
259 }
260
261 static int luks_setup(
262 const char *node,
263 const char *dm_name,
264 sd_id128_t uuid,
265 const char *cipher,
266 const char *cipher_mode,
267 uint64_t volume_key_size,
268 char **passwords,
269 const PasswordCache *cache,
270 bool discard,
271 struct crypt_device **ret,
272 sd_id128_t *ret_found_uuid,
273 void **ret_volume_key,
274 size_t *ret_volume_key_size) {
275
276 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
277 _cleanup_(erase_and_freep) void *vk = NULL;
278 sd_id128_t p;
279 size_t vks;
280 char **list;
281 int r;
282
283 assert(node);
284 assert(dm_name);
285 assert(ret);
286
287 r = crypt_init(&cd, node);
288 if (r < 0)
289 return log_error_errno(r, "Failed to allocate libcryptsetup context: %m");
290
291 cryptsetup_enable_logging(cd);
292
293 r = crypt_load(cd, CRYPT_LUKS2, NULL);
294 if (r < 0)
295 return log_error_errno(r, "Failed to load LUKS superblock: %m");
296
297 r = crypt_get_volume_key_size(cd);
298 if (r <= 0)
299 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine LUKS volume key size");
300 vks = (size_t) r;
301
302 if (!sd_id128_is_null(uuid) || ret_found_uuid) {
303 const char *s;
304
305 s = crypt_get_uuid(cd);
306 if (!s)
307 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has no UUID.");
308
309 r = sd_id128_from_string(s, &p);
310 if (r < 0)
311 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has invalid UUID.");
312
313 /* Check that the UUID matches, if specified */
314 if (!sd_id128_is_null(uuid) &&
315 !sd_id128_equal(uuid, p))
316 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has wrong UUID.");
317 }
318
319 if (cipher && !streq_ptr(cipher, crypt_get_cipher(cd)))
320 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock declares wrong cipher.");
321
322 if (cipher_mode && !streq_ptr(cipher_mode, crypt_get_cipher_mode(cd)))
323 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock declares wrong cipher mode.");
324
325 if (volume_key_size != UINT64_MAX && vks != volume_key_size)
326 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock declares wrong volume key size.");
327
328 vk = malloc(vks);
329 if (!vk)
330 return log_oom();
331
332 r = -ENOKEY;
333 FOREACH_POINTER(list, cache->pkcs11_passwords, cache->fido2_passwords, passwords) {
334 r = luks_try_passwords(cd, list, vk, &vks);
335 if (r != -ENOKEY)
336 break;
337 }
338 if (r == -ENOKEY)
339 return log_error_errno(r, "No valid password for LUKS superblock.");
340 if (r < 0)
341 return log_error_errno(r, "Failed to unlocks LUKS superblock: %m");
342
343 r = crypt_activate_by_volume_key(
344 cd,
345 dm_name,
346 vk, vks,
347 discard ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0);
348 if (r < 0)
349 return log_error_errno(r, "Failed to unlock LUKS superblock: %m");
350
351 log_info("Setting up LUKS device /dev/mapper/%s completed.", dm_name);
352
353 *ret = TAKE_PTR(cd);
354
355 if (ret_found_uuid) /* Return the UUID actually found if the caller wants to know */
356 *ret_found_uuid = p;
357 if (ret_volume_key)
358 *ret_volume_key = TAKE_PTR(vk);
359 if (ret_volume_key_size)
360 *ret_volume_key_size = vks;
361
362 return 0;
363 }
364
365 static int luks_open(
366 const char *dm_name,
367 char **passwords,
368 PasswordCache *cache,
369 struct crypt_device **ret,
370 sd_id128_t *ret_found_uuid,
371 void **ret_volume_key,
372 size_t *ret_volume_key_size) {
373
374 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
375 _cleanup_(erase_and_freep) void *vk = NULL;
376 sd_id128_t p;
377 char **list;
378 size_t vks;
379 int r;
380
381 assert(dm_name);
382 assert(ret);
383
384 /* Opens a LUKS device that is already set up. Re-validates the password while doing so (which also
385 * provides us with the volume key, which we want). */
386
387 r = crypt_init_by_name(&cd, dm_name);
388 if (r < 0)
389 return log_error_errno(r, "Failed to initialize cryptsetup context for %s: %m", dm_name);
390
391 cryptsetup_enable_logging(cd);
392
393 r = crypt_load(cd, CRYPT_LUKS2, NULL);
394 if (r < 0)
395 return log_error_errno(r, "Failed to load LUKS superblock: %m");
396
397 r = crypt_get_volume_key_size(cd);
398 if (r <= 0)
399 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine LUKS volume key size");
400 vks = (size_t) r;
401
402 if (ret_found_uuid) {
403 const char *s;
404
405 s = crypt_get_uuid(cd);
406 if (!s)
407 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has no UUID.");
408
409 r = sd_id128_from_string(s, &p);
410 if (r < 0)
411 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has invalid UUID.");
412 }
413
414 vk = malloc(vks);
415 if (!vk)
416 return log_oom();
417
418 r = -ENOKEY;
419 FOREACH_POINTER(list, cache->pkcs11_passwords, cache->fido2_passwords, passwords) {
420 r = luks_try_passwords(cd, list, vk, &vks);
421 if (r != -ENOKEY)
422 break;
423 }
424 if (r == -ENOKEY)
425 return log_error_errno(r, "No valid password for LUKS superblock.");
426 if (r < 0)
427 return log_error_errno(r, "Failed to unlocks LUKS superblock: %m");
428
429 log_info("Discovered used LUKS device /dev/mapper/%s, and validated password.", dm_name);
430
431 /* This is needed so that crypt_resize() can operate correctly for pre-existing LUKS devices. We need
432 * to tell libcryptsetup the volume key explicitly, so that it is in the kernel keyring. */
433 r = crypt_activate_by_volume_key(cd, NULL, vk, vks, CRYPT_ACTIVATE_KEYRING_KEY);
434 if (r < 0)
435 return log_error_errno(r, "Failed to upload volume key again: %m");
436
437 log_info("Successfully re-activated LUKS device.");
438
439 *ret = TAKE_PTR(cd);
440
441 if (ret_found_uuid)
442 *ret_found_uuid = p;
443 if (ret_volume_key)
444 *ret_volume_key = TAKE_PTR(vk);
445 if (ret_volume_key_size)
446 *ret_volume_key_size = vks;
447
448 return 0;
449 }
450
451 static int fs_validate(
452 const char *dm_node,
453 sd_id128_t uuid,
454 char **ret_fstype,
455 sd_id128_t *ret_found_uuid) {
456
457 _cleanup_free_ char *fstype = NULL;
458 sd_id128_t u;
459 int r;
460
461 assert(dm_node);
462 assert(ret_fstype);
463
464 r = probe_file_system_by_path(dm_node, &fstype, &u);
465 if (r < 0)
466 return log_error_errno(r, "Failed to probe file system: %m");
467
468 /* Limit the set of supported file systems a bit, as protection against little tested kernel file
469 * systems. Also, we only support the resize ioctls for these file systems. */
470 if (!supported_fstype(fstype))
471 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "Image contains unsupported file system: %s", strna(fstype));
472
473 if (!sd_id128_is_null(uuid) &&
474 !sd_id128_equal(uuid, u))
475 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "File system has wrong UUID.");
476
477 log_info("Probing file system completed (found %s).", fstype);
478
479 *ret_fstype = TAKE_PTR(fstype);
480
481 if (ret_found_uuid) /* Return the UUID actually found if the caller wants to know */
482 *ret_found_uuid = u;
483
484 return 0;
485 }
486
487 static int make_dm_names(const char *user_name, char **ret_dm_name, char **ret_dm_node) {
488 _cleanup_free_ char *name = NULL, *node = NULL;
489
490 assert(user_name);
491 assert(ret_dm_name);
492 assert(ret_dm_node);
493
494 name = strjoin("home-", user_name);
495 if (!name)
496 return log_oom();
497
498 node = path_join("/dev/mapper/", name);
499 if (!node)
500 return log_oom();
501
502 *ret_dm_name = TAKE_PTR(name);
503 *ret_dm_node = TAKE_PTR(node);
504 return 0;
505 }
506
507 static int luks_validate(
508 int fd,
509 const char *label,
510 sd_id128_t partition_uuid,
511 sd_id128_t *ret_partition_uuid,
512 uint64_t *ret_offset,
513 uint64_t *ret_size) {
514
515 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
516 sd_id128_t found_partition_uuid = SD_ID128_NULL;
517 const char *fstype = NULL, *pttype = NULL;
518 blkid_loff_t offset = 0, size = 0;
519 blkid_partlist pl;
520 bool found = false;
521 int r, i, n;
522
523 assert(fd >= 0);
524 assert(label);
525 assert(ret_offset);
526 assert(ret_size);
527
528 b = blkid_new_probe();
529 if (!b)
530 return -ENOMEM;
531
532 errno = 0;
533 r = blkid_probe_set_device(b, fd, 0, 0);
534 if (r != 0)
535 return errno > 0 ? -errno : -ENOMEM;
536
537 (void) blkid_probe_enable_superblocks(b, 1);
538 (void) blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
539 (void) blkid_probe_enable_partitions(b, 1);
540 (void) blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
541
542 errno = 0;
543 r = blkid_do_safeprobe(b);
544 if (IN_SET(r, -2, 1)) /* nothing found or ambiguous result */
545 return -ENOPKG;
546 if (r != 0)
547 return errno > 0 ? -errno : -EIO;
548
549 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
550 if (streq_ptr(fstype, "crypto_LUKS")) {
551 /* Directly a LUKS image */
552 *ret_offset = 0;
553 *ret_size = UINT64_MAX; /* full disk */
554 *ret_partition_uuid = SD_ID128_NULL;
555 return 0;
556 } else if (fstype)
557 return -ENOPKG;
558
559 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
560 if (!streq_ptr(pttype, "gpt"))
561 return -ENOPKG;
562
563 errno = 0;
564 pl = blkid_probe_get_partitions(b);
565 if (!pl)
566 return errno > 0 ? -errno : -ENOMEM;
567
568 errno = 0;
569 n = blkid_partlist_numof_partitions(pl);
570 if (n < 0)
571 return errno > 0 ? -errno : -EIO;
572
573 for (i = 0; i < n; i++) {
574 blkid_partition pp;
575 sd_id128_t id;
576 const char *sid;
577
578 errno = 0;
579 pp = blkid_partlist_get_partition(pl, i);
580 if (!pp)
581 return errno > 0 ? -errno : -EIO;
582
583 if (!streq_ptr(blkid_partition_get_type_string(pp), "773f91ef-66d4-49b5-bd83-d683bf40ad16"))
584 continue;
585
586 if (!streq_ptr(blkid_partition_get_name(pp), label))
587 continue;
588
589 sid = blkid_partition_get_uuid(pp);
590 if (sid) {
591 r = sd_id128_from_string(sid, &id);
592 if (r < 0)
593 log_debug_errno(r, "Couldn't parse partition UUID %s, weird: %m", sid);
594
595 if (!sd_id128_is_null(partition_uuid) && !sd_id128_equal(id, partition_uuid))
596 continue;
597 }
598
599 if (found)
600 return -ENOPKG;
601
602 offset = blkid_partition_get_start(pp);
603 size = blkid_partition_get_size(pp);
604 found_partition_uuid = id;
605
606 found = true;
607 }
608
609 if (!found)
610 return -ENOPKG;
611
612 if (offset < 0)
613 return -EINVAL;
614 if ((uint64_t) offset > UINT64_MAX / 512U)
615 return -EINVAL;
616 if (size <= 0)
617 return -EINVAL;
618 if ((uint64_t) size > UINT64_MAX / 512U)
619 return -EINVAL;
620
621 *ret_offset = offset * 512U;
622 *ret_size = size * 512U;
623 *ret_partition_uuid = found_partition_uuid;
624
625 return 0;
626 }
627
628 static int crypt_device_to_evp_cipher(struct crypt_device *cd, const EVP_CIPHER **ret) {
629 _cleanup_free_ char *cipher_name = NULL;
630 const char *cipher, *cipher_mode, *e;
631 size_t key_size, key_bits;
632 const EVP_CIPHER *cc;
633 int r;
634
635 assert(cd);
636
637 /* Let's find the right OpenSSL EVP_CIPHER object that matches the encryption settings of the LUKS
638 * device */
639
640 cipher = crypt_get_cipher(cd);
641 if (!cipher)
642 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot get cipher from LUKS device.");
643
644 cipher_mode = crypt_get_cipher_mode(cd);
645 if (!cipher_mode)
646 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot get cipher mode from LUKS device.");
647
648 e = strchr(cipher_mode, '-');
649 if (e)
650 cipher_mode = strndupa(cipher_mode, e - cipher_mode);
651
652 r = crypt_get_volume_key_size(cd);
653 if (r <= 0)
654 return log_error_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Cannot get volume key size from LUKS device.");
655
656 key_size = r;
657 key_bits = key_size * 8;
658 if (streq(cipher_mode, "xts"))
659 key_bits /= 2;
660
661 if (asprintf(&cipher_name, "%s-%zu-%s", cipher, key_bits, cipher_mode) < 0)
662 return log_oom();
663
664 cc = EVP_get_cipherbyname(cipher_name);
665 if (!cc)
666 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Selected cipher mode '%s' not supported, can't encrypt JSON record.", cipher_name);
667
668 /* Verify that our key length calculations match what OpenSSL thinks */
669 r = EVP_CIPHER_key_length(cc);
670 if (r < 0 || (uint64_t) r != key_size)
671 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Key size of selected cipher doesn't meet our expectations.");
672
673 *ret = cc;
674 return 0;
675 }
676
677 static int luks_validate_home_record(
678 struct crypt_device *cd,
679 UserRecord *h,
680 const void *volume_key,
681 PasswordCache *cache,
682 UserRecord **ret_luks_home_record) {
683
684 int r, token;
685
686 assert(cd);
687 assert(h);
688
689 for (token = 0;; token++) {
690 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL, *rr = NULL;
691 _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
692 _cleanup_(user_record_unrefp) UserRecord *lhr = NULL;
693 _cleanup_free_ void *encrypted = NULL, *iv = NULL;
694 size_t decrypted_size, encrypted_size, iv_size;
695 int decrypted_size_out1, decrypted_size_out2;
696 _cleanup_free_ char *decrypted = NULL;
697 const char *text, *type;
698 crypt_token_info state;
699 JsonVariant *jr, *jiv;
700 unsigned line, column;
701 const EVP_CIPHER *cc;
702
703 state = crypt_token_status(cd, token, &type);
704 if (state == CRYPT_TOKEN_INACTIVE) /* First unconfigured token, give up */
705 break;
706 if (IN_SET(state, CRYPT_TOKEN_INTERNAL, CRYPT_TOKEN_INTERNAL_UNKNOWN, CRYPT_TOKEN_EXTERNAL))
707 continue;
708 if (state != CRYPT_TOKEN_EXTERNAL_UNKNOWN)
709 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected token state of token %i: %i", token, (int) state);
710
711 if (!streq(type, "systemd-homed"))
712 continue;
713
714 r = crypt_token_json_get(cd, token, &text);
715 if (r < 0)
716 return log_error_errno(r, "Failed to read LUKS token %i: %m", token);
717
718 r = json_parse(text, JSON_PARSE_SENSITIVE, &v, &line, &column);
719 if (r < 0)
720 return log_error_errno(r, "Failed to parse LUKS token JSON data %u:%u: %m", line, column);
721
722 jr = json_variant_by_key(v, "record");
723 if (!jr)
724 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS token lacks 'record' field.");
725 jiv = json_variant_by_key(v, "iv");
726 if (!jiv)
727 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS token lacks 'iv' field.");
728
729 r = json_variant_unbase64(jr, &encrypted, &encrypted_size);
730 if (r < 0)
731 return log_error_errno(r, "Failed to base64 decode record: %m");
732
733 r = json_variant_unbase64(jiv, &iv, &iv_size);
734 if (r < 0)
735 return log_error_errno(r, "Failed to base64 decode IV: %m");
736
737 r = crypt_device_to_evp_cipher(cd, &cc);
738 if (r < 0)
739 return r;
740 if (iv_size > INT_MAX || EVP_CIPHER_iv_length(cc) != (int) iv_size)
741 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "IV size doesn't match.");
742
743 context = EVP_CIPHER_CTX_new();
744 if (!context)
745 return log_oom();
746
747 if (EVP_DecryptInit_ex(context, cc, NULL, volume_key, iv) != 1)
748 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize decryption context.");
749
750 decrypted_size = encrypted_size + EVP_CIPHER_key_length(cc) * 2;
751 decrypted = new(char, decrypted_size);
752 if (!decrypted)
753 return log_oom();
754
755 if (EVP_DecryptUpdate(context, (uint8_t*) decrypted, &decrypted_size_out1, encrypted, encrypted_size) != 1)
756 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to decrypt JSON record.");
757
758 assert((size_t) decrypted_size_out1 <= decrypted_size);
759
760 if (EVP_DecryptFinal_ex(context, (uint8_t*) decrypted + decrypted_size_out1, &decrypted_size_out2) != 1)
761 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finish decryption of JSON record.");
762
763 assert((size_t) decrypted_size_out1 + (size_t) decrypted_size_out2 < decrypted_size);
764 decrypted_size = (size_t) decrypted_size_out1 + (size_t) decrypted_size_out2;
765
766 if (memchr(decrypted, 0, decrypted_size))
767 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Inner NUL byte in JSON record, refusing.");
768
769 decrypted[decrypted_size] = 0;
770
771 r = json_parse(decrypted, JSON_PARSE_SENSITIVE, &rr, NULL, NULL);
772 if (r < 0)
773 return log_error_errno(r, "Failed to parse decrypted JSON record, refusing.");
774
775 lhr = user_record_new();
776 if (!lhr)
777 return log_oom();
778
779 r = user_record_load(lhr, rr, USER_RECORD_LOAD_EMBEDDED);
780 if (r < 0)
781 return log_error_errno(r, "Failed to parse user record: %m");
782
783 if (!user_record_compatible(h, lhr))
784 return log_error_errno(SYNTHETIC_ERRNO(EREMCHG), "LUKS home record not compatible with host record, refusing.");
785
786 r = user_record_authenticate(lhr, h, cache, /* strict_verify= */ true);
787 if (r < 0)
788 return r;
789 assert(r > 0); /* Insist that a password was verified */
790
791 *ret_luks_home_record = TAKE_PTR(lhr);
792 return 0;
793 }
794
795 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Couldn't find home record in LUKS2 header, refusing.");
796 }
797
798 static int format_luks_token_text(
799 struct crypt_device *cd,
800 UserRecord *hr,
801 const void *volume_key,
802 char **ret) {
803
804 int r, encrypted_size_out1 = 0, encrypted_size_out2 = 0, iv_size, key_size;
805 _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
806 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
807 _cleanup_free_ void *iv = NULL, *encrypted = NULL;
808 size_t text_length, encrypted_size;
809 _cleanup_free_ char *text = NULL;
810 const EVP_CIPHER *cc;
811
812 assert(cd);
813 assert(hr);
814 assert(volume_key);
815 assert(ret);
816
817 r = crypt_device_to_evp_cipher(cd, &cc);
818 if (r < 0)
819 return r;
820
821 key_size = EVP_CIPHER_key_length(cc);
822 iv_size = EVP_CIPHER_iv_length(cc);
823
824 if (iv_size > 0) {
825 iv = malloc(iv_size);
826 if (!iv)
827 return log_oom();
828
829 r = genuine_random_bytes(iv, iv_size, RANDOM_BLOCK);
830 if (r < 0)
831 return log_error_errno(r, "Failed to generate IV: %m");
832 }
833
834 context = EVP_CIPHER_CTX_new();
835 if (!context)
836 return log_oom();
837
838 if (EVP_EncryptInit_ex(context, cc, NULL, volume_key, iv) != 1)
839 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize encryption context.");
840
841 r = json_variant_format(hr->json, 0, &text);
842 if (r < 0)
843 return log_error_errno(r, "Failed to format user record for LUKS: %m");
844
845 text_length = strlen(text);
846 encrypted_size = text_length + 2*key_size - 1;
847
848 encrypted = malloc(encrypted_size);
849 if (!encrypted)
850 return log_oom();
851
852 if (EVP_EncryptUpdate(context, encrypted, &encrypted_size_out1, (uint8_t*) text, text_length) != 1)
853 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to encrypt JSON record.");
854
855 assert((size_t) encrypted_size_out1 <= encrypted_size);
856
857 if (EVP_EncryptFinal_ex(context, (uint8_t*) encrypted + encrypted_size_out1, &encrypted_size_out2) != 1)
858 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finish encryption of JSON record. ");
859
860 assert((size_t) encrypted_size_out1 + (size_t) encrypted_size_out2 <= encrypted_size);
861
862 r = json_build(&v,
863 JSON_BUILD_OBJECT(
864 JSON_BUILD_PAIR("type", JSON_BUILD_STRING("systemd-homed")),
865 JSON_BUILD_PAIR("keyslots", JSON_BUILD_EMPTY_ARRAY),
866 JSON_BUILD_PAIR("record", JSON_BUILD_BASE64(encrypted, encrypted_size_out1 + encrypted_size_out2)),
867 JSON_BUILD_PAIR("iv", JSON_BUILD_BASE64(iv, iv_size))));
868 if (r < 0)
869 return log_error_errno(r, "Failed to prepare LUKS JSON token object: %m");
870
871 r = json_variant_format(v, 0, ret);
872 if (r < 0)
873 return log_error_errno(r, "Failed to format encrypted user record for LUKS: %m");
874
875 return 0;
876 }
877
878 int home_store_header_identity_luks(
879 UserRecord *h,
880 HomeSetup *setup,
881 UserRecord *old_home) {
882
883 _cleanup_(user_record_unrefp) UserRecord *header_home = NULL;
884 _cleanup_free_ char *text = NULL;
885 int token = 0, r;
886
887 assert(h);
888
889 if (!setup->crypt_device)
890 return 0;
891
892 assert(setup->volume_key);
893
894 /* Let's store the user's identity record in the LUKS2 "token" header data fields, in an encrypted
895 * fashion. Why that? If we'd rely on the record being embedded in the payload file system itself we
896 * would have to mount the file system before we can validate the JSON record, its signatures and
897 * whether it matches what we are looking for. However, kernel file system implementations are
898 * generally not ready to be used on untrusted media. Hence let's store the record independently of
899 * the file system, so that we can validate it first, and only then mount the file system. To keep
900 * things simple we use the same encryption settings for this record as for the file system itself. */
901
902 r = user_record_clone(h, USER_RECORD_EXTRACT_EMBEDDED, &header_home);
903 if (r < 0)
904 return log_error_errno(r, "Failed to determine new header record: %m");
905
906 if (old_home && user_record_equal(old_home, header_home)) {
907 log_debug("Not updating header home record.");
908 return 0;
909 }
910
911 r = format_luks_token_text(setup->crypt_device, header_home, setup->volume_key, &text);
912 if (r < 0)
913 return r;
914
915 for (;; token++) {
916 crypt_token_info state;
917 const char *type;
918
919 state = crypt_token_status(setup->crypt_device, token, &type);
920 if (state == CRYPT_TOKEN_INACTIVE) /* First unconfigured token, we are done */
921 break;
922 if (IN_SET(state, CRYPT_TOKEN_INTERNAL, CRYPT_TOKEN_INTERNAL_UNKNOWN, CRYPT_TOKEN_EXTERNAL))
923 continue; /* Not ours */
924 if (state != CRYPT_TOKEN_EXTERNAL_UNKNOWN)
925 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected token state of token %i: %i", token, (int) state);
926
927 if (!streq(type, "systemd-homed"))
928 continue;
929
930 r = crypt_token_json_set(setup->crypt_device, token, text);
931 if (r < 0)
932 return log_error_errno(r, "Failed to set JSON token for slot %i: %m", token);
933
934 /* Now, let's free the text so that for all further matching tokens we all crypt_json_token_set()
935 * with a NULL text in order to invalidate the tokens. */
936 text = mfree(text);
937 token++;
938 }
939
940 if (text)
941 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Didn't find any record token to update.");
942
943 log_info("Wrote LUKS header user record.");
944
945 return 1;
946 }
947
948 int run_fitrim(int root_fd) {
949 char buf[FORMAT_BYTES_MAX];
950 struct fstrim_range range = {
951 .len = UINT64_MAX,
952 };
953
954 /* If discarding is on, discard everything right after mounting, so that the discard setting takes
955 * effect on activation. (Also, optionally, trim on logout) */
956
957 assert(root_fd >= 0);
958
959 if (ioctl(root_fd, FITRIM, &range) < 0) {
960 if (ERRNO_IS_NOT_SUPPORTED(errno) || errno == EBADF) {
961 log_debug_errno(errno, "File system does not support FITRIM, not trimming.");
962 return 0;
963 }
964
965 return log_warning_errno(errno, "Failed to invoke FITRIM, ignoring: %m");
966 }
967
968 log_info("Discarded unused %s.",
969 format_bytes(buf, sizeof(buf), range.len));
970 return 1;
971 }
972
973 int run_fitrim_by_path(const char *root_path) {
974 _cleanup_close_ int root_fd = -1;
975
976 root_fd = open(root_path, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
977 if (root_fd < 0)
978 return log_error_errno(errno, "Failed to open file system '%s' for trimming: %m", root_path);
979
980 return run_fitrim(root_fd);
981 }
982
983 int run_fallocate(int backing_fd, const struct stat *st) {
984 char buf[FORMAT_BYTES_MAX];
985 struct stat stbuf;
986
987 assert(backing_fd >= 0);
988
989 /* If discarding is off, let's allocate the whole image before mounting, so that the setting takes
990 * effect on activation */
991
992 if (!st) {
993 if (fstat(backing_fd, &stbuf) < 0)
994 return log_error_errno(errno, "Failed to fstat(): %m");
995
996 st = &stbuf;
997 }
998
999 if (!S_ISREG(st->st_mode))
1000 return 0;
1001
1002 if (st->st_blocks >= DIV_ROUND_UP(st->st_size, 512)) {
1003 log_info("Backing file is fully allocated already.");
1004 return 0;
1005 }
1006
1007 if (fallocate(backing_fd, FALLOC_FL_KEEP_SIZE, 0, st->st_size) < 0) {
1008
1009 if (ERRNO_IS_NOT_SUPPORTED(errno)) {
1010 log_debug_errno(errno, "fallocate() not supported on file system, ignoring.");
1011 return 0;
1012 }
1013
1014 if (ERRNO_IS_DISK_SPACE(errno)) {
1015 log_debug_errno(errno, "Not enough disk space to fully allocate home.");
1016 return -ENOSPC; /* make recognizable */
1017 }
1018
1019 return log_error_errno(errno, "Failed to allocate backing file blocks: %m");
1020 }
1021
1022 log_info("Allocated additional %s.",
1023 format_bytes(buf, sizeof(buf), (DIV_ROUND_UP(st->st_size, 512) - st->st_blocks) * 512));
1024 return 1;
1025 }
1026
1027 int run_fallocate_by_path(const char *backing_path) {
1028 _cleanup_close_ int backing_fd = -1;
1029
1030 backing_fd = open(backing_path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
1031 if (backing_fd < 0)
1032 return log_error_errno(errno, "Failed to open '%s' for fallocate(): %m", backing_path);
1033
1034 return run_fallocate(backing_fd, NULL);
1035 }
1036
1037 int home_prepare_luks(
1038 UserRecord *h,
1039 bool already_activated,
1040 const char *force_image_path,
1041 PasswordCache *cache,
1042 HomeSetup *setup,
1043 UserRecord **ret_luks_home) {
1044
1045 sd_id128_t found_partition_uuid, found_luks_uuid, found_fs_uuid;
1046 _cleanup_(user_record_unrefp) UserRecord *luks_home = NULL;
1047 _cleanup_(loop_device_unrefp) LoopDevice *loop = NULL;
1048 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1049 _cleanup_(erase_and_freep) void *volume_key = NULL;
1050 _cleanup_close_ int root_fd = -1, image_fd = -1;
1051 bool dm_activated = false, mounted = false;
1052 size_t volume_key_size = 0;
1053 bool marked_dirty = false;
1054 uint64_t offset, size;
1055 int r;
1056
1057 assert(h);
1058 assert(setup);
1059 assert(setup->dm_name);
1060 assert(setup->dm_node);
1061
1062 assert(user_record_storage(h) == USER_LUKS);
1063
1064 if (already_activated) {
1065 struct loop_info64 info;
1066 const char *n;
1067
1068 r = luks_open(setup->dm_name,
1069 h->password,
1070 cache,
1071 &cd,
1072 &found_luks_uuid,
1073 &volume_key,
1074 &volume_key_size);
1075 if (r < 0)
1076 return r;
1077
1078 r = luks_validate_home_record(cd, h, volume_key, cache, &luks_home);
1079 if (r < 0)
1080 return r;
1081
1082 n = crypt_get_device_name(cd);
1083 if (!n)
1084 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine backing device for DM %s.", setup->dm_name);
1085
1086 r = loop_device_open(n, O_RDWR, &loop);
1087 if (r < 0)
1088 return log_error_errno(r, "Failed to open loopback device %s: %m", n);
1089
1090 if (ioctl(loop->fd, LOOP_GET_STATUS64, &info) < 0) {
1091 _cleanup_free_ char *sysfs = NULL;
1092 struct stat st;
1093
1094 if (!IN_SET(errno, ENOTTY, EINVAL))
1095 return log_error_errno(errno, "Failed to get block device metrics of %s: %m", n);
1096
1097 if (ioctl(loop->fd, BLKGETSIZE64, &size) < 0)
1098 return log_error_errno(r, "Failed to read block device size of %s: %m", n);
1099
1100 if (fstat(loop->fd, &st) < 0)
1101 return log_error_errno(r, "Failed to stat block device %s: %m", n);
1102 assert(S_ISBLK(st.st_mode));
1103
1104 if (asprintf(&sysfs, "/sys/dev/block/%u:%u/partition", major(st.st_rdev), minor(st.st_rdev)) < 0)
1105 return log_oom();
1106
1107 if (access(sysfs, F_OK) < 0) {
1108 if (errno != ENOENT)
1109 return log_error_errno(errno, "Failed to determine whether %s exists: %m", sysfs);
1110
1111 offset = 0;
1112 } else {
1113 _cleanup_free_ char *buffer = NULL;
1114
1115 if (asprintf(&sysfs, "/sys/dev/block/%u:%u/start", major(st.st_rdev), minor(st.st_rdev)) < 0)
1116 return log_oom();
1117
1118 r = read_one_line_file(sysfs, &buffer);
1119 if (r < 0)
1120 return log_error_errno(r, "Failed to read partition start offset: %m");
1121
1122 r = safe_atou64(buffer, &offset);
1123 if (r < 0)
1124 return log_error_errno(r, "Failed to parse partition start offset: %m");
1125
1126 if (offset > UINT64_MAX / 512U)
1127 return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "Offset too large for 64 byte range, refusing.");
1128
1129 offset *= 512U;
1130 }
1131 } else {
1132 offset = info.lo_offset;
1133 size = info.lo_sizelimit;
1134 }
1135
1136 found_partition_uuid = found_fs_uuid = SD_ID128_NULL;
1137
1138 log_info("Discovered used loopback device %s.", loop->node);
1139
1140 root_fd = open(user_record_home_directory(h), O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
1141 if (root_fd < 0) {
1142 r = log_error_errno(r, "Failed to open home directory: %m");
1143 goto fail;
1144 }
1145 } else {
1146 _cleanup_free_ char *fstype = NULL, *subdir = NULL;
1147 const char *ip;
1148 struct stat st;
1149
1150 ip = force_image_path ?: user_record_image_path(h);
1151
1152 subdir = path_join("/run/systemd/user-home-mount/", user_record_user_name_and_realm(h));
1153 if (!subdir)
1154 return log_oom();
1155
1156 image_fd = open(ip, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
1157 if (image_fd < 0)
1158 return log_error_errno(errno, "Failed to open image file %s: %m", ip);
1159
1160 if (fstat(image_fd, &st) < 0)
1161 return log_error_errno(errno, "Failed to fstat() image file: %m");
1162 if (!S_ISREG(st.st_mode) && !S_ISBLK(st.st_mode))
1163 return log_error_errno(
1164 S_ISDIR(st.st_mode) ? SYNTHETIC_ERRNO(EISDIR) : SYNTHETIC_ERRNO(EBADFD),
1165 "Image file %s is not a regular file or block device: %m", ip);
1166
1167 r = luks_validate(image_fd, user_record_user_name_and_realm(h), h->partition_uuid, &found_partition_uuid, &offset, &size);
1168 if (r < 0)
1169 return log_error_errno(r, "Failed to validate disk label: %m");
1170
1171 /* Everything before this point left the image untouched. We are now starting to make
1172 * changes, hence mark the image dirty */
1173 marked_dirty = run_mark_dirty(image_fd, true) > 0;
1174
1175 if (!user_record_luks_discard(h)) {
1176 r = run_fallocate(image_fd, &st);
1177 if (r < 0)
1178 return r;
1179 }
1180
1181 r = loop_device_make(image_fd, O_RDWR, offset, size, 0, &loop);
1182 if (r == -ENOENT) {
1183 log_error_errno(r, "Loopback block device support is not available on this system.");
1184 return -ENOLINK; /* make recognizable */
1185 }
1186 if (r < 0)
1187 return log_error_errno(r, "Failed to allocate loopback context: %m");
1188
1189 log_info("Setting up loopback device %s completed.", loop->node ?: ip);
1190
1191 r = luks_setup(loop->node ?: ip,
1192 setup->dm_name,
1193 h->luks_uuid,
1194 h->luks_cipher,
1195 h->luks_cipher_mode,
1196 h->luks_volume_key_size,
1197 h->password,
1198 cache,
1199 user_record_luks_discard(h) || user_record_luks_offline_discard(h),
1200 &cd,
1201 &found_luks_uuid,
1202 &volume_key,
1203 &volume_key_size);
1204 if (r < 0)
1205 return r;
1206
1207 dm_activated = true;
1208
1209 r = luks_validate_home_record(cd, h, volume_key, cache, &luks_home);
1210 if (r < 0)
1211 goto fail;
1212
1213 r = fs_validate(setup->dm_node, h->file_system_uuid, &fstype, &found_fs_uuid);
1214 if (r < 0)
1215 goto fail;
1216
1217 r = run_fsck(setup->dm_node, fstype);
1218 if (r < 0)
1219 goto fail;
1220
1221 r = home_unshare_and_mount(setup->dm_node, fstype, user_record_luks_discard(h), user_record_mount_flags(h));
1222 if (r < 0)
1223 goto fail;
1224
1225 mounted = true;
1226
1227 root_fd = open(subdir, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
1228 if (root_fd < 0) {
1229 r = log_error_errno(r, "Failed to open home directory: %m");
1230 goto fail;
1231 }
1232
1233 if (user_record_luks_discard(h))
1234 (void) run_fitrim(root_fd);
1235
1236 setup->image_fd = TAKE_FD(image_fd);
1237 setup->do_offline_fallocate = !(setup->do_offline_fitrim = user_record_luks_offline_discard(h));
1238 setup->do_mark_clean = marked_dirty;
1239 }
1240
1241 setup->loop = TAKE_PTR(loop);
1242 setup->crypt_device = TAKE_PTR(cd);
1243 setup->root_fd = TAKE_FD(root_fd);
1244 setup->found_partition_uuid = found_partition_uuid;
1245 setup->found_luks_uuid = found_luks_uuid;
1246 setup->found_fs_uuid = found_fs_uuid;
1247 setup->partition_offset = offset;
1248 setup->partition_size = size;
1249 setup->volume_key = TAKE_PTR(volume_key);
1250 setup->volume_key_size = volume_key_size;
1251
1252 setup->undo_mount = mounted;
1253 setup->undo_dm = dm_activated;
1254
1255 if (ret_luks_home)
1256 *ret_luks_home = TAKE_PTR(luks_home);
1257
1258 return 0;
1259
1260 fail:
1261 if (mounted)
1262 (void) umount_verbose(LOG_ERR, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW);
1263
1264 if (dm_activated)
1265 (void) crypt_deactivate(cd, setup->dm_name);
1266
1267 if (image_fd >= 0 && marked_dirty)
1268 (void) run_mark_dirty(image_fd, false);
1269
1270 return r;
1271 }
1272
1273 static void print_size_summary(uint64_t host_size, uint64_t encrypted_size, struct statfs *sfs) {
1274 char buffer1[FORMAT_BYTES_MAX], buffer2[FORMAT_BYTES_MAX], buffer3[FORMAT_BYTES_MAX], buffer4[FORMAT_BYTES_MAX];
1275
1276 assert(sfs);
1277
1278 log_info("Image size is %s, file system size is %s, file system payload size is %s, file system free is %s.",
1279 format_bytes(buffer1, sizeof(buffer1), host_size),
1280 format_bytes(buffer2, sizeof(buffer2), encrypted_size),
1281 format_bytes(buffer3, sizeof(buffer3), (uint64_t) sfs->f_blocks * (uint64_t) sfs->f_frsize),
1282 format_bytes(buffer4, sizeof(buffer4), (uint64_t) sfs->f_bfree * (uint64_t) sfs->f_frsize));
1283 }
1284
1285 int home_activate_luks(
1286 UserRecord *h,
1287 PasswordCache *cache,
1288 UserRecord **ret_home) {
1289
1290 _cleanup_(user_record_unrefp) UserRecord *new_home = NULL, *luks_home_record = NULL;
1291 _cleanup_(home_setup_undo) HomeSetup setup = HOME_SETUP_INIT;
1292 uint64_t host_size, encrypted_size;
1293 const char *hdo, *hd;
1294 struct statfs sfs;
1295 int r;
1296
1297 assert(h);
1298 assert(user_record_storage(h) == USER_LUKS);
1299 assert(ret_home);
1300
1301 assert_se(hdo = user_record_home_directory(h));
1302 hd = strdupa(hdo); /* copy the string out, since it might change later in the home record object */
1303
1304 r = make_dm_names(h->user_name, &setup.dm_name, &setup.dm_node);
1305 if (r < 0)
1306 return r;
1307
1308 r = access(setup.dm_node, F_OK);
1309 if (r < 0) {
1310 if (errno != ENOENT)
1311 return log_error_errno(errno, "Failed to determine whether %s exists: %m", setup.dm_node);
1312 } else
1313 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Device mapper device %s already exists, refusing.", setup.dm_node);
1314
1315 r = home_prepare_luks(
1316 h,
1317 false,
1318 NULL,
1319 cache,
1320 &setup,
1321 &luks_home_record);
1322 if (r < 0)
1323 return r;
1324
1325 r = block_get_size_by_fd(setup.loop->fd, &host_size);
1326 if (r < 0)
1327 return log_error_errno(r, "Failed to get loopback block device size: %m");
1328
1329 r = block_get_size_by_path(setup.dm_node, &encrypted_size);
1330 if (r < 0)
1331 return log_error_errno(r, "Failed to get LUKS block device size: %m");
1332
1333 r = home_refresh(
1334 h,
1335 &setup,
1336 luks_home_record,
1337 cache,
1338 &sfs,
1339 &new_home);
1340 if (r < 0)
1341 return r;
1342
1343 r = home_extend_embedded_identity(new_home, h, &setup);
1344 if (r < 0)
1345 return r;
1346
1347 setup.root_fd = safe_close(setup.root_fd);
1348
1349 r = home_move_mount(user_record_user_name_and_realm(h), hd);
1350 if (r < 0)
1351 return r;
1352
1353 setup.undo_mount = false;
1354 setup.do_offline_fitrim = false;
1355
1356 loop_device_relinquish(setup.loop);
1357
1358 r = crypt_deactivate_by_name(NULL, setup.dm_name, CRYPT_DEACTIVATE_DEFERRED);
1359 if (r < 0)
1360 log_warning_errno(r, "Failed to relinquish DM device, ignoring: %m");
1361
1362 setup.undo_dm = false;
1363 setup.do_offline_fallocate = false;
1364 setup.do_mark_clean = false;
1365
1366 log_info("Everything completed.");
1367
1368 print_size_summary(host_size, encrypted_size, &sfs);
1369
1370 *ret_home = TAKE_PTR(new_home);
1371 return 1;
1372 }
1373
1374 int home_deactivate_luks(UserRecord *h) {
1375 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1376 _cleanup_free_ char *dm_name = NULL, *dm_node = NULL;
1377 bool we_detached;
1378 int r;
1379
1380 /* Note that the DM device and loopback device are set to auto-detach, hence strictly speaking we
1381 * don't have to explicitly have to detach them. However, we do that nonetheless (in case of the DM
1382 * device), to avoid races: by explicitly detaching them we know when the detaching is complete. We
1383 * don't bother about the loopback device because unlike the DM device it doesn't have a fixed
1384 * name. */
1385
1386 r = make_dm_names(h->user_name, &dm_name, &dm_node);
1387 if (r < 0)
1388 return r;
1389
1390 r = crypt_init_by_name(&cd, dm_name);
1391 if (IN_SET(r, -ENODEV, -EINVAL, -ENOENT)) {
1392 log_debug_errno(r, "LUKS device %s has already been detached.", dm_name);
1393 we_detached = false;
1394 } else if (r < 0)
1395 return log_error_errno(r, "Failed to initialize cryptsetup context for %s: %m", dm_name);
1396 else {
1397 log_info("Discovered used LUKS device %s.", dm_node);
1398
1399 cryptsetup_enable_logging(cd);
1400
1401 r = crypt_deactivate(cd, dm_name);
1402 if (IN_SET(r, -ENODEV, -EINVAL, -ENOENT)) {
1403 log_debug_errno(r, "LUKS device %s is already detached.", dm_node);
1404 we_detached = false;
1405 } else if (r < 0)
1406 return log_info_errno(r, "LUKS device %s couldn't be deactivated: %m", dm_node);
1407 else {
1408 log_info("LUKS device detaching completed.");
1409 we_detached = true;
1410 }
1411 }
1412
1413 if (user_record_luks_offline_discard(h))
1414 log_debug("Not allocating on logout.");
1415 else
1416 (void) run_fallocate_by_path(user_record_image_path(h));
1417
1418 run_mark_dirty_by_path(user_record_image_path(h), false);
1419 return we_detached;
1420 }
1421
1422 int home_trim_luks(UserRecord *h) {
1423 assert(h);
1424
1425 if (!user_record_luks_offline_discard(h)) {
1426 log_debug("Not trimming on logout.");
1427 return 0;
1428 }
1429
1430 (void) run_fitrim_by_path(user_record_home_directory(h));
1431 return 0;
1432 }
1433
1434 static struct crypt_pbkdf_type* build_good_pbkdf(struct crypt_pbkdf_type *buffer, UserRecord *hr) {
1435 assert(buffer);
1436 assert(hr);
1437
1438 *buffer = (struct crypt_pbkdf_type) {
1439 .hash = user_record_luks_pbkdf_hash_algorithm(hr),
1440 .type = user_record_luks_pbkdf_type(hr),
1441 .time_ms = user_record_luks_pbkdf_time_cost_usec(hr) / USEC_PER_MSEC,
1442 .max_memory_kb = user_record_luks_pbkdf_memory_cost(hr) / 1024,
1443 .parallel_threads = user_record_luks_pbkdf_parallel_threads(hr),
1444 };
1445
1446 return buffer;
1447 }
1448
1449 static struct crypt_pbkdf_type* build_minimal_pbkdf(struct crypt_pbkdf_type *buffer, UserRecord *hr) {
1450 assert(buffer);
1451 assert(hr);
1452
1453 /* For PKCS#11 derived keys (which are generated randomly and are of high quality already) we use a
1454 * minimal PBKDF */
1455 *buffer = (struct crypt_pbkdf_type) {
1456 .hash = user_record_luks_pbkdf_hash_algorithm(hr),
1457 .type = CRYPT_KDF_PBKDF2,
1458 .iterations = 1,
1459 .time_ms = 1,
1460 };
1461
1462 return buffer;
1463 }
1464
1465 static int luks_format(
1466 const char *node,
1467 const char *dm_name,
1468 sd_id128_t uuid,
1469 const char *label,
1470 const PasswordCache *cache,
1471 char **effective_passwords,
1472 bool discard,
1473 UserRecord *hr,
1474 struct crypt_device **ret) {
1475
1476 _cleanup_(user_record_unrefp) UserRecord *reduced = NULL;
1477 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1478 _cleanup_(erase_and_freep) void *volume_key = NULL;
1479 struct crypt_pbkdf_type good_pbkdf, minimal_pbkdf;
1480 char suuid[ID128_UUID_STRING_MAX], **pp;
1481 _cleanup_free_ char *text = NULL;
1482 size_t volume_key_size;
1483 int slot = 0, r;
1484
1485 assert(node);
1486 assert(dm_name);
1487 assert(hr);
1488 assert(ret);
1489
1490 r = crypt_init(&cd, node);
1491 if (r < 0)
1492 return log_error_errno(r, "Failed to allocate libcryptsetup context: %m");
1493
1494 cryptsetup_enable_logging(cd);
1495
1496 /* Normally we'd, just leave volume key generation to libcryptsetup. However, we can't, since we
1497 * can't extract the volume key from the library again, but we need it in order to encrypt the JSON
1498 * record. Hence, let's generate it on our own, so that we can keep track of it. */
1499
1500 volume_key_size = user_record_luks_volume_key_size(hr);
1501 volume_key = malloc(volume_key_size);
1502 if (!volume_key)
1503 return log_oom();
1504
1505 r = genuine_random_bytes(volume_key, volume_key_size, RANDOM_BLOCK);
1506 if (r < 0)
1507 return log_error_errno(r, "Failed to generate volume key: %m");
1508
1509 #if HAVE_CRYPT_SET_METADATA_SIZE
1510 /* Increase the metadata space to 4M, the largest LUKS2 supports */
1511 r = crypt_set_metadata_size(cd, 4096U*1024U, 0);
1512 if (r < 0)
1513 return log_error_errno(r, "Failed to change LUKS2 metadata size: %m");
1514 #endif
1515
1516 build_good_pbkdf(&good_pbkdf, hr);
1517 build_minimal_pbkdf(&minimal_pbkdf, hr);
1518
1519 r = crypt_format(cd,
1520 CRYPT_LUKS2,
1521 user_record_luks_cipher(hr),
1522 user_record_luks_cipher_mode(hr),
1523 id128_to_uuid_string(uuid, suuid),
1524 volume_key,
1525 volume_key_size,
1526 &(struct crypt_params_luks2) {
1527 .label = label,
1528 .subsystem = "systemd-home",
1529 .sector_size = 512U,
1530 .pbkdf = &good_pbkdf,
1531 });
1532 if (r < 0)
1533 return log_error_errno(r, "Failed to format LUKS image: %m");
1534
1535 log_info("LUKS formatting completed.");
1536
1537 STRV_FOREACH(pp, effective_passwords) {
1538
1539 if (strv_contains(cache->pkcs11_passwords, *pp) ||
1540 strv_contains(cache->fido2_passwords, *pp)) {
1541 log_debug("Using minimal PBKDF for slot %i", slot);
1542 r = crypt_set_pbkdf_type(cd, &minimal_pbkdf);
1543 } else {
1544 log_debug("Using good PBKDF for slot %i", slot);
1545 r = crypt_set_pbkdf_type(cd, &good_pbkdf);
1546 }
1547 if (r < 0)
1548 return log_error_errno(r, "Failed to tweak PBKDF for slot %i: %m", slot);
1549
1550 r = crypt_keyslot_add_by_volume_key(
1551 cd,
1552 slot,
1553 volume_key,
1554 volume_key_size,
1555 *pp,
1556 strlen(*pp));
1557 if (r < 0)
1558 return log_error_errno(r, "Failed to set up LUKS password for slot %i: %m", slot);
1559
1560 log_info("Writing password to LUKS keyslot %i completed.", slot);
1561 slot++;
1562 }
1563
1564 r = crypt_activate_by_volume_key(
1565 cd,
1566 dm_name,
1567 volume_key,
1568 volume_key_size,
1569 discard ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0);
1570 if (r < 0)
1571 return log_error_errno(r, "Failed to activate LUKS superblock: %m");
1572
1573 log_info("LUKS activation by volume key succeeded.");
1574
1575 r = user_record_clone(hr, USER_RECORD_EXTRACT_EMBEDDED, &reduced);
1576 if (r < 0)
1577 return log_error_errno(r, "Failed to prepare home record for LUKS: %m");
1578
1579 r = format_luks_token_text(cd, reduced, volume_key, &text);
1580 if (r < 0)
1581 return r;
1582
1583 r = crypt_token_json_set(cd, CRYPT_ANY_TOKEN, text);
1584 if (r < 0)
1585 return log_error_errno(r, "Failed to set LUKS JSON token: %m");
1586
1587 log_info("Writing user record as LUKS token completed.");
1588
1589 if (ret)
1590 *ret = TAKE_PTR(cd);
1591
1592 return 0;
1593 }
1594
1595 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_context*, fdisk_unref_context);
1596 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_partition*, fdisk_unref_partition);
1597 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_parttype*, fdisk_unref_parttype);
1598 DEFINE_TRIVIAL_CLEANUP_FUNC(struct fdisk_table*, fdisk_unref_table);
1599
1600 static int make_partition_table(
1601 int fd,
1602 const char *label,
1603 sd_id128_t uuid,
1604 uint64_t *ret_offset,
1605 uint64_t *ret_size,
1606 sd_id128_t *ret_disk_uuid) {
1607
1608 _cleanup_(fdisk_unref_partitionp) struct fdisk_partition *p = NULL, *q = NULL;
1609 _cleanup_(fdisk_unref_parttypep) struct fdisk_parttype *t = NULL;
1610 _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
1611 _cleanup_free_ char *path = NULL, *disk_uuid_as_string = NULL;
1612 uint64_t offset, size;
1613 sd_id128_t disk_uuid;
1614 char uuids[ID128_UUID_STRING_MAX];
1615 int r;
1616
1617 assert(fd >= 0);
1618 assert(label);
1619 assert(ret_offset);
1620 assert(ret_size);
1621
1622 t = fdisk_new_parttype();
1623 if (!t)
1624 return log_oom();
1625
1626 r = fdisk_parttype_set_typestr(t, "773f91ef-66d4-49b5-bd83-d683bf40ad16");
1627 if (r < 0)
1628 return log_error_errno(r, "Failed to initialize partition type: %m");
1629
1630 c = fdisk_new_context();
1631 if (!c)
1632 return log_oom();
1633
1634 if (asprintf(&path, "/proc/self/fd/%i", fd) < 0)
1635 return log_oom();
1636
1637 r = fdisk_assign_device(c, path, 0);
1638 if (r < 0)
1639 return log_error_errno(r, "Failed to open device: %m");
1640
1641 r = fdisk_create_disklabel(c, "gpt");
1642 if (r < 0)
1643 return log_error_errno(r, "Failed to create GPT disk label: %m");
1644
1645 p = fdisk_new_partition();
1646 if (!p)
1647 return log_oom();
1648
1649 r = fdisk_partition_set_type(p, t);
1650 if (r < 0)
1651 return log_error_errno(r, "Failed to set partition type: %m");
1652
1653 r = fdisk_partition_start_follow_default(p, 1);
1654 if (r < 0)
1655 return log_error_errno(r, "Failed to place partition at beginning of space: %m");
1656
1657 r = fdisk_partition_partno_follow_default(p, 1);
1658 if (r < 0)
1659 return log_error_errno(r, "Failed to place partition at first free partition index: %m");
1660
1661 r = fdisk_partition_end_follow_default(p, 1);
1662 if (r < 0)
1663 return log_error_errno(r, "Failed to make partition cover all free space: %m");
1664
1665 r = fdisk_partition_set_name(p, label);
1666 if (r < 0)
1667 return log_error_errno(r, "Failed to set partition name: %m");
1668
1669 r = fdisk_partition_set_uuid(p, id128_to_uuid_string(uuid, uuids));
1670 if (r < 0)
1671 return log_error_errno(r, "Failed to set partition UUID: %m");
1672
1673 r = fdisk_add_partition(c, p, NULL);
1674 if (r < 0)
1675 return log_error_errno(r, "Failed to add partition: %m");
1676
1677 r = fdisk_write_disklabel(c);
1678 if (r < 0)
1679 return log_error_errno(r, "Failed to write disk label: %m");
1680
1681 r = fdisk_get_disklabel_id(c, &disk_uuid_as_string);
1682 if (r < 0)
1683 return log_error_errno(r, "Failed to determine disk label UUID: %m");
1684
1685 r = sd_id128_from_string(disk_uuid_as_string, &disk_uuid);
1686 if (r < 0)
1687 return log_error_errno(r, "Failed to parse disk label UUID: %m");
1688
1689 r = fdisk_get_partition(c, 0, &q);
1690 if (r < 0)
1691 return log_error_errno(r, "Failed to read created partition metadata: %m");
1692
1693 assert(fdisk_partition_has_start(q));
1694 offset = fdisk_partition_get_start(q);
1695 if (offset > UINT64_MAX / 512U)
1696 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Partition offset too large.");
1697
1698 assert(fdisk_partition_has_size(q));
1699 size = fdisk_partition_get_size(q);
1700 if (size > UINT64_MAX / 512U)
1701 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Partition size too large.");
1702
1703 *ret_offset = offset * 512U;
1704 *ret_size = size * 512U;
1705 *ret_disk_uuid = disk_uuid;
1706
1707 return 0;
1708 }
1709
1710 static bool supported_fs_size(const char *fstype, uint64_t host_size) {
1711 uint64_t m;
1712
1713 m = minimal_size_by_fs_name(fstype);
1714 if (m == UINT64_MAX)
1715 return false;
1716
1717 return host_size >= m;
1718 }
1719
1720 static int wait_for_devlink(const char *path) {
1721 _cleanup_close_ int inotify_fd = -1;
1722 usec_t until;
1723 int r;
1724
1725 /* let's wait for a device link to show up in /dev, with a timeout. This is good to do since we
1726 * return a /dev/disk/by-uuid/… link to our callers and they likely want to access it right-away,
1727 * hence let's wait until udev has caught up with our changes, and wait for the symlink to be
1728 * created. */
1729
1730 until = usec_add(now(CLOCK_MONOTONIC), 45 * USEC_PER_SEC);
1731
1732 for (;;) {
1733 _cleanup_free_ char *dn = NULL;
1734 usec_t w;
1735
1736 if (laccess(path, F_OK) < 0) {
1737 if (errno != ENOENT)
1738 return log_error_errno(errno, "Failed to determine whether %s exists: %m", path);
1739 } else
1740 return 0; /* Found it */
1741
1742 if (inotify_fd < 0) {
1743 /* We need to wait for the device symlink to show up, let's create an inotify watch for it */
1744 inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1745 if (inotify_fd < 0)
1746 return log_error_errno(errno, "Failed to allocate inotify fd: %m");
1747 }
1748
1749 dn = dirname_malloc(path);
1750 for (;;) {
1751 if (!dn)
1752 return log_oom();
1753
1754 log_info("Watching %s", dn);
1755
1756 if (inotify_add_watch(inotify_fd, dn, IN_CREATE|IN_MOVED_TO|IN_ONLYDIR|IN_DELETE_SELF|IN_MOVE_SELF) < 0) {
1757 if (errno != ENOENT)
1758 return log_error_errno(errno, "Failed to add watch on %s: %m", dn);
1759 } else
1760 break;
1761
1762 if (empty_or_root(dn))
1763 break;
1764
1765 dn = dirname_malloc(dn);
1766 }
1767
1768 w = now(CLOCK_MONOTONIC);
1769 if (w >= until)
1770 return log_error_errno(SYNTHETIC_ERRNO(ETIMEDOUT), "Device link %s still hasn't shown up, giving up.", path);
1771
1772 r = fd_wait_for_event(inotify_fd, POLLIN, usec_sub_unsigned(until, w));
1773 if (r < 0)
1774 return log_error_errno(r, "Failed to watch inotify: %m");
1775
1776 (void) flush_fd(inotify_fd);
1777 }
1778 }
1779
1780 static int calculate_disk_size(UserRecord *h, const char *parent_dir, uint64_t *ret) {
1781 char buf[FORMAT_BYTES_MAX];
1782 struct statfs sfs;
1783 uint64_t m;
1784
1785 assert(h);
1786 assert(parent_dir);
1787 assert(ret);
1788
1789 if (h->disk_size != UINT64_MAX) {
1790 *ret = DISK_SIZE_ROUND_DOWN(h->disk_size);
1791 return 0;
1792 }
1793
1794 if (statfs(parent_dir, &sfs) < 0)
1795 return log_error_errno(errno, "statfs() on %s failed: %m", parent_dir);
1796
1797 m = sfs.f_bsize * sfs.f_bavail;
1798
1799 if (h->disk_size_relative == UINT64_MAX) {
1800
1801 if (m > UINT64_MAX / USER_DISK_SIZE_DEFAULT_PERCENT)
1802 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Disk size too large.");
1803
1804 *ret = DISK_SIZE_ROUND_DOWN(m * USER_DISK_SIZE_DEFAULT_PERCENT / 100);
1805
1806 log_info("Sizing home to %u%% of available disk space, which is %s.",
1807 USER_DISK_SIZE_DEFAULT_PERCENT,
1808 format_bytes(buf, sizeof(buf), *ret));
1809 } else {
1810 *ret = DISK_SIZE_ROUND_DOWN((uint64_t) ((double) m * (double) h->disk_size_relative / (double) UINT32_MAX));
1811
1812 log_info("Sizing home to %" PRIu64 ".%01" PRIu64 "%% of available disk space, which is %s.",
1813 (h->disk_size_relative * 100) / UINT32_MAX,
1814 ((h->disk_size_relative * 1000) / UINT32_MAX) % 10,
1815 format_bytes(buf, sizeof(buf), *ret));
1816 }
1817
1818 if (*ret < USER_DISK_SIZE_MIN)
1819 *ret = USER_DISK_SIZE_MIN;
1820
1821 return 0;
1822 }
1823
1824 static int home_truncate(
1825 UserRecord *h,
1826 int fd,
1827 const char *path,
1828 uint64_t size) {
1829
1830 bool trunc;
1831 int r;
1832
1833 assert(h);
1834 assert(fd >= 0);
1835 assert(path);
1836
1837 trunc = user_record_luks_discard(h);
1838 if (!trunc) {
1839 r = fallocate(fd, 0, 0, size);
1840 if (r < 0 && ERRNO_IS_NOT_SUPPORTED(errno)) {
1841 /* Some file systems do not support fallocate(), let's gracefully degrade
1842 * (ZFS, reiserfs, …) and fall back to truncation */
1843 log_notice_errno(errno, "Backing file system does not support fallocate(), falling back to ftruncate(), i.e. implicitly using non-discard mode.");
1844 trunc = true;
1845 }
1846 }
1847
1848 if (trunc)
1849 r = ftruncate(fd, size);
1850
1851 if (r < 0) {
1852 if (ERRNO_IS_DISK_SPACE(errno)) {
1853 log_error_errno(errno, "Not enough disk space to allocate home.");
1854 return -ENOSPC; /* make recognizable */
1855 }
1856
1857 return log_error_errno(errno, "Failed to truncate home image %s: %m", path);
1858 }
1859
1860 return 0;
1861 }
1862
1863 int home_create_luks(
1864 UserRecord *h,
1865 PasswordCache *cache,
1866 char **effective_passwords,
1867 UserRecord **ret_home) {
1868
1869 _cleanup_free_ char *dm_name = NULL, *dm_node = NULL, *subdir = NULL, *disk_uuid_path = NULL, *temporary_image_path = NULL;
1870 uint64_t host_size, encrypted_size, partition_offset, partition_size;
1871 bool image_created = false, dm_activated = false, mounted = false;
1872 _cleanup_(user_record_unrefp) UserRecord *new_home = NULL;
1873 sd_id128_t partition_uuid, fs_uuid, luks_uuid, disk_uuid;
1874 _cleanup_(loop_device_unrefp) LoopDevice *loop = NULL;
1875 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1876 _cleanup_close_ int image_fd = -1, root_fd = -1;
1877 const char *fstype, *ip;
1878 struct statfs sfs;
1879 int r;
1880
1881 assert(h);
1882 assert(h->storage < 0 || h->storage == USER_LUKS);
1883 assert(ret_home);
1884
1885 assert_se(ip = user_record_image_path(h));
1886
1887 fstype = user_record_file_system_type(h);
1888 if (!supported_fstype(fstype))
1889 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "Unsupported file system type: %s", fstype);
1890
1891 r = mkfs_exists(fstype);
1892 if (r < 0)
1893 return log_error_errno(r, "Failed to check if mkfs binary for %s exists: %m", fstype);
1894 if (r == 0) {
1895 if (h->file_system_type || streq(fstype, "ext4") || !supported_fstype("ext4"))
1896 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "mkfs binary for file system type %s does not exist.", fstype);
1897
1898 /* If the record does not explicitly declare a file system to use, and the compiled-in
1899 * default does not actually exist, than do an automatic fallback onto ext4, as the baseline
1900 * fs of Linux. We won't search for a working fs type here beyond ext4, i.e. nothing fancier
1901 * than a single, conservative fallback to baseline. This should be useful in minimal
1902 * environments where mkfs.btrfs or so are not made available, but mkfs.ext4 as Linux' most
1903 * boring, most basic fs is. */
1904 log_info("Formatting tool for compiled-in default file system %s not available, falling back to ext4 instead.", fstype);
1905 fstype = "ext4";
1906 }
1907
1908 if (sd_id128_is_null(h->partition_uuid)) {
1909 r = sd_id128_randomize(&partition_uuid);
1910 if (r < 0)
1911 return log_error_errno(r, "Failed to acquire partition UUID: %m");
1912 } else
1913 partition_uuid = h->partition_uuid;
1914
1915 if (sd_id128_is_null(h->luks_uuid)) {
1916 r = sd_id128_randomize(&luks_uuid);
1917 if (r < 0)
1918 return log_error_errno(r, "Failed to acquire LUKS UUID: %m");
1919 } else
1920 luks_uuid = h->luks_uuid;
1921
1922 if (sd_id128_is_null(h->file_system_uuid)) {
1923 r = sd_id128_randomize(&fs_uuid);
1924 if (r < 0)
1925 return log_error_errno(r, "Failed to acquire file system UUID: %m");
1926 } else
1927 fs_uuid = h->file_system_uuid;
1928
1929 r = make_dm_names(h->user_name, &dm_name, &dm_node);
1930 if (r < 0)
1931 return r;
1932
1933 r = access(dm_node, F_OK);
1934 if (r < 0) {
1935 if (errno != ENOENT)
1936 return log_error_errno(errno, "Failed to determine whether %s exists: %m", dm_node);
1937 } else
1938 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Device mapper device %s already exists, refusing.", dm_node);
1939
1940 if (path_startswith(ip, "/dev/")) {
1941 _cleanup_free_ char *sysfs = NULL;
1942 uint64_t block_device_size;
1943 struct stat st;
1944
1945 /* Let's place the home directory on a real device, i.e. an USB stick or such */
1946
1947 image_fd = open(ip, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
1948 if (image_fd < 0)
1949 return log_error_errno(errno, "Failed to open device %s: %m", ip);
1950
1951 if (fstat(image_fd, &st) < 0)
1952 return log_error_errno(errno, "Failed to stat device %s: %m", ip);
1953 if (!S_ISBLK(st.st_mode))
1954 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK), "Device is not a block device, refusing.");
1955
1956 if (asprintf(&sysfs, "/sys/dev/block/%u:%u/partition", major(st.st_rdev), minor(st.st_rdev)) < 0)
1957 return log_oom();
1958 if (access(sysfs, F_OK) < 0) {
1959 if (errno != ENOENT)
1960 return log_error_errno(errno, "Failed to check whether %s exists: %m", sysfs);
1961 } else
1962 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK), "Operating on partitions is currently not supported, sorry. Please specify a top-level block device.");
1963
1964 if (flock(image_fd, LOCK_EX) < 0) /* make sure udev doesn't read from it while we operate on the device */
1965 return log_error_errno(errno, "Failed to lock block device %s: %m", ip);
1966
1967 if (ioctl(image_fd, BLKGETSIZE64, &block_device_size) < 0)
1968 return log_error_errno(errno, "Failed to read block device size: %m");
1969
1970 if (h->disk_size == UINT64_MAX) {
1971
1972 /* If a relative disk size is requested, apply it relative to the block device size */
1973 if (h->disk_size_relative < UINT32_MAX)
1974 host_size = CLAMP(DISK_SIZE_ROUND_DOWN(block_device_size * h->disk_size_relative / UINT32_MAX),
1975 USER_DISK_SIZE_MIN, USER_DISK_SIZE_MAX);
1976 else
1977 host_size = block_device_size; /* Otherwise, take the full device */
1978
1979 } else if (h->disk_size > block_device_size)
1980 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE), "Selected disk size larger than backing block device, refusing.");
1981 else
1982 host_size = DISK_SIZE_ROUND_DOWN(h->disk_size);
1983
1984 if (!supported_fs_size(fstype, host_size))
1985 return log_error_errno(SYNTHETIC_ERRNO(ERANGE),
1986 "Selected file system size too small for %s.", fstype);
1987
1988 /* After creation we should reference this partition by its UUID instead of the block
1989 * device. That's preferable since the user might have specified a device node such as
1990 * /dev/sdb to us, which might look very different when replugged. */
1991 if (asprintf(&disk_uuid_path, "/dev/disk/by-uuid/" SD_ID128_UUID_FORMAT_STR, SD_ID128_FORMAT_VAL(luks_uuid)) < 0)
1992 return log_oom();
1993
1994 if (user_record_luks_discard(h) || user_record_luks_offline_discard(h)) {
1995 /* If we want online or offline discard, discard once before we start using things. */
1996
1997 if (ioctl(image_fd, BLKDISCARD, (uint64_t[]) { 0, block_device_size }) < 0)
1998 log_full_errno(errno == EOPNOTSUPP ? LOG_DEBUG : LOG_WARNING, errno,
1999 "Failed to issue full-device BLKDISCARD on device, ignoring: %m");
2000 else
2001 log_info("Full device discard completed.");
2002 }
2003 } else {
2004 _cleanup_free_ char *parent = NULL;
2005
2006 parent = dirname_malloc(ip);
2007 if (!parent)
2008 return log_oom();
2009
2010 r = mkdir_p(parent, 0755);
2011 if (r < 0)
2012 return log_error_errno(r, "Failed to create parent directory %s: %m", parent);
2013
2014 r = calculate_disk_size(h, parent, &host_size);
2015 if (r < 0)
2016 return r;
2017
2018 if (!supported_fs_size(fstype, host_size))
2019 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Selected file system size too small for %s.", fstype);
2020
2021 r = tempfn_random(ip, "homework", &temporary_image_path);
2022 if (r < 0)
2023 return log_error_errno(r, "Failed to derive temporary file name for %s: %m", ip);
2024
2025 image_fd = open(temporary_image_path, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
2026 if (image_fd < 0)
2027 return log_error_errno(errno, "Failed to create home image %s: %m", temporary_image_path);
2028
2029 image_created = true;
2030
2031 r = chattr_fd(image_fd, FS_NOCOW_FL, FS_NOCOW_FL, NULL);
2032 if (r < 0)
2033 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
2034 "Failed to set file attributes on %s, ignoring: %m", temporary_image_path);
2035
2036 r = home_truncate(h, image_fd, temporary_image_path, host_size);
2037 if (r < 0)
2038 goto fail;
2039
2040 log_info("Allocating image file completed.");
2041 }
2042
2043 r = make_partition_table(
2044 image_fd,
2045 user_record_user_name_and_realm(h),
2046 partition_uuid,
2047 &partition_offset,
2048 &partition_size,
2049 &disk_uuid);
2050 if (r < 0)
2051 goto fail;
2052
2053 log_info("Writing of partition table completed.");
2054
2055 r = loop_device_make(image_fd, O_RDWR, partition_offset, partition_size, 0, &loop);
2056 if (r < 0) {
2057 if (r == -ENOENT) { /* this means /dev/loop-control doesn't exist, i.e. we are in a container
2058 * or similar and loopback bock devices are not available, return a
2059 * recognizable error in this case. */
2060 log_error_errno(r, "Loopback block device support is not available on this system.");
2061 r = -ENOLINK;
2062 goto fail;
2063 }
2064
2065 log_error_errno(r, "Failed to set up loopback device for %s: %m", temporary_image_path);
2066 goto fail;
2067 }
2068
2069 r = loop_device_flock(loop, LOCK_EX); /* make sure udev won't read before we are done */
2070 if (r < 0) {
2071 log_error_errno(r, "Failed to take lock on loop device: %m");
2072 goto fail;
2073 }
2074
2075 log_info("Setting up loopback device %s completed.", loop->node ?: ip);
2076
2077 r = luks_format(loop->node,
2078 dm_name,
2079 luks_uuid,
2080 user_record_user_name_and_realm(h),
2081 cache,
2082 effective_passwords,
2083 user_record_luks_discard(h) || user_record_luks_offline_discard(h),
2084 h,
2085 &cd);
2086 if (r < 0)
2087 goto fail;
2088
2089 dm_activated = true;
2090
2091 r = block_get_size_by_path(dm_node, &encrypted_size);
2092 if (r < 0) {
2093 log_error_errno(r, "Failed to get encrypted block device size: %m");
2094 goto fail;
2095 }
2096
2097 log_info("Setting up LUKS device %s completed.", dm_node);
2098
2099 r = make_filesystem(dm_node, fstype, user_record_user_name_and_realm(h), fs_uuid, user_record_luks_discard(h));
2100 if (r < 0)
2101 goto fail;
2102
2103 log_info("Formatting file system completed.");
2104
2105 r = home_unshare_and_mount(dm_node, fstype, user_record_luks_discard(h), user_record_mount_flags(h));
2106 if (r < 0)
2107 goto fail;
2108
2109 mounted = true;
2110
2111 subdir = path_join("/run/systemd/user-home-mount/", user_record_user_name_and_realm(h));
2112 if (!subdir) {
2113 r = log_oom();
2114 goto fail;
2115 }
2116
2117 /* Prefer using a btrfs subvolume if we can, fall back to directory otherwise */
2118 r = btrfs_subvol_make_fallback(subdir, 0700);
2119 if (r < 0) {
2120 log_error_errno(r, "Failed to create user directory in mounted image file: %m");
2121 goto fail;
2122 }
2123
2124 root_fd = open(subdir, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
2125 if (root_fd < 0) {
2126 r = log_error_errno(errno, "Failed to open user directory in mounted image file: %m");
2127 goto fail;
2128 }
2129
2130 r = home_populate(h, root_fd);
2131 if (r < 0)
2132 goto fail;
2133
2134 r = home_sync_and_statfs(root_fd, &sfs);
2135 if (r < 0)
2136 goto fail;
2137
2138 r = user_record_clone(h, USER_RECORD_LOAD_MASK_SECRET|USER_RECORD_LOG, &new_home);
2139 if (r < 0) {
2140 log_error_errno(r, "Failed to clone record: %m");
2141 goto fail;
2142 }
2143
2144 r = user_record_add_binding(
2145 new_home,
2146 USER_LUKS,
2147 disk_uuid_path ?: ip,
2148 partition_uuid,
2149 luks_uuid,
2150 fs_uuid,
2151 crypt_get_cipher(cd),
2152 crypt_get_cipher_mode(cd),
2153 luks_volume_key_size_convert(cd),
2154 fstype,
2155 NULL,
2156 h->uid,
2157 (gid_t) h->uid);
2158 if (r < 0) {
2159 log_error_errno(r, "Failed to add binding to record: %m");
2160 goto fail;
2161 }
2162
2163 if (user_record_luks_offline_discard(h)) {
2164 r = run_fitrim(root_fd);
2165 if (r < 0)
2166 goto fail;
2167 }
2168
2169 root_fd = safe_close(root_fd);
2170
2171 r = umount_verbose(LOG_ERR, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW);
2172 if (r < 0)
2173 goto fail;
2174
2175 mounted = false;
2176
2177 r = crypt_deactivate(cd, dm_name);
2178 if (r < 0) {
2179 log_error_errno(r, "Failed to deactivate LUKS device: %m");
2180 goto fail;
2181 }
2182
2183 crypt_free(cd);
2184 cd = NULL;
2185
2186 dm_activated = false;
2187
2188 loop = loop_device_unref(loop);
2189
2190 if (!user_record_luks_offline_discard(h)) {
2191 r = run_fallocate(image_fd, NULL /* refresh stat() data */);
2192 if (r < 0)
2193 goto fail;
2194 }
2195
2196 /* Sync everything to disk before we move things into place under the final name. */
2197 if (fsync(image_fd) < 0) {
2198 r = log_error_errno(r, "Failed to synchronize image to disk: %m");
2199 goto fail;
2200 }
2201
2202 if (disk_uuid_path)
2203 (void) ioctl(image_fd, BLKRRPART, 0);
2204 else {
2205 /* If we operate on a file, sync the containing directory too. */
2206 r = fsync_directory_of_file(image_fd);
2207 if (r < 0) {
2208 log_error_errno(r, "Failed to synchronize directory of image file to disk: %m");
2209 goto fail;
2210 }
2211 }
2212
2213 /* Let's close the image fd now. If we are operating on a real block device this will release the BSD
2214 * lock that ensures udev doesn't interfere with what we are doing */
2215 image_fd = safe_close(image_fd);
2216
2217 if (temporary_image_path) {
2218 if (rename(temporary_image_path, ip) < 0) {
2219 log_error_errno(errno, "Failed to rename image file: %m");
2220 goto fail;
2221 }
2222
2223 log_info("Moved image file into place.");
2224 }
2225
2226 if (disk_uuid_path)
2227 (void) wait_for_devlink(disk_uuid_path);
2228
2229 log_info("Everything completed.");
2230
2231 print_size_summary(host_size, encrypted_size, &sfs);
2232
2233 *ret_home = TAKE_PTR(new_home);
2234 return 0;
2235
2236 fail:
2237 /* Let's close all files before we unmount the file system, to avoid EBUSY */
2238 root_fd = safe_close(root_fd);
2239
2240 if (mounted)
2241 (void) umount_verbose(LOG_WARNING, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW);
2242
2243 if (dm_activated)
2244 (void) crypt_deactivate(cd, dm_name);
2245
2246 loop = loop_device_unref(loop);
2247
2248 if (image_created)
2249 (void) unlink(temporary_image_path);
2250
2251 return r;
2252 }
2253
2254 int home_validate_update_luks(UserRecord *h, HomeSetup *setup) {
2255 _cleanup_free_ char *dm_name = NULL, *dm_node = NULL;
2256 int r;
2257
2258 assert(h);
2259 assert(setup);
2260
2261 r = make_dm_names(h->user_name, &dm_name, &dm_node);
2262 if (r < 0)
2263 return r;
2264
2265 r = access(dm_node, F_OK);
2266 if (r < 0 && errno != ENOENT)
2267 return log_error_errno(errno, "Failed to determine whether %s exists: %m", dm_node);
2268
2269 free_and_replace(setup->dm_name, dm_name);
2270 free_and_replace(setup->dm_node, dm_node);
2271
2272 return r >= 0;
2273 }
2274
2275 enum {
2276 CAN_RESIZE_ONLINE,
2277 CAN_RESIZE_OFFLINE,
2278 };
2279
2280 static int can_resize_fs(int fd, uint64_t old_size, uint64_t new_size) {
2281 struct statfs sfs;
2282
2283 assert(fd >= 0);
2284
2285 /* Filter out bogus requests early */
2286 if (old_size == 0 || old_size == UINT64_MAX ||
2287 new_size == 0 || new_size == UINT64_MAX)
2288 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid resize parameters.");
2289
2290 if ((old_size & 511) != 0 || (new_size & 511) != 0)
2291 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Resize parameters not multiple of 512.");
2292
2293 if (fstatfs(fd, &sfs) < 0)
2294 return log_error_errno(errno, "Failed to fstatfs() file system: %m");
2295
2296 if (is_fs_type(&sfs, BTRFS_SUPER_MAGIC)) {
2297
2298 if (new_size < BTRFS_MINIMAL_SIZE)
2299 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "New file system size too small for btrfs (needs to be 256M at least.");
2300
2301 /* btrfs can grow and shrink online */
2302
2303 } else if (is_fs_type(&sfs, XFS_SB_MAGIC)) {
2304
2305 if (new_size < XFS_MINIMAL_SIZE)
2306 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "New file system size too small for xfs (needs to be 14M at least).");
2307
2308 /* XFS can grow, but not shrink */
2309 if (new_size < old_size)
2310 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE), "Shrinking this type of file system is not supported.");
2311
2312 } else if (is_fs_type(&sfs, EXT4_SUPER_MAGIC)) {
2313
2314 if (new_size < EXT4_MINIMAL_SIZE)
2315 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "New file system size too small for ext4 (needs to be 1M at least).");
2316
2317 /* ext4 can grow online, and shrink offline */
2318 if (new_size < old_size)
2319 return CAN_RESIZE_OFFLINE;
2320
2321 } else
2322 return log_error_errno(SYNTHETIC_ERRNO(ESOCKTNOSUPPORT), "Resizing this type of file system is not supported.");
2323
2324 return CAN_RESIZE_ONLINE;
2325 }
2326
2327 static int ext4_offline_resize_fs(HomeSetup *setup, uint64_t new_size, bool discard, unsigned long flags) {
2328 _cleanup_free_ char *size_str = NULL;
2329 bool re_open = false, re_mount = false;
2330 pid_t resize_pid, fsck_pid;
2331 int r, exit_status;
2332
2333 assert(setup);
2334 assert(setup->dm_node);
2335
2336 /* First, unmount the file system */
2337 if (setup->root_fd >= 0) {
2338 setup->root_fd = safe_close(setup->root_fd);
2339 re_open = true;
2340 }
2341
2342 if (setup->undo_mount) {
2343 r = umount_verbose(LOG_ERR, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW);
2344 if (r < 0)
2345 return r;
2346
2347 setup->undo_mount = false;
2348 re_mount = true;
2349 }
2350
2351 log_info("Temporary unmounting of file system completed.");
2352
2353 /* resize2fs requires that the file system is force checked first, do so. */
2354 r = safe_fork("(e2fsck)", FORK_RESET_SIGNALS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_LOG|FORK_STDOUT_TO_STDERR, &fsck_pid);
2355 if (r < 0)
2356 return r;
2357 if (r == 0) {
2358 /* Child */
2359 execlp("e2fsck" ,"e2fsck", "-fp", setup->dm_node, NULL);
2360 log_error_errno(errno, "Failed to execute e2fsck: %m");
2361 _exit(EXIT_FAILURE);
2362 }
2363
2364 exit_status = wait_for_terminate_and_check("e2fsck", fsck_pid, WAIT_LOG_ABNORMAL);
2365 if (exit_status < 0)
2366 return exit_status;
2367 if ((exit_status & ~FSCK_ERROR_CORRECTED) != 0) {
2368 log_warning("e2fsck failed with exit status %i.", exit_status);
2369
2370 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
2371 return log_error_errno(SYNTHETIC_ERRNO(EIO), "File system is corrupted, refusing.");
2372
2373 log_warning("Ignoring fsck error.");
2374 }
2375
2376 log_info("Forced file system check completed.");
2377
2378 /* We use 512 sectors here, because resize2fs doesn't do byte sizes */
2379 if (asprintf(&size_str, "%" PRIu64 "s", new_size / 512) < 0)
2380 return log_oom();
2381
2382 /* Resize the thing */
2383 r = safe_fork("(e2resize)", FORK_RESET_SIGNALS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_LOG|FORK_WAIT|FORK_STDOUT_TO_STDERR, &resize_pid);
2384 if (r < 0)
2385 return r;
2386 if (r == 0) {
2387 /* Child */
2388 execlp("resize2fs" ,"resize2fs", setup->dm_node, size_str, NULL);
2389 log_error_errno(errno, "Failed to execute resize2fs: %m");
2390 _exit(EXIT_FAILURE);
2391 }
2392
2393 log_info("Offline file system resize completed.");
2394
2395 /* Re-establish mounts and reopen the directory */
2396 if (re_mount) {
2397 r = home_mount_node(setup->dm_node, "ext4", discard, flags);
2398 if (r < 0)
2399 return r;
2400
2401 setup->undo_mount = true;
2402 }
2403
2404 if (re_open) {
2405 setup->root_fd = open("/run/systemd/user-home-mount", O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
2406 if (setup->root_fd < 0)
2407 return log_error_errno(errno, "Failed to reopen file system: %m");
2408 }
2409
2410 log_info("File system mounted again.");
2411
2412 return 0;
2413 }
2414
2415 static int prepare_resize_partition(
2416 int fd,
2417 uint64_t partition_offset,
2418 uint64_t old_partition_size,
2419 uint64_t new_partition_size,
2420 sd_id128_t *ret_disk_uuid,
2421 struct fdisk_table **ret_table) {
2422
2423 _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
2424 _cleanup_(fdisk_unref_tablep) struct fdisk_table *t = NULL;
2425 _cleanup_free_ char *path = NULL, *disk_uuid_as_string = NULL;
2426 size_t n_partitions, i;
2427 sd_id128_t disk_uuid;
2428 bool found = false;
2429 int r;
2430
2431 assert(fd >= 0);
2432 assert(ret_disk_uuid);
2433 assert(ret_table);
2434
2435 assert((partition_offset & 511) == 0);
2436 assert((old_partition_size & 511) == 0);
2437 assert((new_partition_size & 511) == 0);
2438 assert(UINT64_MAX - old_partition_size >= partition_offset);
2439 assert(UINT64_MAX - new_partition_size >= partition_offset);
2440
2441 if (partition_offset == 0) {
2442 /* If the offset is at the beginning we assume no partition table, let's exit early. */
2443 log_debug("Not rewriting partition table, operating on naked device.");
2444 *ret_disk_uuid = SD_ID128_NULL;
2445 *ret_table = NULL;
2446 return 0;
2447 }
2448
2449 c = fdisk_new_context();
2450 if (!c)
2451 return log_oom();
2452
2453 if (asprintf(&path, "/proc/self/fd/%i", fd) < 0)
2454 return log_oom();
2455
2456 r = fdisk_assign_device(c, path, 0);
2457 if (r < 0)
2458 return log_error_errno(r, "Failed to open device: %m");
2459
2460 if (!fdisk_is_labeltype(c, FDISK_DISKLABEL_GPT))
2461 return log_error_errno(SYNTHETIC_ERRNO(ENOMEDIUM), "Disk has no GPT partition table.");
2462
2463 r = fdisk_get_disklabel_id(c, &disk_uuid_as_string);
2464 if (r < 0)
2465 return log_error_errno(r, "Failed to acquire disk UUID: %m");
2466
2467 r = sd_id128_from_string(disk_uuid_as_string, &disk_uuid);
2468 if (r < 0)
2469 return log_error_errno(r, "Failed parse disk UUID: %m");
2470
2471 r = fdisk_get_partitions(c, &t);
2472 if (r < 0)
2473 return log_error_errno(r, "Failed to acquire partition table: %m");
2474
2475 n_partitions = fdisk_table_get_nents(t);
2476 for (i = 0; i < n_partitions; i++) {
2477 struct fdisk_partition *p;
2478
2479 p = fdisk_table_get_partition(t, i);
2480 if (!p)
2481 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata: %m");
2482
2483 if (fdisk_partition_is_used(p) <= 0)
2484 continue;
2485 if (fdisk_partition_has_start(p) <= 0 || fdisk_partition_has_size(p) <= 0 || fdisk_partition_has_end(p) <= 0)
2486 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Found partition without a size.");
2487
2488 if (fdisk_partition_get_start(p) == partition_offset / 512U &&
2489 fdisk_partition_get_size(p) == old_partition_size / 512U) {
2490
2491 if (found)
2492 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ), "Partition found twice, refusing.");
2493
2494 /* Found our partition, now patch it */
2495 r = fdisk_partition_size_explicit(p, 1);
2496 if (r < 0)
2497 return log_error_errno(r, "Failed to enable explicit partition size: %m");
2498
2499 r = fdisk_partition_set_size(p, new_partition_size / 512U);
2500 if (r < 0)
2501 return log_error_errno(r, "Failed to change partition size: %m");
2502
2503 found = true;
2504 continue;
2505
2506 } else {
2507 if (fdisk_partition_get_start(p) < partition_offset + new_partition_size / 512U &&
2508 fdisk_partition_get_end(p) >= partition_offset / 512)
2509 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Can't extend, conflicting partition found.");
2510 }
2511 }
2512
2513 if (!found)
2514 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to find matching partition to resize.");
2515
2516 *ret_table = TAKE_PTR(t);
2517 *ret_disk_uuid = disk_uuid;
2518
2519 return 1;
2520 }
2521
2522 static int ask_cb(struct fdisk_context *c, struct fdisk_ask *ask, void *userdata) {
2523 char *result;
2524
2525 assert(c);
2526
2527 switch (fdisk_ask_get_type(ask)) {
2528
2529 case FDISK_ASKTYPE_STRING:
2530 result = new(char, 37);
2531 if (!result)
2532 return log_oom();
2533
2534 fdisk_ask_string_set_result(ask, id128_to_uuid_string(*(sd_id128_t*) userdata, result));
2535 break;
2536
2537 default:
2538 log_debug("Unexpected question from libfdisk, ignoring.");
2539 }
2540
2541 return 0;
2542 }
2543
2544 static int apply_resize_partition(int fd, sd_id128_t disk_uuids, struct fdisk_table *t) {
2545 _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
2546 _cleanup_free_ void *two_zero_lbas = NULL;
2547 _cleanup_free_ char *path = NULL;
2548 ssize_t n;
2549 int r;
2550
2551 assert(fd >= 0);
2552
2553 if (!t) /* no partition table to apply, exit early */
2554 return 0;
2555
2556 two_zero_lbas = malloc0(1024U);
2557 if (!two_zero_lbas)
2558 return log_oom();
2559
2560 /* libfdisk appears to get confused by the existing PMBR. Let's explicitly flush it out. */
2561 n = pwrite(fd, two_zero_lbas, 1024U, 0);
2562 if (n < 0)
2563 return log_error_errno(errno, "Failed to wipe partition table: %m");
2564 if (n != 1024)
2565 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while wiping partition table.");
2566
2567 c = fdisk_new_context();
2568 if (!c)
2569 return log_oom();
2570
2571 if (asprintf(&path, "/proc/self/fd/%i", fd) < 0)
2572 return log_oom();
2573
2574 r = fdisk_assign_device(c, path, 0);
2575 if (r < 0)
2576 return log_error_errno(r, "Failed to open device: %m");
2577
2578 r = fdisk_create_disklabel(c, "gpt");
2579 if (r < 0)
2580 return log_error_errno(r, "Failed to create GPT disk label: %m");
2581
2582 r = fdisk_apply_table(c, t);
2583 if (r < 0)
2584 return log_error_errno(r, "Failed to apply partition table: %m");
2585
2586 r = fdisk_set_ask(c, ask_cb, &disk_uuids);
2587 if (r < 0)
2588 return log_error_errno(r, "Failed to set libfdisk query function: %m");
2589
2590 r = fdisk_set_disklabel_id(c);
2591 if (r < 0)
2592 return log_error_errno(r, "Failed to change disklabel ID: %m");
2593
2594 r = fdisk_write_disklabel(c);
2595 if (r < 0)
2596 return log_error_errno(r, "Failed to write disk label: %m");
2597
2598 return 1;
2599 }
2600
2601 int home_resize_luks(
2602 UserRecord *h,
2603 bool already_activated,
2604 PasswordCache *cache,
2605 HomeSetup *setup,
2606 UserRecord **ret_home) {
2607
2608 char buffer1[FORMAT_BYTES_MAX], buffer2[FORMAT_BYTES_MAX], buffer3[FORMAT_BYTES_MAX],
2609 buffer4[FORMAT_BYTES_MAX], buffer5[FORMAT_BYTES_MAX], buffer6[FORMAT_BYTES_MAX];
2610 uint64_t old_image_size, new_image_size, old_fs_size, new_fs_size, crypto_offset, new_partition_size;
2611 _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *embedded_home = NULL, *new_home = NULL;
2612 _cleanup_(fdisk_unref_tablep) struct fdisk_table *table = NULL;
2613 _cleanup_free_ char *whole_disk = NULL;
2614 _cleanup_close_ int image_fd = -1;
2615 sd_id128_t disk_uuid;
2616 const char *ip, *ipo;
2617 struct statfs sfs;
2618 struct stat st;
2619 int r, resize_type;
2620
2621 assert(h);
2622 assert(user_record_storage(h) == USER_LUKS);
2623 assert(setup);
2624 assert(ret_home);
2625
2626 assert_se(ipo = user_record_image_path(h));
2627 ip = strdupa(ipo); /* copy out since original might change later in home record object */
2628
2629 image_fd = open(ip, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
2630 if (image_fd < 0)
2631 return log_error_errno(errno, "Failed to open image file %s: %m", ip);
2632
2633 if (fstat(image_fd, &st) < 0)
2634 return log_error_errno(errno, "Failed to stat image file %s: %m", ip);
2635 if (S_ISBLK(st.st_mode)) {
2636 dev_t parent;
2637
2638 r = block_get_whole_disk(st.st_rdev, &parent);
2639 if (r < 0)
2640 return log_error_errno(r, "Failed to acquire whole block device for %s: %m", ip);
2641 if (r > 0) {
2642 /* If we shall resize a file system on a partition device, then let's figure out the
2643 * whole disk device and operate on that instead, since we need to rewrite the
2644 * partition table to resize the partition. */
2645
2646 log_info("Operating on partition device %s, using parent device.", ip);
2647
2648 r = device_path_make_major_minor(st.st_mode, parent, &whole_disk);
2649 if (r < 0)
2650 return log_error_errno(r, "Failed to derive whole disk path for %s: %m", ip);
2651
2652 safe_close(image_fd);
2653
2654 image_fd = open(whole_disk, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
2655 if (image_fd < 0)
2656 return log_error_errno(errno, "Failed to open whole block device %s: %m", whole_disk);
2657
2658 if (fstat(image_fd, &st) < 0)
2659 return log_error_errno(errno, "Failed to stat whole block device %s: %m", whole_disk);
2660 if (!S_ISBLK(st.st_mode))
2661 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK), "Whole block device %s is not actually a block device, refusing.", whole_disk);
2662 } else
2663 log_info("Operating on whole block device %s.", ip);
2664
2665 if (ioctl(image_fd, BLKGETSIZE64, &old_image_size) < 0)
2666 return log_error_errno(errno, "Failed to determine size of original block device: %m");
2667
2668 if (flock(image_fd, LOCK_EX) < 0) /* make sure udev doesn't read from it while we operate on the device */
2669 return log_error_errno(errno, "Failed to lock block device %s: %m", ip);
2670
2671 new_image_size = old_image_size; /* we can't resize physical block devices */
2672 } else {
2673 r = stat_verify_regular(&st);
2674 if (r < 0)
2675 return log_error_errno(r, "Image %s is not a block device nor regular file: %m", ip);
2676
2677 old_image_size = st.st_size;
2678
2679 /* Note an asymetry here: when we operate on loopback files the specified disk size we get we
2680 * apply onto the loopback file as a whole. When we operate on block devices we instead apply
2681 * to the partition itself only. */
2682
2683 new_image_size = DISK_SIZE_ROUND_DOWN(h->disk_size);
2684 if (new_image_size == old_image_size) {
2685 log_info("Image size already matching, skipping operation.");
2686 return 0;
2687 }
2688 }
2689
2690 r = home_prepare_luks(h, already_activated, whole_disk, cache, setup, &header_home);
2691 if (r < 0)
2692 return r;
2693
2694 r = home_load_embedded_identity(h, setup->root_fd, header_home, USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL, cache, &embedded_home, &new_home);
2695 if (r < 0)
2696 return r;
2697
2698 log_info("offset = %" PRIu64 ", size = %" PRIu64 ", image = %" PRIu64, setup->partition_offset, setup->partition_size, old_image_size);
2699
2700 if ((UINT64_MAX - setup->partition_offset) < setup->partition_size ||
2701 setup->partition_offset + setup->partition_size > old_image_size)
2702 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Old partition doesn't fit in backing storage, refusing.");
2703
2704 if (S_ISREG(st.st_mode)) {
2705 uint64_t partition_table_extra;
2706
2707 partition_table_extra = old_image_size - setup->partition_size;
2708 if (new_image_size <= partition_table_extra)
2709 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "New size smaller than partition table metadata.");
2710
2711 new_partition_size = new_image_size - partition_table_extra;
2712 } else {
2713 assert(S_ISBLK(st.st_mode));
2714
2715 new_partition_size = DISK_SIZE_ROUND_DOWN(h->disk_size);
2716 if (new_partition_size == setup->partition_size) {
2717 log_info("Partition size already matching, skipping operation.");
2718 return 0;
2719 }
2720 }
2721
2722 if ((UINT64_MAX - setup->partition_offset) < new_partition_size ||
2723 setup->partition_offset + new_partition_size > new_image_size)
2724 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "New partition doesn't fit into backing storage, refusing.");
2725
2726 crypto_offset = crypt_get_data_offset(setup->crypt_device);
2727 if (setup->partition_size / 512U <= crypto_offset)
2728 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Weird, old crypto payload offset doesn't actually fit in partition size?");
2729 if (new_partition_size / 512U <= crypto_offset)
2730 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "New size smaller than crypto payload offset?");
2731
2732 old_fs_size = (setup->partition_size / 512U - crypto_offset) * 512U;
2733 new_fs_size = (new_partition_size / 512U - crypto_offset) * 512U;
2734
2735 /* Before we start doing anything, let's figure out if we actually can */
2736 resize_type = can_resize_fs(setup->root_fd, old_fs_size, new_fs_size);
2737 if (resize_type < 0)
2738 return resize_type;
2739 if (resize_type == CAN_RESIZE_OFFLINE && already_activated)
2740 return log_error_errno(SYNTHETIC_ERRNO(ETXTBSY), "File systems of this type can only be resized offline, but is currently online.");
2741
2742 log_info("Ready to resize image size %s → %s, partition size %s → %s, file system size %s → %s.",
2743 format_bytes(buffer1, sizeof(buffer1), old_image_size),
2744 format_bytes(buffer2, sizeof(buffer2), new_image_size),
2745 format_bytes(buffer3, sizeof(buffer3), setup->partition_size),
2746 format_bytes(buffer4, sizeof(buffer4), new_partition_size),
2747 format_bytes(buffer5, sizeof(buffer5), old_fs_size),
2748 format_bytes(buffer6, sizeof(buffer6), new_fs_size));
2749
2750 r = prepare_resize_partition(
2751 image_fd,
2752 setup->partition_offset,
2753 setup->partition_size,
2754 new_partition_size,
2755 &disk_uuid,
2756 &table);
2757 if (r < 0)
2758 return r;
2759
2760 if (new_fs_size > old_fs_size) {
2761
2762 if (S_ISREG(st.st_mode)) {
2763 /* Grow file size */
2764 r = home_truncate(h, image_fd, ip, new_image_size);
2765 if (r < 0)
2766 return r;
2767
2768 log_info("Growing of image file completed.");
2769 }
2770
2771 /* Make sure loopback device sees the new bigger size */
2772 r = loop_device_refresh_size(setup->loop, UINT64_MAX, new_partition_size);
2773 if (r == -ENOTTY)
2774 log_debug_errno(r, "Device is not a loopback device, not refreshing size.");
2775 else if (r < 0)
2776 return log_error_errno(r, "Failed to refresh loopback device size: %m");
2777 else
2778 log_info("Refreshing loop device size completed.");
2779
2780 r = apply_resize_partition(image_fd, disk_uuid, table);
2781 if (r < 0)
2782 return r;
2783 if (r > 0)
2784 log_info("Growing of partition completed.");
2785
2786 if (ioctl(image_fd, BLKRRPART, 0) < 0)
2787 log_debug_errno(errno, "BLKRRPART failed on block device, ignoring: %m");
2788
2789 /* Tell LUKS about the new bigger size too */
2790 r = crypt_resize(setup->crypt_device, setup->dm_name, new_fs_size / 512U);
2791 if (r < 0)
2792 return log_error_errno(r, "Failed to grow LUKS device: %m");
2793
2794 log_info("LUKS device growing completed.");
2795 } else {
2796 r = home_store_embedded_identity(new_home, setup->root_fd, h->uid, embedded_home);
2797 if (r < 0)
2798 return r;
2799
2800 if (S_ISREG(st.st_mode)) {
2801 if (user_record_luks_discard(h))
2802 /* Before we shrink, let's trim the file system, so that we need less space on disk during the shrinking */
2803 (void) run_fitrim(setup->root_fd);
2804 else {
2805 /* If discard is off, let's ensure all backing blocks are allocated, so that our resize operation doesn't fail half-way */
2806 r = run_fallocate(image_fd, &st);
2807 if (r < 0)
2808 return r;
2809 }
2810 }
2811 }
2812
2813 /* Now resize the file system */
2814 if (resize_type == CAN_RESIZE_ONLINE)
2815 r = resize_fs(setup->root_fd, new_fs_size, NULL);
2816 else
2817 r = ext4_offline_resize_fs(setup, new_fs_size, user_record_luks_discard(h), user_record_mount_flags(h));
2818 if (r < 0)
2819 return log_error_errno(r, "Failed to resize file system: %m");
2820
2821 log_info("File system resizing completed.");
2822
2823 /* Immediately sync afterwards */
2824 r = home_sync_and_statfs(setup->root_fd, NULL);
2825 if (r < 0)
2826 return r;
2827
2828 if (new_fs_size < old_fs_size) {
2829
2830 /* Shrink the LUKS device now, matching the new file system size */
2831 r = crypt_resize(setup->crypt_device, setup->dm_name, new_fs_size / 512);
2832 if (r < 0)
2833 return log_error_errno(r, "Failed to shrink LUKS device: %m");
2834
2835 log_info("LUKS device shrinking completed.");
2836
2837 if (S_ISREG(st.st_mode)) {
2838 /* Shrink the image file */
2839 if (ftruncate(image_fd, new_image_size) < 0)
2840 return log_error_errno(errno, "Failed to shrink image file %s: %m", ip);
2841
2842 log_info("Shrinking of image file completed.");
2843 }
2844
2845 /* Refresh the loop devices size */
2846 r = loop_device_refresh_size(setup->loop, UINT64_MAX, new_partition_size);
2847 if (r == -ENOTTY)
2848 log_debug_errno(r, "Device is not a loopback device, not refreshing size.");
2849 else if (r < 0)
2850 return log_error_errno(r, "Failed to refresh loopback device size: %m");
2851 else
2852 log_info("Refreshing loop device size completed.");
2853
2854 r = apply_resize_partition(image_fd, disk_uuid, table);
2855 if (r < 0)
2856 return r;
2857 if (r > 0)
2858 log_info("Shrinking of partition completed.");
2859
2860 if (ioctl(image_fd, BLKRRPART, 0) < 0)
2861 log_debug_errno(errno, "BLKRRPART failed on block device, ignoring: %m");
2862 } else {
2863 r = home_store_embedded_identity(new_home, setup->root_fd, h->uid, embedded_home);
2864 if (r < 0)
2865 return r;
2866 }
2867
2868 r = home_store_header_identity_luks(new_home, setup, header_home);
2869 if (r < 0)
2870 return r;
2871
2872 r = home_extend_embedded_identity(new_home, h, setup);
2873 if (r < 0)
2874 return r;
2875
2876 if (user_record_luks_discard(h))
2877 (void) run_fitrim(setup->root_fd);
2878
2879 r = home_sync_and_statfs(setup->root_fd, &sfs);
2880 if (r < 0)
2881 return r;
2882
2883 r = home_setup_undo(setup);
2884 if (r < 0)
2885 return r;
2886
2887 log_info("Everything completed.");
2888
2889 print_size_summary(new_image_size, new_fs_size, &sfs);
2890
2891 *ret_home = TAKE_PTR(new_home);
2892 return 0;
2893 }
2894
2895 int home_passwd_luks(
2896 UserRecord *h,
2897 HomeSetup *setup,
2898 PasswordCache *cache, /* the passwords acquired via PKCS#11/FIDO2 security tokens */
2899 char **effective_passwords /* new passwords */) {
2900
2901 size_t volume_key_size, i, max_key_slots, n_effective;
2902 _cleanup_(erase_and_freep) void *volume_key = NULL;
2903 struct crypt_pbkdf_type good_pbkdf, minimal_pbkdf;
2904 const char *type;
2905 char **list;
2906 int r;
2907
2908 assert(h);
2909 assert(user_record_storage(h) == USER_LUKS);
2910 assert(setup);
2911
2912 type = crypt_get_type(setup->crypt_device);
2913 if (!type)
2914 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine crypto device type.");
2915
2916 r = crypt_keyslot_max(type);
2917 if (r <= 0)
2918 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine number of key slots.");
2919 max_key_slots = r;
2920
2921 r = crypt_get_volume_key_size(setup->crypt_device);
2922 if (r <= 0)
2923 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine volume key size.");
2924 volume_key_size = (size_t) r;
2925
2926 volume_key = malloc(volume_key_size);
2927 if (!volume_key)
2928 return log_oom();
2929
2930 r = -ENOKEY;
2931 FOREACH_POINTER(list, cache->pkcs11_passwords, cache->fido2_passwords, h->password) {
2932 r = luks_try_passwords(setup->crypt_device, list, volume_key, &volume_key_size);
2933 if (r != -ENOKEY)
2934 break;
2935 }
2936 if (r == -ENOKEY)
2937 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Failed to unlock LUKS superblock with supplied passwords.");
2938 if (r < 0)
2939 return log_error_errno(r, "Failed to unlocks LUKS superblock: %m");
2940
2941 n_effective = strv_length(effective_passwords);
2942
2943 build_good_pbkdf(&good_pbkdf, h);
2944 build_minimal_pbkdf(&minimal_pbkdf, h);
2945
2946 for (i = 0; i < max_key_slots; i++) {
2947 r = crypt_keyslot_destroy(setup->crypt_device, i);
2948 if (r < 0 && !IN_SET(r, -ENOENT, -EINVAL)) /* Returns EINVAL or ENOENT if there's no key in this slot already */
2949 return log_error_errno(r, "Failed to destroy LUKS password: %m");
2950
2951 if (i >= n_effective) {
2952 if (r >= 0)
2953 log_info("Destroyed LUKS key slot %zu.", i);
2954 continue;
2955 }
2956
2957 if (strv_contains(cache->pkcs11_passwords, effective_passwords[i]) ||
2958 strv_contains(cache->fido2_passwords, effective_passwords[i])) {
2959 log_debug("Using minimal PBKDF for slot %zu", i);
2960 r = crypt_set_pbkdf_type(setup->crypt_device, &minimal_pbkdf);
2961 } else {
2962 log_debug("Using good PBKDF for slot %zu", i);
2963 r = crypt_set_pbkdf_type(setup->crypt_device, &good_pbkdf);
2964 }
2965 if (r < 0)
2966 return log_error_errno(r, "Failed to tweak PBKDF for slot %zu: %m", i);
2967
2968 r = crypt_keyslot_add_by_volume_key(
2969 setup->crypt_device,
2970 i,
2971 volume_key,
2972 volume_key_size,
2973 effective_passwords[i],
2974 strlen(effective_passwords[i]));
2975 if (r < 0)
2976 return log_error_errno(r, "Failed to set up LUKS password: %m");
2977
2978 log_info("Updated LUKS key slot %zu.", i);
2979 }
2980
2981 return 1;
2982 }
2983
2984 int home_lock_luks(UserRecord *h) {
2985 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
2986 _cleanup_free_ char *dm_name = NULL, *dm_node = NULL;
2987 _cleanup_close_ int root_fd = -1;
2988 const char *p;
2989 int r;
2990
2991 assert(h);
2992
2993 assert_se(p = user_record_home_directory(h));
2994 root_fd = open(p, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
2995 if (root_fd < 0)
2996 return log_error_errno(errno, "Failed to open home directory: %m");
2997
2998 r = make_dm_names(h->user_name, &dm_name, &dm_node);
2999 if (r < 0)
3000 return r;
3001
3002 r = crypt_init_by_name(&cd, dm_name);
3003 if (r < 0)
3004 return log_error_errno(r, "Failed to initialize cryptsetup context for %s: %m", dm_name);
3005
3006 log_info("Discovered used LUKS device %s.", dm_node);
3007 cryptsetup_enable_logging(cd);
3008
3009 if (syncfs(root_fd) < 0) /* Snake oil, but let's better be safe than sorry */
3010 return log_error_errno(errno, "Failed to synchronize file system %s: %m", p);
3011
3012 root_fd = safe_close(root_fd);
3013
3014 log_info("File system synchronized.");
3015
3016 /* Note that we don't invoke FIFREEZE here, it appears libcryptsetup/device-mapper already does that on its own for us */
3017
3018 r = crypt_suspend(cd, dm_name);
3019 if (r < 0)
3020 return log_error_errno(r, "Failed to suspend cryptsetup device: %s: %m", dm_node);
3021
3022 log_info("LUKS device suspended.");
3023 return 0;
3024 }
3025
3026 static int luks_try_resume(
3027 struct crypt_device *cd,
3028 const char *dm_name,
3029 char **password) {
3030
3031 char **pp;
3032 int r;
3033
3034 assert(cd);
3035 assert(dm_name);
3036
3037 STRV_FOREACH(pp, password) {
3038 r = crypt_resume_by_passphrase(
3039 cd,
3040 dm_name,
3041 CRYPT_ANY_SLOT,
3042 *pp,
3043 strlen(*pp));
3044 if (r >= 0) {
3045 log_info("Resumed LUKS device %s.", dm_name);
3046 return 0;
3047 }
3048
3049 log_debug_errno(r, "Password %zu didn't work for resuming device: %m", (size_t) (pp - password));
3050 }
3051
3052 return -ENOKEY;
3053 }
3054
3055 int home_unlock_luks(UserRecord *h, PasswordCache *cache) {
3056 _cleanup_free_ char *dm_name = NULL, *dm_node = NULL;
3057 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
3058 char **list;
3059 int r;
3060
3061 assert(h);
3062
3063 r = make_dm_names(h->user_name, &dm_name, &dm_node);
3064 if (r < 0)
3065 return r;
3066
3067 r = crypt_init_by_name(&cd, dm_name);
3068 if (r < 0)
3069 return log_error_errno(r, "Failed to initialize cryptsetup context for %s: %m", dm_name);
3070
3071 log_info("Discovered used LUKS device %s.", dm_node);
3072 cryptsetup_enable_logging(cd);
3073
3074 r = -ENOKEY;
3075 FOREACH_POINTER(list, cache->pkcs11_passwords, cache->fido2_passwords, h->password) {
3076 r = luks_try_resume(cd, dm_name, list);
3077 if (r != -ENOKEY)
3078 break;
3079 }
3080 if (r == -ENOKEY)
3081 return log_error_errno(r, "No valid password for LUKS superblock.");
3082 if (r < 0)
3083 return log_error_errno(r, "Failed to resume LUKS superblock: %m");
3084
3085 log_info("LUKS device resumed.");
3086 return 0;
3087 }