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_headless
= false;
86 static usec_t arg_token_timeout_usec
= 30*USEC_PER_SEC
;
88 STATIC_DESTRUCTOR_REGISTER(arg_cipher
, freep
);
89 STATIC_DESTRUCTOR_REGISTER(arg_hash
, freep
);
90 STATIC_DESTRUCTOR_REGISTER(arg_header
, freep
);
91 STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles
, strv_freep
);
92 STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri
, freep
);
93 STATIC_DESTRUCTOR_REGISTER(arg_fido2_device
, freep
);
94 STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid
, freep
);
95 STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id
, freep
);
96 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
98 /* Options Debian's crypttab knows we don't:
109 static int parse_one_option(const char *option
) {
115 /* Handled outside of this tool */
116 if (STR_IN_SET(option
, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
119 if (startswith(option
, "keyfile-timeout="))
122 if ((val
= startswith(option
, "cipher="))) {
123 r
= free_and_strdup(&arg_cipher
, val
);
127 } else if ((val
= startswith(option
, "size="))) {
129 r
= safe_atou(val
, &arg_key_size
);
131 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
135 if (arg_key_size
% 8) {
136 log_error("size= not a multiple of 8, ignoring.");
142 } else if ((val
= startswith(option
, "sector-size="))) {
144 r
= safe_atou(val
, &arg_sector_size
);
146 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
150 if (arg_sector_size
% 2) {
151 log_error("sector-size= not a multiple of 2, ignoring.");
155 if (arg_sector_size
< CRYPT_SECTOR_SIZE
|| arg_sector_size
> CRYPT_MAX_SECTOR_SIZE
) {
156 log_error("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE
, CRYPT_MAX_SECTOR_SIZE
);
160 } else if ((val
= startswith(option
, "key-slot=")) ||
161 (val
= startswith(option
, "keyslot="))) {
164 r
= safe_atoi(val
, &arg_key_slot
);
166 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
170 } else if ((val
= startswith(option
, "tcrypt-keyfile="))) {
172 arg_type
= CRYPT_TCRYPT
;
173 if (path_is_absolute(val
)) {
174 if (strv_extend(&arg_tcrypt_keyfiles
, val
) < 0)
177 log_error("Key file path \"%s\" is not absolute. Ignoring.", val
);
179 } else if ((val
= startswith(option
, "keyfile-size="))) {
181 r
= safe_atou(val
, &arg_keyfile_size
);
183 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
187 } else if ((val
= startswith(option
, "keyfile-offset="))) {
189 r
= safe_atou64(val
, &arg_keyfile_offset
);
191 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
195 } else if ((val
= startswith(option
, "keyfile-erase="))) {
197 r
= parse_boolean(val
);
199 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
203 arg_keyfile_erase
= r
;
205 } else if (streq(option
, "keyfile-erase"))
206 arg_keyfile_erase
= true;
208 else if ((val
= startswith(option
, "hash="))) {
209 r
= free_and_strdup(&arg_hash
, val
);
213 } else if ((val
= startswith(option
, "header="))) {
216 if (!path_is_absolute(val
))
217 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
218 "Header path \"%s\" is not absolute, refusing.", val
);
221 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
222 "Duplicate header= option, refusing.");
224 arg_header
= strdup(val
);
228 } else if ((val
= startswith(option
, "tries="))) {
230 r
= safe_atou(val
, &arg_tries
);
232 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
236 } else if (STR_IN_SET(option
, "readonly", "read-only"))
238 else if (streq(option
, "verify"))
240 else if ((val
= startswith(option
, "password-echo="))) {
241 if (streq(val
, "masked"))
242 arg_ask_password_flags
&= ~(ASK_PASSWORD_ECHO
|ASK_PASSWORD_SILENT
);
244 r
= parse_boolean(val
);
246 log_warning_errno(r
, "Invalid password-echo= option \"%s\", ignoring.", val
);
250 SET_FLAG(arg_ask_password_flags
, ASK_PASSWORD_ECHO
, r
);
251 SET_FLAG(arg_ask_password_flags
, ASK_PASSWORD_SILENT
, !r
);
253 } else if (STR_IN_SET(option
, "allow-discards", "discard"))
255 else if (streq(option
, "same-cpu-crypt"))
256 arg_same_cpu_crypt
= true;
257 else if (streq(option
, "submit-from-crypt-cpus"))
258 arg_submit_from_crypt_cpus
= true;
259 else if (streq(option
, "no-read-workqueue"))
260 arg_no_read_workqueue
= true;
261 else if (streq(option
, "no-write-workqueue"))
262 arg_no_write_workqueue
= true;
263 else if (streq(option
, "luks"))
265 /* since cryptsetup 2.3.0 (Feb 2020) */
267 else if (streq(option
, "bitlk"))
268 arg_type
= CRYPT_BITLK
;
270 else if (streq(option
, "tcrypt"))
271 arg_type
= CRYPT_TCRYPT
;
272 else if (STR_IN_SET(option
, "tcrypt-hidden", "tcrypthidden")) {
273 arg_type
= CRYPT_TCRYPT
;
274 arg_tcrypt_hidden
= true;
275 } else if (streq(option
, "tcrypt-system")) {
276 arg_type
= CRYPT_TCRYPT
;
277 arg_tcrypt_system
= true;
278 } else if (STR_IN_SET(option
, "tcrypt-veracrypt", "veracrypt")) {
279 arg_type
= CRYPT_TCRYPT
;
280 arg_tcrypt_veracrypt
= true;
281 } else if (STR_IN_SET(option
, "plain", "swap", "tmp") ||
282 startswith(option
, "tmp="))
283 arg_type
= CRYPT_PLAIN
;
284 else if ((val
= startswith(option
, "timeout="))) {
286 r
= parse_sec_fix_0(val
, &arg_timeout
);
288 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
292 } else if ((val
= startswith(option
, "offset="))) {
294 r
= safe_atou64(val
, &arg_offset
);
296 return log_error_errno(r
, "Failed to parse %s: %m", option
);
298 } else if ((val
= startswith(option
, "skip="))) {
300 r
= safe_atou64(val
, &arg_skip
);
302 return log_error_errno(r
, "Failed to parse %s: %m", option
);
304 } else if ((val
= startswith(option
, "pkcs11-uri="))) {
306 if (streq(val
, "auto")) {
307 arg_pkcs11_uri
= mfree(arg_pkcs11_uri
);
308 arg_pkcs11_uri_auto
= true;
310 if (!pkcs11_uri_valid(val
))
311 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing");
313 r
= free_and_strdup(&arg_pkcs11_uri
, val
);
317 arg_pkcs11_uri_auto
= false;
320 } else if ((val
= startswith(option
, "fido2-device="))) {
322 if (streq(val
, "auto")) {
323 arg_fido2_device
= mfree(arg_fido2_device
);
324 arg_fido2_device_auto
= true;
326 r
= free_and_strdup(&arg_fido2_device
, val
);
330 arg_fido2_device_auto
= false;
333 } else if ((val
= startswith(option
, "fido2-cid="))) {
335 if (streq(val
, "auto"))
336 arg_fido2_cid
= mfree(arg_fido2_cid
);
338 _cleanup_free_
void *cid
= NULL
;
341 r
= unbase64mem(val
, SIZE_MAX
, &cid
, &cid_size
);
343 return log_error_errno(r
, "Failed to decode FIDO2 CID data: %m");
346 arg_fido2_cid
= TAKE_PTR(cid
);
347 arg_fido2_cid_size
= cid_size
;
350 /* Turn on FIDO2 as side-effect, if not turned on yet. */
351 if (!arg_fido2_device
&& !arg_fido2_device_auto
)
352 arg_fido2_device_auto
= true;
354 } else if ((val
= startswith(option
, "fido2-rp="))) {
356 r
= free_and_strdup(&arg_fido2_rp_id
, val
);
360 } else if ((val
= startswith(option
, "tpm2-device="))) {
362 if (streq(val
, "auto")) {
363 arg_tpm2_device
= mfree(arg_tpm2_device
);
364 arg_tpm2_device_auto
= true;
366 r
= free_and_strdup(&arg_tpm2_device
, val
);
370 arg_tpm2_device_auto
= false;
373 } else if ((val
= startswith(option
, "tpm2-pcrs="))) {
376 arg_tpm2_pcr_mask
= 0;
380 r
= tpm2_parse_pcrs(val
, &mask
);
384 if (arg_tpm2_pcr_mask
== UINT32_MAX
)
385 arg_tpm2_pcr_mask
= mask
;
387 arg_tpm2_pcr_mask
|= mask
;
390 } else if ((val
= startswith(option
, "try-empty-password="))) {
392 r
= parse_boolean(val
);
394 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
398 arg_try_empty_password
= r
;
400 } else if (streq(option
, "try-empty-password"))
401 arg_try_empty_password
= true;
402 else if ((val
= startswith(option
, "headless="))) {
404 r
= parse_boolean(val
);
406 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
411 } else if (streq(option
, "headless"))
414 else if ((val
= startswith(option
, "token-timeout="))) {
416 r
= parse_sec_fix_0(val
, &arg_token_timeout_usec
);
418 log_error_errno(r
, "Failed to parse %s, ignoring: %m", option
);
422 } else if (!streq(option
, "x-initrd.attach"))
423 log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option
);
428 static int parse_options(const char *options
) {
432 _cleanup_free_
char *word
= NULL
;
435 r
= extract_first_word(&options
, &word
, ",", EXTRACT_DONT_COALESCE_SEPARATORS
| EXTRACT_UNESCAPE_SEPARATORS
);
437 return log_error_errno(r
, "Failed to parse options: %m");
441 r
= parse_one_option(word
);
446 /* sanity-check options */
447 if (arg_type
&& !streq(arg_type
, CRYPT_PLAIN
)) {
449 log_warning("offset= ignored with type %s", arg_type
);
451 log_warning("skip= ignored with type %s", arg_type
);
457 static char* disk_description(const char *path
) {
458 static const char name_fields
[] =
460 "ID_MODEL_FROM_DATABASE\0"
463 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
464 const char *i
, *name
;
469 if (stat(path
, &st
) < 0)
472 if (!S_ISBLK(st
.st_mode
))
475 if (sd_device_new_from_stat_rdev(&device
, &st
) < 0)
478 if (sd_device_get_property_value(device
, "ID_PART_ENTRY_NAME", &name
) >= 0) {
479 _cleanup_free_
char *unescaped
= NULL
;
482 /* ID_PART_ENTRY_NAME uses \x style escaping, using libblkid's blkid_encode_string(). Let's
483 * reverse this here to make the string more human friendly in case people embed spaces or
484 * other weird stuff. */
486 l
= cunescape(name
, UNESCAPE_RELAX
, &unescaped
);
488 log_debug_errno(l
, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
492 if (!isempty(unescaped
) && !string_has_cc(unescaped
, NULL
))
493 return TAKE_PTR(unescaped
);
496 /* These need no unescaping. */
497 NULSTR_FOREACH(i
, name_fields
)
498 if (sd_device_get_property_value(device
, i
, &name
) >= 0 &&
505 static char *disk_mount_point(const char *label
) {
506 _cleanup_free_
char *device
= NULL
;
507 _cleanup_endmntent_
FILE *f
= NULL
;
510 /* Yeah, we don't support native systemd unit files here for now */
512 device
= strjoin("/dev/mapper/", label
);
516 f
= setmntent(fstab_path(), "re");
520 while ((m
= getmntent(f
)))
521 if (path_equal(m
->mnt_fsname
, device
))
522 return strdup(m
->mnt_dir
);
527 static char *friendly_disk_name(const char *src
, const char *vol
) {
528 _cleanup_free_
char *description
= NULL
, *mount_point
= NULL
;
529 char *name_buffer
= NULL
;
535 description
= disk_description(src
);
536 mount_point
= disk_mount_point(vol
);
538 /* If the description string is simply the volume name, then let's not show this twice */
539 if (description
&& streq(vol
, description
))
540 description
= mfree(description
);
542 if (mount_point
&& description
)
543 r
= asprintf(&name_buffer
, "%s (%s) on %s", description
, vol
, mount_point
);
544 else if (mount_point
)
545 r
= asprintf(&name_buffer
, "%s on %s", vol
, mount_point
);
546 else if (description
)
547 r
= asprintf(&name_buffer
, "%s (%s)", description
, vol
);
556 static int get_password(
563 _cleanup_free_
char *friendly
= NULL
, *text
= NULL
, *disk_path
= NULL
;
564 _cleanup_strv_free_erase_
char **passwords
= NULL
;
567 AskPasswordFlags flags
= arg_ask_password_flags
| ASK_PASSWORD_PUSH_CACHE
;
574 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "Password querying disabled via 'headless' option.");
576 friendly
= friendly_disk_name(src
, vol
);
580 if (asprintf(&text
, "Please enter passphrase for disk %s:", friendly
) < 0)
583 disk_path
= cescape(src
);
587 id
= strjoina("cryptsetup:", disk_path
);
589 r
= ask_password_auto(text
, "drive-harddisk", id
, "cryptsetup", "cryptsetup.passphrase", until
,
590 flags
| (accept_cached
*ASK_PASSWORD_ACCEPT_CACHED
),
593 return log_error_errno(r
, "Failed to query password: %m");
596 _cleanup_strv_free_erase_
char **passwords2
= NULL
;
598 assert(strv_length(passwords
) == 1);
600 if (asprintf(&text
, "Please enter passphrase for disk %s (verification):", friendly
) < 0)
603 id
= strjoina("cryptsetup-verification:", disk_path
);
605 r
= ask_password_auto(text
, "drive-harddisk", id
, "cryptsetup", "cryptsetup.passphrase", until
, flags
, &passwords2
);
607 return log_error_errno(r
, "Failed to query verification password: %m");
609 assert(strv_length(passwords2
) == 1);
611 if (!streq(passwords
[0], passwords2
[0]))
612 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
),
613 "Passwords did not match, retrying.");
616 strv_uniq(passwords
);
618 STRV_FOREACH(p
, passwords
) {
621 if (strlen(*p
)+1 >= arg_key_size
)
624 /* Pad password if necessary */
625 c
= new(char, arg_key_size
);
629 strncpy(c
, *p
, arg_key_size
);
634 *ret
= TAKE_PTR(passwords
);
639 static int attach_tcrypt(
640 struct crypt_device
*cd
,
642 const char *key_file
,
643 const void *key_data
,
644 size_t key_data_size
,
649 _cleanup_(erase_and_freep
) char *passphrase
= NULL
;
650 struct crypt_params_tcrypt params
= {
651 .flags
= CRYPT_TCRYPT_LEGACY_MODES
,
652 .keyfiles
= (const char **)arg_tcrypt_keyfiles
,
653 .keyfiles_count
= strv_length(arg_tcrypt_keyfiles
)
658 assert(key_file
|| key_data
|| !strv_isempty(passwords
));
660 if (arg_pkcs11_uri
|| arg_pkcs11_uri_auto
|| arg_fido2_device
|| arg_fido2_device_auto
|| arg_tpm2_device
|| arg_tpm2_device_auto
)
661 /* Ask for a regular password */
662 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN
),
663 "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
665 if (arg_tcrypt_hidden
)
666 params
.flags
|= CRYPT_TCRYPT_HIDDEN_HEADER
;
668 if (arg_tcrypt_system
)
669 params
.flags
|= CRYPT_TCRYPT_SYSTEM_HEADER
;
671 if (arg_tcrypt_veracrypt
)
672 params
.flags
|= CRYPT_TCRYPT_VERA_MODES
;
675 params
.passphrase
= key_data
;
676 params
.passphrase_size
= key_data_size
;
679 r
= read_one_line_file(key_file
, &passphrase
);
681 log_error_errno(r
, "Failed to read password file '%s': %m", key_file
);
682 return -EAGAIN
; /* log with the actual error, but return EAGAIN */
685 params
.passphrase
= passphrase
;
687 params
.passphrase
= passwords
[0];
689 params
.passphrase_size
= strlen(params
.passphrase
);
692 r
= crypt_load(cd
, CRYPT_TCRYPT
, ¶ms
);
696 log_error_errno(r
, "Failed to activate using discovered key. (Key not correct?)");
699 log_error_errno(r
, "Failed to activate using password file '%s'. (Key data not correct?)", key_file
);
701 return -EAGAIN
; /* log the actual error, but return EAGAIN */
704 return log_error_errno(r
, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd
));
707 r
= crypt_activate_by_volume_key(cd
, name
, NULL
, 0, flags
);
709 return log_error_errno(r
, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd
));
714 static char *make_bindname(const char *volume
) {
717 if (asprintf(&s
, "@%" PRIx64
"/cryptsetup/%s", random_u64(), volume
) < 0)
723 static int make_security_device_monitor(
724 sd_event
**ret_event
,
725 sd_device_monitor
**ret_monitor
) {
726 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
727 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
733 /* Waits for a device with "security-device" tag to show up in udev */
735 r
= sd_event_default(&event
);
737 return log_error_errno(r
, "Failed to allocate event loop: %m");
739 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, arg_token_timeout_usec
, USEC_PER_SEC
, NULL
, INT_TO_PTR(-ETIMEDOUT
));
741 return log_error_errno(r
, "Failed to install timeout event source: %m");
743 r
= sd_device_monitor_new(&monitor
);
745 return log_error_errno(r
, "Failed to allocate device monitor: %m");
747 r
= sd_device_monitor_filter_add_match_tag(monitor
, "security-device");
749 return log_error_errno(r
, "Failed to configure device monitor: %m");
751 r
= sd_device_monitor_attach_event(monitor
, event
);
753 return log_error_errno(r
, "Failed to attach device monitor: %m");
755 r
= sd_device_monitor_start(monitor
, NULL
, NULL
);
757 return log_error_errno(r
, "Failed to start device monitor: %m");
759 *ret_event
= TAKE_PTR(event
);
760 *ret_monitor
= TAKE_PTR(monitor
);
764 static int run_security_device_monitor(
766 sd_device_monitor
*monitor
) {
767 bool processed
= false;
773 /* Runs the event loop for the device monitor until either something happens, or the time-out is
779 r
= sd_event_get_exit_code(event
, &x
);
782 return log_error_errno(r
, "Failed to query exit code from event loop: %m");
784 /* On ENODATA we aren't told to exit yet. */
786 assert(x
== -ETIMEDOUT
);
787 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
),
788 "Timed out waiting for security device, aborting security device based authentication attempt.");
791 /* Wait for one event, and then eat all subsequent events until there are no further ones */
792 r
= sd_event_run(event
, processed
? 0 : UINT64_MAX
);
794 return log_error_errno(r
, "Failed to run event loop: %m");
795 if (r
== 0) /* no events queued anymore */
802 static bool libcryptsetup_plugins_support(void) {
803 #if HAVE_LIBCRYPTSETUP_PLUGINS
806 /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
807 r
= getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
808 if (r
< 0 && r
!= -ENXIO
)
809 log_debug_errno(r
, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
813 return crypt_token_external_path();
819 #if HAVE_LIBCRYPTSETUP_PLUGINS
820 static int acquire_pins_from_env_variable(char ***ret_pins
) {
822 _cleanup_strv_free_erase_
char **pins
= NULL
;
833 if (unsetenv("PIN") < 0)
834 return log_error_errno(errno
, "Failed to unset $PIN: %m");
837 *ret_pins
= TAKE_PTR(pins
);
843 static int attach_luks2_by_fido2(
844 struct crypt_device
*cd
,
849 uint32_t activation_flags
) {
851 #if HAVE_LIBCRYPTSETUP_PLUGINS
852 AskPasswordFlags flags
= ASK_PASSWORD_PUSH_CACHE
| ASK_PASSWORD_ACCEPT_CACHED
;
853 _cleanup_strv_free_erase_
char **pins
= NULL
;
857 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-fido2", CRYPT_ANY_TOKEN
, NULL
, 0, usrptr
, activation_flags
);
858 if (r
> 0) /* returns unlocked keyslot id on success */
860 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
863 r
= acquire_pins_from_env_variable(&pins
);
867 STRV_FOREACH(p
, pins
) {
868 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-fido2", CRYPT_ANY_TOKEN
, *p
, strlen(*p
), usrptr
, activation_flags
);
869 if (r
> 0) /* returns unlocked keyslot id on success */
871 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
876 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
879 pins
= strv_free_erase(pins
);
880 r
= ask_password_auto("Please enter security token PIN:", "drive-harddisk", NULL
, "fido2-pin", "cryptsetup.fido2-pin", until
, flags
, &pins
);
884 STRV_FOREACH(p
, pins
) {
885 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-fido2", CRYPT_ANY_TOKEN
, *p
, strlen(*p
), usrptr
, activation_flags
);
886 if (r
> 0) /* returns unlocked keyslot id on success */
888 if (r
!= -ENOANO
) /* needs pin or pin is wrong */
892 flags
&= ~ASK_PASSWORD_ACCEPT_CACHED
;
900 static int attach_luks_or_plain_or_bitlk_by_fido2(
901 struct crypt_device
*cd
,
903 const char *key_file
,
904 const void *key_data
,
905 size_t key_data_size
,
908 bool pass_volume_key
) {
910 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
911 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
912 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
913 _cleanup_free_
void *discovered_salt
= NULL
, *discovered_cid
= NULL
;
914 size_t discovered_salt_size
, discovered_cid_size
, decrypted_key_size
, cid_size
= 0;
915 _cleanup_free_
char *friendly
= NULL
, *discovered_rp_id
= NULL
;
916 int keyslot
= arg_key_slot
, r
;
917 const char *rp_id
= NULL
;
918 const void *cid
= NULL
;
919 Fido2EnrollFlags required
;
920 bool use_libcryptsetup_plugin
= libcryptsetup_plugins_support();
924 assert(arg_fido2_device
|| arg_fido2_device_auto
);
927 if (!key_file
&& !key_data
)
928 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
929 "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
931 rp_id
= arg_fido2_rp_id
;
933 cid_size
= arg_fido2_cid_size
;
935 /* For now and for compatibility, if the user explicitly configured FIDO2 support and we do
936 * not read FIDO2 metadata off the LUKS2 header, default to the systemd 248 logic, where we
937 * use PIN + UP when needed, and do not configure UV at all. Eventually, we should make this
938 * explicitly configurable. */
939 required
= FIDO2ENROLL_PIN_IF_NEEDED
| FIDO2ENROLL_UP_IF_NEEDED
| FIDO2ENROLL_UV_OMIT
;
940 } else if (!use_libcryptsetup_plugin
) {
941 r
= find_fido2_auto_data(
945 &discovered_salt_size
,
947 &discovered_cid_size
,
951 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
))
952 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
953 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
957 if ((required
& (FIDO2ENROLL_PIN
| FIDO2ENROLL_UP
| FIDO2ENROLL_UV
)) && arg_headless
)
958 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG
),
959 "Local verification is required to unlock this volume, but the 'headless' parameter was set.");
961 rp_id
= discovered_rp_id
;
962 key_data
= discovered_salt
;
963 key_data_size
= discovered_salt_size
;
964 cid
= discovered_cid
;
965 cid_size
= discovered_cid_size
;
968 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
973 if (use_libcryptsetup_plugin
&& !arg_fido2_cid
) {
974 r
= attach_luks2_by_fido2(cd
, name
, until
, arg_headless
, arg_fido2_device
, flags
);
975 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
, -ENOENT
))
976 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
977 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
980 r
= acquire_fido2_key(
986 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
987 key_data
, key_data_size
,
991 &decrypted_key
, &decrypted_key_size
,
992 arg_ask_password_flags
);
997 if (r
!= -EAGAIN
) /* EAGAIN means: token not found */
1001 /* We didn't find the token. In this case, watch for it via udev. Let's
1002 * create an event loop and monitor first. */
1006 r
= make_security_device_monitor(&event
, &monitor
);
1010 log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly
);
1012 /* Let's immediately rescan in case the token appeared in the time we needed
1013 * to create and configure the monitor */
1017 r
= run_security_device_monitor(event
, monitor
);
1021 log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
1024 if (pass_volume_key
)
1025 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1027 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1029 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1031 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1035 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1038 log_error_errno(r
, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
1039 return -EAGAIN
; /* log actual error, but return EAGAIN */
1042 return log_error_errno(r
, "Failed to activate with FIDO2 acquired key: %m");
1047 static int attach_luks2_by_pkcs11(
1048 struct crypt_device
*cd
,
1050 const char *friendly_name
,
1055 #if HAVE_LIBCRYPTSETUP_PLUGINS
1058 if (!streq_ptr(crypt_get_type(cd
), CRYPT_LUKS2
))
1059 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Automatic PKCS#11 metadata requires LUKS2 device.");
1061 systemd_pkcs11_plugin_params params
= {
1062 .friendly_name
= friendly_name
,
1064 .headless
= headless
1067 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-pkcs11", CRYPT_ANY_TOKEN
, NULL
, 0, ¶ms
, flags
);
1068 if (r
> 0) /* returns unlocked keyslot id on success */
1077 static int attach_luks_or_plain_or_bitlk_by_pkcs11(
1078 struct crypt_device
*cd
,
1080 const char *key_file
,
1081 const void *key_data
,
1082 size_t key_data_size
,
1085 bool pass_volume_key
) {
1087 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1088 _cleanup_free_
char *friendly
= NULL
, *discovered_uri
= NULL
;
1089 size_t decrypted_key_size
= 0, discovered_key_size
= 0;
1090 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
1091 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1092 _cleanup_free_
void *discovered_key
= NULL
;
1093 int keyslot
= arg_key_slot
, r
;
1094 const char *uri
= NULL
;
1095 bool use_libcryptsetup_plugin
= libcryptsetup_plugins_support();
1099 assert(arg_pkcs11_uri
|| arg_pkcs11_uri_auto
);
1101 if (arg_pkcs11_uri_auto
) {
1102 if (!use_libcryptsetup_plugin
) {
1103 r
= find_pkcs11_auto_data(cd
, &discovered_uri
, &discovered_key
, &discovered_key_size
, &keyslot
);
1104 if (IN_SET(r
, -ENOTUNIQ
, -ENXIO
))
1105 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1106 "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1110 uri
= discovered_uri
;
1111 key_data
= discovered_key
;
1112 key_data_size
= discovered_key_size
;
1115 uri
= arg_pkcs11_uri
;
1117 if (!key_file
&& !key_data
)
1118 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "PKCS#11 mode selected but no key file specified, refusing.");
1121 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1126 if (use_libcryptsetup_plugin
&& arg_pkcs11_uri_auto
)
1127 r
= attach_luks2_by_pkcs11(cd
, name
, friendly
, until
, arg_headless
, flags
);
1129 r
= decrypt_pkcs11_key(
1133 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1134 key_data
, key_data_size
,
1137 &decrypted_key
, &decrypted_key_size
);
1142 if (r
!= -EAGAIN
) /* EAGAIN means: token not found */
1146 /* We didn't find the token. In this case, watch for it via udev. Let's
1147 * create an event loop and monitor first. */
1151 r
= make_security_device_monitor(&event
, &monitor
);
1155 log_notice("Security token %s not present for unlocking volume %s, please plug it in.",
1158 /* Let's immediately rescan in case the token appeared in the time we needed
1159 * to create and configure the monitor */
1163 r
= run_security_device_monitor(event
, monitor
);
1167 log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
1169 assert(decrypted_key
);
1171 if (pass_volume_key
)
1172 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1174 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1176 /* Before using this key as passphrase we base64 encode it. Why? For compatibility
1177 * with homed's PKCS#11 hookup: there we want to use the key we acquired through
1178 * PKCS#11 for other authentication/decryption mechanisms too, and some of them do
1179 * not not take arbitrary binary blobs, but require NUL-terminated strings — most
1180 * importantly UNIX password hashes. Hence, for compatibility we want to use a string
1181 * without embedded NUL here too, and that's easiest to generate from a binary blob
1182 * via base64 encoding. */
1184 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1188 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1191 log_error_errno(r
, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
1192 return -EAGAIN
; /* log actual error, but return EAGAIN */
1195 return log_error_errno(r
, "Failed to activate with PKCS#11 acquired key: %m");
1200 static int make_tpm2_device_monitor(
1201 sd_event
**ret_event
,
1202 sd_device_monitor
**ret_monitor
) {
1204 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1205 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1209 assert(ret_monitor
);
1211 r
= sd_event_default(&event
);
1213 return log_error_errno(r
, "Failed to allocate event loop: %m");
1215 r
= sd_event_add_time_relative(event
, NULL
, CLOCK_MONOTONIC
, arg_token_timeout_usec
, USEC_PER_SEC
, NULL
, INT_TO_PTR(-ETIMEDOUT
));
1217 return log_error_errno(r
, "Failed to install timeout event source: %m");
1219 r
= sd_device_monitor_new(&monitor
);
1221 return log_error_errno(r
, "Failed to allocate device monitor: %m");
1223 r
= sd_device_monitor_filter_add_match_subsystem_devtype(monitor
, "tpmrm", NULL
);
1225 return log_error_errno(r
, "Failed to configure device monitor: %m");
1227 r
= sd_device_monitor_attach_event(monitor
, event
);
1229 return log_error_errno(r
, "Failed to attach device monitor: %m");
1231 r
= sd_device_monitor_start(monitor
, NULL
, NULL
);
1233 return log_error_errno(r
, "Failed to start device monitor: %m");
1235 *ret_event
= TAKE_PTR(event
);
1236 *ret_monitor
= TAKE_PTR(monitor
);
1240 static int attach_luks2_by_tpm2(
1241 struct crypt_device
*cd
,
1245 #if HAVE_LIBCRYPTSETUP_PLUGINS
1248 systemd_tpm2_plugin_params params
= {
1249 .search_pcr_mask
= arg_tpm2_pcr_mask
,
1250 .device
= arg_tpm2_device
1253 if (!crypt_token_external_path())
1254 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1255 "Libcryptsetup has external plugins support disabled.");
1257 r
= crypt_activate_by_token_pin(cd
, name
, "systemd-tpm2", CRYPT_ANY_TOKEN
, NULL
, 0, ¶ms
, flags
);
1258 if (r
> 0) /* returns unlocked keyslot id on success */
1267 static int attach_luks_or_plain_or_bitlk_by_tpm2(
1268 struct crypt_device
*cd
,
1270 const char *key_file
,
1271 const void *key_data
,
1272 size_t key_data_size
,
1275 bool pass_volume_key
) {
1277 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
1278 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
;
1279 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1280 _cleanup_free_
char *friendly
= NULL
;
1281 int keyslot
= arg_key_slot
, r
;
1282 size_t decrypted_key_size
;
1286 assert(arg_tpm2_device
|| arg_tpm2_device_auto
);
1288 friendly
= friendly_disk_name(crypt_get_device_name(cd
), name
);
1293 if (key_file
|| key_data
) {
1294 /* If key data is specified, use that */
1296 r
= acquire_tpm2_key(
1299 arg_tpm2_pcr_mask
== UINT32_MAX
? TPM2_PCR_MASK_DEFAULT
: arg_tpm2_pcr_mask
,
1302 key_file
, arg_keyfile_size
, arg_keyfile_offset
,
1303 key_data
, key_data_size
,
1304 NULL
, 0, /* we don't know the policy hash */
1305 &decrypted_key
, &decrypted_key_size
);
1308 if (ERRNO_IS_NOT_SUPPORTED(r
)) /* TPM2 support not compiled in? */
1309 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 support not available, falling back to traditional unlocking.");
1310 if (r
!= -EAGAIN
) /* EAGAIN means: no tpm2 chip found */
1313 r
= attach_luks2_by_tpm2(cd
, name
, flags
);
1314 /* EAGAIN means: no tpm2 chip found
1315 * EOPNOTSUPP means: no libcryptsetup plugins support */
1317 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1318 "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
1320 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1321 "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
1322 if (!IN_SET(r
, -EOPNOTSUPP
, -EAGAIN
))
1326 if (r
== -EOPNOTSUPP
) {
1327 _cleanup_free_
void *blob
= NULL
, *policy_hash
= NULL
;
1328 size_t blob_size
, policy_hash_size
;
1329 bool found_some
= false;
1330 int token
= 0; /* first token to look at */
1332 /* If no key data is specified, look for it in the header. In order to support
1333 * software upgrades we'll iterate through all suitable tokens, maybe one of them
1338 uint16_t pcr_bank
, primary_alg
;
1340 r
= find_tpm2_auto_data(
1342 arg_tpm2_pcr_mask
, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1343 token
, /* search for the token with this index, or any later index than this */
1348 &policy_hash
, &policy_hash_size
,
1352 /* No further TPM2 tokens found in the LUKS2 header. */
1353 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
1355 ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
1356 : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
1357 if (ERRNO_IS_NOT_SUPPORTED(r
)) /* TPM2 support not compiled in? */
1358 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
), "TPM2 support not available, falling back to traditional unlocking.");
1364 r
= acquire_tpm2_key(
1370 NULL
, 0, 0, /* no key file */
1372 policy_hash
, policy_hash_size
,
1373 &decrypted_key
, &decrypted_key_size
);
1377 token
++; /* try a different token next time */
1382 if (r
!= -EAGAIN
) /* EAGAIN means: no tpm2 chip found */
1387 /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
1388 * an event loop and monitor first. */
1392 if (is_efi_boot() && !efi_has_tpm2())
1393 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN
),
1394 "No TPM2 hardware discovered and EFI bios indicates no support for it either, assuming TPM2-less system, falling back to traditional unocking.");
1396 r
= make_tpm2_device_monitor(&event
, &monitor
);
1400 log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly
);
1402 /* Let's immediately rescan in case the device appeared in the time we needed
1403 * to create and configure the monitor */
1407 r
= run_security_device_monitor(event
, monitor
);
1411 log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
1413 assert(decrypted_key
);
1415 if (pass_volume_key
)
1416 r
= crypt_activate_by_volume_key(cd
, name
, decrypted_key
, decrypted_key_size
, flags
);
1418 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
1420 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1422 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
1426 r
= crypt_activate_by_passphrase(cd
, name
, keyslot
, base64_encoded
, strlen(base64_encoded
), flags
);
1429 log_error_errno(r
, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
1430 return -EAGAIN
; /* log actual error, but return EAGAIN */
1433 return log_error_errno(r
, "Failed to activate with TPM2 acquired key: %m");
1438 static int attach_luks_or_plain_or_bitlk_by_key_data(
1439 struct crypt_device
*cd
,
1441 const void *key_data
,
1442 size_t key_data_size
,
1444 bool pass_volume_key
) {
1452 if (pass_volume_key
)
1453 r
= crypt_activate_by_volume_key(cd
, name
, key_data
, key_data_size
, flags
);
1455 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, key_data
, key_data_size
, flags
);
1457 log_error_errno(r
, "Failed to activate. (Key incorrect?)");
1458 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1461 return log_error_errno(r
, "Failed to activate: %m");
1466 static int attach_luks_or_plain_or_bitlk_by_key_file(
1467 struct crypt_device
*cd
,
1469 const char *key_file
,
1471 bool pass_volume_key
) {
1473 _cleanup_(erase_and_freep
) char *kfdata
= NULL
;
1474 _cleanup_free_
char *bindname
= NULL
;
1482 /* If we read the key via AF_UNIX, make this client recognizable */
1483 bindname
= make_bindname(name
);
1487 r
= read_full_file_full(
1489 arg_keyfile_offset
== 0 ? UINT64_MAX
: arg_keyfile_offset
,
1490 arg_keyfile_size
== 0 ? SIZE_MAX
: arg_keyfile_size
,
1491 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
1495 log_error_errno(r
, "Failed to activate, key file '%s' too large.", key_file
);
1499 log_error_errno(r
, "Failed to activate, key file '%s' missing.", key_file
);
1500 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1503 return log_error_errno(r
, "Failed to read key file '%s': %m", key_file
);
1505 if (pass_volume_key
)
1506 r
= crypt_activate_by_volume_key(cd
, name
, kfdata
, kfsize
, flags
);
1508 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, kfdata
, kfsize
, flags
);
1510 log_error_errno(r
, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file
);
1511 return -EAGAIN
; /* Log actual error, but return EAGAIN */
1514 return log_error_errno(r
, "Failed to activate with key file '%s': %m", key_file
);
1519 static int attach_luks_or_plain_or_bitlk_by_passphrase(
1520 struct crypt_device
*cd
,
1524 bool pass_volume_key
) {
1533 STRV_FOREACH(p
, passwords
) {
1534 if (pass_volume_key
)
1535 r
= crypt_activate_by_volume_key(cd
, name
, *p
, arg_key_size
, flags
);
1537 r
= crypt_activate_by_passphrase(cd
, name
, arg_key_slot
, *p
, strlen(*p
), flags
);
1542 log_error_errno(r
, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
1543 return -EAGAIN
; /* log actual error, but return EAGAIN */
1546 return log_error_errno(r
, "Failed to activate with specified passphrase: %m");
1551 static int attach_luks_or_plain_or_bitlk(
1552 struct crypt_device
*cd
,
1554 const char *key_file
,
1555 const void *key_data
,
1556 size_t key_data_size
,
1561 bool pass_volume_key
= false;
1567 if ((!arg_type
&& !crypt_get_type(cd
)) || streq_ptr(arg_type
, CRYPT_PLAIN
)) {
1568 struct crypt_params_plain params
= {
1569 .offset
= arg_offset
,
1571 .sector_size
= arg_sector_size
,
1573 const char *cipher
, *cipher_mode
;
1574 _cleanup_free_
char *truncated_cipher
= NULL
;
1576 if (streq_ptr(arg_hash
, "plain"))
1577 /* plain isn't a real hash type. it just means "use no hash" */
1580 params
.hash
= arg_hash
;
1582 /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
1583 * file is provided */
1584 params
.hash
= "ripemd160";
1589 l
= strcspn(arg_cipher
, "-");
1590 truncated_cipher
= strndup(arg_cipher
, l
);
1591 if (!truncated_cipher
)
1594 cipher
= truncated_cipher
;
1595 cipher_mode
= arg_cipher
[l
] ? arg_cipher
+l
+1 : "plain";
1598 cipher_mode
= "cbc-essiv:sha256";
1601 /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
1602 arg_keyfile_size
= arg_key_size
;
1604 /* In contrast to what the name crypt_format() might suggest this doesn't actually format
1605 * anything, it just configures encryption parameters when used for plain mode. */
1606 r
= crypt_format(cd
, CRYPT_PLAIN
, cipher
, cipher_mode
, NULL
, NULL
, arg_keyfile_size
, ¶ms
);
1608 return log_error_errno(r
, "Loading of cryptographic parameters failed: %m");
1610 /* hash == NULL implies the user passed "plain" */
1611 pass_volume_key
= !params
.hash
;
1614 log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
1615 crypt_get_cipher(cd
),
1616 crypt_get_cipher_mode(cd
),
1617 crypt_get_volume_key_size(cd
)*8,
1618 crypt_get_device_name(cd
));
1620 if (arg_tpm2_device
|| arg_tpm2_device_auto
)
1621 return attach_luks_or_plain_or_bitlk_by_tpm2(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1622 if (arg_fido2_device
|| arg_fido2_device_auto
)
1623 return attach_luks_or_plain_or_bitlk_by_fido2(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1624 if (arg_pkcs11_uri
|| arg_pkcs11_uri_auto
)
1625 return attach_luks_or_plain_or_bitlk_by_pkcs11(cd
, name
, key_file
, key_data
, key_data_size
, until
, flags
, pass_volume_key
);
1627 return attach_luks_or_plain_or_bitlk_by_key_data(cd
, name
, key_data
, key_data_size
, flags
, pass_volume_key
);
1629 return attach_luks_or_plain_or_bitlk_by_key_file(cd
, name
, key_file
, flags
, pass_volume_key
);
1631 return attach_luks_or_plain_or_bitlk_by_passphrase(cd
, name
, passwords
, flags
, pass_volume_key
);
1634 static int help(void) {
1635 _cleanup_free_
char *link
= NULL
;
1638 r
= terminal_urlify_man("systemd-cryptsetup@.service", "8", &link
);
1642 printf("%s attach VOLUME SOURCEDEVICE [PASSWORD] [OPTIONS]\n"
1643 "%s detach VOLUME\n\n"
1644 "Attaches or detaches an encrypted block device.\n"
1645 "\nSee the %s for details.\n",
1646 program_invocation_short_name
,
1647 program_invocation_short_name
,
1653 static uint32_t determine_flags(void) {
1657 flags
|= CRYPT_ACTIVATE_READONLY
;
1660 flags
|= CRYPT_ACTIVATE_ALLOW_DISCARDS
;
1662 if (arg_same_cpu_crypt
)
1663 flags
|= CRYPT_ACTIVATE_SAME_CPU_CRYPT
;
1665 if (arg_submit_from_crypt_cpus
)
1666 flags
|= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS
;
1668 if (arg_no_read_workqueue
)
1669 flags
|= CRYPT_ACTIVATE_NO_READ_WORKQUEUE
;
1671 if (arg_no_write_workqueue
)
1672 flags
|= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE
;
1674 #ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
1675 /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
1676 /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
1677 flags
|= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
;
1683 static void remove_and_erasep(const char **p
) {
1689 r
= unlinkat_deallocate(AT_FDCWD
, *p
, UNLINK_ERASE
);
1690 if (r
< 0 && r
!= -ENOENT
)
1691 log_warning_errno(r
, "Unable to erase key file '%s', ignoring: %m", *p
);
1694 static int run(int argc
, char *argv
[]) {
1695 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1703 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1704 "This program requires at least two arguments.");
1708 cryptsetup_enable_logging(NULL
);
1714 if (streq(verb
, "attach")) {
1715 _unused_
_cleanup_(remove_and_erasep
) const char *destroy_key_file
= NULL
;
1716 _cleanup_(erase_and_freep
) void *key_data
= NULL
;
1717 const char *volume
, *source
, *key_file
, *options
;
1718 crypt_status_info status
;
1719 size_t key_data_size
= 0;
1724 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [PASSWORD] [OPTIONS] */
1727 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "attach requires at least two arguments.");
1731 key_file
= argc
>= 5 && !STR_IN_SET(argv
[4], "", "-", "none") ? argv
[4] : NULL
;
1732 options
= argc
>= 6 && !STR_IN_SET(argv
[5], "", "-", "none") ? argv
[5] : NULL
;
1734 if (!filename_is_valid(volume
))
1735 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume name '%s' is not valid.", volume
);
1737 if (key_file
&& !path_is_absolute(key_file
)) {
1738 log_warning("Password file path '%s' is not absolute. Ignoring.", key_file
);
1743 r
= parse_options(options
);
1748 log_debug("%s %s ← %s type=%s cipher=%s", __func__
,
1749 volume
, source
, strempty(arg_type
), strempty(arg_cipher
));
1751 /* A delicious drop of snake oil */
1752 (void) mlockall(MCL_FUTURE
);
1755 _cleanup_free_
char *bindname
= NULL
;
1758 bindname
= make_bindname(volume
);
1762 /* If a key file is not explicitly specified, search for a key in a well defined
1763 * search path, and load it. */
1765 fn
= strjoina(volume
, ".key");
1768 STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"),
1770 &key_data
, &key_data_size
);
1774 log_debug("Automatically discovered key for volume '%s'.", volume
);
1775 } else if (arg_keyfile_erase
)
1776 destroy_key_file
= key_file
; /* let's get this baby erased when we leave */
1779 log_debug("LUKS header: %s", arg_header
);
1780 r
= crypt_init(&cd
, arg_header
);
1782 r
= crypt_init(&cd
, source
);
1784 return log_error_errno(r
, "crypt_init() failed: %m");
1786 cryptsetup_enable_logging(cd
);
1788 status
= crypt_status(cd
, volume
);
1789 if (IN_SET(status
, CRYPT_ACTIVE
, CRYPT_BUSY
)) {
1790 log_info("Volume %s already active.", volume
);
1794 flags
= determine_flags();
1796 until
= usec_add(now(CLOCK_MONOTONIC
), arg_timeout
);
1797 if (until
== USEC_INFINITY
)
1800 arg_key_size
= (arg_key_size
> 0 ? arg_key_size
: (256 / 8));
1805 /* Ideally we'd do this on the open fd, but since this is just a
1806 * warning it's OK to do this in two steps. */
1807 if (stat(key_file
, &st
) >= 0 && S_ISREG(st
.st_mode
) && (st
.st_mode
& 0005))
1808 log_warning("Key file %s is world-readable. This is not a good idea!", key_file
);
1811 if (!arg_type
|| STR_IN_SET(arg_type
, ANY_LUKS
, CRYPT_LUKS1
, CRYPT_LUKS2
)) {
1812 r
= crypt_load(cd
, !arg_type
|| streq(arg_type
, ANY_LUKS
) ? CRYPT_LUKS
: arg_type
, NULL
);
1814 return log_error_errno(r
, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd
));
1817 r
= crypt_set_data_device(cd
, source
);
1819 return log_error_errno(r
, "Failed to set LUKS data device %s: %m", source
);
1822 /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
1823 if (!key_file
&& !key_data
) {
1824 r
= crypt_activate_by_token(cd
, volume
, CRYPT_ANY_TOKEN
, NULL
, flags
);
1826 log_debug("Volume %s activated with LUKS token id %i.", volume
, r
);
1830 log_debug_errno(r
, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd
));
1834 /* since cryptsetup 2.3.0 (Feb 2020) */
1836 if (streq_ptr(arg_type
, CRYPT_BITLK
)) {
1837 r
= crypt_load(cd
, CRYPT_BITLK
, NULL
);
1839 return log_error_errno(r
, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd
));
1843 for (tries
= 0; arg_tries
== 0 || tries
< arg_tries
; tries
++) {
1844 _cleanup_strv_free_erase_
char **passwords
= NULL
;
1846 /* When we were able to acquire multiple keys, let's always process them in this order:
1848 * 1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
1849 * 2. The discovered key: i.e. key_data + key_data_size
1850 * 3. The configured key: i.e. key_file + arg_keyfile_offset + arg_keyfile_size
1851 * 4. The empty password, in case arg_try_empty_password is set
1852 * 5. We enquire the user for a password
1855 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
) {
1857 if (arg_try_empty_password
) {
1858 /* Hmm, let's try an empty password now, but only once */
1859 arg_try_empty_password
= false;
1861 key_data
= strdup("");
1867 /* Ask the user for a passphrase only as last resort, if we have
1868 * nothing else to check for */
1870 r
= get_password(volume
, source
, until
, tries
== 0 && !arg_verify
, &passwords
);
1878 if (streq_ptr(arg_type
, CRYPT_TCRYPT
))
1879 r
= attach_tcrypt(cd
, volume
, key_file
, key_data
, key_data_size
, passwords
, flags
);
1881 r
= attach_luks_or_plain_or_bitlk(cd
, volume
, key_file
, key_data
, key_data_size
, passwords
, flags
, until
);
1887 /* Key not correct? Let's try again! */
1890 key_data
= erase_and_free(key_data
);
1892 arg_pkcs11_uri
= mfree(arg_pkcs11_uri
);
1893 arg_pkcs11_uri_auto
= false;
1894 arg_fido2_device
= mfree(arg_fido2_device
);
1895 arg_fido2_device_auto
= false;
1896 arg_tpm2_device
= mfree(arg_tpm2_device
);
1897 arg_tpm2_device_auto
= false;
1900 if (arg_tries
!= 0 && tries
>= arg_tries
)
1901 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Too many attempts to activate; giving up.");
1903 } else if (streq(verb
, "detach")) {
1908 if (!filename_is_valid(volume
))
1909 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume name '%s' is not valid.", volume
);
1911 r
= crypt_init_by_name(&cd
, volume
);
1913 log_info("Volume %s already inactive.", volume
);
1917 return log_error_errno(r
, "crypt_init_by_name() failed: %m");
1919 cryptsetup_enable_logging(cd
);
1921 r
= crypt_deactivate(cd
, volume
);
1923 return log_error_errno(r
, "Failed to deactivate: %m");
1926 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown verb %s.", verb
);
1931 DEFINE_MAIN_FUNCTION(run
);