]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/cryptsetup/cryptsetup.c
Merge pull request #28891 from poettering/pcrlock
[thirdparty/systemd.git] / src / cryptsetup / cryptsetup.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
e23a0ce8 2
7f4e0805 3#include <errno.h>
166015fa 4#include <getopt.h>
07630cea 5#include <mntent.h>
07630cea 6#include <sys/mman.h>
ca78ad1d
ZJS
7#include <sys/stat.h>
8#include <sys/types.h>
9#include <unistd.h>
e23a0ce8 10
4f5dd394 11#include "sd-device.h"
94c0c85e 12#include "sd-messages.h"
4f5dd394 13
b5efdb8a 14#include "alloc-util.h"
4f5dd394 15#include "ask-password-api.h"
166015fa 16#include "build.h"
2bc5c425 17#include "cryptsetup-fido2.h"
1e2f3230 18#include "cryptsetup-keyfile.h"
08669709 19#include "cryptsetup-pkcs11.h"
18843ecc 20#include "cryptsetup-tpm2.h"
7407f689 21#include "cryptsetup-util.h"
4f5dd394 22#include "device-util.h"
7be4b236 23#include "efi-api.h"
6c51b49c 24#include "efi-loader.h"
64c590fb 25#include "env-util.h"
4f5dd394 26#include "escape.h"
8cf3ca80 27#include "fileio.h"
d3d49e76 28#include "fs-util.h"
ed4ad488 29#include "fstab-util.h"
08669709 30#include "hexdecoct.h"
2bc5c425 31#include "libfido2-util.h"
e23a0ce8 32#include "log.h"
3a40f366 33#include "main-func.h"
7407f689 34#include "memory-util.h"
4349cd7c 35#include "mount-util.h"
d8b4d14d 36#include "nulstr-util.h"
6bedfcbb 37#include "parse-util.h"
9eb977db 38#include "path-util.h"
08669709 39#include "pkcs11-util.h"
d8b4d14d 40#include "pretty-print.h"
542bb9be 41#include "process-util.h"
e2c2f868 42#include "random-util.h"
b6c0bd11 43#include "string-table.h"
21bc923a 44#include "strv.h"
e0e1f4f7 45#include "tpm2-pcr.h"
18843ecc 46#include "tpm2-util.h"
7f4e0805 47
b3b4ebab
OK
48/* internal helper */
49#define ANY_LUKS "LUKS"
a9fc6406 50/* as in src/cryptsetup.h */
63b98386
JJ
51#define CRYPT_SECTOR_SIZE 512U
52#define CRYPT_MAX_SECTOR_SIZE 4096U
b3b4ebab 53
b6c0bd11
AAF
54typedef enum PassphraseType {
55 PASSPHRASE_NONE,
56 PASSPHRASE_REGULAR = 1 << 0,
57 PASSPHRASE_RECOVERY_KEY = 1 << 1,
58 PASSPHRASE_BOTH = PASSPHRASE_REGULAR|PASSPHRASE_RECOVERY_KEY,
59 _PASSPHRASE_TYPE_MAX,
60 _PASSPHRASE_TYPE_INVALID = -1,
61} PassphraseType;
62
6cc27c29 63static const char *arg_type = NULL; /* ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT, CRYPT_BITLK or CRYPT_PLAIN */
f75cac37
LP
64static char *arg_cipher = NULL;
65static unsigned arg_key_size = 0;
a9fc6406 66static unsigned arg_sector_size = CRYPT_SECTOR_SIZE;
f75cac37
LP
67static int arg_key_slot = CRYPT_ANY_SLOT;
68static unsigned arg_keyfile_size = 0;
dc0a3555 69static uint64_t arg_keyfile_offset = 0;
d3d49e76 70static bool arg_keyfile_erase = false;
0ba6f85e 71static bool arg_try_empty_password = false;
f75cac37 72static char *arg_hash = NULL;
7376e835 73static char *arg_header = NULL;
f75cac37
LP
74static unsigned arg_tries = 3;
75static bool arg_readonly = false;
76static bool arg_verify = false;
2cbca51a 77static AskPasswordFlags arg_ask_password_flags = 0;
f75cac37 78static bool arg_discards = false;
2c65512e
YW
79static bool arg_same_cpu_crypt = false;
80static bool arg_submit_from_crypt_cpus = false;
227acf00
JU
81static bool arg_no_read_workqueue = false;
82static bool arg_no_write_workqueue = false;
f75cac37
LP
83static bool arg_tcrypt_hidden = false;
84static bool arg_tcrypt_system = false;
52028838 85static bool arg_tcrypt_veracrypt = false;
70390240 86static uint32_t arg_tcrypt_veracrypt_pim = 0;
f75cac37 87static char **arg_tcrypt_keyfiles = NULL;
4eac2773
MP
88static uint64_t arg_offset = 0;
89static uint64_t arg_skip = 0;
0864d311 90static usec_t arg_timeout = USEC_INFINITY;
08669709 91static char *arg_pkcs11_uri = NULL;
b997d111 92static bool arg_pkcs11_uri_auto = false;
2bc5c425
LP
93static char *arg_fido2_device = NULL;
94static bool arg_fido2_device_auto = false;
95static void *arg_fido2_cid = NULL;
96static size_t arg_fido2_cid_size = 0;
97static char *arg_fido2_rp_id = NULL;
d09df6b9 98static char *arg_tpm2_device = NULL; /* These and the following fields are about locking an encrypted volume to the local TPM */
18843ecc
LP
99static bool arg_tpm2_device_auto = false;
100static uint32_t arg_tpm2_pcr_mask = UINT32_MAX;
dc63b2c9 101static char *arg_tpm2_signature = NULL;
4005d41e 102static bool arg_tpm2_pin = false;
404aea78 103static char *arg_tpm2_pcrlock = NULL;
cd5f57bd 104static bool arg_headless = false;
5cbe70af 105static usec_t arg_token_timeout_usec = 30*USEC_PER_SEC;
94c0c85e
LP
106static unsigned arg_tpm2_measure_pcr = UINT_MAX; /* This and the following field is about measuring the unlocked volume key to the local TPM */
107static char **arg_tpm2_measure_banks = NULL;
7f4e0805 108
3a40f366
YW
109STATIC_DESTRUCTOR_REGISTER(arg_cipher, freep);
110STATIC_DESTRUCTOR_REGISTER(arg_hash, freep);
111STATIC_DESTRUCTOR_REGISTER(arg_header, freep);
112STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles, strv_freep);
08669709 113STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri, freep);
2bc5c425
LP
114STATIC_DESTRUCTOR_REGISTER(arg_fido2_device, freep);
115STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid, freep);
116STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id, freep);
18843ecc 117STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
dc63b2c9 118STATIC_DESTRUCTOR_REGISTER(arg_tpm2_signature, freep);
94c0c85e 119STATIC_DESTRUCTOR_REGISTER(arg_tpm2_measure_banks, strv_freep);
404aea78 120STATIC_DESTRUCTOR_REGISTER(arg_tpm2_pcrlock, freep);
3a40f366 121
b6c0bd11
AAF
122static const char* const passphrase_type_table[_PASSPHRASE_TYPE_MAX] = {
123 [PASSPHRASE_REGULAR] = "passphrase",
124 [PASSPHRASE_RECOVERY_KEY] = "recovery key",
125 [PASSPHRASE_BOTH] = "passphrase or recovery key",
126};
127
128const char* passphrase_type_to_string(PassphraseType t);
129PassphraseType passphrase_type_from_string(const char *s);
130
131DEFINE_STRING_TABLE_LOOKUP(passphrase_type, PassphraseType);
132
1fc76335 133/* Options Debian's crypttab knows we don't:
1fc76335
LP
134 check=
135 checkargs=
8ced40c0
LP
136 noearly
137 loud
138 quiet
1fc76335 139 keyscript=
8ced40c0 140 initramfs
1fc76335
LP
141*/
142
7f4e0805 143static int parse_one_option(const char *option) {
fb4650aa
ZJS
144 const char *val;
145 int r;
146
7f4e0805
LP
147 assert(option);
148
149 /* Handled outside of this tool */
50d2eba2 150 if (STR_IN_SET(option, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
151 return 0;
152
153 if (startswith(option, "keyfile-timeout="))
7f4e0805
LP
154 return 0;
155
fb4650aa
ZJS
156 if ((val = startswith(option, "cipher="))) {
157 r = free_and_strdup(&arg_cipher, val);
158 if (r < 0)
4b93637f 159 return log_oom();
7f4e0805 160
fb4650aa 161 } else if ((val = startswith(option, "size="))) {
7f4e0805 162
fb4650aa
ZJS
163 r = safe_atou(val, &arg_key_size);
164 if (r < 0) {
b96cc40a 165 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
7f4e0805
LP
166 return 0;
167 }
168
6131a78b 169 if (arg_key_size % 8) {
b96cc40a 170 log_warning("size= not a multiple of 8, ignoring.");
6131a78b
DH
171 return 0;
172 }
173
174 arg_key_size /= 8;
175
a9fc6406
DJL
176 } else if ((val = startswith(option, "sector-size="))) {
177
a9fc6406
DJL
178 r = safe_atou(val, &arg_sector_size);
179 if (r < 0) {
b96cc40a 180 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
a9fc6406
DJL
181 return 0;
182 }
183
184 if (arg_sector_size % 2) {
b96cc40a 185 log_warning("sector-size= not a multiple of 2, ignoring.");
a9fc6406
DJL
186 return 0;
187 }
188
b96cc40a
LP
189 if (arg_sector_size < CRYPT_SECTOR_SIZE || arg_sector_size > CRYPT_MAX_SECTOR_SIZE)
190 log_warning("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE, CRYPT_MAX_SECTOR_SIZE);
a9fc6406 191
8ced40c0
LP
192 } else if ((val = startswith(option, "key-slot=")) ||
193 (val = startswith(option, "keyslot="))) {
b4a11878 194
b3b4ebab 195 arg_type = ANY_LUKS;
fb4650aa 196 r = safe_atoi(val, &arg_key_slot);
b96cc40a
LP
197 if (r < 0)
198 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
b4a11878 199
fb4650aa 200 } else if ((val = startswith(option, "tcrypt-keyfile="))) {
8cf3ca80 201
f75cac37 202 arg_type = CRYPT_TCRYPT;
fb4650aa
ZJS
203 if (path_is_absolute(val)) {
204 if (strv_extend(&arg_tcrypt_keyfiles, val) < 0)
4b93637f
LP
205 return log_oom();
206 } else
b96cc40a 207 log_warning("Key file path \"%s\" is not absolute, ignoring.", val);
8cf3ca80 208
fb4650aa 209 } else if ((val = startswith(option, "keyfile-size="))) {
4271d823 210
fb4650aa 211 r = safe_atou(val, &arg_keyfile_size);
b96cc40a
LP
212 if (r < 0)
213 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
4271d823 214
fb4650aa 215 } else if ((val = startswith(option, "keyfile-offset="))) {
880a599e 216
d90874b4 217 r = safe_atou64(val, &arg_keyfile_offset);
b96cc40a
LP
218 if (r < 0)
219 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
880a599e 220
d3d49e76
LP
221 } else if ((val = startswith(option, "keyfile-erase="))) {
222
223 r = parse_boolean(val);
224 if (r < 0) {
b96cc40a 225 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
d3d49e76
LP
226 return 0;
227 }
228
229 arg_keyfile_erase = r;
230
231 } else if (streq(option, "keyfile-erase"))
232 arg_keyfile_erase = true;
233
234 else if ((val = startswith(option, "hash="))) {
fb4650aa
ZJS
235 r = free_and_strdup(&arg_hash, val);
236 if (r < 0)
4b93637f 237 return log_oom();
7f4e0805 238
fb4650aa 239 } else if ((val = startswith(option, "header="))) {
cdece7e3 240 if (!arg_type || !STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT))
70390240 241 arg_type = ANY_LUKS;
7376e835 242
baaa35ad
ZJS
243 if (!path_is_absolute(val))
244 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
245 "Header path \"%s\" is not absolute, refusing.", val);
7376e835 246
baaa35ad
ZJS
247 if (arg_header)
248 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
249 "Duplicate header= option, refusing.");
7376e835 250
fb4650aa 251 arg_header = strdup(val);
7376e835
AC
252 if (!arg_header)
253 return log_oom();
254
fb4650aa 255 } else if ((val = startswith(option, "tries="))) {
7f4e0805 256
fb4650aa 257 r = safe_atou(val, &arg_tries);
b96cc40a
LP
258 if (r < 0)
259 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
7f4e0805 260
f75cac37
LP
261 } else if (STR_IN_SET(option, "readonly", "read-only"))
262 arg_readonly = true;
7f4e0805 263 else if (streq(option, "verify"))
f75cac37 264 arg_verify = true;
2cbca51a
SB
265 else if ((val = startswith(option, "password-echo="))) {
266 if (streq(val, "masked"))
267 arg_ask_password_flags &= ~(ASK_PASSWORD_ECHO|ASK_PASSWORD_SILENT);
268 else {
269 r = parse_boolean(val);
270 if (r < 0) {
271 log_warning_errno(r, "Invalid password-echo= option \"%s\", ignoring.", val);
272 return 0;
273 }
274
275 SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_ECHO, r);
276 SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_SILENT, !r);
277 }
278 } else if (STR_IN_SET(option, "allow-discards", "discard"))
f75cac37 279 arg_discards = true;
2c65512e
YW
280 else if (streq(option, "same-cpu-crypt"))
281 arg_same_cpu_crypt = true;
282 else if (streq(option, "submit-from-crypt-cpus"))
283 arg_submit_from_crypt_cpus = true;
227acf00
JU
284 else if (streq(option, "no-read-workqueue"))
285 arg_no_read_workqueue = true;
286 else if (streq(option, "no-write-workqueue"))
287 arg_no_write_workqueue = true;
260ab287 288 else if (streq(option, "luks"))
b3b4ebab 289 arg_type = ANY_LUKS;
6cc27c29
MF
290/* since cryptsetup 2.3.0 (Feb 2020) */
291#ifdef CRYPT_BITLK
292 else if (streq(option, "bitlk"))
293 arg_type = CRYPT_BITLK;
294#endif
8cf3ca80 295 else if (streq(option, "tcrypt"))
f75cac37 296 arg_type = CRYPT_TCRYPT;
8ced40c0 297 else if (STR_IN_SET(option, "tcrypt-hidden", "tcrypthidden")) {
f75cac37
LP
298 arg_type = CRYPT_TCRYPT;
299 arg_tcrypt_hidden = true;
8cf3ca80 300 } else if (streq(option, "tcrypt-system")) {
f75cac37
LP
301 arg_type = CRYPT_TCRYPT;
302 arg_tcrypt_system = true;
8ced40c0 303 } else if (STR_IN_SET(option, "tcrypt-veracrypt", "veracrypt")) {
52028838
GH
304 arg_type = CRYPT_TCRYPT;
305 arg_tcrypt_veracrypt = true;
70390240
KZ
306 } else if ((val = startswith(option, "veracrypt-pim="))) {
307
308 r = safe_atou32(val, &arg_tcrypt_veracrypt_pim);
309 if (r < 0) {
310 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
311 return 0;
312 }
53ac130b
LP
313 } else if (STR_IN_SET(option, "plain", "swap", "tmp") ||
314 startswith(option, "tmp="))
f75cac37 315 arg_type = CRYPT_PLAIN;
fb4650aa 316 else if ((val = startswith(option, "timeout="))) {
7f4e0805 317
0004f698 318 r = parse_sec_fix_0(val, &arg_timeout);
b96cc40a
LP
319 if (r < 0)
320 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
7f4e0805 321
fb4650aa 322 } else if ((val = startswith(option, "offset="))) {
4eac2773 323
fb4650aa
ZJS
324 r = safe_atou64(val, &arg_offset);
325 if (r < 0)
326 return log_error_errno(r, "Failed to parse %s: %m", option);
4eac2773 327
fb4650aa 328 } else if ((val = startswith(option, "skip="))) {
4eac2773 329
fb4650aa
ZJS
330 r = safe_atou64(val, &arg_skip);
331 if (r < 0)
332 return log_error_errno(r, "Failed to parse %s: %m", option);
4eac2773 333
08669709
LP
334 } else if ((val = startswith(option, "pkcs11-uri="))) {
335
b997d111
LP
336 if (streq(val, "auto")) {
337 arg_pkcs11_uri = mfree(arg_pkcs11_uri);
338 arg_pkcs11_uri_auto = true;
339 } else {
340 if (!pkcs11_uri_valid(val))
341 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing");
08669709 342
b997d111
LP
343 r = free_and_strdup(&arg_pkcs11_uri, val);
344 if (r < 0)
345 return log_oom();
346
347 arg_pkcs11_uri_auto = false;
348 }
08669709 349
2bc5c425
LP
350 } else if ((val = startswith(option, "fido2-device="))) {
351
352 if (streq(val, "auto")) {
353 arg_fido2_device = mfree(arg_fido2_device);
354 arg_fido2_device_auto = true;
355 } else {
356 r = free_and_strdup(&arg_fido2_device, val);
357 if (r < 0)
358 return log_oom();
359
360 arg_fido2_device_auto = false;
361 }
362
363 } else if ((val = startswith(option, "fido2-cid="))) {
364
365 if (streq(val, "auto"))
366 arg_fido2_cid = mfree(arg_fido2_cid);
367 else {
368 _cleanup_free_ void *cid = NULL;
369 size_t cid_size;
370
f5fbe71d 371 r = unbase64mem(val, SIZE_MAX, &cid, &cid_size);
2bc5c425
LP
372 if (r < 0)
373 return log_error_errno(r, "Failed to decode FIDO2 CID data: %m");
374
375 free(arg_fido2_cid);
376 arg_fido2_cid = TAKE_PTR(cid);
377 arg_fido2_cid_size = cid_size;
378 }
379
380 /* Turn on FIDO2 as side-effect, if not turned on yet. */
381 if (!arg_fido2_device && !arg_fido2_device_auto)
382 arg_fido2_device_auto = true;
383
384 } else if ((val = startswith(option, "fido2-rp="))) {
385
386 r = free_and_strdup(&arg_fido2_rp_id, val);
387 if (r < 0)
388 return log_oom();
389
18843ecc
LP
390 } else if ((val = startswith(option, "tpm2-device="))) {
391
392 if (streq(val, "auto")) {
393 arg_tpm2_device = mfree(arg_tpm2_device);
394 arg_tpm2_device_auto = true;
395 } else {
396 r = free_and_strdup(&arg_tpm2_device, val);
397 if (r < 0)
398 return log_oom();
399
400 arg_tpm2_device_auto = false;
401 }
402
403 } else if ((val = startswith(option, "tpm2-pcrs="))) {
404
07c04061 405 r = tpm2_parse_pcr_argument_to_mask(val, &arg_tpm2_pcr_mask);
222a951f
LP
406 if (r < 0)
407 return r;
18843ecc 408
dc63b2c9
LP
409 } else if ((val = startswith(option, "tpm2-signature="))) {
410
411 if (!path_is_absolute(val))
412 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
413 "TPM2 signature path \"%s\" is not absolute, refusing.", val);
414
415 r = free_and_strdup(&arg_tpm2_signature, val);
416 if (r < 0)
417 return log_oom();
418
4005d41e
GG
419 } else if ((val = startswith(option, "tpm2-pin="))) {
420
421 r = parse_boolean(val);
422 if (r < 0) {
b96cc40a 423 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
4005d41e
GG
424 return 0;
425 }
426
427 arg_tpm2_pin = r;
428
404aea78
LP
429 } else if ((val = startswith(option, "tpm2-pcrlock="))) {
430
431 if (!path_is_absolute(val))
432 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
433 "TPM2 pcrlock policy path \"%s\" is not absolute, refusing.", val);
434
435 r = free_and_strdup(&arg_tpm2_pcrlock, val);
436 if (r < 0)
437 return log_oom();
438
94c0c85e
LP
439 } else if ((val = startswith(option, "tpm2-measure-pcr="))) {
440 unsigned pcr;
441
442 r = safe_atou(val, &pcr);
443 if (r < 0) {
444 r = parse_boolean(val);
445 if (r < 0) {
446 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
447 return 0;
448 }
449
2099cd62 450 pcr = r ? TPM2_PCR_SYSTEM_IDENTITY : UINT_MAX;
323eb480 451 } else if (!TPM2_PCR_INDEX_VALID(pcr)) {
b96cc40a 452 log_warning("Selected TPM index for measurement %u outside of allowed range 0…%u, ignoring.", pcr, TPM2_PCRS_MAX-1);
94c0c85e
LP
453 return 0;
454 }
455
456 arg_tpm2_measure_pcr = pcr;
457
458 } else if ((val = startswith(option, "tpm2-measure-bank="))) {
459
460#if HAVE_OPENSSL
461 _cleanup_strv_free_ char **l = NULL;
462
463 l = strv_split(optarg, ":");
464 if (!l)
465 return log_oom();
466
467 STRV_FOREACH(i, l) {
468 const EVP_MD *implementation;
469
470 implementation = EVP_get_digestbyname(*i);
471 if (!implementation)
472 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown bank '%s', refusing.", val);
473
474 if (strv_extend(&arg_tpm2_measure_banks, EVP_MD_name(implementation)) < 0)
475 return log_oom();
476 }
477#else
478 log_error("Build lacks OpenSSL support, cannot measure to PCR banks, ignoring: %s", option);
479#endif
480
0ba6f85e
LP
481 } else if ((val = startswith(option, "try-empty-password="))) {
482
483 r = parse_boolean(val);
484 if (r < 0) {
b96cc40a 485 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
0ba6f85e
LP
486 return 0;
487 }
488
489 arg_try_empty_password = r;
490
491 } else if (streq(option, "try-empty-password"))
492 arg_try_empty_password = true;
cd5f57bd
LB
493 else if ((val = startswith(option, "headless="))) {
494
495 r = parse_boolean(val);
496 if (r < 0) {
b96cc40a 497 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
cd5f57bd
LB
498 return 0;
499 }
500
501 arg_headless = r;
502 } else if (streq(option, "headless"))
503 arg_headless = true;
0ba6f85e 504
5cbe70af
LP
505 else if ((val = startswith(option, "token-timeout="))) {
506
507 r = parse_sec_fix_0(val, &arg_token_timeout_usec);
b96cc40a
LP
508 if (r < 0)
509 log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
5cbe70af
LP
510
511 } else if (!streq(option, "x-initrd.attach"))
fb4650aa 512 log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
7f4e0805
LP
513
514 return 0;
515}
516
166015fa 517static int parse_crypt_config(const char *options) {
7f4e0805
LP
518 assert(options);
519
dd2fff3a
ZJS
520 for (;;) {
521 _cleanup_free_ char *word = NULL;
522 int r;
523
7bb553bb 524 r = extract_first_word(&options, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS | EXTRACT_UNESCAPE_SEPARATORS);
dd2fff3a 525 if (r < 0)
be36bc1e 526 return log_error_errno(r, "Failed to parse options: %m");
dd2fff3a
ZJS
527 if (r == 0)
528 break;
7f4e0805 529
dd2fff3a 530 r = parse_one_option(word);
7f4e0805
LP
531 if (r < 0)
532 return r;
533 }
534
4eac2773 535 /* sanity-check options */
9c5253ff
LP
536 if (arg_type && !streq(arg_type, CRYPT_PLAIN)) {
537 if (arg_offset != 0)
4eac2773 538 log_warning("offset= ignored with type %s", arg_type);
9c5253ff 539 if (arg_skip != 0)
4eac2773
MP
540 log_warning("skip= ignored with type %s", arg_type);
541 }
542
7f4e0805
LP
543 return 0;
544}
545
1ca208fb 546static char* disk_description(const char *path) {
f75cac37 547 static const char name_fields[] =
74b1c371
LP
548 "DM_NAME\0"
549 "ID_MODEL_FROM_DATABASE\0"
f75cac37 550 "ID_MODEL\0";
74b1c371 551
4afd3348 552 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
12e2b70f 553 const char *name;
b1a2da0a 554 struct stat st;
b1a2da0a
LP
555
556 assert(path);
557
558 if (stat(path, &st) < 0)
559 return NULL;
560
561 if (!S_ISBLK(st.st_mode))
562 return NULL;
563
930aa88f 564 if (sd_device_new_from_stat_rdev(&device, &st) < 0)
1ca208fb 565 return NULL;
b1a2da0a 566
fadd34dd
LP
567 if (sd_device_get_property_value(device, "ID_PART_ENTRY_NAME", &name) >= 0) {
568 _cleanup_free_ char *unescaped = NULL;
e437538f 569 ssize_t l;
fadd34dd
LP
570
571 /* ID_PART_ENTRY_NAME uses \x style escaping, using libblkid's blkid_encode_string(). Let's
572 * reverse this here to make the string more human friendly in case people embed spaces or
573 * other weird stuff. */
574
e437538f
ZJS
575 l = cunescape(name, UNESCAPE_RELAX, &unescaped);
576 if (l < 0) {
577 log_debug_errno(l, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
fadd34dd
LP
578 return NULL;
579 }
580
581 if (!isempty(unescaped) && !string_has_cc(unescaped, NULL))
582 return TAKE_PTR(unescaped);
583 }
584
585 /* These need no unescaping. */
2c740afd
YW
586 NULSTR_FOREACH(i, name_fields)
587 if (sd_device_get_property_value(device, i, &name) >= 0 &&
588 !isempty(name))
1ca208fb 589 return strdup(name);
b1a2da0a 590
1ca208fb 591 return NULL;
b1a2da0a
LP
592}
593
b61e476f 594static char *disk_mount_point(const char *label) {
e7d90b71 595 _cleanup_free_ char *device = NULL;
5862d652 596 _cleanup_endmntent_ FILE *f = NULL;
b61e476f
LP
597 struct mntent *m;
598
599 /* Yeah, we don't support native systemd unit files here for now */
600
090685b5
LP
601 device = strjoin("/dev/mapper/", label);
602 if (!device)
5862d652 603 return NULL;
b61e476f 604
ed4ad488 605 f = setmntent(fstab_path(), "re");
e0295d26 606 if (!f)
5862d652 607 return NULL;
b61e476f
LP
608
609 while ((m = getmntent(f)))
5862d652
ZJS
610 if (path_equal(m->mnt_fsname, device))
611 return strdup(m->mnt_dir);
b61e476f 612
5862d652 613 return NULL;
b61e476f
LP
614}
615
08669709
LP
616static char *friendly_disk_name(const char *src, const char *vol) {
617 _cleanup_free_ char *description = NULL, *mount_point = NULL;
618 char *name_buffer = NULL;
619 int r;
e7d90b71 620
e51b9486 621 assert(src);
08669709 622 assert(vol);
e7d90b71 623
e51b9486
HH
624 description = disk_description(src);
625 mount_point = disk_mount_point(vol);
626
08669709 627 /* If the description string is simply the volume name, then let's not show this twice */
ece174c5 628 if (description && streq(vol, description))
97b11eed 629 description = mfree(description);
e51b9486
HH
630
631 if (mount_point && description)
632 r = asprintf(&name_buffer, "%s (%s) on %s", description, vol, mount_point);
633 else if (mount_point)
634 r = asprintf(&name_buffer, "%s on %s", vol, mount_point);
635 else if (description)
636 r = asprintf(&name_buffer, "%s (%s)", description, vol);
08669709
LP
637 else
638 return strdup(vol);
e51b9486 639 if (r < 0)
08669709
LP
640 return NULL;
641
642 return name_buffer;
643}
644
b6c0bd11
AAF
645static PassphraseType check_registered_passwords(struct crypt_device *cd) {
646 _cleanup_free_ bool *slots = NULL;
647 int slot_max;
648 PassphraseType passphrase_type = PASSPHRASE_NONE;
649
650 assert(cd);
651
652 if (!streq_ptr(crypt_get_type(cd), CRYPT_LUKS2)) {
653 log_debug("%s: not a LUKS2 device, only passphrases are supported", crypt_get_device_name(cd));
654 return PASSPHRASE_REGULAR;
655 }
656
657 /* Search all used slots */
658 assert_se((slot_max = crypt_keyslot_max(CRYPT_LUKS2)) > 0);
659 slots = new(bool, slot_max);
660 if (!slots)
661 return log_oom();
662
663 for (int slot = 0; slot < slot_max; slot++)
664 slots[slot] = IN_SET(crypt_keyslot_status(cd, slot), CRYPT_SLOT_ACTIVE, CRYPT_SLOT_ACTIVE_LAST);
665
666 /* Iterate all LUKS2 tokens and keep track of all their slots */
667 for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
668 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
669 const char *type;
670 JsonVariant *w, *z;
671 int tk;
672
673 tk = cryptsetup_get_token_as_json(cd, token, NULL, &v);
674 if (IN_SET(tk, -ENOENT, -EINVAL))
675 continue;
676 if (tk < 0) {
677 log_warning_errno(tk, "Failed to read JSON token data, ignoring: %m");
678 continue;
679 }
680
681 w = json_variant_by_key(v, "type");
682 if (!w || !json_variant_is_string(w)) {
683 log_warning("Token JSON data lacks type field, ignoring.");
684 continue;
685 }
686
687 type = json_variant_string(w);
688 if (STR_IN_SET(type, "systemd-recovery", "systemd-pkcs11", "systemd-fido2", "systemd-tpm2")) {
689
690 /* At least exists one recovery key */
691 if (streq(type, "systemd-recovery"))
692 passphrase_type |= PASSPHRASE_RECOVERY_KEY;
693
694 w = json_variant_by_key(v, "keyslots");
695 if (!w || !json_variant_is_array(w)) {
696 log_warning("Token JSON data lacks keyslots field, ignoring.");
697 continue;
698 }
699
700 JSON_VARIANT_ARRAY_FOREACH(z, w) {
701 unsigned u;
702 int at;
703
704 if (!json_variant_is_string(z)) {
705 log_warning("Token JSON data's keyslot field is not an array of strings, ignoring.");
706 continue;
707 }
708
709 at = safe_atou(json_variant_string(z), &u);
710 if (at < 0) {
711 log_warning_errno(at, "Token JSON data's keyslot field is not an integer formatted as string, ignoring.");
712 continue;
713 }
714
715 if (u >= (unsigned) slot_max) {
716 log_warning_errno(at, "Token JSON data's keyslot field exceeds the maximum value allowed, ignoring.");
717 continue;
718 }
719
720 slots[u] = false;
721 }
722 }
723 }
724
725 /* Check if any of the slots is not referenced by systemd tokens */
726 for (int slot = 0; slot < slot_max; slot++)
727 if (slots[slot]) {
728 passphrase_type |= PASSPHRASE_REGULAR;
729 break;
730 }
731
732 /* All the slots are referenced by systemd tokens, so if a recovery key is not enrolled,
733 * we will not be able to enter a passphrase. */
734 return passphrase_type;
735}
736
08669709
LP
737static int get_password(
738 const char *vol,
739 const char *src,
740 usec_t until,
741 bool accept_cached,
b6c0bd11 742 PassphraseType passphrase_type,
08669709
LP
743 char ***ret) {
744
745 _cleanup_free_ char *friendly = NULL, *text = NULL, *disk_path = NULL;
746 _cleanup_strv_free_erase_ char **passwords = NULL;
de010b0b 747 char *id;
08669709 748 int r = 0;
2cbca51a 749 AskPasswordFlags flags = arg_ask_password_flags | ASK_PASSWORD_PUSH_CACHE;
08669709
LP
750
751 assert(vol);
752 assert(src);
753 assert(ret);
754
cd5f57bd
LB
755 if (arg_headless)
756 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Password querying disabled via 'headless' option.");
757
08669709
LP
758 friendly = friendly_disk_name(src, vol);
759 if (!friendly)
e51b9486
HH
760 return log_oom();
761
b6c0bd11 762 if (asprintf(&text, "Please enter %s for disk %s:", passphrase_type_to_string(passphrase_type), friendly) < 0)
08669709 763 return log_oom();
e51b9486 764
08669709
LP
765 disk_path = cescape(src);
766 if (!disk_path)
e7d90b71
JJ
767 return log_oom();
768
ea7e7c1e 769 id = strjoina("cryptsetup:", disk_path);
9fa1de96 770
8806bb4b 771 r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", "cryptsetup.passphrase", until,
1fa94a31 772 flags | (accept_cached*ASK_PASSWORD_ACCEPT_CACHED),
ab84f5b9 773 &passwords);
23bbb0de
MS
774 if (r < 0)
775 return log_error_errno(r, "Failed to query password: %m");
e7d90b71 776
f75cac37 777 if (arg_verify) {
ab84f5b9
ZJS
778 _cleanup_strv_free_erase_ char **passwords2 = NULL;
779
1602b008 780 assert(strv_length(passwords) == 1);
e7d90b71 781
b6c0bd11 782 if (asprintf(&text, "Please enter %s for disk %s (verification):", passphrase_type_to_string(passphrase_type), friendly) < 0)
ab84f5b9 783 return log_oom();
e7d90b71 784
ea7e7c1e 785 id = strjoina("cryptsetup-verification:", disk_path);
9fa1de96 786
1fa94a31 787 r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", "cryptsetup.passphrase", until, flags, &passwords2);
ab84f5b9
ZJS
788 if (r < 0)
789 return log_error_errno(r, "Failed to query verification password: %m");
e7d90b71
JJ
790
791 assert(strv_length(passwords2) == 1);
792
8bc6ade7
LP
793 if (!streq(passwords[0], passwords2[0]))
794 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN),
795 "Passwords did not match, retrying.");
e7d90b71
JJ
796 }
797
1602b008 798 strv_uniq(passwords);
e7d90b71 799
1602b008 800 STRV_FOREACH(p, passwords) {
e7d90b71
JJ
801 char *c;
802
f75cac37 803 if (strlen(*p)+1 >= arg_key_size)
e7d90b71
JJ
804 continue;
805
806 /* Pad password if necessary */
1602b008 807 c = new(char, arg_key_size);
ab84f5b9
ZJS
808 if (!c)
809 return log_oom();
e7d90b71 810
f75cac37 811 strncpy(c, *p, arg_key_size);
d3ad474f
LP
812 erase_and_free(*p);
813 *p = TAKE_PTR(c);
e7d90b71
JJ
814 }
815
ae2a15bc 816 *ret = TAKE_PTR(passwords);
1602b008 817
ab84f5b9 818 return 0;
e7d90b71
JJ
819}
820
94c0c85e
LP
821static int measure_volume_key(
822 struct crypt_device *cd,
823 const char *name,
824 const void *volume_key,
825 size_t volume_key_size) {
826
827 int r;
828
829 assert(cd);
830 assert(name);
831 assert(volume_key);
832 assert(volume_key_size > 0);
833
834 if (arg_tpm2_measure_pcr == UINT_MAX) {
835 log_debug("Not measuring volume key, deactivated.");
836 return 0;
837 }
838
be8f478c 839 r = efi_measured_uki(LOG_WARNING);
6c51b49c 840 if (r < 0)
2f6c52b9 841 return r;
6c51b49c
LP
842 if (r == 0) {
843 log_debug("Kernel stub did not measure kernel image into the expected PCR, skipping userspace measurement, too.");
844 return 0;
845 }
846
94c0c85e 847#if HAVE_TPM2
1dc8f518 848 _cleanup_(tpm2_context_unrefp) Tpm2Context *c = NULL;
68d084ce 849 r = tpm2_context_new(arg_tpm2_device, &c);
94c0c85e 850 if (r < 0)
f9a0ee75 851 return log_error_errno(r, "Failed to create TPM2 context: %m");
94c0c85e
LP
852
853 _cleanup_strv_free_ char **l = NULL;
854 if (strv_isempty(arg_tpm2_measure_banks)) {
23e9ccc2 855 r = tpm2_get_good_pcr_banks_strv(c, UINT32_C(1) << arg_tpm2_measure_pcr, &l);
94c0c85e 856 if (r < 0)
f9a0ee75 857 return log_error_errno(r, "Could not verify pcr banks: %m");
94c0c85e
LP
858 }
859
860 _cleanup_free_ char *joined = strv_join(l ?: arg_tpm2_measure_banks, ", ");
861 if (!joined)
862 return log_oom();
863
864 /* Note: we don't directly measure the volume key, it might be a security problem to send an
865 * unprotected direct hash of the secret volume key over the wire to the TPM. Hence let's instead
866 * send a HMAC signature instead. */
867
868 _cleanup_free_ char *escaped = NULL;
869 escaped = xescape(name, ":"); /* avoid ambiguity around ":" once we join things below */
870 if (!escaped)
871 return log_oom();
872
873 _cleanup_free_ char *s = NULL;
874 s = strjoin("cryptsetup:", escaped, ":", strempty(crypt_get_uuid(cd)));
875 if (!s)
876 return log_oom();
877
cb19bdae 878 r = tpm2_extend_bytes(c, l ?: arg_tpm2_measure_banks, arg_tpm2_measure_pcr, s, SIZE_MAX, volume_key, volume_key_size, TPM2_EVENT_VOLUME_KEY, s);
94c0c85e 879 if (r < 0)
f9a0ee75 880 return log_error_errno(r, "Could not extend PCR: %m");
94c0c85e
LP
881
882 log_struct(LOG_INFO,
883 "MESSAGE_ID=" SD_MESSAGE_TPM_PCR_EXTEND_STR,
884 LOG_MESSAGE("Successfully extended PCR index %u with '%s' and volume key (banks %s).", arg_tpm2_measure_pcr, s, joined),
885 "MEASURING=%s", s,
886 "PCR=%u", arg_tpm2_measure_pcr,
887 "BANKS=%s", joined);
888
889 return 0;
890#else
891 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support disabled, not measuring.");
892#endif
893}
894
895static int measured_crypt_activate_by_volume_key(
896 struct crypt_device *cd,
897 const char *name,
898 const void *volume_key,
899 size_t volume_key_size,
900 uint32_t flags) {
901
902 int r;
903
904 assert(cd);
905 assert(name);
906
907 /* A wrapper around crypt_activate_by_volume_key() which also measures to a PCR if that's requested. */
908
909 r = crypt_activate_by_volume_key(cd, name, volume_key, volume_key_size, flags);
910 if (r < 0)
911 return r;
912
913 if (volume_key_size == 0) {
914 log_debug("Not measuring volume key, none specified.");
915 return r;
916 }
917
918 (void) measure_volume_key(cd, name, volume_key, volume_key_size); /* OK if fails */
919 return r;
920}
921
922static int measured_crypt_activate_by_passphrase(
923 struct crypt_device *cd,
924 const char *name,
925 int keyslot,
926 const char *passphrase,
927 size_t passphrase_size,
928 uint32_t flags) {
929
930 _cleanup_(erase_and_freep) void *vk = NULL;
931 size_t vks;
932 int r;
933
934 assert(cd);
935
936 /* A wrapper around crypt_activate_by_passphrase() which also measures to a PCR if that's
937 * requested. Note that we need the volume key for the measurement, and
938 * crypt_activate_by_passphrase() doesn't give us access to this. Hence, we operate indirectly, and
939 * retrieve the volume key first, and then activate through that. */
940
941 if (arg_tpm2_measure_pcr == UINT_MAX) {
942 log_debug("Not measuring volume key, deactivated.");
943 goto shortcut;
944 }
945
946 r = crypt_get_volume_key_size(cd);
947 if (r < 0)
948 return r;
949 if (r == 0) {
950 log_debug("Not measuring volume key, none defined.");
951 goto shortcut;
952 }
953
954 vk = malloc(vks = r);
955 if (!vk)
956 return -ENOMEM;
957
958 r = crypt_volume_key_get(cd, keyslot, vk, &vks, passphrase, passphrase_size);
959 if (r < 0)
960 return r;
961
962 return measured_crypt_activate_by_volume_key(cd, name, vk, vks, flags);
963
964shortcut:
965 return crypt_activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags);
966}
967
1602b008
LP
968static int attach_tcrypt(
969 struct crypt_device *cd,
970 const char *name,
971 const char *key_file,
7407f689
LP
972 const void *key_data,
973 size_t key_data_size,
1602b008
LP
974 char **passwords,
975 uint32_t flags) {
976
8cf3ca80 977 int r = 0;
d3ad474f 978 _cleanup_(erase_and_freep) char *passphrase = NULL;
8cf3ca80
JJ
979 struct crypt_params_tcrypt params = {
980 .flags = CRYPT_TCRYPT_LEGACY_MODES,
f75cac37
LP
981 .keyfiles = (const char **)arg_tcrypt_keyfiles,
982 .keyfiles_count = strv_length(arg_tcrypt_keyfiles)
8cf3ca80
JJ
983 };
984
985 assert(cd);
986 assert(name);
7407f689 987 assert(key_file || key_data || !strv_isempty(passwords));
8cf3ca80 988
18843ecc 989 if (arg_pkcs11_uri || arg_pkcs11_uri_auto || arg_fido2_device || arg_fido2_device_auto || arg_tpm2_device || arg_tpm2_device_auto)
e514aa1e
FS
990 /* Ask for a regular password */
991 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN),
18843ecc 992 "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
08669709 993
f75cac37 994 if (arg_tcrypt_hidden)
8cf3ca80
JJ
995 params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
996
f75cac37 997 if (arg_tcrypt_system)
8cf3ca80
JJ
998 params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
999
52028838
GH
1000 if (arg_tcrypt_veracrypt)
1001 params.flags |= CRYPT_TCRYPT_VERA_MODES;
6747d9a1 1002
70390240
KZ
1003 if (arg_tcrypt_veracrypt && arg_tcrypt_veracrypt_pim != 0)
1004 params.veracrypt_pim = arg_tcrypt_veracrypt_pim;
52028838 1005
7407f689
LP
1006 if (key_data) {
1007 params.passphrase = key_data;
1008 params.passphrase_size = key_data_size;
1009 } else {
1010 if (key_file) {
1011 r = read_one_line_file(key_file, &passphrase);
1012 if (r < 0) {
1013 log_error_errno(r, "Failed to read password file '%s': %m", key_file);
1014 return -EAGAIN; /* log with the actual error, but return EAGAIN */
1015 }
8cf3ca80 1016
7407f689
LP
1017 params.passphrase = passphrase;
1018 } else
1019 params.passphrase = passwords[0];
1020
1021 params.passphrase_size = strlen(params.passphrase);
1022 }
8cf3ca80
JJ
1023
1024 r = crypt_load(cd, CRYPT_TCRYPT, &params);
1025 if (r < 0) {
7407f689 1026 if (r == -EPERM) {
cb6c9283 1027 if (key_data)
7407f689 1028 log_error_errno(r, "Failed to activate using discovered key. (Key not correct?)");
7407f689 1029
cb6c9283 1030 if (key_file)
7407f689 1031 log_error_errno(r, "Failed to activate using password file '%s'. (Key data not correct?)", key_file);
cb6c9283
LP
1032
1033 return -EAGAIN; /* log the actual error, but return EAGAIN */
6f177c7d
LP
1034 }
1035
1036 return log_error_errno(r, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd));
8cf3ca80
JJ
1037 }
1038
94c0c85e 1039 r = measured_crypt_activate_by_volume_key(cd, name, NULL, 0, flags);
6f177c7d
LP
1040 if (r < 0)
1041 return log_error_errno(r, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd));
1042
1043 return 0;
8cf3ca80
JJ
1044}
1045
e2c2f868
LP
1046static char *make_bindname(const char *volume) {
1047 char *s;
1048
1049 if (asprintf(&s, "@%" PRIx64"/cryptsetup/%s", random_u64(), volume) < 0)
1050 return NULL;
1051
1052 return s;
1053}
1054
5cbe70af
LP
1055static int make_security_device_monitor(
1056 sd_event **ret_event,
1057 sd_device_monitor **ret_monitor) {
8414cd48 1058 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
5cbe70af 1059 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
8414cd48
LP
1060 int r;
1061
5cbe70af
LP
1062 assert(ret_event);
1063 assert(ret_monitor);
1064
1065 /* Waits for a device with "security-device" tag to show up in udev */
1066
1067 r = sd_event_default(&event);
1068 if (r < 0)
1069 return log_error_errno(r, "Failed to allocate event loop: %m");
1070
1071 r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
1072 if (r < 0)
1073 return log_error_errno(r, "Failed to install timeout event source: %m");
8414cd48
LP
1074
1075 r = sd_device_monitor_new(&monitor);
1076 if (r < 0)
1077 return log_error_errno(r, "Failed to allocate device monitor: %m");
1078
17bf3c55
YW
1079 (void) sd_device_monitor_set_description(monitor, "security-device");
1080
8414cd48
LP
1081 r = sd_device_monitor_filter_add_match_tag(monitor, "security-device");
1082 if (r < 0)
1083 return log_error_errno(r, "Failed to configure device monitor: %m");
1084
1085 r = sd_device_monitor_attach_event(monitor, event);
1086 if (r < 0)
1087 return log_error_errno(r, "Failed to attach device monitor: %m");
1088
1089 r = sd_device_monitor_start(monitor, NULL, NULL);
1090 if (r < 0)
1091 return log_error_errno(r, "Failed to start device monitor: %m");
1092
5cbe70af
LP
1093 *ret_event = TAKE_PTR(event);
1094 *ret_monitor = TAKE_PTR(monitor);
8414cd48
LP
1095 return 0;
1096}
1097
5cbe70af
LP
1098static int run_security_device_monitor(
1099 sd_event *event,
1100 sd_device_monitor *monitor) {
1101 bool processed = false;
1102 int r;
1103
1104 assert(event);
1105 assert(monitor);
1106
1107 /* Runs the event loop for the device monitor until either something happens, or the time-out is
1108 * hit. */
1109
1110 for (;;) {
1111 int x;
1112
1113 r = sd_event_get_exit_code(event, &x);
1114 if (r < 0) {
1115 if (r != -ENODATA)
1116 return log_error_errno(r, "Failed to query exit code from event loop: %m");
1117
1118 /* On ENODATA we aren't told to exit yet. */
1119 } else {
1120 assert(x == -ETIMEDOUT);
1121 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
1122 "Timed out waiting for security device, aborting security device based authentication attempt.");
1123 }
1124
1125 /* Wait for one event, and then eat all subsequent events until there are no further ones */
1126 r = sd_event_run(event, processed ? 0 : UINT64_MAX);
1127 if (r < 0)
1128 return log_error_errno(r, "Failed to run event loop: %m");
1129 if (r == 0) /* no events queued anymore */
1130 return 0;
1131
1132 processed = true;
1133 }
1134}
1135
351716e1 1136static bool libcryptsetup_plugins_support(void) {
94c0c85e
LP
1137
1138#if HAVE_TPM2
1139 /* Currently, there's no way for us to query the volume key when plugins are used. Hence don't use
1140 * plugins, if measurement has been requested. */
1141 if (arg_tpm2_measure_pcr != UINT_MAX)
1142 return false;
1143#endif
1144
351716e1 1145#if HAVE_LIBCRYPTSETUP_PLUGINS
64c590fb
LP
1146 int r;
1147
1148 /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
1149 r = getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
1150 if (r < 0 && r != -ENXIO)
1151 log_debug_errno(r, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
1152 if (r == 0)
1153 return false;
1154
1155 return crypt_token_external_path();
351716e1
OK
1156#else
1157 return false;
1158#endif
1159}
1160
1161#if HAVE_LIBCRYPTSETUP_PLUGINS
1162static int acquire_pins_from_env_variable(char ***ret_pins) {
e99ca147 1163 _cleanup_(erase_and_freep) char *envpin = NULL;
351716e1 1164 _cleanup_strv_free_erase_ char **pins = NULL;
e99ca147 1165 int r;
351716e1
OK
1166
1167 assert(ret_pins);
1168
e99ca147
LP
1169 r = getenv_steal_erase("PIN", &envpin);
1170 if (r < 0)
1171 return log_error_errno(r, "Failed to acquire PIN from environment: %m");
1172 if (r > 0) {
1173 pins = strv_new(envpin);
351716e1
OK
1174 if (!pins)
1175 return log_oom();
351716e1
OK
1176 }
1177
1178 *ret_pins = TAKE_PTR(pins);
1179
1180 return 0;
1181}
1182#endif
1183
d1411499 1184static int crypt_activate_by_token_pin_ask_password(
351716e1
OK
1185 struct crypt_device *cd,
1186 const char *name,
d1411499 1187 const char *type,
351716e1
OK
1188 usec_t until,
1189 bool headless,
c50a7776 1190 void *userdata,
d1411499
JW
1191 uint32_t activation_flags,
1192 const char *message,
1193 const char *key_name,
1194 const char *credential_name) {
351716e1 1195
351716e1 1196#if HAVE_LIBCRYPTSETUP_PLUGINS
58925605 1197 AskPasswordFlags flags = arg_ask_password_flags | ASK_PASSWORD_PUSH_CACHE | ASK_PASSWORD_ACCEPT_CACHED;
a2236110 1198 _cleanup_strv_free_erase_ char **pins = NULL;
a2236110 1199 int r;
351716e1 1200
c50a7776 1201 r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, /* pin=*/ NULL, /* pin_size= */ 0, userdata, activation_flags);
351716e1 1202 if (r > 0) /* returns unlocked keyslot id on success */
c50a7776 1203 return 0;
351716e1
OK
1204 if (r != -ENOANO) /* needs pin or pin is wrong */
1205 return r;
1206
1207 r = acquire_pins_from_env_variable(&pins);
1208 if (r < 0)
1209 return r;
1210
1211 STRV_FOREACH(p, pins) {
c50a7776 1212 r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
351716e1 1213 if (r > 0) /* returns unlocked keyslot id on success */
c50a7776 1214 return 0;
351716e1
OK
1215 if (r != -ENOANO) /* needs pin or pin is wrong */
1216 return r;
1217 }
1218
1219 if (headless)
1220 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
1221
351716e1
OK
1222 for (;;) {
1223 pins = strv_free_erase(pins);
c50a7776 1224 r = ask_password_auto(message, "drive-harddisk", /* id= */ NULL, key_name, credential_name, until, flags, &pins);
351716e1
OK
1225 if (r < 0)
1226 return r;
1227
1228 STRV_FOREACH(p, pins) {
c50a7776 1229 r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
351716e1 1230 if (r > 0) /* returns unlocked keyslot id on success */
c50a7776 1231 return 0;
351716e1
OK
1232 if (r != -ENOANO) /* needs pin or pin is wrong */
1233 return r;
1234 }
92828080
LP
1235
1236 flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
351716e1 1237 }
351716e1 1238 return r;
a2236110
LP
1239#else
1240 return -EOPNOTSUPP;
1241#endif
351716e1
OK
1242}
1243
d1411499
JW
1244static int attach_luks2_by_fido2_via_plugin(
1245 struct crypt_device *cd,
1246 const char *name,
1247 usec_t until,
1248 bool headless,
c50a7776 1249 void *userdata,
d1411499
JW
1250 uint32_t activation_flags) {
1251
1252 return crypt_activate_by_token_pin_ask_password(
1253 cd,
1254 name,
1255 "systemd-fido2",
1256 until,
1257 headless,
c50a7776 1258 userdata,
d1411499
JW
1259 activation_flags,
1260 "Please enter security token PIN:",
1261 "fido2-pin",
1262 "cryptsetup.fido2-pin");
1263}
1264
2bc5c425
LP
1265static int attach_luks_or_plain_or_bitlk_by_fido2(
1266 struct crypt_device *cd,
1267 const char *name,
1268 const char *key_file,
1269 const void *key_data,
1270 size_t key_data_size,
1271 usec_t until,
1272 uint32_t flags,
1273 bool pass_volume_key) {
1274
1275 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1276 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1277 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
e6319a10
PC
1278 size_t decrypted_key_size, cid_size = 0;
1279 _cleanup_free_ char *friendly = NULL;
2bc5c425 1280 int keyslot = arg_key_slot, r;
351716e1
OK
1281 const char *rp_id = NULL;
1282 const void *cid = NULL;
cde2f860 1283 Fido2EnrollFlags required;
351716e1 1284 bool use_libcryptsetup_plugin = libcryptsetup_plugins_support();
2bc5c425
LP
1285
1286 assert(cd);
1287 assert(name);
1288 assert(arg_fido2_device || arg_fido2_device_auto);
1289
1290 if (arg_fido2_cid) {
1291 if (!key_file && !key_data)
8205c151
ZJS
1292 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1293 "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
2bc5c425
LP
1294
1295 rp_id = arg_fido2_rp_id;
1296 cid = arg_fido2_cid;
1297 cid_size = arg_fido2_cid_size;
8205c151 1298
3cc00ba6
LP
1299 /* For now and for compatibility, if the user explicitly configured FIDO2 support and we do
1300 * not read FIDO2 metadata off the LUKS2 header, default to the systemd 248 logic, where we
1301 * use PIN + UP when needed, and do not configure UV at all. Eventually, we should make this
1302 * explicitly configurable. */
1303 required = FIDO2ENROLL_PIN_IF_NEEDED | FIDO2ENROLL_UP_IF_NEEDED | FIDO2ENROLL_UV_OMIT;
2bc5c425
LP
1304 }
1305
1306 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1307 if (!friendly)
1308 return log_oom();
1309
1310 for (;;) {
351716e1 1311 if (use_libcryptsetup_plugin && !arg_fido2_cid) {
dcbc38c9 1312 r = attach_luks2_by_fido2_via_plugin(cd, name, until, arg_headless, arg_fido2_device, flags);
351716e1
OK
1313 if (IN_SET(r, -ENOTUNIQ, -ENXIO, -ENOENT))
1314 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1315 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1316
1317 } else {
e6319a10
PC
1318 if (cid)
1319 r = acquire_fido2_key(
1320 name,
1321 friendly,
1322 arg_fido2_device,
1323 rp_id,
1324 cid, cid_size,
1325 key_file, arg_keyfile_size, arg_keyfile_offset,
1326 key_data, key_data_size,
1327 until,
1328 arg_headless,
1329 required,
1330 &decrypted_key, &decrypted_key_size,
1331 arg_ask_password_flags);
1332 else
1333 r = acquire_fido2_key_auto(
1334 cd,
1335 name,
1336 friendly,
1337 arg_fido2_device,
e6319a10
PC
1338 until,
1339 arg_headless,
1340 &decrypted_key, &decrypted_key_size,
1341 arg_ask_password_flags);
351716e1
OK
1342 if (r >= 0)
1343 break;
1344 }
1345
2bc5c425
LP
1346 if (r != -EAGAIN) /* EAGAIN means: token not found */
1347 return r;
1348
1349 if (!monitor) {
1350 /* We didn't find the token. In this case, watch for it via udev. Let's
1351 * create an event loop and monitor first. */
1352
1353 assert(!event);
1354
5cbe70af 1355 r = make_security_device_monitor(&event, &monitor);
2bc5c425
LP
1356 if (r < 0)
1357 return r;
1358
1359 log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly);
1360
1361 /* Let's immediately rescan in case the token appeared in the time we needed
1362 * to create and configure the monitor */
1363 continue;
1364 }
1365
5cbe70af
LP
1366 r = run_security_device_monitor(event, monitor);
1367 if (r < 0)
1368 return r;
2bc5c425
LP
1369
1370 log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
1371 }
1372
1373 if (pass_volume_key)
94c0c85e 1374 r = measured_crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
2bc5c425
LP
1375 else {
1376 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
5e476b85 1377 ssize_t base64_encoded_size;
2bc5c425
LP
1378
1379 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1380
5e476b85
LP
1381 base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1382 if (base64_encoded_size < 0)
2bc5c425
LP
1383 return log_oom();
1384
94c0c85e 1385 r = measured_crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, base64_encoded_size, flags);
2bc5c425
LP
1386 }
1387 if (r == -EPERM) {
1388 log_error_errno(r, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
1389 return -EAGAIN; /* log actual error, but return EAGAIN */
1390 }
1391 if (r < 0)
1392 return log_error_errno(r, "Failed to activate with FIDO2 acquired key: %m");
1393
1394 return 0;
1395}
1396
dcbc38c9 1397static int attach_luks2_by_pkcs11_via_plugin(
8186022c
OK
1398 struct crypt_device *cd,
1399 const char *name,
1400 const char *friendly_name,
1401 usec_t until,
1402 bool headless,
1403 uint32_t flags) {
1404
8186022c 1405#if HAVE_LIBCRYPTSETUP_PLUGINS
a2236110
LP
1406 int r;
1407
1408 if (!streq_ptr(crypt_get_type(cd), CRYPT_LUKS2))
8186022c
OK
1409 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Automatic PKCS#11 metadata requires LUKS2 device.");
1410
1411 systemd_pkcs11_plugin_params params = {
1412 .friendly_name = friendly_name,
1413 .until = until,
a758a128
LP
1414 .headless = headless,
1415 .askpw_flags = arg_ask_password_flags,
8186022c
OK
1416 };
1417
1418 r = crypt_activate_by_token_pin(cd, name, "systemd-pkcs11", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
1419 if (r > 0) /* returns unlocked keyslot id on success */
1420 r = 0;
a2236110 1421
8186022c 1422 return r;
a2236110
LP
1423#else
1424 return -EOPNOTSUPP;
1425#endif
8186022c
OK
1426}
1427
b8c80b56
LP
1428static int attach_luks_or_plain_or_bitlk_by_pkcs11(
1429 struct crypt_device *cd,
1430 const char *name,
1431 const char *key_file,
1432 const void *key_data,
1433 size_t key_data_size,
1434 usec_t until,
1435 uint32_t flags,
1436 bool pass_volume_key) {
1437
1438 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1439 _cleanup_free_ char *friendly = NULL, *discovered_uri = NULL;
1440 size_t decrypted_key_size = 0, discovered_key_size = 0;
1441 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1442 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1443 _cleanup_free_ void *discovered_key = NULL;
1444 int keyslot = arg_key_slot, r;
8186022c
OK
1445 const char *uri = NULL;
1446 bool use_libcryptsetup_plugin = libcryptsetup_plugins_support();
b8c80b56
LP
1447
1448 assert(cd);
1449 assert(name);
1450 assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
1451
1452 if (arg_pkcs11_uri_auto) {
8186022c
OK
1453 if (!use_libcryptsetup_plugin) {
1454 r = find_pkcs11_auto_data(cd, &discovered_uri, &discovered_key, &discovered_key_size, &keyslot);
1455 if (IN_SET(r, -ENOTUNIQ, -ENXIO))
1456 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1457 "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1458 if (r < 0)
1459 return r;
b8c80b56 1460
8186022c
OK
1461 uri = discovered_uri;
1462 key_data = discovered_key;
1463 key_data_size = discovered_key_size;
1464 }
b8c80b56
LP
1465 } else {
1466 uri = arg_pkcs11_uri;
1467
1468 if (!key_file && !key_data)
1469 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing.");
1470 }
1471
1472 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1473 if (!friendly)
1474 return log_oom();
1475
1476 for (;;) {
8186022c 1477 if (use_libcryptsetup_plugin && arg_pkcs11_uri_auto)
dcbc38c9 1478 r = attach_luks2_by_pkcs11_via_plugin(cd, name, friendly, until, arg_headless, flags);
8186022c
OK
1479 else {
1480 r = decrypt_pkcs11_key(
1481 name,
1482 friendly,
1483 uri,
1484 key_file, arg_keyfile_size, arg_keyfile_offset,
1485 key_data, key_data_size,
1486 until,
1487 arg_headless,
1488 &decrypted_key, &decrypted_key_size);
1489 if (r >= 0)
1490 break;
1491 }
1492
b8c80b56
LP
1493 if (r != -EAGAIN) /* EAGAIN means: token not found */
1494 return r;
1495
1496 if (!monitor) {
1497 /* We didn't find the token. In this case, watch for it via udev. Let's
1498 * create an event loop and monitor first. */
1499
1500 assert(!event);
1501
5cbe70af 1502 r = make_security_device_monitor(&event, &monitor);
b8c80b56
LP
1503 if (r < 0)
1504 return r;
1505
1506 log_notice("Security token %s not present for unlocking volume %s, please plug it in.",
1507 uri, friendly);
1508
1509 /* Let's immediately rescan in case the token appeared in the time we needed
1510 * to create and configure the monitor */
1511 continue;
1512 }
1513
5cbe70af
LP
1514 r = run_security_device_monitor(event, monitor);
1515 if (r < 0)
1516 return r;
b8c80b56
LP
1517
1518 log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
1519 }
8186022c 1520 assert(decrypted_key);
b8c80b56
LP
1521
1522 if (pass_volume_key)
94c0c85e 1523 r = measured_crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
b8c80b56
LP
1524 else {
1525 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
5e476b85 1526 ssize_t base64_encoded_size;
b8c80b56
LP
1527
1528 /* Before using this key as passphrase we base64 encode it. Why? For compatibility
1529 * with homed's PKCS#11 hookup: there we want to use the key we acquired through
1530 * PKCS#11 for other authentication/decryption mechanisms too, and some of them do
ad337e55 1531 * not take arbitrary binary blobs, but require NUL-terminated strings — most
b8c80b56
LP
1532 * importantly UNIX password hashes. Hence, for compatibility we want to use a string
1533 * without embedded NUL here too, and that's easiest to generate from a binary blob
1534 * via base64 encoding. */
1535
5e476b85
LP
1536 base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1537 if (base64_encoded_size < 0)
b8c80b56
LP
1538 return log_oom();
1539
94c0c85e 1540 r = measured_crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, base64_encoded_size, flags);
b8c80b56
LP
1541 }
1542 if (r == -EPERM) {
1543 log_error_errno(r, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
1544 return -EAGAIN; /* log actual error, but return EAGAIN */
1545 }
1546 if (r < 0)
1547 return log_error_errno(r, "Failed to activate with PKCS#11 acquired key: %m");
1548
1549 return 0;
1550}
1551
5cbe70af
LP
1552static int make_tpm2_device_monitor(
1553 sd_event **ret_event,
1554 sd_device_monitor **ret_monitor) {
1555
18843ecc 1556 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
5cbe70af 1557 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
18843ecc
LP
1558 int r;
1559
5cbe70af
LP
1560 assert(ret_event);
1561 assert(ret_monitor);
1562
1563 r = sd_event_default(&event);
1564 if (r < 0)
1565 return log_error_errno(r, "Failed to allocate event loop: %m");
1566
1567 r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
1568 if (r < 0)
1569 return log_error_errno(r, "Failed to install timeout event source: %m");
18843ecc
LP
1570
1571 r = sd_device_monitor_new(&monitor);
1572 if (r < 0)
1573 return log_error_errno(r, "Failed to allocate device monitor: %m");
1574
17bf3c55
YW
1575 (void) sd_device_monitor_set_description(monitor, "tpmrm");
1576
18843ecc
LP
1577 r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "tpmrm", NULL);
1578 if (r < 0)
1579 return log_error_errno(r, "Failed to configure device monitor: %m");
1580
1581 r = sd_device_monitor_attach_event(monitor, event);
1582 if (r < 0)
1583 return log_error_errno(r, "Failed to attach device monitor: %m");
1584
1585 r = sd_device_monitor_start(monitor, NULL, NULL);
1586 if (r < 0)
1587 return log_error_errno(r, "Failed to start device monitor: %m");
1588
5cbe70af
LP
1589 *ret_event = TAKE_PTR(event);
1590 *ret_monitor = TAKE_PTR(monitor);
18843ecc
LP
1591 return 0;
1592}
1593
00392b14
LP
1594static bool use_token_plugins(void) {
1595 int r;
1596
1597 /* Disable tokens if we shall measure, since we won't get access to the volume key then. */
1598 if (arg_tpm2_measure_pcr != UINT_MAX)
1599 return false;
1600
1601 r = getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
1602 if (r < 0 && r != -ENXIO)
1603 log_debug_errno(r, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE value, ignoring: %m");
1604
1605 return r != 0;
1606}
1607
dcbc38c9 1608static int attach_luks2_by_tpm2_via_plugin(
d1ae38d8
OK
1609 struct crypt_device *cd,
1610 const char *name,
35ba2b4f
JW
1611 usec_t until,
1612 bool headless,
d1ae38d8
OK
1613 uint32_t flags) {
1614
1615#if HAVE_LIBCRYPTSETUP_PLUGINS
d1ae38d8
OK
1616 systemd_tpm2_plugin_params params = {
1617 .search_pcr_mask = arg_tpm2_pcr_mask,
75a9681e
LP
1618 .device = arg_tpm2_device,
1619 .signature_path = arg_tpm2_signature,
404aea78 1620 .pcrlock_path = arg_tpm2_pcrlock,
d1ae38d8
OK
1621 };
1622
d1b2e043 1623 if (!libcryptsetup_plugins_support())
d1ae38d8
OK
1624 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1625 "Libcryptsetup has external plugins support disabled.");
1626
35ba2b4f
JW
1627 return crypt_activate_by_token_pin_ask_password(
1628 cd,
1629 name,
1630 "systemd-tpm2",
1631 until,
1632 headless,
1633 &params,
1634 flags,
1635 "Please enter TPM2 PIN:",
1636 "tpm2-pin",
1637 "cryptsetup.tpm2-pin");
d1ae38d8
OK
1638#else
1639 return -EOPNOTSUPP;
1640#endif
1641}
1642
18843ecc
LP
1643static int attach_luks_or_plain_or_bitlk_by_tpm2(
1644 struct crypt_device *cd,
1645 const char *name,
1646 const char *key_file,
1647 const void *key_data,
1648 size_t key_data_size,
1649 usec_t until,
1650 uint32_t flags,
1651 bool pass_volume_key) {
1652
1653 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1654 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1655 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1656 _cleanup_free_ char *friendly = NULL;
1657 int keyslot = arg_key_slot, r;
67e9c83b 1658 size_t decrypted_key_size;
18843ecc
LP
1659
1660 assert(cd);
1661 assert(name);
1662 assert(arg_tpm2_device || arg_tpm2_device_auto);
1663
1664 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1665 if (!friendly)
1666 return log_oom();
1667
1668 for (;;) {
18843ecc
LP
1669 if (key_file || key_data) {
1670 /* If key data is specified, use that */
1671
1672 r = acquire_tpm2_key(
1673 name,
1674 arg_tpm2_device,
1675 arg_tpm2_pcr_mask == UINT32_MAX ? TPM2_PCR_MASK_DEFAULT : arg_tpm2_pcr_mask,
07697bfe 1676 UINT16_MAX,
dc63b2c9
LP
1677 /* pubkey= */ NULL, /* pubkey_size= */ 0,
1678 /* pubkey_pcr_mask= */ 0,
1679 /* signature_path= */ NULL,
404aea78 1680 /* pcrlock_path= */ NULL,
dc63b2c9 1681 /* primary_alg= */ 0,
18843ecc
LP
1682 key_file, arg_keyfile_size, arg_keyfile_offset,
1683 key_data, key_data_size,
dc63b2c9 1684 /* policy_hash= */ NULL, /* policy_hash_size= */ 0, /* we don't know the policy hash */
aae6eb96 1685 /* salt= */ NULL, /* salt_size= */ 0,
acbb504e 1686 /* srk_buf= */ NULL, /* srk_buf_size= */ 0,
3fab44b2 1687 arg_tpm2_pin ? TPM2_FLAGS_USE_PIN : 0,
bea344a1
GG
1688 until,
1689 arg_headless,
1690 arg_ask_password_flags,
18843ecc
LP
1691 &decrypted_key, &decrypted_key_size);
1692 if (r >= 0)
1693 break;
bea344a1
GG
1694 if (IN_SET(r, -EACCES, -ENOLCK))
1695 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
cad10544
LP
1696 if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
1697 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");
49be0383
AAF
1698 /* EAGAIN means: no tpm2 chip found */
1699 if (r != -EAGAIN) {
1700 log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
1701 return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1702 }
18843ecc 1703 } else {
35ba2b4f
JW
1704 r = attach_luks2_by_tpm2_via_plugin(cd, name, until, arg_headless, flags);
1705 if (r >= 0)
1706 return 0;
d1ae38d8
OK
1707 /* EAGAIN means: no tpm2 chip found
1708 * EOPNOTSUPP means: no libcryptsetup plugins support */
1709 if (r == -ENXIO)
2e4aae98
LP
1710 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
1711 "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
d1ae38d8
OK
1712 if (r == -ENOENT)
1713 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1714 "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
49be0383
AAF
1715 if (!IN_SET(r, -EOPNOTSUPP, -EAGAIN)) {
1716 log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
1717 return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1718 }
d1ae38d8
OK
1719 }
1720
dcbc38c9 1721 if (r == -EOPNOTSUPP) { /* Plugin not available, let's process TPM2 stuff right here instead */
18843ecc
LP
1722 _cleanup_free_ void *blob = NULL, *policy_hash = NULL;
1723 size_t blob_size, policy_hash_size;
1724 bool found_some = false;
1725 int token = 0; /* first token to look at */
1726
1727 /* If no key data is specified, look for it in the header. In order to support
1728 * software upgrades we'll iterate through all suitable tokens, maybe one of them
1729 * works. */
1730
1731 for (;;) {
acbb504e
WR
1732 _cleanup_free_ void *pubkey = NULL, *salt = NULL, *srk_buf = NULL;
1733 size_t pubkey_size = 0, salt_size = 0, srk_buf_size = 0;
dc63b2c9 1734 uint32_t hash_pcr_mask, pubkey_pcr_mask;
2b92a672 1735 uint16_t pcr_bank, primary_alg;
bea344a1 1736 TPM2Flags tpm2_flags;
18843ecc
LP
1737
1738 r = find_tpm2_auto_data(
1739 cd,
1740 arg_tpm2_pcr_mask, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1741 token, /* search for the token with this index, or any later index than this */
dc63b2c9 1742 &hash_pcr_mask,
07697bfe 1743 &pcr_bank,
dc63b2c9
LP
1744 &pubkey, &pubkey_size,
1745 &pubkey_pcr_mask,
2b92a672 1746 &primary_alg,
18843ecc
LP
1747 &blob, &blob_size,
1748 &policy_hash, &policy_hash_size,
aae6eb96 1749 &salt, &salt_size,
acbb504e 1750 &srk_buf, &srk_buf_size,
fdf6c27c 1751 &tpm2_flags,
18843ecc 1752 &keyslot,
fdf6c27c 1753 &token);
c26f7dd9 1754 if (r == -ENXIO)
7802194a 1755 /* No further TPM2 tokens found in the LUKS2 header. */
2e4aae98
LP
1756 return log_full_errno(found_some ? LOG_NOTICE : LOG_DEBUG,
1757 SYNTHETIC_ERRNO(EAGAIN),
1758 found_some
1759 ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
1760 : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
bb44fd07
ZJS
1761 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
1762 /* TPM2 support not compiled in? */
1763 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1764 "TPM2 support not available, falling back to traditional unlocking.");
1765 if (r < 0)
18843ecc
LP
1766 return r;
1767
1768 found_some = true;
1769
1770 r = acquire_tpm2_key(
1771 name,
1772 arg_tpm2_device,
dc63b2c9 1773 hash_pcr_mask,
07697bfe 1774 pcr_bank,
dc63b2c9
LP
1775 pubkey, pubkey_size,
1776 pubkey_pcr_mask,
1777 arg_tpm2_signature,
404aea78 1778 arg_tpm2_pcrlock,
2b92a672 1779 primary_alg,
dc63b2c9 1780 /* key_file= */ NULL, /* key_file_size= */ 0, /* key_file_offset= */ 0, /* no key file */
18843ecc
LP
1781 blob, blob_size,
1782 policy_hash, policy_hash_size,
aae6eb96 1783 salt, salt_size,
acbb504e 1784 srk_buf, srk_buf_size,
bea344a1
GG
1785 tpm2_flags,
1786 until,
1787 arg_headless,
1788 arg_ask_password_flags,
18843ecc 1789 &decrypted_key, &decrypted_key_size);
bea344a1 1790 if (IN_SET(r, -EACCES, -ENOLCK))
2e4aae98 1791 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
18843ecc
LP
1792 if (r != -EPERM)
1793 break;
1794
1795 token++; /* try a different token next time */
1796 }
1797
1798 if (r >= 0)
1799 break;
49be0383
AAF
1800 /* EAGAIN means: no tpm2 chip found */
1801 if (r != -EAGAIN) {
1802 log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
1803 return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
1804 }
18843ecc
LP
1805 }
1806
1807 if (!monitor) {
1808 /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
1809 * an event loop and monitor first. */
1810
1811 assert(!event);
1812
71b25dea
LP
1813 if (is_efi_boot() && !efi_has_tpm2())
1814 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
88a65c93 1815 "No TPM2 hardware discovered and EFI firmware does not see it either, falling back to traditional unlocking.");
71b25dea 1816
5cbe70af 1817 r = make_tpm2_device_monitor(&event, &monitor);
18843ecc
LP
1818 if (r < 0)
1819 return r;
1820
1821 log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly);
1822
1823 /* Let's immediately rescan in case the device appeared in the time we needed
1824 * to create and configure the monitor */
1825 continue;
1826 }
1827
5cbe70af
LP
1828 r = run_security_device_monitor(event, monitor);
1829 if (r < 0)
1830 return r;
18843ecc
LP
1831
1832 log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
1833 }
26fbc5aa 1834 assert(decrypted_key);
18843ecc
LP
1835
1836 if (pass_volume_key)
94c0c85e 1837 r = measured_crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
18843ecc
LP
1838 else {
1839 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
5e476b85 1840 ssize_t base64_encoded_size;
18843ecc
LP
1841
1842 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1843
5e476b85
LP
1844 base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1845 if (base64_encoded_size < 0)
18843ecc
LP
1846 return log_oom();
1847
94c0c85e 1848 r = measured_crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, base64_encoded_size, flags);
18843ecc
LP
1849 }
1850 if (r == -EPERM) {
1851 log_error_errno(r, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
1852 return -EAGAIN; /* log actual error, but return EAGAIN */
1853 }
1854 if (r < 0)
1855 return log_error_errno(r, "Failed to activate with TPM2 acquired key: %m");
1856
1857 return 0;
1858}
1859
b8c80b56
LP
1860static int attach_luks_or_plain_or_bitlk_by_key_data(
1861 struct crypt_device *cd,
1862 const char *name,
1863 const void *key_data,
1864 size_t key_data_size,
1865 uint32_t flags,
1866 bool pass_volume_key) {
1867
1868 int r;
1869
1870 assert(cd);
1871 assert(name);
1872 assert(key_data);
1873
1874 if (pass_volume_key)
94c0c85e 1875 r = measured_crypt_activate_by_volume_key(cd, name, key_data, key_data_size, flags);
b8c80b56 1876 else
94c0c85e 1877 r = measured_crypt_activate_by_passphrase(cd, name, arg_key_slot, key_data, key_data_size, flags);
b8c80b56
LP
1878 if (r == -EPERM) {
1879 log_error_errno(r, "Failed to activate. (Key incorrect?)");
1880 return -EAGAIN; /* Log actual error, but return EAGAIN */
1881 }
1882 if (r < 0)
1883 return log_error_errno(r, "Failed to activate: %m");
1884
1885 return 0;
1886}
1887
1888static int attach_luks_or_plain_or_bitlk_by_key_file(
1889 struct crypt_device *cd,
1890 const char *name,
1891 const char *key_file,
1892 uint32_t flags,
1893 bool pass_volume_key) {
1894
1895 _cleanup_(erase_and_freep) char *kfdata = NULL;
1896 _cleanup_free_ char *bindname = NULL;
1897 size_t kfsize;
1898 int r;
1899
1900 assert(cd);
1901 assert(name);
1902 assert(key_file);
1903
1904 /* If we read the key via AF_UNIX, make this client recognizable */
1905 bindname = make_bindname(name);
1906 if (!bindname)
1907 return log_oom();
1908
1909 r = read_full_file_full(
1910 AT_FDCWD, key_file,
1911 arg_keyfile_offset == 0 ? UINT64_MAX : arg_keyfile_offset,
1912 arg_keyfile_size == 0 ? SIZE_MAX : arg_keyfile_size,
1913 READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
1914 bindname,
1915 &kfdata, &kfsize);
871f35af
LP
1916 if (r == -E2BIG) {
1917 log_error_errno(r, "Failed to activate, key file '%s' too large.", key_file);
1918 return -EAGAIN;
1919 }
b8c80b56
LP
1920 if (r == -ENOENT) {
1921 log_error_errno(r, "Failed to activate, key file '%s' missing.", key_file);
1922 return -EAGAIN; /* Log actual error, but return EAGAIN */
1923 }
abc50cf6
LP
1924 if (r < 0)
1925 return log_error_errno(r, "Failed to read key file '%s': %m", key_file);
b8c80b56
LP
1926
1927 if (pass_volume_key)
94c0c85e 1928 r = measured_crypt_activate_by_volume_key(cd, name, kfdata, kfsize, flags);
b8c80b56 1929 else
94c0c85e 1930 r = measured_crypt_activate_by_passphrase(cd, name, arg_key_slot, kfdata, kfsize, flags);
b8c80b56
LP
1931 if (r == -EPERM) {
1932 log_error_errno(r, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file);
1933 return -EAGAIN; /* Log actual error, but return EAGAIN */
1934 }
1935 if (r < 0)
1936 return log_error_errno(r, "Failed to activate with key file '%s': %m", key_file);
1937
1938 return 0;
1939}
1940
1941static int attach_luks_or_plain_or_bitlk_by_passphrase(
1942 struct crypt_device *cd,
1943 const char *name,
1944 char **passwords,
1945 uint32_t flags,
1946 bool pass_volume_key) {
1947
b8c80b56
LP
1948 int r;
1949
1950 assert(cd);
1951 assert(name);
1952
1953 r = -EINVAL;
1954 STRV_FOREACH(p, passwords) {
1955 if (pass_volume_key)
94c0c85e 1956 r = measured_crypt_activate_by_volume_key(cd, name, *p, arg_key_size, flags);
b8c80b56 1957 else
94c0c85e 1958 r = measured_crypt_activate_by_passphrase(cd, name, arg_key_slot, *p, strlen(*p), flags);
b8c80b56
LP
1959 if (r >= 0)
1960 break;
1961 }
1962 if (r == -EPERM) {
1963 log_error_errno(r, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
1964 return -EAGAIN; /* log actual error, but return EAGAIN */
1965 }
1966 if (r < 0)
1967 return log_error_errno(r, "Failed to activate with specified passphrase: %m");
1968
1969 return 0;
1970}
1971
6cc27c29 1972static int attach_luks_or_plain_or_bitlk(
9c5253ff
LP
1973 struct crypt_device *cd,
1974 const char *name,
1975 const char *key_file,
7407f689
LP
1976 const void *key_data,
1977 size_t key_data_size,
9c5253ff 1978 char **passwords,
08669709
LP
1979 uint32_t flags,
1980 usec_t until) {
9c5253ff 1981
10fb4e35 1982 bool pass_volume_key = false;
b8c80b56 1983 int r;
10fb4e35
JJ
1984
1985 assert(cd);
1986 assert(name);
10fb4e35 1987
2e4beb87 1988 if ((!arg_type && !crypt_get_type(cd)) || streq_ptr(arg_type, CRYPT_PLAIN)) {
4eac2773
MP
1989 struct crypt_params_plain params = {
1990 .offset = arg_offset,
1991 .skip = arg_skip,
a9fc6406 1992 .sector_size = arg_sector_size,
4eac2773 1993 };
10fb4e35
JJ
1994 const char *cipher, *cipher_mode;
1995 _cleanup_free_ char *truncated_cipher = NULL;
1996
b8c80b56 1997 if (streq_ptr(arg_hash, "plain"))
10fb4e35 1998 /* plain isn't a real hash type. it just means "use no hash" */
b8c80b56
LP
1999 params.hash = NULL;
2000 else if (arg_hash)
2001 params.hash = arg_hash;
2002 else if (!key_file)
2003 /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
2004 * file is provided */
10fb4e35
JJ
2005 params.hash = "ripemd160";
2006
f75cac37 2007 if (arg_cipher) {
10fb4e35
JJ
2008 size_t l;
2009
f75cac37
LP
2010 l = strcspn(arg_cipher, "-");
2011 truncated_cipher = strndup(arg_cipher, l);
10fb4e35
JJ
2012 if (!truncated_cipher)
2013 return log_oom();
2014
2015 cipher = truncated_cipher;
f75cac37 2016 cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain";
10fb4e35
JJ
2017 } else {
2018 cipher = "aes";
2019 cipher_mode = "cbc-essiv:sha256";
2020 }
2021
aed68083 2022 /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
6131a78b 2023 arg_keyfile_size = arg_key_size;
10fb4e35 2024
30747265 2025 /* In contrast to what the name crypt_format() might suggest this doesn't actually format
aed68083 2026 * anything, it just configures encryption parameters when used for plain mode. */
1602b008 2027 r = crypt_format(cd, CRYPT_PLAIN, cipher, cipher_mode, NULL, NULL, arg_keyfile_size, &params);
2e4beb87
MB
2028 if (r < 0)
2029 return log_error_errno(r, "Loading of cryptographic parameters failed: %m");
10fb4e35
JJ
2030
2031 /* hash == NULL implies the user passed "plain" */
b8c80b56 2032 pass_volume_key = !params.hash;
10fb4e35 2033 }
10fb4e35
JJ
2034
2035 log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
2036 crypt_get_cipher(cd),
2037 crypt_get_cipher_mode(cd),
2038 crypt_get_volume_key_size(cd)*8,
2039 crypt_get_device_name(cd));
2040
18843ecc
LP
2041 if (arg_tpm2_device || arg_tpm2_device_auto)
2042 return attach_luks_or_plain_or_bitlk_by_tpm2(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
2bc5c425
LP
2043 if (arg_fido2_device || arg_fido2_device_auto)
2044 return attach_luks_or_plain_or_bitlk_by_fido2(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
b8c80b56
LP
2045 if (arg_pkcs11_uri || arg_pkcs11_uri_auto)
2046 return attach_luks_or_plain_or_bitlk_by_pkcs11(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
2047 if (key_data)
2048 return attach_luks_or_plain_or_bitlk_by_key_data(cd, name, key_data, key_data_size, flags, pass_volume_key);
2049 if (key_file)
2050 return attach_luks_or_plain_or_bitlk_by_key_file(cd, name, key_file, flags, pass_volume_key);
10fb4e35 2051
b8c80b56 2052 return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
10fb4e35
JJ
2053}
2054
dd5e696d 2055static int help(void) {
37ec0fdd
LP
2056 _cleanup_free_ char *link = NULL;
2057 int r;
2058
166015fa 2059 r = terminal_urlify_man("systemd-cryptsetup", "8", &link);
37ec0fdd
LP
2060 if (r < 0)
2061 return log_oom();
dd5e696d 2062
166015fa
ZJS
2063 printf("%1$s attach VOLUME SOURCE-DEVICE [KEY-FILE] [CONFIG]\n"
2064 "%1$s detach VOLUME\n\n"
2065 "%2$sAttach or detach an encrypted block device.%3$s\n\n"
2066 " -h --help Show this help\n"
2067 " --version Show package version\n"
2068 "\nSee the %4$s for details.\n",
bc556335 2069 program_invocation_short_name,
166015fa
ZJS
2070 ansi_highlight(),
2071 ansi_normal(),
bc556335 2072 link);
dd5e696d
LP
2073
2074 return 0;
2075}
2076
166015fa
ZJS
2077static int parse_argv(int argc, char *argv[]) {
2078 enum {
2079 ARG_VERSION = 0x100,
2080 };
2081
2082 static const struct option options[] = {
2083 { "help", no_argument, NULL, 'h' },
2084 { "version", no_argument, NULL, ARG_VERSION },
2085 {}
2086 };
2087
2088 int c;
2089
2090 assert(argc >= 0);
2091 assert(argv);
2092
2093 if (argv_looks_like_help(argc, argv))
2094 return help();
2095
2096 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
2097 switch (c) {
2098
2099 case 'h':
2100 return help();
2101
2102 case ARG_VERSION:
2103 return version();
2104
2105 case '?':
2106 return -EINVAL;
2107
2108 default:
2109 assert_not_reached();
2110 }
2111
2112 return 1;
2113}
2114
d5d1ae15
LP
2115static uint32_t determine_flags(void) {
2116 uint32_t flags = 0;
2117
2118 if (arg_readonly)
2119 flags |= CRYPT_ACTIVATE_READONLY;
2120
2121 if (arg_discards)
2122 flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
2123
2124 if (arg_same_cpu_crypt)
2125 flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
2126
2127 if (arg_submit_from_crypt_cpus)
2128 flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
2129
227acf00
JU
2130 if (arg_no_read_workqueue)
2131 flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
2132
2133 if (arg_no_write_workqueue)
2134 flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
2135
408c81f6
MS
2136#ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
2137 /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
2138 /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
2139 flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF;
2140#endif
2141
d5d1ae15
LP
2142 return flags;
2143}
2144
d3d49e76
LP
2145static void remove_and_erasep(const char **p) {
2146 int r;
2147
2148 if (!*p)
2149 return;
2150
2151 r = unlinkat_deallocate(AT_FDCWD, *p, UNLINK_ERASE);
2152 if (r < 0 && r != -ENOENT)
2153 log_warning_errno(r, "Unable to erase key file '%s', ignoring: %m", *p);
2154}
2155
3a40f366 2156static int run(int argc, char *argv[]) {
294bd454 2157 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
da2268f9 2158 const char *verb;
3a40f366 2159 int r;
e23a0ce8 2160
166015fa 2161 log_setup();
dd5e696d 2162
166015fa 2163 umask(0022);
e23a0ce8 2164
166015fa
ZJS
2165 r = parse_argv(argc, argv);
2166 if (r <= 0)
2167 return r;
e23a0ce8 2168
2f678640 2169 cryptsetup_enable_logging(NULL);
568a8404 2170
166015fa
ZJS
2171 if (argc - optind < 2)
2172 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2173 "This program requires at least two arguments.");
2174 verb = ASSERT_PTR(argv[optind]);
da2268f9
LP
2175
2176 if (streq(verb, "attach")) {
d7ac0952 2177 _unused_ _cleanup_(remove_and_erasep) const char *destroy_key_file = NULL;
7407f689 2178 _cleanup_(erase_and_freep) void *key_data = NULL;
da2268f9 2179 crypt_status_info status;
7407f689 2180 size_t key_data_size = 0;
da2268f9
LP
2181 uint32_t flags = 0;
2182 unsigned tries;
2183 usec_t until;
b6c0bd11 2184 PassphraseType passphrase_type = PASSPHRASE_NONE;
7f4e0805 2185
166015fa 2186 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [KEY-FILE] [CONFIG] */
b61e476f 2187
166015fa 2188 if (argc - optind < 3)
0ffff81a 2189 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "attach requires at least two arguments.");
5bae80bd
ZJS
2190 if (argc - optind >= 6)
2191 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "attach does not accept more than four arguments.");
7f4e0805 2192
166015fa
ZJS
2193 const char *volume = ASSERT_PTR(argv[optind + 1]),
2194 *source = ASSERT_PTR(argv[optind + 2]),
2195 *key_file = argc - optind >= 4 ? mangle_none(argv[optind + 3]) : NULL,
2196 *config = argc - optind >= 5 ? mangle_none(argv[optind + 4]) : NULL;
7407f689 2197
da2268f9
LP
2198 if (!filename_is_valid(volume))
2199 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
2200
2201 if (key_file && !path_is_absolute(key_file)) {
2202 log_warning("Password file path '%s' is not absolute. Ignoring.", key_file);
2203 key_file = NULL;
7f4e0805
LP
2204 }
2205
166015fa
ZJS
2206 if (config) {
2207 r = parse_crypt_config(config);
3a40f366
YW
2208 if (r < 0)
2209 return r;
74b1c371 2210 }
e23a0ce8 2211
7bb553bb 2212 log_debug("%s %s ← %s type=%s cipher=%s", __func__,
da2268f9 2213 volume, source, strempty(arg_type), strempty(arg_cipher));
7bb553bb 2214
b853f6e9 2215 /* A delicious drop of snake oil */
9c5253ff 2216 (void) mlockall(MCL_FUTURE);
b853f6e9 2217
7407f689 2218 if (!key_file) {
e060ed32 2219 _cleanup_free_ char *bindname = NULL;
7407f689
LP
2220 const char *fn;
2221
da2268f9 2222 bindname = make_bindname(volume);
e060ed32
LP
2223 if (!bindname)
2224 return log_oom();
2225
7407f689
LP
2226 /* If a key file is not explicitly specified, search for a key in a well defined
2227 * search path, and load it. */
2228
da2268f9 2229 fn = strjoina(volume, ".key");
e060ed32
LP
2230 r = find_key_file(
2231 fn,
2232 STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"),
2233 bindname,
2234 &key_data, &key_data_size);
7407f689
LP
2235 if (r < 0)
2236 return r;
2237 if (r > 0)
da2268f9 2238 log_debug("Automatically discovered key for volume '%s'.", volume);
7407f689 2239 } else if (arg_keyfile_erase)
d3d49e76
LP
2240 destroy_key_file = key_file; /* let's get this baby erased when we leave */
2241
7376e835 2242 if (arg_header) {
70390240
KZ
2243 if (streq_ptr(arg_type, CRYPT_TCRYPT)){
2244 log_debug("tcrypt header: %s", arg_header);
2245 r = crypt_init_data_device(&cd, arg_header, source);
2246 } else {
2247 log_debug("LUKS header: %s", arg_header);
2248 r = crypt_init(&cd, arg_header);
2249 }
7376e835 2250 } else
da2268f9 2251 r = crypt_init(&cd, source);
3a40f366
YW
2252 if (r < 0)
2253 return log_error_errno(r, "crypt_init() failed: %m");
e23a0ce8 2254
efc3b12f 2255 cryptsetup_enable_logging(cd);
7f4e0805 2256
da2268f9 2257 status = crypt_status(cd, volume);
3742095b 2258 if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) {
da2268f9 2259 log_info("Volume %s already active.", volume);
3a40f366 2260 return 0;
7f4e0805
LP
2261 }
2262
d5d1ae15 2263 flags = determine_flags();
2c65512e 2264
496db330
YW
2265 until = usec_add(now(CLOCK_MONOTONIC), arg_timeout);
2266 if (until == USEC_INFINITY)
7dcda352 2267 until = 0;
260ab287 2268
714c5869
LP
2269 if (arg_key_size == 0)
2270 arg_key_size = 256U / 8U;
e2d480b9 2271
10fb4e35
JJ
2272 if (key_file) {
2273 struct stat st;
e2d480b9 2274
10fb4e35
JJ
2275 /* Ideally we'd do this on the open fd, but since this is just a
2276 * warning it's OK to do this in two steps. */
3f4d56a0
MP
2277 if (stat(key_file, &st) >= 0 && S_ISREG(st.st_mode) && (st.st_mode & 0005))
2278 log_warning("Key file %s is world-readable. This is not a good idea!", key_file);
e2d480b9
LP
2279 }
2280
6930d069
LP
2281 if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2)) {
2282 r = crypt_load(cd, !arg_type || streq(arg_type, ANY_LUKS) ? CRYPT_LUKS : arg_type, NULL);
ea9a9d49
MB
2283 if (r < 0)
2284 return log_error_errno(r, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd));
2285
2286 if (arg_header) {
da2268f9 2287 r = crypt_set_data_device(cd, source);
ea9a9d49 2288 if (r < 0)
da2268f9 2289 return log_error_errno(r, "Failed to set LUKS data device %s: %m", source);
ea9a9d49 2290 }
d90874b4 2291
894bb3ca 2292 /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
00392b14 2293 if (!key_file && !key_data && use_token_plugins()) {
ee6c66ac
JW
2294 r = crypt_activate_by_token_pin_ask_password(
2295 cd,
2296 volume,
c50a7776 2297 /* type= */ NULL,
ee6c66ac
JW
2298 until,
2299 arg_headless,
c50a7776 2300 /* userdata= */ NULL,
ee6c66ac
JW
2301 flags,
2302 "Please enter LUKS2 token PIN:",
2303 "luks2-pin",
2304 "cryptsetup.luks2-pin");
894bb3ca 2305 if (r >= 0) {
da2268f9 2306 log_debug("Volume %s activated with LUKS token id %i.", volume, r);
894bb3ca
MB
2307 return 0;
2308 }
2309
2310 log_debug_errno(r, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd));
2311 }
ea9a9d49
MB
2312 }
2313
6cc27c29
MF
2314/* since cryptsetup 2.3.0 (Feb 2020) */
2315#ifdef CRYPT_BITLK
5af39ac8 2316 if (streq_ptr(arg_type, CRYPT_BITLK)) {
6cc27c29
MF
2317 r = crypt_load(cd, CRYPT_BITLK, NULL);
2318 if (r < 0)
2319 return log_error_errno(r, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd));
2320 }
2321#endif
2322
f75cac37 2323 for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) {
ab84f5b9 2324 _cleanup_strv_free_erase_ char **passwords = NULL;
260ab287 2325
0ba6f85e
LP
2326 /* When we were able to acquire multiple keys, let's always process them in this order:
2327 *
18843ecc 2328 * 1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
0ba6f85e
LP
2329 * 2. The discovered key: i.e. key_data + key_data_size
2330 * 3. The configured key: i.e. key_file + arg_keyfile_offset + arg_keyfile_size
2331 * 4. The empty password, in case arg_try_empty_password is set
2332 * 5. We enquire the user for a password
2333 */
2334
18843ecc 2335 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) {
0ba6f85e
LP
2336
2337 if (arg_try_empty_password) {
2338 /* Hmm, let's try an empty password now, but only once */
2339 arg_try_empty_password = false;
2340
2341 key_data = strdup("");
2342 if (!key_data)
2343 return log_oom();
2344
2345 key_data_size = 0;
2346 } else {
b6c0bd11 2347 /* Ask the user for a passphrase or recovery key only as last resort, if we have
0ba6f85e 2348 * nothing else to check for */
b6c0bd11
AAF
2349 if (passphrase_type == PASSPHRASE_NONE) {
2350 passphrase_type = check_registered_passwords(cd);
2351 if (passphrase_type == PASSPHRASE_NONE)
2352 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No passphrase or recovery key registered.");
2353 }
0ba6f85e 2354
b6c0bd11 2355 r = get_password(volume, source, until, tries == 0 && !arg_verify, passphrase_type, &passwords);
0ba6f85e
LP
2356 if (r == -EAGAIN)
2357 continue;
2358 if (r < 0)
2359 return r;
2360 }
260ab287
LP
2361 }
2362
f75cac37 2363 if (streq_ptr(arg_type, CRYPT_TCRYPT))
da2268f9 2364 r = attach_tcrypt(cd, volume, key_file, key_data, key_data_size, passwords, flags);
8cf3ca80 2365 else
da2268f9 2366 r = attach_luks_or_plain_or_bitlk(cd, volume, key_file, key_data, key_data_size, passwords, flags, until);
5f4bfe56 2367 if (r >= 0)
260ab287 2368 break;
6f177c7d
LP
2369 if (r != -EAGAIN)
2370 return r;
260ab287 2371
2424fb7e
LP
2372 /* Key not correct? Let's try again! */
2373
6f177c7d 2374 key_file = NULL;
7407f689
LP
2375 key_data = erase_and_free(key_data);
2376 key_data_size = 0;
2424fb7e 2377 arg_pkcs11_uri = mfree(arg_pkcs11_uri);
b997d111 2378 arg_pkcs11_uri_auto = false;
2bc5c425
LP
2379 arg_fido2_device = mfree(arg_fido2_device);
2380 arg_fido2_device_auto = false;
18843ecc
LP
2381 arg_tpm2_device = mfree(arg_tpm2_device);
2382 arg_tpm2_device_auto = false;
7f4e0805
LP
2383 }
2384
0ffff81a
LP
2385 if (arg_tries != 0 && tries >= arg_tries)
2386 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to activate; giving up.");
7f4e0805 2387
da2268f9 2388 } else if (streq(verb, "detach")) {
166015fa 2389 const char *volume = ASSERT_PTR(argv[optind + 1]);
7f4e0805 2390
5bae80bd
ZJS
2391 if (argc - optind >= 3)
2392 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "attach does not accept more than one argument.");
2393
da2268f9
LP
2394 if (!filename_is_valid(volume))
2395 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
7407f689 2396
da2268f9 2397 r = crypt_init_by_name(&cd, volume);
5f4bfe56 2398 if (r == -ENODEV) {
da2268f9 2399 log_info("Volume %s already inactive.", volume);
3a40f366 2400 return 0;
7f4e0805 2401 }
3a40f366 2402 if (r < 0)
ffe0da29 2403 return log_error_errno(r, "crypt_init_by_name() for volume '%s' failed: %m", volume);
7f4e0805 2404
efc3b12f 2405 cryptsetup_enable_logging(cd);
7f4e0805 2406
da2268f9 2407 r = crypt_deactivate(cd, volume);
3a40f366 2408 if (r < 0)
ffe0da29 2409 return log_error_errno(r, "Failed to deactivate '%s': %m", volume);
e23a0ce8 2410
0ffff81a 2411 } else
da2268f9 2412 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb %s.", verb);
e23a0ce8 2413
3a40f366 2414 return 0;
e23a0ce8 2415}
3a40f366
YW
2416
2417DEFINE_MAIN_FUNCTION(run);