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