]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/cryptsetup/cryptsetup.c
pkcs11-util: split pkcs11_token_login function
[thirdparty/systemd.git] / src / cryptsetup / cryptsetup.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
e23a0ce8 2
7f4e0805 3#include <errno.h>
07630cea 4#include <mntent.h>
07630cea 5#include <sys/mman.h>
ca78ad1d
ZJS
6#include <sys/stat.h>
7#include <sys/types.h>
8#include <unistd.h>
e23a0ce8 9
4f5dd394
LP
10#include "sd-device.h"
11
b5efdb8a 12#include "alloc-util.h"
4f5dd394 13#include "ask-password-api.h"
2bc5c425 14#include "cryptsetup-fido2.h"
1e2f3230 15#include "cryptsetup-keyfile.h"
08669709 16#include "cryptsetup-pkcs11.h"
18843ecc 17#include "cryptsetup-tpm2.h"
7407f689 18#include "cryptsetup-util.h"
4f5dd394 19#include "device-util.h"
71b25dea 20#include "efi-loader.h"
4f5dd394 21#include "escape.h"
8cf3ca80 22#include "fileio.h"
d3d49e76 23#include "fs-util.h"
ed4ad488 24#include "fstab-util.h"
08669709 25#include "hexdecoct.h"
2bc5c425 26#include "libfido2-util.h"
e23a0ce8 27#include "log.h"
3a40f366 28#include "main-func.h"
7407f689 29#include "memory-util.h"
4349cd7c 30#include "mount-util.h"
d8b4d14d 31#include "nulstr-util.h"
6bedfcbb 32#include "parse-util.h"
9eb977db 33#include "path-util.h"
08669709 34#include "pkcs11-util.h"
d8b4d14d 35#include "pretty-print.h"
e2c2f868 36#include "random-util.h"
07630cea 37#include "string-util.h"
21bc923a 38#include "strv.h"
18843ecc 39#include "tpm2-util.h"
7f4e0805 40
b3b4ebab
OK
41/* internal helper */
42#define ANY_LUKS "LUKS"
a9fc6406
DJL
43/* as in src/cryptsetup.h */
44#define CRYPT_SECTOR_SIZE 512
45#define CRYPT_MAX_SECTOR_SIZE 4096
b3b4ebab 46
6cc27c29 47static const char *arg_type = NULL; /* ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT, CRYPT_BITLK or CRYPT_PLAIN */
f75cac37
LP
48static char *arg_cipher = NULL;
49static unsigned arg_key_size = 0;
a9fc6406 50static unsigned arg_sector_size = CRYPT_SECTOR_SIZE;
f75cac37
LP
51static int arg_key_slot = CRYPT_ANY_SLOT;
52static unsigned arg_keyfile_size = 0;
dc0a3555 53static uint64_t arg_keyfile_offset = 0;
d3d49e76 54static bool arg_keyfile_erase = false;
0ba6f85e 55static bool arg_try_empty_password = false;
f75cac37 56static char *arg_hash = NULL;
7376e835 57static char *arg_header = NULL;
f75cac37
LP
58static unsigned arg_tries = 3;
59static bool arg_readonly = false;
60static bool arg_verify = false;
2cbca51a 61static AskPasswordFlags arg_ask_password_flags = 0;
f75cac37 62static bool arg_discards = false;
2c65512e
YW
63static bool arg_same_cpu_crypt = false;
64static bool arg_submit_from_crypt_cpus = false;
227acf00
JU
65static bool arg_no_read_workqueue = false;
66static bool arg_no_write_workqueue = false;
f75cac37
LP
67static bool arg_tcrypt_hidden = false;
68static bool arg_tcrypt_system = false;
52028838 69static bool arg_tcrypt_veracrypt = false;
f75cac37 70static char **arg_tcrypt_keyfiles = NULL;
4eac2773
MP
71static uint64_t arg_offset = 0;
72static uint64_t arg_skip = 0;
0864d311 73static usec_t arg_timeout = USEC_INFINITY;
08669709 74static char *arg_pkcs11_uri = NULL;
b997d111 75static bool arg_pkcs11_uri_auto = false;
2bc5c425
LP
76static char *arg_fido2_device = NULL;
77static bool arg_fido2_device_auto = false;
78static void *arg_fido2_cid = NULL;
79static size_t arg_fido2_cid_size = 0;
80static char *arg_fido2_rp_id = NULL;
18843ecc
LP
81static char *arg_tpm2_device = NULL;
82static bool arg_tpm2_device_auto = false;
83static uint32_t arg_tpm2_pcr_mask = UINT32_MAX;
cd5f57bd 84static bool arg_headless = false;
7f4e0805 85
3a40f366
YW
86STATIC_DESTRUCTOR_REGISTER(arg_cipher, freep);
87STATIC_DESTRUCTOR_REGISTER(arg_hash, freep);
88STATIC_DESTRUCTOR_REGISTER(arg_header, freep);
89STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles, strv_freep);
08669709 90STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri, freep);
2bc5c425
LP
91STATIC_DESTRUCTOR_REGISTER(arg_fido2_device, freep);
92STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid, freep);
93STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id, freep);
18843ecc 94STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
3a40f366 95
1fc76335
LP
96/* Options Debian's crypttab knows we don't:
97
1fc76335
LP
98 check=
99 checkargs=
8ced40c0
LP
100 noearly
101 loud
102 quiet
1fc76335 103 keyscript=
8ced40c0 104 initramfs
1fc76335
LP
105*/
106
7f4e0805 107static int parse_one_option(const char *option) {
fb4650aa
ZJS
108 const char *val;
109 int r;
110
7f4e0805
LP
111 assert(option);
112
113 /* Handled outside of this tool */
50d2eba2 114 if (STR_IN_SET(option, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
115 return 0;
116
117 if (startswith(option, "keyfile-timeout="))
7f4e0805
LP
118 return 0;
119
fb4650aa
ZJS
120 if ((val = startswith(option, "cipher="))) {
121 r = free_and_strdup(&arg_cipher, val);
122 if (r < 0)
4b93637f 123 return log_oom();
7f4e0805 124
fb4650aa 125 } else if ((val = startswith(option, "size="))) {
7f4e0805 126
fb4650aa
ZJS
127 r = safe_atou(val, &arg_key_size);
128 if (r < 0) {
129 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
7f4e0805
LP
130 return 0;
131 }
132
6131a78b
DH
133 if (arg_key_size % 8) {
134 log_error("size= not a multiple of 8, ignoring.");
135 return 0;
136 }
137
138 arg_key_size /= 8;
139
a9fc6406
DJL
140 } else if ((val = startswith(option, "sector-size="))) {
141
a9fc6406
DJL
142 r = safe_atou(val, &arg_sector_size);
143 if (r < 0) {
144 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
145 return 0;
146 }
147
148 if (arg_sector_size % 2) {
149 log_error("sector-size= not a multiple of 2, ignoring.");
150 return 0;
151 }
152
153 if (arg_sector_size < CRYPT_SECTOR_SIZE || arg_sector_size > CRYPT_MAX_SECTOR_SIZE) {
154 log_error("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE, CRYPT_MAX_SECTOR_SIZE);
155 return 0;
156 }
a9fc6406 157
8ced40c0
LP
158 } else if ((val = startswith(option, "key-slot=")) ||
159 (val = startswith(option, "keyslot="))) {
b4a11878 160
b3b4ebab 161 arg_type = ANY_LUKS;
fb4650aa
ZJS
162 r = safe_atoi(val, &arg_key_slot);
163 if (r < 0) {
164 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
b4a11878
CS
165 return 0;
166 }
167
fb4650aa 168 } else if ((val = startswith(option, "tcrypt-keyfile="))) {
8cf3ca80 169
f75cac37 170 arg_type = CRYPT_TCRYPT;
fb4650aa
ZJS
171 if (path_is_absolute(val)) {
172 if (strv_extend(&arg_tcrypt_keyfiles, val) < 0)
4b93637f
LP
173 return log_oom();
174 } else
fb4650aa 175 log_error("Key file path \"%s\" is not absolute. Ignoring.", val);
8cf3ca80 176
fb4650aa 177 } else if ((val = startswith(option, "keyfile-size="))) {
4271d823 178
fb4650aa
ZJS
179 r = safe_atou(val, &arg_keyfile_size);
180 if (r < 0) {
181 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
4271d823
TG
182 return 0;
183 }
184
fb4650aa 185 } else if ((val = startswith(option, "keyfile-offset="))) {
880a599e 186
d90874b4 187 r = safe_atou64(val, &arg_keyfile_offset);
fb4650aa
ZJS
188 if (r < 0) {
189 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
880a599e
TG
190 return 0;
191 }
192
d3d49e76
LP
193 } else if ((val = startswith(option, "keyfile-erase="))) {
194
195 r = parse_boolean(val);
196 if (r < 0) {
197 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
198 return 0;
199 }
200
201 arg_keyfile_erase = r;
202
203 } else if (streq(option, "keyfile-erase"))
204 arg_keyfile_erase = true;
205
206 else if ((val = startswith(option, "hash="))) {
fb4650aa
ZJS
207 r = free_and_strdup(&arg_hash, val);
208 if (r < 0)
4b93637f 209 return log_oom();
7f4e0805 210
fb4650aa 211 } else if ((val = startswith(option, "header="))) {
b3b4ebab 212 arg_type = ANY_LUKS;
7376e835 213
baaa35ad
ZJS
214 if (!path_is_absolute(val))
215 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
216 "Header path \"%s\" is not absolute, refusing.", val);
7376e835 217
baaa35ad
ZJS
218 if (arg_header)
219 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
220 "Duplicate header= option, refusing.");
7376e835 221
fb4650aa 222 arg_header = strdup(val);
7376e835
AC
223 if (!arg_header)
224 return log_oom();
225
fb4650aa 226 } else if ((val = startswith(option, "tries="))) {
7f4e0805 227
fb4650aa
ZJS
228 r = safe_atou(val, &arg_tries);
229 if (r < 0) {
230 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
7f4e0805
LP
231 return 0;
232 }
233
f75cac37
LP
234 } else if (STR_IN_SET(option, "readonly", "read-only"))
235 arg_readonly = true;
7f4e0805 236 else if (streq(option, "verify"))
f75cac37 237 arg_verify = true;
2cbca51a
SB
238 else if ((val = startswith(option, "password-echo="))) {
239 if (streq(val, "masked"))
240 arg_ask_password_flags &= ~(ASK_PASSWORD_ECHO|ASK_PASSWORD_SILENT);
241 else {
242 r = parse_boolean(val);
243 if (r < 0) {
244 log_warning_errno(r, "Invalid password-echo= option \"%s\", ignoring.", val);
245 return 0;
246 }
247
248 SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_ECHO, r);
249 SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_SILENT, !r);
250 }
251 } else if (STR_IN_SET(option, "allow-discards", "discard"))
f75cac37 252 arg_discards = true;
2c65512e
YW
253 else if (streq(option, "same-cpu-crypt"))
254 arg_same_cpu_crypt = true;
255 else if (streq(option, "submit-from-crypt-cpus"))
256 arg_submit_from_crypt_cpus = true;
227acf00
JU
257 else if (streq(option, "no-read-workqueue"))
258 arg_no_read_workqueue = true;
259 else if (streq(option, "no-write-workqueue"))
260 arg_no_write_workqueue = true;
260ab287 261 else if (streq(option, "luks"))
b3b4ebab 262 arg_type = ANY_LUKS;
6cc27c29
MF
263/* since cryptsetup 2.3.0 (Feb 2020) */
264#ifdef CRYPT_BITLK
265 else if (streq(option, "bitlk"))
266 arg_type = CRYPT_BITLK;
267#endif
8cf3ca80 268 else if (streq(option, "tcrypt"))
f75cac37 269 arg_type = CRYPT_TCRYPT;
8ced40c0 270 else if (STR_IN_SET(option, "tcrypt-hidden", "tcrypthidden")) {
f75cac37
LP
271 arg_type = CRYPT_TCRYPT;
272 arg_tcrypt_hidden = true;
8cf3ca80 273 } else if (streq(option, "tcrypt-system")) {
f75cac37
LP
274 arg_type = CRYPT_TCRYPT;
275 arg_tcrypt_system = true;
8ced40c0 276 } else if (STR_IN_SET(option, "tcrypt-veracrypt", "veracrypt")) {
52028838
GH
277 arg_type = CRYPT_TCRYPT;
278 arg_tcrypt_veracrypt = true;
53ac130b
LP
279 } else if (STR_IN_SET(option, "plain", "swap", "tmp") ||
280 startswith(option, "tmp="))
f75cac37 281 arg_type = CRYPT_PLAIN;
fb4650aa 282 else if ((val = startswith(option, "timeout="))) {
7f4e0805 283
0004f698 284 r = parse_sec_fix_0(val, &arg_timeout);
fb4650aa
ZJS
285 if (r < 0) {
286 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
7f4e0805
LP
287 return 0;
288 }
289
fb4650aa 290 } else if ((val = startswith(option, "offset="))) {
4eac2773 291
fb4650aa
ZJS
292 r = safe_atou64(val, &arg_offset);
293 if (r < 0)
294 return log_error_errno(r, "Failed to parse %s: %m", option);
4eac2773 295
fb4650aa 296 } else if ((val = startswith(option, "skip="))) {
4eac2773 297
fb4650aa
ZJS
298 r = safe_atou64(val, &arg_skip);
299 if (r < 0)
300 return log_error_errno(r, "Failed to parse %s: %m", option);
4eac2773 301
08669709
LP
302 } else if ((val = startswith(option, "pkcs11-uri="))) {
303
b997d111
LP
304 if (streq(val, "auto")) {
305 arg_pkcs11_uri = mfree(arg_pkcs11_uri);
306 arg_pkcs11_uri_auto = true;
307 } else {
308 if (!pkcs11_uri_valid(val))
309 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing");
08669709 310
b997d111
LP
311 r = free_and_strdup(&arg_pkcs11_uri, val);
312 if (r < 0)
313 return log_oom();
314
315 arg_pkcs11_uri_auto = false;
316 }
08669709 317
2bc5c425
LP
318 } else if ((val = startswith(option, "fido2-device="))) {
319
320 if (streq(val, "auto")) {
321 arg_fido2_device = mfree(arg_fido2_device);
322 arg_fido2_device_auto = true;
323 } else {
324 r = free_and_strdup(&arg_fido2_device, val);
325 if (r < 0)
326 return log_oom();
327
328 arg_fido2_device_auto = false;
329 }
330
331 } else if ((val = startswith(option, "fido2-cid="))) {
332
333 if (streq(val, "auto"))
334 arg_fido2_cid = mfree(arg_fido2_cid);
335 else {
336 _cleanup_free_ void *cid = NULL;
337 size_t cid_size;
338
f5fbe71d 339 r = unbase64mem(val, SIZE_MAX, &cid, &cid_size);
2bc5c425
LP
340 if (r < 0)
341 return log_error_errno(r, "Failed to decode FIDO2 CID data: %m");
342
343 free(arg_fido2_cid);
344 arg_fido2_cid = TAKE_PTR(cid);
345 arg_fido2_cid_size = cid_size;
346 }
347
348 /* Turn on FIDO2 as side-effect, if not turned on yet. */
349 if (!arg_fido2_device && !arg_fido2_device_auto)
350 arg_fido2_device_auto = true;
351
352 } else if ((val = startswith(option, "fido2-rp="))) {
353
354 r = free_and_strdup(&arg_fido2_rp_id, val);
355 if (r < 0)
356 return log_oom();
357
18843ecc
LP
358 } else if ((val = startswith(option, "tpm2-device="))) {
359
360 if (streq(val, "auto")) {
361 arg_tpm2_device = mfree(arg_tpm2_device);
362 arg_tpm2_device_auto = true;
363 } else {
364 r = free_and_strdup(&arg_tpm2_device, val);
365 if (r < 0)
366 return log_oom();
367
368 arg_tpm2_device_auto = false;
369 }
370
371 } else if ((val = startswith(option, "tpm2-pcrs="))) {
372
373 if (isempty(val))
374 arg_tpm2_pcr_mask = 0;
375 else {
376 uint32_t mask;
377
378 r = tpm2_parse_pcrs(val, &mask);
379 if (r < 0)
380 return r;
381
382 if (arg_tpm2_pcr_mask == UINT32_MAX)
383 arg_tpm2_pcr_mask = mask;
384 else
385 arg_tpm2_pcr_mask |= mask;
386 }
387
0ba6f85e
LP
388 } else if ((val = startswith(option, "try-empty-password="))) {
389
390 r = parse_boolean(val);
391 if (r < 0) {
392 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
393 return 0;
394 }
395
396 arg_try_empty_password = r;
397
398 } else if (streq(option, "try-empty-password"))
399 arg_try_empty_password = true;
cd5f57bd
LB
400 else if ((val = startswith(option, "headless="))) {
401
402 r = parse_boolean(val);
403 if (r < 0) {
404 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
405 return 0;
406 }
407
408 arg_headless = r;
409 } else if (streq(option, "headless"))
410 arg_headless = true;
0ba6f85e
LP
411
412 else if (!streq(option, "x-initrd.attach"))
fb4650aa 413 log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
7f4e0805
LP
414
415 return 0;
416}
417
418static int parse_options(const char *options) {
7f4e0805
LP
419 assert(options);
420
dd2fff3a
ZJS
421 for (;;) {
422 _cleanup_free_ char *word = NULL;
423 int r;
424
7bb553bb 425 r = extract_first_word(&options, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS | EXTRACT_UNESCAPE_SEPARATORS);
dd2fff3a 426 if (r < 0)
be36bc1e 427 return log_error_errno(r, "Failed to parse options: %m");
dd2fff3a
ZJS
428 if (r == 0)
429 break;
7f4e0805 430
dd2fff3a 431 r = parse_one_option(word);
7f4e0805
LP
432 if (r < 0)
433 return r;
434 }
435
4eac2773 436 /* sanity-check options */
9c5253ff
LP
437 if (arg_type && !streq(arg_type, CRYPT_PLAIN)) {
438 if (arg_offset != 0)
4eac2773 439 log_warning("offset= ignored with type %s", arg_type);
9c5253ff 440 if (arg_skip != 0)
4eac2773
MP
441 log_warning("skip= ignored with type %s", arg_type);
442 }
443
7f4e0805
LP
444 return 0;
445}
446
1ca208fb 447static char* disk_description(const char *path) {
f75cac37 448 static const char name_fields[] =
74b1c371
LP
449 "DM_NAME\0"
450 "ID_MODEL_FROM_DATABASE\0"
f75cac37 451 "ID_MODEL\0";
74b1c371 452
4afd3348 453 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
2c740afd 454 const char *i, *name;
b1a2da0a 455 struct stat st;
b1a2da0a
LP
456
457 assert(path);
458
459 if (stat(path, &st) < 0)
460 return NULL;
461
462 if (!S_ISBLK(st.st_mode))
463 return NULL;
464
930aa88f 465 if (sd_device_new_from_stat_rdev(&device, &st) < 0)
1ca208fb 466 return NULL;
b1a2da0a 467
fadd34dd
LP
468 if (sd_device_get_property_value(device, "ID_PART_ENTRY_NAME", &name) >= 0) {
469 _cleanup_free_ char *unescaped = NULL;
e437538f 470 ssize_t l;
fadd34dd
LP
471
472 /* ID_PART_ENTRY_NAME uses \x style escaping, using libblkid's blkid_encode_string(). Let's
473 * reverse this here to make the string more human friendly in case people embed spaces or
474 * other weird stuff. */
475
e437538f
ZJS
476 l = cunescape(name, UNESCAPE_RELAX, &unescaped);
477 if (l < 0) {
478 log_debug_errno(l, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
fadd34dd
LP
479 return NULL;
480 }
481
482 if (!isempty(unescaped) && !string_has_cc(unescaped, NULL))
483 return TAKE_PTR(unescaped);
484 }
485
486 /* These need no unescaping. */
2c740afd
YW
487 NULSTR_FOREACH(i, name_fields)
488 if (sd_device_get_property_value(device, i, &name) >= 0 &&
489 !isempty(name))
1ca208fb 490 return strdup(name);
b1a2da0a 491
1ca208fb 492 return NULL;
b1a2da0a
LP
493}
494
b61e476f 495static char *disk_mount_point(const char *label) {
e7d90b71 496 _cleanup_free_ char *device = NULL;
5862d652 497 _cleanup_endmntent_ FILE *f = NULL;
b61e476f
LP
498 struct mntent *m;
499
500 /* Yeah, we don't support native systemd unit files here for now */
501
090685b5
LP
502 device = strjoin("/dev/mapper/", label);
503 if (!device)
5862d652 504 return NULL;
b61e476f 505
ed4ad488 506 f = setmntent(fstab_path(), "re");
e0295d26 507 if (!f)
5862d652 508 return NULL;
b61e476f
LP
509
510 while ((m = getmntent(f)))
5862d652
ZJS
511 if (path_equal(m->mnt_fsname, device))
512 return strdup(m->mnt_dir);
b61e476f 513
5862d652 514 return NULL;
b61e476f
LP
515}
516
08669709
LP
517static char *friendly_disk_name(const char *src, const char *vol) {
518 _cleanup_free_ char *description = NULL, *mount_point = NULL;
519 char *name_buffer = NULL;
520 int r;
e7d90b71 521
e51b9486 522 assert(src);
08669709 523 assert(vol);
e7d90b71 524
e51b9486
HH
525 description = disk_description(src);
526 mount_point = disk_mount_point(vol);
527
08669709 528 /* If the description string is simply the volume name, then let's not show this twice */
ece174c5 529 if (description && streq(vol, description))
97b11eed 530 description = mfree(description);
e51b9486
HH
531
532 if (mount_point && description)
533 r = asprintf(&name_buffer, "%s (%s) on %s", description, vol, mount_point);
534 else if (mount_point)
535 r = asprintf(&name_buffer, "%s on %s", vol, mount_point);
536 else if (description)
537 r = asprintf(&name_buffer, "%s (%s)", description, vol);
08669709
LP
538 else
539 return strdup(vol);
e51b9486 540 if (r < 0)
08669709
LP
541 return NULL;
542
543 return name_buffer;
544}
545
546static int get_password(
547 const char *vol,
548 const char *src,
549 usec_t until,
550 bool accept_cached,
551 char ***ret) {
552
553 _cleanup_free_ char *friendly = NULL, *text = NULL, *disk_path = NULL;
554 _cleanup_strv_free_erase_ char **passwords = NULL;
555 char **p, *id;
556 int r = 0;
2cbca51a 557 AskPasswordFlags flags = arg_ask_password_flags | ASK_PASSWORD_PUSH_CACHE;
08669709
LP
558
559 assert(vol);
560 assert(src);
561 assert(ret);
562
cd5f57bd
LB
563 if (arg_headless)
564 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Password querying disabled via 'headless' option.");
565
08669709
LP
566 friendly = friendly_disk_name(src, vol);
567 if (!friendly)
e51b9486
HH
568 return log_oom();
569
08669709
LP
570 if (asprintf(&text, "Please enter passphrase for disk %s:", friendly) < 0)
571 return log_oom();
e51b9486 572
08669709
LP
573 disk_path = cescape(src);
574 if (!disk_path)
e7d90b71
JJ
575 return log_oom();
576
ea7e7c1e 577 id = strjoina("cryptsetup:", disk_path);
9fa1de96 578
8806bb4b 579 r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", "cryptsetup.passphrase", until,
1fa94a31 580 flags | (accept_cached*ASK_PASSWORD_ACCEPT_CACHED),
ab84f5b9 581 &passwords);
23bbb0de
MS
582 if (r < 0)
583 return log_error_errno(r, "Failed to query password: %m");
e7d90b71 584
f75cac37 585 if (arg_verify) {
ab84f5b9
ZJS
586 _cleanup_strv_free_erase_ char **passwords2 = NULL;
587
1602b008 588 assert(strv_length(passwords) == 1);
e7d90b71 589
08669709 590 if (asprintf(&text, "Please enter passphrase for disk %s (verification):", friendly) < 0)
ab84f5b9 591 return log_oom();
e7d90b71 592
ea7e7c1e 593 id = strjoina("cryptsetup-verification:", disk_path);
9fa1de96 594
1fa94a31 595 r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", "cryptsetup.passphrase", until, flags, &passwords2);
ab84f5b9
ZJS
596 if (r < 0)
597 return log_error_errno(r, "Failed to query verification password: %m");
e7d90b71
JJ
598
599 assert(strv_length(passwords2) == 1);
600
8bc6ade7
LP
601 if (!streq(passwords[0], passwords2[0]))
602 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN),
603 "Passwords did not match, retrying.");
e7d90b71
JJ
604 }
605
1602b008 606 strv_uniq(passwords);
e7d90b71 607
1602b008 608 STRV_FOREACH(p, passwords) {
e7d90b71
JJ
609 char *c;
610
f75cac37 611 if (strlen(*p)+1 >= arg_key_size)
e7d90b71
JJ
612 continue;
613
614 /* Pad password if necessary */
1602b008 615 c = new(char, arg_key_size);
ab84f5b9
ZJS
616 if (!c)
617 return log_oom();
e7d90b71 618
f75cac37 619 strncpy(c, *p, arg_key_size);
d3ad474f
LP
620 erase_and_free(*p);
621 *p = TAKE_PTR(c);
e7d90b71
JJ
622 }
623
ae2a15bc 624 *ret = TAKE_PTR(passwords);
1602b008 625
ab84f5b9 626 return 0;
e7d90b71
JJ
627}
628
1602b008
LP
629static int attach_tcrypt(
630 struct crypt_device *cd,
631 const char *name,
632 const char *key_file,
7407f689
LP
633 const void *key_data,
634 size_t key_data_size,
1602b008
LP
635 char **passwords,
636 uint32_t flags) {
637
8cf3ca80 638 int r = 0;
d3ad474f 639 _cleanup_(erase_and_freep) char *passphrase = NULL;
8cf3ca80
JJ
640 struct crypt_params_tcrypt params = {
641 .flags = CRYPT_TCRYPT_LEGACY_MODES,
f75cac37
LP
642 .keyfiles = (const char **)arg_tcrypt_keyfiles,
643 .keyfiles_count = strv_length(arg_tcrypt_keyfiles)
8cf3ca80
JJ
644 };
645
646 assert(cd);
647 assert(name);
7407f689 648 assert(key_file || key_data || !strv_isempty(passwords));
8cf3ca80 649
18843ecc 650 if (arg_pkcs11_uri || arg_pkcs11_uri_auto || arg_fido2_device || arg_fido2_device_auto || arg_tpm2_device || arg_tpm2_device_auto)
e514aa1e
FS
651 /* Ask for a regular password */
652 return log_error_errno(SYNTHETIC_ERRNO(EAGAIN),
18843ecc 653 "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
08669709 654
f75cac37 655 if (arg_tcrypt_hidden)
8cf3ca80
JJ
656 params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
657
f75cac37 658 if (arg_tcrypt_system)
8cf3ca80
JJ
659 params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
660
52028838
GH
661 if (arg_tcrypt_veracrypt)
662 params.flags |= CRYPT_TCRYPT_VERA_MODES;
52028838 663
7407f689
LP
664 if (key_data) {
665 params.passphrase = key_data;
666 params.passphrase_size = key_data_size;
667 } else {
668 if (key_file) {
669 r = read_one_line_file(key_file, &passphrase);
670 if (r < 0) {
671 log_error_errno(r, "Failed to read password file '%s': %m", key_file);
672 return -EAGAIN; /* log with the actual error, but return EAGAIN */
673 }
8cf3ca80 674
7407f689
LP
675 params.passphrase = passphrase;
676 } else
677 params.passphrase = passwords[0];
678
679 params.passphrase_size = strlen(params.passphrase);
680 }
8cf3ca80
JJ
681
682 r = crypt_load(cd, CRYPT_TCRYPT, &params);
683 if (r < 0) {
7407f689 684 if (r == -EPERM) {
cb6c9283 685 if (key_data)
7407f689 686 log_error_errno(r, "Failed to activate using discovered key. (Key not correct?)");
7407f689 687
cb6c9283 688 if (key_file)
7407f689 689 log_error_errno(r, "Failed to activate using password file '%s'. (Key data not correct?)", key_file);
cb6c9283
LP
690
691 return -EAGAIN; /* log the actual error, but return EAGAIN */
6f177c7d
LP
692 }
693
694 return log_error_errno(r, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd));
8cf3ca80
JJ
695 }
696
6f177c7d
LP
697 r = crypt_activate_by_volume_key(cd, name, NULL, 0, flags);
698 if (r < 0)
699 return log_error_errno(r, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd));
700
701 return 0;
8cf3ca80
JJ
702}
703
e2c2f868
LP
704static char *make_bindname(const char *volume) {
705 char *s;
706
707 if (asprintf(&s, "@%" PRIx64"/cryptsetup/%s", random_u64(), volume) < 0)
708 return NULL;
709
710 return s;
711}
712
8414cd48
LP
713static int make_security_device_monitor(sd_event *event, sd_device_monitor **ret) {
714 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
715 int r;
716
717 assert(ret);
718
719 r = sd_device_monitor_new(&monitor);
720 if (r < 0)
721 return log_error_errno(r, "Failed to allocate device monitor: %m");
722
723 r = sd_device_monitor_filter_add_match_tag(monitor, "security-device");
724 if (r < 0)
725 return log_error_errno(r, "Failed to configure device monitor: %m");
726
727 r = sd_device_monitor_attach_event(monitor, event);
728 if (r < 0)
729 return log_error_errno(r, "Failed to attach device monitor: %m");
730
731 r = sd_device_monitor_start(monitor, NULL, NULL);
732 if (r < 0)
733 return log_error_errno(r, "Failed to start device monitor: %m");
734
735 *ret = TAKE_PTR(monitor);
736 return 0;
737}
738
351716e1
OK
739static bool libcryptsetup_plugins_support(void) {
740#if HAVE_LIBCRYPTSETUP_PLUGINS
741 return crypt_token_external_path() != NULL;
742#else
743 return false;
744#endif
745}
746
747#if HAVE_LIBCRYPTSETUP_PLUGINS
748static int acquire_pins_from_env_variable(char ***ret_pins) {
749 char *e;
750 _cleanup_strv_free_erase_ char **pins = NULL;
751
752 assert(ret_pins);
753
754 e = getenv("PIN");
755 if (e) {
756 pins = strv_new(e);
757 if (!pins)
758 return log_oom();
759
760 string_erase(e);
761 if (unsetenv("PIN") < 0)
762 return log_error_errno(errno, "Failed to unset $PIN: %m");
763 }
764
765 *ret_pins = TAKE_PTR(pins);
766
767 return 0;
768}
769#endif
770
771static int attach_luks2_by_fido2(
772 struct crypt_device *cd,
773 const char *name,
774 usec_t until,
775 bool headless,
776 void *usrptr,
777 uint32_t activation_flags) {
778
779 int r = -EOPNOTSUPP;
780#if HAVE_LIBCRYPTSETUP_PLUGINS
781 char **p;
782 _cleanup_strv_free_erase_ char **pins = NULL;
783 AskPasswordFlags flags = ASK_PASSWORD_PUSH_CACHE | ASK_PASSWORD_ACCEPT_CACHED;
784
785 r = crypt_activate_by_token_pin(cd, name, "systemd-fido2", CRYPT_ANY_TOKEN, NULL, 0, usrptr, activation_flags);
786 if (r > 0) /* returns unlocked keyslot id on success */
787 r = 0;
788 if (r != -ENOANO) /* needs pin or pin is wrong */
789 return r;
790
791 r = acquire_pins_from_env_variable(&pins);
792 if (r < 0)
793 return r;
794
795 STRV_FOREACH(p, pins) {
796 r = crypt_activate_by_token_pin(cd, name, "systemd-fido2", CRYPT_ANY_TOKEN, *p, strlen(*p), usrptr, activation_flags);
797 if (r > 0) /* returns unlocked keyslot id on success */
798 r = 0;
799 if (r != -ENOANO) /* needs pin or pin is wrong */
800 return r;
801 }
802
803 if (headless)
804 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
805
806 pins = strv_free_erase(pins);
807 r = ask_password_auto("Please enter security token PIN:", "drive-harddisk", NULL, "fido2-pin", "cryptsetup.fido2-pin", until, flags, &pins);
808 if (r < 0)
809 return r;
810
811 STRV_FOREACH(p, pins) {
812 r = crypt_activate_by_token_pin(cd, name, "systemd-fido2", CRYPT_ANY_TOKEN, *p, strlen(*p), usrptr, activation_flags);
813 if (r > 0) /* returns unlocked keyslot id on success */
814 r = 0;
815 if (r != -ENOANO) /* needs pin or pin is wrong */
816 return r;
817 }
818
819 flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
820 for (;;) {
821 pins = strv_free_erase(pins);
822 r = ask_password_auto("Please enter security token PIN:", "drive-harddisk", NULL, "fido2-pin", "cryptsetup.fido2-pin", until, flags, &pins);
823 if (r < 0)
824 return r;
825
826 STRV_FOREACH(p, pins) {
827 r = crypt_activate_by_token_pin(cd, name, "systemd-fido2", CRYPT_ANY_TOKEN, *p, strlen(*p), usrptr, activation_flags);
828 if (r > 0) /* returns unlocked keyslot id on success */
829 r = 0;
830 if (r != -ENOANO) /* needs pin or pin is wrong */
831 return r;
832 }
833 }
834#endif
835 return r;
836}
837
2bc5c425
LP
838static int attach_luks_or_plain_or_bitlk_by_fido2(
839 struct crypt_device *cd,
840 const char *name,
841 const char *key_file,
842 const void *key_data,
843 size_t key_data_size,
844 usec_t until,
845 uint32_t flags,
846 bool pass_volume_key) {
847
848 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
849 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
850 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
851 _cleanup_free_ void *discovered_salt = NULL, *discovered_cid = NULL;
351716e1 852 size_t discovered_salt_size, discovered_cid_size, decrypted_key_size, cid_size = 0;
2bc5c425
LP
853 _cleanup_free_ char *friendly = NULL, *discovered_rp_id = NULL;
854 int keyslot = arg_key_slot, r;
351716e1
OK
855 const char *rp_id = NULL;
856 const void *cid = NULL;
cde2f860 857 Fido2EnrollFlags required;
351716e1 858 bool use_libcryptsetup_plugin = libcryptsetup_plugins_support();
2bc5c425
LP
859
860 assert(cd);
861 assert(name);
862 assert(arg_fido2_device || arg_fido2_device_auto);
863
864 if (arg_fido2_cid) {
865 if (!key_file && !key_data)
8205c151
ZJS
866 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
867 "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
2bc5c425
LP
868
869 rp_id = arg_fido2_rp_id;
870 cid = arg_fido2_cid;
871 cid_size = arg_fido2_cid_size;
8205c151 872
3cc00ba6
LP
873 /* For now and for compatibility, if the user explicitly configured FIDO2 support and we do
874 * not read FIDO2 metadata off the LUKS2 header, default to the systemd 248 logic, where we
875 * use PIN + UP when needed, and do not configure UV at all. Eventually, we should make this
876 * explicitly configurable. */
877 required = FIDO2ENROLL_PIN_IF_NEEDED | FIDO2ENROLL_UP_IF_NEEDED | FIDO2ENROLL_UV_OMIT;
351716e1 878 } else if (!use_libcryptsetup_plugin) {
2bc5c425
LP
879 r = find_fido2_auto_data(
880 cd,
881 &discovered_rp_id,
882 &discovered_salt,
883 &discovered_salt_size,
884 &discovered_cid,
885 &discovered_cid_size,
cde2f860
LB
886 &keyslot,
887 &required);
2bc5c425
LP
888
889 if (IN_SET(r, -ENOTUNIQ, -ENXIO))
890 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
891 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
892 if (r < 0)
893 return r;
894
9d59f5b2 895 if ((required & (FIDO2ENROLL_PIN | FIDO2ENROLL_UP | FIDO2ENROLL_UV)) && arg_headless)
cde2f860 896 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG),
06f08719 897 "Local verification is required to unlock this volume, but the 'headless' parameter was set.");
cde2f860 898
2bc5c425
LP
899 rp_id = discovered_rp_id;
900 key_data = discovered_salt;
901 key_data_size = discovered_salt_size;
902 cid = discovered_cid;
903 cid_size = discovered_cid_size;
904 }
905
906 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
907 if (!friendly)
908 return log_oom();
909
910 for (;;) {
911 bool processed = false;
912
351716e1
OK
913 if (use_libcryptsetup_plugin && !arg_fido2_cid) {
914 r = attach_luks2_by_fido2(cd, name, until, arg_headless, arg_fido2_device, flags);
915 if (IN_SET(r, -ENOTUNIQ, -ENXIO, -ENOENT))
916 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
917 "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
918
919 } else {
920 r = acquire_fido2_key(
921 name,
922 friendly,
923 arg_fido2_device,
924 rp_id,
925 cid, cid_size,
926 key_file, arg_keyfile_size, arg_keyfile_offset,
927 key_data, key_data_size,
928 until,
929 arg_headless,
930 required,
931 &decrypted_key, &decrypted_key_size,
932 arg_ask_password_flags);
933 if (r >= 0)
934 break;
935 }
936
2bc5c425
LP
937 if (r != -EAGAIN) /* EAGAIN means: token not found */
938 return r;
939
940 if (!monitor) {
941 /* We didn't find the token. In this case, watch for it via udev. Let's
942 * create an event loop and monitor first. */
943
944 assert(!event);
945
946 r = sd_event_default(&event);
947 if (r < 0)
948 return log_error_errno(r, "Failed to allocate event loop: %m");
949
950 r = make_security_device_monitor(event, &monitor);
951 if (r < 0)
952 return r;
953
954 log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly);
955
956 /* Let's immediately rescan in case the token appeared in the time we needed
957 * to create and configure the monitor */
958 continue;
959 }
960
961 for (;;) {
962 /* Wait for one event, and then eat all subsequent events until there are no
963 * further ones */
964 r = sd_event_run(event, processed ? 0 : UINT64_MAX);
965 if (r < 0)
966 return log_error_errno(r, "Failed to run event loop: %m");
967 if (r == 0)
968 break;
969
970 processed = true;
971 }
972
973 log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
974 }
975
976 if (pass_volume_key)
977 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
978 else {
979 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
980
981 /* Before using this key as passphrase we base64 encode it, for compat with homed */
982
983 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
984 if (r < 0)
985 return log_oom();
986
987 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
988 }
989 if (r == -EPERM) {
990 log_error_errno(r, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
991 return -EAGAIN; /* log actual error, but return EAGAIN */
992 }
993 if (r < 0)
994 return log_error_errno(r, "Failed to activate with FIDO2 acquired key: %m");
995
996 return 0;
997}
998
b8c80b56
LP
999static int attach_luks_or_plain_or_bitlk_by_pkcs11(
1000 struct crypt_device *cd,
1001 const char *name,
1002 const char *key_file,
1003 const void *key_data,
1004 size_t key_data_size,
1005 usec_t until,
1006 uint32_t flags,
1007 bool pass_volume_key) {
1008
1009 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1010 _cleanup_free_ char *friendly = NULL, *discovered_uri = NULL;
1011 size_t decrypted_key_size = 0, discovered_key_size = 0;
1012 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1013 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1014 _cleanup_free_ void *discovered_key = NULL;
1015 int keyslot = arg_key_slot, r;
1016 const char *uri;
1017
1018 assert(cd);
1019 assert(name);
1020 assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
1021
1022 if (arg_pkcs11_uri_auto) {
1023 r = find_pkcs11_auto_data(cd, &discovered_uri, &discovered_key, &discovered_key_size, &keyslot);
1024 if (IN_SET(r, -ENOTUNIQ, -ENXIO))
1025 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1026 "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1027 if (r < 0)
1028 return r;
1029
1030 uri = discovered_uri;
1031 key_data = discovered_key;
1032 key_data_size = discovered_key_size;
1033 } else {
1034 uri = arg_pkcs11_uri;
1035
1036 if (!key_file && !key_data)
1037 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing.");
1038 }
1039
1040 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1041 if (!friendly)
1042 return log_oom();
1043
1044 for (;;) {
1045 bool processed = false;
1046
1047 r = decrypt_pkcs11_key(
1048 name,
1049 friendly,
1050 uri,
1051 key_file, arg_keyfile_size, arg_keyfile_offset,
1052 key_data, key_data_size,
1053 until,
cd5f57bd 1054 arg_headless,
b8c80b56
LP
1055 &decrypted_key, &decrypted_key_size);
1056 if (r >= 0)
1057 break;
1058 if (r != -EAGAIN) /* EAGAIN means: token not found */
1059 return r;
1060
1061 if (!monitor) {
1062 /* We didn't find the token. In this case, watch for it via udev. Let's
1063 * create an event loop and monitor first. */
1064
1065 assert(!event);
1066
1067 r = sd_event_default(&event);
1068 if (r < 0)
1069 return log_error_errno(r, "Failed to allocate event loop: %m");
1070
1071 r = make_security_device_monitor(event, &monitor);
1072 if (r < 0)
1073 return r;
1074
1075 log_notice("Security token %s not present for unlocking volume %s, please plug it in.",
1076 uri, friendly);
1077
1078 /* Let's immediately rescan in case the token appeared in the time we needed
1079 * to create and configure the monitor */
1080 continue;
1081 }
1082
1083 for (;;) {
1084 /* Wait for one event, and then eat all subsequent events until there are no
1085 * further ones */
1086 r = sd_event_run(event, processed ? 0 : UINT64_MAX);
1087 if (r < 0)
1088 return log_error_errno(r, "Failed to run event loop: %m");
1089 if (r == 0)
1090 break;
1091
1092 processed = true;
1093 }
1094
1095 log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
1096 }
1097
1098 if (pass_volume_key)
1099 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
1100 else {
1101 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
1102
1103 /* Before using this key as passphrase we base64 encode it. Why? For compatibility
1104 * with homed's PKCS#11 hookup: there we want to use the key we acquired through
1105 * PKCS#11 for other authentication/decryption mechanisms too, and some of them do
1106 * not not take arbitrary binary blobs, but require NUL-terminated strings — most
1107 * importantly UNIX password hashes. Hence, for compatibility we want to use a string
1108 * without embedded NUL here too, and that's easiest to generate from a binary blob
1109 * via base64 encoding. */
1110
1111 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1112 if (r < 0)
1113 return log_oom();
1114
1115 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
1116 }
1117 if (r == -EPERM) {
1118 log_error_errno(r, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
1119 return -EAGAIN; /* log actual error, but return EAGAIN */
1120 }
1121 if (r < 0)
1122 return log_error_errno(r, "Failed to activate with PKCS#11 acquired key: %m");
1123
1124 return 0;
1125}
1126
18843ecc
LP
1127static int make_tpm2_device_monitor(sd_event *event, sd_device_monitor **ret) {
1128 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1129 int r;
1130
1131 assert(ret);
1132
1133 r = sd_device_monitor_new(&monitor);
1134 if (r < 0)
1135 return log_error_errno(r, "Failed to allocate device monitor: %m");
1136
1137 r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "tpmrm", NULL);
1138 if (r < 0)
1139 return log_error_errno(r, "Failed to configure device monitor: %m");
1140
1141 r = sd_device_monitor_attach_event(monitor, event);
1142 if (r < 0)
1143 return log_error_errno(r, "Failed to attach device monitor: %m");
1144
1145 r = sd_device_monitor_start(monitor, NULL, NULL);
1146 if (r < 0)
1147 return log_error_errno(r, "Failed to start device monitor: %m");
1148
1149 *ret = TAKE_PTR(monitor);
1150 return 0;
1151}
1152
d1ae38d8
OK
1153static int attach_luks2_by_tpm2(
1154 struct crypt_device *cd,
1155 const char *name,
1156 uint32_t flags) {
1157
1158#if HAVE_LIBCRYPTSETUP_PLUGINS
1159 int r;
1160
1161 systemd_tpm2_plugin_params params = {
1162 .search_pcr_mask = arg_tpm2_pcr_mask,
1163 .device = arg_tpm2_device
1164 };
1165
1166 if (crypt_token_external_path() == NULL)
1167 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1168 "Libcryptsetup has external plugins support disabled.");
1169
1170 r = crypt_activate_by_token_pin(cd, name, "systemd-tpm2", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
1171 if (r > 0) /* returns unlocked keyslot id on success */
1172 r = 0;
1173
1174 return r;
1175#else
1176 return -EOPNOTSUPP;
1177#endif
1178}
1179
18843ecc
LP
1180static int attach_luks_or_plain_or_bitlk_by_tpm2(
1181 struct crypt_device *cd,
1182 const char *name,
1183 const char *key_file,
1184 const void *key_data,
1185 size_t key_data_size,
1186 usec_t until,
1187 uint32_t flags,
1188 bool pass_volume_key) {
1189
1190 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1191 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1192 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1193 _cleanup_free_ char *friendly = NULL;
1194 int keyslot = arg_key_slot, r;
67e9c83b 1195 size_t decrypted_key_size;
18843ecc
LP
1196
1197 assert(cd);
1198 assert(name);
1199 assert(arg_tpm2_device || arg_tpm2_device_auto);
1200
1201 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1202 if (!friendly)
1203 return log_oom();
1204
1205 for (;;) {
1206 bool processed = false;
1207
1208 if (key_file || key_data) {
1209 /* If key data is specified, use that */
1210
1211 r = acquire_tpm2_key(
1212 name,
1213 arg_tpm2_device,
1214 arg_tpm2_pcr_mask == UINT32_MAX ? TPM2_PCR_MASK_DEFAULT : arg_tpm2_pcr_mask,
07697bfe 1215 UINT16_MAX,
18843ecc
LP
1216 key_file, arg_keyfile_size, arg_keyfile_offset,
1217 key_data, key_data_size,
1218 NULL, 0, /* we don't know the policy hash */
1219 &decrypted_key, &decrypted_key_size);
1220 if (r >= 0)
1221 break;
cad10544
LP
1222 if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
1223 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");
18843ecc
LP
1224 if (r != -EAGAIN) /* EAGAIN means: no tpm2 chip found */
1225 return r;
1226 } else {
d1ae38d8
OK
1227 r = attach_luks2_by_tpm2(cd, name, flags);
1228 /* EAGAIN means: no tpm2 chip found
1229 * EOPNOTSUPP means: no libcryptsetup plugins support */
1230 if (r == -ENXIO)
1231 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1232 "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
1233 if (r == -ENOENT)
1234 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1235 "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
1236 if (!IN_SET(r, -EOPNOTSUPP, -EAGAIN))
1237 return r;
1238 }
1239
1240 if (r == -EOPNOTSUPP) {
18843ecc
LP
1241 _cleanup_free_ void *blob = NULL, *policy_hash = NULL;
1242 size_t blob_size, policy_hash_size;
1243 bool found_some = false;
1244 int token = 0; /* first token to look at */
1245
1246 /* If no key data is specified, look for it in the header. In order to support
1247 * software upgrades we'll iterate through all suitable tokens, maybe one of them
1248 * works. */
1249
1250 for (;;) {
1251 uint32_t pcr_mask;
07697bfe 1252 uint16_t pcr_bank;
18843ecc
LP
1253
1254 r = find_tpm2_auto_data(
1255 cd,
1256 arg_tpm2_pcr_mask, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1257 token, /* search for the token with this index, or any later index than this */
1258 &pcr_mask,
07697bfe 1259 &pcr_bank,
18843ecc
LP
1260 &blob, &blob_size,
1261 &policy_hash, &policy_hash_size,
1262 &keyslot,
1263 &token);
c26f7dd9 1264 if (r == -ENXIO)
7802194a 1265 /* No further TPM2 tokens found in the LUKS2 header. */
c26f7dd9
ZJS
1266 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1267 found_some
1268 ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
1269 : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
cad10544
LP
1270 if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
1271 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");
18843ecc
LP
1272 if (r < 0)
1273 return r;
1274
1275 found_some = true;
1276
1277 r = acquire_tpm2_key(
1278 name,
1279 arg_tpm2_device,
1280 pcr_mask,
07697bfe 1281 pcr_bank,
18843ecc
LP
1282 NULL, 0, 0, /* no key file */
1283 blob, blob_size,
1284 policy_hash, policy_hash_size,
1285 &decrypted_key, &decrypted_key_size);
1286 if (r != -EPERM)
1287 break;
1288
1289 token++; /* try a different token next time */
1290 }
1291
1292 if (r >= 0)
1293 break;
1294 if (r != -EAGAIN) /* EAGAIN means: no tpm2 chip found */
1295 return r;
1296 }
1297
1298 if (!monitor) {
1299 /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
1300 * an event loop and monitor first. */
1301
1302 assert(!event);
1303
71b25dea
LP
1304 if (is_efi_boot() && !efi_has_tpm2())
1305 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
1306 "No TPM2 hardware discovered and EFI bios indicates no support for it either, assuming TPM2-less system, falling back to traditional unocking.");
1307
18843ecc
LP
1308 r = sd_event_default(&event);
1309 if (r < 0)
1310 return log_error_errno(r, "Failed to allocate event loop: %m");
1311
1312 r = make_tpm2_device_monitor(event, &monitor);
1313 if (r < 0)
1314 return r;
1315
1316 log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly);
1317
1318 /* Let's immediately rescan in case the device appeared in the time we needed
1319 * to create and configure the monitor */
1320 continue;
1321 }
1322
1323 for (;;) {
1324 /* Wait for one event, and then eat all subsequent events until there are no
1325 * 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)
1330 break;
1331
1332 processed = true;
1333 }
1334
1335 log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
1336 }
26fbc5aa 1337 assert(decrypted_key);
18843ecc
LP
1338
1339 if (pass_volume_key)
1340 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
1341 else {
1342 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
1343
1344 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1345
1346 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1347 if (r < 0)
1348 return log_oom();
1349
1350 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
1351 }
1352 if (r == -EPERM) {
1353 log_error_errno(r, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
1354 return -EAGAIN; /* log actual error, but return EAGAIN */
1355 }
1356 if (r < 0)
1357 return log_error_errno(r, "Failed to activate with TPM2 acquired key: %m");
1358
1359 return 0;
1360}
1361
b8c80b56
LP
1362static int attach_luks_or_plain_or_bitlk_by_key_data(
1363 struct crypt_device *cd,
1364 const char *name,
1365 const void *key_data,
1366 size_t key_data_size,
1367 uint32_t flags,
1368 bool pass_volume_key) {
1369
1370 int r;
1371
1372 assert(cd);
1373 assert(name);
1374 assert(key_data);
1375
1376 if (pass_volume_key)
1377 r = crypt_activate_by_volume_key(cd, name, key_data, key_data_size, flags);
1378 else
1379 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, key_data, key_data_size, flags);
1380 if (r == -EPERM) {
1381 log_error_errno(r, "Failed to activate. (Key incorrect?)");
1382 return -EAGAIN; /* Log actual error, but return EAGAIN */
1383 }
1384 if (r < 0)
1385 return log_error_errno(r, "Failed to activate: %m");
1386
1387 return 0;
1388}
1389
1390static int attach_luks_or_plain_or_bitlk_by_key_file(
1391 struct crypt_device *cd,
1392 const char *name,
1393 const char *key_file,
1394 uint32_t flags,
1395 bool pass_volume_key) {
1396
1397 _cleanup_(erase_and_freep) char *kfdata = NULL;
1398 _cleanup_free_ char *bindname = NULL;
1399 size_t kfsize;
1400 int r;
1401
1402 assert(cd);
1403 assert(name);
1404 assert(key_file);
1405
1406 /* If we read the key via AF_UNIX, make this client recognizable */
1407 bindname = make_bindname(name);
1408 if (!bindname)
1409 return log_oom();
1410
1411 r = read_full_file_full(
1412 AT_FDCWD, key_file,
1413 arg_keyfile_offset == 0 ? UINT64_MAX : arg_keyfile_offset,
1414 arg_keyfile_size == 0 ? SIZE_MAX : arg_keyfile_size,
1415 READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
1416 bindname,
1417 &kfdata, &kfsize);
871f35af
LP
1418 if (r == -E2BIG) {
1419 log_error_errno(r, "Failed to activate, key file '%s' too large.", key_file);
1420 return -EAGAIN;
1421 }
b8c80b56
LP
1422 if (r == -ENOENT) {
1423 log_error_errno(r, "Failed to activate, key file '%s' missing.", key_file);
1424 return -EAGAIN; /* Log actual error, but return EAGAIN */
1425 }
abc50cf6
LP
1426 if (r < 0)
1427 return log_error_errno(r, "Failed to read key file '%s': %m", key_file);
b8c80b56
LP
1428
1429 if (pass_volume_key)
1430 r = crypt_activate_by_volume_key(cd, name, kfdata, kfsize, flags);
1431 else
1432 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, kfdata, kfsize, flags);
1433 if (r == -EPERM) {
1434 log_error_errno(r, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file);
1435 return -EAGAIN; /* Log actual error, but return EAGAIN */
1436 }
1437 if (r < 0)
1438 return log_error_errno(r, "Failed to activate with key file '%s': %m", key_file);
1439
1440 return 0;
1441}
1442
1443static int attach_luks_or_plain_or_bitlk_by_passphrase(
1444 struct crypt_device *cd,
1445 const char *name,
1446 char **passwords,
1447 uint32_t flags,
1448 bool pass_volume_key) {
1449
1450 char **p;
1451 int r;
1452
1453 assert(cd);
1454 assert(name);
1455
1456 r = -EINVAL;
1457 STRV_FOREACH(p, passwords) {
1458 if (pass_volume_key)
1459 r = crypt_activate_by_volume_key(cd, name, *p, arg_key_size, flags);
1460 else
1461 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, *p, strlen(*p), flags);
1462 if (r >= 0)
1463 break;
1464 }
1465 if (r == -EPERM) {
1466 log_error_errno(r, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
1467 return -EAGAIN; /* log actual error, but return EAGAIN */
1468 }
1469 if (r < 0)
1470 return log_error_errno(r, "Failed to activate with specified passphrase: %m");
1471
1472 return 0;
1473}
1474
6cc27c29 1475static int attach_luks_or_plain_or_bitlk(
9c5253ff
LP
1476 struct crypt_device *cd,
1477 const char *name,
1478 const char *key_file,
7407f689
LP
1479 const void *key_data,
1480 size_t key_data_size,
9c5253ff 1481 char **passwords,
08669709
LP
1482 uint32_t flags,
1483 usec_t until) {
9c5253ff 1484
10fb4e35 1485 bool pass_volume_key = false;
b8c80b56 1486 int r;
10fb4e35
JJ
1487
1488 assert(cd);
1489 assert(name);
10fb4e35 1490
2e4beb87 1491 if ((!arg_type && !crypt_get_type(cd)) || streq_ptr(arg_type, CRYPT_PLAIN)) {
4eac2773
MP
1492 struct crypt_params_plain params = {
1493 .offset = arg_offset,
1494 .skip = arg_skip,
a9fc6406 1495 .sector_size = arg_sector_size,
4eac2773 1496 };
10fb4e35
JJ
1497 const char *cipher, *cipher_mode;
1498 _cleanup_free_ char *truncated_cipher = NULL;
1499
b8c80b56 1500 if (streq_ptr(arg_hash, "plain"))
10fb4e35 1501 /* plain isn't a real hash type. it just means "use no hash" */
b8c80b56
LP
1502 params.hash = NULL;
1503 else if (arg_hash)
1504 params.hash = arg_hash;
1505 else if (!key_file)
1506 /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
1507 * file is provided */
10fb4e35
JJ
1508 params.hash = "ripemd160";
1509
f75cac37 1510 if (arg_cipher) {
10fb4e35
JJ
1511 size_t l;
1512
f75cac37
LP
1513 l = strcspn(arg_cipher, "-");
1514 truncated_cipher = strndup(arg_cipher, l);
10fb4e35
JJ
1515 if (!truncated_cipher)
1516 return log_oom();
1517
1518 cipher = truncated_cipher;
f75cac37 1519 cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain";
10fb4e35
JJ
1520 } else {
1521 cipher = "aes";
1522 cipher_mode = "cbc-essiv:sha256";
1523 }
1524
aed68083 1525 /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
6131a78b 1526 arg_keyfile_size = arg_key_size;
10fb4e35 1527
30747265 1528 /* In contrast to what the name crypt_format() might suggest this doesn't actually format
aed68083 1529 * anything, it just configures encryption parameters when used for plain mode. */
1602b008 1530 r = crypt_format(cd, CRYPT_PLAIN, cipher, cipher_mode, NULL, NULL, arg_keyfile_size, &params);
2e4beb87
MB
1531 if (r < 0)
1532 return log_error_errno(r, "Loading of cryptographic parameters failed: %m");
10fb4e35
JJ
1533
1534 /* hash == NULL implies the user passed "plain" */
b8c80b56 1535 pass_volume_key = !params.hash;
10fb4e35 1536 }
10fb4e35
JJ
1537
1538 log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
1539 crypt_get_cipher(cd),
1540 crypt_get_cipher_mode(cd),
1541 crypt_get_volume_key_size(cd)*8,
1542 crypt_get_device_name(cd));
1543
18843ecc
LP
1544 if (arg_tpm2_device || arg_tpm2_device_auto)
1545 return attach_luks_or_plain_or_bitlk_by_tpm2(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
2bc5c425
LP
1546 if (arg_fido2_device || arg_fido2_device_auto)
1547 return attach_luks_or_plain_or_bitlk_by_fido2(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
b8c80b56
LP
1548 if (arg_pkcs11_uri || arg_pkcs11_uri_auto)
1549 return attach_luks_or_plain_or_bitlk_by_pkcs11(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
1550 if (key_data)
1551 return attach_luks_or_plain_or_bitlk_by_key_data(cd, name, key_data, key_data_size, flags, pass_volume_key);
1552 if (key_file)
1553 return attach_luks_or_plain_or_bitlk_by_key_file(cd, name, key_file, flags, pass_volume_key);
10fb4e35 1554
b8c80b56 1555 return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
10fb4e35
JJ
1556}
1557
dd5e696d 1558static int help(void) {
37ec0fdd
LP
1559 _cleanup_free_ char *link = NULL;
1560 int r;
1561
1562 r = terminal_urlify_man("systemd-cryptsetup@.service", "8", &link);
1563 if (r < 0)
1564 return log_oom();
dd5e696d
LP
1565
1566 printf("%s attach VOLUME SOURCEDEVICE [PASSWORD] [OPTIONS]\n"
1567 "%s detach VOLUME\n\n"
37ec0fdd 1568 "Attaches or detaches an encrypted block device.\n"
bc556335
DDM
1569 "\nSee the %s for details.\n",
1570 program_invocation_short_name,
1571 program_invocation_short_name,
1572 link);
dd5e696d
LP
1573
1574 return 0;
1575}
1576
d5d1ae15
LP
1577static uint32_t determine_flags(void) {
1578 uint32_t flags = 0;
1579
1580 if (arg_readonly)
1581 flags |= CRYPT_ACTIVATE_READONLY;
1582
1583 if (arg_discards)
1584 flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
1585
1586 if (arg_same_cpu_crypt)
1587 flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
1588
1589 if (arg_submit_from_crypt_cpus)
1590 flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
1591
227acf00
JU
1592 if (arg_no_read_workqueue)
1593 flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
1594
1595 if (arg_no_write_workqueue)
1596 flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
1597
408c81f6
MS
1598#ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
1599 /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
1600 /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
1601 flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF;
1602#endif
1603
d5d1ae15
LP
1604 return flags;
1605}
1606
d3d49e76
LP
1607static void remove_and_erasep(const char **p) {
1608 int r;
1609
1610 if (!*p)
1611 return;
1612
1613 r = unlinkat_deallocate(AT_FDCWD, *p, UNLINK_ERASE);
1614 if (r < 0 && r != -ENOENT)
1615 log_warning_errno(r, "Unable to erase key file '%s', ignoring: %m", *p);
1616}
1617
3a40f366 1618static int run(int argc, char *argv[]) {
294bd454 1619 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
da2268f9 1620 const char *verb;
3a40f366 1621 int r;
e23a0ce8 1622
3a40f366
YW
1623 if (argc <= 1)
1624 return help();
dd5e696d 1625
d7a0f1f4
FS
1626 if (argc < 3)
1627 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1628 "This program requires at least two arguments.");
e23a0ce8 1629
d2acb93d 1630 log_setup();
e23a0ce8 1631
2f678640 1632 cryptsetup_enable_logging(NULL);
568a8404 1633
4c12626c
LP
1634 umask(0022);
1635
da2268f9
LP
1636 verb = argv[1];
1637
1638 if (streq(verb, "attach")) {
d3d49e76 1639 _cleanup_(remove_and_erasep) const char *destroy_key_file = NULL;
7407f689 1640 _cleanup_(erase_and_freep) void *key_data = NULL;
da2268f9
LP
1641 const char *volume, *source, *key_file, *options;
1642 crypt_status_info status;
7407f689 1643 size_t key_data_size = 0;
da2268f9
LP
1644 uint32_t flags = 0;
1645 unsigned tries;
1646 usec_t until;
7f4e0805 1647
b61e476f
LP
1648 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [PASSWORD] [OPTIONS] */
1649
0ffff81a
LP
1650 if (argc < 4)
1651 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "attach requires at least two arguments.");
7f4e0805 1652
da2268f9
LP
1653 volume = argv[2];
1654 source = argv[3];
1655 key_file = argc >= 5 && !STR_IN_SET(argv[4], "", "-", "none") ? argv[4] : NULL;
1656 options = argc >= 6 && !STR_IN_SET(argv[5], "", "-", "none") ? argv[5] : NULL;
7407f689 1657
da2268f9
LP
1658 if (!filename_is_valid(volume))
1659 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
1660
1661 if (key_file && !path_is_absolute(key_file)) {
1662 log_warning("Password file path '%s' is not absolute. Ignoring.", key_file);
1663 key_file = NULL;
7f4e0805
LP
1664 }
1665
da2268f9
LP
1666 if (options) {
1667 r = parse_options(options);
3a40f366
YW
1668 if (r < 0)
1669 return r;
74b1c371 1670 }
e23a0ce8 1671
7bb553bb 1672 log_debug("%s %s ← %s type=%s cipher=%s", __func__,
da2268f9 1673 volume, source, strempty(arg_type), strempty(arg_cipher));
7bb553bb 1674
b853f6e9 1675 /* A delicious drop of snake oil */
9c5253ff 1676 (void) mlockall(MCL_FUTURE);
b853f6e9 1677
7407f689 1678 if (!key_file) {
e060ed32 1679 _cleanup_free_ char *bindname = NULL;
7407f689
LP
1680 const char *fn;
1681
da2268f9 1682 bindname = make_bindname(volume);
e060ed32
LP
1683 if (!bindname)
1684 return log_oom();
1685
7407f689
LP
1686 /* If a key file is not explicitly specified, search for a key in a well defined
1687 * search path, and load it. */
1688
da2268f9 1689 fn = strjoina(volume, ".key");
e060ed32
LP
1690 r = find_key_file(
1691 fn,
1692 STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"),
1693 bindname,
1694 &key_data, &key_data_size);
7407f689
LP
1695 if (r < 0)
1696 return r;
1697 if (r > 0)
da2268f9 1698 log_debug("Automatically discovered key for volume '%s'.", volume);
7407f689 1699 } else if (arg_keyfile_erase)
d3d49e76
LP
1700 destroy_key_file = key_file; /* let's get this baby erased when we leave */
1701
7376e835
AC
1702 if (arg_header) {
1703 log_debug("LUKS header: %s", arg_header);
5f4bfe56 1704 r = crypt_init(&cd, arg_header);
7376e835 1705 } else
da2268f9 1706 r = crypt_init(&cd, source);
3a40f366
YW
1707 if (r < 0)
1708 return log_error_errno(r, "crypt_init() failed: %m");
e23a0ce8 1709
efc3b12f 1710 cryptsetup_enable_logging(cd);
7f4e0805 1711
da2268f9 1712 status = crypt_status(cd, volume);
3742095b 1713 if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) {
da2268f9 1714 log_info("Volume %s already active.", volume);
3a40f366 1715 return 0;
7f4e0805
LP
1716 }
1717
d5d1ae15 1718 flags = determine_flags();
2c65512e 1719
496db330
YW
1720 until = usec_add(now(CLOCK_MONOTONIC), arg_timeout);
1721 if (until == USEC_INFINITY)
7dcda352 1722 until = 0;
260ab287 1723
6131a78b 1724 arg_key_size = (arg_key_size > 0 ? arg_key_size : (256 / 8));
e2d480b9 1725
10fb4e35
JJ
1726 if (key_file) {
1727 struct stat st;
e2d480b9 1728
10fb4e35
JJ
1729 /* Ideally we'd do this on the open fd, but since this is just a
1730 * warning it's OK to do this in two steps. */
3f4d56a0
MP
1731 if (stat(key_file, &st) >= 0 && S_ISREG(st.st_mode) && (st.st_mode & 0005))
1732 log_warning("Key file %s is world-readable. This is not a good idea!", key_file);
e2d480b9
LP
1733 }
1734
6930d069
LP
1735 if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2)) {
1736 r = crypt_load(cd, !arg_type || streq(arg_type, ANY_LUKS) ? CRYPT_LUKS : arg_type, NULL);
ea9a9d49
MB
1737 if (r < 0)
1738 return log_error_errno(r, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd));
1739
1740 if (arg_header) {
da2268f9 1741 r = crypt_set_data_device(cd, source);
ea9a9d49 1742 if (r < 0)
da2268f9 1743 return log_error_errno(r, "Failed to set LUKS data device %s: %m", source);
ea9a9d49 1744 }
d90874b4 1745
894bb3ca 1746 /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
7407f689 1747 if (!key_file && !key_data) {
da2268f9 1748 r = crypt_activate_by_token(cd, volume, CRYPT_ANY_TOKEN, NULL, flags);
894bb3ca 1749 if (r >= 0) {
da2268f9 1750 log_debug("Volume %s activated with LUKS token id %i.", volume, r);
894bb3ca
MB
1751 return 0;
1752 }
1753
1754 log_debug_errno(r, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd));
1755 }
ea9a9d49
MB
1756 }
1757
6cc27c29
MF
1758/* since cryptsetup 2.3.0 (Feb 2020) */
1759#ifdef CRYPT_BITLK
5af39ac8 1760 if (streq_ptr(arg_type, CRYPT_BITLK)) {
6cc27c29
MF
1761 r = crypt_load(cd, CRYPT_BITLK, NULL);
1762 if (r < 0)
1763 return log_error_errno(r, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd));
1764 }
1765#endif
1766
f75cac37 1767 for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) {
ab84f5b9 1768 _cleanup_strv_free_erase_ char **passwords = NULL;
260ab287 1769
0ba6f85e
LP
1770 /* When we were able to acquire multiple keys, let's always process them in this order:
1771 *
18843ecc 1772 * 1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
0ba6f85e
LP
1773 * 2. The discovered key: i.e. key_data + key_data_size
1774 * 3. The configured key: i.e. key_file + arg_keyfile_offset + arg_keyfile_size
1775 * 4. The empty password, in case arg_try_empty_password is set
1776 * 5. We enquire the user for a password
1777 */
1778
18843ecc 1779 if (!key_file && !key_data && !arg_pkcs11_uri && !arg_pkcs11_uri_auto && !arg_fido2_device && !arg_fido2_device_auto && !arg_tpm2_device && !arg_tpm2_device_auto) {
0ba6f85e
LP
1780
1781 if (arg_try_empty_password) {
1782 /* Hmm, let's try an empty password now, but only once */
1783 arg_try_empty_password = false;
1784
1785 key_data = strdup("");
1786 if (!key_data)
1787 return log_oom();
1788
1789 key_data_size = 0;
1790 } else {
1791 /* Ask the user for a passphrase only as last resort, if we have
1792 * nothing else to check for */
1793
da2268f9 1794 r = get_password(volume, source, until, tries == 0 && !arg_verify, &passwords);
0ba6f85e
LP
1795 if (r == -EAGAIN)
1796 continue;
1797 if (r < 0)
1798 return r;
1799 }
260ab287
LP
1800 }
1801
f75cac37 1802 if (streq_ptr(arg_type, CRYPT_TCRYPT))
da2268f9 1803 r = attach_tcrypt(cd, volume, key_file, key_data, key_data_size, passwords, flags);
8cf3ca80 1804 else
da2268f9 1805 r = attach_luks_or_plain_or_bitlk(cd, volume, key_file, key_data, key_data_size, passwords, flags, until);
5f4bfe56 1806 if (r >= 0)
260ab287 1807 break;
6f177c7d
LP
1808 if (r != -EAGAIN)
1809 return r;
260ab287 1810
2424fb7e
LP
1811 /* Key not correct? Let's try again! */
1812
6f177c7d 1813 key_file = NULL;
7407f689
LP
1814 key_data = erase_and_free(key_data);
1815 key_data_size = 0;
2424fb7e 1816 arg_pkcs11_uri = mfree(arg_pkcs11_uri);
b997d111 1817 arg_pkcs11_uri_auto = false;
2bc5c425
LP
1818 arg_fido2_device = mfree(arg_fido2_device);
1819 arg_fido2_device_auto = false;
18843ecc
LP
1820 arg_tpm2_device = mfree(arg_tpm2_device);
1821 arg_tpm2_device_auto = false;
7f4e0805
LP
1822 }
1823
0ffff81a
LP
1824 if (arg_tries != 0 && tries >= arg_tries)
1825 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to activate; giving up.");
7f4e0805 1826
da2268f9
LP
1827 } else if (streq(verb, "detach")) {
1828 const char *volume;
1829
1830 volume = argv[2];
7f4e0805 1831
da2268f9
LP
1832 if (!filename_is_valid(volume))
1833 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
7407f689 1834
da2268f9 1835 r = crypt_init_by_name(&cd, volume);
5f4bfe56 1836 if (r == -ENODEV) {
da2268f9 1837 log_info("Volume %s already inactive.", volume);
3a40f366 1838 return 0;
7f4e0805 1839 }
3a40f366
YW
1840 if (r < 0)
1841 return log_error_errno(r, "crypt_init_by_name() failed: %m");
7f4e0805 1842
efc3b12f 1843 cryptsetup_enable_logging(cd);
7f4e0805 1844
da2268f9 1845 r = crypt_deactivate(cd, volume);
3a40f366
YW
1846 if (r < 0)
1847 return log_error_errno(r, "Failed to deactivate: %m");
e23a0ce8 1848
0ffff81a 1849 } else
da2268f9 1850 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb %s.", verb);
e23a0ce8 1851
3a40f366 1852 return 0;
e23a0ce8 1853}
3a40f366
YW
1854
1855DEFINE_MAIN_FUNCTION(run);