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