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 512U
47 #define CRYPT_MAX_SECTOR_SIZE 4096U
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 char *arg_tpm2_signature
= NULL
;
96 static bool arg_tpm2_pin
= false;
97 static bool arg_headless
= false;
98 static usec_t arg_token_timeout_usec
= 30*USEC_PER_SEC
;
100 STATIC_DESTRUCTOR_REGISTER(arg_cipher
, freep
);
101 STATIC_DESTRUCTOR_REGISTER(arg_hash
, freep
);
102 STATIC_DESTRUCTOR_REGISTER(arg_header
, freep
);
103 STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles
, strv_freep
);
104 STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri
, freep
);
105 STATIC_DESTRUCTOR_REGISTER(arg_fido2_device
, freep
);
106 STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid
, freep
);
107 STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id
, freep
);
108 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
109 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_signature
, freep
);
111 static const char* const passphrase_type_table
[_PASSPHRASE_TYPE_MAX
] = {
112 [PASSPHRASE_REGULAR
] = "passphrase",
113 [PASSPHRASE_RECOVERY_KEY
] = "recovery key",
114 [PASSPHRASE_BOTH
] = "passphrase or recovery key",
117 const char* passphrase_type_to_string(PassphraseType t
);
118 PassphraseType
passphrase_type_from_string(const char *s
);
120 DEFINE_STRING_TABLE_LOOKUP(passphrase_type
, PassphraseType
);
122 /* Options Debian's crypttab knows we don't:
133 static int parse_one_option(const char *option
) {
139 /* Handled outside of this tool */
140 if (STR_IN_SET(option
, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
143 if (startswith(option
, "keyfile-timeout="))
146 if ((val
= startswith(option
, "cipher="))) {
147 r
= free_and_strdup(&arg_cipher
, val
);
151 } else if ((val
= startswith(option
, "size="))) {
153 r
= safe_atou(val
, &arg_key_size
);
155 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
159 if (arg_key_size
% 8) {
160 log_error("size= not a multiple of 8, ignoring.");
166 } else if ((val
= startswith(option
, "sector-size="))) {
168 r
= safe_atou(val
, &arg_sector_size
);
170 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
174 if (arg_sector_size
% 2) {
175 log_error("sector-size= not a multiple of 2, ignoring.");
179 if (arg_sector_size
< CRYPT_SECTOR_SIZE
|| arg_sector_size
> CRYPT_MAX_SECTOR_SIZE
) {
180 log_error("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE
, CRYPT_MAX_SECTOR_SIZE
);
184 } else if ((val
= startswith(option
, "key-slot=")) ||
185 (val
= startswith(option
, "keyslot="))) {
188 r
= safe_atoi(val
, &arg_key_slot
);
190 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
194 } else if ((val
= startswith(option
, "tcrypt-keyfile="))) {
196 arg_type
= CRYPT_TCRYPT
;
197 if (path_is_absolute(val
)) {
198 if (strv_extend(&arg_tcrypt_keyfiles
, val
) < 0)
201 log_error("Key file path \"%s\" is not absolute. Ignoring.", val
);
203 } else if ((val
= startswith(option
, "keyfile-size="))) {
205 r
= safe_atou(val
, &arg_keyfile_size
);
207 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
211 } else if ((val
= startswith(option
, "keyfile-offset="))) {
213 r
= safe_atou64(val
, &arg_keyfile_offset
);
215 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
219 } else if ((val
= startswith(option
, "keyfile-erase="))) {
221 r
= parse_boolean(val
);
223 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
227 arg_keyfile_erase
= r
;
229 } else if (streq(option
, "keyfile-erase"))
230 arg_keyfile_erase
= true;
232 else if ((val
= startswith(option
, "hash="))) {
233 r
= free_and_strdup(&arg_hash
, val
);
237 } else if ((val
= startswith(option
, "header="))) {
240 if (!path_is_absolute(val
))
241 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
242 "Header path \"%s\" is not absolute, refusing.", val
);
245 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
246 "Duplicate header= option, refusing.");
248 arg_header
= strdup(val
);
252 } else if ((val
= startswith(option
, "tries="))) {
254 r
= safe_atou(val
, &arg_tries
);
256 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
260 } else if (STR_IN_SET(option
, "readonly", "read-only"))
262 else if (streq(option
, "verify"))
264 else if ((val
= startswith(option
, "password-echo="))) {
265 if (streq(val
, "masked"))
266 arg_ask_password_flags
&= ~(ASK_PASSWORD_ECHO
|ASK_PASSWORD_SILENT
);
268 r
= parse_boolean(val
);
270 log_warning_errno(r
, "Invalid password-echo= option \"%s\", ignoring.", val
);
274 SET_FLAG(arg_ask_password_flags
, ASK_PASSWORD_ECHO
, r
);
275 SET_FLAG(arg_ask_password_flags
, ASK_PASSWORD_SILENT
, !r
);
277 } else if (STR_IN_SET(option
, "allow-discards", "discard"))
279 else if (streq(option
, "same-cpu-crypt"))
280 arg_same_cpu_crypt
= true;
281 else if (streq(option
, "submit-from-crypt-cpus"))
282 arg_submit_from_crypt_cpus
= true;
283 else if (streq(option
, "no-read-workqueue"))
284 arg_no_read_workqueue
= true;
285 else if (streq(option
, "no-write-workqueue"))
286 arg_no_write_workqueue
= true;
287 else if (streq(option
, "luks"))
289 /* since cryptsetup 2.3.0 (Feb 2020) */
291 else if (streq(option
, "bitlk"))
292 arg_type
= CRYPT_BITLK
;
294 else if (streq(option
, "tcrypt"))
295 arg_type
= CRYPT_TCRYPT
;
296 else if (STR_IN_SET(option
, "tcrypt-hidden", "tcrypthidden")) {
297 arg_type
= CRYPT_TCRYPT
;
298 arg_tcrypt_hidden
= true;
299 } else if (streq(option
, "tcrypt-system")) {
300 arg_type
= CRYPT_TCRYPT
;
301 arg_tcrypt_system
= true;
302 } else if (STR_IN_SET(option
, "tcrypt-veracrypt", "veracrypt")) {
303 arg_type
= CRYPT_TCRYPT
;
304 arg_tcrypt_veracrypt
= true;
305 } else if (STR_IN_SET(option
, "plain", "swap", "tmp") ||
306 startswith(option
, "tmp="))
307 arg_type
= CRYPT_PLAIN
;
308 else if ((val
= startswith(option
, "timeout="))) {
310 r
= parse_sec_fix_0(val
, &arg_timeout
);
312 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
316 } else if ((val
= startswith(option
, "offset="))) {
318 r
= safe_atou64(val
, &arg_offset
);
320 return log_error_errno(r
, "Failed to parse %s: %m", option
);
322 } else if ((val
= startswith(option
, "skip="))) {
324 r
= safe_atou64(val
, &arg_skip
);
326 return log_error_errno(r
, "Failed to parse %s: %m", option
);
328 } else if ((val
= startswith(option
, "pkcs11-uri="))) {
330 if (streq(val
, "auto")) {
331 arg_pkcs11_uri
= mfree(arg_pkcs11_uri
);
332 arg_pkcs11_uri_auto
= true;
334 if (!pkcs11_uri_valid(val
))
335 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing");
337 r
= free_and_strdup(&arg_pkcs11_uri
, val
);
341 arg_pkcs11_uri_auto
= false;
344 } else if ((val
= startswith(option
, "fido2-device="))) {
346 if (streq(val
, "auto")) {
347 arg_fido2_device
= mfree(arg_fido2_device
);
348 arg_fido2_device_auto
= true;
350 r
= free_and_strdup(&arg_fido2_device
, val
);
354 arg_fido2_device_auto
= false;
357 } else if ((val
= startswith(option
, "fido2-cid="))) {
359 if (streq(val
, "auto"))
360 arg_fido2_cid
= mfree(arg_fido2_cid
);
362 _cleanup_free_
void *cid
= NULL
;
365 r
= unbase64mem(val
, SIZE_MAX
, &cid
, &cid_size
);
367 return log_error_errno(r
, "Failed to decode FIDO2 CID data: %m");
370 arg_fido2_cid
= TAKE_PTR(cid
);
371 arg_fido2_cid_size
= cid_size
;
374 /* Turn on FIDO2 as side-effect, if not turned on yet. */
375 if (!arg_fido2_device
&& !arg_fido2_device_auto
)
376 arg_fido2_device_auto
= true;
378 } else if ((val
= startswith(option
, "fido2-rp="))) {
380 r
= free_and_strdup(&arg_fido2_rp_id
, val
);
384 } else if ((val
= startswith(option
, "tpm2-device="))) {
386 if (streq(val
, "auto")) {
387 arg_tpm2_device
= mfree(arg_tpm2_device
);
388 arg_tpm2_device_auto
= true;
390 r
= free_and_strdup(&arg_tpm2_device
, val
);
394 arg_tpm2_device_auto
= false;
397 } else if ((val
= startswith(option
, "tpm2-pcrs="))) {
399 r
= tpm2_parse_pcr_argument(val
, &arg_tpm2_pcr_mask
);
403 } else if ((val
= startswith(option
, "tpm2-signature="))) {
405 if (!path_is_absolute(val
))
406 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
407 "TPM2 signature path \"%s\" is not absolute, refusing.", val
);
409 r
= free_and_strdup(&arg_tpm2_signature
, val
);
413 } else if ((val
= startswith(option
, "tpm2-pin="))) {
415 r
= parse_boolean(val
);
417 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
423 } else if ((val
= startswith(option
, "try-empty-password="))) {
425 r
= parse_boolean(val
);
427 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
431 arg_try_empty_password
= r
;
433 } else if (streq(option
, "try-empty-password"))
434 arg_try_empty_password
= true;
435 else if ((val
= startswith(option
, "headless="))) {
437 r
= parse_boolean(val
);
439 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
444 } else if (streq(option
, "headless"))
447 else if ((val
= startswith(option
, "token-timeout="))) {
449 r
= parse_sec_fix_0(val
, &arg_token_timeout_usec
);
451 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
455 } else if (!streq(option
, "x-initrd.attach"))
456 log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option
);
461 static int parse_options(const char *options
) {
465 _cleanup_free_
char *word
= NULL
;
468 r
= extract_first_word(&options
, &word
, ",", EXTRACT_DONT_COALESCE_SEPARATORS
| EXTRACT_UNESCAPE_SEPARATORS
);
470 return log_error_errno(r
, "Failed to parse options: %m");
474 r
= parse_one_option(word
);
479 /* sanity-check options */
480 if (arg_type
&& !streq(arg_type
, CRYPT_PLAIN
)) {
482 log_warning("offset= ignored with type %s", arg_type
);
484 log_warning("skip= ignored with type %s", arg_type
);
490 static char* disk_description(const char *path
) {
491 static const char name_fields
[] =
493 "ID_MODEL_FROM_DATABASE\0"
496 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
497 const char *i
, *name
;
502 if (stat(path
, &st
) < 0)
505 if (!S_ISBLK(st
.st_mode
))
508 if (sd_device_new_from_stat_rdev(&device
, &st
) < 0)
511 if (sd_device_get_property_value(device
, "ID_PART_ENTRY_NAME", &name
) >= 0) {
512 _cleanup_free_
char *unescaped
= NULL
;
515 /* ID_PART_ENTRY_NAME uses \x style escaping, using libblkid's blkid_encode_string(). Let's
516 * reverse this here to make the string more human friendly in case people embed spaces or
517 * other weird stuff. */
519 l
= cunescape(name
, UNESCAPE_RELAX
, &unescaped
);
521 log_debug_errno(l
, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
525 if (!isempty(unescaped
) && !string_has_cc(unescaped
, NULL
))
526 return TAKE_PTR(unescaped
);
529 /* These need no unescaping. */
530 NULSTR_FOREACH(i
, name_fields
)
531 if (sd_device_get_property_value(device
, i
, &name
) >= 0 &&
538 static char *disk_mount_point(const char *label
) {
539 _cleanup_free_
char *device
= NULL
;
540 _cleanup_endmntent_
FILE *f
= NULL
;
543 /* Yeah, we don't support native systemd unit files here for now */
545 device
= strjoin("/dev/mapper/", label
);
549 f
= setmntent(fstab_path(), "re");
553 while ((m
= getmntent(f
)))
554 if (path_equal(m
->mnt_fsname
, device
))
555 return strdup(m
->mnt_dir
);
560 static char *friendly_disk_name(const char *src
, const char *vol
) {
561 _cleanup_free_
char *description
= NULL
, *mount_point
= NULL
;
562 char *name_buffer
= NULL
;
568 description
= disk_description(src
);
569 mount_point
= disk_mount_point(vol
);
571 /* If the description string is simply the volume name, then let's not show this twice */
572 if (description
&& streq(vol
, description
))
573 description
= mfree(description
);
575 if (mount_point
&& description
)
576 r
= asprintf(&name_buffer
, "%s (%s) on %s", description
, vol
, mount_point
);
577 else if (mount_point
)
578 r
= asprintf(&name_buffer
, "%s on %s", vol
, mount_point
);
579 else if (description
)
580 r
= asprintf(&name_buffer
, "%s (%s)", description
, vol
);
589 static PassphraseType
check_registered_passwords(struct crypt_device
*cd
) {
590 _cleanup_free_
bool *slots
= NULL
;
592 PassphraseType passphrase_type
= PASSPHRASE_NONE
;
596 if (!streq_ptr(crypt_get_type(cd
), CRYPT_LUKS2
)) {
597 log_debug("%s: not a LUKS2 device, only passphrases are supported", crypt_get_device_name(cd
));
598 return PASSPHRASE_REGULAR
;
601 /* Search all used slots */
602 assert_se((slot_max
= crypt_keyslot_max(CRYPT_LUKS2
)) > 0);
603 slots
= new(bool, slot_max
);
607 for (int slot
= 0; slot
< slot_max
; slot
++)
608 slots
[slot
] = IN_SET(crypt_keyslot_status(cd
, slot
), CRYPT_SLOT_ACTIVE
, CRYPT_SLOT_ACTIVE_LAST
);
610 /* Iterate all LUKS2 tokens and keep track of all their slots */
611 for (int token
= 0; token
< sym_crypt_token_max(CRYPT_LUKS2
); token
++) {
612 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
617 tk
= cryptsetup_get_token_as_json(cd
, token
, NULL
, &v
);
618 if (IN_SET(tk
, -ENOENT
, -EINVAL
))
621 log_warning_errno(tk
, "Failed to read JSON token data, ignoring: %m");
625 w
= json_variant_by_key(v
, "type");
626 if (!w
|| !json_variant_is_string(w
)) {
627 log_warning("Token JSON data lacks type field, ignoring.");
631 type
= json_variant_string(w
);
632 if (STR_IN_SET(type
, "systemd-recovery", "systemd-pkcs11", "systemd-fido2", "systemd-tpm2")) {
634 /* At least exists one recovery key */
635 if (streq(type
, "systemd-recovery"))
636 passphrase_type
|= PASSPHRASE_RECOVERY_KEY
;
638 w
= json_variant_by_key(v
, "keyslots");
639 if (!w
|| !json_variant_is_array(w
)) {
640 log_warning("Token JSON data lacks keyslots field, ignoring.");
644 JSON_VARIANT_ARRAY_FOREACH(z
, w
) {
648 if (!json_variant_is_string(z
)) {
649 log_warning("Token JSON data's keyslot field is not an array of strings, ignoring.");
653 at
= safe_atou(json_variant_string(z
), &u
);
655 log_warning_errno(at
, "Token JSON data's keyslot field is not an integer formatted as string, ignoring.");
659 if (u
>= (unsigned) slot_max
) {
660 log_warning_errno(at
, "Token JSON data's keyslot field exceeds the maximum value allowed, ignoring.");
669 /* Check if any of the slots is not referenced by systemd tokens */
670 for (int slot
= 0; slot
< slot_max
; slot
++)
672 passphrase_type
|= PASSPHRASE_REGULAR
;
676 /* All the slots are referenced by systemd tokens, so if a recovery key is not enrolled,
677 * we will not be able to enter a passphrase. */
678 return passphrase_type
;
681 static int get_password(
686 PassphraseType passphrase_type
,
689 _cleanup_free_
char *friendly
= NULL
, *text
= NULL
, *disk_path
= NULL
;
690 _cleanup_strv_free_erase_
char **passwords
= NULL
;
693 AskPasswordFlags flags
= arg_ask_password_flags
| ASK_PASSWORD_PUSH_CACHE
;
700 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "Password querying disabled via 'headless' option.");
702 friendly
= friendly_disk_name(src
, vol
);
706 if (asprintf(&text
, "Please enter %s for disk %s:", passphrase_type_to_string(passphrase_type
), friendly
) < 0)
709 disk_path
= cescape(src
);
713 id
= strjoina("cryptsetup:", disk_path
);
715 r
= ask_password_auto(text
, "drive-harddisk", id
, "cryptsetup", "cryptsetup.passphrase", until
,
716 flags
| (accept_cached
*ASK_PASSWORD_ACCEPT_CACHED
),
719 return log_error_errno(r
, "Failed to query password: %m");
722 _cleanup_strv_free_erase_
char **passwords2
= NULL
;
724 assert(strv_length(passwords
) == 1);
726 if (asprintf(&text
, "Please enter %s for disk %s (verification):", passphrase_type_to_string(passphrase_type
), friendly
) < 0)
729 id
= strjoina("cryptsetup-verification:", disk_path
);
731 r
= ask_password_auto(text
, "drive-harddisk", id
, "cryptsetup", "cryptsetup.passphrase", until
, flags
, &passwords2
);
733 return log_error_errno(r
, "Failed to query verification password: %m");
735 assert(strv_length(passwords2
) == 1);
737 if (!streq(passwords
[0], passwords2
[0]))
738 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
),
739 "Passwords did not match, retrying.");
742 strv_uniq(passwords
);
744 STRV_FOREACH(p
, passwords
) {
747 if (strlen(*p
)+1 >= arg_key_size
)
750 /* Pad password if necessary */
751 c
= new(char, arg_key_size
);
755 strncpy(c
, *p
, arg_key_size
);
760 *ret
= TAKE_PTR(passwords
);
765 static int attach_tcrypt(
766 struct crypt_device
*cd
,
768 const char *key_file
,
769 const void *key_data
,
770 size_t key_data_size
,
775 _cleanup_(erase_and_freep
) char *passphrase
= NULL
;
776 struct crypt_params_tcrypt params
= {
777 .flags
= CRYPT_TCRYPT_LEGACY_MODES
,
778 .keyfiles
= (const char **)arg_tcrypt_keyfiles
,
779 .keyfiles_count
= strv_length(arg_tcrypt_keyfiles
)
784 assert(key_file
|| key_data
|| !strv_isempty(passwords
));
786 if (arg_pkcs11_uri
|| arg_pkcs11_uri_auto
|| arg_fido2_device
|| arg_fido2_device_auto
|| arg_tpm2_device
|| arg_tpm2_device_auto
)
787 /* Ask for a regular password */
788 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN
),
789 "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
791 if (arg_tcrypt_hidden
)
792 params
.flags
|= CRYPT_TCRYPT_HIDDEN_HEADER
;
794 if (arg_tcrypt_system
)
795 params
.flags
|= CRYPT_TCRYPT_SYSTEM_HEADER
;
797 if (arg_tcrypt_veracrypt
)
798 params
.flags
|= CRYPT_TCRYPT_VERA_MODES
;
801 params
.passphrase
= key_data
;
802 params
.passphrase_size
= key_data_size
;
805 r
= read_one_line_file(key_file
, &passphrase
);
807 log_error_errno(r
, "Failed to read password file '%s': %m", key_file
);
808 return -EAGAIN
; /* log with the actual error, but return EAGAIN */
811 params
.passphrase
= passphrase
;
813 params
.passphrase
= passwords
[0];
815 params
.passphrase_size
= strlen(params
.passphrase
);
818 r
= crypt_load(cd
, CRYPT_TCRYPT
, ¶ms
);
822 log_error_errno(r
, "Failed to activate using discovered key. (Key not correct?)");
825 log_error_errno(r
, "Failed to activate using password file '%s'. (Key data not correct?)", key_file
);
827 return -EAGAIN
; /* log the actual error, but return EAGAIN */
830 return log_error_errno(r
, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd
));
833 r
= crypt_activate_by_volume_key(cd
, name
, NULL
, 0, flags
);
835 return log_error_errno(r
, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd
));
840 static char *make_bindname(const char *volume
) {
843 if (asprintf(&s
, "@%" PRIx64
"/cryptsetup/%s", random_u64(), volume
) < 0)
849 static int make_security_device_monitor(
850 sd_event
**ret_event
,
851 sd_device_monitor
**ret_monitor
) {
852 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
853 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
859 /* Waits for a device with "security-device" tag to show up in udev */
861 r
= sd_event_default(&event
);
863 return log_error_errno(r
, "Failed to allocate event loop: %m");
865 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, arg_token_timeout_usec
, USEC_PER_SEC
, NULL
, INT_TO_PTR(-ETIMEDOUT
));
867 return log_error_errno(r
, "Failed to install timeout event source: %m");
869 r
= sd_device_monitor_new(&monitor
);
871 return log_error_errno(r
, "Failed to allocate device monitor: %m");
873 r
= sd_device_monitor_filter_add_match_tag(monitor
, "security-device");
875 return log_error_errno(r
, "Failed to configure device monitor: %m");
877 r
= sd_device_monitor_attach_event(monitor
, event
);
879 return log_error_errno(r
, "Failed to attach device monitor: %m");
881 r
= sd_device_monitor_start(monitor
, NULL
, NULL
);
883 return log_error_errno(r
, "Failed to start device monitor: %m");
885 *ret_event
= TAKE_PTR(event
);
886 *ret_monitor
= TAKE_PTR(monitor
);
890 static int run_security_device_monitor(
892 sd_device_monitor
*monitor
) {
893 bool processed
= false;
899 /* Runs the event loop for the device monitor until either something happens, or the time-out is
905 r
= sd_event_get_exit_code(event
, &x
);
908 return log_error_errno(r
, "Failed to query exit code from event loop: %m");
910 /* On ENODATA we aren't told to exit yet. */
912 assert(x
== -ETIMEDOUT
);
913 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
),
914 "Timed out waiting for security device, aborting security device based authentication attempt.");
917 /* Wait for one event, and then eat all subsequent events until there are no further ones */
918 r
= sd_event_run(event
, processed
? 0 : UINT64_MAX
);
920 return log_error_errno(r
, "Failed to run event loop: %m");
921 if (r
== 0) /* no events queued anymore */
928 static bool libcryptsetup_plugins_support(void) {
929 #if HAVE_LIBCRYPTSETUP_PLUGINS
932 /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
933 r
= getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
934 if (r
< 0 && r
!= -ENXIO
)
935 log_debug_errno(r
, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
939 return crypt_token_external_path();
945 #if HAVE_LIBCRYPTSETUP_PLUGINS
946 static int acquire_pins_from_env_variable(char ***ret_pins
) {
947 _cleanup_(erase_and_freep
) char *envpin
= NULL
;
948 _cleanup_strv_free_erase_
char **pins
= NULL
;
953 r
= getenv_steal_erase("PIN", &envpin
);
955 return log_error_errno(r
, "Failed to acquire PIN from environment: %m");
957 pins
= strv_new(envpin
);
962 *ret_pins
= TAKE_PTR(pins
);
968 static int crypt_activate_by_token_pin_ask_password(
969 struct crypt_device
*cd
,
975 uint32_t activation_flags
,
977 const char *key_name
,
978 const char *credential_name
) {
980 #if HAVE_LIBCRYPTSETUP_PLUGINS
981 AskPasswordFlags flags
= ASK_PASSWORD_PUSH_CACHE
| ASK_PASSWORD_ACCEPT_CACHED
;
982 _cleanup_strv_free_erase_
char **pins
= NULL
;
985 r
= crypt_activate_by_token_pin(cd
, name
, type
, CRYPT_ANY_TOKEN
, NULL
, 0, usrptr
, activation_flags
);
986 if (r
> 0) /* returns unlocked keyslot id on success */
988 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
991 r
= acquire_pins_from_env_variable(&pins
);
995 STRV_FOREACH(p
, pins
) {
996 r
= crypt_activate_by_token_pin(cd
, name
, type
, CRYPT_ANY_TOKEN
, *p
, strlen(*p
), usrptr
, activation_flags
);
997 if (r
> 0) /* returns unlocked keyslot id on success */
999 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
1004 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
1007 pins
= strv_free_erase(pins
);
1008 r
= ask_password_auto(message
, "drive-harddisk", NULL
, key_name
, credential_name
, until
, flags
, &pins
);
1012 STRV_FOREACH(p
, pins
) {
1013 r
= crypt_activate_by_token_pin(cd
, name
, type
, CRYPT_ANY_TOKEN
, *p
, strlen(*p
), usrptr
, activation_flags
);
1014 if (r
> 0) /* returns unlocked keyslot id on success */
1016 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
1020 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
1028 static int attach_luks2_by_fido2_via_plugin(
1029 struct crypt_device
*cd
,
1034 uint32_t activation_flags
) {
1036 return crypt_activate_by_token_pin_ask_password(
1044 "Please enter security token PIN:",
1046 "cryptsetup.fido2-pin");
1049 static int attach_luks_or_plain_or_bitlk_by_fido2(
1050 struct crypt_device
*cd
,
1052 const char *key_file
,
1053 const void *key_data
,
1054 size_t key_data_size
,
1057 bool pass_volume_key
) {
1059 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1060 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
1061 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1062 _cleanup_free_
void *discovered_salt
= NULL
, *discovered_cid
= NULL
;
1063 size_t discovered_salt_size
, discovered_cid_size
, decrypted_key_size
, cid_size
= 0;
1064 _cleanup_free_
char *friendly
= NULL
, *discovered_rp_id
= NULL
;
1065 int keyslot
= arg_key_slot
, r
;
1066 const char *rp_id
= NULL
;
1067 const void *cid
= NULL
;
1068 Fido2EnrollFlags required
;
1069 bool use_libcryptsetup_plugin
= libcryptsetup_plugins_support();
1073 assert(arg_fido2_device
|| arg_fido2_device_auto
);
1075 if (arg_fido2_cid
) {
1076 if (!key_file
&& !key_data
)
1077 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1078 "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
1080 rp_id
= arg_fido2_rp_id
;
1081 cid
= arg_fido2_cid
;
1082 cid_size
= arg_fido2_cid_size
;
1084 /* For now and for compatibility, if the user explicitly configured FIDO2 support and we do
1085 * not read FIDO2 metadata off the LUKS2 header, default to the systemd 248 logic, where we
1086 * use PIN + UP when needed, and do not configure UV at all. Eventually, we should make this
1087 * explicitly configurable. */
1088 required
= FIDO2ENROLL_PIN_IF_NEEDED
| FIDO2ENROLL_UP_IF_NEEDED
| FIDO2ENROLL_UV_OMIT
;
1089 } else if (!use_libcryptsetup_plugin
) {
1090 r
= find_fido2_auto_data(
1094 &discovered_salt_size
,
1096 &discovered_cid_size
,
1100 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
))
1101 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1102 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1106 if ((required
& (FIDO2ENROLL_PIN
| FIDO2ENROLL_UP
| FIDO2ENROLL_UV
)) && arg_headless
)
1107 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
),
1108 "Local verification is required to unlock this volume, but the 'headless' parameter was set.");
1110 rp_id
= discovered_rp_id
;
1111 key_data
= discovered_salt
;
1112 key_data_size
= discovered_salt_size
;
1113 cid
= discovered_cid
;
1114 cid_size
= discovered_cid_size
;
1117 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1122 if (use_libcryptsetup_plugin
&& !arg_fido2_cid
) {
1123 r
= attach_luks2_by_fido2_via_plugin(cd
, name
, until
, arg_headless
, arg_fido2_device
, flags
);
1124 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
, -ENOENT
))
1125 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1126 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1129 r
= acquire_fido2_key(
1135 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1136 key_data
, key_data_size
,
1140 &decrypted_key
, &decrypted_key_size
,
1141 arg_ask_password_flags
);
1146 if (r
!= -EAGAIN
) /* EAGAIN means: token not found */
1150 /* We didn't find the token. In this case, watch for it via udev. Let's
1151 * create an event loop and monitor first. */
1155 r
= make_security_device_monitor(&event
, &monitor
);
1159 log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly
);
1161 /* Let's immediately rescan in case the token appeared in the time we needed
1162 * to create and configure the monitor */
1166 r
= run_security_device_monitor(event
, monitor
);
1170 log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
1173 if (pass_volume_key
)
1174 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1176 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1178 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1180 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1184 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1187 log_error_errno(r
, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
1188 return -EAGAIN
; /* log actual error, but return EAGAIN */
1191 return log_error_errno(r
, "Failed to activate with FIDO2 acquired key: %m");
1196 static int attach_luks2_by_pkcs11_via_plugin(
1197 struct crypt_device
*cd
,
1199 const char *friendly_name
,
1204 #if HAVE_LIBCRYPTSETUP_PLUGINS
1207 if (!streq_ptr(crypt_get_type(cd
), CRYPT_LUKS2
))
1208 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Automatic PKCS#11 metadata requires LUKS2 device.");
1210 systemd_pkcs11_plugin_params params
= {
1211 .friendly_name
= friendly_name
,
1213 .headless
= headless
1216 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-pkcs11", CRYPT_ANY_TOKEN
, NULL
, 0, ¶ms
, flags
);
1217 if (r
> 0) /* returns unlocked keyslot id on success */
1226 static int attach_luks_or_plain_or_bitlk_by_pkcs11(
1227 struct crypt_device
*cd
,
1229 const char *key_file
,
1230 const void *key_data
,
1231 size_t key_data_size
,
1234 bool pass_volume_key
) {
1236 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1237 _cleanup_free_
char *friendly
= NULL
, *discovered_uri
= NULL
;
1238 size_t decrypted_key_size
= 0, discovered_key_size
= 0;
1239 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
1240 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1241 _cleanup_free_
void *discovered_key
= NULL
;
1242 int keyslot
= arg_key_slot
, r
;
1243 const char *uri
= NULL
;
1244 bool use_libcryptsetup_plugin
= libcryptsetup_plugins_support();
1248 assert(arg_pkcs11_uri
|| arg_pkcs11_uri_auto
);
1250 if (arg_pkcs11_uri_auto
) {
1251 if (!use_libcryptsetup_plugin
) {
1252 r
= find_pkcs11_auto_data(cd
, &discovered_uri
, &discovered_key
, &discovered_key_size
, &keyslot
);
1253 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
))
1254 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1255 "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1259 uri
= discovered_uri
;
1260 key_data
= discovered_key
;
1261 key_data_size
= discovered_key_size
;
1264 uri
= arg_pkcs11_uri
;
1266 if (!key_file
&& !key_data
)
1267 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "PKCS#11 mode selected but no key file specified, refusing.");
1270 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1275 if (use_libcryptsetup_plugin
&& arg_pkcs11_uri_auto
)
1276 r
= attach_luks2_by_pkcs11_via_plugin(cd
, name
, friendly
, until
, arg_headless
, flags
);
1278 r
= decrypt_pkcs11_key(
1282 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1283 key_data
, key_data_size
,
1286 &decrypted_key
, &decrypted_key_size
);
1291 if (r
!= -EAGAIN
) /* EAGAIN means: token not found */
1295 /* We didn't find the token. In this case, watch for it via udev. Let's
1296 * create an event loop and monitor first. */
1300 r
= make_security_device_monitor(&event
, &monitor
);
1304 log_notice("Security token %s not present for unlocking volume %s, please plug it in.",
1307 /* Let's immediately rescan in case the token appeared in the time we needed
1308 * to create and configure the monitor */
1312 r
= run_security_device_monitor(event
, monitor
);
1316 log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
1318 assert(decrypted_key
);
1320 if (pass_volume_key
)
1321 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1323 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1325 /* Before using this key as passphrase we base64 encode it. Why? For compatibility
1326 * with homed's PKCS#11 hookup: there we want to use the key we acquired through
1327 * PKCS#11 for other authentication/decryption mechanisms too, and some of them do
1328 * not take arbitrary binary blobs, but require NUL-terminated strings — most
1329 * importantly UNIX password hashes. Hence, for compatibility we want to use a string
1330 * without embedded NUL here too, and that's easiest to generate from a binary blob
1331 * via base64 encoding. */
1333 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1337 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1340 log_error_errno(r
, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
1341 return -EAGAIN
; /* log actual error, but return EAGAIN */
1344 return log_error_errno(r
, "Failed to activate with PKCS#11 acquired key: %m");
1349 static int make_tpm2_device_monitor(
1350 sd_event
**ret_event
,
1351 sd_device_monitor
**ret_monitor
) {
1353 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1354 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1358 assert(ret_monitor
);
1360 r
= sd_event_default(&event
);
1362 return log_error_errno(r
, "Failed to allocate event loop: %m");
1364 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, arg_token_timeout_usec
, USEC_PER_SEC
, NULL
, INT_TO_PTR(-ETIMEDOUT
));
1366 return log_error_errno(r
, "Failed to install timeout event source: %m");
1368 r
= sd_device_monitor_new(&monitor
);
1370 return log_error_errno(r
, "Failed to allocate device monitor: %m");
1372 r
= sd_device_monitor_filter_add_match_subsystem_devtype(monitor
, "tpmrm", NULL
);
1374 return log_error_errno(r
, "Failed to configure device monitor: %m");
1376 r
= sd_device_monitor_attach_event(monitor
, event
);
1378 return log_error_errno(r
, "Failed to attach device monitor: %m");
1380 r
= sd_device_monitor_start(monitor
, NULL
, NULL
);
1382 return log_error_errno(r
, "Failed to start device monitor: %m");
1384 *ret_event
= TAKE_PTR(event
);
1385 *ret_monitor
= TAKE_PTR(monitor
);
1389 static int attach_luks2_by_tpm2_via_plugin(
1390 struct crypt_device
*cd
,
1396 #if HAVE_LIBCRYPTSETUP_PLUGINS
1397 systemd_tpm2_plugin_params params
= {
1398 .search_pcr_mask
= arg_tpm2_pcr_mask
,
1399 .device
= arg_tpm2_device
,
1400 .signature_path
= arg_tpm2_signature
,
1403 if (!libcryptsetup_plugins_support())
1404 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1405 "Libcryptsetup has external plugins support disabled.");
1407 return crypt_activate_by_token_pin_ask_password(
1415 "Please enter TPM2 PIN:",
1417 "cryptsetup.tpm2-pin");
1423 static int attach_luks_or_plain_or_bitlk_by_tpm2(
1424 struct crypt_device
*cd
,
1426 const char *key_file
,
1427 const void *key_data
,
1428 size_t key_data_size
,
1431 bool pass_volume_key
) {
1433 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1434 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
1435 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1436 _cleanup_free_
char *friendly
= NULL
;
1437 int keyslot
= arg_key_slot
, r
;
1438 size_t decrypted_key_size
;
1442 assert(arg_tpm2_device
|| arg_tpm2_device_auto
);
1444 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1449 if (key_file
|| key_data
) {
1450 /* If key data is specified, use that */
1452 r
= acquire_tpm2_key(
1455 arg_tpm2_pcr_mask
== UINT32_MAX
? TPM2_PCR_MASK_DEFAULT
: arg_tpm2_pcr_mask
,
1457 /* pubkey= */ NULL
, /* pubkey_size= */ 0,
1458 /* pubkey_pcr_mask= */ 0,
1459 /* signature_path= */ NULL
,
1460 /* primary_alg= */ 0,
1461 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1462 key_data
, key_data_size
,
1463 /* policy_hash= */ NULL
, /* policy_hash_size= */ 0, /* we don't know the policy hash */
1464 arg_tpm2_pin
? TPM2_FLAGS_USE_PIN
: 0,
1467 arg_ask_password_flags
,
1468 &decrypted_key
, &decrypted_key_size
);
1471 if (IN_SET(r
, -EACCES
, -ENOLCK
))
1472 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
1473 if (ERRNO_IS_NOT_SUPPORTED(r
)) /* TPM2 support not compiled in? */
1474 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 support not available, falling back to traditional unlocking.");
1475 /* EAGAIN means: no tpm2 chip found */
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. */
1481 r
= attach_luks2_by_tpm2_via_plugin(cd
, name
, until
, arg_headless
, flags
);
1484 /* EAGAIN means: no tpm2 chip found
1485 * EOPNOTSUPP means: no libcryptsetup plugins support */
1487 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
),
1488 "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
1490 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1491 "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
1492 if (!IN_SET(r
, -EOPNOTSUPP
, -EAGAIN
)) {
1493 log_notice_errno(r
, "TPM2 operation failed, falling back to traditional unlocking: %m");
1494 return -EAGAIN
; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1498 if (r
== -EOPNOTSUPP
) { /* Plugin not available, let's process TPM2 stuff right here instead */
1499 _cleanup_free_
void *blob
= NULL
, *policy_hash
= NULL
;
1500 size_t blob_size
, policy_hash_size
;
1501 bool found_some
= false;
1502 int token
= 0; /* first token to look at */
1504 /* If no key data is specified, look for it in the header. In order to support
1505 * software upgrades we'll iterate through all suitable tokens, maybe one of them
1509 _cleanup_free_
void *pubkey
= NULL
;
1510 size_t pubkey_size
= 0;
1511 uint32_t hash_pcr_mask
, pubkey_pcr_mask
;
1512 uint16_t pcr_bank
, primary_alg
;
1513 TPM2Flags tpm2_flags
;
1515 r
= find_tpm2_auto_data(
1517 arg_tpm2_pcr_mask
, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1518 token
, /* search for the token with this index, or any later index than this */
1521 &pubkey
, &pubkey_size
,
1525 &policy_hash
, &policy_hash_size
,
1530 /* No further TPM2 tokens found in the LUKS2 header. */
1531 return log_full_errno(found_some
? LOG_NOTICE
: LOG_DEBUG
,
1532 SYNTHETIC_ERRNO(EAGAIN
),
1534 ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
1535 : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
1536 if (ERRNO_IS_NOT_SUPPORTED(r
)) /* TPM2 support not compiled in? */
1537 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 support not available, falling back to traditional unlocking.");
1543 r
= acquire_tpm2_key(
1548 pubkey
, pubkey_size
,
1552 /* key_file= */ NULL
, /* key_file_size= */ 0, /* key_file_offset= */ 0, /* no key file */
1554 policy_hash
, policy_hash_size
,
1558 arg_ask_password_flags
,
1559 &decrypted_key
, &decrypted_key_size
);
1560 if (IN_SET(r
, -EACCES
, -ENOLCK
))
1561 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
1565 token
++; /* try a different token next time */
1570 /* EAGAIN means: no tpm2 chip found */
1572 log_notice_errno(r
, "TPM2 operation failed, falling back to traditional unlocking: %m");
1573 return -EAGAIN
; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1578 /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
1579 * an event loop and monitor first. */
1583 if (is_efi_boot() && !efi_has_tpm2())
1584 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
),
1585 "No TPM2 hardware discovered and EFI firmware does not see it either, falling back to traditional unlocking.");
1587 r
= make_tpm2_device_monitor(&event
, &monitor
);
1591 log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly
);
1593 /* Let's immediately rescan in case the device appeared in the time we needed
1594 * to create and configure the monitor */
1598 r
= run_security_device_monitor(event
, monitor
);
1602 log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
1604 assert(decrypted_key
);
1606 if (pass_volume_key
)
1607 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1609 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1611 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1613 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1617 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1620 log_error_errno(r
, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
1621 return -EAGAIN
; /* log actual error, but return EAGAIN */
1624 return log_error_errno(r
, "Failed to activate with TPM2 acquired key: %m");
1629 static int attach_luks_or_plain_or_bitlk_by_key_data(
1630 struct crypt_device
*cd
,
1632 const void *key_data
,
1633 size_t key_data_size
,
1635 bool pass_volume_key
) {
1643 if (pass_volume_key
)
1644 r
= crypt_activate_by_volume_key(cd
, name
, key_data
, key_data_size
, flags
);
1646 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, key_data
, key_data_size
, flags
);
1648 log_error_errno(r
, "Failed to activate. (Key incorrect?)");
1649 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1652 return log_error_errno(r
, "Failed to activate: %m");
1657 static int attach_luks_or_plain_or_bitlk_by_key_file(
1658 struct crypt_device
*cd
,
1660 const char *key_file
,
1662 bool pass_volume_key
) {
1664 _cleanup_(erase_and_freep
) char *kfdata
= NULL
;
1665 _cleanup_free_
char *bindname
= NULL
;
1673 /* If we read the key via AF_UNIX, make this client recognizable */
1674 bindname
= make_bindname(name
);
1678 r
= read_full_file_full(
1680 arg_keyfile_offset
== 0 ? UINT64_MAX
: arg_keyfile_offset
,
1681 arg_keyfile_size
== 0 ? SIZE_MAX
: arg_keyfile_size
,
1682 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
1686 log_error_errno(r
, "Failed to activate, key file '%s' too large.", key_file
);
1690 log_error_errno(r
, "Failed to activate, key file '%s' missing.", key_file
);
1691 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1694 return log_error_errno(r
, "Failed to read key file '%s': %m", key_file
);
1696 if (pass_volume_key
)
1697 r
= crypt_activate_by_volume_key(cd
, name
, kfdata
, kfsize
, flags
);
1699 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, kfdata
, kfsize
, flags
);
1701 log_error_errno(r
, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file
);
1702 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1705 return log_error_errno(r
, "Failed to activate with key file '%s': %m", key_file
);
1710 static int attach_luks_or_plain_or_bitlk_by_passphrase(
1711 struct crypt_device
*cd
,
1715 bool pass_volume_key
) {
1723 STRV_FOREACH(p
, passwords
) {
1724 if (pass_volume_key
)
1725 r
= crypt_activate_by_volume_key(cd
, name
, *p
, arg_key_size
, flags
);
1727 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, *p
, strlen(*p
), flags
);
1732 log_error_errno(r
, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
1733 return -EAGAIN
; /* log actual error, but return EAGAIN */
1736 return log_error_errno(r
, "Failed to activate with specified passphrase: %m");
1741 static int attach_luks_or_plain_or_bitlk(
1742 struct crypt_device
*cd
,
1744 const char *key_file
,
1745 const void *key_data
,
1746 size_t key_data_size
,
1751 bool pass_volume_key
= false;
1757 if ((!arg_type
&& !crypt_get_type(cd
)) || streq_ptr(arg_type
, CRYPT_PLAIN
)) {
1758 struct crypt_params_plain params
= {
1759 .offset
= arg_offset
,
1761 .sector_size
= arg_sector_size
,
1763 const char *cipher
, *cipher_mode
;
1764 _cleanup_free_
char *truncated_cipher
= NULL
;
1766 if (streq_ptr(arg_hash
, "plain"))
1767 /* plain isn't a real hash type. it just means "use no hash" */
1770 params
.hash
= arg_hash
;
1772 /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
1773 * file is provided */
1774 params
.hash
= "ripemd160";
1779 l
= strcspn(arg_cipher
, "-");
1780 truncated_cipher
= strndup(arg_cipher
, l
);
1781 if (!truncated_cipher
)
1784 cipher
= truncated_cipher
;
1785 cipher_mode
= arg_cipher
[l
] ? arg_cipher
+l
+1 : "plain";
1788 cipher_mode
= "cbc-essiv:sha256";
1791 /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
1792 arg_keyfile_size
= arg_key_size
;
1794 /* In contrast to what the name crypt_format() might suggest this doesn't actually format
1795 * anything, it just configures encryption parameters when used for plain mode. */
1796 r
= crypt_format(cd
, CRYPT_PLAIN
, cipher
, cipher_mode
, NULL
, NULL
, arg_keyfile_size
, ¶ms
);
1798 return log_error_errno(r
, "Loading of cryptographic parameters failed: %m");
1800 /* hash == NULL implies the user passed "plain" */
1801 pass_volume_key
= !params
.hash
;
1804 log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
1805 crypt_get_cipher(cd
),
1806 crypt_get_cipher_mode(cd
),
1807 crypt_get_volume_key_size(cd
)*8,
1808 crypt_get_device_name(cd
));
1810 if (arg_tpm2_device
|| arg_tpm2_device_auto
)
1811 return attach_luks_or_plain_or_bitlk_by_tpm2(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1812 if (arg_fido2_device
|| arg_fido2_device_auto
)
1813 return attach_luks_or_plain_or_bitlk_by_fido2(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1814 if (arg_pkcs11_uri
|| arg_pkcs11_uri_auto
)
1815 return attach_luks_or_plain_or_bitlk_by_pkcs11(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1817 return attach_luks_or_plain_or_bitlk_by_key_data(cd
, name
, key_data
, key_data_size
, flags
, pass_volume_key
);
1819 return attach_luks_or_plain_or_bitlk_by_key_file(cd
, name
, key_file
, flags
, pass_volume_key
);
1821 return attach_luks_or_plain_or_bitlk_by_passphrase(cd
, name
, passwords
, flags
, pass_volume_key
);
1824 static int help(void) {
1825 _cleanup_free_
char *link
= NULL
;
1828 r
= terminal_urlify_man("systemd-cryptsetup@.service", "8", &link
);
1832 printf("%s attach VOLUME SOURCEDEVICE [KEY-FILE] [OPTIONS]\n"
1833 "%s detach VOLUME\n\n"
1834 "Attaches or detaches an encrypted block device.\n"
1835 "\nSee the %s for details.\n",
1836 program_invocation_short_name
,
1837 program_invocation_short_name
,
1843 static uint32_t determine_flags(void) {
1847 flags
|= CRYPT_ACTIVATE_READONLY
;
1850 flags
|= CRYPT_ACTIVATE_ALLOW_DISCARDS
;
1852 if (arg_same_cpu_crypt
)
1853 flags
|= CRYPT_ACTIVATE_SAME_CPU_CRYPT
;
1855 if (arg_submit_from_crypt_cpus
)
1856 flags
|= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS
;
1858 if (arg_no_read_workqueue
)
1859 flags
|= CRYPT_ACTIVATE_NO_READ_WORKQUEUE
;
1861 if (arg_no_write_workqueue
)
1862 flags
|= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE
;
1864 #ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
1865 /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
1866 /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
1867 flags
|= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
;
1873 static void remove_and_erasep(const char **p
) {
1879 r
= unlinkat_deallocate(AT_FDCWD
, *p
, UNLINK_ERASE
);
1880 if (r
< 0 && r
!= -ENOENT
)
1881 log_warning_errno(r
, "Unable to erase key file '%s', ignoring: %m", *p
);
1884 static int run(int argc
, char *argv
[]) {
1885 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1889 if (argv_looks_like_help(argc
, argv
))
1893 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1894 "This program requires at least two arguments.");
1898 cryptsetup_enable_logging(NULL
);
1904 if (streq(verb
, "attach")) {
1905 _unused_
_cleanup_(remove_and_erasep
) const char *destroy_key_file
= NULL
;
1906 _cleanup_(erase_and_freep
) void *key_data
= NULL
;
1907 const char *volume
, *source
, *key_file
, *options
;
1908 crypt_status_info status
;
1909 size_t key_data_size
= 0;
1913 PassphraseType passphrase_type
= PASSPHRASE_NONE
;
1915 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [KEY-FILE] [OPTIONS] */
1918 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "attach requires at least two arguments.");
1922 key_file
= mangle_none(argc
>= 5 ? argv
[4] : NULL
);
1923 options
= mangle_none(argc
>= 6 ? argv
[5] : NULL
);
1925 if (!filename_is_valid(volume
))
1926 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume name '%s' is not valid.", volume
);
1928 if (key_file
&& !path_is_absolute(key_file
)) {
1929 log_warning("Password file path '%s' is not absolute. Ignoring.", key_file
);
1934 r
= parse_options(options
);
1939 log_debug("%s %s ← %s type=%s cipher=%s", __func__
,
1940 volume
, source
, strempty(arg_type
), strempty(arg_cipher
));
1942 /* A delicious drop of snake oil */
1943 (void) mlockall(MCL_FUTURE
);
1946 _cleanup_free_
char *bindname
= NULL
;
1949 bindname
= make_bindname(volume
);
1953 /* If a key file is not explicitly specified, search for a key in a well defined
1954 * search path, and load it. */
1956 fn
= strjoina(volume
, ".key");
1959 STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"),
1961 &key_data
, &key_data_size
);
1965 log_debug("Automatically discovered key for volume '%s'.", volume
);
1966 } else if (arg_keyfile_erase
)
1967 destroy_key_file
= key_file
; /* let's get this baby erased when we leave */
1970 log_debug("LUKS header: %s", arg_header
);
1971 r
= crypt_init(&cd
, arg_header
);
1973 r
= crypt_init(&cd
, source
);
1975 return log_error_errno(r
, "crypt_init() failed: %m");
1977 cryptsetup_enable_logging(cd
);
1979 status
= crypt_status(cd
, volume
);
1980 if (IN_SET(status
, CRYPT_ACTIVE
, CRYPT_BUSY
)) {
1981 log_info("Volume %s already active.", volume
);
1985 flags
= determine_flags();
1987 until
= usec_add(now(CLOCK_MONOTONIC
), arg_timeout
);
1988 if (until
== USEC_INFINITY
)
1991 arg_key_size
= (arg_key_size
> 0 ? arg_key_size
: (256 / 8));
1996 /* Ideally we'd do this on the open fd, but since this is just a
1997 * warning it's OK to do this in two steps. */
1998 if (stat(key_file
, &st
) >= 0 && S_ISREG(st
.st_mode
) && (st
.st_mode
& 0005))
1999 log_warning("Key file %s is world-readable. This is not a good idea!", key_file
);
2002 if (!arg_type
|| STR_IN_SET(arg_type
, ANY_LUKS
, CRYPT_LUKS1
, CRYPT_LUKS2
)) {
2003 r
= crypt_load(cd
, !arg_type
|| streq(arg_type
, ANY_LUKS
) ? CRYPT_LUKS
: arg_type
, NULL
);
2005 return log_error_errno(r
, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd
));
2008 r
= crypt_set_data_device(cd
, source
);
2010 return log_error_errno(r
, "Failed to set LUKS data device %s: %m", source
);
2013 /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
2014 if (!key_file
&& !key_data
&& getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE") != 0) {
2015 r
= crypt_activate_by_token_pin_ask_password(
2023 "Please enter LUKS2 token PIN:",
2025 "cryptsetup.luks2-pin");
2027 log_debug("Volume %s activated with LUKS token id %i.", volume
, r
);
2031 log_debug_errno(r
, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd
));
2035 /* since cryptsetup 2.3.0 (Feb 2020) */
2037 if (streq_ptr(arg_type
, CRYPT_BITLK
)) {
2038 r
= crypt_load(cd
, CRYPT_BITLK
, NULL
);
2040 return log_error_errno(r
, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd
));
2044 for (tries
= 0; arg_tries
== 0 || tries
< arg_tries
; tries
++) {
2045 _cleanup_strv_free_erase_
char **passwords
= NULL
;
2047 /* When we were able to acquire multiple keys, let's always process them in this order:
2049 * 1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
2050 * 2. The discovered key: i.e. key_data + key_data_size
2051 * 3. The configured key: i.e. key_file + arg_keyfile_offset + arg_keyfile_size
2052 * 4. The empty password, in case arg_try_empty_password is set
2053 * 5. We enquire the user for a password
2056 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
) {
2058 if (arg_try_empty_password
) {
2059 /* Hmm, let's try an empty password now, but only once */
2060 arg_try_empty_password
= false;
2062 key_data
= strdup("");
2068 /* Ask the user for a passphrase or recovery key only as last resort, if we have
2069 * nothing else to check for */
2070 if (passphrase_type
== PASSPHRASE_NONE
) {
2071 passphrase_type
= check_registered_passwords(cd
);
2072 if (passphrase_type
== PASSPHRASE_NONE
)
2073 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No passphrase or recovery key registered.");
2076 r
= get_password(volume
, source
, until
, tries
== 0 && !arg_verify
, passphrase_type
, &passwords
);
2084 if (streq_ptr(arg_type
, CRYPT_TCRYPT
))
2085 r
= attach_tcrypt(cd
, volume
, key_file
, key_data
, key_data_size
, passwords
, flags
);
2087 r
= attach_luks_or_plain_or_bitlk(cd
, volume
, key_file
, key_data
, key_data_size
, passwords
, flags
, until
);
2093 /* Key not correct? Let's try again! */
2096 key_data
= erase_and_free(key_data
);
2098 arg_pkcs11_uri
= mfree(arg_pkcs11_uri
);
2099 arg_pkcs11_uri_auto
= false;
2100 arg_fido2_device
= mfree(arg_fido2_device
);
2101 arg_fido2_device_auto
= false;
2102 arg_tpm2_device
= mfree(arg_tpm2_device
);
2103 arg_tpm2_device_auto
= false;
2106 if (arg_tries
!= 0 && tries
>= arg_tries
)
2107 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Too many attempts to activate; giving up.");
2109 } else if (streq(verb
, "detach")) {
2114 if (!filename_is_valid(volume
))
2115 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume name '%s' is not valid.", volume
);
2117 r
= crypt_init_by_name(&cd
, volume
);
2119 log_info("Volume %s already inactive.", volume
);
2123 return log_error_errno(r
, "crypt_init_by_name() failed: %m");
2125 cryptsetup_enable_logging(cd
);
2127 r
= crypt_deactivate(cd
, volume
);
2129 return log_error_errno(r
, "Failed to deactivate: %m");
2132 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown verb %s.", verb
);
2137 DEFINE_MAIN_FUNCTION(run
);