]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/cryptsetup/cryptsetup.c
Merge pull request #23893 from yuwata/core-mount-re-read-mountinfo
[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 "efi-api.h"
21 #include "env-util.h"
22 #include "escape.h"
23 #include "fileio.h"
24 #include "fs-util.h"
25 #include "fstab-util.h"
26 #include "hexdecoct.h"
27 #include "libfido2-util.h"
28 #include "log.h"
29 #include "main-func.h"
30 #include "memory-util.h"
31 #include "mount-util.h"
32 #include "nulstr-util.h"
33 #include "parse-util.h"
34 #include "path-util.h"
35 #include "pkcs11-util.h"
36 #include "pretty-print.h"
37 #include "process-util.h"
38 #include "random-util.h"
39 #include "string-table.h"
40 #include "strv.h"
41 #include "tpm2-util.h"
42
43 /* internal helper */
44 #define ANY_LUKS "LUKS"
45 /* as in src/cryptsetup.h */
46 #define CRYPT_SECTOR_SIZE 512
47 #define CRYPT_MAX_SECTOR_SIZE 4096
48
49 typedef enum PassphraseType {
50 PASSPHRASE_NONE,
51 PASSPHRASE_REGULAR = 1 << 0,
52 PASSPHRASE_RECOVERY_KEY = 1 << 1,
53 PASSPHRASE_BOTH = PASSPHRASE_REGULAR|PASSPHRASE_RECOVERY_KEY,
54 _PASSPHRASE_TYPE_MAX,
55 _PASSPHRASE_TYPE_INVALID = -1,
56 } PassphraseType;
57
58 static const char *arg_type = NULL; /* ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT, CRYPT_BITLK or CRYPT_PLAIN */
59 static char *arg_cipher = NULL;
60 static unsigned arg_key_size = 0;
61 static unsigned arg_sector_size = CRYPT_SECTOR_SIZE;
62 static int arg_key_slot = CRYPT_ANY_SLOT;
63 static unsigned arg_keyfile_size = 0;
64 static uint64_t arg_keyfile_offset = 0;
65 static bool arg_keyfile_erase = false;
66 static bool arg_try_empty_password = false;
67 static char *arg_hash = NULL;
68 static char *arg_header = NULL;
69 static unsigned arg_tries = 3;
70 static bool arg_readonly = false;
71 static bool arg_verify = false;
72 static AskPasswordFlags arg_ask_password_flags = 0;
73 static bool arg_discards = false;
74 static bool arg_same_cpu_crypt = false;
75 static bool arg_submit_from_crypt_cpus = false;
76 static bool arg_no_read_workqueue = false;
77 static bool arg_no_write_workqueue = false;
78 static bool arg_tcrypt_hidden = false;
79 static bool arg_tcrypt_system = false;
80 static bool arg_tcrypt_veracrypt = false;
81 static char **arg_tcrypt_keyfiles = NULL;
82 static uint64_t arg_offset = 0;
83 static uint64_t arg_skip = 0;
84 static usec_t arg_timeout = USEC_INFINITY;
85 static char *arg_pkcs11_uri = NULL;
86 static bool arg_pkcs11_uri_auto = false;
87 static char *arg_fido2_device = NULL;
88 static bool arg_fido2_device_auto = false;
89 static void *arg_fido2_cid = NULL;
90 static size_t arg_fido2_cid_size = 0;
91 static char *arg_fido2_rp_id = NULL;
92 static char *arg_tpm2_device = NULL;
93 static bool arg_tpm2_device_auto = false;
94 static uint32_t arg_tpm2_pcr_mask = UINT32_MAX;
95 static bool arg_tpm2_pin = false;
96 static bool arg_headless = false;
97 static usec_t arg_token_timeout_usec = 30*USEC_PER_SEC;
98
99 STATIC_DESTRUCTOR_REGISTER(arg_cipher, freep);
100 STATIC_DESTRUCTOR_REGISTER(arg_hash, freep);
101 STATIC_DESTRUCTOR_REGISTER(arg_header, freep);
102 STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles, strv_freep);
103 STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri, freep);
104 STATIC_DESTRUCTOR_REGISTER(arg_fido2_device, freep);
105 STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid, freep);
106 STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id, freep);
107 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
108
109 static const char* const passphrase_type_table[_PASSPHRASE_TYPE_MAX] = {
110 [PASSPHRASE_REGULAR] = "passphrase",
111 [PASSPHRASE_RECOVERY_KEY] = "recovery key",
112 [PASSPHRASE_BOTH] = "passphrase or recovery key",
113 };
114
115 const char* passphrase_type_to_string(PassphraseType t);
116 PassphraseType passphrase_type_from_string(const char *s);
117
118 DEFINE_STRING_TABLE_LOOKUP(passphrase_type, PassphraseType);
119
120 /* Options Debian's crypttab knows we don't:
121
122 check=
123 checkargs=
124 noearly
125 loud
126 quiet
127 keyscript=
128 initramfs
129 */
130
131 static int parse_one_option(const char *option) {
132 const char *val;
133 int r;
134
135 assert(option);
136
137 /* Handled outside of this tool */
138 if (STR_IN_SET(option, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
139 return 0;
140
141 if (startswith(option, "keyfile-timeout="))
142 return 0;
143
144 if ((val = startswith(option, "cipher="))) {
145 r = free_and_strdup(&arg_cipher, val);
146 if (r < 0)
147 return log_oom();
148
149 } else if ((val = startswith(option, "size="))) {
150
151 r = safe_atou(val, &arg_key_size);
152 if (r < 0) {
153 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
154 return 0;
155 }
156
157 if (arg_key_size % 8) {
158 log_error("size= not a multiple of 8, ignoring.");
159 return 0;
160 }
161
162 arg_key_size /= 8;
163
164 } else if ((val = startswith(option, "sector-size="))) {
165
166 r = safe_atou(val, &arg_sector_size);
167 if (r < 0) {
168 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
169 return 0;
170 }
171
172 if (arg_sector_size % 2) {
173 log_error("sector-size= not a multiple of 2, ignoring.");
174 return 0;
175 }
176
177 if (arg_sector_size < CRYPT_SECTOR_SIZE || arg_sector_size > CRYPT_MAX_SECTOR_SIZE) {
178 log_error("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE, CRYPT_MAX_SECTOR_SIZE);
179 return 0;
180 }
181
182 } else if ((val = startswith(option, "key-slot=")) ||
183 (val = startswith(option, "keyslot="))) {
184
185 arg_type = ANY_LUKS;
186 r = safe_atoi(val, &arg_key_slot);
187 if (r < 0) {
188 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
189 return 0;
190 }
191
192 } else if ((val = startswith(option, "tcrypt-keyfile="))) {
193
194 arg_type = CRYPT_TCRYPT;
195 if (path_is_absolute(val)) {
196 if (strv_extend(&arg_tcrypt_keyfiles, val) < 0)
197 return log_oom();
198 } else
199 log_error("Key file path \"%s\" is not absolute. Ignoring.", val);
200
201 } else if ((val = startswith(option, "keyfile-size="))) {
202
203 r = safe_atou(val, &arg_keyfile_size);
204 if (r < 0) {
205 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
206 return 0;
207 }
208
209 } else if ((val = startswith(option, "keyfile-offset="))) {
210
211 r = safe_atou64(val, &arg_keyfile_offset);
212 if (r < 0) {
213 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
214 return 0;
215 }
216
217 } else if ((val = startswith(option, "keyfile-erase="))) {
218
219 r = parse_boolean(val);
220 if (r < 0) {
221 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
222 return 0;
223 }
224
225 arg_keyfile_erase = r;
226
227 } else if (streq(option, "keyfile-erase"))
228 arg_keyfile_erase = true;
229
230 else if ((val = startswith(option, "hash="))) {
231 r = free_and_strdup(&arg_hash, val);
232 if (r < 0)
233 return log_oom();
234
235 } else if ((val = startswith(option, "header="))) {
236 arg_type = ANY_LUKS;
237
238 if (!path_is_absolute(val))
239 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
240 "Header path \"%s\" is not absolute, refusing.", val);
241
242 if (arg_header)
243 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
244 "Duplicate header= option, refusing.");
245
246 arg_header = strdup(val);
247 if (!arg_header)
248 return log_oom();
249
250 } else if ((val = startswith(option, "tries="))) {
251
252 r = safe_atou(val, &arg_tries);
253 if (r < 0) {
254 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
255 return 0;
256 }
257
258 } else if (STR_IN_SET(option, "readonly", "read-only"))
259 arg_readonly = true;
260 else if (streq(option, "verify"))
261 arg_verify = true;
262 else if ((val = startswith(option, "password-echo="))) {
263 if (streq(val, "masked"))
264 arg_ask_password_flags &= ~(ASK_PASSWORD_ECHO|ASK_PASSWORD_SILENT);
265 else {
266 r = parse_boolean(val);
267 if (r < 0) {
268 log_warning_errno(r, "Invalid password-echo= option \"%s\", ignoring.", val);
269 return 0;
270 }
271
272 SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_ECHO, r);
273 SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_SILENT, !r);
274 }
275 } else if (STR_IN_SET(option, "allow-discards", "discard"))
276 arg_discards = true;
277 else if (streq(option, "same-cpu-crypt"))
278 arg_same_cpu_crypt = true;
279 else if (streq(option, "submit-from-crypt-cpus"))
280 arg_submit_from_crypt_cpus = true;
281 else if (streq(option, "no-read-workqueue"))
282 arg_no_read_workqueue = true;
283 else if (streq(option, "no-write-workqueue"))
284 arg_no_write_workqueue = true;
285 else if (streq(option, "luks"))
286 arg_type = ANY_LUKS;
287 /* since cryptsetup 2.3.0 (Feb 2020) */
288 #ifdef CRYPT_BITLK
289 else if (streq(option, "bitlk"))
290 arg_type = CRYPT_BITLK;
291 #endif
292 else if (streq(option, "tcrypt"))
293 arg_type = CRYPT_TCRYPT;
294 else if (STR_IN_SET(option, "tcrypt-hidden", "tcrypthidden")) {
295 arg_type = CRYPT_TCRYPT;
296 arg_tcrypt_hidden = true;
297 } else if (streq(option, "tcrypt-system")) {
298 arg_type = CRYPT_TCRYPT;
299 arg_tcrypt_system = true;
300 } else if (STR_IN_SET(option, "tcrypt-veracrypt", "veracrypt")) {
301 arg_type = CRYPT_TCRYPT;
302 arg_tcrypt_veracrypt = true;
303 } else if (STR_IN_SET(option, "plain", "swap", "tmp") ||
304 startswith(option, "tmp="))
305 arg_type = CRYPT_PLAIN;
306 else if ((val = startswith(option, "timeout="))) {
307
308 r = parse_sec_fix_0(val, &arg_timeout);
309 if (r < 0) {
310 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
311 return 0;
312 }
313
314 } else if ((val = startswith(option, "offset="))) {
315
316 r = safe_atou64(val, &arg_offset);
317 if (r < 0)
318 return log_error_errno(r, "Failed to parse %s: %m", option);
319
320 } else if ((val = startswith(option, "skip="))) {
321
322 r = safe_atou64(val, &arg_skip);
323 if (r < 0)
324 return log_error_errno(r, "Failed to parse %s: %m", option);
325
326 } else if ((val = startswith(option, "pkcs11-uri="))) {
327
328 if (streq(val, "auto")) {
329 arg_pkcs11_uri = mfree(arg_pkcs11_uri);
330 arg_pkcs11_uri_auto = true;
331 } else {
332 if (!pkcs11_uri_valid(val))
333 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing");
334
335 r = free_and_strdup(&arg_pkcs11_uri, val);
336 if (r < 0)
337 return log_oom();
338
339 arg_pkcs11_uri_auto = false;
340 }
341
342 } else if ((val = startswith(option, "fido2-device="))) {
343
344 if (streq(val, "auto")) {
345 arg_fido2_device = mfree(arg_fido2_device);
346 arg_fido2_device_auto = true;
347 } else {
348 r = free_and_strdup(&arg_fido2_device, val);
349 if (r < 0)
350 return log_oom();
351
352 arg_fido2_device_auto = false;
353 }
354
355 } else if ((val = startswith(option, "fido2-cid="))) {
356
357 if (streq(val, "auto"))
358 arg_fido2_cid = mfree(arg_fido2_cid);
359 else {
360 _cleanup_free_ void *cid = NULL;
361 size_t cid_size;
362
363 r = unbase64mem(val, SIZE_MAX, &cid, &cid_size);
364 if (r < 0)
365 return log_error_errno(r, "Failed to decode FIDO2 CID data: %m");
366
367 free(arg_fido2_cid);
368 arg_fido2_cid = TAKE_PTR(cid);
369 arg_fido2_cid_size = cid_size;
370 }
371
372 /* Turn on FIDO2 as side-effect, if not turned on yet. */
373 if (!arg_fido2_device && !arg_fido2_device_auto)
374 arg_fido2_device_auto = true;
375
376 } else if ((val = startswith(option, "fido2-rp="))) {
377
378 r = free_and_strdup(&arg_fido2_rp_id, val);
379 if (r < 0)
380 return log_oom();
381
382 } else if ((val = startswith(option, "tpm2-device="))) {
383
384 if (streq(val, "auto")) {
385 arg_tpm2_device = mfree(arg_tpm2_device);
386 arg_tpm2_device_auto = true;
387 } else {
388 r = free_and_strdup(&arg_tpm2_device, val);
389 if (r < 0)
390 return log_oom();
391
392 arg_tpm2_device_auto = false;
393 }
394
395 } else if ((val = startswith(option, "tpm2-pcrs="))) {
396
397 r = tpm2_parse_pcr_argument(val, &arg_tpm2_pcr_mask);
398 if (r < 0)
399 return r;
400
401 } else if ((val = startswith(option, "tpm2-pin="))) {
402
403 r = parse_boolean(val);
404 if (r < 0) {
405 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
406 return 0;
407 }
408
409 arg_tpm2_pin = r;
410
411 } else if ((val = startswith(option, "try-empty-password="))) {
412
413 r = parse_boolean(val);
414 if (r < 0) {
415 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
416 return 0;
417 }
418
419 arg_try_empty_password = r;
420
421 } else if (streq(option, "try-empty-password"))
422 arg_try_empty_password = true;
423 else if ((val = startswith(option, "headless="))) {
424
425 r = parse_boolean(val);
426 if (r < 0) {
427 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
428 return 0;
429 }
430
431 arg_headless = r;
432 } else if (streq(option, "headless"))
433 arg_headless = true;
434
435 else if ((val = startswith(option, "token-timeout="))) {
436
437 r = parse_sec_fix_0(val, &arg_token_timeout_usec);
438 if (r < 0) {
439 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
440 return 0;
441 }
442
443 } else if (!streq(option, "x-initrd.attach"))
444 log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
445
446 return 0;
447 }
448
449 static int parse_options(const char *options) {
450 assert(options);
451
452 for (;;) {
453 _cleanup_free_ char *word = NULL;
454 int r;
455
456 r = extract_first_word(&options, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS | EXTRACT_UNESCAPE_SEPARATORS);
457 if (r < 0)
458 return log_error_errno(r, "Failed to parse options: %m");
459 if (r == 0)
460 break;
461
462 r = parse_one_option(word);
463 if (r < 0)
464 return r;
465 }
466
467 /* sanity-check options */
468 if (arg_type && !streq(arg_type, CRYPT_PLAIN)) {
469 if (arg_offset != 0)
470 log_warning("offset= ignored with type %s", arg_type);
471 if (arg_skip != 0)
472 log_warning("skip= ignored with type %s", arg_type);
473 }
474
475 return 0;
476 }
477
478 static char* disk_description(const char *path) {
479 static const char name_fields[] =
480 "DM_NAME\0"
481 "ID_MODEL_FROM_DATABASE\0"
482 "ID_MODEL\0";
483
484 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
485 const char *i, *name;
486 struct stat st;
487
488 assert(path);
489
490 if (stat(path, &st) < 0)
491 return NULL;
492
493 if (!S_ISBLK(st.st_mode))
494 return NULL;
495
496 if (sd_device_new_from_stat_rdev(&device, &st) < 0)
497 return NULL;
498
499 if (sd_device_get_property_value(device, "ID_PART_ENTRY_NAME", &name) >= 0) {
500 _cleanup_free_ char *unescaped = NULL;
501 ssize_t l;
502
503 /* ID_PART_ENTRY_NAME uses \x style escaping, using libblkid's blkid_encode_string(). Let's
504 * reverse this here to make the string more human friendly in case people embed spaces or
505 * other weird stuff. */
506
507 l = cunescape(name, UNESCAPE_RELAX, &unescaped);
508 if (l < 0) {
509 log_debug_errno(l, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
510 return NULL;
511 }
512
513 if (!isempty(unescaped) && !string_has_cc(unescaped, NULL))
514 return TAKE_PTR(unescaped);
515 }
516
517 /* These need no unescaping. */
518 NULSTR_FOREACH(i, name_fields)
519 if (sd_device_get_property_value(device, i, &name) >= 0 &&
520 !isempty(name))
521 return strdup(name);
522
523 return NULL;
524 }
525
526 static char *disk_mount_point(const char *label) {
527 _cleanup_free_ char *device = NULL;
528 _cleanup_endmntent_ FILE *f = NULL;
529 struct mntent *m;
530
531 /* Yeah, we don't support native systemd unit files here for now */
532
533 device = strjoin("/dev/mapper/", label);
534 if (!device)
535 return NULL;
536
537 f = setmntent(fstab_path(), "re");
538 if (!f)
539 return NULL;
540
541 while ((m = getmntent(f)))
542 if (path_equal(m->mnt_fsname, device))
543 return strdup(m->mnt_dir);
544
545 return NULL;
546 }
547
548 static char *friendly_disk_name(const char *src, const char *vol) {
549 _cleanup_free_ char *description = NULL, *mount_point = NULL;
550 char *name_buffer = NULL;
551 int r;
552
553 assert(src);
554 assert(vol);
555
556 description = disk_description(src);
557 mount_point = disk_mount_point(vol);
558
559 /* If the description string is simply the volume name, then let's not show this twice */
560 if (description && streq(vol, description))
561 description = mfree(description);
562
563 if (mount_point && description)
564 r = asprintf(&name_buffer, "%s (%s) on %s", description, vol, mount_point);
565 else if (mount_point)
566 r = asprintf(&name_buffer, "%s on %s", vol, mount_point);
567 else if (description)
568 r = asprintf(&name_buffer, "%s (%s)", description, vol);
569 else
570 return strdup(vol);
571 if (r < 0)
572 return NULL;
573
574 return name_buffer;
575 }
576
577 static PassphraseType check_registered_passwords(struct crypt_device *cd) {
578 _cleanup_free_ bool *slots = NULL;
579 int slot_max;
580 PassphraseType passphrase_type = PASSPHRASE_NONE;
581
582 assert(cd);
583
584 if (!streq_ptr(crypt_get_type(cd), CRYPT_LUKS2)) {
585 log_debug("%s: not a LUKS2 device, only passphrases are supported", crypt_get_device_name(cd));
586 return PASSPHRASE_REGULAR;
587 }
588
589 /* Search all used slots */
590 assert_se((slot_max = crypt_keyslot_max(CRYPT_LUKS2)) > 0);
591 slots = new(bool, slot_max);
592 if (!slots)
593 return log_oom();
594
595 for (int slot = 0; slot < slot_max; slot++)
596 slots[slot] = IN_SET(crypt_keyslot_status(cd, slot), CRYPT_SLOT_ACTIVE, CRYPT_SLOT_ACTIVE_LAST);
597
598 /* Iterate all LUKS2 tokens and keep track of all their slots */
599 for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
600 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
601 const char *type;
602 JsonVariant *w, *z;
603 int tk;
604
605 tk = cryptsetup_get_token_as_json(cd, token, NULL, &v);
606 if (IN_SET(tk, -ENOENT, -EINVAL))
607 continue;
608 if (tk < 0) {
609 log_warning_errno(tk, "Failed to read JSON token data, ignoring: %m");
610 continue;
611 }
612
613 w = json_variant_by_key(v, "type");
614 if (!w || !json_variant_is_string(w)) {
615 log_warning("Token JSON data lacks type field, ignoring.");
616 continue;
617 }
618
619 type = json_variant_string(w);
620 if (STR_IN_SET(type, "systemd-recovery", "systemd-pkcs11", "systemd-fido2", "systemd-tpm2")) {
621
622 /* At least exists one recovery key */
623 if (streq(type, "systemd-recovery"))
624 passphrase_type |= PASSPHRASE_RECOVERY_KEY;
625
626 w = json_variant_by_key(v, "keyslots");
627 if (!w || !json_variant_is_array(w)) {
628 log_warning("Token JSON data lacks keyslots field, ignoring.");
629 continue;
630 }
631
632 JSON_VARIANT_ARRAY_FOREACH(z, w) {
633 unsigned u;
634 int at;
635
636 if (!json_variant_is_string(z)) {
637 log_warning("Token JSON data's keyslot field is not an array of strings, ignoring.");
638 continue;
639 }
640
641 at = safe_atou(json_variant_string(z), &u);
642 if (at < 0) {
643 log_warning_errno(at, "Token JSON data's keyslot field is not an integer formatted as string, ignoring.");
644 continue;
645 }
646
647 if (u >= (unsigned) slot_max) {
648 log_warning_errno(at, "Token JSON data's keyslot field exceeds the maximum value allowed, ignoring.");
649 continue;
650 }
651
652 slots[u] = false;
653 }
654 }
655 }
656
657 /* Check if any of the slots is not referenced by systemd tokens */
658 for (int slot = 0; slot < slot_max; slot++)
659 if (slots[slot]) {
660 passphrase_type |= PASSPHRASE_REGULAR;
661 break;
662 }
663
664 /* All the slots are referenced by systemd tokens, so if a recovery key is not enrolled,
665 * we will not be able to enter a passphrase. */
666 return passphrase_type;
667 }
668
669 static int get_password(
670 const char *vol,
671 const char *src,
672 usec_t until,
673 bool accept_cached,
674 PassphraseType passphrase_type,
675 char ***ret) {
676
677 _cleanup_free_ char *friendly = NULL, *text = NULL, *disk_path = NULL;
678 _cleanup_strv_free_erase_ char **passwords = NULL;
679 char *id;
680 int r = 0;
681 AskPasswordFlags flags = arg_ask_password_flags | ASK_PASSWORD_PUSH_CACHE;
682
683 assert(vol);
684 assert(src);
685 assert(ret);
686
687 if (arg_headless)
688 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Password querying disabled via 'headless' option.");
689
690 friendly = friendly_disk_name(src, vol);
691 if (!friendly)
692 return log_oom();
693
694 if (asprintf(&text, "Please enter %s for disk %s:", passphrase_type_to_string(passphrase_type), friendly) < 0)
695 return log_oom();
696
697 disk_path = cescape(src);
698 if (!disk_path)
699 return log_oom();
700
701 id = strjoina("cryptsetup:", disk_path);
702
703 r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", "cryptsetup.passphrase", until,
704 flags | (accept_cached*ASK_PASSWORD_ACCEPT_CACHED),
705 &passwords);
706 if (r < 0)
707 return log_error_errno(r, "Failed to query password: %m");
708
709 if (arg_verify) {
710 _cleanup_strv_free_erase_ char **passwords2 = NULL;
711
712 assert(strv_length(passwords) == 1);
713
714 if (asprintf(&text, "Please enter %s for disk %s (verification):", passphrase_type_to_string(passphrase_type), friendly) < 0)
715 return log_oom();
716
717 id = strjoina("cryptsetup-verification:", disk_path);
718
719 r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", "cryptsetup.passphrase", until, flags, &passwords2);
720 if (r < 0)
721 return log_error_errno(r, "Failed to query verification password: %m");
722
723 assert(strv_length(passwords2) == 1);
724
725 if (!streq(passwords[0], passwords2[0]))
726 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN),
727 "Passwords did not match, retrying.");
728 }
729
730 strv_uniq(passwords);
731
732 STRV_FOREACH(p, passwords) {
733 char *c;
734
735 if (strlen(*p)+1 >= arg_key_size)
736 continue;
737
738 /* Pad password if necessary */
739 c = new(char, arg_key_size);
740 if (!c)
741 return log_oom();
742
743 strncpy(c, *p, arg_key_size);
744 erase_and_free(*p);
745 *p = TAKE_PTR(c);
746 }
747
748 *ret = TAKE_PTR(passwords);
749
750 return 0;
751 }
752
753 static int attach_tcrypt(
754 struct crypt_device *cd,
755 const char *name,
756 const char *key_file,
757 const void *key_data,
758 size_t key_data_size,
759 char **passwords,
760 uint32_t flags) {
761
762 int r = 0;
763 _cleanup_(erase_and_freep) char *passphrase = NULL;
764 struct crypt_params_tcrypt params = {
765 .flags = CRYPT_TCRYPT_LEGACY_MODES,
766 .keyfiles = (const char **)arg_tcrypt_keyfiles,
767 .keyfiles_count = strv_length(arg_tcrypt_keyfiles)
768 };
769
770 assert(cd);
771 assert(name);
772 assert(key_file || key_data || !strv_isempty(passwords));
773
774 if (arg_pkcs11_uri || arg_pkcs11_uri_auto || arg_fido2_device || arg_fido2_device_auto || arg_tpm2_device || arg_tpm2_device_auto)
775 /* Ask for a regular password */
776 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN),
777 "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
778
779 if (arg_tcrypt_hidden)
780 params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
781
782 if (arg_tcrypt_system)
783 params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
784
785 if (arg_tcrypt_veracrypt)
786 params.flags |= CRYPT_TCRYPT_VERA_MODES;
787
788 if (key_data) {
789 params.passphrase = key_data;
790 params.passphrase_size = key_data_size;
791 } else {
792 if (key_file) {
793 r = read_one_line_file(key_file, &passphrase);
794 if (r < 0) {
795 log_error_errno(r, "Failed to read password file '%s': %m", key_file);
796 return -EAGAIN; /* log with the actual error, but return EAGAIN */
797 }
798
799 params.passphrase = passphrase;
800 } else
801 params.passphrase = passwords[0];
802
803 params.passphrase_size = strlen(params.passphrase);
804 }
805
806 r = crypt_load(cd, CRYPT_TCRYPT, &params);
807 if (r < 0) {
808 if (r == -EPERM) {
809 if (key_data)
810 log_error_errno(r, "Failed to activate using discovered key. (Key not correct?)");
811
812 if (key_file)
813 log_error_errno(r, "Failed to activate using password file '%s'. (Key data not correct?)", key_file);
814
815 return -EAGAIN; /* log the actual error, but return EAGAIN */
816 }
817
818 return log_error_errno(r, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd));
819 }
820
821 r = crypt_activate_by_volume_key(cd, name, NULL, 0, flags);
822 if (r < 0)
823 return log_error_errno(r, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd));
824
825 return 0;
826 }
827
828 static char *make_bindname(const char *volume) {
829 char *s;
830
831 if (asprintf(&s, "@%" PRIx64"/cryptsetup/%s", random_u64(), volume) < 0)
832 return NULL;
833
834 return s;
835 }
836
837 static int make_security_device_monitor(
838 sd_event **ret_event,
839 sd_device_monitor **ret_monitor) {
840 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
841 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
842 int r;
843
844 assert(ret_event);
845 assert(ret_monitor);
846
847 /* Waits for a device with "security-device" tag to show up in udev */
848
849 r = sd_event_default(&event);
850 if (r < 0)
851 return log_error_errno(r, "Failed to allocate event loop: %m");
852
853 r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
854 if (r < 0)
855 return log_error_errno(r, "Failed to install timeout event source: %m");
856
857 r = sd_device_monitor_new(&monitor);
858 if (r < 0)
859 return log_error_errno(r, "Failed to allocate device monitor: %m");
860
861 r = sd_device_monitor_filter_add_match_tag(monitor, "security-device");
862 if (r < 0)
863 return log_error_errno(r, "Failed to configure device monitor: %m");
864
865 r = sd_device_monitor_attach_event(monitor, event);
866 if (r < 0)
867 return log_error_errno(r, "Failed to attach device monitor: %m");
868
869 r = sd_device_monitor_start(monitor, NULL, NULL);
870 if (r < 0)
871 return log_error_errno(r, "Failed to start device monitor: %m");
872
873 *ret_event = TAKE_PTR(event);
874 *ret_monitor = TAKE_PTR(monitor);
875 return 0;
876 }
877
878 static int run_security_device_monitor(
879 sd_event *event,
880 sd_device_monitor *monitor) {
881 bool processed = false;
882 int r;
883
884 assert(event);
885 assert(monitor);
886
887 /* Runs the event loop for the device monitor until either something happens, or the time-out is
888 * hit. */
889
890 for (;;) {
891 int x;
892
893 r = sd_event_get_exit_code(event, &x);
894 if (r < 0) {
895 if (r != -ENODATA)
896 return log_error_errno(r, "Failed to query exit code from event loop: %m");
897
898 /* On ENODATA we aren't told to exit yet. */
899 } else {
900 assert(x == -ETIMEDOUT);
901 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
902 "Timed out waiting for security device, aborting security device based authentication attempt.");
903 }
904
905 /* Wait for one event, and then eat all subsequent events until there are no further ones */
906 r = sd_event_run(event, processed ? 0 : UINT64_MAX);
907 if (r < 0)
908 return log_error_errno(r, "Failed to run event loop: %m");
909 if (r == 0) /* no events queued anymore */
910 return 0;
911
912 processed = true;
913 }
914 }
915
916 static bool libcryptsetup_plugins_support(void) {
917 #if HAVE_LIBCRYPTSETUP_PLUGINS
918 int r;
919
920 /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
921 r = getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
922 if (r < 0 && r != -ENXIO)
923 log_debug_errno(r, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
924 if (r == 0)
925 return false;
926
927 return crypt_token_external_path();
928 #else
929 return false;
930 #endif
931 }
932
933 #if HAVE_LIBCRYPTSETUP_PLUGINS
934 static int acquire_pins_from_env_variable(char ***ret_pins) {
935 _cleanup_(erase_and_freep) char *envpin = NULL;
936 _cleanup_strv_free_erase_ char **pins = NULL;
937 int r;
938
939 assert(ret_pins);
940
941 r = getenv_steal_erase("PIN", &envpin);
942 if (r < 0)
943 return log_error_errno(r, "Failed to acquire PIN from environment: %m");
944 if (r > 0) {
945 pins = strv_new(envpin);
946 if (!pins)
947 return log_oom();
948 }
949
950 *ret_pins = TAKE_PTR(pins);
951
952 return 0;
953 }
954 #endif
955
956 static int crypt_activate_by_token_pin_ask_password(
957 struct crypt_device *cd,
958 const char *name,
959 const char *type,
960 usec_t until,
961 bool headless,
962 void *usrptr,
963 uint32_t activation_flags,
964 const char *message,
965 const char *key_name,
966 const char *credential_name) {
967
968 #if HAVE_LIBCRYPTSETUP_PLUGINS
969 AskPasswordFlags flags = ASK_PASSWORD_PUSH_CACHE | ASK_PASSWORD_ACCEPT_CACHED;
970 _cleanup_strv_free_erase_ char **pins = NULL;
971 int r;
972
973 r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, NULL, 0, usrptr, activation_flags);
974 if (r > 0) /* returns unlocked keyslot id on success */
975 r = 0;
976 if (r != -ENOANO) /* needs pin or pin is wrong */
977 return r;
978
979 r = acquire_pins_from_env_variable(&pins);
980 if (r < 0)
981 return r;
982
983 STRV_FOREACH(p, pins) {
984 r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), usrptr, activation_flags);
985 if (r > 0) /* returns unlocked keyslot id on success */
986 r = 0;
987 if (r != -ENOANO) /* needs pin or pin is wrong */
988 return r;
989 }
990
991 if (headless)
992 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
993
994 for (;;) {
995 pins = strv_free_erase(pins);
996 r = ask_password_auto(message, "drive-harddisk", NULL, key_name, credential_name, until, flags, &pins);
997 if (r < 0)
998 return r;
999
1000 STRV_FOREACH(p, pins) {
1001 r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), usrptr, activation_flags);
1002 if (r > 0) /* returns unlocked keyslot id on success */
1003 r = 0;
1004 if (r != -ENOANO) /* needs pin or pin is wrong */
1005 return r;
1006 }
1007
1008 flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
1009 }
1010 return r;
1011 #else
1012 return -EOPNOTSUPP;
1013 #endif
1014 }
1015
1016 static int attach_luks2_by_fido2_via_plugin(
1017 struct crypt_device *cd,
1018 const char *name,
1019 usec_t until,
1020 bool headless,
1021 void *usrptr,
1022 uint32_t activation_flags) {
1023
1024 return crypt_activate_by_token_pin_ask_password(
1025 cd,
1026 name,
1027 "systemd-fido2",
1028 until,
1029 headless,
1030 usrptr,
1031 activation_flags,
1032 "Please enter security token PIN:",
1033 "fido2-pin",
1034 "cryptsetup.fido2-pin");
1035 }
1036
1037 static int attach_luks_or_plain_or_bitlk_by_fido2(
1038 struct crypt_device *cd,
1039 const char *name,
1040 const char *key_file,
1041 const void *key_data,
1042 size_t key_data_size,
1043 usec_t until,
1044 uint32_t flags,
1045 bool pass_volume_key) {
1046
1047 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1048 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1049 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1050 _cleanup_free_ void *discovered_salt = NULL, *discovered_cid = NULL;
1051 size_t discovered_salt_size, discovered_cid_size, decrypted_key_size, cid_size = 0;
1052 _cleanup_free_ char *friendly = NULL, *discovered_rp_id = NULL;
1053 int keyslot = arg_key_slot, r;
1054 const char *rp_id = NULL;
1055 const void *cid = NULL;
1056 Fido2EnrollFlags required;
1057 bool use_libcryptsetup_plugin = libcryptsetup_plugins_support();
1058
1059 assert(cd);
1060 assert(name);
1061 assert(arg_fido2_device || arg_fido2_device_auto);
1062
1063 if (arg_fido2_cid) {
1064 if (!key_file && !key_data)
1065 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1066 "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
1067
1068 rp_id = arg_fido2_rp_id;
1069 cid = arg_fido2_cid;
1070 cid_size = arg_fido2_cid_size;
1071
1072 /* For now and for compatibility, if the user explicitly configured FIDO2 support and we do
1073 * not read FIDO2 metadata off the LUKS2 header, default to the systemd 248 logic, where we
1074 * use PIN + UP when needed, and do not configure UV at all. Eventually, we should make this
1075 * explicitly configurable. */
1076 required = FIDO2ENROLL_PIN_IF_NEEDED | FIDO2ENROLL_UP_IF_NEEDED | FIDO2ENROLL_UV_OMIT;
1077 } else if (!use_libcryptsetup_plugin) {
1078 r = find_fido2_auto_data(
1079 cd,
1080 &discovered_rp_id,
1081 &discovered_salt,
1082 &discovered_salt_size,
1083 &discovered_cid,
1084 &discovered_cid_size,
1085 &keyslot,
1086 &required);
1087
1088 if (IN_SET(r, -ENOTUNIQ, -ENXIO))
1089 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1090 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1091 if (r < 0)
1092 return r;
1093
1094 if ((required & (FIDO2ENROLL_PIN | FIDO2ENROLL_UP | FIDO2ENROLL_UV)) && arg_headless)
1095 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG),
1096 "Local verification is required to unlock this volume, but the 'headless' parameter was set.");
1097
1098 rp_id = discovered_rp_id;
1099 key_data = discovered_salt;
1100 key_data_size = discovered_salt_size;
1101 cid = discovered_cid;
1102 cid_size = discovered_cid_size;
1103 }
1104
1105 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1106 if (!friendly)
1107 return log_oom();
1108
1109 for (;;) {
1110 if (use_libcryptsetup_plugin && !arg_fido2_cid) {
1111 r = attach_luks2_by_fido2_via_plugin(cd, name, until, arg_headless, arg_fido2_device, flags);
1112 if (IN_SET(r, -ENOTUNIQ, -ENXIO, -ENOENT))
1113 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1114 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1115
1116 } else {
1117 r = acquire_fido2_key(
1118 name,
1119 friendly,
1120 arg_fido2_device,
1121 rp_id,
1122 cid, cid_size,
1123 key_file, arg_keyfile_size, arg_keyfile_offset,
1124 key_data, key_data_size,
1125 until,
1126 arg_headless,
1127 required,
1128 &decrypted_key, &decrypted_key_size,
1129 arg_ask_password_flags);
1130 if (r >= 0)
1131 break;
1132 }
1133
1134 if (r != -EAGAIN) /* EAGAIN means: token not found */
1135 return r;
1136
1137 if (!monitor) {
1138 /* We didn't find the token. In this case, watch for it via udev. Let's
1139 * create an event loop and monitor first. */
1140
1141 assert(!event);
1142
1143 r = make_security_device_monitor(&event, &monitor);
1144 if (r < 0)
1145 return r;
1146
1147 log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly);
1148
1149 /* Let's immediately rescan in case the token appeared in the time we needed
1150 * to create and configure the monitor */
1151 continue;
1152 }
1153
1154 r = run_security_device_monitor(event, monitor);
1155 if (r < 0)
1156 return r;
1157
1158 log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
1159 }
1160
1161 if (pass_volume_key)
1162 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
1163 else {
1164 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
1165
1166 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1167
1168 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1169 if (r < 0)
1170 return log_oom();
1171
1172 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
1173 }
1174 if (r == -EPERM) {
1175 log_error_errno(r, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
1176 return -EAGAIN; /* log actual error, but return EAGAIN */
1177 }
1178 if (r < 0)
1179 return log_error_errno(r, "Failed to activate with FIDO2 acquired key: %m");
1180
1181 return 0;
1182 }
1183
1184 static int attach_luks2_by_pkcs11_via_plugin(
1185 struct crypt_device *cd,
1186 const char *name,
1187 const char *friendly_name,
1188 usec_t until,
1189 bool headless,
1190 uint32_t flags) {
1191
1192 #if HAVE_LIBCRYPTSETUP_PLUGINS
1193 int r;
1194
1195 if (!streq_ptr(crypt_get_type(cd), CRYPT_LUKS2))
1196 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Automatic PKCS#11 metadata requires LUKS2 device.");
1197
1198 systemd_pkcs11_plugin_params params = {
1199 .friendly_name = friendly_name,
1200 .until = until,
1201 .headless = headless
1202 };
1203
1204 r = crypt_activate_by_token_pin(cd, name, "systemd-pkcs11", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
1205 if (r > 0) /* returns unlocked keyslot id on success */
1206 r = 0;
1207
1208 return r;
1209 #else
1210 return -EOPNOTSUPP;
1211 #endif
1212 }
1213
1214 static int attach_luks_or_plain_or_bitlk_by_pkcs11(
1215 struct crypt_device *cd,
1216 const char *name,
1217 const char *key_file,
1218 const void *key_data,
1219 size_t key_data_size,
1220 usec_t until,
1221 uint32_t flags,
1222 bool pass_volume_key) {
1223
1224 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1225 _cleanup_free_ char *friendly = NULL, *discovered_uri = NULL;
1226 size_t decrypted_key_size = 0, discovered_key_size = 0;
1227 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1228 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1229 _cleanup_free_ void *discovered_key = NULL;
1230 int keyslot = arg_key_slot, r;
1231 const char *uri = NULL;
1232 bool use_libcryptsetup_plugin = libcryptsetup_plugins_support();
1233
1234 assert(cd);
1235 assert(name);
1236 assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
1237
1238 if (arg_pkcs11_uri_auto) {
1239 if (!use_libcryptsetup_plugin) {
1240 r = find_pkcs11_auto_data(cd, &discovered_uri, &discovered_key, &discovered_key_size, &keyslot);
1241 if (IN_SET(r, -ENOTUNIQ, -ENXIO))
1242 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1243 "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1244 if (r < 0)
1245 return r;
1246
1247 uri = discovered_uri;
1248 key_data = discovered_key;
1249 key_data_size = discovered_key_size;
1250 }
1251 } else {
1252 uri = arg_pkcs11_uri;
1253
1254 if (!key_file && !key_data)
1255 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing.");
1256 }
1257
1258 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1259 if (!friendly)
1260 return log_oom();
1261
1262 for (;;) {
1263 if (use_libcryptsetup_plugin && arg_pkcs11_uri_auto)
1264 r = attach_luks2_by_pkcs11_via_plugin(cd, name, friendly, until, arg_headless, flags);
1265 else {
1266 r = decrypt_pkcs11_key(
1267 name,
1268 friendly,
1269 uri,
1270 key_file, arg_keyfile_size, arg_keyfile_offset,
1271 key_data, key_data_size,
1272 until,
1273 arg_headless,
1274 &decrypted_key, &decrypted_key_size);
1275 if (r >= 0)
1276 break;
1277 }
1278
1279 if (r != -EAGAIN) /* EAGAIN means: token not found */
1280 return r;
1281
1282 if (!monitor) {
1283 /* We didn't find the token. In this case, watch for it via udev. Let's
1284 * create an event loop and monitor first. */
1285
1286 assert(!event);
1287
1288 r = make_security_device_monitor(&event, &monitor);
1289 if (r < 0)
1290 return r;
1291
1292 log_notice("Security token %s not present for unlocking volume %s, please plug it in.",
1293 uri, friendly);
1294
1295 /* Let's immediately rescan in case the token appeared in the time we needed
1296 * to create and configure the monitor */
1297 continue;
1298 }
1299
1300 r = run_security_device_monitor(event, monitor);
1301 if (r < 0)
1302 return r;
1303
1304 log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
1305 }
1306 assert(decrypted_key);
1307
1308 if (pass_volume_key)
1309 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
1310 else {
1311 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
1312
1313 /* Before using this key as passphrase we base64 encode it. Why? For compatibility
1314 * with homed's PKCS#11 hookup: there we want to use the key we acquired through
1315 * PKCS#11 for other authentication/decryption mechanisms too, and some of them do
1316 * not take arbitrary binary blobs, but require NUL-terminated strings — most
1317 * importantly UNIX password hashes. Hence, for compatibility we want to use a string
1318 * without embedded NUL here too, and that's easiest to generate from a binary blob
1319 * via base64 encoding. */
1320
1321 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1322 if (r < 0)
1323 return log_oom();
1324
1325 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
1326 }
1327 if (r == -EPERM) {
1328 log_error_errno(r, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
1329 return -EAGAIN; /* log actual error, but return EAGAIN */
1330 }
1331 if (r < 0)
1332 return log_error_errno(r, "Failed to activate with PKCS#11 acquired key: %m");
1333
1334 return 0;
1335 }
1336
1337 static int make_tpm2_device_monitor(
1338 sd_event **ret_event,
1339 sd_device_monitor **ret_monitor) {
1340
1341 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1342 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1343 int r;
1344
1345 assert(ret_event);
1346 assert(ret_monitor);
1347
1348 r = sd_event_default(&event);
1349 if (r < 0)
1350 return log_error_errno(r, "Failed to allocate event loop: %m");
1351
1352 r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
1353 if (r < 0)
1354 return log_error_errno(r, "Failed to install timeout event source: %m");
1355
1356 r = sd_device_monitor_new(&monitor);
1357 if (r < 0)
1358 return log_error_errno(r, "Failed to allocate device monitor: %m");
1359
1360 r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "tpmrm", NULL);
1361 if (r < 0)
1362 return log_error_errno(r, "Failed to configure device monitor: %m");
1363
1364 r = sd_device_monitor_attach_event(monitor, event);
1365 if (r < 0)
1366 return log_error_errno(r, "Failed to attach device monitor: %m");
1367
1368 r = sd_device_monitor_start(monitor, NULL, NULL);
1369 if (r < 0)
1370 return log_error_errno(r, "Failed to start device monitor: %m");
1371
1372 *ret_event = TAKE_PTR(event);
1373 *ret_monitor = TAKE_PTR(monitor);
1374 return 0;
1375 }
1376
1377 static int attach_luks2_by_tpm2_via_plugin(
1378 struct crypt_device *cd,
1379 const char *name,
1380 usec_t until,
1381 bool headless,
1382 uint32_t flags) {
1383
1384 #if HAVE_LIBCRYPTSETUP_PLUGINS
1385 systemd_tpm2_plugin_params params = {
1386 .search_pcr_mask = arg_tpm2_pcr_mask,
1387 .device = arg_tpm2_device
1388 };
1389
1390 if (!libcryptsetup_plugins_support())
1391 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1392 "Libcryptsetup has external plugins support disabled.");
1393
1394 return crypt_activate_by_token_pin_ask_password(
1395 cd,
1396 name,
1397 "systemd-tpm2",
1398 until,
1399 headless,
1400 &params,
1401 flags,
1402 "Please enter TPM2 PIN:",
1403 "tpm2-pin",
1404 "cryptsetup.tpm2-pin");
1405 #else
1406 return -EOPNOTSUPP;
1407 #endif
1408 }
1409
1410 static int attach_luks_or_plain_or_bitlk_by_tpm2(
1411 struct crypt_device *cd,
1412 const char *name,
1413 const char *key_file,
1414 const void *key_data,
1415 size_t key_data_size,
1416 usec_t until,
1417 uint32_t flags,
1418 bool pass_volume_key) {
1419
1420 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1421 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1422 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1423 _cleanup_free_ char *friendly = NULL;
1424 int keyslot = arg_key_slot, r;
1425 size_t decrypted_key_size;
1426
1427 assert(cd);
1428 assert(name);
1429 assert(arg_tpm2_device || arg_tpm2_device_auto);
1430
1431 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1432 if (!friendly)
1433 return log_oom();
1434
1435 for (;;) {
1436 if (key_file || key_data) {
1437 /* If key data is specified, use that */
1438
1439 r = acquire_tpm2_key(
1440 name,
1441 arg_tpm2_device,
1442 arg_tpm2_pcr_mask == UINT32_MAX ? TPM2_PCR_MASK_DEFAULT : arg_tpm2_pcr_mask,
1443 UINT16_MAX,
1444 0,
1445 key_file, arg_keyfile_size, arg_keyfile_offset,
1446 key_data, key_data_size,
1447 NULL, 0, /* we don't know the policy hash */
1448 arg_tpm2_pin,
1449 until,
1450 arg_headless,
1451 arg_ask_password_flags,
1452 &decrypted_key, &decrypted_key_size);
1453 if (r >= 0)
1454 break;
1455 if (IN_SET(r, -EACCES, -ENOLCK))
1456 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
1457 if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
1458 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");
1459 /* EAGAIN means: no tpm2 chip found */
1460 if (r != -EAGAIN) {
1461 log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
1462 return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1463 }
1464 } else {
1465 r = attach_luks2_by_tpm2_via_plugin(cd, name, until, arg_headless, flags);
1466 if (r >= 0)
1467 return 0;
1468 /* EAGAIN means: no tpm2 chip found
1469 * EOPNOTSUPP means: no libcryptsetup plugins support */
1470 if (r == -ENXIO)
1471 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
1472 "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
1473 if (r == -ENOENT)
1474 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1475 "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
1476 if (!IN_SET(r, -EOPNOTSUPP, -EAGAIN)) {
1477 log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
1478 return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1479 }
1480 }
1481
1482 if (r == -EOPNOTSUPP) { /* Plugin not available, let's process TPM2 stuff right here instead */
1483 _cleanup_free_ void *blob = NULL, *policy_hash = NULL;
1484 size_t blob_size, policy_hash_size;
1485 bool found_some = false;
1486 int token = 0; /* first token to look at */
1487
1488 /* If no key data is specified, look for it in the header. In order to support
1489 * software upgrades we'll iterate through all suitable tokens, maybe one of them
1490 * works. */
1491
1492 for (;;) {
1493 uint32_t pcr_mask;
1494 uint16_t pcr_bank, primary_alg;
1495 TPM2Flags tpm2_flags;
1496
1497 r = find_tpm2_auto_data(
1498 cd,
1499 arg_tpm2_pcr_mask, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1500 token, /* search for the token with this index, or any later index than this */
1501 &pcr_mask,
1502 &pcr_bank,
1503 &primary_alg,
1504 &blob, &blob_size,
1505 &policy_hash, &policy_hash_size,
1506 &keyslot,
1507 &token,
1508 &tpm2_flags);
1509 if (r == -ENXIO)
1510 /* No further TPM2 tokens found in the LUKS2 header. */
1511 return log_full_errno(found_some ? LOG_NOTICE : LOG_DEBUG,
1512 SYNTHETIC_ERRNO(EAGAIN),
1513 found_some
1514 ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
1515 : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
1516 if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
1517 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");
1518 if (r < 0)
1519 return r;
1520
1521 found_some = true;
1522
1523 r = acquire_tpm2_key(
1524 name,
1525 arg_tpm2_device,
1526 pcr_mask,
1527 pcr_bank,
1528 primary_alg,
1529 NULL, 0, 0, /* no key file */
1530 blob, blob_size,
1531 policy_hash, policy_hash_size,
1532 tpm2_flags,
1533 until,
1534 arg_headless,
1535 arg_ask_password_flags,
1536 &decrypted_key, &decrypted_key_size);
1537 if (IN_SET(r, -EACCES, -ENOLCK))
1538 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
1539 if (r != -EPERM)
1540 break;
1541
1542 token++; /* try a different token next time */
1543 }
1544
1545 if (r >= 0)
1546 break;
1547 /* EAGAIN means: no tpm2 chip found */
1548 if (r != -EAGAIN) {
1549 log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
1550 return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1551 }
1552 }
1553
1554 if (!monitor) {
1555 /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
1556 * an event loop and monitor first. */
1557
1558 assert(!event);
1559
1560 if (is_efi_boot() && !efi_has_tpm2())
1561 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
1562 "No TPM2 hardware discovered and EFI firmware does not see it either, falling back to traditional unlocking.");
1563
1564 r = make_tpm2_device_monitor(&event, &monitor);
1565 if (r < 0)
1566 return r;
1567
1568 log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly);
1569
1570 /* Let's immediately rescan in case the device appeared in the time we needed
1571 * to create and configure the monitor */
1572 continue;
1573 }
1574
1575 r = run_security_device_monitor(event, monitor);
1576 if (r < 0)
1577 return r;
1578
1579 log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
1580 }
1581 assert(decrypted_key);
1582
1583 if (pass_volume_key)
1584 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
1585 else {
1586 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
1587
1588 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1589
1590 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1591 if (r < 0)
1592 return log_oom();
1593
1594 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
1595 }
1596 if (r == -EPERM) {
1597 log_error_errno(r, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
1598 return -EAGAIN; /* log actual error, but return EAGAIN */
1599 }
1600 if (r < 0)
1601 return log_error_errno(r, "Failed to activate with TPM2 acquired key: %m");
1602
1603 return 0;
1604 }
1605
1606 static int attach_luks_or_plain_or_bitlk_by_key_data(
1607 struct crypt_device *cd,
1608 const char *name,
1609 const void *key_data,
1610 size_t key_data_size,
1611 uint32_t flags,
1612 bool pass_volume_key) {
1613
1614 int r;
1615
1616 assert(cd);
1617 assert(name);
1618 assert(key_data);
1619
1620 if (pass_volume_key)
1621 r = crypt_activate_by_volume_key(cd, name, key_data, key_data_size, flags);
1622 else
1623 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, key_data, key_data_size, flags);
1624 if (r == -EPERM) {
1625 log_error_errno(r, "Failed to activate. (Key incorrect?)");
1626 return -EAGAIN; /* Log actual error, but return EAGAIN */
1627 }
1628 if (r < 0)
1629 return log_error_errno(r, "Failed to activate: %m");
1630
1631 return 0;
1632 }
1633
1634 static int attach_luks_or_plain_or_bitlk_by_key_file(
1635 struct crypt_device *cd,
1636 const char *name,
1637 const char *key_file,
1638 uint32_t flags,
1639 bool pass_volume_key) {
1640
1641 _cleanup_(erase_and_freep) char *kfdata = NULL;
1642 _cleanup_free_ char *bindname = NULL;
1643 size_t kfsize;
1644 int r;
1645
1646 assert(cd);
1647 assert(name);
1648 assert(key_file);
1649
1650 /* If we read the key via AF_UNIX, make this client recognizable */
1651 bindname = make_bindname(name);
1652 if (!bindname)
1653 return log_oom();
1654
1655 r = read_full_file_full(
1656 AT_FDCWD, key_file,
1657 arg_keyfile_offset == 0 ? UINT64_MAX : arg_keyfile_offset,
1658 arg_keyfile_size == 0 ? SIZE_MAX : arg_keyfile_size,
1659 READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
1660 bindname,
1661 &kfdata, &kfsize);
1662 if (r == -E2BIG) {
1663 log_error_errno(r, "Failed to activate, key file '%s' too large.", key_file);
1664 return -EAGAIN;
1665 }
1666 if (r == -ENOENT) {
1667 log_error_errno(r, "Failed to activate, key file '%s' missing.", key_file);
1668 return -EAGAIN; /* Log actual error, but return EAGAIN */
1669 }
1670 if (r < 0)
1671 return log_error_errno(r, "Failed to read key file '%s': %m", key_file);
1672
1673 if (pass_volume_key)
1674 r = crypt_activate_by_volume_key(cd, name, kfdata, kfsize, flags);
1675 else
1676 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, kfdata, kfsize, flags);
1677 if (r == -EPERM) {
1678 log_error_errno(r, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file);
1679 return -EAGAIN; /* Log actual error, but return EAGAIN */
1680 }
1681 if (r < 0)
1682 return log_error_errno(r, "Failed to activate with key file '%s': %m", key_file);
1683
1684 return 0;
1685 }
1686
1687 static int attach_luks_or_plain_or_bitlk_by_passphrase(
1688 struct crypt_device *cd,
1689 const char *name,
1690 char **passwords,
1691 uint32_t flags,
1692 bool pass_volume_key) {
1693
1694 int r;
1695
1696 assert(cd);
1697 assert(name);
1698
1699 r = -EINVAL;
1700 STRV_FOREACH(p, passwords) {
1701 if (pass_volume_key)
1702 r = crypt_activate_by_volume_key(cd, name, *p, arg_key_size, flags);
1703 else
1704 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, *p, strlen(*p), flags);
1705 if (r >= 0)
1706 break;
1707 }
1708 if (r == -EPERM) {
1709 log_error_errno(r, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
1710 return -EAGAIN; /* log actual error, but return EAGAIN */
1711 }
1712 if (r < 0)
1713 return log_error_errno(r, "Failed to activate with specified passphrase: %m");
1714
1715 return 0;
1716 }
1717
1718 static int attach_luks_or_plain_or_bitlk(
1719 struct crypt_device *cd,
1720 const char *name,
1721 const char *key_file,
1722 const void *key_data,
1723 size_t key_data_size,
1724 char **passwords,
1725 uint32_t flags,
1726 usec_t until) {
1727
1728 bool pass_volume_key = false;
1729 int r;
1730
1731 assert(cd);
1732 assert(name);
1733
1734 if ((!arg_type && !crypt_get_type(cd)) || streq_ptr(arg_type, CRYPT_PLAIN)) {
1735 struct crypt_params_plain params = {
1736 .offset = arg_offset,
1737 .skip = arg_skip,
1738 .sector_size = arg_sector_size,
1739 };
1740 const char *cipher, *cipher_mode;
1741 _cleanup_free_ char *truncated_cipher = NULL;
1742
1743 if (streq_ptr(arg_hash, "plain"))
1744 /* plain isn't a real hash type. it just means "use no hash" */
1745 params.hash = NULL;
1746 else if (arg_hash)
1747 params.hash = arg_hash;
1748 else if (!key_file)
1749 /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
1750 * file is provided */
1751 params.hash = "ripemd160";
1752
1753 if (arg_cipher) {
1754 size_t l;
1755
1756 l = strcspn(arg_cipher, "-");
1757 truncated_cipher = strndup(arg_cipher, l);
1758 if (!truncated_cipher)
1759 return log_oom();
1760
1761 cipher = truncated_cipher;
1762 cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain";
1763 } else {
1764 cipher = "aes";
1765 cipher_mode = "cbc-essiv:sha256";
1766 }
1767
1768 /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
1769 arg_keyfile_size = arg_key_size;
1770
1771 /* In contrast to what the name crypt_format() might suggest this doesn't actually format
1772 * anything, it just configures encryption parameters when used for plain mode. */
1773 r = crypt_format(cd, CRYPT_PLAIN, cipher, cipher_mode, NULL, NULL, arg_keyfile_size, &params);
1774 if (r < 0)
1775 return log_error_errno(r, "Loading of cryptographic parameters failed: %m");
1776
1777 /* hash == NULL implies the user passed "plain" */
1778 pass_volume_key = !params.hash;
1779 }
1780
1781 log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
1782 crypt_get_cipher(cd),
1783 crypt_get_cipher_mode(cd),
1784 crypt_get_volume_key_size(cd)*8,
1785 crypt_get_device_name(cd));
1786
1787 if (arg_tpm2_device || arg_tpm2_device_auto)
1788 return attach_luks_or_plain_or_bitlk_by_tpm2(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
1789 if (arg_fido2_device || arg_fido2_device_auto)
1790 return attach_luks_or_plain_or_bitlk_by_fido2(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
1791 if (arg_pkcs11_uri || arg_pkcs11_uri_auto)
1792 return attach_luks_or_plain_or_bitlk_by_pkcs11(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
1793 if (key_data)
1794 return attach_luks_or_plain_or_bitlk_by_key_data(cd, name, key_data, key_data_size, flags, pass_volume_key);
1795 if (key_file)
1796 return attach_luks_or_plain_or_bitlk_by_key_file(cd, name, key_file, flags, pass_volume_key);
1797
1798 return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
1799 }
1800
1801 static int help(void) {
1802 _cleanup_free_ char *link = NULL;
1803 int r;
1804
1805 r = terminal_urlify_man("systemd-cryptsetup@.service", "8", &link);
1806 if (r < 0)
1807 return log_oom();
1808
1809 printf("%s attach VOLUME SOURCEDEVICE [KEY-FILE] [OPTIONS]\n"
1810 "%s detach VOLUME\n\n"
1811 "Attaches or detaches an encrypted block device.\n"
1812 "\nSee the %s for details.\n",
1813 program_invocation_short_name,
1814 program_invocation_short_name,
1815 link);
1816
1817 return 0;
1818 }
1819
1820 static uint32_t determine_flags(void) {
1821 uint32_t flags = 0;
1822
1823 if (arg_readonly)
1824 flags |= CRYPT_ACTIVATE_READONLY;
1825
1826 if (arg_discards)
1827 flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
1828
1829 if (arg_same_cpu_crypt)
1830 flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
1831
1832 if (arg_submit_from_crypt_cpus)
1833 flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
1834
1835 if (arg_no_read_workqueue)
1836 flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
1837
1838 if (arg_no_write_workqueue)
1839 flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
1840
1841 #ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
1842 /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
1843 /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
1844 flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF;
1845 #endif
1846
1847 return flags;
1848 }
1849
1850 static void remove_and_erasep(const char **p) {
1851 int r;
1852
1853 if (!*p)
1854 return;
1855
1856 r = unlinkat_deallocate(AT_FDCWD, *p, UNLINK_ERASE);
1857 if (r < 0 && r != -ENOENT)
1858 log_warning_errno(r, "Unable to erase key file '%s', ignoring: %m", *p);
1859 }
1860
1861 static int run(int argc, char *argv[]) {
1862 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1863 const char *verb;
1864 int r;
1865
1866 if (argv_looks_like_help(argc, argv))
1867 return help();
1868
1869 if (argc < 3)
1870 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1871 "This program requires at least two arguments.");
1872
1873 log_setup();
1874
1875 cryptsetup_enable_logging(NULL);
1876
1877 umask(0022);
1878
1879 verb = argv[1];
1880
1881 if (streq(verb, "attach")) {
1882 _unused_ _cleanup_(remove_and_erasep) const char *destroy_key_file = NULL;
1883 _cleanup_(erase_and_freep) void *key_data = NULL;
1884 const char *volume, *source, *key_file, *options;
1885 crypt_status_info status;
1886 size_t key_data_size = 0;
1887 uint32_t flags = 0;
1888 unsigned tries;
1889 usec_t until;
1890 PassphraseType passphrase_type = PASSPHRASE_NONE;
1891
1892 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [KEY-FILE] [OPTIONS] */
1893
1894 if (argc < 4)
1895 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "attach requires at least two arguments.");
1896
1897 volume = argv[2];
1898 source = argv[3];
1899 key_file = mangle_none(argc >= 5 ? argv[4] : NULL);
1900 options = mangle_none(argc >= 6 ? argv[5] : NULL);
1901
1902 if (!filename_is_valid(volume))
1903 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
1904
1905 if (key_file && !path_is_absolute(key_file)) {
1906 log_warning("Password file path '%s' is not absolute. Ignoring.", key_file);
1907 key_file = NULL;
1908 }
1909
1910 if (options) {
1911 r = parse_options(options);
1912 if (r < 0)
1913 return r;
1914 }
1915
1916 log_debug("%s %s ← %s type=%s cipher=%s", __func__,
1917 volume, source, strempty(arg_type), strempty(arg_cipher));
1918
1919 /* A delicious drop of snake oil */
1920 (void) mlockall(MCL_FUTURE);
1921
1922 if (!key_file) {
1923 _cleanup_free_ char *bindname = NULL;
1924 const char *fn;
1925
1926 bindname = make_bindname(volume);
1927 if (!bindname)
1928 return log_oom();
1929
1930 /* If a key file is not explicitly specified, search for a key in a well defined
1931 * search path, and load it. */
1932
1933 fn = strjoina(volume, ".key");
1934 r = find_key_file(
1935 fn,
1936 STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"),
1937 bindname,
1938 &key_data, &key_data_size);
1939 if (r < 0)
1940 return r;
1941 if (r > 0)
1942 log_debug("Automatically discovered key for volume '%s'.", volume);
1943 } else if (arg_keyfile_erase)
1944 destroy_key_file = key_file; /* let's get this baby erased when we leave */
1945
1946 if (arg_header) {
1947 log_debug("LUKS header: %s", arg_header);
1948 r = crypt_init(&cd, arg_header);
1949 } else
1950 r = crypt_init(&cd, source);
1951 if (r < 0)
1952 return log_error_errno(r, "crypt_init() failed: %m");
1953
1954 cryptsetup_enable_logging(cd);
1955
1956 status = crypt_status(cd, volume);
1957 if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) {
1958 log_info("Volume %s already active.", volume);
1959 return 0;
1960 }
1961
1962 flags = determine_flags();
1963
1964 until = usec_add(now(CLOCK_MONOTONIC), arg_timeout);
1965 if (until == USEC_INFINITY)
1966 until = 0;
1967
1968 arg_key_size = (arg_key_size > 0 ? arg_key_size : (256 / 8));
1969
1970 if (key_file) {
1971 struct stat st;
1972
1973 /* Ideally we'd do this on the open fd, but since this is just a
1974 * warning it's OK to do this in two steps. */
1975 if (stat(key_file, &st) >= 0 && S_ISREG(st.st_mode) && (st.st_mode & 0005))
1976 log_warning("Key file %s is world-readable. This is not a good idea!", key_file);
1977 }
1978
1979 if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2)) {
1980 r = crypt_load(cd, !arg_type || streq(arg_type, ANY_LUKS) ? CRYPT_LUKS : arg_type, NULL);
1981 if (r < 0)
1982 return log_error_errno(r, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd));
1983
1984 if (arg_header) {
1985 r = crypt_set_data_device(cd, source);
1986 if (r < 0)
1987 return log_error_errno(r, "Failed to set LUKS data device %s: %m", source);
1988 }
1989
1990 /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
1991 if (!key_file && !key_data && getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE") != 0) {
1992 r = crypt_activate_by_token_pin_ask_password(
1993 cd,
1994 volume,
1995 NULL,
1996 until,
1997 arg_headless,
1998 NULL,
1999 flags,
2000 "Please enter LUKS2 token PIN:",
2001 "luks2-pin",
2002 "cryptsetup.luks2-pin");
2003 if (r >= 0) {
2004 log_debug("Volume %s activated with LUKS token id %i.", volume, r);
2005 return 0;
2006 }
2007
2008 log_debug_errno(r, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd));
2009 }
2010 }
2011
2012 /* since cryptsetup 2.3.0 (Feb 2020) */
2013 #ifdef CRYPT_BITLK
2014 if (streq_ptr(arg_type, CRYPT_BITLK)) {
2015 r = crypt_load(cd, CRYPT_BITLK, NULL);
2016 if (r < 0)
2017 return log_error_errno(r, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd));
2018 }
2019 #endif
2020
2021 for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) {
2022 _cleanup_strv_free_erase_ char **passwords = NULL;
2023
2024 /* When we were able to acquire multiple keys, let's always process them in this order:
2025 *
2026 * 1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
2027 * 2. The discovered key: i.e. key_data + key_data_size
2028 * 3. The configured key: i.e. key_file + arg_keyfile_offset + arg_keyfile_size
2029 * 4. The empty password, in case arg_try_empty_password is set
2030 * 5. We enquire the user for a password
2031 */
2032
2033 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) {
2034
2035 if (arg_try_empty_password) {
2036 /* Hmm, let's try an empty password now, but only once */
2037 arg_try_empty_password = false;
2038
2039 key_data = strdup("");
2040 if (!key_data)
2041 return log_oom();
2042
2043 key_data_size = 0;
2044 } else {
2045 /* Ask the user for a passphrase or recovery key only as last resort, if we have
2046 * nothing else to check for */
2047 if (passphrase_type == PASSPHRASE_NONE) {
2048 passphrase_type = check_registered_passwords(cd);
2049 if (passphrase_type == PASSPHRASE_NONE)
2050 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No passphrase or recovery key registered.");
2051 }
2052
2053 r = get_password(volume, source, until, tries == 0 && !arg_verify, passphrase_type, &passwords);
2054 if (r == -EAGAIN)
2055 continue;
2056 if (r < 0)
2057 return r;
2058 }
2059 }
2060
2061 if (streq_ptr(arg_type, CRYPT_TCRYPT))
2062 r = attach_tcrypt(cd, volume, key_file, key_data, key_data_size, passwords, flags);
2063 else
2064 r = attach_luks_or_plain_or_bitlk(cd, volume, key_file, key_data, key_data_size, passwords, flags, until);
2065 if (r >= 0)
2066 break;
2067 if (r != -EAGAIN)
2068 return r;
2069
2070 /* Key not correct? Let's try again! */
2071
2072 key_file = NULL;
2073 key_data = erase_and_free(key_data);
2074 key_data_size = 0;
2075 arg_pkcs11_uri = mfree(arg_pkcs11_uri);
2076 arg_pkcs11_uri_auto = false;
2077 arg_fido2_device = mfree(arg_fido2_device);
2078 arg_fido2_device_auto = false;
2079 arg_tpm2_device = mfree(arg_tpm2_device);
2080 arg_tpm2_device_auto = false;
2081 }
2082
2083 if (arg_tries != 0 && tries >= arg_tries)
2084 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to activate; giving up.");
2085
2086 } else if (streq(verb, "detach")) {
2087 const char *volume;
2088
2089 volume = argv[2];
2090
2091 if (!filename_is_valid(volume))
2092 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
2093
2094 r = crypt_init_by_name(&cd, volume);
2095 if (r == -ENODEV) {
2096 log_info("Volume %s already inactive.", volume);
2097 return 0;
2098 }
2099 if (r < 0)
2100 return log_error_errno(r, "crypt_init_by_name() failed: %m");
2101
2102 cryptsetup_enable_logging(cd);
2103
2104 r = crypt_deactivate(cd, volume);
2105 if (r < 0)
2106 return log_error_errno(r, "Failed to deactivate: %m");
2107
2108 } else
2109 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb %s.", verb);
2110
2111 return 0;
2112 }
2113
2114 DEFINE_MAIN_FUNCTION(run);