]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/cryptsetup/cryptsetup.c
Merge pull request #18886 from anitazha/shutdownconsole
[thirdparty/systemd.git] / src / cryptsetup / cryptsetup.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <mntent.h>
5 #include <sys/mman.h>
6 #include <sys/stat.h>
7 #include <sys/types.h>
8 #include <unistd.h>
9
10 #include "sd-device.h"
11
12 #include "alloc-util.h"
13 #include "ask-password-api.h"
14 #include "cryptsetup-fido2.h"
15 #include "cryptsetup-keyfile.h"
16 #include "cryptsetup-pkcs11.h"
17 #include "cryptsetup-tpm2.h"
18 #include "cryptsetup-util.h"
19 #include "device-util.h"
20 #include "escape.h"
21 #include "fileio.h"
22 #include "fs-util.h"
23 #include "fstab-util.h"
24 #include "hexdecoct.h"
25 #include "libfido2-util.h"
26 #include "log.h"
27 #include "main-func.h"
28 #include "memory-util.h"
29 #include "mount-util.h"
30 #include "nulstr-util.h"
31 #include "parse-util.h"
32 #include "path-util.h"
33 #include "pkcs11-util.h"
34 #include "pretty-print.h"
35 #include "random-util.h"
36 #include "string-util.h"
37 #include "strv.h"
38 #include "tpm2-util.h"
39
40 /* internal helper */
41 #define ANY_LUKS "LUKS"
42 /* as in src/cryptsetup.h */
43 #define CRYPT_SECTOR_SIZE 512
44 #define CRYPT_MAX_SECTOR_SIZE 4096
45
46 static const char *arg_type = NULL; /* ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT, CRYPT_BITLK or CRYPT_PLAIN */
47 static char *arg_cipher = NULL;
48 static unsigned arg_key_size = 0;
49 static unsigned arg_sector_size = CRYPT_SECTOR_SIZE;
50 static int arg_key_slot = CRYPT_ANY_SLOT;
51 static unsigned arg_keyfile_size = 0;
52 static uint64_t arg_keyfile_offset = 0;
53 static bool arg_keyfile_erase = false;
54 static bool arg_try_empty_password = false;
55 static char *arg_hash = NULL;
56 static char *arg_header = NULL;
57 static unsigned arg_tries = 3;
58 static bool arg_readonly = false;
59 static bool arg_verify = false;
60 static bool arg_discards = false;
61 static bool arg_same_cpu_crypt = false;
62 static bool arg_submit_from_crypt_cpus = false;
63 static bool arg_no_read_workqueue = false;
64 static bool arg_no_write_workqueue = false;
65 static bool arg_tcrypt_hidden = false;
66 static bool arg_tcrypt_system = false;
67 static bool arg_tcrypt_veracrypt = false;
68 static char **arg_tcrypt_keyfiles = NULL;
69 static uint64_t arg_offset = 0;
70 static uint64_t arg_skip = 0;
71 static usec_t arg_timeout = USEC_INFINITY;
72 static char *arg_pkcs11_uri = NULL;
73 static bool arg_pkcs11_uri_auto = false;
74 static char *arg_fido2_device = NULL;
75 static bool arg_fido2_device_auto = false;
76 static void *arg_fido2_cid = NULL;
77 static size_t arg_fido2_cid_size = 0;
78 static char *arg_fido2_rp_id = NULL;
79 static char *arg_tpm2_device = NULL;
80 static bool arg_tpm2_device_auto = false;
81 static uint32_t arg_tpm2_pcr_mask = UINT32_MAX;
82
83 STATIC_DESTRUCTOR_REGISTER(arg_cipher, freep);
84 STATIC_DESTRUCTOR_REGISTER(arg_hash, freep);
85 STATIC_DESTRUCTOR_REGISTER(arg_header, freep);
86 STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles, strv_freep);
87 STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri, freep);
88 STATIC_DESTRUCTOR_REGISTER(arg_fido2_device, freep);
89 STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid, freep);
90 STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id, freep);
91 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
92
93 /* Options Debian's crypttab knows we don't:
94
95 check=
96 checkargs=
97 noearly
98 loud
99 quiet
100 keyscript=
101 initramfs
102 */
103
104 static int parse_one_option(const char *option) {
105 const char *val;
106 int r;
107
108 assert(option);
109
110 /* Handled outside of this tool */
111 if (STR_IN_SET(option, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
112 return 0;
113
114 if (startswith(option, "keyfile-timeout="))
115 return 0;
116
117 if ((val = startswith(option, "cipher="))) {
118 r = free_and_strdup(&arg_cipher, val);
119 if (r < 0)
120 return log_oom();
121
122 } else if ((val = startswith(option, "size="))) {
123
124 r = safe_atou(val, &arg_key_size);
125 if (r < 0) {
126 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
127 return 0;
128 }
129
130 if (arg_key_size % 8) {
131 log_error("size= not a multiple of 8, ignoring.");
132 return 0;
133 }
134
135 arg_key_size /= 8;
136
137 } else if ((val = startswith(option, "sector-size="))) {
138
139 r = safe_atou(val, &arg_sector_size);
140 if (r < 0) {
141 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
142 return 0;
143 }
144
145 if (arg_sector_size % 2) {
146 log_error("sector-size= not a multiple of 2, ignoring.");
147 return 0;
148 }
149
150 if (arg_sector_size < CRYPT_SECTOR_SIZE || arg_sector_size > CRYPT_MAX_SECTOR_SIZE) {
151 log_error("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE, CRYPT_MAX_SECTOR_SIZE);
152 return 0;
153 }
154
155 } else if ((val = startswith(option, "key-slot=")) ||
156 (val = startswith(option, "keyslot="))) {
157
158 arg_type = ANY_LUKS;
159 r = safe_atoi(val, &arg_key_slot);
160 if (r < 0) {
161 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
162 return 0;
163 }
164
165 } else if ((val = startswith(option, "tcrypt-keyfile="))) {
166
167 arg_type = CRYPT_TCRYPT;
168 if (path_is_absolute(val)) {
169 if (strv_extend(&arg_tcrypt_keyfiles, val) < 0)
170 return log_oom();
171 } else
172 log_error("Key file path \"%s\" is not absolute. Ignoring.", val);
173
174 } else if ((val = startswith(option, "keyfile-size="))) {
175
176 r = safe_atou(val, &arg_keyfile_size);
177 if (r < 0) {
178 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
179 return 0;
180 }
181
182 } else if ((val = startswith(option, "keyfile-offset="))) {
183
184 r = safe_atou64(val, &arg_keyfile_offset);
185 if (r < 0) {
186 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
187 return 0;
188 }
189
190 } else if ((val = startswith(option, "keyfile-erase="))) {
191
192 r = parse_boolean(val);
193 if (r < 0) {
194 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
195 return 0;
196 }
197
198 arg_keyfile_erase = r;
199
200 } else if (streq(option, "keyfile-erase"))
201 arg_keyfile_erase = true;
202
203 else if ((val = startswith(option, "hash="))) {
204 r = free_and_strdup(&arg_hash, val);
205 if (r < 0)
206 return log_oom();
207
208 } else if ((val = startswith(option, "header="))) {
209 arg_type = ANY_LUKS;
210
211 if (!path_is_absolute(val))
212 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
213 "Header path \"%s\" is not absolute, refusing.", val);
214
215 if (arg_header)
216 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
217 "Duplicate header= option, refusing.");
218
219 arg_header = strdup(val);
220 if (!arg_header)
221 return log_oom();
222
223 } else if ((val = startswith(option, "tries="))) {
224
225 r = safe_atou(val, &arg_tries);
226 if (r < 0) {
227 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
228 return 0;
229 }
230
231 } else if (STR_IN_SET(option, "readonly", "read-only"))
232 arg_readonly = true;
233 else if (streq(option, "verify"))
234 arg_verify = true;
235 else if (STR_IN_SET(option, "allow-discards", "discard"))
236 arg_discards = true;
237 else if (streq(option, "same-cpu-crypt"))
238 arg_same_cpu_crypt = true;
239 else if (streq(option, "submit-from-crypt-cpus"))
240 arg_submit_from_crypt_cpus = true;
241 else if (streq(option, "no-read-workqueue"))
242 arg_no_read_workqueue = true;
243 else if (streq(option, "no-write-workqueue"))
244 arg_no_write_workqueue = true;
245 else if (streq(option, "luks"))
246 arg_type = ANY_LUKS;
247 /* since cryptsetup 2.3.0 (Feb 2020) */
248 #ifdef CRYPT_BITLK
249 else if (streq(option, "bitlk"))
250 arg_type = CRYPT_BITLK;
251 #endif
252 else if (streq(option, "tcrypt"))
253 arg_type = CRYPT_TCRYPT;
254 else if (STR_IN_SET(option, "tcrypt-hidden", "tcrypthidden")) {
255 arg_type = CRYPT_TCRYPT;
256 arg_tcrypt_hidden = true;
257 } else if (streq(option, "tcrypt-system")) {
258 arg_type = CRYPT_TCRYPT;
259 arg_tcrypt_system = true;
260 } else if (STR_IN_SET(option, "tcrypt-veracrypt", "veracrypt")) {
261 arg_type = CRYPT_TCRYPT;
262 arg_tcrypt_veracrypt = true;
263 } else if (STR_IN_SET(option, "plain", "swap", "tmp") ||
264 startswith(option, "tmp="))
265 arg_type = CRYPT_PLAIN;
266 else if ((val = startswith(option, "timeout="))) {
267
268 r = parse_sec_fix_0(val, &arg_timeout);
269 if (r < 0) {
270 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
271 return 0;
272 }
273
274 } else if ((val = startswith(option, "offset="))) {
275
276 r = safe_atou64(val, &arg_offset);
277 if (r < 0)
278 return log_error_errno(r, "Failed to parse %s: %m", option);
279
280 } else if ((val = startswith(option, "skip="))) {
281
282 r = safe_atou64(val, &arg_skip);
283 if (r < 0)
284 return log_error_errno(r, "Failed to parse %s: %m", option);
285
286 } else if ((val = startswith(option, "pkcs11-uri="))) {
287
288 if (streq(val, "auto")) {
289 arg_pkcs11_uri = mfree(arg_pkcs11_uri);
290 arg_pkcs11_uri_auto = true;
291 } else {
292 if (!pkcs11_uri_valid(val))
293 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing");
294
295 r = free_and_strdup(&arg_pkcs11_uri, val);
296 if (r < 0)
297 return log_oom();
298
299 arg_pkcs11_uri_auto = false;
300 }
301
302 } else if ((val = startswith(option, "fido2-device="))) {
303
304 if (streq(val, "auto")) {
305 arg_fido2_device = mfree(arg_fido2_device);
306 arg_fido2_device_auto = true;
307 } else {
308 r = free_and_strdup(&arg_fido2_device, val);
309 if (r < 0)
310 return log_oom();
311
312 arg_fido2_device_auto = false;
313 }
314
315 } else if ((val = startswith(option, "fido2-cid="))) {
316
317 if (streq(val, "auto"))
318 arg_fido2_cid = mfree(arg_fido2_cid);
319 else {
320 _cleanup_free_ void *cid = NULL;
321 size_t cid_size;
322
323 r = unbase64mem(val, SIZE_MAX, &cid, &cid_size);
324 if (r < 0)
325 return log_error_errno(r, "Failed to decode FIDO2 CID data: %m");
326
327 free(arg_fido2_cid);
328 arg_fido2_cid = TAKE_PTR(cid);
329 arg_fido2_cid_size = cid_size;
330 }
331
332 /* Turn on FIDO2 as side-effect, if not turned on yet. */
333 if (!arg_fido2_device && !arg_fido2_device_auto)
334 arg_fido2_device_auto = true;
335
336 } else if ((val = startswith(option, "fido2-rp="))) {
337
338 r = free_and_strdup(&arg_fido2_rp_id, val);
339 if (r < 0)
340 return log_oom();
341
342 } else if ((val = startswith(option, "tpm2-device="))) {
343
344 if (streq(val, "auto")) {
345 arg_tpm2_device = mfree(arg_tpm2_device);
346 arg_tpm2_device_auto = true;
347 } else {
348 r = free_and_strdup(&arg_tpm2_device, val);
349 if (r < 0)
350 return log_oom();
351
352 arg_tpm2_device_auto = false;
353 }
354
355 } else if ((val = startswith(option, "tpm2-pcrs="))) {
356
357 if (isempty(val))
358 arg_tpm2_pcr_mask = 0;
359 else {
360 uint32_t mask;
361
362 r = tpm2_parse_pcrs(val, &mask);
363 if (r < 0)
364 return r;
365
366 if (arg_tpm2_pcr_mask == UINT32_MAX)
367 arg_tpm2_pcr_mask = mask;
368 else
369 arg_tpm2_pcr_mask |= mask;
370 }
371
372 } else if ((val = startswith(option, "try-empty-password="))) {
373
374 r = parse_boolean(val);
375 if (r < 0) {
376 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
377 return 0;
378 }
379
380 arg_try_empty_password = r;
381
382 } else if (streq(option, "try-empty-password"))
383 arg_try_empty_password = true;
384
385 else if (!streq(option, "x-initrd.attach"))
386 log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
387
388 return 0;
389 }
390
391 static int parse_options(const char *options) {
392 assert(options);
393
394 for (;;) {
395 _cleanup_free_ char *word = NULL;
396 int r;
397
398 r = extract_first_word(&options, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS | EXTRACT_UNESCAPE_SEPARATORS);
399 if (r < 0)
400 return log_error_errno(r, "Failed to parse options: %m");
401 if (r == 0)
402 break;
403
404 r = parse_one_option(word);
405 if (r < 0)
406 return r;
407 }
408
409 /* sanity-check options */
410 if (arg_type && !streq(arg_type, CRYPT_PLAIN)) {
411 if (arg_offset != 0)
412 log_warning("offset= ignored with type %s", arg_type);
413 if (arg_skip != 0)
414 log_warning("skip= ignored with type %s", arg_type);
415 }
416
417 return 0;
418 }
419
420 static char* disk_description(const char *path) {
421 static const char name_fields[] =
422 "DM_NAME\0"
423 "ID_MODEL_FROM_DATABASE\0"
424 "ID_MODEL\0";
425
426 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
427 const char *i, *name;
428 struct stat st;
429 int r;
430
431 assert(path);
432
433 if (stat(path, &st) < 0)
434 return NULL;
435
436 if (!S_ISBLK(st.st_mode))
437 return NULL;
438
439 if (sd_device_new_from_stat_rdev(&device, &st) < 0)
440 return NULL;
441
442 if (sd_device_get_property_value(device, "ID_PART_ENTRY_NAME", &name) >= 0) {
443 _cleanup_free_ char *unescaped = NULL;
444
445 /* ID_PART_ENTRY_NAME uses \x style escaping, using libblkid's blkid_encode_string(). Let's
446 * reverse this here to make the string more human friendly in case people embed spaces or
447 * other weird stuff. */
448
449 r = cunescape(name, UNESCAPE_RELAX, &unescaped);
450 if (r < 0) {
451 log_debug_errno(r, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
452 return NULL;
453 }
454
455 if (!isempty(unescaped) && !string_has_cc(unescaped, NULL))
456 return TAKE_PTR(unescaped);
457 }
458
459 /* These need no unescaping. */
460 NULSTR_FOREACH(i, name_fields)
461 if (sd_device_get_property_value(device, i, &name) >= 0 &&
462 !isempty(name))
463 return strdup(name);
464
465 return NULL;
466 }
467
468 static char *disk_mount_point(const char *label) {
469 _cleanup_free_ char *device = NULL;
470 _cleanup_endmntent_ FILE *f = NULL;
471 struct mntent *m;
472
473 /* Yeah, we don't support native systemd unit files here for now */
474
475 device = strjoin("/dev/mapper/", label);
476 if (!device)
477 return NULL;
478
479 f = setmntent(fstab_path(), "re");
480 if (!f)
481 return NULL;
482
483 while ((m = getmntent(f)))
484 if (path_equal(m->mnt_fsname, device))
485 return strdup(m->mnt_dir);
486
487 return NULL;
488 }
489
490 static char *friendly_disk_name(const char *src, const char *vol) {
491 _cleanup_free_ char *description = NULL, *mount_point = NULL;
492 char *name_buffer = NULL;
493 int r;
494
495 assert(src);
496 assert(vol);
497
498 description = disk_description(src);
499 mount_point = disk_mount_point(vol);
500
501 /* If the description string is simply the volume name, then let's not show this twice */
502 if (description && streq(vol, description))
503 description = mfree(description);
504
505 if (mount_point && description)
506 r = asprintf(&name_buffer, "%s (%s) on %s", description, vol, mount_point);
507 else if (mount_point)
508 r = asprintf(&name_buffer, "%s on %s", vol, mount_point);
509 else if (description)
510 r = asprintf(&name_buffer, "%s (%s)", description, vol);
511 else
512 return strdup(vol);
513 if (r < 0)
514 return NULL;
515
516 return name_buffer;
517 }
518
519 static int get_password(
520 const char *vol,
521 const char *src,
522 usec_t until,
523 bool accept_cached,
524 char ***ret) {
525
526 _cleanup_free_ char *friendly = NULL, *text = NULL, *disk_path = NULL;
527 _cleanup_strv_free_erase_ char **passwords = NULL;
528 char **p, *id;
529 int r = 0;
530
531 assert(vol);
532 assert(src);
533 assert(ret);
534
535 friendly = friendly_disk_name(src, vol);
536 if (!friendly)
537 return log_oom();
538
539 if (asprintf(&text, "Please enter passphrase for disk %s:", friendly) < 0)
540 return log_oom();
541
542 disk_path = cescape(src);
543 if (!disk_path)
544 return log_oom();
545
546 id = strjoina("cryptsetup:", disk_path);
547
548 r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", until,
549 ASK_PASSWORD_PUSH_CACHE | (accept_cached*ASK_PASSWORD_ACCEPT_CACHED),
550 &passwords);
551 if (r < 0)
552 return log_error_errno(r, "Failed to query password: %m");
553
554 if (arg_verify) {
555 _cleanup_strv_free_erase_ char **passwords2 = NULL;
556
557 assert(strv_length(passwords) == 1);
558
559 if (asprintf(&text, "Please enter passphrase for disk %s (verification):", friendly) < 0)
560 return log_oom();
561
562 id = strjoina("cryptsetup-verification:", disk_path);
563
564 r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", until, ASK_PASSWORD_PUSH_CACHE, &passwords2);
565 if (r < 0)
566 return log_error_errno(r, "Failed to query verification password: %m");
567
568 assert(strv_length(passwords2) == 1);
569
570 if (!streq(passwords[0], passwords2[0]))
571 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN),
572 "Passwords did not match, retrying.");
573 }
574
575 strv_uniq(passwords);
576
577 STRV_FOREACH(p, passwords) {
578 char *c;
579
580 if (strlen(*p)+1 >= arg_key_size)
581 continue;
582
583 /* Pad password if necessary */
584 c = new(char, arg_key_size);
585 if (!c)
586 return log_oom();
587
588 strncpy(c, *p, arg_key_size);
589 erase_and_free(*p);
590 *p = TAKE_PTR(c);
591 }
592
593 *ret = TAKE_PTR(passwords);
594
595 return 0;
596 }
597
598 static int attach_tcrypt(
599 struct crypt_device *cd,
600 const char *name,
601 const char *key_file,
602 const void *key_data,
603 size_t key_data_size,
604 char **passwords,
605 uint32_t flags) {
606
607 int r = 0;
608 _cleanup_(erase_and_freep) char *passphrase = NULL;
609 struct crypt_params_tcrypt params = {
610 .flags = CRYPT_TCRYPT_LEGACY_MODES,
611 .keyfiles = (const char **)arg_tcrypt_keyfiles,
612 .keyfiles_count = strv_length(arg_tcrypt_keyfiles)
613 };
614
615 assert(cd);
616 assert(name);
617 assert(key_file || key_data || !strv_isempty(passwords));
618
619 if (arg_pkcs11_uri || arg_pkcs11_uri_auto || arg_fido2_device || arg_fido2_device_auto || arg_tpm2_device || arg_tpm2_device_auto)
620 /* Ask for a regular password */
621 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN),
622 "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
623
624 if (arg_tcrypt_hidden)
625 params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
626
627 if (arg_tcrypt_system)
628 params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
629
630 if (arg_tcrypt_veracrypt)
631 params.flags |= CRYPT_TCRYPT_VERA_MODES;
632
633 if (key_data) {
634 params.passphrase = key_data;
635 params.passphrase_size = key_data_size;
636 } else {
637 if (key_file) {
638 r = read_one_line_file(key_file, &passphrase);
639 if (r < 0) {
640 log_error_errno(r, "Failed to read password file '%s': %m", key_file);
641 return -EAGAIN; /* log with the actual error, but return EAGAIN */
642 }
643
644 params.passphrase = passphrase;
645 } else
646 params.passphrase = passwords[0];
647
648 params.passphrase_size = strlen(params.passphrase);
649 }
650
651 r = crypt_load(cd, CRYPT_TCRYPT, &params);
652 if (r < 0) {
653 if (r == -EPERM) {
654 if (key_data)
655 log_error_errno(r, "Failed to activate using discovered key. (Key not correct?)");
656
657 if (key_file)
658 log_error_errno(r, "Failed to activate using password file '%s'. (Key data not correct?)", key_file);
659
660 return -EAGAIN; /* log the actual error, but return EAGAIN */
661 }
662
663 return log_error_errno(r, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd));
664 }
665
666 r = crypt_activate_by_volume_key(cd, name, NULL, 0, flags);
667 if (r < 0)
668 return log_error_errno(r, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd));
669
670 return 0;
671 }
672
673 static char *make_bindname(const char *volume) {
674 char *s;
675
676 if (asprintf(&s, "@%" PRIx64"/cryptsetup/%s", random_u64(), volume) < 0)
677 return NULL;
678
679 return s;
680 }
681
682 static int make_security_device_monitor(sd_event *event, sd_device_monitor **ret) {
683 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
684 int r;
685
686 assert(ret);
687
688 r = sd_device_monitor_new(&monitor);
689 if (r < 0)
690 return log_error_errno(r, "Failed to allocate device monitor: %m");
691
692 r = sd_device_monitor_filter_add_match_tag(monitor, "security-device");
693 if (r < 0)
694 return log_error_errno(r, "Failed to configure device monitor: %m");
695
696 r = sd_device_monitor_attach_event(monitor, event);
697 if (r < 0)
698 return log_error_errno(r, "Failed to attach device monitor: %m");
699
700 r = sd_device_monitor_start(monitor, NULL, NULL);
701 if (r < 0)
702 return log_error_errno(r, "Failed to start device monitor: %m");
703
704 *ret = TAKE_PTR(monitor);
705 return 0;
706 }
707
708 static int attach_luks_or_plain_or_bitlk_by_fido2(
709 struct crypt_device *cd,
710 const char *name,
711 const char *key_file,
712 const void *key_data,
713 size_t key_data_size,
714 usec_t until,
715 uint32_t flags,
716 bool pass_volume_key) {
717
718 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
719 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
720 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
721 _cleanup_free_ void *discovered_salt = NULL, *discovered_cid = NULL;
722 size_t discovered_salt_size, discovered_cid_size, cid_size, decrypted_key_size;
723 _cleanup_free_ char *friendly = NULL, *discovered_rp_id = NULL;
724 int keyslot = arg_key_slot, r;
725 const char *rp_id;
726 const void *cid;
727
728 assert(cd);
729 assert(name);
730 assert(arg_fido2_device || arg_fido2_device_auto);
731
732 if (arg_fido2_cid) {
733 if (!key_file && !key_data)
734 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "FIDO2 mode selected but no key file specified, refusing.");
735
736 rp_id = arg_fido2_rp_id;
737 cid = arg_fido2_cid;
738 cid_size = arg_fido2_cid_size;
739 } else {
740 r = find_fido2_auto_data(
741 cd,
742 &discovered_rp_id,
743 &discovered_salt,
744 &discovered_salt_size,
745 &discovered_cid,
746 &discovered_cid_size,
747 &keyslot);
748
749 if (IN_SET(r, -ENOTUNIQ, -ENXIO))
750 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
751 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
752 if (r < 0)
753 return r;
754
755 rp_id = discovered_rp_id;
756 key_data = discovered_salt;
757 key_data_size = discovered_salt_size;
758 cid = discovered_cid;
759 cid_size = discovered_cid_size;
760 }
761
762 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
763 if (!friendly)
764 return log_oom();
765
766 for (;;) {
767 bool processed = false;
768
769 r = acquire_fido2_key(
770 name,
771 friendly,
772 arg_fido2_device,
773 rp_id,
774 cid, cid_size,
775 key_file, arg_keyfile_size, arg_keyfile_offset,
776 key_data, key_data_size,
777 until,
778 &decrypted_key, &decrypted_key_size);
779 if (r >= 0)
780 break;
781 if (r != -EAGAIN) /* EAGAIN means: token not found */
782 return r;
783
784 if (!monitor) {
785 /* We didn't find the token. In this case, watch for it via udev. Let's
786 * create an event loop and monitor first. */
787
788 assert(!event);
789
790 r = sd_event_default(&event);
791 if (r < 0)
792 return log_error_errno(r, "Failed to allocate event loop: %m");
793
794 r = make_security_device_monitor(event, &monitor);
795 if (r < 0)
796 return r;
797
798 log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly);
799
800 /* Let's immediately rescan in case the token appeared in the time we needed
801 * to create and configure the monitor */
802 continue;
803 }
804
805 for (;;) {
806 /* Wait for one event, and then eat all subsequent events until there are no
807 * further ones */
808 r = sd_event_run(event, processed ? 0 : UINT64_MAX);
809 if (r < 0)
810 return log_error_errno(r, "Failed to run event loop: %m");
811 if (r == 0)
812 break;
813
814 processed = true;
815 }
816
817 log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
818 }
819
820 if (pass_volume_key)
821 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
822 else {
823 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
824
825 /* Before using this key as passphrase we base64 encode it, for compat with homed */
826
827 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
828 if (r < 0)
829 return log_oom();
830
831 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
832 }
833 if (r == -EPERM) {
834 log_error_errno(r, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
835 return -EAGAIN; /* log actual error, but return EAGAIN */
836 }
837 if (r < 0)
838 return log_error_errno(r, "Failed to activate with FIDO2 acquired key: %m");
839
840 return 0;
841 }
842
843 static int attach_luks_or_plain_or_bitlk_by_pkcs11(
844 struct crypt_device *cd,
845 const char *name,
846 const char *key_file,
847 const void *key_data,
848 size_t key_data_size,
849 usec_t until,
850 uint32_t flags,
851 bool pass_volume_key) {
852
853 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
854 _cleanup_free_ char *friendly = NULL, *discovered_uri = NULL;
855 size_t decrypted_key_size = 0, discovered_key_size = 0;
856 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
857 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
858 _cleanup_free_ void *discovered_key = NULL;
859 int keyslot = arg_key_slot, r;
860 const char *uri;
861
862 assert(cd);
863 assert(name);
864 assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
865
866 if (arg_pkcs11_uri_auto) {
867 r = find_pkcs11_auto_data(cd, &discovered_uri, &discovered_key, &discovered_key_size, &keyslot);
868 if (IN_SET(r, -ENOTUNIQ, -ENXIO))
869 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
870 "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
871 if (r < 0)
872 return r;
873
874 uri = discovered_uri;
875 key_data = discovered_key;
876 key_data_size = discovered_key_size;
877 } else {
878 uri = arg_pkcs11_uri;
879
880 if (!key_file && !key_data)
881 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing.");
882 }
883
884 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
885 if (!friendly)
886 return log_oom();
887
888 for (;;) {
889 bool processed = false;
890
891 r = decrypt_pkcs11_key(
892 name,
893 friendly,
894 uri,
895 key_file, arg_keyfile_size, arg_keyfile_offset,
896 key_data, key_data_size,
897 until,
898 &decrypted_key, &decrypted_key_size);
899 if (r >= 0)
900 break;
901 if (r != -EAGAIN) /* EAGAIN means: token not found */
902 return r;
903
904 if (!monitor) {
905 /* We didn't find the token. In this case, watch for it via udev. Let's
906 * create an event loop and monitor first. */
907
908 assert(!event);
909
910 r = sd_event_default(&event);
911 if (r < 0)
912 return log_error_errno(r, "Failed to allocate event loop: %m");
913
914 r = make_security_device_monitor(event, &monitor);
915 if (r < 0)
916 return r;
917
918 log_notice("Security token %s not present for unlocking volume %s, please plug it in.",
919 uri, friendly);
920
921 /* Let's immediately rescan in case the token appeared in the time we needed
922 * to create and configure the monitor */
923 continue;
924 }
925
926 for (;;) {
927 /* Wait for one event, and then eat all subsequent events until there are no
928 * further ones */
929 r = sd_event_run(event, processed ? 0 : UINT64_MAX);
930 if (r < 0)
931 return log_error_errno(r, "Failed to run event loop: %m");
932 if (r == 0)
933 break;
934
935 processed = true;
936 }
937
938 log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
939 }
940
941 if (pass_volume_key)
942 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
943 else {
944 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
945
946 /* Before using this key as passphrase we base64 encode it. Why? For compatibility
947 * with homed's PKCS#11 hookup: there we want to use the key we acquired through
948 * PKCS#11 for other authentication/decryption mechanisms too, and some of them do
949 * not not take arbitrary binary blobs, but require NUL-terminated strings — most
950 * importantly UNIX password hashes. Hence, for compatibility we want to use a string
951 * without embedded NUL here too, and that's easiest to generate from a binary blob
952 * via base64 encoding. */
953
954 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
955 if (r < 0)
956 return log_oom();
957
958 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
959 }
960 if (r == -EPERM) {
961 log_error_errno(r, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
962 return -EAGAIN; /* log actual error, but return EAGAIN */
963 }
964 if (r < 0)
965 return log_error_errno(r, "Failed to activate with PKCS#11 acquired key: %m");
966
967 return 0;
968 }
969
970 static int make_tpm2_device_monitor(sd_event *event, sd_device_monitor **ret) {
971 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
972 int r;
973
974 assert(ret);
975
976 r = sd_device_monitor_new(&monitor);
977 if (r < 0)
978 return log_error_errno(r, "Failed to allocate device monitor: %m");
979
980 r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "tpmrm", NULL);
981 if (r < 0)
982 return log_error_errno(r, "Failed to configure device monitor: %m");
983
984 r = sd_device_monitor_attach_event(monitor, event);
985 if (r < 0)
986 return log_error_errno(r, "Failed to attach device monitor: %m");
987
988 r = sd_device_monitor_start(monitor, NULL, NULL);
989 if (r < 0)
990 return log_error_errno(r, "Failed to start device monitor: %m");
991
992 *ret = TAKE_PTR(monitor);
993 return 0;
994 }
995
996 static int attach_luks_or_plain_or_bitlk_by_tpm2(
997 struct crypt_device *cd,
998 const char *name,
999 const char *key_file,
1000 const void *key_data,
1001 size_t key_data_size,
1002 usec_t until,
1003 uint32_t flags,
1004 bool pass_volume_key) {
1005
1006 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1007 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1008 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1009 _cleanup_free_ char *friendly = NULL;
1010 int keyslot = arg_key_slot, r;
1011 size_t decrypted_key_size;
1012
1013 assert(cd);
1014 assert(name);
1015 assert(arg_tpm2_device || arg_tpm2_device_auto);
1016
1017 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1018 if (!friendly)
1019 return log_oom();
1020
1021 for (;;) {
1022 bool processed = false;
1023
1024 if (key_file || key_data) {
1025 /* If key data is specified, use that */
1026
1027 r = acquire_tpm2_key(
1028 name,
1029 arg_tpm2_device,
1030 arg_tpm2_pcr_mask == UINT32_MAX ? TPM2_PCR_MASK_DEFAULT : arg_tpm2_pcr_mask,
1031 key_file, arg_keyfile_size, arg_keyfile_offset,
1032 key_data, key_data_size,
1033 NULL, 0, /* we don't know the policy hash */
1034 &decrypted_key, &decrypted_key_size);
1035 if (r >= 0)
1036 break;
1037 if (r != -EAGAIN) /* EAGAIN means: no tpm2 chip found */
1038 return r;
1039 } else {
1040 _cleanup_free_ void *blob = NULL, *policy_hash = NULL;
1041 size_t blob_size, policy_hash_size;
1042 bool found_some = false;
1043 int token = 0; /* first token to look at */
1044
1045 /* If no key data is specified, look for it in the header. In order to support
1046 * software upgrades we'll iterate through all suitable tokens, maybe one of them
1047 * works. */
1048
1049 for (;;) {
1050 uint32_t pcr_mask;
1051
1052 r = find_tpm2_auto_data(
1053 cd,
1054 arg_tpm2_pcr_mask, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1055 token, /* search for the token with this index, or any later index than this */
1056 &pcr_mask,
1057 &blob, &blob_size,
1058 &policy_hash, &policy_hash_size,
1059 &keyslot,
1060 &token);
1061 if (r == -ENXIO) {
1062 /* No further TPM2 tokens found in the LUKS2 header.*/
1063 if (found_some)
1064 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1065 "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
1066 else
1067 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1068 "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
1069 }
1070 if (r < 0)
1071 return r;
1072
1073 found_some = true;
1074
1075 r = acquire_tpm2_key(
1076 name,
1077 arg_tpm2_device,
1078 pcr_mask,
1079 NULL, 0, 0, /* no key file */
1080 blob, blob_size,
1081 policy_hash, policy_hash_size,
1082 &decrypted_key, &decrypted_key_size);
1083 if (r != -EPERM)
1084 break;
1085
1086 token++; /* try a different token next time */
1087 }
1088
1089 if (r >= 0)
1090 break;
1091 if (r != -EAGAIN) /* EAGAIN means: no tpm2 chip found */
1092 return r;
1093 }
1094
1095 if (!monitor) {
1096 /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
1097 * an event loop and monitor first. */
1098
1099 assert(!event);
1100
1101 r = sd_event_default(&event);
1102 if (r < 0)
1103 return log_error_errno(r, "Failed to allocate event loop: %m");
1104
1105 r = make_tpm2_device_monitor(event, &monitor);
1106 if (r < 0)
1107 return r;
1108
1109 log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly);
1110
1111 /* Let's immediately rescan in case the device appeared in the time we needed
1112 * to create and configure the monitor */
1113 continue;
1114 }
1115
1116 for (;;) {
1117 /* Wait for one event, and then eat all subsequent events until there are no
1118 * further ones */
1119 r = sd_event_run(event, processed ? 0 : UINT64_MAX);
1120 if (r < 0)
1121 return log_error_errno(r, "Failed to run event loop: %m");
1122 if (r == 0)
1123 break;
1124
1125 processed = true;
1126 }
1127
1128 log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
1129 }
1130
1131 if (pass_volume_key)
1132 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
1133 else {
1134 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
1135
1136 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1137
1138 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1139 if (r < 0)
1140 return log_oom();
1141
1142 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
1143 }
1144 if (r == -EPERM) {
1145 log_error_errno(r, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
1146 return -EAGAIN; /* log actual error, but return EAGAIN */
1147 }
1148 if (r < 0)
1149 return log_error_errno(r, "Failed to activate with TPM2 acquired key: %m");
1150
1151 return 0;
1152 }
1153
1154 static int attach_luks_or_plain_or_bitlk_by_key_data(
1155 struct crypt_device *cd,
1156 const char *name,
1157 const void *key_data,
1158 size_t key_data_size,
1159 uint32_t flags,
1160 bool pass_volume_key) {
1161
1162 int r;
1163
1164 assert(cd);
1165 assert(name);
1166 assert(key_data);
1167
1168 if (pass_volume_key)
1169 r = crypt_activate_by_volume_key(cd, name, key_data, key_data_size, flags);
1170 else
1171 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, key_data, key_data_size, flags);
1172 if (r == -EPERM) {
1173 log_error_errno(r, "Failed to activate. (Key incorrect?)");
1174 return -EAGAIN; /* Log actual error, but return EAGAIN */
1175 }
1176 if (r < 0)
1177 return log_error_errno(r, "Failed to activate: %m");
1178
1179 return 0;
1180 }
1181
1182 static int attach_luks_or_plain_or_bitlk_by_key_file(
1183 struct crypt_device *cd,
1184 const char *name,
1185 const char *key_file,
1186 uint32_t flags,
1187 bool pass_volume_key) {
1188
1189 _cleanup_(erase_and_freep) char *kfdata = NULL;
1190 _cleanup_free_ char *bindname = NULL;
1191 size_t kfsize;
1192 int r;
1193
1194 assert(cd);
1195 assert(name);
1196 assert(key_file);
1197
1198 /* If we read the key via AF_UNIX, make this client recognizable */
1199 bindname = make_bindname(name);
1200 if (!bindname)
1201 return log_oom();
1202
1203 r = read_full_file_full(
1204 AT_FDCWD, key_file,
1205 arg_keyfile_offset == 0 ? UINT64_MAX : arg_keyfile_offset,
1206 arg_keyfile_size == 0 ? SIZE_MAX : arg_keyfile_size,
1207 READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
1208 bindname,
1209 &kfdata, &kfsize);
1210 if (r == -ENOENT) {
1211 log_error_errno(r, "Failed to activate, key file '%s' missing.", key_file);
1212 return -EAGAIN; /* Log actual error, but return EAGAIN */
1213 }
1214
1215 if (pass_volume_key)
1216 r = crypt_activate_by_volume_key(cd, name, kfdata, kfsize, flags);
1217 else
1218 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, kfdata, kfsize, flags);
1219 if (r == -EPERM) {
1220 log_error_errno(r, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file);
1221 return -EAGAIN; /* Log actual error, but return EAGAIN */
1222 }
1223 if (r < 0)
1224 return log_error_errno(r, "Failed to activate with key file '%s': %m", key_file);
1225
1226 return 0;
1227 }
1228
1229 static int attach_luks_or_plain_or_bitlk_by_passphrase(
1230 struct crypt_device *cd,
1231 const char *name,
1232 char **passwords,
1233 uint32_t flags,
1234 bool pass_volume_key) {
1235
1236 char **p;
1237 int r;
1238
1239 assert(cd);
1240 assert(name);
1241
1242 r = -EINVAL;
1243 STRV_FOREACH(p, passwords) {
1244 if (pass_volume_key)
1245 r = crypt_activate_by_volume_key(cd, name, *p, arg_key_size, flags);
1246 else
1247 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, *p, strlen(*p), flags);
1248 if (r >= 0)
1249 break;
1250 }
1251 if (r == -EPERM) {
1252 log_error_errno(r, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
1253 return -EAGAIN; /* log actual error, but return EAGAIN */
1254 }
1255 if (r < 0)
1256 return log_error_errno(r, "Failed to activate with specified passphrase: %m");
1257
1258 return 0;
1259 }
1260
1261 static int attach_luks_or_plain_or_bitlk(
1262 struct crypt_device *cd,
1263 const char *name,
1264 const char *key_file,
1265 const void *key_data,
1266 size_t key_data_size,
1267 char **passwords,
1268 uint32_t flags,
1269 usec_t until) {
1270
1271 bool pass_volume_key = false;
1272 int r;
1273
1274 assert(cd);
1275 assert(name);
1276
1277 if ((!arg_type && !crypt_get_type(cd)) || streq_ptr(arg_type, CRYPT_PLAIN)) {
1278 struct crypt_params_plain params = {
1279 .offset = arg_offset,
1280 .skip = arg_skip,
1281 .sector_size = arg_sector_size,
1282 };
1283 const char *cipher, *cipher_mode;
1284 _cleanup_free_ char *truncated_cipher = NULL;
1285
1286 if (streq_ptr(arg_hash, "plain"))
1287 /* plain isn't a real hash type. it just means "use no hash" */
1288 params.hash = NULL;
1289 else if (arg_hash)
1290 params.hash = arg_hash;
1291 else if (!key_file)
1292 /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
1293 * file is provided */
1294 params.hash = "ripemd160";
1295
1296 if (arg_cipher) {
1297 size_t l;
1298
1299 l = strcspn(arg_cipher, "-");
1300 truncated_cipher = strndup(arg_cipher, l);
1301 if (!truncated_cipher)
1302 return log_oom();
1303
1304 cipher = truncated_cipher;
1305 cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain";
1306 } else {
1307 cipher = "aes";
1308 cipher_mode = "cbc-essiv:sha256";
1309 }
1310
1311 /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
1312 arg_keyfile_size = arg_key_size;
1313
1314 /* In contrast to what the name crypt_format() might suggest this doesn't actually format
1315 * anything, it just configures encryption parameters when used for plain mode. */
1316 r = crypt_format(cd, CRYPT_PLAIN, cipher, cipher_mode, NULL, NULL, arg_keyfile_size, &params);
1317 if (r < 0)
1318 return log_error_errno(r, "Loading of cryptographic parameters failed: %m");
1319
1320 /* hash == NULL implies the user passed "plain" */
1321 pass_volume_key = !params.hash;
1322 }
1323
1324 log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
1325 crypt_get_cipher(cd),
1326 crypt_get_cipher_mode(cd),
1327 crypt_get_volume_key_size(cd)*8,
1328 crypt_get_device_name(cd));
1329
1330 if (arg_tpm2_device || arg_tpm2_device_auto)
1331 return attach_luks_or_plain_or_bitlk_by_tpm2(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
1332 if (arg_fido2_device || arg_fido2_device_auto)
1333 return attach_luks_or_plain_or_bitlk_by_fido2(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
1334 if (arg_pkcs11_uri || arg_pkcs11_uri_auto)
1335 return attach_luks_or_plain_or_bitlk_by_pkcs11(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
1336 if (key_data)
1337 return attach_luks_or_plain_or_bitlk_by_key_data(cd, name, key_data, key_data_size, flags, pass_volume_key);
1338 if (key_file)
1339 return attach_luks_or_plain_or_bitlk_by_key_file(cd, name, key_file, flags, pass_volume_key);
1340
1341 return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
1342 }
1343
1344 static int help(void) {
1345 _cleanup_free_ char *link = NULL;
1346 int r;
1347
1348 r = terminal_urlify_man("systemd-cryptsetup@.service", "8", &link);
1349 if (r < 0)
1350 return log_oom();
1351
1352 printf("%s attach VOLUME SOURCEDEVICE [PASSWORD] [OPTIONS]\n"
1353 "%s detach VOLUME\n\n"
1354 "Attaches or detaches an encrypted block device.\n"
1355 "\nSee the %s for details.\n",
1356 program_invocation_short_name,
1357 program_invocation_short_name,
1358 link);
1359
1360 return 0;
1361 }
1362
1363 static uint32_t determine_flags(void) {
1364 uint32_t flags = 0;
1365
1366 if (arg_readonly)
1367 flags |= CRYPT_ACTIVATE_READONLY;
1368
1369 if (arg_discards)
1370 flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
1371
1372 if (arg_same_cpu_crypt)
1373 flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
1374
1375 if (arg_submit_from_crypt_cpus)
1376 flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
1377
1378 if (arg_no_read_workqueue)
1379 flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
1380
1381 if (arg_no_write_workqueue)
1382 flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
1383
1384 #ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
1385 /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
1386 /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
1387 flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF;
1388 #endif
1389
1390 return flags;
1391 }
1392
1393 static void remove_and_erasep(const char **p) {
1394 int r;
1395
1396 if (!*p)
1397 return;
1398
1399 r = unlinkat_deallocate(AT_FDCWD, *p, UNLINK_ERASE);
1400 if (r < 0 && r != -ENOENT)
1401 log_warning_errno(r, "Unable to erase key file '%s', ignoring: %m", *p);
1402 }
1403
1404 static int run(int argc, char *argv[]) {
1405 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1406 const char *verb;
1407 int r;
1408
1409 if (argc <= 1)
1410 return help();
1411
1412 if (argc < 3)
1413 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1414 "This program requires at least two arguments.");
1415
1416 log_setup();
1417
1418 cryptsetup_enable_logging(cd);
1419
1420 umask(0022);
1421
1422 verb = argv[1];
1423
1424 if (streq(verb, "attach")) {
1425 _cleanup_(remove_and_erasep) const char *destroy_key_file = NULL;
1426 _cleanup_(erase_and_freep) void *key_data = NULL;
1427 const char *volume, *source, *key_file, *options;
1428 crypt_status_info status;
1429 size_t key_data_size = 0;
1430 uint32_t flags = 0;
1431 unsigned tries;
1432 usec_t until;
1433
1434 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [PASSWORD] [OPTIONS] */
1435
1436 if (argc < 4)
1437 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "attach requires at least two arguments.");
1438
1439 volume = argv[2];
1440 source = argv[3];
1441 key_file = argc >= 5 && !STR_IN_SET(argv[4], "", "-", "none") ? argv[4] : NULL;
1442 options = argc >= 6 && !STR_IN_SET(argv[5], "", "-", "none") ? argv[5] : NULL;
1443
1444 if (!filename_is_valid(volume))
1445 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
1446
1447 if (key_file && !path_is_absolute(key_file)) {
1448 log_warning("Password file path '%s' is not absolute. Ignoring.", key_file);
1449 key_file = NULL;
1450 }
1451
1452 if (options) {
1453 r = parse_options(options);
1454 if (r < 0)
1455 return r;
1456 }
1457
1458 log_debug("%s %s ← %s type=%s cipher=%s", __func__,
1459 volume, source, strempty(arg_type), strempty(arg_cipher));
1460
1461 /* A delicious drop of snake oil */
1462 (void) mlockall(MCL_FUTURE);
1463
1464 if (!key_file) {
1465 _cleanup_free_ char *bindname = NULL;
1466 const char *fn;
1467
1468 bindname = make_bindname(volume);
1469 if (!bindname)
1470 return log_oom();
1471
1472 /* If a key file is not explicitly specified, search for a key in a well defined
1473 * search path, and load it. */
1474
1475 fn = strjoina(volume, ".key");
1476 r = find_key_file(
1477 fn,
1478 STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"),
1479 bindname,
1480 &key_data, &key_data_size);
1481 if (r < 0)
1482 return r;
1483 if (r > 0)
1484 log_debug("Automatically discovered key for volume '%s'.", volume);
1485 } else if (arg_keyfile_erase)
1486 destroy_key_file = key_file; /* let's get this baby erased when we leave */
1487
1488 if (arg_header) {
1489 log_debug("LUKS header: %s", arg_header);
1490 r = crypt_init(&cd, arg_header);
1491 } else
1492 r = crypt_init(&cd, source);
1493 if (r < 0)
1494 return log_error_errno(r, "crypt_init() failed: %m");
1495
1496 cryptsetup_enable_logging(cd);
1497
1498 status = crypt_status(cd, volume);
1499 if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) {
1500 log_info("Volume %s already active.", volume);
1501 return 0;
1502 }
1503
1504 flags = determine_flags();
1505
1506 until = usec_add(now(CLOCK_MONOTONIC), arg_timeout);
1507 if (until == USEC_INFINITY)
1508 until = 0;
1509
1510 arg_key_size = (arg_key_size > 0 ? arg_key_size : (256 / 8));
1511
1512 if (key_file) {
1513 struct stat st;
1514
1515 /* Ideally we'd do this on the open fd, but since this is just a
1516 * warning it's OK to do this in two steps. */
1517 if (stat(key_file, &st) >= 0 && S_ISREG(st.st_mode) && (st.st_mode & 0005))
1518 log_warning("Key file %s is world-readable. This is not a good idea!", key_file);
1519 }
1520
1521 if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2)) {
1522 r = crypt_load(cd, !arg_type || streq(arg_type, ANY_LUKS) ? CRYPT_LUKS : arg_type, NULL);
1523 if (r < 0)
1524 return log_error_errno(r, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd));
1525
1526 if (arg_header) {
1527 r = crypt_set_data_device(cd, source);
1528 if (r < 0)
1529 return log_error_errno(r, "Failed to set LUKS data device %s: %m", source);
1530 }
1531
1532 /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
1533 if (!key_file && !key_data) {
1534 r = crypt_activate_by_token(cd, volume, CRYPT_ANY_TOKEN, NULL, flags);
1535 if (r >= 0) {
1536 log_debug("Volume %s activated with LUKS token id %i.", volume, r);
1537 return 0;
1538 }
1539
1540 log_debug_errno(r, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd));
1541 }
1542 }
1543
1544 /* since cryptsetup 2.3.0 (Feb 2020) */
1545 #ifdef CRYPT_BITLK
1546 if (streq_ptr(arg_type, CRYPT_BITLK)) {
1547 r = crypt_load(cd, CRYPT_BITLK, NULL);
1548 if (r < 0)
1549 return log_error_errno(r, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd));
1550 }
1551 #endif
1552
1553 for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) {
1554 _cleanup_strv_free_erase_ char **passwords = NULL;
1555
1556 /* When we were able to acquire multiple keys, let's always process them in this order:
1557 *
1558 * 1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
1559 * 2. The discovered key: i.e. key_data + key_data_size
1560 * 3. The configured key: i.e. key_file + arg_keyfile_offset + arg_keyfile_size
1561 * 4. The empty password, in case arg_try_empty_password is set
1562 * 5. We enquire the user for a password
1563 */
1564
1565 if (!key_file && !key_data && !arg_pkcs11_uri && !arg_pkcs11_uri_auto && !arg_fido2_device && !arg_fido2_device_auto && !arg_tpm2_device && !arg_tpm2_device_auto) {
1566
1567 if (arg_try_empty_password) {
1568 /* Hmm, let's try an empty password now, but only once */
1569 arg_try_empty_password = false;
1570
1571 key_data = strdup("");
1572 if (!key_data)
1573 return log_oom();
1574
1575 key_data_size = 0;
1576 } else {
1577 /* Ask the user for a passphrase only as last resort, if we have
1578 * nothing else to check for */
1579
1580 r = get_password(volume, source, until, tries == 0 && !arg_verify, &passwords);
1581 if (r == -EAGAIN)
1582 continue;
1583 if (r < 0)
1584 return r;
1585 }
1586 }
1587
1588 if (streq_ptr(arg_type, CRYPT_TCRYPT))
1589 r = attach_tcrypt(cd, volume, key_file, key_data, key_data_size, passwords, flags);
1590 else
1591 r = attach_luks_or_plain_or_bitlk(cd, volume, key_file, key_data, key_data_size, passwords, flags, until);
1592 if (r >= 0)
1593 break;
1594 if (r != -EAGAIN)
1595 return r;
1596
1597 /* Key not correct? Let's try again! */
1598
1599 key_file = NULL;
1600 key_data = erase_and_free(key_data);
1601 key_data_size = 0;
1602 arg_pkcs11_uri = mfree(arg_pkcs11_uri);
1603 arg_pkcs11_uri_auto = false;
1604 arg_fido2_device = mfree(arg_fido2_device);
1605 arg_fido2_device_auto = false;
1606 arg_tpm2_device = mfree(arg_tpm2_device);
1607 arg_tpm2_device_auto = false;
1608 }
1609
1610 if (arg_tries != 0 && tries >= arg_tries)
1611 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to activate; giving up.");
1612
1613 } else if (streq(verb, "detach")) {
1614 const char *volume;
1615
1616 volume = argv[2];
1617
1618 if (!filename_is_valid(volume))
1619 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
1620
1621 r = crypt_init_by_name(&cd, volume);
1622 if (r == -ENODEV) {
1623 log_info("Volume %s already inactive.", volume);
1624 return 0;
1625 }
1626 if (r < 0)
1627 return log_error_errno(r, "crypt_init_by_name() failed: %m");
1628
1629 cryptsetup_enable_logging(cd);
1630
1631 r = crypt_deactivate(cd, volume);
1632 if (r < 0)
1633 return log_error_errno(r, "Failed to deactivate: %m");
1634
1635 } else
1636 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb %s.", verb);
1637
1638 return 0;
1639 }
1640
1641 DEFINE_MAIN_FUNCTION(run);