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