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