]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/home/homework-luks.c
Merge pull request #31779 from keszybz/elf2efi-clang-18
[thirdparty/systemd.git] / src / home / homework-luks.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/loop.h>
4 #include <poll.h>
5 #include <sys/file.h>
6 #include <sys/ioctl.h>
7 #include <sys/xattr.h>
8
9 #if HAVE_VALGRIND_MEMCHECK_H
10 #include <valgrind/memcheck.h>
11 #endif
12
13 #include "sd-daemon.h"
14 #include "sd-device.h"
15 #include "sd-event.h"
16 #include "sd-id128.h"
17
18 #include "blkid-util.h"
19 #include "blockdev-util.h"
20 #include "btrfs-util.h"
21 #include "chattr-util.h"
22 #include "device-util.h"
23 #include "devnum-util.h"
24 #include "dm-util.h"
25 #include "env-util.h"
26 #include "errno-util.h"
27 #include "fd-util.h"
28 #include "fdisk-util.h"
29 #include "fileio.h"
30 #include "filesystems.h"
31 #include "fs-util.h"
32 #include "fsck-util.h"
33 #include "glyph-util.h"
34 #include "gpt.h"
35 #include "home-util.h"
36 #include "homework-blob.h"
37 #include "homework-luks.h"
38 #include "homework-mount.h"
39 #include "io-util.h"
40 #include "keyring-util.h"
41 #include "memory-util.h"
42 #include "missing_magic.h"
43 #include "mkdir.h"
44 #include "mkfs-util.h"
45 #include "mount-util.h"
46 #include "openssl-util.h"
47 #include "parse-util.h"
48 #include "path-util.h"
49 #include "process-util.h"
50 #include "random-util.h"
51 #include "resize-fs.h"
52 #include "strv.h"
53 #include "sync-util.h"
54 #include "tmpfile-util.h"
55 #include "udev-util.h"
56 #include "user-util.h"
57
58 /* Round down to the nearest 4K size. Given that newer hardware generally prefers 4K sectors, let's align our
59 * partitions to that too. In the worst case we'll waste 3.5K per partition that way, but I think I can live
60 * with that. */
61 #define DISK_SIZE_ROUND_DOWN(x) ((x) & ~UINT64_C(4095))
62
63 /* Rounds up to the nearest 4K boundary. Returns UINT64_MAX on overflow */
64 #define DISK_SIZE_ROUND_UP(x) \
65 ({ \
66 uint64_t _x = (x); \
67 _x > UINT64_MAX - 4095U ? UINT64_MAX : (_x + 4095U) & ~UINT64_C(4095); \
68 })
69
70 /* How much larger will the image on disk be than the fs inside it, i.e. the space we pay for the GPT and
71 * LUKS2 envelope. (As measured on cryptsetup 2.4.1) */
72 #define GPT_LUKS2_OVERHEAD UINT64_C(18874368)
73
74 static int resize_image_loop(UserRecord *h, HomeSetup *setup, uint64_t old_image_size, uint64_t new_image_size, uint64_t *ret_image_size);
75
76 int run_mark_dirty(int fd, bool b) {
77 char x = '1';
78 int r, ret;
79
80 /* Sets or removes the 'user.home-dirty' xattr on the specified file. We use this to detect when a
81 * home directory was not properly unmounted. */
82
83 assert(fd >= 0);
84
85 r = fd_verify_regular(fd);
86 if (r < 0)
87 return r;
88
89 if (b) {
90 ret = fsetxattr(fd, "user.home-dirty", &x, 1, XATTR_CREATE);
91 if (ret < 0 && errno != EEXIST)
92 return log_debug_errno(errno, "Could not mark home directory as dirty: %m");
93
94 } else {
95 r = fsync_full(fd);
96 if (r < 0)
97 return log_debug_errno(r, "Failed to synchronize image before marking it clean: %m");
98
99 ret = fremovexattr(fd, "user.home-dirty");
100 if (ret < 0 && !ERRNO_IS_XATTR_ABSENT(errno))
101 return log_debug_errno(errno, "Could not mark home directory as clean: %m");
102 }
103
104 r = fsync_full(fd);
105 if (r < 0)
106 return log_debug_errno(r, "Failed to synchronize dirty flag to disk: %m");
107
108 return ret >= 0;
109 }
110
111 int run_mark_dirty_by_path(const char *path, bool b) {
112 _cleanup_close_ int fd = -EBADF;
113
114 assert(path);
115
116 fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY);
117 if (fd < 0)
118 return log_debug_errno(errno, "Failed to open %s to mark dirty or clean: %m", path);
119
120 return run_mark_dirty(fd, b);
121 }
122
123 static int probe_file_system_by_fd(
124 int fd,
125 char **ret_fstype,
126 sd_id128_t *ret_uuid) {
127
128 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
129 const char *fstype = NULL, *uuid = NULL;
130 sd_id128_t id;
131 int r;
132
133 assert(fd >= 0);
134 assert(ret_fstype);
135 assert(ret_uuid);
136
137 b = blkid_new_probe();
138 if (!b)
139 return -ENOMEM;
140
141 errno = 0;
142 r = blkid_probe_set_device(b, fd, 0, 0);
143 if (r != 0)
144 return errno_or_else(ENOMEM);
145
146 (void) blkid_probe_enable_superblocks(b, 1);
147 (void) blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_UUID);
148
149 errno = 0;
150 r = blkid_do_safeprobe(b);
151 if (r == _BLKID_SAFEPROBE_ERROR)
152 return errno_or_else(EIO);
153 if (IN_SET(r, _BLKID_SAFEPROBE_AMBIGUOUS, _BLKID_SAFEPROBE_NOT_FOUND))
154 return -ENOPKG;
155
156 assert(r == _BLKID_SAFEPROBE_FOUND);
157
158 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
159 if (!fstype)
160 return -ENOPKG;
161
162 (void) blkid_probe_lookup_value(b, "UUID", &uuid, NULL);
163 if (!uuid)
164 return -ENOPKG;
165
166 r = sd_id128_from_string(uuid, &id);
167 if (r < 0)
168 return r;
169
170 r = strdup_to(ret_fstype, fstype);
171 if (r < 0)
172 return r;
173 *ret_uuid = id;
174 return 0;
175 }
176
177 static int probe_file_system_by_path(const char *path, char **ret_fstype, sd_id128_t *ret_uuid) {
178 _cleanup_close_ int fd = -EBADF;
179
180 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
181 if (fd < 0)
182 return negative_errno();
183
184 return probe_file_system_by_fd(fd, ret_fstype, ret_uuid);
185 }
186
187 static int block_get_size_by_fd(int fd, uint64_t *ret) {
188 struct stat st;
189
190 assert(fd >= 0);
191 assert(ret);
192
193 if (fstat(fd, &st) < 0)
194 return -errno;
195
196 if (!S_ISBLK(st.st_mode))
197 return -ENOTBLK;
198
199 return blockdev_get_device_size(fd, ret);
200 }
201
202 static int block_get_size_by_path(const char *path, uint64_t *ret) {
203 _cleanup_close_ int fd = -EBADF;
204
205 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
206 if (fd < 0)
207 return -errno;
208
209 return block_get_size_by_fd(fd, ret);
210 }
211
212 static int run_fsck(const char *node, const char *fstype) {
213 int r, exit_status;
214 pid_t fsck_pid;
215
216 assert(node);
217 assert(fstype);
218
219 r = fsck_exists_for_fstype(fstype);
220 if (r < 0)
221 return log_error_errno(r, "Failed to check if fsck for file system %s exists: %m", fstype);
222 if (r == 0) {
223 log_warning("No fsck for file system %s installed, ignoring.", fstype);
224 return 0;
225 }
226
227 r = safe_fork("(fsck)",
228 FORK_RESET_SIGNALS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_STDOUT_TO_STDERR|FORK_CLOSE_ALL_FDS,
229 &fsck_pid);
230 if (r < 0)
231 return r;
232 if (r == 0) {
233 /* Child */
234 execlp("fsck", "fsck", "-aTl", node, NULL);
235 log_open();
236 log_error_errno(errno, "Failed to execute fsck: %m");
237 _exit(FSCK_OPERATIONAL_ERROR);
238 }
239
240 exit_status = wait_for_terminate_and_check("fsck", fsck_pid, WAIT_LOG_ABNORMAL);
241 if (exit_status < 0)
242 return exit_status;
243 if ((exit_status & ~FSCK_ERROR_CORRECTED) != 0) {
244 log_warning("fsck failed with exit status %i.", exit_status);
245
246 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
247 return log_error_errno(SYNTHETIC_ERRNO(EIO), "File system is corrupted, refusing.");
248
249 log_warning("Ignoring fsck error.");
250 }
251
252 log_info("File system check completed.");
253
254 return 1;
255 }
256
257 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(key_serial_t, keyring_unlink, -1);
258
259 static int upload_to_keyring(
260 UserRecord *h,
261 const char *password,
262 key_serial_t *ret_key_serial) {
263
264 _cleanup_free_ char *name = NULL;
265 key_serial_t serial;
266
267 assert(h);
268 assert(password);
269
270 /* If auto-shrink-on-logout is turned on, we need to keep the key we used to unlock the LUKS volume
271 * around, since we'll need it when automatically resizing (since we can't ask the user there
272 * again). We do this by uploading it into the kernel keyring, specifically the "session" one. This
273 * is done under the assumption systemd-homed gets its private per-session keyring (i.e. default
274 * service behaviour, given that KeyringMode=private is the default). It will survive between our
275 * systemd-homework invocations that way.
276 *
277 * If auto-shrink-on-logout is disabled we'll skip this step, to be frugal with sensitive data. */
278
279 if (user_record_auto_resize_mode(h) != AUTO_RESIZE_SHRINK_AND_GROW) { /* Won't need it */
280 if (ret_key_serial)
281 *ret_key_serial = -1;
282 return 0;
283 }
284
285 name = strjoin("homework-user-", h->user_name);
286 if (!name)
287 return -ENOMEM;
288
289 serial = add_key("user", name, password, strlen(password), KEY_SPEC_SESSION_KEYRING);
290 if (serial == -1)
291 return -errno;
292
293 if (ret_key_serial)
294 *ret_key_serial = serial;
295
296 return 1;
297 }
298
299 static int luks_try_passwords(
300 UserRecord *h,
301 struct crypt_device *cd,
302 char **passwords,
303 void *volume_key,
304 size_t *volume_key_size,
305 key_serial_t *ret_key_serial) {
306
307 int r;
308
309 assert(h);
310 assert(cd);
311
312 STRV_FOREACH(pp, passwords) {
313 size_t vks = *volume_key_size;
314
315 r = sym_crypt_volume_key_get(
316 cd,
317 CRYPT_ANY_SLOT,
318 volume_key,
319 &vks,
320 *pp,
321 strlen(*pp));
322 if (r >= 0) {
323 if (ret_key_serial) {
324 /* If ret_key_serial is non-NULL, let's try to upload the password that
325 * worked, and return its serial. */
326 r = upload_to_keyring(h, *pp, ret_key_serial);
327 if (r < 0) {
328 log_debug_errno(r, "Failed to upload LUKS password to kernel keyring, ignoring: %m");
329 *ret_key_serial = -1;
330 }
331 }
332
333 *volume_key_size = vks;
334 return 0;
335 }
336
337 log_debug_errno(r, "Password %zu didn't work for unlocking LUKS superblock: %m", (size_t) (pp - passwords));
338 }
339
340 return -ENOKEY;
341 }
342
343 static int luks_setup(
344 UserRecord *h,
345 const char *node,
346 const char *dm_name,
347 sd_id128_t uuid,
348 const char *cipher,
349 const char *cipher_mode,
350 uint64_t volume_key_size,
351 char **passwords,
352 const PasswordCache *cache,
353 bool discard,
354 struct crypt_device **ret,
355 sd_id128_t *ret_found_uuid,
356 void **ret_volume_key,
357 size_t *ret_volume_key_size,
358 key_serial_t *ret_key_serial) {
359
360 _cleanup_(keyring_unlinkp) key_serial_t key_serial = -1;
361 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
362 _cleanup_(erase_and_freep) void *vk = NULL;
363 sd_id128_t p;
364 size_t vks;
365 int r;
366
367 assert(h);
368 assert(node);
369 assert(dm_name);
370 assert(ret);
371
372 r = sym_crypt_init(&cd, node);
373 if (r < 0)
374 return log_error_errno(r, "Failed to allocate libcryptsetup context: %m");
375
376 cryptsetup_enable_logging(cd);
377
378 r = sym_crypt_load(cd, CRYPT_LUKS2, NULL);
379 if (r < 0)
380 return log_error_errno(r, "Failed to load LUKS superblock: %m");
381
382 r = sym_crypt_get_volume_key_size(cd);
383 if (r <= 0)
384 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine LUKS volume key size");
385 vks = (size_t) r;
386
387 if (!sd_id128_is_null(uuid) || ret_found_uuid) {
388 const char *s;
389
390 s = sym_crypt_get_uuid(cd);
391 if (!s)
392 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has no UUID.");
393
394 r = sd_id128_from_string(s, &p);
395 if (r < 0)
396 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has invalid UUID.");
397
398 /* Check that the UUID matches, if specified */
399 if (!sd_id128_is_null(uuid) &&
400 !sd_id128_equal(uuid, p))
401 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has wrong UUID.");
402 }
403
404 if (cipher && !streq_ptr(cipher, sym_crypt_get_cipher(cd)))
405 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock declares wrong cipher.");
406
407 if (cipher_mode && !streq_ptr(cipher_mode, sym_crypt_get_cipher_mode(cd)))
408 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock declares wrong cipher mode.");
409
410 if (volume_key_size != UINT64_MAX && vks != volume_key_size)
411 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock declares wrong volume key size.");
412
413 vk = malloc(vks);
414 if (!vk)
415 return log_oom();
416
417 r = -ENOKEY;
418 char **list;
419 FOREACH_ARGUMENT(list,
420 cache ? cache->keyring_passswords : NULL,
421 cache ? cache->pkcs11_passwords : NULL,
422 cache ? cache->fido2_passwords : NULL,
423 passwords) {
424
425 r = luks_try_passwords(h, cd, list, vk, &vks, ret_key_serial ? &key_serial : NULL);
426 if (r != -ENOKEY)
427 break;
428 }
429 if (r == -ENOKEY)
430 return log_error_errno(r, "No valid password for LUKS superblock.");
431 if (r < 0)
432 return log_error_errno(r, "Failed to unlock LUKS superblock: %m");
433
434 r = sym_crypt_activate_by_volume_key(
435 cd,
436 dm_name,
437 vk, vks,
438 discard ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0);
439 if (r < 0)
440 return log_error_errno(r, "Failed to unlock LUKS superblock: %m");
441
442 log_info("Setting up LUKS device /dev/mapper/%s completed.", dm_name);
443
444 *ret = TAKE_PTR(cd);
445
446 if (ret_found_uuid) /* Return the UUID actually found if the caller wants to know */
447 *ret_found_uuid = p;
448 if (ret_volume_key)
449 *ret_volume_key = TAKE_PTR(vk);
450 if (ret_volume_key_size)
451 *ret_volume_key_size = vks;
452 if (ret_key_serial)
453 *ret_key_serial = TAKE_KEY_SERIAL(key_serial);
454
455 return 0;
456 }
457
458 static int make_dm_names(UserRecord *h, HomeSetup *setup) {
459 assert(h);
460 assert(h->user_name);
461 assert(setup);
462
463 if (!setup->dm_name) {
464 setup->dm_name = strjoin("home-", h->user_name);
465 if (!setup->dm_name)
466 return log_oom();
467 }
468
469 if (!setup->dm_node) {
470 setup->dm_node = path_join("/dev/mapper/", setup->dm_name);
471 if (!setup->dm_node)
472 return log_oom();
473 }
474
475 return 0;
476 }
477
478 static int acquire_open_luks_device(
479 UserRecord *h,
480 HomeSetup *setup,
481 bool graceful) {
482
483 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
484 int r;
485
486 assert(h);
487 assert(setup);
488 assert(!setup->crypt_device);
489
490 r = dlopen_cryptsetup();
491 if (r < 0)
492 return r;
493
494 r = make_dm_names(h, setup);
495 if (r < 0)
496 return r;
497
498 r = sym_crypt_init_by_name(&cd, setup->dm_name);
499 if ((ERRNO_IS_NEG_DEVICE_ABSENT(r) || r == -EINVAL) && graceful)
500 return 0;
501 if (r < 0)
502 return log_error_errno(r, "Failed to initialize cryptsetup context for %s: %m", setup->dm_name);
503
504 cryptsetup_enable_logging(cd);
505
506 setup->crypt_device = TAKE_PTR(cd);
507 return 1;
508 }
509
510 static int luks_open(
511 UserRecord *h,
512 HomeSetup *setup,
513 const PasswordCache *cache,
514 sd_id128_t *ret_found_uuid,
515 void **ret_volume_key,
516 size_t *ret_volume_key_size) {
517
518 _cleanup_(erase_and_freep) void *vk = NULL;
519 sd_id128_t p;
520 size_t vks;
521 int r;
522
523 assert(h);
524 assert(setup);
525 assert(!setup->crypt_device);
526
527 /* Opens a LUKS device that is already set up. Re-validates the password while doing so (which also
528 * provides us with the volume key, which we want). */
529
530 r = acquire_open_luks_device(h, setup, /* graceful= */ false);
531 if (r < 0)
532 return r;
533
534 r = sym_crypt_load(setup->crypt_device, CRYPT_LUKS2, NULL);
535 if (r < 0)
536 return log_error_errno(r, "Failed to load LUKS superblock: %m");
537
538 r = sym_crypt_get_volume_key_size(setup->crypt_device);
539 if (r <= 0)
540 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine LUKS volume key size");
541 vks = (size_t) r;
542
543 if (ret_found_uuid) {
544 const char *s;
545
546 s = sym_crypt_get_uuid(setup->crypt_device);
547 if (!s)
548 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has no UUID.");
549
550 r = sd_id128_from_string(s, &p);
551 if (r < 0)
552 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has invalid UUID.");
553 }
554
555 vk = malloc(vks);
556 if (!vk)
557 return log_oom();
558
559 r = -ENOKEY;
560 char **list;
561 FOREACH_ARGUMENT(list,
562 cache ? cache->keyring_passswords : NULL,
563 cache ? cache->pkcs11_passwords : NULL,
564 cache ? cache->fido2_passwords : NULL,
565 h->password) {
566
567 r = luks_try_passwords(h, setup->crypt_device, list, vk, &vks, NULL);
568 if (r != -ENOKEY)
569 break;
570 }
571 if (r == -ENOKEY)
572 return log_error_errno(r, "No valid password for LUKS superblock.");
573 if (r < 0)
574 return log_error_errno(r, "Failed to unlock LUKS superblock: %m");
575
576 log_info("Discovered used LUKS device /dev/mapper/%s, and validated password.", setup->dm_name);
577
578 /* This is needed so that crypt_resize() can operate correctly for pre-existing LUKS devices. We need
579 * to tell libcryptsetup the volume key explicitly, so that it is in the kernel keyring. */
580 r = sym_crypt_activate_by_volume_key(setup->crypt_device, NULL, vk, vks, CRYPT_ACTIVATE_KEYRING_KEY);
581 if (r < 0)
582 return log_error_errno(r, "Failed to upload volume key again: %m");
583
584 log_info("Successfully re-activated LUKS device.");
585
586 if (ret_found_uuid)
587 *ret_found_uuid = p;
588 if (ret_volume_key)
589 *ret_volume_key = TAKE_PTR(vk);
590 if (ret_volume_key_size)
591 *ret_volume_key_size = vks;
592
593 return 0;
594 }
595
596 static int fs_validate(
597 const char *dm_node,
598 sd_id128_t uuid,
599 char **ret_fstype,
600 sd_id128_t *ret_found_uuid) {
601
602 _cleanup_free_ char *fstype = NULL;
603 sd_id128_t u = SD_ID128_NULL; /* avoid false maybe-unitialized warning */
604 int r;
605
606 assert(dm_node);
607 assert(ret_fstype);
608
609 r = probe_file_system_by_path(dm_node, &fstype, &u);
610 if (r < 0)
611 return log_error_errno(r, "Failed to probe file system: %m");
612
613 /* Limit the set of supported file systems a bit, as protection against little tested kernel file
614 * systems. Also, we only support the resize ioctls for these file systems. */
615 if (!supported_fstype(fstype))
616 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "Image contains unsupported file system: %s", strna(fstype));
617
618 if (!sd_id128_is_null(uuid) &&
619 !sd_id128_equal(uuid, u))
620 return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "File system has wrong UUID.");
621
622 log_info("Probing file system completed (found %s).", fstype);
623
624 *ret_fstype = TAKE_PTR(fstype);
625
626 if (ret_found_uuid) /* Return the UUID actually found if the caller wants to know */
627 *ret_found_uuid = u;
628
629 return 0;
630 }
631
632 static int luks_validate(
633 int fd,
634 const char *label,
635 sd_id128_t partition_uuid,
636 sd_id128_t *ret_partition_uuid,
637 uint64_t *ret_offset,
638 uint64_t *ret_size) {
639
640 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
641 sd_id128_t found_partition_uuid = SD_ID128_NULL;
642 const char *fstype = NULL, *pttype = NULL;
643 blkid_loff_t offset = 0, size = 0;
644 blkid_partlist pl;
645 bool found = false;
646 int r, n;
647
648 assert(fd >= 0);
649 assert(label);
650 assert(ret_offset);
651 assert(ret_size);
652
653 b = blkid_new_probe();
654 if (!b)
655 return -ENOMEM;
656
657 errno = 0;
658 r = blkid_probe_set_device(b, fd, 0, 0);
659 if (r != 0)
660 return errno_or_else(ENOMEM);
661
662 (void) blkid_probe_enable_superblocks(b, 1);
663 (void) blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
664 (void) blkid_probe_enable_partitions(b, 1);
665 (void) blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
666
667 errno = 0;
668 r = blkid_do_safeprobe(b);
669 if (r == _BLKID_SAFEPROBE_ERROR)
670 return errno_or_else(EIO);
671 if (IN_SET(r, _BLKID_SAFEPROBE_AMBIGUOUS, _BLKID_SAFEPROBE_NOT_FOUND))
672 return -ENOPKG;
673
674 assert(r == _BLKID_SAFEPROBE_FOUND);
675
676 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
677 if (streq_ptr(fstype, "crypto_LUKS")) {
678 /* Directly a LUKS image */
679 *ret_offset = 0;
680 *ret_size = UINT64_MAX; /* full disk */
681 *ret_partition_uuid = SD_ID128_NULL;
682 return 0;
683 } else if (fstype)
684 return -ENOPKG;
685
686 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
687 if (!streq_ptr(pttype, "gpt"))
688 return -ENOPKG;
689
690 errno = 0;
691 pl = blkid_probe_get_partitions(b);
692 if (!pl)
693 return errno_or_else(ENOMEM);
694
695 errno = 0;
696 n = blkid_partlist_numof_partitions(pl);
697 if (n < 0)
698 return errno_or_else(EIO);
699
700 for (int i = 0; i < n; i++) {
701 sd_id128_t id = SD_ID128_NULL;
702 blkid_partition pp;
703
704 errno = 0;
705 pp = blkid_partlist_get_partition(pl, i);
706 if (!pp)
707 return errno_or_else(EIO);
708
709 if (sd_id128_string_equal(blkid_partition_get_type_string(pp), SD_GPT_USER_HOME) <= 0)
710 continue;
711
712 if (!streq_ptr(blkid_partition_get_name(pp), label))
713 continue;
714
715
716 r = blkid_partition_get_uuid_id128(pp, &id);
717 if (r < 0)
718 log_debug_errno(r, "Failed to read partition UUID, ignoring: %m");
719 else if (!sd_id128_is_null(partition_uuid) && !sd_id128_equal(id, partition_uuid))
720 continue;
721
722 if (found)
723 return -ENOPKG;
724
725 offset = blkid_partition_get_start(pp);
726 size = blkid_partition_get_size(pp);
727 found_partition_uuid = id;
728
729 found = true;
730 }
731
732 if (!found)
733 return -ENOPKG;
734
735 if (offset < 0)
736 return -EINVAL;
737 if ((uint64_t) offset > UINT64_MAX / 512U)
738 return -EINVAL;
739 if (size <= 0)
740 return -EINVAL;
741 if ((uint64_t) size > UINT64_MAX / 512U)
742 return -EINVAL;
743
744 *ret_offset = offset * 512U;
745 *ret_size = size * 512U;
746 *ret_partition_uuid = found_partition_uuid;
747
748 return 0;
749 }
750
751 static int crypt_device_to_evp_cipher(struct crypt_device *cd, const EVP_CIPHER **ret) {
752 _cleanup_free_ char *cipher_name = NULL;
753 const char *cipher, *cipher_mode, *e;
754 size_t key_size, key_bits;
755 const EVP_CIPHER *cc;
756 int r;
757
758 assert(cd);
759
760 /* Let's find the right OpenSSL EVP_CIPHER object that matches the encryption settings of the LUKS
761 * device */
762
763 cipher = sym_crypt_get_cipher(cd);
764 if (!cipher)
765 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot get cipher from LUKS device.");
766
767 cipher_mode = sym_crypt_get_cipher_mode(cd);
768 if (!cipher_mode)
769 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot get cipher mode from LUKS device.");
770
771 e = strchr(cipher_mode, '-');
772 if (e)
773 cipher_mode = strndupa_safe(cipher_mode, e - cipher_mode);
774
775 r = sym_crypt_get_volume_key_size(cd);
776 if (r <= 0)
777 return log_error_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Cannot get volume key size from LUKS device.");
778
779 key_size = r;
780 key_bits = key_size * 8;
781 if (streq(cipher_mode, "xts"))
782 key_bits /= 2;
783
784 if (asprintf(&cipher_name, "%s-%zu-%s", cipher, key_bits, cipher_mode) < 0)
785 return log_oom();
786
787 cc = EVP_get_cipherbyname(cipher_name);
788 if (!cc)
789 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Selected cipher mode '%s' not supported, can't encrypt JSON record.", cipher_name);
790
791 /* Verify that our key length calculations match what OpenSSL thinks */
792 r = EVP_CIPHER_key_length(cc);
793 if (r < 0 || (uint64_t) r != key_size)
794 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Key size of selected cipher doesn't meet our expectations.");
795
796 *ret = cc;
797 return 0;
798 }
799
800 static int luks_validate_home_record(
801 struct crypt_device *cd,
802 UserRecord *h,
803 const void *volume_key,
804 PasswordCache *cache,
805 UserRecord **ret_luks_home_record) {
806
807 int r;
808
809 assert(cd);
810 assert(h);
811
812 for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
813 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL, *rr = NULL;
814 _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
815 _cleanup_(user_record_unrefp) UserRecord *lhr = NULL;
816 _cleanup_free_ void *encrypted = NULL, *iv = NULL;
817 size_t decrypted_size, encrypted_size, iv_size;
818 int decrypted_size_out1, decrypted_size_out2;
819 _cleanup_free_ char *decrypted = NULL;
820 const char *text, *type;
821 crypt_token_info state;
822 JsonVariant *jr, *jiv;
823 unsigned line, column;
824 const EVP_CIPHER *cc;
825
826 state = sym_crypt_token_status(cd, token, &type);
827 if (state == CRYPT_TOKEN_INACTIVE) /* First unconfigured token, give up */
828 break;
829 if (IN_SET(state, CRYPT_TOKEN_INTERNAL, CRYPT_TOKEN_INTERNAL_UNKNOWN, CRYPT_TOKEN_EXTERNAL))
830 continue;
831 if (state != CRYPT_TOKEN_EXTERNAL_UNKNOWN)
832 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected token state of token %i: %i", token, (int) state);
833
834 if (!streq(type, "systemd-homed"))
835 continue;
836
837 r = sym_crypt_token_json_get(cd, token, &text);
838 if (r < 0)
839 return log_error_errno(r, "Failed to read LUKS token %i: %m", token);
840
841 r = json_parse(text, JSON_PARSE_SENSITIVE, &v, &line, &column);
842 if (r < 0)
843 return log_error_errno(r, "Failed to parse LUKS token JSON data %u:%u: %m", line, column);
844
845 jr = json_variant_by_key(v, "record");
846 if (!jr)
847 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS token lacks 'record' field.");
848 jiv = json_variant_by_key(v, "iv");
849 if (!jiv)
850 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS token lacks 'iv' field.");
851
852 r = json_variant_unbase64(jr, &encrypted, &encrypted_size);
853 if (r < 0)
854 return log_error_errno(r, "Failed to base64 decode record: %m");
855
856 r = json_variant_unbase64(jiv, &iv, &iv_size);
857 if (r < 0)
858 return log_error_errno(r, "Failed to base64 decode IV: %m");
859
860 r = crypt_device_to_evp_cipher(cd, &cc);
861 if (r < 0)
862 return r;
863 if (iv_size > INT_MAX || EVP_CIPHER_iv_length(cc) != (int) iv_size)
864 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "IV size doesn't match.");
865
866 context = EVP_CIPHER_CTX_new();
867 if (!context)
868 return log_oom();
869
870 if (EVP_DecryptInit_ex(context, cc, NULL, volume_key, iv) != 1)
871 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize decryption context.");
872
873 decrypted_size = encrypted_size + EVP_CIPHER_key_length(cc) * 2;
874 decrypted = new(char, decrypted_size);
875 if (!decrypted)
876 return log_oom();
877
878 if (EVP_DecryptUpdate(context, (uint8_t*) decrypted, &decrypted_size_out1, encrypted, encrypted_size) != 1)
879 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to decrypt JSON record.");
880
881 assert((size_t) decrypted_size_out1 <= decrypted_size);
882
883 if (EVP_DecryptFinal_ex(context, (uint8_t*) decrypted + decrypted_size_out1, &decrypted_size_out2) != 1)
884 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finish decryption of JSON record.");
885
886 assert((size_t) decrypted_size_out1 + (size_t) decrypted_size_out2 < decrypted_size);
887 decrypted_size = (size_t) decrypted_size_out1 + (size_t) decrypted_size_out2;
888
889 if (memchr(decrypted, 0, decrypted_size))
890 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Inner NUL byte in JSON record, refusing.");
891
892 decrypted[decrypted_size] = 0;
893
894 r = json_parse(decrypted, JSON_PARSE_SENSITIVE, &rr, NULL, NULL);
895 if (r < 0)
896 return log_error_errno(r, "Failed to parse decrypted JSON record, refusing.");
897
898 lhr = user_record_new();
899 if (!lhr)
900 return log_oom();
901
902 r = user_record_load(lhr, rr, USER_RECORD_LOAD_EMBEDDED|USER_RECORD_PERMISSIVE);
903 if (r < 0)
904 return log_error_errno(r, "Failed to parse user record: %m");
905
906 if (!user_record_compatible(h, lhr))
907 return log_error_errno(SYNTHETIC_ERRNO(EREMCHG), "LUKS home record not compatible with host record, refusing.");
908
909 r = user_record_authenticate(lhr, h, cache, /* strict_verify= */ true);
910 if (r < 0)
911 return r;
912 assert(r > 0); /* Insist that a password was verified */
913
914 *ret_luks_home_record = TAKE_PTR(lhr);
915 return 0;
916 }
917
918 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Couldn't find home record in LUKS2 header, refusing.");
919 }
920
921 static int format_luks_token_text(
922 struct crypt_device *cd,
923 UserRecord *hr,
924 const void *volume_key,
925 char **ret) {
926
927 int r, encrypted_size_out1 = 0, encrypted_size_out2 = 0, iv_size, key_size;
928 _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
929 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
930 _cleanup_free_ void *iv = NULL, *encrypted = NULL;
931 size_t text_length, encrypted_size;
932 _cleanup_free_ char *text = NULL;
933 const EVP_CIPHER *cc;
934
935 assert(cd);
936 assert(hr);
937 assert(volume_key);
938 assert(ret);
939
940 r = crypt_device_to_evp_cipher(cd, &cc);
941 if (r < 0)
942 return r;
943
944 key_size = EVP_CIPHER_key_length(cc);
945 iv_size = EVP_CIPHER_iv_length(cc);
946
947 if (iv_size > 0) {
948 iv = malloc(iv_size);
949 if (!iv)
950 return log_oom();
951
952 r = crypto_random_bytes(iv, iv_size);
953 if (r < 0)
954 return log_error_errno(r, "Failed to generate IV: %m");
955 }
956
957 context = EVP_CIPHER_CTX_new();
958 if (!context)
959 return log_oom();
960
961 if (EVP_EncryptInit_ex(context, cc, NULL, volume_key, iv) != 1)
962 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize encryption context.");
963
964 r = json_variant_format(hr->json, 0, &text);
965 if (r < 0)
966 return log_error_errno(r, "Failed to format user record for LUKS: %m");
967
968 text_length = strlen(text);
969 encrypted_size = text_length + 2*key_size - 1;
970
971 encrypted = malloc(encrypted_size);
972 if (!encrypted)
973 return log_oom();
974
975 if (EVP_EncryptUpdate(context, encrypted, &encrypted_size_out1, (uint8_t*) text, text_length) != 1)
976 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to encrypt JSON record.");
977
978 assert((size_t) encrypted_size_out1 <= encrypted_size);
979
980 if (EVP_EncryptFinal_ex(context, (uint8_t*) encrypted + encrypted_size_out1, &encrypted_size_out2) != 1)
981 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finish encryption of JSON record. ");
982
983 assert((size_t) encrypted_size_out1 + (size_t) encrypted_size_out2 <= encrypted_size);
984
985 r = json_build(&v,
986 JSON_BUILD_OBJECT(
987 JSON_BUILD_PAIR("type", JSON_BUILD_CONST_STRING("systemd-homed")),
988 JSON_BUILD_PAIR("keyslots", JSON_BUILD_EMPTY_ARRAY),
989 JSON_BUILD_PAIR("record", JSON_BUILD_BASE64(encrypted, encrypted_size_out1 + encrypted_size_out2)),
990 JSON_BUILD_PAIR("iv", JSON_BUILD_BASE64(iv, iv_size))));
991 if (r < 0)
992 return log_error_errno(r, "Failed to prepare LUKS JSON token object: %m");
993
994 r = json_variant_format(v, 0, ret);
995 if (r < 0)
996 return log_error_errno(r, "Failed to format encrypted user record for LUKS: %m");
997
998 return 0;
999 }
1000
1001 int home_store_header_identity_luks(
1002 UserRecord *h,
1003 HomeSetup *setup,
1004 UserRecord *old_home) {
1005
1006 _cleanup_(user_record_unrefp) UserRecord *header_home = NULL;
1007 _cleanup_free_ char *text = NULL;
1008 int r;
1009
1010 assert(h);
1011
1012 if (!setup->crypt_device)
1013 return 0;
1014
1015 assert(setup->volume_key);
1016
1017 /* Let's store the user's identity record in the LUKS2 "token" header data fields, in an encrypted
1018 * fashion. Why that? If we'd rely on the record being embedded in the payload file system itself we
1019 * would have to mount the file system before we can validate the JSON record, its signatures and
1020 * whether it matches what we are looking for. However, kernel file system implementations are
1021 * generally not ready to be used on untrusted media. Hence let's store the record independently of
1022 * the file system, so that we can validate it first, and only then mount the file system. To keep
1023 * things simple we use the same encryption settings for this record as for the file system itself. */
1024
1025 r = user_record_clone(h, USER_RECORD_EXTRACT_EMBEDDED|USER_RECORD_PERMISSIVE, &header_home);
1026 if (r < 0)
1027 return log_error_errno(r, "Failed to determine new header record: %m");
1028
1029 if (old_home && user_record_equal(old_home, header_home)) {
1030 log_debug("Not updating header home record.");
1031 return 0;
1032 }
1033
1034 r = format_luks_token_text(setup->crypt_device, header_home, setup->volume_key, &text);
1035 if (r < 0)
1036 return r;
1037
1038 for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
1039 crypt_token_info state;
1040 const char *type;
1041
1042 state = sym_crypt_token_status(setup->crypt_device, token, &type);
1043 if (state == CRYPT_TOKEN_INACTIVE) /* First unconfigured token, we are done */
1044 break;
1045 if (IN_SET(state, CRYPT_TOKEN_INTERNAL, CRYPT_TOKEN_INTERNAL_UNKNOWN, CRYPT_TOKEN_EXTERNAL))
1046 continue; /* Not ours */
1047 if (state != CRYPT_TOKEN_EXTERNAL_UNKNOWN)
1048 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected token state of token %i: %i", token, (int) state);
1049
1050 if (!streq(type, "systemd-homed"))
1051 continue;
1052
1053 r = sym_crypt_token_json_set(setup->crypt_device, token, text);
1054 if (r < 0)
1055 return log_error_errno(r, "Failed to set JSON token for slot %i: %m", token);
1056
1057 /* Now, let's free the text so that for all further matching tokens we all crypt_json_token_set()
1058 * with a NULL text in order to invalidate the tokens. */
1059 text = mfree(text);
1060 }
1061
1062 if (text)
1063 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Didn't find any record token to update.");
1064
1065 log_info("Wrote LUKS header user record.");
1066
1067 return 1;
1068 }
1069
1070 int run_fitrim(int root_fd) {
1071 struct fstrim_range range = {
1072 .len = UINT64_MAX,
1073 };
1074
1075 /* If discarding is on, discard everything right after mounting, so that the discard setting takes
1076 * effect on activation. (Also, optionally, trim on logout) */
1077
1078 assert(root_fd >= 0);
1079
1080 if (ioctl(root_fd, FITRIM, &range) < 0) {
1081 if (ERRNO_IS_NOT_SUPPORTED(errno) || errno == EBADF) {
1082 log_debug_errno(errno, "File system does not support FITRIM, not trimming.");
1083 return 0;
1084 }
1085
1086 return log_warning_errno(errno, "Failed to invoke FITRIM, ignoring: %m");
1087 }
1088
1089 log_info("Discarded unused %s.", FORMAT_BYTES(range.len));
1090 return 1;
1091 }
1092
1093 int run_fallocate(int backing_fd, const struct stat *st) {
1094 struct stat stbuf;
1095
1096 assert(backing_fd >= 0);
1097
1098 /* If discarding is off, let's allocate the whole image before mounting, so that the setting takes
1099 * effect on activation */
1100
1101 if (!st) {
1102 if (fstat(backing_fd, &stbuf) < 0)
1103 return log_error_errno(errno, "Failed to fstat(): %m");
1104
1105 st = &stbuf;
1106 }
1107
1108 if (!S_ISREG(st->st_mode))
1109 return 0;
1110
1111 if (st->st_blocks >= DIV_ROUND_UP(st->st_size, 512)) {
1112 log_info("Backing file is fully allocated already.");
1113 return 0;
1114 }
1115
1116 if (fallocate(backing_fd, FALLOC_FL_KEEP_SIZE, 0, st->st_size) < 0) {
1117
1118 if (ERRNO_IS_NOT_SUPPORTED(errno)) {
1119 log_debug_errno(errno, "fallocate() not supported on file system, ignoring.");
1120 return 0;
1121 }
1122
1123 if (ERRNO_IS_DISK_SPACE(errno)) {
1124 log_debug_errno(errno, "Not enough disk space to fully allocate home.");
1125 return -ENOSPC; /* make recognizable */
1126 }
1127
1128 return log_error_errno(errno, "Failed to allocate backing file blocks: %m");
1129 }
1130
1131 log_info("Allocated additional %s.",
1132 FORMAT_BYTES((DIV_ROUND_UP(st->st_size, 512) - st->st_blocks) * 512));
1133 return 1;
1134 }
1135
1136 int run_fallocate_by_path(const char *backing_path) {
1137 _cleanup_close_ int backing_fd = -EBADF;
1138
1139 backing_fd = open(backing_path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
1140 if (backing_fd < 0)
1141 return log_error_errno(errno, "Failed to open '%s' for fallocate(): %m", backing_path);
1142
1143 return run_fallocate(backing_fd, NULL);
1144 }
1145
1146 static int lock_image_fd(int image_fd, const char *ip) {
1147 int r;
1148
1149 /* If the $SYSTEMD_LUKS_LOCK environment variable is set we'll take an exclusive BSD lock on the
1150 * image file, and send it to our parent. homed will keep it open to ensure no other instance of
1151 * homed (across the network or such) will also mount the file. */
1152
1153 assert(image_fd >= 0);
1154 assert(ip);
1155
1156 r = getenv_bool("SYSTEMD_LUKS_LOCK");
1157 if (r == -ENXIO)
1158 return 0;
1159 if (r < 0)
1160 return log_error_errno(r, "Failed to parse $SYSTEMD_LUKS_LOCK environment variable: %m");
1161 if (r == 0)
1162 return 0;
1163
1164 if (flock(image_fd, LOCK_EX|LOCK_NB) < 0) {
1165
1166 if (errno == EAGAIN)
1167 log_error_errno(errno, "Image file '%s' already locked, can't use.", ip);
1168 else
1169 log_error_errno(errno, "Failed to lock image file '%s': %m", ip);
1170
1171 return errno != EAGAIN ? -errno : -EADDRINUSE; /* Make error recognizable */
1172 }
1173
1174 log_info("Successfully locked image file '%s'.", ip);
1175
1176 /* Now send it to our parent to keep safe while the home dir is active */
1177 r = sd_pid_notify_with_fds(0, false, "SYSTEMD_LUKS_LOCK_FD=1", &image_fd, 1);
1178 if (r < 0)
1179 log_warning_errno(r, "Failed to send LUKS lock fd to parent, ignoring: %m");
1180
1181 return 0;
1182 }
1183
1184 static int open_image_file(
1185 UserRecord *h,
1186 const char *force_image_path,
1187 struct stat *ret_stat) {
1188
1189 _cleanup_close_ int image_fd = -EBADF;
1190 struct stat st;
1191 const char *ip;
1192 int r;
1193
1194 assert(h || force_image_path);
1195
1196 ip = force_image_path ?: user_record_image_path(h);
1197
1198 image_fd = open(ip, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
1199 if (image_fd < 0)
1200 return log_error_errno(errno, "Failed to open image file %s: %m", ip);
1201
1202 if (fstat(image_fd, &st) < 0)
1203 return log_error_errno(errno, "Failed to fstat() image file: %m");
1204 if (!S_ISREG(st.st_mode) && !S_ISBLK(st.st_mode))
1205 return log_error_errno(
1206 S_ISDIR(st.st_mode) ? SYNTHETIC_ERRNO(EISDIR) : SYNTHETIC_ERRNO(EBADFD),
1207 "Image file %s is not a regular file or block device: %m", ip);
1208
1209 /* Locking block devices doesn't really make sense, as this might interfere with
1210 * udev's workings, and these locks aren't network propagated anyway, hence not what
1211 * we are after here. */
1212 if (S_ISREG(st.st_mode)) {
1213 r = lock_image_fd(image_fd, ip);
1214 if (r < 0)
1215 return r;
1216 }
1217
1218 if (ret_stat)
1219 *ret_stat = st;
1220
1221 return TAKE_FD(image_fd);
1222 }
1223
1224 int home_setup_luks(
1225 UserRecord *h,
1226 HomeSetupFlags flags,
1227 const char *force_image_path,
1228 HomeSetup *setup,
1229 PasswordCache *cache,
1230 UserRecord **ret_luks_home) {
1231
1232 sd_id128_t found_partition_uuid, found_fs_uuid = SD_ID128_NULL, found_luks_uuid = SD_ID128_NULL;
1233 _cleanup_(user_record_unrefp) UserRecord *luks_home = NULL;
1234 _cleanup_(erase_and_freep) void *volume_key = NULL;
1235 size_t volume_key_size = 0;
1236 uint64_t offset, size;
1237 struct stat st;
1238 int r;
1239
1240 assert(h);
1241 assert(setup);
1242 assert(user_record_storage(h) == USER_LUKS);
1243
1244 r = dlopen_cryptsetup();
1245 if (r < 0)
1246 return r;
1247
1248 r = make_dm_names(h, setup);
1249 if (r < 0)
1250 return r;
1251
1252 /* Reuse the image fd if it has already been opened by an earlier step */
1253 if (setup->image_fd < 0) {
1254 setup->image_fd = open_image_file(h, force_image_path, &st);
1255 if (setup->image_fd < 0)
1256 return setup->image_fd;
1257 } else if (fstat(setup->image_fd, &st) < 0)
1258 return log_error_errno(errno, "Failed to stat image: %m");
1259
1260 if (FLAGS_SET(flags, HOME_SETUP_ALREADY_ACTIVATED)) {
1261 struct loop_info64 info;
1262 const char *n;
1263
1264 if (!setup->crypt_device) {
1265 r = luks_open(h,
1266 setup,
1267 cache,
1268 &found_luks_uuid,
1269 &volume_key,
1270 &volume_key_size);
1271 if (r < 0)
1272 return r;
1273 }
1274
1275 if (ret_luks_home) {
1276 r = luks_validate_home_record(setup->crypt_device, h, volume_key, cache, &luks_home);
1277 if (r < 0)
1278 return r;
1279 }
1280
1281 n = sym_crypt_get_device_name(setup->crypt_device);
1282 if (!n)
1283 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine backing device for DM %s.", setup->dm_name);
1284
1285 if (!setup->loop) {
1286 r = loop_device_open_from_path(n, O_RDWR, LOCK_UN, &setup->loop);
1287 if (r < 0)
1288 return log_error_errno(r, "Failed to open loopback device %s: %m", n);
1289 }
1290
1291 if (ioctl(setup->loop->fd, LOOP_GET_STATUS64, &info) < 0) {
1292 _cleanup_free_ char *sysfs = NULL;
1293
1294 if (!IN_SET(errno, ENOTTY, EINVAL))
1295 return log_error_errno(errno, "Failed to get block device metrics of %s: %m", n);
1296
1297 if (fstat(setup->loop->fd, &st) < 0)
1298 return log_error_errno(r, "Failed to stat block device %s: %m", n);
1299 assert(S_ISBLK(st.st_mode));
1300
1301 if (asprintf(&sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/partition", DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
1302 return log_oom();
1303
1304 if (access(sysfs, F_OK) < 0) {
1305 if (errno != ENOENT)
1306 return log_error_errno(errno, "Failed to determine whether %s exists: %m", sysfs);
1307
1308 offset = 0;
1309 } else {
1310 _cleanup_free_ char *buffer = NULL;
1311
1312 if (asprintf(&sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/start", DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
1313 return log_oom();
1314
1315 r = read_one_line_file(sysfs, &buffer);
1316 if (r < 0)
1317 return log_error_errno(r, "Failed to read partition start offset: %m");
1318
1319 r = safe_atou64(buffer, &offset);
1320 if (r < 0)
1321 return log_error_errno(r, "Failed to parse partition start offset: %m");
1322
1323 if (offset > UINT64_MAX / 512U)
1324 return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "Offset too large for 64 byte range, refusing.");
1325
1326 offset *= 512U;
1327 }
1328
1329 size = setup->loop->device_size;
1330 } else {
1331 #if HAVE_VALGRIND_MEMCHECK_H
1332 VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
1333 #endif
1334
1335 offset = info.lo_offset;
1336 size = info.lo_sizelimit;
1337 }
1338
1339 found_partition_uuid = found_fs_uuid = SD_ID128_NULL;
1340
1341 log_info("Discovered used loopback device %s.", setup->loop->node);
1342
1343 if (setup->root_fd < 0) {
1344 setup->root_fd = open(user_record_home_directory(h), O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
1345 if (setup->root_fd < 0)
1346 return log_error_errno(errno, "Failed to open home directory: %m");
1347 }
1348 } else {
1349 _cleanup_free_ char *fstype = NULL, *subdir = NULL;
1350 const char *ip;
1351
1352 /* When we aren't reopening the home directory we are allocating it fresh, hence the relevant
1353 * objects can't be allocated yet. */
1354 assert(setup->root_fd < 0);
1355 assert(!setup->crypt_device);
1356 assert(!setup->loop);
1357
1358 ip = force_image_path ?: user_record_image_path(h);
1359
1360 subdir = path_join(HOME_RUNTIME_WORK_DIR, user_record_user_name_and_realm(h));
1361 if (!subdir)
1362 return log_oom();
1363
1364 r = luks_validate(setup->image_fd, user_record_user_name_and_realm(h), h->partition_uuid, &found_partition_uuid, &offset, &size);
1365 if (r < 0)
1366 return log_error_errno(r, "Failed to validate disk label: %m");
1367
1368 /* Everything before this point left the image untouched. We are now starting to make
1369 * changes, hence mark the image dirty */
1370 if (run_mark_dirty(setup->image_fd, true) > 0)
1371 setup->do_mark_clean = true;
1372
1373 if (!user_record_luks_discard(h)) {
1374 r = run_fallocate(setup->image_fd, &st);
1375 if (r < 0)
1376 return r;
1377 }
1378
1379 r = loop_device_make(
1380 setup->image_fd,
1381 O_RDWR,
1382 offset,
1383 size,
1384 h->luks_sector_size == UINT64_MAX ? UINT32_MAX : user_record_luks_sector_size(h), /* if sector size is not specified, select UINT32_MAX, i.e. auto-probe */
1385 /* loop_flags= */ 0,
1386 LOCK_UN,
1387 &setup->loop);
1388 if (r == -ENOENT) {
1389 log_error_errno(r, "Loopback block device support is not available on this system.");
1390 return -ENOLINK; /* make recognizable */
1391 }
1392 if (r < 0)
1393 return log_error_errno(r, "Failed to allocate loopback context: %m");
1394
1395 log_info("Setting up loopback device %s completed.", setup->loop->node ?: ip);
1396
1397 r = luks_setup(h,
1398 setup->loop->node ?: ip,
1399 setup->dm_name,
1400 h->luks_uuid,
1401 h->luks_cipher,
1402 h->luks_cipher_mode,
1403 h->luks_volume_key_size,
1404 h->password,
1405 cache,
1406 user_record_luks_discard(h) || user_record_luks_offline_discard(h),
1407 &setup->crypt_device,
1408 &found_luks_uuid,
1409 &volume_key,
1410 &volume_key_size,
1411 &setup->key_serial);
1412 if (r < 0)
1413 return r;
1414
1415 setup->undo_dm = true;
1416
1417 if (ret_luks_home) {
1418 r = luks_validate_home_record(setup->crypt_device, h, volume_key, cache, &luks_home);
1419 if (r < 0)
1420 return r;
1421 }
1422
1423 r = fs_validate(setup->dm_node, h->file_system_uuid, &fstype, &found_fs_uuid);
1424 if (r < 0)
1425 return r;
1426
1427 r = run_fsck(setup->dm_node, fstype);
1428 if (r < 0)
1429 return r;
1430
1431 r = home_unshare_and_mount(setup->dm_node, fstype, user_record_luks_discard(h), user_record_mount_flags(h), h->luks_extra_mount_options);
1432 if (r < 0)
1433 return r;
1434
1435 setup->undo_mount = true;
1436
1437 setup->root_fd = open(subdir, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
1438 if (setup->root_fd < 0)
1439 return log_error_errno(errno, "Failed to open home directory: %m");
1440
1441 if (user_record_luks_discard(h))
1442 (void) run_fitrim(setup->root_fd);
1443
1444 setup->do_offline_fallocate = !(setup->do_offline_fitrim = user_record_luks_offline_discard(h));
1445 }
1446
1447 if (!sd_id128_is_null(found_partition_uuid))
1448 setup->found_partition_uuid = found_partition_uuid;
1449 if (!sd_id128_is_null(found_luks_uuid))
1450 setup->found_luks_uuid = found_luks_uuid;
1451 if (!sd_id128_is_null(found_fs_uuid))
1452 setup->found_fs_uuid = found_fs_uuid;
1453
1454 setup->partition_offset = offset;
1455 setup->partition_size = size;
1456
1457 if (volume_key) {
1458 erase_and_free(setup->volume_key);
1459 setup->volume_key = TAKE_PTR(volume_key);
1460 setup->volume_key_size = volume_key_size;
1461 }
1462
1463 if (ret_luks_home)
1464 *ret_luks_home = TAKE_PTR(luks_home);
1465
1466 return 0;
1467 }
1468
1469 static void print_size_summary(uint64_t host_size, uint64_t encrypted_size, const struct statfs *sfs) {
1470 assert(sfs);
1471
1472 log_info("Image size is %s, file system size is %s, file system payload size is %s, file system free is %s.",
1473 FORMAT_BYTES(host_size),
1474 FORMAT_BYTES(encrypted_size),
1475 FORMAT_BYTES((uint64_t) sfs->f_blocks * (uint64_t) sfs->f_frsize),
1476 FORMAT_BYTES((uint64_t) sfs->f_bfree * (uint64_t) sfs->f_frsize));
1477 }
1478
1479 static int home_auto_grow_luks(
1480 UserRecord *h,
1481 HomeSetup *setup,
1482 PasswordCache *cache) {
1483
1484 struct statfs sfs;
1485
1486 assert(h);
1487 assert(setup);
1488
1489 if (!IN_SET(user_record_auto_resize_mode(h), AUTO_RESIZE_GROW, AUTO_RESIZE_SHRINK_AND_GROW))
1490 return 0;
1491
1492 assert(setup->root_fd >= 0);
1493
1494 if (fstatfs(setup->root_fd, &sfs) < 0)
1495 return log_error_errno(errno, "Failed to statfs home directory: %m");
1496
1497 if (!fs_can_online_shrink_and_grow(sfs.f_type)) {
1498 log_debug("Not auto-grow file system, since selected file system cannot do both online shrink and grow.");
1499 return 0;
1500 }
1501
1502 log_debug("Initiating auto-grow...");
1503
1504 return home_resize_luks(
1505 h,
1506 HOME_SETUP_ALREADY_ACTIVATED|
1507 HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES|
1508 HOME_SETUP_RESIZE_DONT_SHRINK|
1509 HOME_SETUP_RESIZE_DONT_UNDO,
1510 setup,
1511 cache,
1512 NULL);
1513 }
1514
1515 int home_activate_luks(
1516 UserRecord *h,
1517 HomeSetupFlags flags,
1518 HomeSetup *setup,
1519 PasswordCache *cache,
1520 UserRecord **ret_home) {
1521
1522 _cleanup_(user_record_unrefp) UserRecord *new_home = NULL, *luks_home_record = NULL;
1523 uint64_t host_size, encrypted_size;
1524 const char *hdo, *hd;
1525 struct statfs sfs;
1526 int r;
1527
1528 assert(h);
1529 assert(user_record_storage(h) == USER_LUKS);
1530 assert(setup);
1531 assert(ret_home);
1532
1533 r = dlopen_cryptsetup();
1534 if (r < 0)
1535 return r;
1536
1537 assert_se(hdo = user_record_home_directory(h));
1538 hd = strdupa_safe(hdo); /* copy the string out, since it might change later in the home record object */
1539
1540 r = home_get_state_luks(h, setup);
1541 if (r < 0)
1542 return r;
1543 if (r > 0)
1544 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Device mapper device %s already exists, refusing.", setup->dm_node);
1545
1546 r = home_setup_luks(
1547 h,
1548 0,
1549 NULL,
1550 setup,
1551 cache,
1552 &luks_home_record);
1553 if (r < 0)
1554 return r;
1555
1556 r = home_auto_grow_luks(h, setup, cache);
1557 if (r < 0)
1558 return r;
1559
1560 r = block_get_size_by_fd(setup->loop->fd, &host_size);
1561 if (r < 0)
1562 return log_error_errno(r, "Failed to get loopback block device size: %m");
1563
1564 r = block_get_size_by_path(setup->dm_node, &encrypted_size);
1565 if (r < 0)
1566 return log_error_errno(r, "Failed to get LUKS block device size: %m");
1567
1568 r = home_refresh(
1569 h,
1570 flags,
1571 setup,
1572 luks_home_record,
1573 cache,
1574 &sfs,
1575 &new_home);
1576 if (r < 0)
1577 return r;
1578
1579 r = home_extend_embedded_identity(new_home, h, setup);
1580 if (r < 0)
1581 return r;
1582
1583 setup->root_fd = safe_close(setup->root_fd);
1584
1585 r = home_move_mount(user_record_user_name_and_realm(h), hd);
1586 if (r < 0)
1587 return r;
1588
1589 setup->undo_mount = false;
1590 setup->do_offline_fitrim = false;
1591
1592 loop_device_relinquish(setup->loop);
1593
1594 r = sym_crypt_deactivate_by_name(NULL, setup->dm_name, CRYPT_DEACTIVATE_DEFERRED);
1595 if (r < 0)
1596 log_warning_errno(r, "Failed to relinquish DM device, ignoring: %m");
1597
1598 setup->undo_dm = false;
1599 setup->do_offline_fallocate = false;
1600 setup->do_mark_clean = false;
1601 setup->do_drop_caches = false;
1602 TAKE_KEY_SERIAL(setup->key_serial); /* Leave key in kernel keyring */
1603
1604 log_info("Activation completed.");
1605
1606 print_size_summary(host_size, encrypted_size, &sfs);
1607
1608 *ret_home = TAKE_PTR(new_home);
1609 return 1;
1610 }
1611
1612 int home_deactivate_luks(UserRecord *h, HomeSetup *setup) {
1613 bool we_detached = false;
1614 int r;
1615
1616 assert(h);
1617 assert(setup);
1618
1619 /* Note that the DM device and loopback device are set to auto-detach, hence strictly speaking we
1620 * don't have to explicitly have to detach them. However, we do that nonetheless (in case of the DM
1621 * device), to avoid races: by explicitly detaching them we know when the detaching is complete. We
1622 * don't bother about the loopback device because unlike the DM device it doesn't have a fixed
1623 * name. */
1624
1625 if (!setup->crypt_device) {
1626 r = acquire_open_luks_device(h, setup, /* graceful= */ true);
1627 if (r < 0)
1628 return log_error_errno(r, "Failed to initialize cryptsetup context for %s: %m", setup->dm_name);
1629 if (r == 0)
1630 log_debug("LUKS device %s has already been detached.", setup->dm_name);
1631 }
1632
1633 if (setup->crypt_device) {
1634 log_info("Discovered used LUKS device %s.", setup->dm_node);
1635
1636 cryptsetup_enable_logging(setup->crypt_device);
1637
1638 r = sym_crypt_deactivate_by_name(setup->crypt_device, setup->dm_name, 0);
1639 if (ERRNO_IS_NEG_DEVICE_ABSENT(r) || r == -EINVAL)
1640 log_debug_errno(r, "LUKS device %s is already detached.", setup->dm_node);
1641 else if (r < 0)
1642 return log_info_errno(r, "LUKS device %s couldn't be deactivated: %m", setup->dm_node);
1643 else {
1644 log_info("LUKS device detaching completed.");
1645 we_detached = true;
1646 }
1647 }
1648
1649 (void) wait_for_block_device_gone(setup, USEC_PER_SEC * 30);
1650 setup->undo_dm = false;
1651
1652 if (user_record_luks_offline_discard(h))
1653 log_debug("Not allocating on logout.");
1654 else
1655 (void) run_fallocate_by_path(user_record_image_path(h));
1656
1657 run_mark_dirty_by_path(user_record_image_path(h), false);
1658 return we_detached;
1659 }
1660
1661 int home_trim_luks(UserRecord *h, HomeSetup *setup) {
1662 assert(h);
1663 assert(setup);
1664 assert(setup->root_fd >= 0);
1665
1666 if (!user_record_luks_offline_discard(h)) {
1667 log_debug("Not trimming on logout.");
1668 return 0;
1669 }
1670
1671 (void) run_fitrim(setup->root_fd);
1672 return 0;
1673 }
1674
1675 static struct crypt_pbkdf_type* build_good_pbkdf(struct crypt_pbkdf_type *buffer, UserRecord *hr) {
1676 assert(buffer);
1677 assert(hr);
1678
1679 bool benchmark = user_record_luks_pbkdf_force_iterations(hr) == UINT64_MAX;
1680
1681 *buffer = (struct crypt_pbkdf_type) {
1682 .hash = user_record_luks_pbkdf_hash_algorithm(hr),
1683 .type = user_record_luks_pbkdf_type(hr),
1684 .time_ms = benchmark ? user_record_luks_pbkdf_time_cost_usec(hr) / USEC_PER_MSEC : 0,
1685 .iterations = benchmark ? 0 : user_record_luks_pbkdf_force_iterations(hr),
1686 .max_memory_kb = user_record_luks_pbkdf_memory_cost(hr) / 1024,
1687 .parallel_threads = user_record_luks_pbkdf_parallel_threads(hr),
1688 .flags = benchmark ? 0 : CRYPT_PBKDF_NO_BENCHMARK,
1689 };
1690
1691 return buffer;
1692 }
1693
1694 static struct crypt_pbkdf_type* build_minimal_pbkdf(struct crypt_pbkdf_type *buffer, UserRecord *hr) {
1695 assert(buffer);
1696 assert(hr);
1697
1698 /* For PKCS#11 derived keys (which are generated randomly and are of high quality already) we use a
1699 * minimal PBKDF and CRYPT_PBKDF_NO_BENCHMARK flag to skip benchmark. */
1700 *buffer = (struct crypt_pbkdf_type) {
1701 .hash = user_record_luks_pbkdf_hash_algorithm(hr),
1702 .type = CRYPT_KDF_PBKDF2,
1703 .iterations = 1000, /* recommended minimum count for pbkdf2
1704 * according to NIST SP 800-132, ch. 5.2 */
1705 .flags = CRYPT_PBKDF_NO_BENCHMARK
1706 };
1707
1708 return buffer;
1709 }
1710
1711 static int luks_format(
1712 const char *node,
1713 const char *dm_name,
1714 sd_id128_t uuid,
1715 const char *label,
1716 const PasswordCache *cache,
1717 char **effective_passwords,
1718 bool discard,
1719 UserRecord *hr,
1720 struct crypt_device **ret) {
1721
1722 _cleanup_(user_record_unrefp) UserRecord *reduced = NULL;
1723 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
1724 _cleanup_(erase_and_freep) void *volume_key = NULL;
1725 struct crypt_pbkdf_type good_pbkdf, minimal_pbkdf;
1726 _cleanup_free_ char *text = NULL;
1727 size_t volume_key_size;
1728 int slot = 0, r;
1729
1730 assert(node);
1731 assert(dm_name);
1732 assert(hr);
1733 assert(ret);
1734
1735 r = sym_crypt_init(&cd, node);
1736 if (r < 0)
1737 return log_error_errno(r, "Failed to allocate libcryptsetup context: %m");
1738
1739 cryptsetup_enable_logging(cd);
1740
1741 /* Normally we'd, just leave volume key generation to libcryptsetup. However, we can't, since we
1742 * can't extract the volume key from the library again, but we need it in order to encrypt the JSON
1743 * record. Hence, let's generate it on our own, so that we can keep track of it. */
1744
1745 volume_key_size = user_record_luks_volume_key_size(hr);
1746 volume_key = malloc(volume_key_size);
1747 if (!volume_key)
1748 return log_oom();
1749
1750 r = crypto_random_bytes(volume_key, volume_key_size);
1751 if (r < 0)
1752 return log_error_errno(r, "Failed to generate volume key: %m");
1753
1754 #if HAVE_CRYPT_SET_METADATA_SIZE
1755 /* Increase the metadata space to 4M, the largest LUKS2 supports */
1756 r = sym_crypt_set_metadata_size(cd, 4096U*1024U, 0);
1757 if (r < 0)
1758 return log_error_errno(r, "Failed to change LUKS2 metadata size: %m");
1759 #endif
1760
1761 build_good_pbkdf(&good_pbkdf, hr);
1762 build_minimal_pbkdf(&minimal_pbkdf, hr);
1763
1764 r = sym_crypt_format(
1765 cd,
1766 CRYPT_LUKS2,
1767 user_record_luks_cipher(hr),
1768 user_record_luks_cipher_mode(hr),
1769 SD_ID128_TO_UUID_STRING(uuid),
1770 volume_key,
1771 volume_key_size,
1772 &(struct crypt_params_luks2) {
1773 .label = label,
1774 .subsystem = "systemd-home",
1775 .sector_size = user_record_luks_sector_size(hr),
1776 .pbkdf = &good_pbkdf,
1777 });
1778 if (r < 0)
1779 return log_error_errno(r, "Failed to format LUKS image: %m");
1780
1781 log_info("LUKS formatting completed.");
1782
1783 STRV_FOREACH(pp, effective_passwords) {
1784
1785 if (password_cache_contains(cache, *pp)) { /* is this a fido2 or pkcs11 password? */
1786 log_debug("Using minimal PBKDF for slot %i", slot);
1787 r = sym_crypt_set_pbkdf_type(cd, &minimal_pbkdf);
1788 } else {
1789 log_debug("Using good PBKDF for slot %i", slot);
1790 r = sym_crypt_set_pbkdf_type(cd, &good_pbkdf);
1791 }
1792 if (r < 0)
1793 return log_error_errno(r, "Failed to tweak PBKDF for slot %i: %m", slot);
1794
1795 r = sym_crypt_keyslot_add_by_volume_key(
1796 cd,
1797 slot,
1798 volume_key,
1799 volume_key_size,
1800 *pp,
1801 strlen(*pp));
1802 if (r < 0)
1803 return log_error_errno(r, "Failed to set up LUKS password for slot %i: %m", slot);
1804
1805 log_info("Writing password to LUKS keyslot %i completed.", slot);
1806 slot++;
1807 }
1808
1809 r = sym_crypt_activate_by_volume_key(
1810 cd,
1811 dm_name,
1812 volume_key,
1813 volume_key_size,
1814 discard ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0);
1815 if (r < 0)
1816 return log_error_errno(r, "Failed to activate LUKS superblock: %m");
1817
1818 log_info("LUKS activation by volume key succeeded.");
1819
1820 r = user_record_clone(hr, USER_RECORD_EXTRACT_EMBEDDED|USER_RECORD_PERMISSIVE, &reduced);
1821 if (r < 0)
1822 return log_error_errno(r, "Failed to prepare home record for LUKS: %m");
1823
1824 r = format_luks_token_text(cd, reduced, volume_key, &text);
1825 if (r < 0)
1826 return r;
1827
1828 r = sym_crypt_token_json_set(cd, CRYPT_ANY_TOKEN, text);
1829 if (r < 0)
1830 return log_error_errno(r, "Failed to set LUKS JSON token: %m");
1831
1832 log_info("Writing user record as LUKS token completed.");
1833
1834 if (ret)
1835 *ret = TAKE_PTR(cd);
1836
1837 return 0;
1838 }
1839
1840 static int make_partition_table(
1841 int fd,
1842 uint32_t sector_size,
1843 const char *label,
1844 sd_id128_t uuid,
1845 uint64_t *ret_offset,
1846 uint64_t *ret_size,
1847 sd_id128_t *ret_disk_uuid) {
1848
1849 _cleanup_(fdisk_unref_partitionp) struct fdisk_partition *p = NULL, *q = NULL;
1850 _cleanup_(fdisk_unref_parttypep) struct fdisk_parttype *t = NULL;
1851 _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
1852 _cleanup_free_ char *disk_uuid_as_string = NULL;
1853 uint64_t offset, size, first_lba, start, last_lba, end;
1854 sd_id128_t disk_uuid;
1855 int r;
1856
1857 assert(fd >= 0);
1858 assert(label);
1859 assert(ret_offset);
1860 assert(ret_size);
1861
1862 t = fdisk_new_parttype();
1863 if (!t)
1864 return log_oom();
1865
1866 r = fdisk_parttype_set_typestr(t, SD_GPT_USER_HOME_STR);
1867 if (r < 0)
1868 return log_error_errno(r, "Failed to initialize partition type: %m");
1869
1870 r = fdisk_new_context_at(fd, /* path= */ NULL, /* read_only= */ false, sector_size, &c);
1871 if (r < 0)
1872 return log_error_errno(r, "Failed to open device: %m");
1873
1874 r = fdisk_create_disklabel(c, "gpt");
1875 if (r < 0)
1876 return log_error_errno(r, "Failed to create GPT disk label: %m");
1877
1878 p = fdisk_new_partition();
1879 if (!p)
1880 return log_oom();
1881
1882 r = fdisk_partition_set_type(p, t);
1883 if (r < 0)
1884 return log_error_errno(r, "Failed to set partition type: %m");
1885
1886 r = fdisk_partition_partno_follow_default(p, 1);
1887 if (r < 0)
1888 return log_error_errno(r, "Failed to place partition at first free partition index: %m");
1889
1890 first_lba = fdisk_get_first_lba(c); /* Boundary where usable space starts */
1891 assert(first_lba <= UINT64_MAX/512);
1892 start = DISK_SIZE_ROUND_UP(first_lba * 512); /* Round up to multiple of 4K */
1893
1894 log_debug("Starting partition at offset %" PRIu64, start);
1895
1896 if (start == UINT64_MAX)
1897 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Overflow while rounding up start LBA.");
1898
1899 last_lba = fdisk_get_last_lba(c); /* One sector before boundary where usable space ends */
1900 assert(last_lba < UINT64_MAX/512);
1901 end = DISK_SIZE_ROUND_DOWN((last_lba + 1) * 512); /* Round down to multiple of 4K */
1902
1903 if (end <= start)
1904 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Resulting partition size zero or negative.");
1905
1906 r = fdisk_partition_set_start(p, start / 512);
1907 if (r < 0)
1908 return log_error_errno(r, "Failed to place partition at offset %" PRIu64 ": %m", start);
1909
1910 r = fdisk_partition_set_size(p, (end - start) / 512);
1911 if (r < 0)
1912 return log_error_errno(r, "Failed to end partition at offset %" PRIu64 ": %m", end);
1913
1914 r = fdisk_partition_set_name(p, label);
1915 if (r < 0)
1916 return log_error_errno(r, "Failed to set partition name: %m");
1917
1918 r = fdisk_partition_set_uuid(p, SD_ID128_TO_UUID_STRING(uuid));
1919 if (r < 0)
1920 return log_error_errno(r, "Failed to set partition UUID: %m");
1921
1922 r = fdisk_add_partition(c, p, NULL);
1923 if (r < 0)
1924 return log_error_errno(r, "Failed to add partition: %m");
1925
1926 r = fdisk_write_disklabel(c);
1927 if (r < 0)
1928 return log_error_errno(r, "Failed to write disk label: %m");
1929
1930 r = fdisk_get_disklabel_id(c, &disk_uuid_as_string);
1931 if (r < 0)
1932 return log_error_errno(r, "Failed to determine disk label UUID: %m");
1933
1934 r = sd_id128_from_string(disk_uuid_as_string, &disk_uuid);
1935 if (r < 0)
1936 return log_error_errno(r, "Failed to parse disk label UUID: %m");
1937
1938 r = fdisk_get_partition(c, 0, &q);
1939 if (r < 0)
1940 return log_error_errno(r, "Failed to read created partition metadata: %m");
1941
1942 assert(fdisk_partition_has_start(q));
1943 offset = fdisk_partition_get_start(q);
1944 if (offset > UINT64_MAX / 512U)
1945 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Partition offset too large.");
1946
1947 assert(fdisk_partition_has_size(q));
1948 size = fdisk_partition_get_size(q);
1949 if (size > UINT64_MAX / 512U)
1950 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Partition size too large.");
1951
1952 *ret_offset = offset * 512U;
1953 *ret_size = size * 512U;
1954 *ret_disk_uuid = disk_uuid;
1955
1956 return 0;
1957 }
1958
1959 static bool supported_fs_size(const char *fstype, uint64_t host_size) {
1960 uint64_t m;
1961
1962 m = minimal_size_by_fs_name(fstype);
1963 if (m == UINT64_MAX)
1964 return false;
1965
1966 return host_size >= m;
1967 }
1968
1969 static int wait_for_devlink(const char *path) {
1970 _cleanup_close_ int inotify_fd = -EBADF;
1971 usec_t until;
1972 int r;
1973
1974 /* let's wait for a device link to show up in /dev, with a timeout. This is good to do since we
1975 * return a /dev/disk/by-uuid/… link to our callers and they likely want to access it right-away,
1976 * hence let's wait until udev has caught up with our changes, and wait for the symlink to be
1977 * created. */
1978
1979 until = usec_add(now(CLOCK_MONOTONIC), 45 * USEC_PER_SEC);
1980
1981 for (;;) {
1982 _cleanup_free_ char *dn = NULL;
1983 usec_t w;
1984
1985 if (laccess(path, F_OK) < 0) {
1986 if (errno != ENOENT)
1987 return log_error_errno(errno, "Failed to determine whether %s exists: %m", path);
1988 } else
1989 return 0; /* Found it */
1990
1991 if (inotify_fd < 0) {
1992 /* We need to wait for the device symlink to show up, let's create an inotify watch for it */
1993 inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1994 if (inotify_fd < 0)
1995 return log_error_errno(errno, "Failed to allocate inotify fd: %m");
1996 }
1997
1998 r = path_extract_directory(path, &dn);
1999 if (r < 0)
2000 return log_error_errno(r, "Failed to extract directory from device node path '%s': %m", path);
2001 for (;;) {
2002 _cleanup_free_ char *ndn = NULL;
2003
2004 log_info("Watching %s", dn);
2005
2006 if (inotify_add_watch(inotify_fd, dn, IN_CREATE|IN_MOVED_TO|IN_ONLYDIR|IN_DELETE_SELF|IN_MOVE_SELF) < 0) {
2007 if (errno != ENOENT)
2008 return log_error_errno(errno, "Failed to add watch on %s: %m", dn);
2009 } else
2010 break;
2011
2012 r = path_extract_directory(dn, &ndn);
2013 if (r == -EADDRNOTAVAIL) /* Arrived at the top? */
2014 break;
2015 if (r < 0)
2016 return log_error_errno(r, "Failed to extract directory from device node path '%s': %m", dn);
2017
2018 free_and_replace(dn, ndn);
2019 }
2020
2021 w = now(CLOCK_MONOTONIC);
2022 if (w >= until)
2023 return log_error_errno(SYNTHETIC_ERRNO(ETIMEDOUT), "Device link %s still hasn't shown up, giving up.", path);
2024
2025 r = fd_wait_for_event(inotify_fd, POLLIN, until - w);
2026 if (ERRNO_IS_NEG_TRANSIENT(r))
2027 continue;
2028 if (r < 0)
2029 return log_error_errno(r, "Failed to watch inotify: %m");
2030
2031 (void) flush_fd(inotify_fd);
2032 }
2033 }
2034
2035 static int calculate_initial_image_size(UserRecord *h, int image_fd, const char *fstype, uint64_t *ret) {
2036 uint64_t upper_boundary, lower_boundary;
2037 struct statfs sfs;
2038
2039 assert(h);
2040 assert(image_fd >= 0);
2041 assert(ret);
2042
2043 if (fstatfs(image_fd, &sfs) < 0)
2044 return log_error_errno(errno, "statfs() on image failed: %m");
2045
2046 upper_boundary = DISK_SIZE_ROUND_DOWN((uint64_t) sfs.f_bsize * sfs.f_bavail);
2047
2048 if (h->disk_size != UINT64_MAX)
2049 *ret = MIN(DISK_SIZE_ROUND_DOWN(h->disk_size), upper_boundary);
2050 else if (h->disk_size_relative == UINT64_MAX) {
2051
2052 if (upper_boundary > UINT64_MAX / USER_DISK_SIZE_DEFAULT_PERCENT)
2053 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Disk size too large.");
2054
2055 *ret = DISK_SIZE_ROUND_DOWN(upper_boundary * USER_DISK_SIZE_DEFAULT_PERCENT / 100);
2056
2057 log_info("Sizing home to %u%% of available disk space, which is %s.",
2058 USER_DISK_SIZE_DEFAULT_PERCENT,
2059 FORMAT_BYTES(*ret));
2060 } else {
2061 *ret = DISK_SIZE_ROUND_DOWN((uint64_t) ((double) upper_boundary * (double) CLAMP(h->disk_size_relative, 0U, UINT32_MAX) / (double) UINT32_MAX));
2062
2063 log_info("Sizing home to %" PRIu64 ".%01" PRIu64 "%% of available disk space, which is %s.",
2064 (h->disk_size_relative * 100) / UINT32_MAX,
2065 ((h->disk_size_relative * 1000) / UINT32_MAX) % 10,
2066 FORMAT_BYTES(*ret));
2067 }
2068
2069 lower_boundary = minimal_size_by_fs_name(fstype);
2070 if (lower_boundary != UINT64_MAX) {
2071 assert(GPT_LUKS2_OVERHEAD < UINT64_MAX - lower_boundary);
2072 lower_boundary += GPT_LUKS2_OVERHEAD;
2073 }
2074 if (lower_boundary == UINT64_MAX || lower_boundary < USER_DISK_SIZE_MIN)
2075 lower_boundary = USER_DISK_SIZE_MIN;
2076
2077 if (*ret < lower_boundary)
2078 *ret = lower_boundary;
2079
2080 return 0;
2081 }
2082
2083 static int home_truncate(
2084 UserRecord *h,
2085 int fd,
2086 uint64_t size) {
2087
2088 bool trunc;
2089 int r;
2090
2091 assert(h);
2092 assert(fd >= 0);
2093
2094 trunc = user_record_luks_discard(h);
2095 if (!trunc) {
2096 r = fallocate(fd, 0, 0, size);
2097 if (r < 0 && ERRNO_IS_NOT_SUPPORTED(errno)) {
2098 /* Some file systems do not support fallocate(), let's gracefully degrade
2099 * (ZFS, reiserfs, …) and fall back to truncation */
2100 log_notice_errno(errno, "Backing file system does not support fallocate(), falling back to ftruncate(), i.e. implicitly using non-discard mode.");
2101 trunc = true;
2102 }
2103 }
2104
2105 if (trunc)
2106 r = ftruncate(fd, size);
2107
2108 if (r < 0) {
2109 if (ERRNO_IS_DISK_SPACE(errno)) {
2110 log_debug_errno(errno, "Not enough disk space to allocate home of size %s.", FORMAT_BYTES(size));
2111 return -ENOSPC; /* make recognizable */
2112 }
2113
2114 return log_error_errno(errno, "Failed to truncate home image: %m");
2115 }
2116
2117 return !trunc; /* Return == 0 if we managed to truncate, > 0 if we managed to allocate */
2118 }
2119
2120 int home_create_luks(
2121 UserRecord *h,
2122 HomeSetup *setup,
2123 const PasswordCache *cache,
2124 char **effective_passwords,
2125 UserRecord **ret_home) {
2126
2127 _cleanup_free_ char *subdir = NULL, *disk_uuid_path = NULL;
2128 uint64_t encrypted_size,
2129 host_size = 0, partition_offset = 0, partition_size = 0; /* Unnecessary initialization to appease gcc */
2130 _cleanup_(user_record_unrefp) UserRecord *new_home = NULL;
2131 sd_id128_t partition_uuid, fs_uuid, luks_uuid, disk_uuid;
2132 _cleanup_close_ int mount_fd = -EBADF;
2133 const char *fstype, *ip;
2134 struct statfs sfs;
2135 int r;
2136 _cleanup_strv_free_ char **extra_mkfs_options = NULL;
2137
2138 assert(h);
2139 assert(h->storage < 0 || h->storage == USER_LUKS);
2140 assert(setup);
2141 assert(!setup->temporary_image_path);
2142 assert(setup->image_fd < 0);
2143 assert(ret_home);
2144
2145 r = dlopen_cryptsetup();
2146 if (r < 0)
2147 return r;
2148
2149 assert_se(ip = user_record_image_path(h));
2150
2151 fstype = user_record_file_system_type(h);
2152 if (!supported_fstype(fstype))
2153 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "Unsupported file system type: %s", fstype);
2154
2155 r = mkfs_exists(fstype);
2156 if (r < 0)
2157 return log_error_errno(r, "Failed to check if mkfs binary for %s exists: %m", fstype);
2158 if (r == 0) {
2159 if (h->file_system_type || streq(fstype, "ext4") || !supported_fstype("ext4"))
2160 return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "mkfs binary for file system type %s does not exist.", fstype);
2161
2162 /* If the record does not explicitly declare a file system to use, and the compiled-in
2163 * default does not actually exist, than do an automatic fallback onto ext4, as the baseline
2164 * fs of Linux. We won't search for a working fs type here beyond ext4, i.e. nothing fancier
2165 * than a single, conservative fallback to baseline. This should be useful in minimal
2166 * environments where mkfs.btrfs or so are not made available, but mkfs.ext4 as Linux' most
2167 * boring, most basic fs is. */
2168 log_info("Formatting tool for compiled-in default file system %s not available, falling back to ext4 instead.", fstype);
2169 fstype = "ext4";
2170 }
2171
2172 if (sd_id128_is_null(h->partition_uuid)) {
2173 r = sd_id128_randomize(&partition_uuid);
2174 if (r < 0)
2175 return log_error_errno(r, "Failed to acquire partition UUID: %m");
2176 } else
2177 partition_uuid = h->partition_uuid;
2178
2179 if (sd_id128_is_null(h->luks_uuid)) {
2180 r = sd_id128_randomize(&luks_uuid);
2181 if (r < 0)
2182 return log_error_errno(r, "Failed to acquire LUKS UUID: %m");
2183 } else
2184 luks_uuid = h->luks_uuid;
2185
2186 if (sd_id128_is_null(h->file_system_uuid)) {
2187 r = sd_id128_randomize(&fs_uuid);
2188 if (r < 0)
2189 return log_error_errno(r, "Failed to acquire file system UUID: %m");
2190 } else
2191 fs_uuid = h->file_system_uuid;
2192
2193 r = make_dm_names(h, setup);
2194 if (r < 0)
2195 return r;
2196
2197 r = access(setup->dm_node, F_OK);
2198 if (r < 0) {
2199 if (errno != ENOENT)
2200 return log_error_errno(errno, "Failed to determine whether %s exists: %m", setup->dm_node);
2201 } else
2202 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Device mapper device %s already exists, refusing.", setup->dm_node);
2203
2204 if (path_startswith(ip, "/dev/")) {
2205 _cleanup_free_ char *sysfs = NULL;
2206 uint64_t block_device_size;
2207 struct stat st;
2208
2209 /* Let's place the home directory on a real device, i.e. a USB stick or such */
2210
2211 setup->image_fd = open_image_file(h, ip, &st);
2212 if (setup->image_fd < 0)
2213 return setup->image_fd;
2214
2215 if (!S_ISBLK(st.st_mode))
2216 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK), "Device is not a block device, refusing.");
2217
2218 if (asprintf(&sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/partition", DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
2219 return log_oom();
2220 if (access(sysfs, F_OK) < 0) {
2221 if (errno != ENOENT)
2222 return log_error_errno(errno, "Failed to check whether %s exists: %m", sysfs);
2223 } else
2224 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK), "Operating on partitions is currently not supported, sorry. Please specify a top-level block device.");
2225
2226 if (flock(setup->image_fd, LOCK_EX) < 0) /* make sure udev doesn't read from it while we operate on the device */
2227 return log_error_errno(errno, "Failed to lock block device %s: %m", ip);
2228
2229 r = blockdev_get_device_size(setup->image_fd, &block_device_size);
2230 if (r < 0)
2231 return log_error_errno(r, "Failed to read block device size: %m");
2232
2233 if (h->disk_size == UINT64_MAX) {
2234
2235 /* If a relative disk size is requested, apply it relative to the block device size */
2236 if (h->disk_size_relative < UINT32_MAX)
2237 host_size = CLAMP(DISK_SIZE_ROUND_DOWN(block_device_size * h->disk_size_relative / UINT32_MAX),
2238 USER_DISK_SIZE_MIN, USER_DISK_SIZE_MAX);
2239 else
2240 host_size = block_device_size; /* Otherwise, take the full device */
2241
2242 } else if (h->disk_size > block_device_size)
2243 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE), "Selected disk size larger than backing block device, refusing.");
2244 else
2245 host_size = DISK_SIZE_ROUND_DOWN(h->disk_size);
2246
2247 if (!supported_fs_size(fstype, LESS_BY(host_size, GPT_LUKS2_OVERHEAD)))
2248 return log_error_errno(SYNTHETIC_ERRNO(ERANGE),
2249 "Selected file system size too small for %s.", fstype);
2250
2251 /* After creation we should reference this partition by its UUID instead of the block
2252 * device. That's preferable since the user might have specified a device node such as
2253 * /dev/sdb to us, which might look very different when replugged. */
2254 if (asprintf(&disk_uuid_path, "/dev/disk/by-uuid/" SD_ID128_UUID_FORMAT_STR, SD_ID128_FORMAT_VAL(luks_uuid)) < 0)
2255 return log_oom();
2256
2257 if (user_record_luks_discard(h) || user_record_luks_offline_discard(h)) {
2258 /* If we want online or offline discard, discard once before we start using things. */
2259
2260 if (ioctl(setup->image_fd, BLKDISCARD, (uint64_t[]) { 0, block_device_size }) < 0)
2261 log_full_errno(errno == EOPNOTSUPP ? LOG_DEBUG : LOG_WARNING, errno,
2262 "Failed to issue full-device BLKDISCARD on device, ignoring: %m");
2263 else
2264 log_info("Full device discard completed.");
2265 }
2266 } else {
2267 _cleanup_free_ char *t = NULL;
2268
2269 r = mkdir_parents(ip, 0755);
2270 if (r < 0)
2271 return log_error_errno(r, "Failed to create parent directory of %s: %m", ip);
2272
2273 r = tempfn_random(ip, "homework", &t);
2274 if (r < 0)
2275 return log_error_errno(r, "Failed to derive temporary file name for %s: %m", ip);
2276
2277 setup->image_fd = open(t, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
2278 if (setup->image_fd < 0)
2279 return log_error_errno(errno, "Failed to create home image %s: %m", t);
2280
2281 setup->temporary_image_path = TAKE_PTR(t);
2282
2283 r = chattr_full(setup->image_fd, NULL, FS_NOCOW_FL|FS_NOCOMP_FL, FS_NOCOW_FL|FS_NOCOMP_FL, NULL, NULL, CHATTR_FALLBACK_BITWISE);
2284 if (r < 0 && r != -ENOANO) /* ENOANO → some bits didn't work; which we skip logging about because chattr_full() already debug logs about those flags */
2285 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
2286 "Failed to set file attributes on %s, ignoring: %m", setup->temporary_image_path);
2287
2288 r = calculate_initial_image_size(h, setup->image_fd, fstype, &host_size);
2289 if (r < 0)
2290 return r;
2291
2292 r = resize_image_loop(h, setup, 0, host_size, &host_size);
2293 if (r < 0)
2294 return r;
2295
2296 log_info("Allocating image file completed.");
2297 }
2298
2299 r = make_partition_table(
2300 setup->image_fd,
2301 user_record_luks_sector_size(h),
2302 user_record_user_name_and_realm(h),
2303 partition_uuid,
2304 &partition_offset,
2305 &partition_size,
2306 &disk_uuid);
2307 if (r < 0)
2308 return r;
2309
2310 log_info("Writing of partition table completed.");
2311
2312 r = loop_device_make(
2313 setup->image_fd,
2314 O_RDWR,
2315 partition_offset,
2316 partition_size,
2317 user_record_luks_sector_size(h),
2318 0,
2319 LOCK_EX,
2320 &setup->loop);
2321 if (r < 0) {
2322 if (r == -ENOENT) { /* this means /dev/loop-control doesn't exist, i.e. we are in a container
2323 * or similar and loopback bock devices are not available, return a
2324 * recognizable error in this case. */
2325 log_error_errno(r, "Loopback block device support is not available on this system.");
2326 return -ENOLINK; /* Make recognizable */
2327 }
2328
2329 return log_error_errno(r, "Failed to set up loopback device for %s: %m", setup->temporary_image_path);
2330 }
2331
2332 log_info("Setting up loopback device %s completed.", setup->loop->node ?: ip);
2333
2334 r = luks_format(setup->loop->node,
2335 setup->dm_name,
2336 luks_uuid,
2337 user_record_user_name_and_realm(h),
2338 cache,
2339 effective_passwords,
2340 user_record_luks_discard(h) || user_record_luks_offline_discard(h),
2341 h,
2342 &setup->crypt_device);
2343 if (r < 0)
2344 return r;
2345
2346 setup->undo_dm = true;
2347
2348 r = block_get_size_by_path(setup->dm_node, &encrypted_size);
2349 if (r < 0)
2350 return log_error_errno(r, "Failed to get encrypted block device size: %m");
2351
2352 log_info("Setting up LUKS device %s completed.", setup->dm_node);
2353
2354 r = mkfs_options_from_env("HOME", fstype, &extra_mkfs_options);
2355 if (r < 0)
2356 return log_error_errno(r, "Failed to determine mkfs command line options for '%s': %m", fstype);
2357
2358 r = make_filesystem(setup->dm_node,
2359 fstype,
2360 user_record_user_name_and_realm(h),
2361 /* root = */ NULL,
2362 fs_uuid,
2363 user_record_luks_discard(h),
2364 /* quiet = */ true,
2365 /* sector_size = */ 0,
2366 extra_mkfs_options);
2367 if (r < 0)
2368 return r;
2369
2370 log_info("Formatting file system completed.");
2371
2372 r = home_unshare_and_mount(setup->dm_node, fstype, user_record_luks_discard(h), user_record_mount_flags(h), h->luks_extra_mount_options);
2373 if (r < 0)
2374 return r;
2375
2376 setup->undo_mount = true;
2377
2378 subdir = path_join(HOME_RUNTIME_WORK_DIR, user_record_user_name_and_realm(h));
2379 if (!subdir)
2380 return log_oom();
2381
2382 /* Prefer using a btrfs subvolume if we can, fall back to directory otherwise */
2383 r = btrfs_subvol_make_fallback(AT_FDCWD, subdir, 0700);
2384 if (r < 0)
2385 return log_error_errno(r, "Failed to create user directory in mounted image file: %m");
2386
2387 setup->root_fd = open(subdir, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
2388 if (setup->root_fd < 0)
2389 return log_error_errno(errno, "Failed to open user directory in mounted image file: %m");
2390
2391 (void) home_shift_uid(setup->root_fd, NULL, UID_NOBODY, h->uid, &mount_fd);
2392
2393 if (mount_fd >= 0) {
2394 /* If we have established a new mount, then we can use that as new root fd to our home directory. */
2395 safe_close(setup->root_fd);
2396
2397 setup->root_fd = fd_reopen(mount_fd, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
2398 if (setup->root_fd < 0)
2399 return log_error_errno(setup->root_fd, "Unable to convert mount fd into proper directory fd: %m");
2400
2401 mount_fd = safe_close(mount_fd);
2402 }
2403
2404 r = home_populate(h, setup->root_fd);
2405 if (r < 0)
2406 return r;
2407
2408 r = home_sync_and_statfs(setup->root_fd, &sfs);
2409 if (r < 0)
2410 return r;
2411
2412 r = user_record_clone(h, USER_RECORD_LOAD_MASK_SECRET|USER_RECORD_LOG|USER_RECORD_PERMISSIVE, &new_home);
2413 if (r < 0)
2414 return log_error_errno(r, "Failed to clone record: %m");
2415
2416 r = user_record_add_binding(
2417 new_home,
2418 USER_LUKS,
2419 disk_uuid_path ?: ip,
2420 partition_uuid,
2421 luks_uuid,
2422 fs_uuid,
2423 sym_crypt_get_cipher(setup->crypt_device),
2424 sym_crypt_get_cipher_mode(setup->crypt_device),
2425 luks_volume_key_size_convert(setup->crypt_device),
2426 fstype,
2427 NULL,
2428 h->uid,
2429 (gid_t) h->uid);
2430 if (r < 0)
2431 return log_error_errno(r, "Failed to add binding to record: %m");
2432
2433 if (user_record_luks_offline_discard(h)) {
2434 r = run_fitrim(setup->root_fd);
2435 if (r < 0)
2436 return r;
2437 }
2438
2439 setup->root_fd = safe_close(setup->root_fd);
2440
2441 r = home_setup_undo_mount(setup, LOG_ERR);
2442 if (r < 0)
2443 return r;
2444
2445 r = home_setup_undo_dm(setup, LOG_ERR);
2446 if (r < 0)
2447 return r;
2448
2449 setup->loop = loop_device_unref(setup->loop);
2450
2451 if (!user_record_luks_offline_discard(h)) {
2452 r= run_fallocate(setup->image_fd, NULL /* refresh stat() data */);
2453 if (r < 0)
2454 return r;
2455 }
2456
2457 /* Sync everything to disk before we move things into place under the final name. */
2458 if (fsync(setup->image_fd) < 0)
2459 return log_error_errno(r, "Failed to synchronize image to disk: %m");
2460
2461 if (disk_uuid_path)
2462 /* Reread partition table if this is a block device */
2463 (void) ioctl(setup->image_fd, BLKRRPART, 0);
2464 else {
2465 assert(setup->temporary_image_path);
2466
2467 if (rename(setup->temporary_image_path, ip) < 0)
2468 return log_error_errno(errno, "Failed to rename image file: %m");
2469
2470 setup->temporary_image_path = mfree(setup->temporary_image_path);
2471
2472 /* If we operate on a file, sync the containing directory too. */
2473 r = fsync_directory_of_file(setup->image_fd);
2474 if (r < 0)
2475 return log_error_errno(r, "Failed to synchronize directory of image file to disk: %m");
2476
2477 log_info("Moved image file into place.");
2478 }
2479
2480 /* Let's close the image fd now. If we are operating on a real block device this will release the BSD
2481 * lock that ensures udev doesn't interfere with what we are doing */
2482 setup->image_fd = safe_close(setup->image_fd);
2483
2484 if (disk_uuid_path)
2485 (void) wait_for_devlink(disk_uuid_path);
2486
2487 log_info("Creation completed.");
2488
2489 print_size_summary(host_size, encrypted_size, &sfs);
2490
2491 log_debug("GPT + LUKS2 overhead is %" PRIu64 " (expected %" PRIu64 ")", host_size - encrypted_size, GPT_LUKS2_OVERHEAD);
2492
2493 *ret_home = TAKE_PTR(new_home);
2494 return 0;
2495 }
2496
2497 int home_get_state_luks(UserRecord *h, HomeSetup *setup) {
2498 int r;
2499
2500 assert(h);
2501 assert(setup);
2502
2503 r = make_dm_names(h, setup);
2504 if (r < 0)
2505 return r;
2506
2507 r = access(setup->dm_node, F_OK);
2508 if (r < 0 && errno != ENOENT)
2509 return log_error_errno(errno, "Failed to determine whether %s exists: %m", setup->dm_node);
2510
2511 return r >= 0;
2512 }
2513
2514 enum {
2515 CAN_RESIZE_ONLINE,
2516 CAN_RESIZE_OFFLINE,
2517 };
2518
2519 static int can_resize_fs(int fd, uint64_t old_size, uint64_t new_size) {
2520 struct statfs sfs;
2521
2522 assert(fd >= 0);
2523
2524 /* Filter out bogus requests early */
2525 if (old_size == 0 || old_size == UINT64_MAX ||
2526 new_size == 0 || new_size == UINT64_MAX)
2527 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid resize parameters.");
2528
2529 if ((old_size & 511) != 0 || (new_size & 511) != 0)
2530 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Resize parameters not multiple of 512.");
2531
2532 if (fstatfs(fd, &sfs) < 0)
2533 return log_error_errno(errno, "Failed to fstatfs() file system: %m");
2534
2535 if (is_fs_type(&sfs, BTRFS_SUPER_MAGIC)) {
2536
2537 if (new_size < BTRFS_MINIMAL_SIZE)
2538 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "New file system size too small for btrfs (needs to be 256M at least.");
2539
2540 /* btrfs can grow and shrink online */
2541
2542 } else if (is_fs_type(&sfs, XFS_SB_MAGIC)) {
2543
2544 if (new_size < XFS_MINIMAL_SIZE)
2545 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "New file system size too small for xfs (needs to be 14M at least).");
2546
2547 /* XFS can grow, but not shrink */
2548 if (new_size < old_size)
2549 return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE), "Shrinking this type of file system is not supported.");
2550
2551 } else if (is_fs_type(&sfs, EXT4_SUPER_MAGIC)) {
2552
2553 if (new_size < EXT4_MINIMAL_SIZE)
2554 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "New file system size too small for ext4 (needs to be 1M at least).");
2555
2556 /* ext4 can grow online, and shrink offline */
2557 if (new_size < old_size)
2558 return CAN_RESIZE_OFFLINE;
2559
2560 } else
2561 return log_error_errno(SYNTHETIC_ERRNO(ESOCKTNOSUPPORT), "Resizing this type of file system is not supported.");
2562
2563 return CAN_RESIZE_ONLINE;
2564 }
2565
2566 static int ext4_offline_resize_fs(
2567 HomeSetup *setup,
2568 uint64_t new_size,
2569 bool discard,
2570 unsigned long flags,
2571 const char *extra_mount_options) {
2572
2573 _cleanup_free_ char *size_str = NULL;
2574 bool re_open = false, re_mount = false;
2575 pid_t resize_pid, fsck_pid;
2576 int r, exit_status;
2577
2578 assert(setup);
2579 assert(setup->dm_node);
2580
2581 /* First, unmount the file system */
2582 if (setup->root_fd >= 0) {
2583 setup->root_fd = safe_close(setup->root_fd);
2584 re_open = true;
2585 }
2586
2587 if (setup->undo_mount) {
2588 r = home_setup_undo_mount(setup, LOG_ERR);
2589 if (r < 0)
2590 return r;
2591
2592 re_mount = true;
2593 }
2594
2595 log_info("Temporary unmounting of file system completed.");
2596
2597 /* resize2fs requires that the file system is force checked first, do so. */
2598 r = safe_fork("(e2fsck)",
2599 FORK_RESET_SIGNALS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_STDOUT_TO_STDERR|FORK_CLOSE_ALL_FDS,
2600 &fsck_pid);
2601 if (r < 0)
2602 return r;
2603 if (r == 0) {
2604 /* Child */
2605 execlp("e2fsck" ,"e2fsck", "-fp", setup->dm_node, NULL);
2606 log_open();
2607 log_error_errno(errno, "Failed to execute e2fsck: %m");
2608 _exit(EXIT_FAILURE);
2609 }
2610
2611 exit_status = wait_for_terminate_and_check("e2fsck", fsck_pid, WAIT_LOG_ABNORMAL);
2612 if (exit_status < 0)
2613 return exit_status;
2614 if ((exit_status & ~FSCK_ERROR_CORRECTED) != 0) {
2615 log_warning("e2fsck failed with exit status %i.", exit_status);
2616
2617 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
2618 return log_error_errno(SYNTHETIC_ERRNO(EIO), "File system is corrupted, refusing.");
2619
2620 log_warning("Ignoring fsck error.");
2621 }
2622
2623 log_info("Forced file system check completed.");
2624
2625 /* We use 512 sectors here, because resize2fs doesn't do byte sizes */
2626 if (asprintf(&size_str, "%" PRIu64 "s", new_size / 512) < 0)
2627 return log_oom();
2628
2629 /* Resize the thing */
2630 r = safe_fork("(e2resize)",
2631 FORK_RESET_SIGNALS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_WAIT|FORK_STDOUT_TO_STDERR|FORK_CLOSE_ALL_FDS,
2632 &resize_pid);
2633 if (r < 0)
2634 return r;
2635 if (r == 0) {
2636 /* Child */
2637 execlp("resize2fs" ,"resize2fs", setup->dm_node, size_str, NULL);
2638 log_open();
2639 log_error_errno(errno, "Failed to execute resize2fs: %m");
2640 _exit(EXIT_FAILURE);
2641 }
2642
2643 log_info("Offline file system resize completed.");
2644
2645 /* Re-establish mounts and reopen the directory */
2646 if (re_mount) {
2647 r = home_mount_node(setup->dm_node, "ext4", discard, flags, extra_mount_options);
2648 if (r < 0)
2649 return r;
2650
2651 setup->undo_mount = true;
2652 }
2653
2654 if (re_open) {
2655 setup->root_fd = open(HOME_RUNTIME_WORK_DIR, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
2656 if (setup->root_fd < 0)
2657 return log_error_errno(errno, "Failed to reopen file system: %m");
2658 }
2659
2660 log_info("File system mounted again.");
2661
2662 return 0;
2663 }
2664
2665 static int prepare_resize_partition(
2666 int fd,
2667 uint64_t partition_offset,
2668 uint64_t old_partition_size,
2669 sd_id128_t *ret_disk_uuid,
2670 struct fdisk_table **ret_table,
2671 struct fdisk_partition **ret_partition) {
2672
2673 _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
2674 _cleanup_(fdisk_unref_tablep) struct fdisk_table *t = NULL;
2675 _cleanup_free_ char *disk_uuid_as_string = NULL;
2676 struct fdisk_partition *found = NULL;
2677 sd_id128_t disk_uuid;
2678 size_t n_partitions;
2679 int r;
2680
2681 assert(fd >= 0);
2682 assert(ret_disk_uuid);
2683 assert(ret_table);
2684
2685 assert((partition_offset & 511) == 0);
2686 assert((old_partition_size & 511) == 0);
2687 assert(UINT64_MAX - old_partition_size >= partition_offset);
2688
2689 if (partition_offset == 0) {
2690 /* If the offset is at the beginning we assume no partition table, let's exit early. */
2691 log_debug("Not rewriting partition table, operating on naked device.");
2692 *ret_disk_uuid = SD_ID128_NULL;
2693 *ret_table = NULL;
2694 *ret_partition = NULL;
2695 return 0;
2696 }
2697
2698 r = fdisk_new_context_at(fd, /* path= */ NULL, /* read_only= */ false, UINT32_MAX, &c);
2699 if (r < 0)
2700 return log_error_errno(r, "Failed to open device: %m");
2701
2702 if (!fdisk_is_labeltype(c, FDISK_DISKLABEL_GPT))
2703 return log_error_errno(SYNTHETIC_ERRNO(ENOMEDIUM), "Disk has no GPT partition table.");
2704
2705 r = fdisk_get_disklabel_id(c, &disk_uuid_as_string);
2706 if (r < 0)
2707 return log_error_errno(r, "Failed to acquire disk UUID: %m");
2708
2709 r = sd_id128_from_string(disk_uuid_as_string, &disk_uuid);
2710 if (r < 0)
2711 return log_error_errno(r, "Failed parse disk UUID: %m");
2712
2713 r = fdisk_get_partitions(c, &t);
2714 if (r < 0)
2715 return log_error_errno(r, "Failed to acquire partition table: %m");
2716
2717 n_partitions = fdisk_table_get_nents(t);
2718 for (size_t i = 0; i < n_partitions; i++) {
2719 struct fdisk_partition *p;
2720
2721 p = fdisk_table_get_partition(t, i);
2722 if (!p)
2723 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata: %m");
2724
2725 if (fdisk_partition_is_used(p) <= 0)
2726 continue;
2727 if (fdisk_partition_has_start(p) <= 0 || fdisk_partition_has_size(p) <= 0 || fdisk_partition_has_end(p) <= 0)
2728 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Found partition without a size.");
2729
2730 if (fdisk_partition_get_start(p) == partition_offset / 512U &&
2731 fdisk_partition_get_size(p) == old_partition_size / 512U) {
2732
2733 if (found)
2734 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ), "Partition found twice, refusing.");
2735
2736 found = p;
2737 } else if (fdisk_partition_get_end(p) > partition_offset / 512U)
2738 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Can't extend, not last partition in image.");
2739 }
2740
2741 if (!found)
2742 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to find matching partition to resize.");
2743
2744 *ret_disk_uuid = disk_uuid;
2745 *ret_table = TAKE_PTR(t);
2746 *ret_partition = found;
2747
2748 return 1;
2749 }
2750
2751 static int get_maximum_partition_size(
2752 int fd,
2753 struct fdisk_partition *p,
2754 uint64_t *ret_maximum_partition_size) {
2755
2756 _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
2757 uint64_t start_lba, start, last_lba, end;
2758 int r;
2759
2760 assert(fd >= 0);
2761 assert(p);
2762 assert(ret_maximum_partition_size);
2763
2764 r = fdisk_new_context_at(fd, /* path= */ NULL, /* read_only= */ true, /* sector_size= */ UINT32_MAX, &c);
2765 if (r < 0)
2766 return log_error_errno(r, "Failed to create fdisk context: %m");
2767
2768 start_lba = fdisk_partition_get_start(p);
2769 assert(start_lba <= UINT64_MAX/512);
2770 start = start_lba * 512;
2771
2772 last_lba = fdisk_get_last_lba(c); /* One sector before boundary where usable space ends */
2773 assert(last_lba < UINT64_MAX/512);
2774 end = DISK_SIZE_ROUND_DOWN((last_lba + 1) * 512); /* Round down to multiple of 4K */
2775
2776 if (start > end)
2777 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Last LBA is before partition start.");
2778
2779 *ret_maximum_partition_size = DISK_SIZE_ROUND_DOWN(end - start);
2780
2781 return 1;
2782 }
2783
2784 static int ask_cb(struct fdisk_context *c, struct fdisk_ask *ask, void *userdata) {
2785 char *result;
2786
2787 assert(c);
2788
2789 switch (fdisk_ask_get_type(ask)) {
2790
2791 case FDISK_ASKTYPE_STRING:
2792 result = new(char, 37);
2793 if (!result)
2794 return log_oom();
2795
2796 fdisk_ask_string_set_result(ask, sd_id128_to_uuid_string(*(sd_id128_t*) userdata, result));
2797 break;
2798
2799 default:
2800 log_debug("Unexpected question from libfdisk, ignoring.");
2801 }
2802
2803 return 0;
2804 }
2805
2806 static int apply_resize_partition(
2807 int fd,
2808 sd_id128_t disk_uuids,
2809 struct fdisk_table *t,
2810 struct fdisk_partition *p,
2811 size_t new_partition_size) {
2812
2813 _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
2814 _cleanup_free_ void *two_zero_lbas = NULL;
2815 uint32_t ssz;
2816 ssize_t n;
2817 int r;
2818
2819 assert(fd >= 0);
2820 assert(!t == !p);
2821
2822 if (!t) /* no partition table to apply, exit early */
2823 return 0;
2824
2825 assert(p);
2826
2827 /* Before writing our partition patch the final size in */
2828 r = fdisk_partition_size_explicit(p, 1);
2829 if (r < 0)
2830 return log_error_errno(r, "Failed to enable explicit partition size: %m");
2831
2832 r = fdisk_partition_set_size(p, new_partition_size / 512U);
2833 if (r < 0)
2834 return log_error_errno(r, "Failed to change partition size: %m");
2835
2836 r = probe_sector_size(fd, &ssz);
2837 if (r < 0)
2838 return log_error_errno(r, "Failed to determine current sector size: %m");
2839
2840 two_zero_lbas = malloc0(ssz * 2);
2841 if (!two_zero_lbas)
2842 return log_oom();
2843
2844 /* libfdisk appears to get confused by the existing PMBR. Let's explicitly flush it out. */
2845 n = pwrite(fd, two_zero_lbas, ssz * 2, 0);
2846 if (n < 0)
2847 return log_error_errno(errno, "Failed to wipe partition table: %m");
2848 if ((size_t) n != ssz * 2)
2849 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while wiping partition table.");
2850
2851 r = fdisk_new_context_at(fd, /* path= */ NULL, /* read_only= */ false, ssz, &c);
2852 if (r < 0)
2853 return log_error_errno(r, "Failed to open device: %m");
2854
2855 r = fdisk_create_disklabel(c, "gpt");
2856 if (r < 0)
2857 return log_error_errno(r, "Failed to create GPT disk label: %m");
2858
2859 r = fdisk_apply_table(c, t);
2860 if (r < 0)
2861 return log_error_errno(r, "Failed to apply partition table: %m");
2862
2863 r = fdisk_set_ask(c, ask_cb, &disk_uuids);
2864 if (r < 0)
2865 return log_error_errno(r, "Failed to set libfdisk query function: %m");
2866
2867 r = fdisk_set_disklabel_id(c);
2868 if (r < 0)
2869 return log_error_errno(r, "Failed to change disklabel ID: %m");
2870
2871 r = fdisk_write_disklabel(c);
2872 if (r < 0)
2873 return log_error_errno(r, "Failed to write disk label: %m");
2874
2875 return 1;
2876 }
2877
2878 /* Always keep at least 16M free, so that we can safely log in and update the user record while doing so */
2879 #define HOME_MIN_FREE (16U*1024U*1024U)
2880
2881 static int get_smallest_fs_size(int fd, uint64_t *ret) {
2882 uint64_t minsz, needed;
2883 struct statfs sfs;
2884
2885 assert(fd >= 0);
2886 assert(ret);
2887
2888 /* Determines the minimal disk size we might be able to shrink the file system referenced by the fd to. */
2889
2890 if (syncfs(fd) < 0) /* let's sync before we query the size, so that the values returned are accurate */
2891 return log_error_errno(errno, "Failed to synchronize home file system: %m");
2892
2893 if (fstatfs(fd, &sfs) < 0)
2894 return log_error_errno(errno, "Failed to statfs() home file system: %m");
2895
2896 /* Let's determine the minimal file system size of the used fstype */
2897 minsz = minimal_size_by_fs_magic(sfs.f_type);
2898 if (minsz == UINT64_MAX)
2899 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Don't know minimum file system size of file system type '%s' of home directory.", fs_type_to_string(sfs.f_type));
2900
2901 if (minsz < USER_DISK_SIZE_MIN)
2902 minsz = USER_DISK_SIZE_MIN;
2903
2904 if (sfs.f_bfree > sfs.f_blocks)
2905 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Detected amount of free blocks is greater than the total amount of file system blocks. Refusing.");
2906
2907 /* Calculate how much disk space is currently in use. */
2908 needed = sfs.f_blocks - sfs.f_bfree;
2909 if (needed > UINT64_MAX / sfs.f_bsize)
2910 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "File system size out of range.");
2911
2912 needed *= sfs.f_bsize;
2913
2914 /* Add some safety margin of free space we'll always keep */
2915 if (needed > UINT64_MAX - HOME_MIN_FREE) /* Check for overflow */
2916 needed = UINT64_MAX;
2917 else
2918 needed += HOME_MIN_FREE;
2919
2920 *ret = DISK_SIZE_ROUND_UP(MAX(needed, minsz));
2921 return 0;
2922 }
2923
2924 static int get_largest_image_size(int fd, const struct stat *st, uint64_t *ret) {
2925 uint64_t used, avail, sum;
2926 struct statfs sfs;
2927 int r;
2928
2929 assert(fd >= 0);
2930 assert(st);
2931 assert(ret);
2932
2933 /* Determines the maximum file size we might be able to grow the image file referenced by the fd to. */
2934
2935 r = stat_verify_regular(st);
2936 if (r < 0)
2937 return log_error_errno(r, "Image file is not a regular file, refusing: %m");
2938
2939 if (syncfs(fd) < 0)
2940 return log_error_errno(errno, "Failed to synchronize file system backing image file: %m");
2941
2942 if (fstatfs(fd, &sfs) < 0)
2943 return log_error_errno(errno, "Failed to statfs() image file: %m");
2944
2945 used = (uint64_t) st->st_blocks * 512;
2946 avail = (uint64_t) sfs.f_bsize * sfs.f_bavail;
2947
2948 if (avail > UINT64_MAX - used)
2949 sum = UINT64_MAX;
2950 else
2951 sum = avail + used;
2952
2953 *ret = DISK_SIZE_ROUND_DOWN(MIN(sum, USER_DISK_SIZE_MAX));
2954 return 0;
2955 }
2956
2957 static int resize_fs_loop(
2958 UserRecord *h,
2959 HomeSetup *setup,
2960 int resize_type,
2961 uint64_t old_fs_size,
2962 uint64_t new_fs_size,
2963 uint64_t *ret_fs_size) {
2964
2965 uint64_t current_fs_size;
2966 unsigned n_iterations = 0;
2967 int r;
2968
2969 assert(h);
2970 assert(setup);
2971 assert(setup->root_fd >= 0);
2972
2973 /* A bisection loop trying to find the closest size to what the user asked for. (Well, we bisect like
2974 * this only when we *shrink* the fs — if we grow the fs there's no need to bisect.) */
2975
2976 current_fs_size = old_fs_size;
2977 for (uint64_t lower_boundary = new_fs_size, upper_boundary = old_fs_size, try_fs_size = new_fs_size;;) {
2978 bool worked;
2979
2980 n_iterations++;
2981
2982 /* Now resize the file system */
2983 if (resize_type == CAN_RESIZE_ONLINE) {
2984 r = resize_fs(setup->root_fd, try_fs_size, NULL);
2985 if (r < 0) {
2986 if (!ERRNO_IS_DISK_SPACE(r) || new_fs_size > old_fs_size) /* Not a disk space issue? Not trying to shrink? */
2987 return log_error_errno(r, "Failed to resize file system: %m");
2988
2989 log_debug_errno(r, "Shrinking from %s to %s didn't work, not enough space for contained data.", FORMAT_BYTES(current_fs_size), FORMAT_BYTES(try_fs_size));
2990 worked = false;
2991 } else {
2992 log_debug("Successfully resized from %s to %s.", FORMAT_BYTES(current_fs_size), FORMAT_BYTES(try_fs_size));
2993 current_fs_size = try_fs_size;
2994 worked = true;
2995 }
2996
2997 /* If we hit a disk space issue and are shrinking the fs, then maybe it helps to
2998 * increase the image size. */
2999 } else {
3000 r = ext4_offline_resize_fs(setup, try_fs_size, user_record_luks_discard(h), user_record_mount_flags(h), h->luks_extra_mount_options);
3001 if (r < 0)
3002 return r;
3003
3004 /* For now, when we fail to shrink an ext4 image we'll not try again via the
3005 * bisection logic. We might add that later, but given this involves shelling out
3006 * multiple programs, it's a bit too cumbersome for my taste. */
3007
3008 worked = true;
3009 current_fs_size = try_fs_size;
3010 }
3011
3012 if (new_fs_size > old_fs_size) /* If we are growing we are done after one iteration */
3013 break;
3014
3015 /* If we are shrinking then let's adjust our bisection boundaries and try again. */
3016 if (worked)
3017 upper_boundary = MIN(upper_boundary, try_fs_size);
3018 else
3019 lower_boundary = MAX(lower_boundary, try_fs_size);
3020
3021 /* OK, this attempt to shrink didn't work. Let's try between the old size and what worked. */
3022 if (lower_boundary >= upper_boundary) {
3023 log_debug("Image can't be shrunk further (range to try is empty).");
3024 break;
3025 }
3026
3027 /* Let's find a new value to try half-way between the lower boundary and the upper boundary
3028 * to try now. */
3029 try_fs_size = DISK_SIZE_ROUND_DOWN(lower_boundary + (upper_boundary - lower_boundary) / 2);
3030 if (try_fs_size <= lower_boundary || try_fs_size >= upper_boundary) {
3031 log_debug("Image can't be shrunk further (remaining range to try too small).");
3032 break;
3033 }
3034 }
3035
3036 log_debug("Bisection loop completed after %u iterations.", n_iterations);
3037
3038 if (ret_fs_size)
3039 *ret_fs_size = current_fs_size;
3040
3041 return 0;
3042 }
3043
3044 static int resize_image_loop(
3045 UserRecord *h,
3046 HomeSetup *setup,
3047 uint64_t old_image_size,
3048 uint64_t new_image_size,
3049 uint64_t *ret_image_size) {
3050
3051 uint64_t current_image_size;
3052 unsigned n_iterations = 0;
3053 int r;
3054
3055 assert(h);
3056 assert(setup);
3057 assert(setup->image_fd >= 0);
3058
3059 /* A bisection loop trying to find the closest size to what the user asked for. (Well, we bisect like
3060 * this only when we *grow* the image — if we shrink the image then there's no need to bisect.) */
3061
3062 current_image_size = old_image_size;
3063 for (uint64_t lower_boundary = old_image_size, upper_boundary = new_image_size, try_image_size = new_image_size;;) {
3064 bool worked;
3065
3066 n_iterations++;
3067
3068 r = home_truncate(h, setup->image_fd, try_image_size);
3069 if (r < 0) {
3070 if (!ERRNO_IS_DISK_SPACE(r) || new_image_size < old_image_size) /* Not a disk space issue? Not trying to grow? */
3071 return r;
3072
3073 log_debug_errno(r, "Growing from %s to %s didn't work, not enough space on backing disk.", FORMAT_BYTES(current_image_size), FORMAT_BYTES(try_image_size));
3074 worked = false;
3075 } else if (r > 0) { /* Success: allocation worked */
3076 log_debug("Resizing from %s to %s via allocation worked successfully.", FORMAT_BYTES(current_image_size), FORMAT_BYTES(try_image_size));
3077 current_image_size = try_image_size;
3078 worked = true;
3079 } else { /* Success, but through truncation, not allocation. */
3080 log_debug("Resizing from %s to %s via truncation worked successfully.", FORMAT_BYTES(old_image_size), FORMAT_BYTES(try_image_size));
3081 current_image_size = try_image_size;
3082 break; /* there's no point in the bisection logic if this was plain truncation and
3083 * not allocation, let's exit immediately. */
3084 }
3085
3086 if (new_image_size < old_image_size) /* If we are shrinking we are done after one iteration */
3087 break;
3088
3089 /* If we are growing then let's adjust our bisection boundaries and try again */
3090 if (worked)
3091 lower_boundary = MAX(lower_boundary, try_image_size);
3092 else
3093 upper_boundary = MIN(upper_boundary, try_image_size);
3094
3095 if (lower_boundary >= upper_boundary) {
3096 log_debug("Image can't be grown further (range to try is empty).");
3097 break;
3098 }
3099
3100 try_image_size = DISK_SIZE_ROUND_DOWN(lower_boundary + (upper_boundary - lower_boundary) / 2);
3101 if (try_image_size <= lower_boundary || try_image_size >= upper_boundary) {
3102 log_debug("Image can't be grown further (remaining range to try too small).");
3103 break;
3104 }
3105 }
3106
3107 log_debug("Bisection loop completed after %u iterations.", n_iterations);
3108
3109 if (ret_image_size)
3110 *ret_image_size = current_image_size;
3111
3112 return 0;
3113 }
3114
3115 int home_resize_luks(
3116 UserRecord *h,
3117 HomeSetupFlags flags,
3118 HomeSetup *setup,
3119 PasswordCache *cache,
3120 UserRecord **ret_home) {
3121
3122 uint64_t old_image_size, new_image_size, old_fs_size, new_fs_size, crypto_offset, crypto_offset_bytes,
3123 new_partition_size, smallest_fs_size, resized_fs_size;
3124 _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *embedded_home = NULL, *new_home = NULL;
3125 _cleanup_(fdisk_unref_tablep) struct fdisk_table *table = NULL;
3126 struct fdisk_partition *partition = NULL;
3127 _cleanup_close_ int opened_image_fd = -EBADF;
3128 _cleanup_free_ char *whole_disk = NULL;
3129 int r, resize_type, image_fd = -EBADF, reconciled = USER_RECONCILE_IDENTICAL;
3130 sd_id128_t disk_uuid;
3131 const char *ip, *ipo;
3132 struct statfs sfs;
3133 struct stat st;
3134 enum {
3135 INTENTION_DONT_KNOW = 0, /* These happen to match the return codes of CMP() */
3136 INTENTION_SHRINK = -1,
3137 INTENTION_GROW = 1,
3138 } intention = INTENTION_DONT_KNOW;
3139
3140 assert(h);
3141 assert(user_record_storage(h) == USER_LUKS);
3142 assert(setup);
3143
3144 r = dlopen_cryptsetup();
3145 if (r < 0)
3146 return r;
3147
3148 assert_se(ipo = user_record_image_path(h));
3149 ip = strdupa_safe(ipo); /* copy out since original might change later in home record object */
3150
3151 if (setup->image_fd < 0) {
3152 setup->image_fd = open_image_file(h, NULL, &st);
3153 if (setup->image_fd < 0)
3154 return setup->image_fd;
3155 } else {
3156 if (fstat(setup->image_fd, &st) < 0)
3157 return log_error_errno(errno, "Failed to stat image file %s: %m", ip);
3158 }
3159
3160 image_fd = setup->image_fd;
3161
3162 if (S_ISBLK(st.st_mode)) {
3163 dev_t parent;
3164
3165 r = block_get_whole_disk(st.st_rdev, &parent);
3166 if (r < 0)
3167 return log_error_errno(r, "Failed to acquire whole block device for %s: %m", ip);
3168 if (r > 0) {
3169 /* If we shall resize a file system on a partition device, then let's figure out the
3170 * whole disk device and operate on that instead, since we need to rewrite the
3171 * partition table to resize the partition. */
3172
3173 log_info("Operating on partition device %s, using parent device.", ip);
3174
3175 opened_image_fd = r = device_open_from_devnum(S_IFBLK, parent, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK, &whole_disk);
3176 if (r < 0)
3177 return log_error_errno(r, "Failed to open whole block device for %s: %m", ip);
3178
3179 image_fd = opened_image_fd;
3180
3181 if (fstat(image_fd, &st) < 0)
3182 return log_error_errno(errno, "Failed to stat whole block device %s: %m", whole_disk);
3183 } else
3184 log_info("Operating on whole block device %s.", ip);
3185
3186 r = blockdev_get_device_size(image_fd, &old_image_size);
3187 if (r < 0)
3188 return log_error_errno(r, "Failed to determine size of original block device: %m");
3189
3190 if (flock(image_fd, LOCK_EX) < 0) /* make sure udev doesn't read from it while we operate on the device */
3191 return log_error_errno(errno, "Failed to lock block device %s: %m", ip);
3192
3193 new_image_size = old_image_size; /* we can't resize physical block devices */
3194 } else {
3195 r = stat_verify_regular(&st);
3196 if (r < 0)
3197 return log_error_errno(r, "Image %s is not a block device nor regular file: %m", ip);
3198
3199 old_image_size = st.st_size;
3200
3201 /* Note an asymmetry here: when we operate on loopback files the specified disk size we get we
3202 * apply onto the loopback file as a whole. When we operate on block devices we instead apply
3203 * to the partition itself only. */
3204
3205 if (FLAGS_SET(flags, HOME_SETUP_RESIZE_MINIMIZE)) {
3206 new_image_size = 0;
3207 intention = INTENTION_SHRINK;
3208 } else {
3209 uint64_t new_image_size_rounded;
3210
3211 new_image_size_rounded = DISK_SIZE_ROUND_DOWN(h->disk_size);
3212
3213 if (old_image_size >= new_image_size_rounded && old_image_size <= h->disk_size) {
3214 /* If exact match, or a match after we rounded down, don't do a thing */
3215 log_info("Image size already matching, skipping operation.");
3216 return 0;
3217 }
3218
3219 new_image_size = new_image_size_rounded;
3220 intention = CMP(new_image_size, old_image_size); /* Is this a shrink */
3221 }
3222 }
3223
3224 r = home_setup_luks(
3225 h,
3226 flags,
3227 whole_disk,
3228 setup,
3229 cache,
3230 FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES) ? NULL : &header_home);
3231 if (r < 0)
3232 return r;
3233
3234 if (!FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES)) {
3235 reconciled = home_load_embedded_identity(h, setup->root_fd, header_home, USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL, cache, &embedded_home, &new_home);
3236 if (reconciled < 0)
3237 return reconciled;
3238 }
3239
3240 r = home_maybe_shift_uid(h, flags, setup);
3241 if (r < 0)
3242 return r;
3243
3244 log_info("offset = %" PRIu64 ", size = %" PRIu64 ", image = %" PRIu64, setup->partition_offset, setup->partition_size, old_image_size);
3245
3246 if ((UINT64_MAX - setup->partition_offset) < setup->partition_size ||
3247 setup->partition_offset + setup->partition_size > old_image_size)
3248 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Old partition doesn't fit in backing storage, refusing.");
3249
3250 /* Get target partition information in here for new_partition_size calculation */
3251 r = prepare_resize_partition(
3252 image_fd,
3253 setup->partition_offset,
3254 setup->partition_size,
3255 &disk_uuid,
3256 &table,
3257 &partition);
3258 if (r < 0)
3259 return r;
3260
3261 if (S_ISREG(st.st_mode)) {
3262 uint64_t partition_table_extra, largest_size;
3263
3264 partition_table_extra = old_image_size - setup->partition_size;
3265
3266 r = get_largest_image_size(setup->image_fd, &st, &largest_size);
3267 if (r < 0)
3268 return r;
3269 if (new_image_size > largest_size)
3270 new_image_size = largest_size;
3271
3272 if (new_image_size < partition_table_extra)
3273 new_image_size = partition_table_extra;
3274
3275 new_partition_size = DISK_SIZE_ROUND_DOWN(new_image_size - partition_table_extra);
3276 } else {
3277 assert(S_ISBLK(st.st_mode));
3278
3279 if (FLAGS_SET(flags, HOME_SETUP_RESIZE_MINIMIZE)) {
3280 new_partition_size = 0;
3281 intention = INTENTION_SHRINK;
3282 } else {
3283 uint64_t new_partition_size_rounded = DISK_SIZE_ROUND_DOWN(h->disk_size);
3284
3285 if (h->disk_size == UINT64_MAX && partition) {
3286 r = get_maximum_partition_size(image_fd, partition, &new_partition_size_rounded);
3287 if (r < 0)
3288 return r;
3289 }
3290
3291 if (setup->partition_size >= new_partition_size_rounded &&
3292 setup->partition_size <= h->disk_size) {
3293 log_info("Partition size already matching, skipping operation.");
3294 return 0;
3295 }
3296
3297 new_partition_size = new_partition_size_rounded;
3298 intention = CMP(new_partition_size, setup->partition_size);
3299 }
3300 }
3301
3302 if ((UINT64_MAX - setup->partition_offset) < new_partition_size ||
3303 setup->partition_offset + new_partition_size > new_image_size)
3304 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "New partition doesn't fit into backing storage, refusing.");
3305
3306 crypto_offset = sym_crypt_get_data_offset(setup->crypt_device);
3307 if (crypto_offset > UINT64_MAX/512U)
3308 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS2 data offset out of range, refusing.");
3309 crypto_offset_bytes = (uint64_t) crypto_offset * 512U;
3310 if (setup->partition_size <= crypto_offset_bytes)
3311 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Weird, old crypto payload offset doesn't actually fit in partition size?");
3312
3313 /* Make sure at least the LUKS header fit in */
3314 if (new_partition_size <= crypto_offset_bytes) {
3315 uint64_t add;
3316
3317 add = DISK_SIZE_ROUND_UP(crypto_offset_bytes) - new_partition_size;
3318 new_partition_size += add;
3319 if (S_ISREG(st.st_mode))
3320 new_image_size += add;
3321 }
3322
3323 old_fs_size = setup->partition_size - crypto_offset_bytes;
3324 new_fs_size = DISK_SIZE_ROUND_DOWN(new_partition_size - crypto_offset_bytes);
3325
3326 r = get_smallest_fs_size(setup->root_fd, &smallest_fs_size);
3327 if (r < 0)
3328 return r;
3329
3330 if (new_fs_size < smallest_fs_size) {
3331 uint64_t add;
3332
3333 add = DISK_SIZE_ROUND_UP(smallest_fs_size) - new_fs_size;
3334 new_fs_size += add;
3335 new_partition_size += add;
3336 if (S_ISREG(st.st_mode))
3337 new_image_size += add;
3338 }
3339
3340 if (new_fs_size == old_fs_size) {
3341 log_info("New file system size identical to old file system size, skipping operation.");
3342 return 0;
3343 }
3344
3345 if (FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_GROW) && new_fs_size > old_fs_size) {
3346 log_info("New file system size would be larger than old, but shrinking requested, skipping operation.");
3347 return 0;
3348 }
3349
3350 if (FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SHRINK) && new_fs_size < old_fs_size) {
3351 log_info("New file system size would be smaller than old, but growing requested, skipping operation.");
3352 return 0;
3353 }
3354
3355 if (CMP(new_fs_size, old_fs_size) != intention) {
3356 if (intention < 0)
3357 log_info("Shrink operation would enlarge file system, skipping operation.");
3358 else {
3359 assert(intention > 0);
3360 log_info("Grow operation would shrink file system, skipping operation.");
3361 }
3362 return 0;
3363 }
3364
3365 /* Before we start doing anything, let's figure out if we actually can */
3366 resize_type = can_resize_fs(setup->root_fd, old_fs_size, new_fs_size);
3367 if (resize_type < 0)
3368 return resize_type;
3369 if (resize_type == CAN_RESIZE_OFFLINE && FLAGS_SET(flags, HOME_SETUP_ALREADY_ACTIVATED))
3370 return log_error_errno(SYNTHETIC_ERRNO(ETXTBSY), "File systems of this type can only be resized offline, but is currently online.");
3371
3372 log_info("Ready to resize image size %s %s %s, partition size %s %s %s, file system size %s %s %s.",
3373 FORMAT_BYTES(old_image_size),
3374 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT),
3375 FORMAT_BYTES(new_image_size),
3376 FORMAT_BYTES(setup->partition_size),
3377 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT),
3378 FORMAT_BYTES(new_partition_size),
3379 FORMAT_BYTES(old_fs_size),
3380 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT),
3381 FORMAT_BYTES(new_fs_size));
3382
3383 if (new_fs_size > old_fs_size) { /* → Grow */
3384
3385 if (S_ISREG(st.st_mode)) {
3386 uint64_t resized_image_size;
3387
3388 /* Grow file size */
3389 r = resize_image_loop(h, setup, old_image_size, new_image_size, &resized_image_size);
3390 if (r < 0)
3391 return r;
3392
3393 if (resized_image_size == old_image_size) {
3394 log_info("Couldn't change image size.");
3395 return 0;
3396 }
3397
3398 assert(resized_image_size > old_image_size);
3399
3400 log_info("Growing of image file from %s to %s completed.", FORMAT_BYTES(old_image_size), FORMAT_BYTES(resized_image_size));
3401
3402 if (resized_image_size < new_image_size) {
3403 uint64_t sub;
3404
3405 /* If the growing we managed to do is smaller than what we wanted we need to
3406 * adjust the partition/file system sizes we are going for, too */
3407 sub = new_image_size - resized_image_size;
3408 assert(new_partition_size >= sub);
3409 new_partition_size -= sub;
3410 assert(new_fs_size >= sub);
3411 new_fs_size -= sub;
3412 }
3413
3414 new_image_size = resized_image_size;
3415 } else {
3416 assert(S_ISBLK(st.st_mode));
3417 assert(new_image_size == old_image_size);
3418 }
3419
3420 /* Make sure loopback device sees the new bigger size */
3421 r = loop_device_refresh_size(setup->loop, UINT64_MAX, new_partition_size);
3422 if (r == -ENOTTY)
3423 log_debug_errno(r, "Device is not a loopback device, not refreshing size.");
3424 else if (r < 0)
3425 return log_error_errno(r, "Failed to refresh loopback device size: %m");
3426 else
3427 log_info("Refreshing loop device size completed.");
3428
3429 r = apply_resize_partition(image_fd, disk_uuid, table, partition, new_partition_size);
3430 if (r < 0)
3431 return r;
3432 if (r > 0)
3433 log_info("Growing of partition completed.");
3434
3435 if (S_ISBLK(st.st_mode) && ioctl(image_fd, BLKRRPART, 0) < 0)
3436 log_debug_errno(errno, "BLKRRPART failed on block device, ignoring: %m");
3437
3438 /* Tell LUKS about the new bigger size too */
3439 r = sym_crypt_resize(setup->crypt_device, setup->dm_name, new_fs_size / 512U);
3440 if (r < 0)
3441 return log_error_errno(r, "Failed to grow LUKS device: %m");
3442
3443 log_info("LUKS device growing completed.");
3444 } else {
3445 /* → Shrink */
3446
3447 if (!FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES)) {
3448 r = home_store_embedded_identity(new_home, setup->root_fd, embedded_home);
3449 if (r < 0)
3450 return r;
3451
3452 r = home_reconcile_blob_dirs(new_home, setup->root_fd, reconciled);
3453 if (r < 0)
3454 return r;
3455 }
3456
3457 if (S_ISREG(st.st_mode)) {
3458 if (user_record_luks_discard(h))
3459 /* Before we shrink, let's trim the file system, so that we need less space on disk during the shrinking */
3460 (void) run_fitrim(setup->root_fd);
3461 else {
3462 /* If discard is off, let's ensure all backing blocks are allocated, so that our resize operation doesn't fail half-way */
3463 r = run_fallocate(image_fd, &st);
3464 if (r < 0)
3465 return r;
3466 }
3467 }
3468 }
3469
3470 /* Now try to resize the file system. The requested size might not always be possible, in which case
3471 * we'll try to get as close as we can get. The result is returned in 'resized_fs_size' */
3472 r = resize_fs_loop(h, setup, resize_type, old_fs_size, new_fs_size, &resized_fs_size);
3473 if (r < 0)
3474 return r;
3475
3476 if (resized_fs_size == old_fs_size) {
3477 log_info("Couldn't change file system size.");
3478 return 0;
3479 }
3480
3481 log_info("File system resizing from %s to %s completed.", FORMAT_BYTES(old_fs_size), FORMAT_BYTES(resized_fs_size));
3482
3483 if (resized_fs_size > new_fs_size) {
3484 uint64_t add;
3485
3486 /* If the shrinking we managed to do is larger than what we wanted we need to adjust the partition/image sizes. */
3487 add = resized_fs_size - new_fs_size;
3488 new_partition_size += add;
3489 if (S_ISREG(st.st_mode))
3490 new_image_size += add;
3491 }
3492
3493 new_fs_size = resized_fs_size;
3494
3495 /* Immediately sync afterwards */
3496 r = home_sync_and_statfs(setup->root_fd, NULL);
3497 if (r < 0)
3498 return r;
3499
3500 if (new_fs_size < old_fs_size) { /* → Shrink */
3501
3502 /* Shrink the LUKS device now, matching the new file system size */
3503 r = sym_crypt_resize(setup->crypt_device, setup->dm_name, new_fs_size / 512);
3504 if (r < 0)
3505 return log_error_errno(r, "Failed to shrink LUKS device: %m");
3506
3507 log_info("LUKS device shrinking completed.");
3508
3509 /* Refresh the loop devices size */
3510 r = loop_device_refresh_size(setup->loop, UINT64_MAX, new_partition_size);
3511 if (r == -ENOTTY)
3512 log_debug_errno(r, "Device is not a loopback device, not refreshing size.");
3513 else if (r < 0)
3514 return log_error_errno(r, "Failed to refresh loopback device size: %m");
3515 else
3516 log_info("Refreshing loop device size completed.");
3517
3518 if (S_ISREG(st.st_mode)) {
3519 /* Shrink the image file */
3520 if (ftruncate(image_fd, new_image_size) < 0)
3521 return log_error_errno(errno, "Failed to shrink image file %s: %m", ip);
3522
3523 log_info("Shrinking of image file completed.");
3524 } else {
3525 assert(S_ISBLK(st.st_mode));
3526 assert(new_image_size == old_image_size);
3527 }
3528
3529 r = apply_resize_partition(image_fd, disk_uuid, table, partition, new_partition_size);
3530 if (r < 0)
3531 return r;
3532 if (r > 0)
3533 log_info("Shrinking of partition completed.");
3534
3535 if (S_ISBLK(st.st_mode) && ioctl(image_fd, BLKRRPART, 0) < 0)
3536 log_debug_errno(errno, "BLKRRPART failed on block device, ignoring: %m");
3537
3538 } else { /* → Grow */
3539 if (!FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES)) {
3540 r = home_store_embedded_identity(new_home, setup->root_fd, embedded_home);
3541 if (r < 0)
3542 return r;
3543
3544 r = home_reconcile_blob_dirs(new_home, setup->root_fd, reconciled);
3545 if (r < 0)
3546 return r;
3547 }
3548 }
3549
3550 if (!FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES)) {
3551 r = home_store_header_identity_luks(new_home, setup, header_home);
3552 if (r < 0)
3553 return r;
3554
3555 r = home_extend_embedded_identity(new_home, h, setup);
3556 if (r < 0)
3557 return r;
3558 }
3559
3560 if (user_record_luks_discard(h))
3561 (void) run_fitrim(setup->root_fd);
3562
3563 r = home_sync_and_statfs(setup->root_fd, &sfs);
3564 if (r < 0)
3565 return r;
3566
3567 if (!FLAGS_SET(flags, HOME_SETUP_RESIZE_DONT_UNDO)) {
3568 r = home_setup_done(setup);
3569 if (r < 0)
3570 return r;
3571 }
3572
3573 log_info("Resizing completed.");
3574
3575 print_size_summary(new_image_size, new_fs_size, &sfs);
3576
3577 if (ret_home)
3578 *ret_home = TAKE_PTR(new_home);
3579
3580 return 0;
3581 }
3582
3583 int home_passwd_luks(
3584 UserRecord *h,
3585 HomeSetupFlags flags,
3586 HomeSetup *setup,
3587 const PasswordCache *cache, /* the passwords acquired via PKCS#11/FIDO2 security tokens */
3588 char **effective_passwords /* new passwords */) {
3589
3590 size_t volume_key_size, max_key_slots, n_effective;
3591 _cleanup_(erase_and_freep) void *volume_key = NULL;
3592 struct crypt_pbkdf_type good_pbkdf, minimal_pbkdf;
3593 const char *type;
3594 int r;
3595
3596 assert(h);
3597 assert(user_record_storage(h) == USER_LUKS);
3598 assert(setup);
3599
3600 r = dlopen_cryptsetup();
3601 if (r < 0)
3602 return r;
3603
3604 type = sym_crypt_get_type(setup->crypt_device);
3605 if (!type)
3606 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine crypto device type.");
3607
3608 r = sym_crypt_keyslot_max(type);
3609 if (r <= 0)
3610 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine number of key slots.");
3611 max_key_slots = r;
3612
3613 r = sym_crypt_get_volume_key_size(setup->crypt_device);
3614 if (r <= 0)
3615 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine volume key size.");
3616 volume_key_size = (size_t) r;
3617
3618 volume_key = malloc(volume_key_size);
3619 if (!volume_key)
3620 return log_oom();
3621
3622 r = -ENOKEY;
3623 char **list;
3624 FOREACH_ARGUMENT(list,
3625 cache ? cache->keyring_passswords : NULL,
3626 cache ? cache->pkcs11_passwords : NULL,
3627 cache ? cache->fido2_passwords : NULL,
3628 h->password) {
3629
3630 r = luks_try_passwords(h, setup->crypt_device, list, volume_key, &volume_key_size, NULL);
3631 if (r != -ENOKEY)
3632 break;
3633 }
3634 if (r == -ENOKEY)
3635 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Failed to unlock LUKS superblock with supplied passwords.");
3636 if (r < 0)
3637 return log_error_errno(r, "Failed to unlock LUKS superblock: %m");
3638
3639 n_effective = strv_length(effective_passwords);
3640
3641 build_good_pbkdf(&good_pbkdf, h);
3642 build_minimal_pbkdf(&minimal_pbkdf, h);
3643
3644 for (size_t i = 0; i < max_key_slots; i++) {
3645 r = sym_crypt_keyslot_destroy(setup->crypt_device, i);
3646 if (r < 0 && !IN_SET(r, -ENOENT, -EINVAL)) /* Returns EINVAL or ENOENT if there's no key in this slot already */
3647 return log_error_errno(r, "Failed to destroy LUKS password: %m");
3648
3649 if (i >= n_effective) {
3650 if (r >= 0)
3651 log_info("Destroyed LUKS key slot %zu.", i);
3652 continue;
3653 }
3654
3655 if (password_cache_contains(cache, effective_passwords[i])) { /* Is this a FIDO2 or PKCS#11 password? */
3656 log_debug("Using minimal PBKDF for slot %zu", i);
3657 r = sym_crypt_set_pbkdf_type(setup->crypt_device, &minimal_pbkdf);
3658 } else {
3659 log_debug("Using good PBKDF for slot %zu", i);
3660 r = sym_crypt_set_pbkdf_type(setup->crypt_device, &good_pbkdf);
3661 }
3662 if (r < 0)
3663 return log_error_errno(r, "Failed to tweak PBKDF for slot %zu: %m", i);
3664
3665 r = sym_crypt_keyslot_add_by_volume_key(
3666 setup->crypt_device,
3667 i,
3668 volume_key,
3669 volume_key_size,
3670 effective_passwords[i],
3671 strlen(effective_passwords[i]));
3672 if (r < 0)
3673 return log_error_errno(r, "Failed to set up LUKS password: %m");
3674
3675 log_info("Updated LUKS key slot %zu.", i);
3676
3677 /* If we changed the password, then make sure to update the copy in the keyring, so that
3678 * auto-rebalance continues to work. We only do this if we operate on an active home dir. */
3679 if (i == 0 && FLAGS_SET(flags, HOME_SETUP_ALREADY_ACTIVATED))
3680 upload_to_keyring(h, effective_passwords[i], NULL);
3681 }
3682
3683 return 1;
3684 }
3685
3686 int home_lock_luks(UserRecord *h, HomeSetup *setup) {
3687 const char *p;
3688 int r;
3689
3690 assert(h);
3691 assert(setup);
3692 assert(setup->root_fd < 0);
3693 assert(!setup->crypt_device);
3694
3695 r = acquire_open_luks_device(h, setup, /* graceful= */ false);
3696 if (r < 0)
3697 return r;
3698
3699 log_info("Discovered used LUKS device %s.", setup->dm_node);
3700
3701 assert_se(p = user_record_home_directory(h));
3702 r = syncfs_path(AT_FDCWD, p);
3703 if (r < 0) /* Snake oil, but let's better be safe than sorry */
3704 return log_error_errno(r, "Failed to synchronize file system %s: %m", p);
3705
3706 log_info("File system synchronized.");
3707
3708 /* Note that we don't invoke FIFREEZE here, it appears libcryptsetup/device-mapper already does that on its own for us */
3709
3710 r = sym_crypt_suspend(setup->crypt_device, setup->dm_name);
3711 if (r < 0)
3712 return log_error_errno(r, "Failed to suspend cryptsetup device: %s: %m", setup->dm_node);
3713
3714 log_info("LUKS device suspended.");
3715 return 0;
3716 }
3717
3718 static int luks_try_resume(
3719 struct crypt_device *cd,
3720 const char *dm_name,
3721 char **password) {
3722
3723 int r;
3724
3725 assert(cd);
3726 assert(dm_name);
3727
3728 STRV_FOREACH(pp, password) {
3729 r = sym_crypt_resume_by_passphrase(
3730 cd,
3731 dm_name,
3732 CRYPT_ANY_SLOT,
3733 *pp,
3734 strlen(*pp));
3735 if (r >= 0) {
3736 log_info("Resumed LUKS device %s.", dm_name);
3737 return 0;
3738 }
3739
3740 log_debug_errno(r, "Password %zu didn't work for resuming device: %m", (size_t) (pp - password));
3741 }
3742
3743 return -ENOKEY;
3744 }
3745
3746 int home_unlock_luks(UserRecord *h, HomeSetup *setup, const PasswordCache *cache) {
3747 int r;
3748
3749 assert(h);
3750 assert(setup);
3751 assert(!setup->crypt_device);
3752
3753 r = acquire_open_luks_device(h, setup, /* graceful= */ false);
3754 if (r < 0)
3755 return r;
3756
3757 log_info("Discovered used LUKS device %s.", setup->dm_node);
3758
3759 r = -ENOKEY;
3760 char **list;
3761 FOREACH_ARGUMENT(list,
3762 cache ? cache->pkcs11_passwords : NULL,
3763 cache ? cache->fido2_passwords : NULL,
3764 h->password) {
3765
3766 r = luks_try_resume(setup->crypt_device, setup->dm_name, list);
3767 if (r != -ENOKEY)
3768 break;
3769 }
3770 if (r == -ENOKEY)
3771 return log_error_errno(r, "No valid password for LUKS superblock.");
3772 if (r < 0)
3773 return log_error_errno(r, "Failed to resume LUKS superblock: %m");
3774
3775 log_info("LUKS device resumed.");
3776 return 0;
3777 }
3778
3779 static int device_is_gone(HomeSetup *setup) {
3780 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
3781 struct stat st;
3782 int r;
3783
3784 assert(setup);
3785
3786 if (!setup->dm_node)
3787 return true;
3788
3789 if (stat(setup->dm_node, &st) < 0) {
3790 if (errno != ENOENT)
3791 return log_error_errno(errno, "Failed to stat block device node %s: %m", setup->dm_node);
3792
3793 return true;
3794 }
3795
3796 r = sd_device_new_from_stat_rdev(&d, &st);
3797 if (r < 0) {
3798 if (r != -ENODEV)
3799 return log_error_errno(errno, "Failed to allocate device object from block device node %s: %m", setup->dm_node);
3800
3801 return true;
3802 }
3803
3804 return false;
3805 }
3806
3807 static int device_monitor_handler(sd_device_monitor *monitor, sd_device *device, void *userdata) {
3808 HomeSetup *setup = ASSERT_PTR(userdata);
3809 int r;
3810
3811 if (!device_for_action(device, SD_DEVICE_REMOVE))
3812 return 0;
3813
3814 /* We don't really care for the device object passed to us, we just check if the device node still
3815 * exists */
3816
3817 r = device_is_gone(setup);
3818 if (r < 0)
3819 return r;
3820 if (r > 0) /* Yay! we are done! */
3821 (void) sd_event_exit(sd_device_monitor_get_event(monitor), 0);
3822
3823 return 0;
3824 }
3825
3826 int wait_for_block_device_gone(HomeSetup *setup, usec_t timeout_usec) {
3827 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *m = NULL;
3828 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
3829 int r;
3830
3831 assert(setup);
3832
3833 /* So here's the thing: we enable "deferred deactivation" on our dm-crypt volumes. This means they
3834 * are automatically torn down once not used anymore (i.e. once unmounted). Which is great. It also
3835 * means that when we deactivate a home directory and try to tear down the volume that backs it, it
3836 * possibly is already torn down or in the process of being torn down, since we race against the
3837 * automatic tearing down. Which is fine, we handle errors from that. However, we lose the ability to
3838 * naturally wait for the tear down operation to complete: if we are not the ones who tear down the
3839 * device we are also not the ones who naturally block on that operation. Hence let's add some code
3840 * to actively wait for the device to go away, via sd-device. We'll call this whenever tearing down a
3841 * LUKS device, to ensure the device is really really gone before we proceed. Net effect: "homectl
3842 * deactivate foo && homectl activate foo" will work reliably, i.e. deactivation immediately followed
3843 * by activation will work. Also, by the time deactivation completes we can guarantee that all data
3844 * is sync'ed down to the lowest block layer as all higher levels are fully and entirely
3845 * destructed. */
3846
3847 if (!setup->dm_name)
3848 return 0;
3849
3850 assert(setup->dm_node);
3851 log_debug("Waiting until %s disappears.", setup->dm_node);
3852
3853 r = sd_event_new(&event);
3854 if (r < 0)
3855 return log_error_errno(r, "Failed to allocate event loop: %m");
3856
3857 r = sd_device_monitor_new(&m);
3858 if (r < 0)
3859 return log_error_errno(r, "Failed to allocate device monitor: %m");
3860
3861 r = sd_device_monitor_filter_add_match_subsystem_devtype(m, "block", "disk");
3862 if (r < 0)
3863 return log_error_errno(r, "Failed to configure device monitor match: %m");
3864
3865 r = sd_device_monitor_attach_event(m, event);
3866 if (r < 0)
3867 return log_error_errno(r, "Failed to attach device monitor to event loop: %m");
3868
3869 r = sd_device_monitor_start(m, device_monitor_handler, setup);
3870 if (r < 0)
3871 return log_error_errno(r, "Failed to start device monitor: %m");
3872
3873 r = device_is_gone(setup);
3874 if (r < 0)
3875 return r;
3876 if (r > 0) {
3877 log_debug("%s has already disappeared before entering wait loop.", setup->dm_node);
3878 return 0; /* gone already */
3879 }
3880
3881 if (timeout_usec != USEC_INFINITY) {
3882 r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, timeout_usec, 0, NULL, NULL);
3883 if (r < 0)
3884 return log_error_errno(r, "Failed to add timer event: %m");
3885 }
3886
3887 r = sd_event_loop(event);
3888 if (r < 0)
3889 return log_error_errno(r, "Failed to run event loop: %m");
3890
3891 r = device_is_gone(setup);
3892 if (r < 0)
3893 return r;
3894 if (r == 0)
3895 return log_error_errno(r, "Device %s still around.", setup->dm_node);
3896
3897 log_debug("Successfully waited until device %s disappeared.", setup->dm_node);
3898 return 0;
3899 }
3900
3901 int home_auto_shrink_luks(UserRecord *h, HomeSetup *setup, PasswordCache *cache) {
3902 struct statfs sfs;
3903 int r;
3904
3905 assert(h);
3906 assert(user_record_storage(h) == USER_LUKS);
3907 assert(setup);
3908 assert(setup->root_fd >= 0);
3909
3910 if (user_record_auto_resize_mode(h) != AUTO_RESIZE_SHRINK_AND_GROW)
3911 return 0;
3912
3913 if (fstatfs(setup->root_fd, &sfs) < 0)
3914 return log_error_errno(errno, "Failed to statfs home directory: %m");
3915
3916 if (!fs_can_online_shrink_and_grow(sfs.f_type)) {
3917 log_debug("Not auto-shrinking file system, since selected file system cannot do both online shrink and grow.");
3918 return 0;
3919 }
3920
3921 r = home_resize_luks(
3922 h,
3923 HOME_SETUP_ALREADY_ACTIVATED|
3924 HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES|
3925 HOME_SETUP_RESIZE_MINIMIZE|
3926 HOME_SETUP_RESIZE_DONT_GROW|
3927 HOME_SETUP_RESIZE_DONT_UNDO,
3928 setup,
3929 cache,
3930 NULL);
3931 if (r < 0)
3932 return r;
3933
3934 return 1;
3935 }