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