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"
20 #include "efi-loader.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 "random-util.h"
38 #include "string-util.h"
40 #include "tpm2-util.h"
43 #define ANY_LUKS "LUKS"
44 /* as in src/cryptsetup.h */
45 #define CRYPT_SECTOR_SIZE 512
46 #define CRYPT_MAX_SECTOR_SIZE 4096
48 static const char *arg_type
= NULL
; /* ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT, CRYPT_BITLK or CRYPT_PLAIN */
49 static char *arg_cipher
= NULL
;
50 static unsigned arg_key_size
= 0;
51 static unsigned arg_sector_size
= CRYPT_SECTOR_SIZE
;
52 static int arg_key_slot
= CRYPT_ANY_SLOT
;
53 static unsigned arg_keyfile_size
= 0;
54 static uint64_t arg_keyfile_offset
= 0;
55 static bool arg_keyfile_erase
= false;
56 static bool arg_try_empty_password
= false;
57 static char *arg_hash
= NULL
;
58 static char *arg_header
= NULL
;
59 static unsigned arg_tries
= 3;
60 static bool arg_readonly
= false;
61 static bool arg_verify
= false;
62 static AskPasswordFlags arg_ask_password_flags
= 0;
63 static bool arg_discards
= false;
64 static bool arg_same_cpu_crypt
= false;
65 static bool arg_submit_from_crypt_cpus
= false;
66 static bool arg_no_read_workqueue
= false;
67 static bool arg_no_write_workqueue
= false;
68 static bool arg_tcrypt_hidden
= false;
69 static bool arg_tcrypt_system
= false;
70 static bool arg_tcrypt_veracrypt
= false;
71 static char **arg_tcrypt_keyfiles
= NULL
;
72 static uint64_t arg_offset
= 0;
73 static uint64_t arg_skip
= 0;
74 static usec_t arg_timeout
= USEC_INFINITY
;
75 static char *arg_pkcs11_uri
= NULL
;
76 static bool arg_pkcs11_uri_auto
= false;
77 static char *arg_fido2_device
= NULL
;
78 static bool arg_fido2_device_auto
= false;
79 static void *arg_fido2_cid
= NULL
;
80 static size_t arg_fido2_cid_size
= 0;
81 static char *arg_fido2_rp_id
= NULL
;
82 static char *arg_tpm2_device
= NULL
;
83 static bool arg_tpm2_device_auto
= false;
84 static uint32_t arg_tpm2_pcr_mask
= UINT32_MAX
;
85 static bool arg_tpm2_pin
= false;
86 static bool arg_headless
= false;
87 static usec_t arg_token_timeout_usec
= 30*USEC_PER_SEC
;
89 STATIC_DESTRUCTOR_REGISTER(arg_cipher
, freep
);
90 STATIC_DESTRUCTOR_REGISTER(arg_hash
, freep
);
91 STATIC_DESTRUCTOR_REGISTER(arg_header
, freep
);
92 STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles
, strv_freep
);
93 STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri
, freep
);
94 STATIC_DESTRUCTOR_REGISTER(arg_fido2_device
, freep
);
95 STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid
, freep
);
96 STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id
, freep
);
97 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
99 /* Options Debian's crypttab knows we don't:
110 static int parse_one_option(const char *option
) {
116 /* Handled outside of this tool */
117 if (STR_IN_SET(option
, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
120 if (startswith(option
, "keyfile-timeout="))
123 if ((val
= startswith(option
, "cipher="))) {
124 r
= free_and_strdup(&arg_cipher
, val
);
128 } else if ((val
= startswith(option
, "size="))) {
130 r
= safe_atou(val
, &arg_key_size
);
132 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
136 if (arg_key_size
% 8) {
137 log_error("size= not a multiple of 8, ignoring.");
143 } else if ((val
= startswith(option
, "sector-size="))) {
145 r
= safe_atou(val
, &arg_sector_size
);
147 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
151 if (arg_sector_size
% 2) {
152 log_error("sector-size= not a multiple of 2, ignoring.");
156 if (arg_sector_size
< CRYPT_SECTOR_SIZE
|| arg_sector_size
> CRYPT_MAX_SECTOR_SIZE
) {
157 log_error("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE
, CRYPT_MAX_SECTOR_SIZE
);
161 } else if ((val
= startswith(option
, "key-slot=")) ||
162 (val
= startswith(option
, "keyslot="))) {
165 r
= safe_atoi(val
, &arg_key_slot
);
167 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
171 } else if ((val
= startswith(option
, "tcrypt-keyfile="))) {
173 arg_type
= CRYPT_TCRYPT
;
174 if (path_is_absolute(val
)) {
175 if (strv_extend(&arg_tcrypt_keyfiles
, val
) < 0)
178 log_error("Key file path \"%s\" is not absolute. Ignoring.", val
);
180 } else if ((val
= startswith(option
, "keyfile-size="))) {
182 r
= safe_atou(val
, &arg_keyfile_size
);
184 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
188 } else if ((val
= startswith(option
, "keyfile-offset="))) {
190 r
= safe_atou64(val
, &arg_keyfile_offset
);
192 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
196 } else if ((val
= startswith(option
, "keyfile-erase="))) {
198 r
= parse_boolean(val
);
200 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
204 arg_keyfile_erase
= r
;
206 } else if (streq(option
, "keyfile-erase"))
207 arg_keyfile_erase
= true;
209 else if ((val
= startswith(option
, "hash="))) {
210 r
= free_and_strdup(&arg_hash
, val
);
214 } else if ((val
= startswith(option
, "header="))) {
217 if (!path_is_absolute(val
))
218 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
219 "Header path \"%s\" is not absolute, refusing.", val
);
222 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
223 "Duplicate header= option, refusing.");
225 arg_header
= strdup(val
);
229 } else if ((val
= startswith(option
, "tries="))) {
231 r
= safe_atou(val
, &arg_tries
);
233 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
237 } else if (STR_IN_SET(option
, "readonly", "read-only"))
239 else if (streq(option
, "verify"))
241 else if ((val
= startswith(option
, "password-echo="))) {
242 if (streq(val
, "masked"))
243 arg_ask_password_flags
&= ~(ASK_PASSWORD_ECHO
|ASK_PASSWORD_SILENT
);
245 r
= parse_boolean(val
);
247 log_warning_errno(r
, "Invalid password-echo= option \"%s\", ignoring.", val
);
251 SET_FLAG(arg_ask_password_flags
, ASK_PASSWORD_ECHO
, r
);
252 SET_FLAG(arg_ask_password_flags
, ASK_PASSWORD_SILENT
, !r
);
254 } else if (STR_IN_SET(option
, "allow-discards", "discard"))
256 else if (streq(option
, "same-cpu-crypt"))
257 arg_same_cpu_crypt
= true;
258 else if (streq(option
, "submit-from-crypt-cpus"))
259 arg_submit_from_crypt_cpus
= true;
260 else if (streq(option
, "no-read-workqueue"))
261 arg_no_read_workqueue
= true;
262 else if (streq(option
, "no-write-workqueue"))
263 arg_no_write_workqueue
= true;
264 else if (streq(option
, "luks"))
266 /* since cryptsetup 2.3.0 (Feb 2020) */
268 else if (streq(option
, "bitlk"))
269 arg_type
= CRYPT_BITLK
;
271 else if (streq(option
, "tcrypt"))
272 arg_type
= CRYPT_TCRYPT
;
273 else if (STR_IN_SET(option
, "tcrypt-hidden", "tcrypthidden")) {
274 arg_type
= CRYPT_TCRYPT
;
275 arg_tcrypt_hidden
= true;
276 } else if (streq(option
, "tcrypt-system")) {
277 arg_type
= CRYPT_TCRYPT
;
278 arg_tcrypt_system
= true;
279 } else if (STR_IN_SET(option
, "tcrypt-veracrypt", "veracrypt")) {
280 arg_type
= CRYPT_TCRYPT
;
281 arg_tcrypt_veracrypt
= true;
282 } else if (STR_IN_SET(option
, "plain", "swap", "tmp") ||
283 startswith(option
, "tmp="))
284 arg_type
= CRYPT_PLAIN
;
285 else if ((val
= startswith(option
, "timeout="))) {
287 r
= parse_sec_fix_0(val
, &arg_timeout
);
289 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
293 } else if ((val
= startswith(option
, "offset="))) {
295 r
= safe_atou64(val
, &arg_offset
);
297 return log_error_errno(r
, "Failed to parse %s: %m", option
);
299 } else if ((val
= startswith(option
, "skip="))) {
301 r
= safe_atou64(val
, &arg_skip
);
303 return log_error_errno(r
, "Failed to parse %s: %m", option
);
305 } else if ((val
= startswith(option
, "pkcs11-uri="))) {
307 if (streq(val
, "auto")) {
308 arg_pkcs11_uri
= mfree(arg_pkcs11_uri
);
309 arg_pkcs11_uri_auto
= true;
311 if (!pkcs11_uri_valid(val
))
312 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing");
314 r
= free_and_strdup(&arg_pkcs11_uri
, val
);
318 arg_pkcs11_uri_auto
= false;
321 } else if ((val
= startswith(option
, "fido2-device="))) {
323 if (streq(val
, "auto")) {
324 arg_fido2_device
= mfree(arg_fido2_device
);
325 arg_fido2_device_auto
= true;
327 r
= free_and_strdup(&arg_fido2_device
, val
);
331 arg_fido2_device_auto
= false;
334 } else if ((val
= startswith(option
, "fido2-cid="))) {
336 if (streq(val
, "auto"))
337 arg_fido2_cid
= mfree(arg_fido2_cid
);
339 _cleanup_free_
void *cid
= NULL
;
342 r
= unbase64mem(val
, SIZE_MAX
, &cid
, &cid_size
);
344 return log_error_errno(r
, "Failed to decode FIDO2 CID data: %m");
347 arg_fido2_cid
= TAKE_PTR(cid
);
348 arg_fido2_cid_size
= cid_size
;
351 /* Turn on FIDO2 as side-effect, if not turned on yet. */
352 if (!arg_fido2_device
&& !arg_fido2_device_auto
)
353 arg_fido2_device_auto
= true;
355 } else if ((val
= startswith(option
, "fido2-rp="))) {
357 r
= free_and_strdup(&arg_fido2_rp_id
, val
);
361 } else if ((val
= startswith(option
, "tpm2-device="))) {
363 if (streq(val
, "auto")) {
364 arg_tpm2_device
= mfree(arg_tpm2_device
);
365 arg_tpm2_device_auto
= true;
367 r
= free_and_strdup(&arg_tpm2_device
, val
);
371 arg_tpm2_device_auto
= false;
374 } else if ((val
= startswith(option
, "tpm2-pcrs="))) {
377 arg_tpm2_pcr_mask
= 0;
381 r
= tpm2_parse_pcrs(val
, &mask
);
385 if (arg_tpm2_pcr_mask
== UINT32_MAX
)
386 arg_tpm2_pcr_mask
= mask
;
388 arg_tpm2_pcr_mask
|= mask
;
391 } else if ((val
= startswith(option
, "tpm2-pin="))) {
393 r
= parse_boolean(val
);
395 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
401 } else if ((val
= startswith(option
, "try-empty-password="))) {
403 r
= parse_boolean(val
);
405 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
409 arg_try_empty_password
= r
;
411 } else if (streq(option
, "try-empty-password"))
412 arg_try_empty_password
= true;
413 else if ((val
= startswith(option
, "headless="))) {
415 r
= parse_boolean(val
);
417 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
422 } else if (streq(option
, "headless"))
425 else if ((val
= startswith(option
, "token-timeout="))) {
427 r
= parse_sec_fix_0(val
, &arg_token_timeout_usec
);
429 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
433 } else if (!streq(option
, "x-initrd.attach"))
434 log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option
);
439 static int parse_options(const char *options
) {
443 _cleanup_free_
char *word
= NULL
;
446 r
= extract_first_word(&options
, &word
, ",", EXTRACT_DONT_COALESCE_SEPARATORS
| EXTRACT_UNESCAPE_SEPARATORS
);
448 return log_error_errno(r
, "Failed to parse options: %m");
452 r
= parse_one_option(word
);
457 /* sanity-check options */
458 if (arg_type
&& !streq(arg_type
, CRYPT_PLAIN
)) {
460 log_warning("offset= ignored with type %s", arg_type
);
462 log_warning("skip= ignored with type %s", arg_type
);
468 static char* disk_description(const char *path
) {
469 static const char name_fields
[] =
471 "ID_MODEL_FROM_DATABASE\0"
474 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
475 const char *i
, *name
;
480 if (stat(path
, &st
) < 0)
483 if (!S_ISBLK(st
.st_mode
))
486 if (sd_device_new_from_stat_rdev(&device
, &st
) < 0)
489 if (sd_device_get_property_value(device
, "ID_PART_ENTRY_NAME", &name
) >= 0) {
490 _cleanup_free_
char *unescaped
= NULL
;
493 /* ID_PART_ENTRY_NAME uses \x style escaping, using libblkid's blkid_encode_string(). Let's
494 * reverse this here to make the string more human friendly in case people embed spaces or
495 * other weird stuff. */
497 l
= cunescape(name
, UNESCAPE_RELAX
, &unescaped
);
499 log_debug_errno(l
, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
503 if (!isempty(unescaped
) && !string_has_cc(unescaped
, NULL
))
504 return TAKE_PTR(unescaped
);
507 /* These need no unescaping. */
508 NULSTR_FOREACH(i
, name_fields
)
509 if (sd_device_get_property_value(device
, i
, &name
) >= 0 &&
516 static char *disk_mount_point(const char *label
) {
517 _cleanup_free_
char *device
= NULL
;
518 _cleanup_endmntent_
FILE *f
= NULL
;
521 /* Yeah, we don't support native systemd unit files here for now */
523 device
= strjoin("/dev/mapper/", label
);
527 f
= setmntent(fstab_path(), "re");
531 while ((m
= getmntent(f
)))
532 if (path_equal(m
->mnt_fsname
, device
))
533 return strdup(m
->mnt_dir
);
538 static char *friendly_disk_name(const char *src
, const char *vol
) {
539 _cleanup_free_
char *description
= NULL
, *mount_point
= NULL
;
540 char *name_buffer
= NULL
;
546 description
= disk_description(src
);
547 mount_point
= disk_mount_point(vol
);
549 /* If the description string is simply the volume name, then let's not show this twice */
550 if (description
&& streq(vol
, description
))
551 description
= mfree(description
);
553 if (mount_point
&& description
)
554 r
= asprintf(&name_buffer
, "%s (%s) on %s", description
, vol
, mount_point
);
555 else if (mount_point
)
556 r
= asprintf(&name_buffer
, "%s on %s", vol
, mount_point
);
557 else if (description
)
558 r
= asprintf(&name_buffer
, "%s (%s)", description
, vol
);
567 static int get_password(
574 _cleanup_free_
char *friendly
= NULL
, *text
= NULL
, *disk_path
= NULL
;
575 _cleanup_strv_free_erase_
char **passwords
= NULL
;
578 AskPasswordFlags flags
= arg_ask_password_flags
| ASK_PASSWORD_PUSH_CACHE
;
585 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "Password querying disabled via 'headless' option.");
587 friendly
= friendly_disk_name(src
, vol
);
591 if (asprintf(&text
, "Please enter passphrase for disk %s:", friendly
) < 0)
594 disk_path
= cescape(src
);
598 id
= strjoina("cryptsetup:", disk_path
);
600 r
= ask_password_auto(text
, "drive-harddisk", id
, "cryptsetup", "cryptsetup.passphrase", until
,
601 flags
| (accept_cached
*ASK_PASSWORD_ACCEPT_CACHED
),
604 return log_error_errno(r
, "Failed to query password: %m");
607 _cleanup_strv_free_erase_
char **passwords2
= NULL
;
609 assert(strv_length(passwords
) == 1);
611 if (asprintf(&text
, "Please enter passphrase for disk %s (verification):", friendly
) < 0)
614 id
= strjoina("cryptsetup-verification:", disk_path
);
616 r
= ask_password_auto(text
, "drive-harddisk", id
, "cryptsetup", "cryptsetup.passphrase", until
, flags
, &passwords2
);
618 return log_error_errno(r
, "Failed to query verification password: %m");
620 assert(strv_length(passwords2
) == 1);
622 if (!streq(passwords
[0], passwords2
[0]))
623 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
),
624 "Passwords did not match, retrying.");
627 strv_uniq(passwords
);
629 STRV_FOREACH(p
, passwords
) {
632 if (strlen(*p
)+1 >= arg_key_size
)
635 /* Pad password if necessary */
636 c
= new(char, arg_key_size
);
640 strncpy(c
, *p
, arg_key_size
);
645 *ret
= TAKE_PTR(passwords
);
650 static int attach_tcrypt(
651 struct crypt_device
*cd
,
653 const char *key_file
,
654 const void *key_data
,
655 size_t key_data_size
,
660 _cleanup_(erase_and_freep
) char *passphrase
= NULL
;
661 struct crypt_params_tcrypt params
= {
662 .flags
= CRYPT_TCRYPT_LEGACY_MODES
,
663 .keyfiles
= (const char **)arg_tcrypt_keyfiles
,
664 .keyfiles_count
= strv_length(arg_tcrypt_keyfiles
)
669 assert(key_file
|| key_data
|| !strv_isempty(passwords
));
671 if (arg_pkcs11_uri
|| arg_pkcs11_uri_auto
|| arg_fido2_device
|| arg_fido2_device_auto
|| arg_tpm2_device
|| arg_tpm2_device_auto
)
672 /* Ask for a regular password */
673 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN
),
674 "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
676 if (arg_tcrypt_hidden
)
677 params
.flags
|= CRYPT_TCRYPT_HIDDEN_HEADER
;
679 if (arg_tcrypt_system
)
680 params
.flags
|= CRYPT_TCRYPT_SYSTEM_HEADER
;
682 if (arg_tcrypt_veracrypt
)
683 params
.flags
|= CRYPT_TCRYPT_VERA_MODES
;
686 params
.passphrase
= key_data
;
687 params
.passphrase_size
= key_data_size
;
690 r
= read_one_line_file(key_file
, &passphrase
);
692 log_error_errno(r
, "Failed to read password file '%s': %m", key_file
);
693 return -EAGAIN
; /* log with the actual error, but return EAGAIN */
696 params
.passphrase
= passphrase
;
698 params
.passphrase
= passwords
[0];
700 params
.passphrase_size
= strlen(params
.passphrase
);
703 r
= crypt_load(cd
, CRYPT_TCRYPT
, ¶ms
);
707 log_error_errno(r
, "Failed to activate using discovered key. (Key not correct?)");
710 log_error_errno(r
, "Failed to activate using password file '%s'. (Key data not correct?)", key_file
);
712 return -EAGAIN
; /* log the actual error, but return EAGAIN */
715 return log_error_errno(r
, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd
));
718 r
= crypt_activate_by_volume_key(cd
, name
, NULL
, 0, flags
);
720 return log_error_errno(r
, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd
));
725 static char *make_bindname(const char *volume
) {
728 if (asprintf(&s
, "@%" PRIx64
"/cryptsetup/%s", random_u64(), volume
) < 0)
734 static int make_security_device_monitor(
735 sd_event
**ret_event
,
736 sd_device_monitor
**ret_monitor
) {
737 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
738 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
744 /* Waits for a device with "security-device" tag to show up in udev */
746 r
= sd_event_default(&event
);
748 return log_error_errno(r
, "Failed to allocate event loop: %m");
750 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, arg_token_timeout_usec
, USEC_PER_SEC
, NULL
, INT_TO_PTR(-ETIMEDOUT
));
752 return log_error_errno(r
, "Failed to install timeout event source: %m");
754 r
= sd_device_monitor_new(&monitor
);
756 return log_error_errno(r
, "Failed to allocate device monitor: %m");
758 r
= sd_device_monitor_filter_add_match_tag(monitor
, "security-device");
760 return log_error_errno(r
, "Failed to configure device monitor: %m");
762 r
= sd_device_monitor_attach_event(monitor
, event
);
764 return log_error_errno(r
, "Failed to attach device monitor: %m");
766 r
= sd_device_monitor_start(monitor
, NULL
, NULL
);
768 return log_error_errno(r
, "Failed to start device monitor: %m");
770 *ret_event
= TAKE_PTR(event
);
771 *ret_monitor
= TAKE_PTR(monitor
);
775 static int run_security_device_monitor(
777 sd_device_monitor
*monitor
) {
778 bool processed
= false;
784 /* Runs the event loop for the device monitor until either something happens, or the time-out is
790 r
= sd_event_get_exit_code(event
, &x
);
793 return log_error_errno(r
, "Failed to query exit code from event loop: %m");
795 /* On ENODATA we aren't told to exit yet. */
797 assert(x
== -ETIMEDOUT
);
798 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
),
799 "Timed out waiting for security device, aborting security device based authentication attempt.");
802 /* Wait for one event, and then eat all subsequent events until there are no further ones */
803 r
= sd_event_run(event
, processed
? 0 : UINT64_MAX
);
805 return log_error_errno(r
, "Failed to run event loop: %m");
806 if (r
== 0) /* no events queued anymore */
813 static bool libcryptsetup_plugins_support(void) {
814 #if HAVE_LIBCRYPTSETUP_PLUGINS
817 /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
818 r
= getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
819 if (r
< 0 && r
!= -ENXIO
)
820 log_debug_errno(r
, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
824 return crypt_token_external_path();
830 #if HAVE_LIBCRYPTSETUP_PLUGINS
831 static int acquire_pins_from_env_variable(char ***ret_pins
) {
832 _cleanup_(erase_and_freep
) char *envpin
= NULL
;
833 _cleanup_strv_free_erase_
char **pins
= NULL
;
838 r
= getenv_steal_erase("PIN", &envpin
);
840 return log_error_errno(r
, "Failed to acquire PIN from environment: %m");
842 pins
= strv_new(envpin
);
847 *ret_pins
= TAKE_PTR(pins
);
853 static int attach_luks2_by_fido2(
854 struct crypt_device
*cd
,
859 uint32_t activation_flags
) {
861 #if HAVE_LIBCRYPTSETUP_PLUGINS
862 AskPasswordFlags flags
= ASK_PASSWORD_PUSH_CACHE
| ASK_PASSWORD_ACCEPT_CACHED
;
863 _cleanup_strv_free_erase_
char **pins
= NULL
;
866 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-fido2", CRYPT_ANY_TOKEN
, NULL
, 0, usrptr
, activation_flags
);
867 if (r
> 0) /* returns unlocked keyslot id on success */
869 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
872 r
= acquire_pins_from_env_variable(&pins
);
876 STRV_FOREACH(p
, pins
) {
877 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-fido2", CRYPT_ANY_TOKEN
, *p
, strlen(*p
), usrptr
, activation_flags
);
878 if (r
> 0) /* returns unlocked keyslot id on success */
880 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
885 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
888 pins
= strv_free_erase(pins
);
889 r
= ask_password_auto("Please enter security token PIN:", "drive-harddisk", NULL
, "fido2-pin", "cryptsetup.fido2-pin", until
, flags
, &pins
);
893 STRV_FOREACH(p
, pins
) {
894 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-fido2", CRYPT_ANY_TOKEN
, *p
, strlen(*p
), usrptr
, activation_flags
);
895 if (r
> 0) /* returns unlocked keyslot id on success */
897 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
901 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
909 static int attach_luks_or_plain_or_bitlk_by_fido2(
910 struct crypt_device
*cd
,
912 const char *key_file
,
913 const void *key_data
,
914 size_t key_data_size
,
917 bool pass_volume_key
) {
919 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
920 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
921 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
922 _cleanup_free_
void *discovered_salt
= NULL
, *discovered_cid
= NULL
;
923 size_t discovered_salt_size
, discovered_cid_size
, decrypted_key_size
, cid_size
= 0;
924 _cleanup_free_
char *friendly
= NULL
, *discovered_rp_id
= NULL
;
925 int keyslot
= arg_key_slot
, r
;
926 const char *rp_id
= NULL
;
927 const void *cid
= NULL
;
928 Fido2EnrollFlags required
;
929 bool use_libcryptsetup_plugin
= libcryptsetup_plugins_support();
933 assert(arg_fido2_device
|| arg_fido2_device_auto
);
936 if (!key_file
&& !key_data
)
937 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
938 "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
940 rp_id
= arg_fido2_rp_id
;
942 cid_size
= arg_fido2_cid_size
;
944 /* For now and for compatibility, if the user explicitly configured FIDO2 support and we do
945 * not read FIDO2 metadata off the LUKS2 header, default to the systemd 248 logic, where we
946 * use PIN + UP when needed, and do not configure UV at all. Eventually, we should make this
947 * explicitly configurable. */
948 required
= FIDO2ENROLL_PIN_IF_NEEDED
| FIDO2ENROLL_UP_IF_NEEDED
| FIDO2ENROLL_UV_OMIT
;
949 } else if (!use_libcryptsetup_plugin
) {
950 r
= find_fido2_auto_data(
954 &discovered_salt_size
,
956 &discovered_cid_size
,
960 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
))
961 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
962 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
966 if ((required
& (FIDO2ENROLL_PIN
| FIDO2ENROLL_UP
| FIDO2ENROLL_UV
)) && arg_headless
)
967 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
),
968 "Local verification is required to unlock this volume, but the 'headless' parameter was set.");
970 rp_id
= discovered_rp_id
;
971 key_data
= discovered_salt
;
972 key_data_size
= discovered_salt_size
;
973 cid
= discovered_cid
;
974 cid_size
= discovered_cid_size
;
977 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
982 if (use_libcryptsetup_plugin
&& !arg_fido2_cid
) {
983 r
= attach_luks2_by_fido2(cd
, name
, until
, arg_headless
, arg_fido2_device
, flags
);
984 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
, -ENOENT
))
985 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
986 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
989 r
= acquire_fido2_key(
995 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
996 key_data
, key_data_size
,
1000 &decrypted_key
, &decrypted_key_size
,
1001 arg_ask_password_flags
);
1006 if (r
!= -EAGAIN
) /* EAGAIN means: token not found */
1010 /* We didn't find the token. In this case, watch for it via udev. Let's
1011 * create an event loop and monitor first. */
1015 r
= make_security_device_monitor(&event
, &monitor
);
1019 log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly
);
1021 /* Let's immediately rescan in case the token appeared in the time we needed
1022 * to create and configure the monitor */
1026 r
= run_security_device_monitor(event
, monitor
);
1030 log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
1033 if (pass_volume_key
)
1034 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1036 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1038 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1040 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1044 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1047 log_error_errno(r
, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
1048 return -EAGAIN
; /* log actual error, but return EAGAIN */
1051 return log_error_errno(r
, "Failed to activate with FIDO2 acquired key: %m");
1056 static int attach_luks2_by_pkcs11(
1057 struct crypt_device
*cd
,
1059 const char *friendly_name
,
1064 #if HAVE_LIBCRYPTSETUP_PLUGINS
1067 if (!streq_ptr(crypt_get_type(cd
), CRYPT_LUKS2
))
1068 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Automatic PKCS#11 metadata requires LUKS2 device.");
1070 systemd_pkcs11_plugin_params params
= {
1071 .friendly_name
= friendly_name
,
1073 .headless
= headless
1076 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-pkcs11", CRYPT_ANY_TOKEN
, NULL
, 0, ¶ms
, flags
);
1077 if (r
> 0) /* returns unlocked keyslot id on success */
1086 static int attach_luks_or_plain_or_bitlk_by_pkcs11(
1087 struct crypt_device
*cd
,
1089 const char *key_file
,
1090 const void *key_data
,
1091 size_t key_data_size
,
1094 bool pass_volume_key
) {
1096 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1097 _cleanup_free_
char *friendly
= NULL
, *discovered_uri
= NULL
;
1098 size_t decrypted_key_size
= 0, discovered_key_size
= 0;
1099 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
1100 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1101 _cleanup_free_
void *discovered_key
= NULL
;
1102 int keyslot
= arg_key_slot
, r
;
1103 const char *uri
= NULL
;
1104 bool use_libcryptsetup_plugin
= libcryptsetup_plugins_support();
1108 assert(arg_pkcs11_uri
|| arg_pkcs11_uri_auto
);
1110 if (arg_pkcs11_uri_auto
) {
1111 if (!use_libcryptsetup_plugin
) {
1112 r
= find_pkcs11_auto_data(cd
, &discovered_uri
, &discovered_key
, &discovered_key_size
, &keyslot
);
1113 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
))
1114 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1115 "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1119 uri
= discovered_uri
;
1120 key_data
= discovered_key
;
1121 key_data_size
= discovered_key_size
;
1124 uri
= arg_pkcs11_uri
;
1126 if (!key_file
&& !key_data
)
1127 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "PKCS#11 mode selected but no key file specified, refusing.");
1130 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1135 if (use_libcryptsetup_plugin
&& arg_pkcs11_uri_auto
)
1136 r
= attach_luks2_by_pkcs11(cd
, name
, friendly
, until
, arg_headless
, flags
);
1138 r
= decrypt_pkcs11_key(
1142 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1143 key_data
, key_data_size
,
1146 &decrypted_key
, &decrypted_key_size
);
1151 if (r
!= -EAGAIN
) /* EAGAIN means: token not found */
1155 /* We didn't find the token. In this case, watch for it via udev. Let's
1156 * create an event loop and monitor first. */
1160 r
= make_security_device_monitor(&event
, &monitor
);
1164 log_notice("Security token %s not present for unlocking volume %s, please plug it in.",
1167 /* Let's immediately rescan in case the token appeared in the time we needed
1168 * to create and configure the monitor */
1172 r
= run_security_device_monitor(event
, monitor
);
1176 log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
1178 assert(decrypted_key
);
1180 if (pass_volume_key
)
1181 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1183 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1185 /* Before using this key as passphrase we base64 encode it. Why? For compatibility
1186 * with homed's PKCS#11 hookup: there we want to use the key we acquired through
1187 * PKCS#11 for other authentication/decryption mechanisms too, and some of them do
1188 * not take arbitrary binary blobs, but require NUL-terminated strings — most
1189 * importantly UNIX password hashes. Hence, for compatibility we want to use a string
1190 * without embedded NUL here too, and that's easiest to generate from a binary blob
1191 * via base64 encoding. */
1193 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1197 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1200 log_error_errno(r
, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
1201 return -EAGAIN
; /* log actual error, but return EAGAIN */
1204 return log_error_errno(r
, "Failed to activate with PKCS#11 acquired key: %m");
1209 static int make_tpm2_device_monitor(
1210 sd_event
**ret_event
,
1211 sd_device_monitor
**ret_monitor
) {
1213 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1214 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1218 assert(ret_monitor
);
1220 r
= sd_event_default(&event
);
1222 return log_error_errno(r
, "Failed to allocate event loop: %m");
1224 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, arg_token_timeout_usec
, USEC_PER_SEC
, NULL
, INT_TO_PTR(-ETIMEDOUT
));
1226 return log_error_errno(r
, "Failed to install timeout event source: %m");
1228 r
= sd_device_monitor_new(&monitor
);
1230 return log_error_errno(r
, "Failed to allocate device monitor: %m");
1232 r
= sd_device_monitor_filter_add_match_subsystem_devtype(monitor
, "tpmrm", NULL
);
1234 return log_error_errno(r
, "Failed to configure device monitor: %m");
1236 r
= sd_device_monitor_attach_event(monitor
, event
);
1238 return log_error_errno(r
, "Failed to attach device monitor: %m");
1240 r
= sd_device_monitor_start(monitor
, NULL
, NULL
);
1242 return log_error_errno(r
, "Failed to start device monitor: %m");
1244 *ret_event
= TAKE_PTR(event
);
1245 *ret_monitor
= TAKE_PTR(monitor
);
1249 static int attach_luks2_by_tpm2(
1250 struct crypt_device
*cd
,
1254 #if HAVE_LIBCRYPTSETUP_PLUGINS
1257 systemd_tpm2_plugin_params params
= {
1258 .search_pcr_mask
= arg_tpm2_pcr_mask
,
1259 .device
= arg_tpm2_device
1262 if (!crypt_token_external_path())
1263 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1264 "Libcryptsetup has external plugins support disabled.");
1266 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-tpm2", CRYPT_ANY_TOKEN
, NULL
, 0, ¶ms
, flags
);
1267 if (r
> 0) /* returns unlocked keyslot id on success */
1276 static int attach_luks_or_plain_or_bitlk_by_tpm2(
1277 struct crypt_device
*cd
,
1279 const char *key_file
,
1280 const void *key_data
,
1281 size_t key_data_size
,
1284 bool pass_volume_key
) {
1286 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1287 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
1288 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1289 _cleanup_free_
char *friendly
= NULL
;
1290 int keyslot
= arg_key_slot
, r
;
1291 size_t decrypted_key_size
;
1295 assert(arg_tpm2_device
|| arg_tpm2_device_auto
);
1297 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1302 if (key_file
|| key_data
) {
1303 /* If key data is specified, use that */
1305 r
= acquire_tpm2_key(
1308 arg_tpm2_pcr_mask
== UINT32_MAX
? TPM2_PCR_MASK_DEFAULT
: arg_tpm2_pcr_mask
,
1311 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1312 key_data
, key_data_size
,
1313 NULL
, 0, /* we don't know the policy hash */
1317 arg_ask_password_flags
,
1318 &decrypted_key
, &decrypted_key_size
);
1321 if (IN_SET(r
, -EACCES
, -ENOLCK
))
1322 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
1323 if (ERRNO_IS_NOT_SUPPORTED(r
)) /* TPM2 support not compiled in? */
1324 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 support not available, falling back to traditional unlocking.");
1325 if (r
!= -EAGAIN
) /* EAGAIN means: no tpm2 chip found */
1328 r
= attach_luks2_by_tpm2(cd
, name
, flags
);
1329 /* EAGAIN means: no tpm2 chip found
1330 * EOPNOTSUPP means: no libcryptsetup plugins support */
1332 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1333 "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
1335 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1336 "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
1337 if (!IN_SET(r
, -EOPNOTSUPP
, -EAGAIN
))
1341 if (r
== -EOPNOTSUPP
) {
1342 _cleanup_free_
void *blob
= NULL
, *policy_hash
= NULL
;
1343 size_t blob_size
, policy_hash_size
;
1344 bool found_some
= false;
1345 int token
= 0; /* first token to look at */
1347 /* If no key data is specified, look for it in the header. In order to support
1348 * software upgrades we'll iterate through all suitable tokens, maybe one of them
1353 uint16_t pcr_bank
, primary_alg
;
1354 TPM2Flags tpm2_flags
;
1356 r
= find_tpm2_auto_data(
1358 arg_tpm2_pcr_mask
, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1359 token
, /* search for the token with this index, or any later index than this */
1364 &policy_hash
, &policy_hash_size
,
1369 /* No further TPM2 tokens found in the LUKS2 header. */
1370 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1372 ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
1373 : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
1374 if (ERRNO_IS_NOT_SUPPORTED(r
)) /* TPM2 support not compiled in? */
1375 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 support not available, falling back to traditional unlocking.");
1381 r
= acquire_tpm2_key(
1387 NULL
, 0, 0, /* no key file */
1389 policy_hash
, policy_hash_size
,
1393 arg_ask_password_flags
,
1394 &decrypted_key
, &decrypted_key_size
);
1395 if (IN_SET(r
, -EACCES
, -ENOLCK
))
1396 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
1400 token
++; /* try a different token next time */
1405 if (r
!= -EAGAIN
) /* EAGAIN means: no tpm2 chip found */
1410 /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
1411 * an event loop and monitor first. */
1415 if (is_efi_boot() && !efi_has_tpm2())
1416 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
),
1417 "No TPM2 hardware discovered and EFI bios indicates no support for it either, assuming TPM2-less system, falling back to traditional unocking.");
1419 r
= make_tpm2_device_monitor(&event
, &monitor
);
1423 log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly
);
1425 /* Let's immediately rescan in case the device appeared in the time we needed
1426 * to create and configure the monitor */
1430 r
= run_security_device_monitor(event
, monitor
);
1434 log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
1436 assert(decrypted_key
);
1438 if (pass_volume_key
)
1439 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1441 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1443 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1445 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1449 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1452 log_error_errno(r
, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
1453 return -EAGAIN
; /* log actual error, but return EAGAIN */
1456 return log_error_errno(r
, "Failed to activate with TPM2 acquired key: %m");
1461 static int attach_luks_or_plain_or_bitlk_by_key_data(
1462 struct crypt_device
*cd
,
1464 const void *key_data
,
1465 size_t key_data_size
,
1467 bool pass_volume_key
) {
1475 if (pass_volume_key
)
1476 r
= crypt_activate_by_volume_key(cd
, name
, key_data
, key_data_size
, flags
);
1478 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, key_data
, key_data_size
, flags
);
1480 log_error_errno(r
, "Failed to activate. (Key incorrect?)");
1481 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1484 return log_error_errno(r
, "Failed to activate: %m");
1489 static int attach_luks_or_plain_or_bitlk_by_key_file(
1490 struct crypt_device
*cd
,
1492 const char *key_file
,
1494 bool pass_volume_key
) {
1496 _cleanup_(erase_and_freep
) char *kfdata
= NULL
;
1497 _cleanup_free_
char *bindname
= NULL
;
1505 /* If we read the key via AF_UNIX, make this client recognizable */
1506 bindname
= make_bindname(name
);
1510 r
= read_full_file_full(
1512 arg_keyfile_offset
== 0 ? UINT64_MAX
: arg_keyfile_offset
,
1513 arg_keyfile_size
== 0 ? SIZE_MAX
: arg_keyfile_size
,
1514 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
1518 log_error_errno(r
, "Failed to activate, key file '%s' too large.", key_file
);
1522 log_error_errno(r
, "Failed to activate, key file '%s' missing.", key_file
);
1523 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1526 return log_error_errno(r
, "Failed to read key file '%s': %m", key_file
);
1528 if (pass_volume_key
)
1529 r
= crypt_activate_by_volume_key(cd
, name
, kfdata
, kfsize
, flags
);
1531 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, kfdata
, kfsize
, flags
);
1533 log_error_errno(r
, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file
);
1534 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1537 return log_error_errno(r
, "Failed to activate with key file '%s': %m", key_file
);
1542 static int attach_luks_or_plain_or_bitlk_by_passphrase(
1543 struct crypt_device
*cd
,
1547 bool pass_volume_key
) {
1555 STRV_FOREACH(p
, passwords
) {
1556 if (pass_volume_key
)
1557 r
= crypt_activate_by_volume_key(cd
, name
, *p
, arg_key_size
, flags
);
1559 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, *p
, strlen(*p
), flags
);
1564 log_error_errno(r
, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
1565 return -EAGAIN
; /* log actual error, but return EAGAIN */
1568 return log_error_errno(r
, "Failed to activate with specified passphrase: %m");
1573 static int attach_luks_or_plain_or_bitlk(
1574 struct crypt_device
*cd
,
1576 const char *key_file
,
1577 const void *key_data
,
1578 size_t key_data_size
,
1583 bool pass_volume_key
= false;
1589 if ((!arg_type
&& !crypt_get_type(cd
)) || streq_ptr(arg_type
, CRYPT_PLAIN
)) {
1590 struct crypt_params_plain params
= {
1591 .offset
= arg_offset
,
1593 .sector_size
= arg_sector_size
,
1595 const char *cipher
, *cipher_mode
;
1596 _cleanup_free_
char *truncated_cipher
= NULL
;
1598 if (streq_ptr(arg_hash
, "plain"))
1599 /* plain isn't a real hash type. it just means "use no hash" */
1602 params
.hash
= arg_hash
;
1604 /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
1605 * file is provided */
1606 params
.hash
= "ripemd160";
1611 l
= strcspn(arg_cipher
, "-");
1612 truncated_cipher
= strndup(arg_cipher
, l
);
1613 if (!truncated_cipher
)
1616 cipher
= truncated_cipher
;
1617 cipher_mode
= arg_cipher
[l
] ? arg_cipher
+l
+1 : "plain";
1620 cipher_mode
= "cbc-essiv:sha256";
1623 /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
1624 arg_keyfile_size
= arg_key_size
;
1626 /* In contrast to what the name crypt_format() might suggest this doesn't actually format
1627 * anything, it just configures encryption parameters when used for plain mode. */
1628 r
= crypt_format(cd
, CRYPT_PLAIN
, cipher
, cipher_mode
, NULL
, NULL
, arg_keyfile_size
, ¶ms
);
1630 return log_error_errno(r
, "Loading of cryptographic parameters failed: %m");
1632 /* hash == NULL implies the user passed "plain" */
1633 pass_volume_key
= !params
.hash
;
1636 log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
1637 crypt_get_cipher(cd
),
1638 crypt_get_cipher_mode(cd
),
1639 crypt_get_volume_key_size(cd
)*8,
1640 crypt_get_device_name(cd
));
1642 if (arg_tpm2_device
|| arg_tpm2_device_auto
)
1643 return attach_luks_or_plain_or_bitlk_by_tpm2(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1644 if (arg_fido2_device
|| arg_fido2_device_auto
)
1645 return attach_luks_or_plain_or_bitlk_by_fido2(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1646 if (arg_pkcs11_uri
|| arg_pkcs11_uri_auto
)
1647 return attach_luks_or_plain_or_bitlk_by_pkcs11(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1649 return attach_luks_or_plain_or_bitlk_by_key_data(cd
, name
, key_data
, key_data_size
, flags
, pass_volume_key
);
1651 return attach_luks_or_plain_or_bitlk_by_key_file(cd
, name
, key_file
, flags
, pass_volume_key
);
1653 return attach_luks_or_plain_or_bitlk_by_passphrase(cd
, name
, passwords
, flags
, pass_volume_key
);
1656 static int help(void) {
1657 _cleanup_free_
char *link
= NULL
;
1660 r
= terminal_urlify_man("systemd-cryptsetup@.service", "8", &link
);
1664 printf("%s attach VOLUME SOURCEDEVICE [KEY-FILE] [OPTIONS]\n"
1665 "%s detach VOLUME\n\n"
1666 "Attaches or detaches an encrypted block device.\n"
1667 "\nSee the %s for details.\n",
1668 program_invocation_short_name
,
1669 program_invocation_short_name
,
1675 static uint32_t determine_flags(void) {
1679 flags
|= CRYPT_ACTIVATE_READONLY
;
1682 flags
|= CRYPT_ACTIVATE_ALLOW_DISCARDS
;
1684 if (arg_same_cpu_crypt
)
1685 flags
|= CRYPT_ACTIVATE_SAME_CPU_CRYPT
;
1687 if (arg_submit_from_crypt_cpus
)
1688 flags
|= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS
;
1690 if (arg_no_read_workqueue
)
1691 flags
|= CRYPT_ACTIVATE_NO_READ_WORKQUEUE
;
1693 if (arg_no_write_workqueue
)
1694 flags
|= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE
;
1696 #ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
1697 /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
1698 /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
1699 flags
|= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
;
1705 static void remove_and_erasep(const char **p
) {
1711 r
= unlinkat_deallocate(AT_FDCWD
, *p
, UNLINK_ERASE
);
1712 if (r
< 0 && r
!= -ENOENT
)
1713 log_warning_errno(r
, "Unable to erase key file '%s', ignoring: %m", *p
);
1716 static int run(int argc
, char *argv
[]) {
1717 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1725 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1726 "This program requires at least two arguments.");
1730 cryptsetup_enable_logging(NULL
);
1736 if (streq(verb
, "attach")) {
1737 _unused_
_cleanup_(remove_and_erasep
) const char *destroy_key_file
= NULL
;
1738 _cleanup_(erase_and_freep
) void *key_data
= NULL
;
1739 const char *volume
, *source
, *key_file
, *options
;
1740 crypt_status_info status
;
1741 size_t key_data_size
= 0;
1746 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [KEY-FILE] [OPTIONS] */
1749 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "attach requires at least two arguments.");
1753 key_file
= argc
>= 5 && !STR_IN_SET(argv
[4], "", "-", "none") ? argv
[4] : NULL
;
1754 options
= argc
>= 6 && !STR_IN_SET(argv
[5], "", "-", "none") ? argv
[5] : NULL
;
1756 if (!filename_is_valid(volume
))
1757 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume name '%s' is not valid.", volume
);
1759 if (key_file
&& !path_is_absolute(key_file
)) {
1760 log_warning("Password file path '%s' is not absolute. Ignoring.", key_file
);
1765 r
= parse_options(options
);
1770 log_debug("%s %s ← %s type=%s cipher=%s", __func__
,
1771 volume
, source
, strempty(arg_type
), strempty(arg_cipher
));
1773 /* A delicious drop of snake oil */
1774 (void) mlockall(MCL_FUTURE
);
1777 _cleanup_free_
char *bindname
= NULL
;
1780 bindname
= make_bindname(volume
);
1784 /* If a key file is not explicitly specified, search for a key in a well defined
1785 * search path, and load it. */
1787 fn
= strjoina(volume
, ".key");
1790 STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"),
1792 &key_data
, &key_data_size
);
1796 log_debug("Automatically discovered key for volume '%s'.", volume
);
1797 } else if (arg_keyfile_erase
)
1798 destroy_key_file
= key_file
; /* let's get this baby erased when we leave */
1801 log_debug("LUKS header: %s", arg_header
);
1802 r
= crypt_init(&cd
, arg_header
);
1804 r
= crypt_init(&cd
, source
);
1806 return log_error_errno(r
, "crypt_init() failed: %m");
1808 cryptsetup_enable_logging(cd
);
1810 status
= crypt_status(cd
, volume
);
1811 if (IN_SET(status
, CRYPT_ACTIVE
, CRYPT_BUSY
)) {
1812 log_info("Volume %s already active.", volume
);
1816 flags
= determine_flags();
1818 until
= usec_add(now(CLOCK_MONOTONIC
), arg_timeout
);
1819 if (until
== USEC_INFINITY
)
1822 arg_key_size
= (arg_key_size
> 0 ? arg_key_size
: (256 / 8));
1827 /* Ideally we'd do this on the open fd, but since this is just a
1828 * warning it's OK to do this in two steps. */
1829 if (stat(key_file
, &st
) >= 0 && S_ISREG(st
.st_mode
) && (st
.st_mode
& 0005))
1830 log_warning("Key file %s is world-readable. This is not a good idea!", key_file
);
1833 if (!arg_type
|| STR_IN_SET(arg_type
, ANY_LUKS
, CRYPT_LUKS1
, CRYPT_LUKS2
)) {
1834 r
= crypt_load(cd
, !arg_type
|| streq(arg_type
, ANY_LUKS
) ? CRYPT_LUKS
: arg_type
, NULL
);
1836 return log_error_errno(r
, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd
));
1839 r
= crypt_set_data_device(cd
, source
);
1841 return log_error_errno(r
, "Failed to set LUKS data device %s: %m", source
);
1844 /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
1845 if (!key_file
&& !key_data
) {
1846 r
= crypt_activate_by_token(cd
, volume
, CRYPT_ANY_TOKEN
, NULL
, flags
);
1848 log_debug("Volume %s activated with LUKS token id %i.", volume
, r
);
1852 log_debug_errno(r
, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd
));
1856 /* since cryptsetup 2.3.0 (Feb 2020) */
1858 if (streq_ptr(arg_type
, CRYPT_BITLK
)) {
1859 r
= crypt_load(cd
, CRYPT_BITLK
, NULL
);
1861 return log_error_errno(r
, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd
));
1865 for (tries
= 0; arg_tries
== 0 || tries
< arg_tries
; tries
++) {
1866 _cleanup_strv_free_erase_
char **passwords
= NULL
;
1868 /* When we were able to acquire multiple keys, let's always process them in this order:
1870 * 1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
1871 * 2. The discovered key: i.e. key_data + key_data_size
1872 * 3. The configured key: i.e. key_file + arg_keyfile_offset + arg_keyfile_size
1873 * 4. The empty password, in case arg_try_empty_password is set
1874 * 5. We enquire the user for a password
1877 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
) {
1879 if (arg_try_empty_password
) {
1880 /* Hmm, let's try an empty password now, but only once */
1881 arg_try_empty_password
= false;
1883 key_data
= strdup("");
1889 /* Ask the user for a passphrase only as last resort, if we have
1890 * nothing else to check for */
1892 r
= get_password(volume
, source
, until
, tries
== 0 && !arg_verify
, &passwords
);
1900 if (streq_ptr(arg_type
, CRYPT_TCRYPT
))
1901 r
= attach_tcrypt(cd
, volume
, key_file
, key_data
, key_data_size
, passwords
, flags
);
1903 r
= attach_luks_or_plain_or_bitlk(cd
, volume
, key_file
, key_data
, key_data_size
, passwords
, flags
, until
);
1909 /* Key not correct? Let's try again! */
1912 key_data
= erase_and_free(key_data
);
1914 arg_pkcs11_uri
= mfree(arg_pkcs11_uri
);
1915 arg_pkcs11_uri_auto
= false;
1916 arg_fido2_device
= mfree(arg_fido2_device
);
1917 arg_fido2_device_auto
= false;
1918 arg_tpm2_device
= mfree(arg_tpm2_device
);
1919 arg_tpm2_device_auto
= false;
1922 if (arg_tries
!= 0 && tries
>= arg_tries
)
1923 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Too many attempts to activate; giving up.");
1925 } else if (streq(verb
, "detach")) {
1930 if (!filename_is_valid(volume
))
1931 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume name '%s' is not valid.", volume
);
1933 r
= crypt_init_by_name(&cd
, volume
);
1935 log_info("Volume %s already inactive.", volume
);
1939 return log_error_errno(r
, "crypt_init_by_name() failed: %m");
1941 cryptsetup_enable_logging(cd
);
1943 r
= crypt_deactivate(cd
, volume
);
1945 return log_error_errno(r
, "Failed to deactivate: %m");
1948 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown verb %s.", verb
);
1953 DEFINE_MAIN_FUNCTION(run
);