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