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