1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include "sd-device.h"
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"
25 #include "fstab-util.h"
26 #include "hexdecoct.h"
27 #include "libfido2-util.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"
41 #include "tpm2-util.h"
44 #define ANY_LUKS "LUKS"
45 /* as in src/cryptsetup.h */
46 #define CRYPT_SECTOR_SIZE 512
47 #define CRYPT_MAX_SECTOR_SIZE 4096
49 typedef enum PassphraseType
{
51 PASSPHRASE_REGULAR
= 1 << 0,
52 PASSPHRASE_RECOVERY_KEY
= 1 << 1,
53 PASSPHRASE_BOTH
= PASSPHRASE_REGULAR
|PASSPHRASE_RECOVERY_KEY
,
55 _PASSPHRASE_TYPE_INVALID
= -1,
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
;
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
);
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",
115 const char* passphrase_type_to_string(PassphraseType t
);
116 PassphraseType
passphrase_type_from_string(const char *s
);
118 DEFINE_STRING_TABLE_LOOKUP(passphrase_type
, PassphraseType
);
120 /* Options Debian's crypttab knows we don't:
131 static int parse_one_option(const char *option
) {
137 /* Handled outside of this tool */
138 if (STR_IN_SET(option
, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
141 if (startswith(option
, "keyfile-timeout="))
144 if ((val
= startswith(option
, "cipher="))) {
145 r
= free_and_strdup(&arg_cipher
, val
);
149 } else if ((val
= startswith(option
, "size="))) {
151 r
= safe_atou(val
, &arg_key_size
);
153 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
157 if (arg_key_size
% 8) {
158 log_error("size= not a multiple of 8, ignoring.");
164 } else if ((val
= startswith(option
, "sector-size="))) {
166 r
= safe_atou(val
, &arg_sector_size
);
168 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
172 if (arg_sector_size
% 2) {
173 log_error("sector-size= not a multiple of 2, ignoring.");
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
);
182 } else if ((val
= startswith(option
, "key-slot=")) ||
183 (val
= startswith(option
, "keyslot="))) {
186 r
= safe_atoi(val
, &arg_key_slot
);
188 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
192 } else if ((val
= startswith(option
, "tcrypt-keyfile="))) {
194 arg_type
= CRYPT_TCRYPT
;
195 if (path_is_absolute(val
)) {
196 if (strv_extend(&arg_tcrypt_keyfiles
, val
) < 0)
199 log_error("Key file path \"%s\" is not absolute. Ignoring.", val
);
201 } else if ((val
= startswith(option
, "keyfile-size="))) {
203 r
= safe_atou(val
, &arg_keyfile_size
);
205 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
209 } else if ((val
= startswith(option
, "keyfile-offset="))) {
211 r
= safe_atou64(val
, &arg_keyfile_offset
);
213 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
217 } else if ((val
= startswith(option
, "keyfile-erase="))) {
219 r
= parse_boolean(val
);
221 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
225 arg_keyfile_erase
= r
;
227 } else if (streq(option
, "keyfile-erase"))
228 arg_keyfile_erase
= true;
230 else if ((val
= startswith(option
, "hash="))) {
231 r
= free_and_strdup(&arg_hash
, val
);
235 } else if ((val
= startswith(option
, "header="))) {
238 if (!path_is_absolute(val
))
239 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
240 "Header path \"%s\" is not absolute, refusing.", val
);
243 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
244 "Duplicate header= option, refusing.");
246 arg_header
= strdup(val
);
250 } else if ((val
= startswith(option
, "tries="))) {
252 r
= safe_atou(val
, &arg_tries
);
254 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
258 } else if (STR_IN_SET(option
, "readonly", "read-only"))
260 else if (streq(option
, "verify"))
262 else if ((val
= startswith(option
, "password-echo="))) {
263 if (streq(val
, "masked"))
264 arg_ask_password_flags
&= ~(ASK_PASSWORD_ECHO
|ASK_PASSWORD_SILENT
);
266 r
= parse_boolean(val
);
268 log_warning_errno(r
, "Invalid password-echo= option \"%s\", ignoring.", val
);
272 SET_FLAG(arg_ask_password_flags
, ASK_PASSWORD_ECHO
, r
);
273 SET_FLAG(arg_ask_password_flags
, ASK_PASSWORD_SILENT
, !r
);
275 } else if (STR_IN_SET(option
, "allow-discards", "discard"))
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"))
287 /* since cryptsetup 2.3.0 (Feb 2020) */
289 else if (streq(option
, "bitlk"))
290 arg_type
= CRYPT_BITLK
;
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="))) {
308 r
= parse_sec_fix_0(val
, &arg_timeout
);
310 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
314 } else if ((val
= startswith(option
, "offset="))) {
316 r
= safe_atou64(val
, &arg_offset
);
318 return log_error_errno(r
, "Failed to parse %s: %m", option
);
320 } else if ((val
= startswith(option
, "skip="))) {
322 r
= safe_atou64(val
, &arg_skip
);
324 return log_error_errno(r
, "Failed to parse %s: %m", option
);
326 } else if ((val
= startswith(option
, "pkcs11-uri="))) {
328 if (streq(val
, "auto")) {
329 arg_pkcs11_uri
= mfree(arg_pkcs11_uri
);
330 arg_pkcs11_uri_auto
= true;
332 if (!pkcs11_uri_valid(val
))
333 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing");
335 r
= free_and_strdup(&arg_pkcs11_uri
, val
);
339 arg_pkcs11_uri_auto
= false;
342 } else if ((val
= startswith(option
, "fido2-device="))) {
344 if (streq(val
, "auto")) {
345 arg_fido2_device
= mfree(arg_fido2_device
);
346 arg_fido2_device_auto
= true;
348 r
= free_and_strdup(&arg_fido2_device
, val
);
352 arg_fido2_device_auto
= false;
355 } else if ((val
= startswith(option
, "fido2-cid="))) {
357 if (streq(val
, "auto"))
358 arg_fido2_cid
= mfree(arg_fido2_cid
);
360 _cleanup_free_
void *cid
= NULL
;
363 r
= unbase64mem(val
, SIZE_MAX
, &cid
, &cid_size
);
365 return log_error_errno(r
, "Failed to decode FIDO2 CID data: %m");
368 arg_fido2_cid
= TAKE_PTR(cid
);
369 arg_fido2_cid_size
= cid_size
;
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;
376 } else if ((val
= startswith(option
, "fido2-rp="))) {
378 r
= free_and_strdup(&arg_fido2_rp_id
, val
);
382 } else if ((val
= startswith(option
, "tpm2-device="))) {
384 if (streq(val
, "auto")) {
385 arg_tpm2_device
= mfree(arg_tpm2_device
);
386 arg_tpm2_device_auto
= true;
388 r
= free_and_strdup(&arg_tpm2_device
, val
);
392 arg_tpm2_device_auto
= false;
395 } else if ((val
= startswith(option
, "tpm2-pcrs="))) {
397 r
= tpm2_parse_pcr_argument(val
, &arg_tpm2_pcr_mask
);
401 } else if ((val
= startswith(option
, "tpm2-pin="))) {
403 r
= parse_boolean(val
);
405 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
411 } else if ((val
= startswith(option
, "try-empty-password="))) {
413 r
= parse_boolean(val
);
415 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
419 arg_try_empty_password
= r
;
421 } else if (streq(option
, "try-empty-password"))
422 arg_try_empty_password
= true;
423 else if ((val
= startswith(option
, "headless="))) {
425 r
= parse_boolean(val
);
427 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
432 } else if (streq(option
, "headless"))
435 else if ((val
= startswith(option
, "token-timeout="))) {
437 r
= parse_sec_fix_0(val
, &arg_token_timeout_usec
);
439 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
443 } else if (!streq(option
, "x-initrd.attach"))
444 log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option
);
449 static int parse_options(const char *options
) {
453 _cleanup_free_
char *word
= NULL
;
456 r
= extract_first_word(&options
, &word
, ",", EXTRACT_DONT_COALESCE_SEPARATORS
| EXTRACT_UNESCAPE_SEPARATORS
);
458 return log_error_errno(r
, "Failed to parse options: %m");
462 r
= parse_one_option(word
);
467 /* sanity-check options */
468 if (arg_type
&& !streq(arg_type
, CRYPT_PLAIN
)) {
470 log_warning("offset= ignored with type %s", arg_type
);
472 log_warning("skip= ignored with type %s", arg_type
);
478 static char* disk_description(const char *path
) {
479 static const char name_fields
[] =
481 "ID_MODEL_FROM_DATABASE\0"
484 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
485 const char *i
, *name
;
490 if (stat(path
, &st
) < 0)
493 if (!S_ISBLK(st
.st_mode
))
496 if (sd_device_new_from_stat_rdev(&device
, &st
) < 0)
499 if (sd_device_get_property_value(device
, "ID_PART_ENTRY_NAME", &name
) >= 0) {
500 _cleanup_free_
char *unescaped
= NULL
;
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. */
507 l
= cunescape(name
, UNESCAPE_RELAX
, &unescaped
);
509 log_debug_errno(l
, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
513 if (!isempty(unescaped
) && !string_has_cc(unescaped
, NULL
))
514 return TAKE_PTR(unescaped
);
517 /* These need no unescaping. */
518 NULSTR_FOREACH(i
, name_fields
)
519 if (sd_device_get_property_value(device
, i
, &name
) >= 0 &&
526 static char *disk_mount_point(const char *label
) {
527 _cleanup_free_
char *device
= NULL
;
528 _cleanup_endmntent_
FILE *f
= NULL
;
531 /* Yeah, we don't support native systemd unit files here for now */
533 device
= strjoin("/dev/mapper/", label
);
537 f
= setmntent(fstab_path(), "re");
541 while ((m
= getmntent(f
)))
542 if (path_equal(m
->mnt_fsname
, device
))
543 return strdup(m
->mnt_dir
);
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
;
556 description
= disk_description(src
);
557 mount_point
= disk_mount_point(vol
);
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
);
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
);
577 static PassphraseType
check_registered_passwords(struct crypt_device
*cd
) {
578 _cleanup_free_
bool *slots
= NULL
;
580 PassphraseType passphrase_type
= PASSPHRASE_NONE
;
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
;
589 /* Search all used slots */
590 assert_se((slot_max
= crypt_keyslot_max(CRYPT_LUKS2
)) > 0);
591 slots
= new(bool, slot_max
);
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
);
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
;
605 tk
= cryptsetup_get_token_as_json(cd
, token
, NULL
, &v
);
606 if (IN_SET(tk
, -ENOENT
, -EINVAL
))
609 log_warning_errno(tk
, "Failed to read JSON token data, ignoring: %m");
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.");
619 type
= json_variant_string(w
);
620 if (STR_IN_SET(type
, "systemd-recovery", "systemd-pkcs11", "systemd-fido2", "systemd-tpm2")) {
622 /* At least exists one recovery key */
623 if (streq(type
, "systemd-recovery"))
624 passphrase_type
|= PASSPHRASE_RECOVERY_KEY
;
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.");
632 JSON_VARIANT_ARRAY_FOREACH(z
, w
) {
636 if (!json_variant_is_string(z
)) {
637 log_warning("Token JSON data's keyslot field is not an array of strings, ignoring.");
641 at
= safe_atou(json_variant_string(z
), &u
);
643 log_warning_errno(at
, "Token JSON data's keyslot field is not an integer formatted as string, ignoring.");
647 if (u
>= (unsigned) slot_max
) {
648 log_warning_errno(at
, "Token JSON data's keyslot field exceeds the maximum value allowed, ignoring.");
657 /* Check if any of the slots is not referenced by systemd tokens */
658 for (int slot
= 0; slot
< slot_max
; slot
++)
660 passphrase_type
|= PASSPHRASE_REGULAR
;
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
;
669 static int get_password(
674 PassphraseType passphrase_type
,
677 _cleanup_free_
char *friendly
= NULL
, *text
= NULL
, *disk_path
= NULL
;
678 _cleanup_strv_free_erase_
char **passwords
= NULL
;
681 AskPasswordFlags flags
= arg_ask_password_flags
| ASK_PASSWORD_PUSH_CACHE
;
688 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "Password querying disabled via 'headless' option.");
690 friendly
= friendly_disk_name(src
, vol
);
694 if (asprintf(&text
, "Please enter %s for disk %s:", passphrase_type_to_string(passphrase_type
), friendly
) < 0)
697 disk_path
= cescape(src
);
701 id
= strjoina("cryptsetup:", disk_path
);
703 r
= ask_password_auto(text
, "drive-harddisk", id
, "cryptsetup", "cryptsetup.passphrase", until
,
704 flags
| (accept_cached
*ASK_PASSWORD_ACCEPT_CACHED
),
707 return log_error_errno(r
, "Failed to query password: %m");
710 _cleanup_strv_free_erase_
char **passwords2
= NULL
;
712 assert(strv_length(passwords
) == 1);
714 if (asprintf(&text
, "Please enter %s for disk %s (verification):", passphrase_type_to_string(passphrase_type
), friendly
) < 0)
717 id
= strjoina("cryptsetup-verification:", disk_path
);
719 r
= ask_password_auto(text
, "drive-harddisk", id
, "cryptsetup", "cryptsetup.passphrase", until
, flags
, &passwords2
);
721 return log_error_errno(r
, "Failed to query verification password: %m");
723 assert(strv_length(passwords2
) == 1);
725 if (!streq(passwords
[0], passwords2
[0]))
726 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
),
727 "Passwords did not match, retrying.");
730 strv_uniq(passwords
);
732 STRV_FOREACH(p
, passwords
) {
735 if (strlen(*p
)+1 >= arg_key_size
)
738 /* Pad password if necessary */
739 c
= new(char, arg_key_size
);
743 strncpy(c
, *p
, arg_key_size
);
748 *ret
= TAKE_PTR(passwords
);
753 static int attach_tcrypt(
754 struct crypt_device
*cd
,
756 const char *key_file
,
757 const void *key_data
,
758 size_t key_data_size
,
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
)
772 assert(key_file
|| key_data
|| !strv_isempty(passwords
));
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.");
779 if (arg_tcrypt_hidden
)
780 params
.flags
|= CRYPT_TCRYPT_HIDDEN_HEADER
;
782 if (arg_tcrypt_system
)
783 params
.flags
|= CRYPT_TCRYPT_SYSTEM_HEADER
;
785 if (arg_tcrypt_veracrypt
)
786 params
.flags
|= CRYPT_TCRYPT_VERA_MODES
;
789 params
.passphrase
= key_data
;
790 params
.passphrase_size
= key_data_size
;
793 r
= read_one_line_file(key_file
, &passphrase
);
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 */
799 params
.passphrase
= passphrase
;
801 params
.passphrase
= passwords
[0];
803 params
.passphrase_size
= strlen(params
.passphrase
);
806 r
= crypt_load(cd
, CRYPT_TCRYPT
, ¶ms
);
810 log_error_errno(r
, "Failed to activate using discovered key. (Key not correct?)");
813 log_error_errno(r
, "Failed to activate using password file '%s'. (Key data not correct?)", key_file
);
815 return -EAGAIN
; /* log the actual error, but return EAGAIN */
818 return log_error_errno(r
, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd
));
821 r
= crypt_activate_by_volume_key(cd
, name
, NULL
, 0, flags
);
823 return log_error_errno(r
, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd
));
828 static char *make_bindname(const char *volume
) {
831 if (asprintf(&s
, "@%" PRIx64
"/cryptsetup/%s", random_u64(), volume
) < 0)
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
;
847 /* Waits for a device with "security-device" tag to show up in udev */
849 r
= sd_event_default(&event
);
851 return log_error_errno(r
, "Failed to allocate event loop: %m");
853 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, arg_token_timeout_usec
, USEC_PER_SEC
, NULL
, INT_TO_PTR(-ETIMEDOUT
));
855 return log_error_errno(r
, "Failed to install timeout event source: %m");
857 r
= sd_device_monitor_new(&monitor
);
859 return log_error_errno(r
, "Failed to allocate device monitor: %m");
861 r
= sd_device_monitor_filter_add_match_tag(monitor
, "security-device");
863 return log_error_errno(r
, "Failed to configure device monitor: %m");
865 r
= sd_device_monitor_attach_event(monitor
, event
);
867 return log_error_errno(r
, "Failed to attach device monitor: %m");
869 r
= sd_device_monitor_start(monitor
, NULL
, NULL
);
871 return log_error_errno(r
, "Failed to start device monitor: %m");
873 *ret_event
= TAKE_PTR(event
);
874 *ret_monitor
= TAKE_PTR(monitor
);
878 static int run_security_device_monitor(
880 sd_device_monitor
*monitor
) {
881 bool processed
= false;
887 /* Runs the event loop for the device monitor until either something happens, or the time-out is
893 r
= sd_event_get_exit_code(event
, &x
);
896 return log_error_errno(r
, "Failed to query exit code from event loop: %m");
898 /* On ENODATA we aren't told to exit yet. */
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.");
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
);
908 return log_error_errno(r
, "Failed to run event loop: %m");
909 if (r
== 0) /* no events queued anymore */
916 static bool libcryptsetup_plugins_support(void) {
917 #if HAVE_LIBCRYPTSETUP_PLUGINS
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");
927 return crypt_token_external_path();
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
;
941 r
= getenv_steal_erase("PIN", &envpin
);
943 return log_error_errno(r
, "Failed to acquire PIN from environment: %m");
945 pins
= strv_new(envpin
);
950 *ret_pins
= TAKE_PTR(pins
);
956 static int crypt_activate_by_token_pin_ask_password(
957 struct crypt_device
*cd
,
963 uint32_t activation_flags
,
965 const char *key_name
,
966 const char *credential_name
) {
968 #if HAVE_LIBCRYPTSETUP_PLUGINS
969 AskPasswordFlags flags
= ASK_PASSWORD_PUSH_CACHE
| ASK_PASSWORD_ACCEPT_CACHED
;
970 _cleanup_strv_free_erase_
char **pins
= NULL
;
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 */
976 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
979 r
= acquire_pins_from_env_variable(&pins
);
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 */
987 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
992 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
995 pins
= strv_free_erase(pins
);
996 r
= ask_password_auto(message
, "drive-harddisk", NULL
, key_name
, credential_name
, until
, flags
, &pins
);
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 */
1004 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
1008 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
1016 static int attach_luks2_by_fido2_via_plugin(
1017 struct crypt_device
*cd
,
1022 uint32_t activation_flags
) {
1024 return crypt_activate_by_token_pin_ask_password(
1032 "Please enter security token PIN:",
1034 "cryptsetup.fido2-pin");
1037 static int attach_luks_or_plain_or_bitlk_by_fido2(
1038 struct crypt_device
*cd
,
1040 const char *key_file
,
1041 const void *key_data
,
1042 size_t key_data_size
,
1045 bool pass_volume_key
) {
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();
1061 assert(arg_fido2_device
|| arg_fido2_device_auto
);
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.");
1068 rp_id
= arg_fido2_rp_id
;
1069 cid
= arg_fido2_cid
;
1070 cid_size
= arg_fido2_cid_size
;
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(
1082 &discovered_salt_size
,
1084 &discovered_cid_size
,
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.");
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.");
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
;
1105 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
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.");
1117 r
= acquire_fido2_key(
1123 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1124 key_data
, key_data_size
,
1128 &decrypted_key
, &decrypted_key_size
,
1129 arg_ask_password_flags
);
1134 if (r
!= -EAGAIN
) /* EAGAIN means: token not found */
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. */
1143 r
= make_security_device_monitor(&event
, &monitor
);
1147 log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly
);
1149 /* Let's immediately rescan in case the token appeared in the time we needed
1150 * to create and configure the monitor */
1154 r
= run_security_device_monitor(event
, monitor
);
1158 log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
1161 if (pass_volume_key
)
1162 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1164 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1166 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1168 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1172 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1175 log_error_errno(r
, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
1176 return -EAGAIN
; /* log actual error, but return EAGAIN */
1179 return log_error_errno(r
, "Failed to activate with FIDO2 acquired key: %m");
1184 static int attach_luks2_by_pkcs11_via_plugin(
1185 struct crypt_device
*cd
,
1187 const char *friendly_name
,
1192 #if HAVE_LIBCRYPTSETUP_PLUGINS
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.");
1198 systemd_pkcs11_plugin_params params
= {
1199 .friendly_name
= friendly_name
,
1201 .headless
= headless
1204 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-pkcs11", CRYPT_ANY_TOKEN
, NULL
, 0, ¶ms
, flags
);
1205 if (r
> 0) /* returns unlocked keyslot id on success */
1214 static int attach_luks_or_plain_or_bitlk_by_pkcs11(
1215 struct crypt_device
*cd
,
1217 const char *key_file
,
1218 const void *key_data
,
1219 size_t key_data_size
,
1222 bool pass_volume_key
) {
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();
1236 assert(arg_pkcs11_uri
|| arg_pkcs11_uri_auto
);
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.");
1247 uri
= discovered_uri
;
1248 key_data
= discovered_key
;
1249 key_data_size
= discovered_key_size
;
1252 uri
= arg_pkcs11_uri
;
1254 if (!key_file
&& !key_data
)
1255 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "PKCS#11 mode selected but no key file specified, refusing.");
1258 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1263 if (use_libcryptsetup_plugin
&& arg_pkcs11_uri_auto
)
1264 r
= attach_luks2_by_pkcs11_via_plugin(cd
, name
, friendly
, until
, arg_headless
, flags
);
1266 r
= decrypt_pkcs11_key(
1270 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1271 key_data
, key_data_size
,
1274 &decrypted_key
, &decrypted_key_size
);
1279 if (r
!= -EAGAIN
) /* EAGAIN means: token not found */
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. */
1288 r
= make_security_device_monitor(&event
, &monitor
);
1292 log_notice("Security token %s not present for unlocking volume %s, please plug it in.",
1295 /* Let's immediately rescan in case the token appeared in the time we needed
1296 * to create and configure the monitor */
1300 r
= run_security_device_monitor(event
, monitor
);
1304 log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
1306 assert(decrypted_key
);
1308 if (pass_volume_key
)
1309 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1311 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
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. */
1321 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1325 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1328 log_error_errno(r
, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
1329 return -EAGAIN
; /* log actual error, but return EAGAIN */
1332 return log_error_errno(r
, "Failed to activate with PKCS#11 acquired key: %m");
1337 static int make_tpm2_device_monitor(
1338 sd_event
**ret_event
,
1339 sd_device_monitor
**ret_monitor
) {
1341 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1342 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1346 assert(ret_monitor
);
1348 r
= sd_event_default(&event
);
1350 return log_error_errno(r
, "Failed to allocate event loop: %m");
1352 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, arg_token_timeout_usec
, USEC_PER_SEC
, NULL
, INT_TO_PTR(-ETIMEDOUT
));
1354 return log_error_errno(r
, "Failed to install timeout event source: %m");
1356 r
= sd_device_monitor_new(&monitor
);
1358 return log_error_errno(r
, "Failed to allocate device monitor: %m");
1360 r
= sd_device_monitor_filter_add_match_subsystem_devtype(monitor
, "tpmrm", NULL
);
1362 return log_error_errno(r
, "Failed to configure device monitor: %m");
1364 r
= sd_device_monitor_attach_event(monitor
, event
);
1366 return log_error_errno(r
, "Failed to attach device monitor: %m");
1368 r
= sd_device_monitor_start(monitor
, NULL
, NULL
);
1370 return log_error_errno(r
, "Failed to start device monitor: %m");
1372 *ret_event
= TAKE_PTR(event
);
1373 *ret_monitor
= TAKE_PTR(monitor
);
1377 static int attach_luks2_by_tpm2_via_plugin(
1378 struct crypt_device
*cd
,
1384 #if HAVE_LIBCRYPTSETUP_PLUGINS
1385 systemd_tpm2_plugin_params params
= {
1386 .search_pcr_mask
= arg_tpm2_pcr_mask
,
1387 .device
= arg_tpm2_device
1390 if (!libcryptsetup_plugins_support())
1391 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1392 "Libcryptsetup has external plugins support disabled.");
1394 return crypt_activate_by_token_pin_ask_password(
1402 "Please enter TPM2 PIN:",
1404 "cryptsetup.tpm2-pin");
1410 static int attach_luks_or_plain_or_bitlk_by_tpm2(
1411 struct crypt_device
*cd
,
1413 const char *key_file
,
1414 const void *key_data
,
1415 size_t key_data_size
,
1418 bool pass_volume_key
) {
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
;
1429 assert(arg_tpm2_device
|| arg_tpm2_device_auto
);
1431 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1436 if (key_file
|| key_data
) {
1437 /* If key data is specified, use that */
1439 r
= acquire_tpm2_key(
1442 arg_tpm2_pcr_mask
== UINT32_MAX
? TPM2_PCR_MASK_DEFAULT
: arg_tpm2_pcr_mask
,
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 */
1451 arg_ask_password_flags
,
1452 &decrypted_key
, &decrypted_key_size
);
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 */
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. */
1465 r
= attach_luks2_by_tpm2_via_plugin(cd
, name
, until
, arg_headless
, flags
);
1468 /* EAGAIN means: no tpm2 chip found
1469 * EOPNOTSUPP means: no libcryptsetup plugins support */
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.");
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. */
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 */
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
1494 uint16_t pcr_bank
, primary_alg
;
1495 TPM2Flags tpm2_flags
;
1497 r
= find_tpm2_auto_data(
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 */
1505 &policy_hash
, &policy_hash_size
,
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
),
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.");
1523 r
= acquire_tpm2_key(
1529 NULL
, 0, 0, /* no key file */
1531 policy_hash
, policy_hash_size
,
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.");
1542 token
++; /* try a different token next time */
1547 /* EAGAIN means: no tpm2 chip found */
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. */
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. */
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.");
1564 r
= make_tpm2_device_monitor(&event
, &monitor
);
1568 log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly
);
1570 /* Let's immediately rescan in case the device appeared in the time we needed
1571 * to create and configure the monitor */
1575 r
= run_security_device_monitor(event
, monitor
);
1579 log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
1581 assert(decrypted_key
);
1583 if (pass_volume_key
)
1584 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1586 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1588 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1590 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1594 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1597 log_error_errno(r
, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
1598 return -EAGAIN
; /* log actual error, but return EAGAIN */
1601 return log_error_errno(r
, "Failed to activate with TPM2 acquired key: %m");
1606 static int attach_luks_or_plain_or_bitlk_by_key_data(
1607 struct crypt_device
*cd
,
1609 const void *key_data
,
1610 size_t key_data_size
,
1612 bool pass_volume_key
) {
1620 if (pass_volume_key
)
1621 r
= crypt_activate_by_volume_key(cd
, name
, key_data
, key_data_size
, flags
);
1623 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, key_data
, key_data_size
, flags
);
1625 log_error_errno(r
, "Failed to activate. (Key incorrect?)");
1626 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1629 return log_error_errno(r
, "Failed to activate: %m");
1634 static int attach_luks_or_plain_or_bitlk_by_key_file(
1635 struct crypt_device
*cd
,
1637 const char *key_file
,
1639 bool pass_volume_key
) {
1641 _cleanup_(erase_and_freep
) char *kfdata
= NULL
;
1642 _cleanup_free_
char *bindname
= NULL
;
1650 /* If we read the key via AF_UNIX, make this client recognizable */
1651 bindname
= make_bindname(name
);
1655 r
= read_full_file_full(
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
,
1663 log_error_errno(r
, "Failed to activate, key file '%s' too large.", key_file
);
1667 log_error_errno(r
, "Failed to activate, key file '%s' missing.", key_file
);
1668 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1671 return log_error_errno(r
, "Failed to read key file '%s': %m", key_file
);
1673 if (pass_volume_key
)
1674 r
= crypt_activate_by_volume_key(cd
, name
, kfdata
, kfsize
, flags
);
1676 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, kfdata
, kfsize
, flags
);
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 */
1682 return log_error_errno(r
, "Failed to activate with key file '%s': %m", key_file
);
1687 static int attach_luks_or_plain_or_bitlk_by_passphrase(
1688 struct crypt_device
*cd
,
1692 bool pass_volume_key
) {
1700 STRV_FOREACH(p
, passwords
) {
1701 if (pass_volume_key
)
1702 r
= crypt_activate_by_volume_key(cd
, name
, *p
, arg_key_size
, flags
);
1704 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, *p
, strlen(*p
), flags
);
1709 log_error_errno(r
, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
1710 return -EAGAIN
; /* log actual error, but return EAGAIN */
1713 return log_error_errno(r
, "Failed to activate with specified passphrase: %m");
1718 static int attach_luks_or_plain_or_bitlk(
1719 struct crypt_device
*cd
,
1721 const char *key_file
,
1722 const void *key_data
,
1723 size_t key_data_size
,
1728 bool pass_volume_key
= false;
1734 if ((!arg_type
&& !crypt_get_type(cd
)) || streq_ptr(arg_type
, CRYPT_PLAIN
)) {
1735 struct crypt_params_plain params
= {
1736 .offset
= arg_offset
,
1738 .sector_size
= arg_sector_size
,
1740 const char *cipher
, *cipher_mode
;
1741 _cleanup_free_
char *truncated_cipher
= NULL
;
1743 if (streq_ptr(arg_hash
, "plain"))
1744 /* plain isn't a real hash type. it just means "use no hash" */
1747 params
.hash
= arg_hash
;
1749 /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
1750 * file is provided */
1751 params
.hash
= "ripemd160";
1756 l
= strcspn(arg_cipher
, "-");
1757 truncated_cipher
= strndup(arg_cipher
, l
);
1758 if (!truncated_cipher
)
1761 cipher
= truncated_cipher
;
1762 cipher_mode
= arg_cipher
[l
] ? arg_cipher
+l
+1 : "plain";
1765 cipher_mode
= "cbc-essiv:sha256";
1768 /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
1769 arg_keyfile_size
= arg_key_size
;
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
, ¶ms
);
1775 return log_error_errno(r
, "Loading of cryptographic parameters failed: %m");
1777 /* hash == NULL implies the user passed "plain" */
1778 pass_volume_key
= !params
.hash
;
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
));
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
);
1794 return attach_luks_or_plain_or_bitlk_by_key_data(cd
, name
, key_data
, key_data_size
, flags
, pass_volume_key
);
1796 return attach_luks_or_plain_or_bitlk_by_key_file(cd
, name
, key_file
, flags
, pass_volume_key
);
1798 return attach_luks_or_plain_or_bitlk_by_passphrase(cd
, name
, passwords
, flags
, pass_volume_key
);
1801 static int help(void) {
1802 _cleanup_free_
char *link
= NULL
;
1805 r
= terminal_urlify_man("systemd-cryptsetup@.service", "8", &link
);
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
,
1820 static uint32_t determine_flags(void) {
1824 flags
|= CRYPT_ACTIVATE_READONLY
;
1827 flags
|= CRYPT_ACTIVATE_ALLOW_DISCARDS
;
1829 if (arg_same_cpu_crypt
)
1830 flags
|= CRYPT_ACTIVATE_SAME_CPU_CRYPT
;
1832 if (arg_submit_from_crypt_cpus
)
1833 flags
|= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS
;
1835 if (arg_no_read_workqueue
)
1836 flags
|= CRYPT_ACTIVATE_NO_READ_WORKQUEUE
;
1838 if (arg_no_write_workqueue
)
1839 flags
|= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE
;
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
;
1850 static void remove_and_erasep(const char **p
) {
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
);
1861 static int run(int argc
, char *argv
[]) {
1862 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1866 if (argv_looks_like_help(argc
, argv
))
1870 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1871 "This program requires at least two arguments.");
1875 cryptsetup_enable_logging(NULL
);
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;
1890 PassphraseType passphrase_type
= PASSPHRASE_NONE
;
1892 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [KEY-FILE] [OPTIONS] */
1895 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "attach requires at least two arguments.");
1899 key_file
= mangle_none(argc
>= 5 ? argv
[4] : NULL
);
1900 options
= mangle_none(argc
>= 6 ? argv
[5] : NULL
);
1902 if (!filename_is_valid(volume
))
1903 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume name '%s' is not valid.", volume
);
1905 if (key_file
&& !path_is_absolute(key_file
)) {
1906 log_warning("Password file path '%s' is not absolute. Ignoring.", key_file
);
1911 r
= parse_options(options
);
1916 log_debug("%s %s ← %s type=%s cipher=%s", __func__
,
1917 volume
, source
, strempty(arg_type
), strempty(arg_cipher
));
1919 /* A delicious drop of snake oil */
1920 (void) mlockall(MCL_FUTURE
);
1923 _cleanup_free_
char *bindname
= NULL
;
1926 bindname
= make_bindname(volume
);
1930 /* If a key file is not explicitly specified, search for a key in a well defined
1931 * search path, and load it. */
1933 fn
= strjoina(volume
, ".key");
1936 STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"),
1938 &key_data
, &key_data_size
);
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 */
1947 log_debug("LUKS header: %s", arg_header
);
1948 r
= crypt_init(&cd
, arg_header
);
1950 r
= crypt_init(&cd
, source
);
1952 return log_error_errno(r
, "crypt_init() failed: %m");
1954 cryptsetup_enable_logging(cd
);
1956 status
= crypt_status(cd
, volume
);
1957 if (IN_SET(status
, CRYPT_ACTIVE
, CRYPT_BUSY
)) {
1958 log_info("Volume %s already active.", volume
);
1962 flags
= determine_flags();
1964 until
= usec_add(now(CLOCK_MONOTONIC
), arg_timeout
);
1965 if (until
== USEC_INFINITY
)
1968 arg_key_size
= (arg_key_size
> 0 ? arg_key_size
: (256 / 8));
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
);
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
);
1982 return log_error_errno(r
, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd
));
1985 r
= crypt_set_data_device(cd
, source
);
1987 return log_error_errno(r
, "Failed to set LUKS data device %s: %m", source
);
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(
2000 "Please enter LUKS2 token PIN:",
2002 "cryptsetup.luks2-pin");
2004 log_debug("Volume %s activated with LUKS token id %i.", volume
, r
);
2008 log_debug_errno(r
, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd
));
2012 /* since cryptsetup 2.3.0 (Feb 2020) */
2014 if (streq_ptr(arg_type
, CRYPT_BITLK
)) {
2015 r
= crypt_load(cd
, CRYPT_BITLK
, NULL
);
2017 return log_error_errno(r
, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd
));
2021 for (tries
= 0; arg_tries
== 0 || tries
< arg_tries
; tries
++) {
2022 _cleanup_strv_free_erase_
char **passwords
= NULL
;
2024 /* When we were able to acquire multiple keys, let's always process them in this order:
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
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
) {
2035 if (arg_try_empty_password
) {
2036 /* Hmm, let's try an empty password now, but only once */
2037 arg_try_empty_password
= false;
2039 key_data
= strdup("");
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.");
2053 r
= get_password(volume
, source
, until
, tries
== 0 && !arg_verify
, passphrase_type
, &passwords
);
2061 if (streq_ptr(arg_type
, CRYPT_TCRYPT
))
2062 r
= attach_tcrypt(cd
, volume
, key_file
, key_data
, key_data_size
, passwords
, flags
);
2064 r
= attach_luks_or_plain_or_bitlk(cd
, volume
, key_file
, key_data
, key_data_size
, passwords
, flags
, until
);
2070 /* Key not correct? Let's try again! */
2073 key_data
= erase_and_free(key_data
);
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;
2083 if (arg_tries
!= 0 && tries
>= arg_tries
)
2084 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Too many attempts to activate; giving up.");
2086 } else if (streq(verb
, "detach")) {
2091 if (!filename_is_valid(volume
))
2092 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume name '%s' is not valid.", volume
);
2094 r
= crypt_init_by_name(&cd
, volume
);
2096 log_info("Volume %s already inactive.", volume
);
2100 return log_error_errno(r
, "crypt_init_by_name() failed: %m");
2102 cryptsetup_enable_logging(cd
);
2104 r
= crypt_deactivate(cd
, volume
);
2106 return log_error_errno(r
, "Failed to deactivate: %m");
2109 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown verb %s.", verb
);
2114 DEFINE_MAIN_FUNCTION(run
);