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