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-util.h"
41 #include "tpm2-util.h"
44 #define ANY_LUKS "LUKS"
45 /* as in src/cryptsetup.h */
46 #define CRYPT_SECTOR_SIZE 512
47 #define CRYPT_MAX_SECTOR_SIZE 4096
49 static const char *arg_type
= NULL
; /* ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT, CRYPT_BITLK or CRYPT_PLAIN */
50 static char *arg_cipher
= NULL
;
51 static unsigned arg_key_size
= 0;
52 static unsigned arg_sector_size
= CRYPT_SECTOR_SIZE
;
53 static int arg_key_slot
= CRYPT_ANY_SLOT
;
54 static unsigned arg_keyfile_size
= 0;
55 static uint64_t arg_keyfile_offset
= 0;
56 static bool arg_keyfile_erase
= false;
57 static bool arg_try_empty_password
= false;
58 static char *arg_hash
= NULL
;
59 static char *arg_header
= NULL
;
60 static unsigned arg_tries
= 3;
61 static bool arg_readonly
= false;
62 static bool arg_verify
= false;
63 static AskPasswordFlags arg_ask_password_flags
= 0;
64 static bool arg_discards
= false;
65 static bool arg_same_cpu_crypt
= false;
66 static bool arg_submit_from_crypt_cpus
= false;
67 static bool arg_no_read_workqueue
= false;
68 static bool arg_no_write_workqueue
= false;
69 static bool arg_tcrypt_hidden
= false;
70 static bool arg_tcrypt_system
= false;
71 static bool arg_tcrypt_veracrypt
= false;
72 static char **arg_tcrypt_keyfiles
= NULL
;
73 static uint64_t arg_offset
= 0;
74 static uint64_t arg_skip
= 0;
75 static usec_t arg_timeout
= USEC_INFINITY
;
76 static char *arg_pkcs11_uri
= NULL
;
77 static bool arg_pkcs11_uri_auto
= false;
78 static char *arg_fido2_device
= NULL
;
79 static bool arg_fido2_device_auto
= false;
80 static void *arg_fido2_cid
= NULL
;
81 static size_t arg_fido2_cid_size
= 0;
82 static char *arg_fido2_rp_id
= NULL
;
83 static char *arg_tpm2_device
= NULL
;
84 static bool arg_tpm2_device_auto
= false;
85 static uint32_t arg_tpm2_pcr_mask
= UINT32_MAX
;
86 static bool arg_tpm2_pin
= false;
87 static bool arg_headless
= false;
88 static usec_t arg_token_timeout_usec
= 30*USEC_PER_SEC
;
90 STATIC_DESTRUCTOR_REGISTER(arg_cipher
, freep
);
91 STATIC_DESTRUCTOR_REGISTER(arg_hash
, freep
);
92 STATIC_DESTRUCTOR_REGISTER(arg_header
, freep
);
93 STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles
, strv_freep
);
94 STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri
, freep
);
95 STATIC_DESTRUCTOR_REGISTER(arg_fido2_device
, freep
);
96 STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid
, freep
);
97 STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id
, freep
);
98 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
100 /* Options Debian's crypttab knows we don't:
111 static int parse_one_option(const char *option
) {
117 /* Handled outside of this tool */
118 if (STR_IN_SET(option
, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
121 if (startswith(option
, "keyfile-timeout="))
124 if ((val
= startswith(option
, "cipher="))) {
125 r
= free_and_strdup(&arg_cipher
, val
);
129 } else if ((val
= startswith(option
, "size="))) {
131 r
= safe_atou(val
, &arg_key_size
);
133 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
137 if (arg_key_size
% 8) {
138 log_error("size= not a multiple of 8, ignoring.");
144 } else if ((val
= startswith(option
, "sector-size="))) {
146 r
= safe_atou(val
, &arg_sector_size
);
148 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
152 if (arg_sector_size
% 2) {
153 log_error("sector-size= not a multiple of 2, ignoring.");
157 if (arg_sector_size
< CRYPT_SECTOR_SIZE
|| arg_sector_size
> CRYPT_MAX_SECTOR_SIZE
) {
158 log_error("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE
, CRYPT_MAX_SECTOR_SIZE
);
162 } else if ((val
= startswith(option
, "key-slot=")) ||
163 (val
= startswith(option
, "keyslot="))) {
166 r
= safe_atoi(val
, &arg_key_slot
);
168 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
172 } else if ((val
= startswith(option
, "tcrypt-keyfile="))) {
174 arg_type
= CRYPT_TCRYPT
;
175 if (path_is_absolute(val
)) {
176 if (strv_extend(&arg_tcrypt_keyfiles
, val
) < 0)
179 log_error("Key file path \"%s\" is not absolute. Ignoring.", val
);
181 } else if ((val
= startswith(option
, "keyfile-size="))) {
183 r
= safe_atou(val
, &arg_keyfile_size
);
185 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
189 } else if ((val
= startswith(option
, "keyfile-offset="))) {
191 r
= safe_atou64(val
, &arg_keyfile_offset
);
193 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
197 } else if ((val
= startswith(option
, "keyfile-erase="))) {
199 r
= parse_boolean(val
);
201 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
205 arg_keyfile_erase
= r
;
207 } else if (streq(option
, "keyfile-erase"))
208 arg_keyfile_erase
= true;
210 else if ((val
= startswith(option
, "hash="))) {
211 r
= free_and_strdup(&arg_hash
, val
);
215 } else if ((val
= startswith(option
, "header="))) {
218 if (!path_is_absolute(val
))
219 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
220 "Header path \"%s\" is not absolute, refusing.", val
);
223 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
224 "Duplicate header= option, refusing.");
226 arg_header
= strdup(val
);
230 } else if ((val
= startswith(option
, "tries="))) {
232 r
= safe_atou(val
, &arg_tries
);
234 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
238 } else if (STR_IN_SET(option
, "readonly", "read-only"))
240 else if (streq(option
, "verify"))
242 else if ((val
= startswith(option
, "password-echo="))) {
243 if (streq(val
, "masked"))
244 arg_ask_password_flags
&= ~(ASK_PASSWORD_ECHO
|ASK_PASSWORD_SILENT
);
246 r
= parse_boolean(val
);
248 log_warning_errno(r
, "Invalid password-echo= option \"%s\", ignoring.", val
);
252 SET_FLAG(arg_ask_password_flags
, ASK_PASSWORD_ECHO
, r
);
253 SET_FLAG(arg_ask_password_flags
, ASK_PASSWORD_SILENT
, !r
);
255 } else if (STR_IN_SET(option
, "allow-discards", "discard"))
257 else if (streq(option
, "same-cpu-crypt"))
258 arg_same_cpu_crypt
= true;
259 else if (streq(option
, "submit-from-crypt-cpus"))
260 arg_submit_from_crypt_cpus
= true;
261 else if (streq(option
, "no-read-workqueue"))
262 arg_no_read_workqueue
= true;
263 else if (streq(option
, "no-write-workqueue"))
264 arg_no_write_workqueue
= true;
265 else if (streq(option
, "luks"))
267 /* since cryptsetup 2.3.0 (Feb 2020) */
269 else if (streq(option
, "bitlk"))
270 arg_type
= CRYPT_BITLK
;
272 else if (streq(option
, "tcrypt"))
273 arg_type
= CRYPT_TCRYPT
;
274 else if (STR_IN_SET(option
, "tcrypt-hidden", "tcrypthidden")) {
275 arg_type
= CRYPT_TCRYPT
;
276 arg_tcrypt_hidden
= true;
277 } else if (streq(option
, "tcrypt-system")) {
278 arg_type
= CRYPT_TCRYPT
;
279 arg_tcrypt_system
= true;
280 } else if (STR_IN_SET(option
, "tcrypt-veracrypt", "veracrypt")) {
281 arg_type
= CRYPT_TCRYPT
;
282 arg_tcrypt_veracrypt
= true;
283 } else if (STR_IN_SET(option
, "plain", "swap", "tmp") ||
284 startswith(option
, "tmp="))
285 arg_type
= CRYPT_PLAIN
;
286 else if ((val
= startswith(option
, "timeout="))) {
288 r
= parse_sec_fix_0(val
, &arg_timeout
);
290 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
294 } else if ((val
= startswith(option
, "offset="))) {
296 r
= safe_atou64(val
, &arg_offset
);
298 return log_error_errno(r
, "Failed to parse %s: %m", option
);
300 } else if ((val
= startswith(option
, "skip="))) {
302 r
= safe_atou64(val
, &arg_skip
);
304 return log_error_errno(r
, "Failed to parse %s: %m", option
);
306 } else if ((val
= startswith(option
, "pkcs11-uri="))) {
308 if (streq(val
, "auto")) {
309 arg_pkcs11_uri
= mfree(arg_pkcs11_uri
);
310 arg_pkcs11_uri_auto
= true;
312 if (!pkcs11_uri_valid(val
))
313 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing");
315 r
= free_and_strdup(&arg_pkcs11_uri
, val
);
319 arg_pkcs11_uri_auto
= false;
322 } else if ((val
= startswith(option
, "fido2-device="))) {
324 if (streq(val
, "auto")) {
325 arg_fido2_device
= mfree(arg_fido2_device
);
326 arg_fido2_device_auto
= true;
328 r
= free_and_strdup(&arg_fido2_device
, val
);
332 arg_fido2_device_auto
= false;
335 } else if ((val
= startswith(option
, "fido2-cid="))) {
337 if (streq(val
, "auto"))
338 arg_fido2_cid
= mfree(arg_fido2_cid
);
340 _cleanup_free_
void *cid
= NULL
;
343 r
= unbase64mem(val
, SIZE_MAX
, &cid
, &cid_size
);
345 return log_error_errno(r
, "Failed to decode FIDO2 CID data: %m");
348 arg_fido2_cid
= TAKE_PTR(cid
);
349 arg_fido2_cid_size
= cid_size
;
352 /* Turn on FIDO2 as side-effect, if not turned on yet. */
353 if (!arg_fido2_device
&& !arg_fido2_device_auto
)
354 arg_fido2_device_auto
= true;
356 } else if ((val
= startswith(option
, "fido2-rp="))) {
358 r
= free_and_strdup(&arg_fido2_rp_id
, val
);
362 } else if ((val
= startswith(option
, "tpm2-device="))) {
364 if (streq(val
, "auto")) {
365 arg_tpm2_device
= mfree(arg_tpm2_device
);
366 arg_tpm2_device_auto
= true;
368 r
= free_and_strdup(&arg_tpm2_device
, val
);
372 arg_tpm2_device_auto
= false;
375 } else if ((val
= startswith(option
, "tpm2-pcrs="))) {
378 arg_tpm2_pcr_mask
= 0;
382 r
= tpm2_parse_pcrs(val
, &mask
);
386 if (arg_tpm2_pcr_mask
== UINT32_MAX
)
387 arg_tpm2_pcr_mask
= mask
;
389 arg_tpm2_pcr_mask
|= mask
;
392 } else if ((val
= startswith(option
, "tpm2-pin="))) {
394 r
= parse_boolean(val
);
396 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
402 } else if ((val
= startswith(option
, "try-empty-password="))) {
404 r
= parse_boolean(val
);
406 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
410 arg_try_empty_password
= r
;
412 } else if (streq(option
, "try-empty-password"))
413 arg_try_empty_password
= true;
414 else if ((val
= startswith(option
, "headless="))) {
416 r
= parse_boolean(val
);
418 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
423 } else if (streq(option
, "headless"))
426 else if ((val
= startswith(option
, "token-timeout="))) {
428 r
= parse_sec_fix_0(val
, &arg_token_timeout_usec
);
430 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
434 } else if (!streq(option
, "x-initrd.attach"))
435 log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option
);
440 static int parse_options(const char *options
) {
444 _cleanup_free_
char *word
= NULL
;
447 r
= extract_first_word(&options
, &word
, ",", EXTRACT_DONT_COALESCE_SEPARATORS
| EXTRACT_UNESCAPE_SEPARATORS
);
449 return log_error_errno(r
, "Failed to parse options: %m");
453 r
= parse_one_option(word
);
458 /* sanity-check options */
459 if (arg_type
&& !streq(arg_type
, CRYPT_PLAIN
)) {
461 log_warning("offset= ignored with type %s", arg_type
);
463 log_warning("skip= ignored with type %s", arg_type
);
469 static char* disk_description(const char *path
) {
470 static const char name_fields
[] =
472 "ID_MODEL_FROM_DATABASE\0"
475 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
476 const char *i
, *name
;
481 if (stat(path
, &st
) < 0)
484 if (!S_ISBLK(st
.st_mode
))
487 if (sd_device_new_from_stat_rdev(&device
, &st
) < 0)
490 if (sd_device_get_property_value(device
, "ID_PART_ENTRY_NAME", &name
) >= 0) {
491 _cleanup_free_
char *unescaped
= NULL
;
494 /* ID_PART_ENTRY_NAME uses \x style escaping, using libblkid's blkid_encode_string(). Let's
495 * reverse this here to make the string more human friendly in case people embed spaces or
496 * other weird stuff. */
498 l
= cunescape(name
, UNESCAPE_RELAX
, &unescaped
);
500 log_debug_errno(l
, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
504 if (!isempty(unescaped
) && !string_has_cc(unescaped
, NULL
))
505 return TAKE_PTR(unescaped
);
508 /* These need no unescaping. */
509 NULSTR_FOREACH(i
, name_fields
)
510 if (sd_device_get_property_value(device
, i
, &name
) >= 0 &&
517 static char *disk_mount_point(const char *label
) {
518 _cleanup_free_
char *device
= NULL
;
519 _cleanup_endmntent_
FILE *f
= NULL
;
522 /* Yeah, we don't support native systemd unit files here for now */
524 device
= strjoin("/dev/mapper/", label
);
528 f
= setmntent(fstab_path(), "re");
532 while ((m
= getmntent(f
)))
533 if (path_equal(m
->mnt_fsname
, device
))
534 return strdup(m
->mnt_dir
);
539 static char *friendly_disk_name(const char *src
, const char *vol
) {
540 _cleanup_free_
char *description
= NULL
, *mount_point
= NULL
;
541 char *name_buffer
= NULL
;
547 description
= disk_description(src
);
548 mount_point
= disk_mount_point(vol
);
550 /* If the description string is simply the volume name, then let's not show this twice */
551 if (description
&& streq(vol
, description
))
552 description
= mfree(description
);
554 if (mount_point
&& description
)
555 r
= asprintf(&name_buffer
, "%s (%s) on %s", description
, vol
, mount_point
);
556 else if (mount_point
)
557 r
= asprintf(&name_buffer
, "%s on %s", vol
, mount_point
);
558 else if (description
)
559 r
= asprintf(&name_buffer
, "%s (%s)", description
, vol
);
568 static int get_password(
575 _cleanup_free_
char *friendly
= NULL
, *text
= NULL
, *disk_path
= NULL
;
576 _cleanup_strv_free_erase_
char **passwords
= NULL
;
579 AskPasswordFlags flags
= arg_ask_password_flags
| ASK_PASSWORD_PUSH_CACHE
;
586 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "Password querying disabled via 'headless' option.");
588 friendly
= friendly_disk_name(src
, vol
);
592 if (asprintf(&text
, "Please enter passphrase for disk %s:", friendly
) < 0)
595 disk_path
= cescape(src
);
599 id
= strjoina("cryptsetup:", disk_path
);
601 r
= ask_password_auto(text
, "drive-harddisk", id
, "cryptsetup", "cryptsetup.passphrase", until
,
602 flags
| (accept_cached
*ASK_PASSWORD_ACCEPT_CACHED
),
605 return log_error_errno(r
, "Failed to query password: %m");
608 _cleanup_strv_free_erase_
char **passwords2
= NULL
;
610 assert(strv_length(passwords
) == 1);
612 if (asprintf(&text
, "Please enter passphrase for disk %s (verification):", friendly
) < 0)
615 id
= strjoina("cryptsetup-verification:", disk_path
);
617 r
= ask_password_auto(text
, "drive-harddisk", id
, "cryptsetup", "cryptsetup.passphrase", until
, flags
, &passwords2
);
619 return log_error_errno(r
, "Failed to query verification password: %m");
621 assert(strv_length(passwords2
) == 1);
623 if (!streq(passwords
[0], passwords2
[0]))
624 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
),
625 "Passwords did not match, retrying.");
628 strv_uniq(passwords
);
630 STRV_FOREACH(p
, passwords
) {
633 if (strlen(*p
)+1 >= arg_key_size
)
636 /* Pad password if necessary */
637 c
= new(char, arg_key_size
);
641 strncpy(c
, *p
, arg_key_size
);
646 *ret
= TAKE_PTR(passwords
);
651 static int attach_tcrypt(
652 struct crypt_device
*cd
,
654 const char *key_file
,
655 const void *key_data
,
656 size_t key_data_size
,
661 _cleanup_(erase_and_freep
) char *passphrase
= NULL
;
662 struct crypt_params_tcrypt params
= {
663 .flags
= CRYPT_TCRYPT_LEGACY_MODES
,
664 .keyfiles
= (const char **)arg_tcrypt_keyfiles
,
665 .keyfiles_count
= strv_length(arg_tcrypt_keyfiles
)
670 assert(key_file
|| key_data
|| !strv_isempty(passwords
));
672 if (arg_pkcs11_uri
|| arg_pkcs11_uri_auto
|| arg_fido2_device
|| arg_fido2_device_auto
|| arg_tpm2_device
|| arg_tpm2_device_auto
)
673 /* Ask for a regular password */
674 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN
),
675 "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
677 if (arg_tcrypt_hidden
)
678 params
.flags
|= CRYPT_TCRYPT_HIDDEN_HEADER
;
680 if (arg_tcrypt_system
)
681 params
.flags
|= CRYPT_TCRYPT_SYSTEM_HEADER
;
683 if (arg_tcrypt_veracrypt
)
684 params
.flags
|= CRYPT_TCRYPT_VERA_MODES
;
687 params
.passphrase
= key_data
;
688 params
.passphrase_size
= key_data_size
;
691 r
= read_one_line_file(key_file
, &passphrase
);
693 log_error_errno(r
, "Failed to read password file '%s': %m", key_file
);
694 return -EAGAIN
; /* log with the actual error, but return EAGAIN */
697 params
.passphrase
= passphrase
;
699 params
.passphrase
= passwords
[0];
701 params
.passphrase_size
= strlen(params
.passphrase
);
704 r
= crypt_load(cd
, CRYPT_TCRYPT
, ¶ms
);
708 log_error_errno(r
, "Failed to activate using discovered key. (Key not correct?)");
711 log_error_errno(r
, "Failed to activate using password file '%s'. (Key data not correct?)", key_file
);
713 return -EAGAIN
; /* log the actual error, but return EAGAIN */
716 return log_error_errno(r
, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd
));
719 r
= crypt_activate_by_volume_key(cd
, name
, NULL
, 0, flags
);
721 return log_error_errno(r
, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd
));
726 static char *make_bindname(const char *volume
) {
729 if (asprintf(&s
, "@%" PRIx64
"/cryptsetup/%s", random_u64(), volume
) < 0)
735 static int make_security_device_monitor(
736 sd_event
**ret_event
,
737 sd_device_monitor
**ret_monitor
) {
738 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
739 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
745 /* Waits for a device with "security-device" tag to show up in udev */
747 r
= sd_event_default(&event
);
749 return log_error_errno(r
, "Failed to allocate event loop: %m");
751 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, arg_token_timeout_usec
, USEC_PER_SEC
, NULL
, INT_TO_PTR(-ETIMEDOUT
));
753 return log_error_errno(r
, "Failed to install timeout event source: %m");
755 r
= sd_device_monitor_new(&monitor
);
757 return log_error_errno(r
, "Failed to allocate device monitor: %m");
759 r
= sd_device_monitor_filter_add_match_tag(monitor
, "security-device");
761 return log_error_errno(r
, "Failed to configure device monitor: %m");
763 r
= sd_device_monitor_attach_event(monitor
, event
);
765 return log_error_errno(r
, "Failed to attach device monitor: %m");
767 r
= sd_device_monitor_start(monitor
, NULL
, NULL
);
769 return log_error_errno(r
, "Failed to start device monitor: %m");
771 *ret_event
= TAKE_PTR(event
);
772 *ret_monitor
= TAKE_PTR(monitor
);
776 static int run_security_device_monitor(
778 sd_device_monitor
*monitor
) {
779 bool processed
= false;
785 /* Runs the event loop for the device monitor until either something happens, or the time-out is
791 r
= sd_event_get_exit_code(event
, &x
);
794 return log_error_errno(r
, "Failed to query exit code from event loop: %m");
796 /* On ENODATA we aren't told to exit yet. */
798 assert(x
== -ETIMEDOUT
);
799 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
),
800 "Timed out waiting for security device, aborting security device based authentication attempt.");
803 /* Wait for one event, and then eat all subsequent events until there are no further ones */
804 r
= sd_event_run(event
, processed
? 0 : UINT64_MAX
);
806 return log_error_errno(r
, "Failed to run event loop: %m");
807 if (r
== 0) /* no events queued anymore */
814 static bool libcryptsetup_plugins_support(void) {
815 #if HAVE_LIBCRYPTSETUP_PLUGINS
818 /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
819 r
= getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
820 if (r
< 0 && r
!= -ENXIO
)
821 log_debug_errno(r
, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
825 return crypt_token_external_path();
831 #if HAVE_LIBCRYPTSETUP_PLUGINS
832 static int acquire_pins_from_env_variable(char ***ret_pins
) {
833 _cleanup_(erase_and_freep
) char *envpin
= NULL
;
834 _cleanup_strv_free_erase_
char **pins
= NULL
;
839 r
= getenv_steal_erase("PIN", &envpin
);
841 return log_error_errno(r
, "Failed to acquire PIN from environment: %m");
843 pins
= strv_new(envpin
);
848 *ret_pins
= TAKE_PTR(pins
);
854 static int crypt_activate_by_token_pin_ask_password(
855 struct crypt_device
*cd
,
861 uint32_t activation_flags
,
863 const char *key_name
,
864 const char *credential_name
) {
866 #if HAVE_LIBCRYPTSETUP_PLUGINS
867 AskPasswordFlags flags
= ASK_PASSWORD_PUSH_CACHE
| ASK_PASSWORD_ACCEPT_CACHED
;
868 _cleanup_strv_free_erase_
char **pins
= NULL
;
871 r
= crypt_activate_by_token_pin(cd
, name
, type
, CRYPT_ANY_TOKEN
, NULL
, 0, usrptr
, activation_flags
);
872 if (r
> 0) /* returns unlocked keyslot id on success */
874 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
877 r
= acquire_pins_from_env_variable(&pins
);
881 STRV_FOREACH(p
, pins
) {
882 r
= crypt_activate_by_token_pin(cd
, name
, type
, CRYPT_ANY_TOKEN
, *p
, strlen(*p
), usrptr
, activation_flags
);
883 if (r
> 0) /* returns unlocked keyslot id on success */
885 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
890 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
893 pins
= strv_free_erase(pins
);
894 r
= ask_password_auto(message
, "drive-harddisk", NULL
, key_name
, credential_name
, until
, flags
, &pins
);
898 STRV_FOREACH(p
, pins
) {
899 r
= crypt_activate_by_token_pin(cd
, name
, type
, CRYPT_ANY_TOKEN
, *p
, strlen(*p
), usrptr
, activation_flags
);
900 if (r
> 0) /* returns unlocked keyslot id on success */
902 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
906 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
914 static int attach_luks2_by_fido2_via_plugin(
915 struct crypt_device
*cd
,
920 uint32_t activation_flags
) {
922 return crypt_activate_by_token_pin_ask_password(
930 "Please enter security token PIN:",
932 "cryptsetup.fido2-pin");
935 static int attach_luks_or_plain_or_bitlk_by_fido2(
936 struct crypt_device
*cd
,
938 const char *key_file
,
939 const void *key_data
,
940 size_t key_data_size
,
943 bool pass_volume_key
) {
945 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
946 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
947 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
948 _cleanup_free_
void *discovered_salt
= NULL
, *discovered_cid
= NULL
;
949 size_t discovered_salt_size
, discovered_cid_size
, decrypted_key_size
, cid_size
= 0;
950 _cleanup_free_
char *friendly
= NULL
, *discovered_rp_id
= NULL
;
951 int keyslot
= arg_key_slot
, r
;
952 const char *rp_id
= NULL
;
953 const void *cid
= NULL
;
954 Fido2EnrollFlags required
;
955 bool use_libcryptsetup_plugin
= libcryptsetup_plugins_support();
959 assert(arg_fido2_device
|| arg_fido2_device_auto
);
962 if (!key_file
&& !key_data
)
963 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
964 "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
966 rp_id
= arg_fido2_rp_id
;
968 cid_size
= arg_fido2_cid_size
;
970 /* For now and for compatibility, if the user explicitly configured FIDO2 support and we do
971 * not read FIDO2 metadata off the LUKS2 header, default to the systemd 248 logic, where we
972 * use PIN + UP when needed, and do not configure UV at all. Eventually, we should make this
973 * explicitly configurable. */
974 required
= FIDO2ENROLL_PIN_IF_NEEDED
| FIDO2ENROLL_UP_IF_NEEDED
| FIDO2ENROLL_UV_OMIT
;
975 } else if (!use_libcryptsetup_plugin
) {
976 r
= find_fido2_auto_data(
980 &discovered_salt_size
,
982 &discovered_cid_size
,
986 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
))
987 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
988 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
992 if ((required
& (FIDO2ENROLL_PIN
| FIDO2ENROLL_UP
| FIDO2ENROLL_UV
)) && arg_headless
)
993 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
),
994 "Local verification is required to unlock this volume, but the 'headless' parameter was set.");
996 rp_id
= discovered_rp_id
;
997 key_data
= discovered_salt
;
998 key_data_size
= discovered_salt_size
;
999 cid
= discovered_cid
;
1000 cid_size
= discovered_cid_size
;
1003 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1008 if (use_libcryptsetup_plugin
&& !arg_fido2_cid
) {
1009 r
= attach_luks2_by_fido2_via_plugin(cd
, name
, until
, arg_headless
, arg_fido2_device
, flags
);
1010 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
, -ENOENT
))
1011 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1012 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1015 r
= acquire_fido2_key(
1021 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1022 key_data
, key_data_size
,
1026 &decrypted_key
, &decrypted_key_size
,
1027 arg_ask_password_flags
);
1032 if (r
!= -EAGAIN
) /* EAGAIN means: token not found */
1036 /* We didn't find the token. In this case, watch for it via udev. Let's
1037 * create an event loop and monitor first. */
1041 r
= make_security_device_monitor(&event
, &monitor
);
1045 log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly
);
1047 /* Let's immediately rescan in case the token appeared in the time we needed
1048 * to create and configure the monitor */
1052 r
= run_security_device_monitor(event
, monitor
);
1056 log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
1059 if (pass_volume_key
)
1060 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1062 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1064 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1066 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1070 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1073 log_error_errno(r
, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
1074 return -EAGAIN
; /* log actual error, but return EAGAIN */
1077 return log_error_errno(r
, "Failed to activate with FIDO2 acquired key: %m");
1082 static int attach_luks2_by_pkcs11_via_plugin(
1083 struct crypt_device
*cd
,
1085 const char *friendly_name
,
1090 #if HAVE_LIBCRYPTSETUP_PLUGINS
1093 if (!streq_ptr(crypt_get_type(cd
), CRYPT_LUKS2
))
1094 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Automatic PKCS#11 metadata requires LUKS2 device.");
1096 systemd_pkcs11_plugin_params params
= {
1097 .friendly_name
= friendly_name
,
1099 .headless
= headless
1102 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-pkcs11", CRYPT_ANY_TOKEN
, NULL
, 0, ¶ms
, flags
);
1103 if (r
> 0) /* returns unlocked keyslot id on success */
1112 static int attach_luks_or_plain_or_bitlk_by_pkcs11(
1113 struct crypt_device
*cd
,
1115 const char *key_file
,
1116 const void *key_data
,
1117 size_t key_data_size
,
1120 bool pass_volume_key
) {
1122 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1123 _cleanup_free_
char *friendly
= NULL
, *discovered_uri
= NULL
;
1124 size_t decrypted_key_size
= 0, discovered_key_size
= 0;
1125 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
1126 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1127 _cleanup_free_
void *discovered_key
= NULL
;
1128 int keyslot
= arg_key_slot
, r
;
1129 const char *uri
= NULL
;
1130 bool use_libcryptsetup_plugin
= libcryptsetup_plugins_support();
1134 assert(arg_pkcs11_uri
|| arg_pkcs11_uri_auto
);
1136 if (arg_pkcs11_uri_auto
) {
1137 if (!use_libcryptsetup_plugin
) {
1138 r
= find_pkcs11_auto_data(cd
, &discovered_uri
, &discovered_key
, &discovered_key_size
, &keyslot
);
1139 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
))
1140 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1141 "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1145 uri
= discovered_uri
;
1146 key_data
= discovered_key
;
1147 key_data_size
= discovered_key_size
;
1150 uri
= arg_pkcs11_uri
;
1152 if (!key_file
&& !key_data
)
1153 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "PKCS#11 mode selected but no key file specified, refusing.");
1156 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1161 if (use_libcryptsetup_plugin
&& arg_pkcs11_uri_auto
)
1162 r
= attach_luks2_by_pkcs11_via_plugin(cd
, name
, friendly
, until
, arg_headless
, flags
);
1164 r
= decrypt_pkcs11_key(
1168 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1169 key_data
, key_data_size
,
1172 &decrypted_key
, &decrypted_key_size
);
1177 if (r
!= -EAGAIN
) /* EAGAIN means: token not found */
1181 /* We didn't find the token. In this case, watch for it via udev. Let's
1182 * create an event loop and monitor first. */
1186 r
= make_security_device_monitor(&event
, &monitor
);
1190 log_notice("Security token %s not present for unlocking volume %s, please plug it in.",
1193 /* Let's immediately rescan in case the token appeared in the time we needed
1194 * to create and configure the monitor */
1198 r
= run_security_device_monitor(event
, monitor
);
1202 log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
1204 assert(decrypted_key
);
1206 if (pass_volume_key
)
1207 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1209 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1211 /* Before using this key as passphrase we base64 encode it. Why? For compatibility
1212 * with homed's PKCS#11 hookup: there we want to use the key we acquired through
1213 * PKCS#11 for other authentication/decryption mechanisms too, and some of them do
1214 * not take arbitrary binary blobs, but require NUL-terminated strings — most
1215 * importantly UNIX password hashes. Hence, for compatibility we want to use a string
1216 * without embedded NUL here too, and that's easiest to generate from a binary blob
1217 * via base64 encoding. */
1219 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1223 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1226 log_error_errno(r
, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
1227 return -EAGAIN
; /* log actual error, but return EAGAIN */
1230 return log_error_errno(r
, "Failed to activate with PKCS#11 acquired key: %m");
1235 static int make_tpm2_device_monitor(
1236 sd_event
**ret_event
,
1237 sd_device_monitor
**ret_monitor
) {
1239 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1240 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1244 assert(ret_monitor
);
1246 r
= sd_event_default(&event
);
1248 return log_error_errno(r
, "Failed to allocate event loop: %m");
1250 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, arg_token_timeout_usec
, USEC_PER_SEC
, NULL
, INT_TO_PTR(-ETIMEDOUT
));
1252 return log_error_errno(r
, "Failed to install timeout event source: %m");
1254 r
= sd_device_monitor_new(&monitor
);
1256 return log_error_errno(r
, "Failed to allocate device monitor: %m");
1258 r
= sd_device_monitor_filter_add_match_subsystem_devtype(monitor
, "tpmrm", NULL
);
1260 return log_error_errno(r
, "Failed to configure device monitor: %m");
1262 r
= sd_device_monitor_attach_event(monitor
, event
);
1264 return log_error_errno(r
, "Failed to attach device monitor: %m");
1266 r
= sd_device_monitor_start(monitor
, NULL
, NULL
);
1268 return log_error_errno(r
, "Failed to start device monitor: %m");
1270 *ret_event
= TAKE_PTR(event
);
1271 *ret_monitor
= TAKE_PTR(monitor
);
1275 static int attach_luks2_by_tpm2_via_plugin(
1276 struct crypt_device
*cd
,
1282 #if HAVE_LIBCRYPTSETUP_PLUGINS
1283 systemd_tpm2_plugin_params params
= {
1284 .search_pcr_mask
= arg_tpm2_pcr_mask
,
1285 .device
= arg_tpm2_device
1288 if (!crypt_token_external_path())
1289 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1290 "Libcryptsetup has external plugins support disabled.");
1292 return crypt_activate_by_token_pin_ask_password(
1300 "Please enter TPM2 PIN:",
1302 "cryptsetup.tpm2-pin");
1308 static int attach_luks_or_plain_or_bitlk_by_tpm2(
1309 struct crypt_device
*cd
,
1311 const char *key_file
,
1312 const void *key_data
,
1313 size_t key_data_size
,
1316 bool pass_volume_key
) {
1318 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1319 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
1320 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1321 _cleanup_free_
char *friendly
= NULL
;
1322 int keyslot
= arg_key_slot
, r
;
1323 size_t decrypted_key_size
;
1327 assert(arg_tpm2_device
|| arg_tpm2_device_auto
);
1329 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1334 if (key_file
|| key_data
) {
1335 /* If key data is specified, use that */
1337 r
= acquire_tpm2_key(
1340 arg_tpm2_pcr_mask
== UINT32_MAX
? TPM2_PCR_MASK_DEFAULT
: arg_tpm2_pcr_mask
,
1343 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1344 key_data
, key_data_size
,
1345 NULL
, 0, /* we don't know the policy hash */
1349 arg_ask_password_flags
,
1350 &decrypted_key
, &decrypted_key_size
);
1353 if (IN_SET(r
, -EACCES
, -ENOLCK
))
1354 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
1355 if (ERRNO_IS_NOT_SUPPORTED(r
)) /* TPM2 support not compiled in? */
1356 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 support not available, falling back to traditional unlocking.");
1357 /* EAGAIN means: no tpm2 chip found */
1359 log_notice_errno(r
, "TPM2 operation failed, falling back to traditional unlocking: %m");
1360 return -EAGAIN
; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1363 r
= attach_luks2_by_tpm2_via_plugin(cd
, name
, until
, arg_headless
, flags
);
1366 /* EAGAIN means: no tpm2 chip found
1367 * EOPNOTSUPP means: no libcryptsetup plugins support */
1369 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
),
1370 "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
1372 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1373 "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
1374 if (!IN_SET(r
, -EOPNOTSUPP
, -EAGAIN
)) {
1375 log_notice_errno(r
, "TPM2 operation failed, falling back to traditional unlocking: %m");
1376 return -EAGAIN
; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1380 if (r
== -EOPNOTSUPP
) { /* Plugin not available, let's process TPM2 stuff right here instead */
1381 _cleanup_free_
void *blob
= NULL
, *policy_hash
= NULL
;
1382 size_t blob_size
, policy_hash_size
;
1383 bool found_some
= false;
1384 int token
= 0; /* first token to look at */
1386 /* If no key data is specified, look for it in the header. In order to support
1387 * software upgrades we'll iterate through all suitable tokens, maybe one of them
1392 uint16_t pcr_bank
, primary_alg
;
1393 TPM2Flags tpm2_flags
;
1395 r
= find_tpm2_auto_data(
1397 arg_tpm2_pcr_mask
, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1398 token
, /* search for the token with this index, or any later index than this */
1403 &policy_hash
, &policy_hash_size
,
1408 /* No further TPM2 tokens found in the LUKS2 header. */
1409 return log_full_errno(found_some
? LOG_NOTICE
: LOG_DEBUG
,
1410 SYNTHETIC_ERRNO(EAGAIN
),
1412 ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
1413 : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
1414 if (ERRNO_IS_NOT_SUPPORTED(r
)) /* TPM2 support not compiled in? */
1415 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 support not available, falling back to traditional unlocking.");
1421 r
= acquire_tpm2_key(
1427 NULL
, 0, 0, /* no key file */
1429 policy_hash
, policy_hash_size
,
1433 arg_ask_password_flags
,
1434 &decrypted_key
, &decrypted_key_size
);
1435 if (IN_SET(r
, -EACCES
, -ENOLCK
))
1436 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
1440 token
++; /* try a different token next time */
1445 /* EAGAIN means: no tpm2 chip found */
1447 log_notice_errno(r
, "TPM2 operation failed, falling back to traditional unlocking: %m");
1448 return -EAGAIN
; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1453 /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
1454 * an event loop and monitor first. */
1458 if (is_efi_boot() && !efi_has_tpm2())
1459 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
),
1460 "No TPM2 hardware discovered and EFI firmware does not see it either, falling back to traditional unlocking.");
1462 r
= make_tpm2_device_monitor(&event
, &monitor
);
1466 log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly
);
1468 /* Let's immediately rescan in case the device appeared in the time we needed
1469 * to create and configure the monitor */
1473 r
= run_security_device_monitor(event
, monitor
);
1477 log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
1479 assert(decrypted_key
);
1481 if (pass_volume_key
)
1482 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1484 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1486 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1488 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1492 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1495 log_error_errno(r
, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
1496 return -EAGAIN
; /* log actual error, but return EAGAIN */
1499 return log_error_errno(r
, "Failed to activate with TPM2 acquired key: %m");
1504 static int attach_luks_or_plain_or_bitlk_by_key_data(
1505 struct crypt_device
*cd
,
1507 const void *key_data
,
1508 size_t key_data_size
,
1510 bool pass_volume_key
) {
1518 if (pass_volume_key
)
1519 r
= crypt_activate_by_volume_key(cd
, name
, key_data
, key_data_size
, flags
);
1521 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, key_data
, key_data_size
, flags
);
1523 log_error_errno(r
, "Failed to activate. (Key incorrect?)");
1524 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1527 return log_error_errno(r
, "Failed to activate: %m");
1532 static int attach_luks_or_plain_or_bitlk_by_key_file(
1533 struct crypt_device
*cd
,
1535 const char *key_file
,
1537 bool pass_volume_key
) {
1539 _cleanup_(erase_and_freep
) char *kfdata
= NULL
;
1540 _cleanup_free_
char *bindname
= NULL
;
1548 /* If we read the key via AF_UNIX, make this client recognizable */
1549 bindname
= make_bindname(name
);
1553 r
= read_full_file_full(
1555 arg_keyfile_offset
== 0 ? UINT64_MAX
: arg_keyfile_offset
,
1556 arg_keyfile_size
== 0 ? SIZE_MAX
: arg_keyfile_size
,
1557 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
1561 log_error_errno(r
, "Failed to activate, key file '%s' too large.", key_file
);
1565 log_error_errno(r
, "Failed to activate, key file '%s' missing.", key_file
);
1566 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1569 return log_error_errno(r
, "Failed to read key file '%s': %m", key_file
);
1571 if (pass_volume_key
)
1572 r
= crypt_activate_by_volume_key(cd
, name
, kfdata
, kfsize
, flags
);
1574 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, kfdata
, kfsize
, flags
);
1576 log_error_errno(r
, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file
);
1577 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1580 return log_error_errno(r
, "Failed to activate with key file '%s': %m", key_file
);
1585 static int attach_luks_or_plain_or_bitlk_by_passphrase(
1586 struct crypt_device
*cd
,
1590 bool pass_volume_key
) {
1598 STRV_FOREACH(p
, passwords
) {
1599 if (pass_volume_key
)
1600 r
= crypt_activate_by_volume_key(cd
, name
, *p
, arg_key_size
, flags
);
1602 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, *p
, strlen(*p
), flags
);
1607 log_error_errno(r
, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
1608 return -EAGAIN
; /* log actual error, but return EAGAIN */
1611 return log_error_errno(r
, "Failed to activate with specified passphrase: %m");
1616 static int attach_luks_or_plain_or_bitlk(
1617 struct crypt_device
*cd
,
1619 const char *key_file
,
1620 const void *key_data
,
1621 size_t key_data_size
,
1626 bool pass_volume_key
= false;
1632 if ((!arg_type
&& !crypt_get_type(cd
)) || streq_ptr(arg_type
, CRYPT_PLAIN
)) {
1633 struct crypt_params_plain params
= {
1634 .offset
= arg_offset
,
1636 .sector_size
= arg_sector_size
,
1638 const char *cipher
, *cipher_mode
;
1639 _cleanup_free_
char *truncated_cipher
= NULL
;
1641 if (streq_ptr(arg_hash
, "plain"))
1642 /* plain isn't a real hash type. it just means "use no hash" */
1645 params
.hash
= arg_hash
;
1647 /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
1648 * file is provided */
1649 params
.hash
= "ripemd160";
1654 l
= strcspn(arg_cipher
, "-");
1655 truncated_cipher
= strndup(arg_cipher
, l
);
1656 if (!truncated_cipher
)
1659 cipher
= truncated_cipher
;
1660 cipher_mode
= arg_cipher
[l
] ? arg_cipher
+l
+1 : "plain";
1663 cipher_mode
= "cbc-essiv:sha256";
1666 /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
1667 arg_keyfile_size
= arg_key_size
;
1669 /* In contrast to what the name crypt_format() might suggest this doesn't actually format
1670 * anything, it just configures encryption parameters when used for plain mode. */
1671 r
= crypt_format(cd
, CRYPT_PLAIN
, cipher
, cipher_mode
, NULL
, NULL
, arg_keyfile_size
, ¶ms
);
1673 return log_error_errno(r
, "Loading of cryptographic parameters failed: %m");
1675 /* hash == NULL implies the user passed "plain" */
1676 pass_volume_key
= !params
.hash
;
1679 log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
1680 crypt_get_cipher(cd
),
1681 crypt_get_cipher_mode(cd
),
1682 crypt_get_volume_key_size(cd
)*8,
1683 crypt_get_device_name(cd
));
1685 if (arg_tpm2_device
|| arg_tpm2_device_auto
)
1686 return attach_luks_or_plain_or_bitlk_by_tpm2(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1687 if (arg_fido2_device
|| arg_fido2_device_auto
)
1688 return attach_luks_or_plain_or_bitlk_by_fido2(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1689 if (arg_pkcs11_uri
|| arg_pkcs11_uri_auto
)
1690 return attach_luks_or_plain_or_bitlk_by_pkcs11(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1692 return attach_luks_or_plain_or_bitlk_by_key_data(cd
, name
, key_data
, key_data_size
, flags
, pass_volume_key
);
1694 return attach_luks_or_plain_or_bitlk_by_key_file(cd
, name
, key_file
, flags
, pass_volume_key
);
1696 return attach_luks_or_plain_or_bitlk_by_passphrase(cd
, name
, passwords
, flags
, pass_volume_key
);
1699 static int help(void) {
1700 _cleanup_free_
char *link
= NULL
;
1703 r
= terminal_urlify_man("systemd-cryptsetup@.service", "8", &link
);
1707 printf("%s attach VOLUME SOURCEDEVICE [KEY-FILE] [OPTIONS]\n"
1708 "%s detach VOLUME\n\n"
1709 "Attaches or detaches an encrypted block device.\n"
1710 "\nSee the %s for details.\n",
1711 program_invocation_short_name
,
1712 program_invocation_short_name
,
1718 static uint32_t determine_flags(void) {
1722 flags
|= CRYPT_ACTIVATE_READONLY
;
1725 flags
|= CRYPT_ACTIVATE_ALLOW_DISCARDS
;
1727 if (arg_same_cpu_crypt
)
1728 flags
|= CRYPT_ACTIVATE_SAME_CPU_CRYPT
;
1730 if (arg_submit_from_crypt_cpus
)
1731 flags
|= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS
;
1733 if (arg_no_read_workqueue
)
1734 flags
|= CRYPT_ACTIVATE_NO_READ_WORKQUEUE
;
1736 if (arg_no_write_workqueue
)
1737 flags
|= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE
;
1739 #ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
1740 /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
1741 /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
1742 flags
|= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
;
1748 static void remove_and_erasep(const char **p
) {
1754 r
= unlinkat_deallocate(AT_FDCWD
, *p
, UNLINK_ERASE
);
1755 if (r
< 0 && r
!= -ENOENT
)
1756 log_warning_errno(r
, "Unable to erase key file '%s', ignoring: %m", *p
);
1759 static int run(int argc
, char *argv
[]) {
1760 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1764 if (argv_looks_like_help(argc
, argv
))
1768 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1769 "This program requires at least two arguments.");
1773 cryptsetup_enable_logging(NULL
);
1779 if (streq(verb
, "attach")) {
1780 _unused_
_cleanup_(remove_and_erasep
) const char *destroy_key_file
= NULL
;
1781 _cleanup_(erase_and_freep
) void *key_data
= NULL
;
1782 const char *volume
, *source
, *key_file
, *options
;
1783 crypt_status_info status
;
1784 size_t key_data_size
= 0;
1789 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [KEY-FILE] [OPTIONS] */
1792 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "attach requires at least two arguments.");
1796 key_file
= mangle_none(argc
>= 5 ? argv
[4] : NULL
);
1797 options
= mangle_none(argc
>= 6 ? argv
[5] : NULL
);
1799 if (!filename_is_valid(volume
))
1800 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume name '%s' is not valid.", volume
);
1802 if (key_file
&& !path_is_absolute(key_file
)) {
1803 log_warning("Password file path '%s' is not absolute. Ignoring.", key_file
);
1808 r
= parse_options(options
);
1813 log_debug("%s %s ← %s type=%s cipher=%s", __func__
,
1814 volume
, source
, strempty(arg_type
), strempty(arg_cipher
));
1816 /* A delicious drop of snake oil */
1817 (void) mlockall(MCL_FUTURE
);
1820 _cleanup_free_
char *bindname
= NULL
;
1823 bindname
= make_bindname(volume
);
1827 /* If a key file is not explicitly specified, search for a key in a well defined
1828 * search path, and load it. */
1830 fn
= strjoina(volume
, ".key");
1833 STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"),
1835 &key_data
, &key_data_size
);
1839 log_debug("Automatically discovered key for volume '%s'.", volume
);
1840 } else if (arg_keyfile_erase
)
1841 destroy_key_file
= key_file
; /* let's get this baby erased when we leave */
1844 log_debug("LUKS header: %s", arg_header
);
1845 r
= crypt_init(&cd
, arg_header
);
1847 r
= crypt_init(&cd
, source
);
1849 return log_error_errno(r
, "crypt_init() failed: %m");
1851 cryptsetup_enable_logging(cd
);
1853 status
= crypt_status(cd
, volume
);
1854 if (IN_SET(status
, CRYPT_ACTIVE
, CRYPT_BUSY
)) {
1855 log_info("Volume %s already active.", volume
);
1859 flags
= determine_flags();
1861 until
= usec_add(now(CLOCK_MONOTONIC
), arg_timeout
);
1862 if (until
== USEC_INFINITY
)
1865 arg_key_size
= (arg_key_size
> 0 ? arg_key_size
: (256 / 8));
1870 /* Ideally we'd do this on the open fd, but since this is just a
1871 * warning it's OK to do this in two steps. */
1872 if (stat(key_file
, &st
) >= 0 && S_ISREG(st
.st_mode
) && (st
.st_mode
& 0005))
1873 log_warning("Key file %s is world-readable. This is not a good idea!", key_file
);
1876 if (!arg_type
|| STR_IN_SET(arg_type
, ANY_LUKS
, CRYPT_LUKS1
, CRYPT_LUKS2
)) {
1877 r
= crypt_load(cd
, !arg_type
|| streq(arg_type
, ANY_LUKS
) ? CRYPT_LUKS
: arg_type
, NULL
);
1879 return log_error_errno(r
, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd
));
1882 r
= crypt_set_data_device(cd
, source
);
1884 return log_error_errno(r
, "Failed to set LUKS data device %s: %m", source
);
1887 /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
1888 if (!key_file
&& !key_data
) {
1889 r
= crypt_activate_by_token_pin_ask_password(
1897 "Please enter LUKS2 token PIN:",
1899 "cryptsetup.luks2-pin");
1901 log_debug("Volume %s activated with LUKS token id %i.", volume
, r
);
1905 log_debug_errno(r
, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd
));
1909 /* since cryptsetup 2.3.0 (Feb 2020) */
1911 if (streq_ptr(arg_type
, CRYPT_BITLK
)) {
1912 r
= crypt_load(cd
, CRYPT_BITLK
, NULL
);
1914 return log_error_errno(r
, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd
));
1918 for (tries
= 0; arg_tries
== 0 || tries
< arg_tries
; tries
++) {
1919 _cleanup_strv_free_erase_
char **passwords
= NULL
;
1921 /* When we were able to acquire multiple keys, let's always process them in this order:
1923 * 1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
1924 * 2. The discovered key: i.e. key_data + key_data_size
1925 * 3. The configured key: i.e. key_file + arg_keyfile_offset + arg_keyfile_size
1926 * 4. The empty password, in case arg_try_empty_password is set
1927 * 5. We enquire the user for a password
1930 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
) {
1932 if (arg_try_empty_password
) {
1933 /* Hmm, let's try an empty password now, but only once */
1934 arg_try_empty_password
= false;
1936 key_data
= strdup("");
1942 /* Ask the user for a passphrase only as last resort, if we have
1943 * nothing else to check for */
1945 r
= get_password(volume
, source
, until
, tries
== 0 && !arg_verify
, &passwords
);
1953 if (streq_ptr(arg_type
, CRYPT_TCRYPT
))
1954 r
= attach_tcrypt(cd
, volume
, key_file
, key_data
, key_data_size
, passwords
, flags
);
1956 r
= attach_luks_or_plain_or_bitlk(cd
, volume
, key_file
, key_data
, key_data_size
, passwords
, flags
, until
);
1962 /* Key not correct? Let's try again! */
1965 key_data
= erase_and_free(key_data
);
1967 arg_pkcs11_uri
= mfree(arg_pkcs11_uri
);
1968 arg_pkcs11_uri_auto
= false;
1969 arg_fido2_device
= mfree(arg_fido2_device
);
1970 arg_fido2_device_auto
= false;
1971 arg_tpm2_device
= mfree(arg_tpm2_device
);
1972 arg_tpm2_device_auto
= false;
1975 if (arg_tries
!= 0 && tries
>= arg_tries
)
1976 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Too many attempts to activate; giving up.");
1978 } else if (streq(verb
, "detach")) {
1983 if (!filename_is_valid(volume
))
1984 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume name '%s' is not valid.", volume
);
1986 r
= crypt_init_by_name(&cd
, volume
);
1988 log_info("Volume %s already inactive.", volume
);
1992 return log_error_errno(r
, "crypt_init_by_name() failed: %m");
1994 cryptsetup_enable_logging(cd
);
1996 r
= crypt_deactivate(cd
, volume
);
1998 return log_error_errno(r
, "Failed to deactivate: %m");
2001 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown verb %s.", verb
);
2006 DEFINE_MAIN_FUNCTION(run
);