]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/cryptsetup/cryptsetup.c
memory-util: replace memeqzero() by a more generic memeqbyte()
[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
8186022c
OK
999static int attach_luks2_by_pkcs11(
1000 struct crypt_device *cd,
1001 const char *name,
1002 const char *friendly_name,
1003 usec_t until,
1004 bool headless,
1005 uint32_t flags) {
1006
1007 int r = -ENOTSUP;
1008#if HAVE_LIBCRYPTSETUP_PLUGINS
1009 if (!crypt_get_type(cd) || strcmp(crypt_get_type(cd), CRYPT_LUKS2))
1010 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Automatic PKCS#11 metadata requires LUKS2 device.");
1011
1012 systemd_pkcs11_plugin_params params = {
1013 .friendly_name = friendly_name,
1014 .until = until,
1015 .headless = headless
1016 };
1017
1018 r = crypt_activate_by_token_pin(cd, name, "systemd-pkcs11", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
1019 if (r > 0) /* returns unlocked keyslot id on success */
1020 r = 0;
1021#endif
1022 return r;
1023}
1024
b8c80b56
LP
1025static int attach_luks_or_plain_or_bitlk_by_pkcs11(
1026 struct crypt_device *cd,
1027 const char *name,
1028 const char *key_file,
1029 const void *key_data,
1030 size_t key_data_size,
1031 usec_t until,
1032 uint32_t flags,
1033 bool pass_volume_key) {
1034
1035 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1036 _cleanup_free_ char *friendly = NULL, *discovered_uri = NULL;
1037 size_t decrypted_key_size = 0, discovered_key_size = 0;
1038 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1039 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1040 _cleanup_free_ void *discovered_key = NULL;
1041 int keyslot = arg_key_slot, r;
8186022c
OK
1042 const char *uri = NULL;
1043 bool use_libcryptsetup_plugin = libcryptsetup_plugins_support();
b8c80b56
LP
1044
1045 assert(cd);
1046 assert(name);
1047 assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
1048
1049 if (arg_pkcs11_uri_auto) {
8186022c
OK
1050 if (!use_libcryptsetup_plugin) {
1051 r = find_pkcs11_auto_data(cd, &discovered_uri, &discovered_key, &discovered_key_size, &keyslot);
1052 if (IN_SET(r, -ENOTUNIQ, -ENXIO))
1053 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1054 "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1055 if (r < 0)
1056 return r;
b8c80b56 1057
8186022c
OK
1058 uri = discovered_uri;
1059 key_data = discovered_key;
1060 key_data_size = discovered_key_size;
1061 }
b8c80b56
LP
1062 } else {
1063 uri = arg_pkcs11_uri;
1064
1065 if (!key_file && !key_data)
1066 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing.");
1067 }
1068
1069 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1070 if (!friendly)
1071 return log_oom();
1072
1073 for (;;) {
1074 bool processed = false;
1075
8186022c
OK
1076 if (use_libcryptsetup_plugin && arg_pkcs11_uri_auto)
1077 r = attach_luks2_by_pkcs11(cd, name, friendly, until, arg_headless, flags);
1078 else {
1079 r = decrypt_pkcs11_key(
1080 name,
1081 friendly,
1082 uri,
1083 key_file, arg_keyfile_size, arg_keyfile_offset,
1084 key_data, key_data_size,
1085 until,
1086 arg_headless,
1087 &decrypted_key, &decrypted_key_size);
1088 if (r >= 0)
1089 break;
1090 }
1091
b8c80b56
LP
1092 if (r != -EAGAIN) /* EAGAIN means: token not found */
1093 return r;
1094
1095 if (!monitor) {
1096 /* We didn't find the token. In this case, watch for it via udev. Let's
1097 * create an event loop and monitor first. */
1098
1099 assert(!event);
1100
1101 r = sd_event_default(&event);
1102 if (r < 0)
1103 return log_error_errno(r, "Failed to allocate event loop: %m");
1104
1105 r = make_security_device_monitor(event, &monitor);
1106 if (r < 0)
1107 return r;
1108
1109 log_notice("Security token %s not present for unlocking volume %s, please plug it in.",
1110 uri, friendly);
1111
1112 /* Let's immediately rescan in case the token appeared in the time we needed
1113 * to create and configure the monitor */
1114 continue;
1115 }
1116
1117 for (;;) {
1118 /* Wait for one event, and then eat all subsequent events until there are no
1119 * further ones */
1120 r = sd_event_run(event, processed ? 0 : UINT64_MAX);
1121 if (r < 0)
1122 return log_error_errno(r, "Failed to run event loop: %m");
1123 if (r == 0)
1124 break;
1125
1126 processed = true;
1127 }
1128
1129 log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
1130 }
8186022c 1131 assert(decrypted_key);
b8c80b56
LP
1132
1133 if (pass_volume_key)
1134 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
1135 else {
1136 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
1137
1138 /* Before using this key as passphrase we base64 encode it. Why? For compatibility
1139 * with homed's PKCS#11 hookup: there we want to use the key we acquired through
1140 * PKCS#11 for other authentication/decryption mechanisms too, and some of them do
1141 * not not take arbitrary binary blobs, but require NUL-terminated strings — most
1142 * importantly UNIX password hashes. Hence, for compatibility we want to use a string
1143 * without embedded NUL here too, and that's easiest to generate from a binary blob
1144 * via base64 encoding. */
1145
1146 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1147 if (r < 0)
1148 return log_oom();
1149
1150 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
1151 }
1152 if (r == -EPERM) {
1153 log_error_errno(r, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
1154 return -EAGAIN; /* log actual error, but return EAGAIN */
1155 }
1156 if (r < 0)
1157 return log_error_errno(r, "Failed to activate with PKCS#11 acquired key: %m");
1158
1159 return 0;
1160}
1161
18843ecc
LP
1162static int make_tpm2_device_monitor(sd_event *event, sd_device_monitor **ret) {
1163 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1164 int r;
1165
1166 assert(ret);
1167
1168 r = sd_device_monitor_new(&monitor);
1169 if (r < 0)
1170 return log_error_errno(r, "Failed to allocate device monitor: %m");
1171
1172 r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "tpmrm", NULL);
1173 if (r < 0)
1174 return log_error_errno(r, "Failed to configure device monitor: %m");
1175
1176 r = sd_device_monitor_attach_event(monitor, event);
1177 if (r < 0)
1178 return log_error_errno(r, "Failed to attach device monitor: %m");
1179
1180 r = sd_device_monitor_start(monitor, NULL, NULL);
1181 if (r < 0)
1182 return log_error_errno(r, "Failed to start device monitor: %m");
1183
1184 *ret = TAKE_PTR(monitor);
1185 return 0;
1186}
1187
d1ae38d8
OK
1188static int attach_luks2_by_tpm2(
1189 struct crypt_device *cd,
1190 const char *name,
1191 uint32_t flags) {
1192
1193#if HAVE_LIBCRYPTSETUP_PLUGINS
1194 int r;
1195
1196 systemd_tpm2_plugin_params params = {
1197 .search_pcr_mask = arg_tpm2_pcr_mask,
1198 .device = arg_tpm2_device
1199 };
1200
1201 if (crypt_token_external_path() == NULL)
1202 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1203 "Libcryptsetup has external plugins support disabled.");
1204
1205 r = crypt_activate_by_token_pin(cd, name, "systemd-tpm2", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
1206 if (r > 0) /* returns unlocked keyslot id on success */
1207 r = 0;
1208
1209 return r;
1210#else
1211 return -EOPNOTSUPP;
1212#endif
1213}
1214
18843ecc
LP
1215static int attach_luks_or_plain_or_bitlk_by_tpm2(
1216 struct crypt_device *cd,
1217 const char *name,
1218 const char *key_file,
1219 const void *key_data,
1220 size_t key_data_size,
1221 usec_t until,
1222 uint32_t flags,
1223 bool pass_volume_key) {
1224
1225 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1226 _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1227 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1228 _cleanup_free_ char *friendly = NULL;
1229 int keyslot = arg_key_slot, r;
67e9c83b 1230 size_t decrypted_key_size;
18843ecc
LP
1231
1232 assert(cd);
1233 assert(name);
1234 assert(arg_tpm2_device || arg_tpm2_device_auto);
1235
1236 friendly = friendly_disk_name(crypt_get_device_name(cd), name);
1237 if (!friendly)
1238 return log_oom();
1239
1240 for (;;) {
1241 bool processed = false;
1242
1243 if (key_file || key_data) {
1244 /* If key data is specified, use that */
1245
1246 r = acquire_tpm2_key(
1247 name,
1248 arg_tpm2_device,
1249 arg_tpm2_pcr_mask == UINT32_MAX ? TPM2_PCR_MASK_DEFAULT : arg_tpm2_pcr_mask,
07697bfe 1250 UINT16_MAX,
18843ecc
LP
1251 key_file, arg_keyfile_size, arg_keyfile_offset,
1252 key_data, key_data_size,
1253 NULL, 0, /* we don't know the policy hash */
1254 &decrypted_key, &decrypted_key_size);
1255 if (r >= 0)
1256 break;
cad10544
LP
1257 if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
1258 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");
18843ecc
LP
1259 if (r != -EAGAIN) /* EAGAIN means: no tpm2 chip found */
1260 return r;
1261 } else {
d1ae38d8
OK
1262 r = attach_luks2_by_tpm2(cd, name, flags);
1263 /* EAGAIN means: no tpm2 chip found
1264 * EOPNOTSUPP means: no libcryptsetup plugins support */
1265 if (r == -ENXIO)
1266 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1267 "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
1268 if (r == -ENOENT)
1269 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1270 "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
1271 if (!IN_SET(r, -EOPNOTSUPP, -EAGAIN))
1272 return r;
1273 }
1274
1275 if (r == -EOPNOTSUPP) {
18843ecc
LP
1276 _cleanup_free_ void *blob = NULL, *policy_hash = NULL;
1277 size_t blob_size, policy_hash_size;
1278 bool found_some = false;
1279 int token = 0; /* first token to look at */
1280
1281 /* If no key data is specified, look for it in the header. In order to support
1282 * software upgrades we'll iterate through all suitable tokens, maybe one of them
1283 * works. */
1284
1285 for (;;) {
1286 uint32_t pcr_mask;
07697bfe 1287 uint16_t pcr_bank;
18843ecc
LP
1288
1289 r = find_tpm2_auto_data(
1290 cd,
1291 arg_tpm2_pcr_mask, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1292 token, /* search for the token with this index, or any later index than this */
1293 &pcr_mask,
07697bfe 1294 &pcr_bank,
18843ecc
LP
1295 &blob, &blob_size,
1296 &policy_hash, &policy_hash_size,
1297 &keyslot,
1298 &token);
c26f7dd9 1299 if (r == -ENXIO)
7802194a 1300 /* No further TPM2 tokens found in the LUKS2 header. */
c26f7dd9
ZJS
1301 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1302 found_some
1303 ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
1304 : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
cad10544
LP
1305 if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
1306 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");
18843ecc
LP
1307 if (r < 0)
1308 return r;
1309
1310 found_some = true;
1311
1312 r = acquire_tpm2_key(
1313 name,
1314 arg_tpm2_device,
1315 pcr_mask,
07697bfe 1316 pcr_bank,
18843ecc
LP
1317 NULL, 0, 0, /* no key file */
1318 blob, blob_size,
1319 policy_hash, policy_hash_size,
1320 &decrypted_key, &decrypted_key_size);
1321 if (r != -EPERM)
1322 break;
1323
1324 token++; /* try a different token next time */
1325 }
1326
1327 if (r >= 0)
1328 break;
1329 if (r != -EAGAIN) /* EAGAIN means: no tpm2 chip found */
1330 return r;
1331 }
1332
1333 if (!monitor) {
1334 /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
1335 * an event loop and monitor first. */
1336
1337 assert(!event);
1338
71b25dea
LP
1339 if (is_efi_boot() && !efi_has_tpm2())
1340 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
1341 "No TPM2 hardware discovered and EFI bios indicates no support for it either, assuming TPM2-less system, falling back to traditional unocking.");
1342
18843ecc
LP
1343 r = sd_event_default(&event);
1344 if (r < 0)
1345 return log_error_errno(r, "Failed to allocate event loop: %m");
1346
1347 r = make_tpm2_device_monitor(event, &monitor);
1348 if (r < 0)
1349 return r;
1350
1351 log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly);
1352
1353 /* Let's immediately rescan in case the device appeared in the time we needed
1354 * to create and configure the monitor */
1355 continue;
1356 }
1357
1358 for (;;) {
1359 /* Wait for one event, and then eat all subsequent events until there are no
1360 * further ones */
1361 r = sd_event_run(event, processed ? 0 : UINT64_MAX);
1362 if (r < 0)
1363 return log_error_errno(r, "Failed to run event loop: %m");
1364 if (r == 0)
1365 break;
1366
1367 processed = true;
1368 }
1369
1370 log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
1371 }
26fbc5aa 1372 assert(decrypted_key);
18843ecc
LP
1373
1374 if (pass_volume_key)
1375 r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
1376 else {
1377 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
1378
1379 /* Before using this key as passphrase we base64 encode it, for compat with homed */
1380
1381 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
1382 if (r < 0)
1383 return log_oom();
1384
1385 r = crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, strlen(base64_encoded), flags);
1386 }
1387 if (r == -EPERM) {
1388 log_error_errno(r, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
1389 return -EAGAIN; /* log actual error, but return EAGAIN */
1390 }
1391 if (r < 0)
1392 return log_error_errno(r, "Failed to activate with TPM2 acquired key: %m");
1393
1394 return 0;
1395}
1396
b8c80b56
LP
1397static int attach_luks_or_plain_or_bitlk_by_key_data(
1398 struct crypt_device *cd,
1399 const char *name,
1400 const void *key_data,
1401 size_t key_data_size,
1402 uint32_t flags,
1403 bool pass_volume_key) {
1404
1405 int r;
1406
1407 assert(cd);
1408 assert(name);
1409 assert(key_data);
1410
1411 if (pass_volume_key)
1412 r = crypt_activate_by_volume_key(cd, name, key_data, key_data_size, flags);
1413 else
1414 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, key_data, key_data_size, flags);
1415 if (r == -EPERM) {
1416 log_error_errno(r, "Failed to activate. (Key incorrect?)");
1417 return -EAGAIN; /* Log actual error, but return EAGAIN */
1418 }
1419 if (r < 0)
1420 return log_error_errno(r, "Failed to activate: %m");
1421
1422 return 0;
1423}
1424
1425static int attach_luks_or_plain_or_bitlk_by_key_file(
1426 struct crypt_device *cd,
1427 const char *name,
1428 const char *key_file,
1429 uint32_t flags,
1430 bool pass_volume_key) {
1431
1432 _cleanup_(erase_and_freep) char *kfdata = NULL;
1433 _cleanup_free_ char *bindname = NULL;
1434 size_t kfsize;
1435 int r;
1436
1437 assert(cd);
1438 assert(name);
1439 assert(key_file);
1440
1441 /* If we read the key via AF_UNIX, make this client recognizable */
1442 bindname = make_bindname(name);
1443 if (!bindname)
1444 return log_oom();
1445
1446 r = read_full_file_full(
1447 AT_FDCWD, key_file,
1448 arg_keyfile_offset == 0 ? UINT64_MAX : arg_keyfile_offset,
1449 arg_keyfile_size == 0 ? SIZE_MAX : arg_keyfile_size,
1450 READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
1451 bindname,
1452 &kfdata, &kfsize);
871f35af
LP
1453 if (r == -E2BIG) {
1454 log_error_errno(r, "Failed to activate, key file '%s' too large.", key_file);
1455 return -EAGAIN;
1456 }
b8c80b56
LP
1457 if (r == -ENOENT) {
1458 log_error_errno(r, "Failed to activate, key file '%s' missing.", key_file);
1459 return -EAGAIN; /* Log actual error, but return EAGAIN */
1460 }
abc50cf6
LP
1461 if (r < 0)
1462 return log_error_errno(r, "Failed to read key file '%s': %m", key_file);
b8c80b56
LP
1463
1464 if (pass_volume_key)
1465 r = crypt_activate_by_volume_key(cd, name, kfdata, kfsize, flags);
1466 else
1467 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, kfdata, kfsize, flags);
1468 if (r == -EPERM) {
1469 log_error_errno(r, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file);
1470 return -EAGAIN; /* Log actual error, but return EAGAIN */
1471 }
1472 if (r < 0)
1473 return log_error_errno(r, "Failed to activate with key file '%s': %m", key_file);
1474
1475 return 0;
1476}
1477
1478static int attach_luks_or_plain_or_bitlk_by_passphrase(
1479 struct crypt_device *cd,
1480 const char *name,
1481 char **passwords,
1482 uint32_t flags,
1483 bool pass_volume_key) {
1484
1485 char **p;
1486 int r;
1487
1488 assert(cd);
1489 assert(name);
1490
1491 r = -EINVAL;
1492 STRV_FOREACH(p, passwords) {
1493 if (pass_volume_key)
1494 r = crypt_activate_by_volume_key(cd, name, *p, arg_key_size, flags);
1495 else
1496 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, *p, strlen(*p), flags);
1497 if (r >= 0)
1498 break;
1499 }
1500 if (r == -EPERM) {
1501 log_error_errno(r, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
1502 return -EAGAIN; /* log actual error, but return EAGAIN */
1503 }
1504 if (r < 0)
1505 return log_error_errno(r, "Failed to activate with specified passphrase: %m");
1506
1507 return 0;
1508}
1509
6cc27c29 1510static int attach_luks_or_plain_or_bitlk(
9c5253ff
LP
1511 struct crypt_device *cd,
1512 const char *name,
1513 const char *key_file,
7407f689
LP
1514 const void *key_data,
1515 size_t key_data_size,
9c5253ff 1516 char **passwords,
08669709
LP
1517 uint32_t flags,
1518 usec_t until) {
9c5253ff 1519
10fb4e35 1520 bool pass_volume_key = false;
b8c80b56 1521 int r;
10fb4e35
JJ
1522
1523 assert(cd);
1524 assert(name);
10fb4e35 1525
2e4beb87 1526 if ((!arg_type && !crypt_get_type(cd)) || streq_ptr(arg_type, CRYPT_PLAIN)) {
4eac2773
MP
1527 struct crypt_params_plain params = {
1528 .offset = arg_offset,
1529 .skip = arg_skip,
a9fc6406 1530 .sector_size = arg_sector_size,
4eac2773 1531 };
10fb4e35
JJ
1532 const char *cipher, *cipher_mode;
1533 _cleanup_free_ char *truncated_cipher = NULL;
1534
b8c80b56 1535 if (streq_ptr(arg_hash, "plain"))
10fb4e35 1536 /* plain isn't a real hash type. it just means "use no hash" */
b8c80b56
LP
1537 params.hash = NULL;
1538 else if (arg_hash)
1539 params.hash = arg_hash;
1540 else if (!key_file)
1541 /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
1542 * file is provided */
10fb4e35
JJ
1543 params.hash = "ripemd160";
1544
f75cac37 1545 if (arg_cipher) {
10fb4e35
JJ
1546 size_t l;
1547
f75cac37
LP
1548 l = strcspn(arg_cipher, "-");
1549 truncated_cipher = strndup(arg_cipher, l);
10fb4e35
JJ
1550 if (!truncated_cipher)
1551 return log_oom();
1552
1553 cipher = truncated_cipher;
f75cac37 1554 cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain";
10fb4e35
JJ
1555 } else {
1556 cipher = "aes";
1557 cipher_mode = "cbc-essiv:sha256";
1558 }
1559
aed68083 1560 /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
6131a78b 1561 arg_keyfile_size = arg_key_size;
10fb4e35 1562
30747265 1563 /* In contrast to what the name crypt_format() might suggest this doesn't actually format
aed68083 1564 * anything, it just configures encryption parameters when used for plain mode. */
1602b008 1565 r = crypt_format(cd, CRYPT_PLAIN, cipher, cipher_mode, NULL, NULL, arg_keyfile_size, &params);
2e4beb87
MB
1566 if (r < 0)
1567 return log_error_errno(r, "Loading of cryptographic parameters failed: %m");
10fb4e35
JJ
1568
1569 /* hash == NULL implies the user passed "plain" */
b8c80b56 1570 pass_volume_key = !params.hash;
10fb4e35 1571 }
10fb4e35
JJ
1572
1573 log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
1574 crypt_get_cipher(cd),
1575 crypt_get_cipher_mode(cd),
1576 crypt_get_volume_key_size(cd)*8,
1577 crypt_get_device_name(cd));
1578
18843ecc
LP
1579 if (arg_tpm2_device || arg_tpm2_device_auto)
1580 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
1581 if (arg_fido2_device || arg_fido2_device_auto)
1582 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
1583 if (arg_pkcs11_uri || arg_pkcs11_uri_auto)
1584 return attach_luks_or_plain_or_bitlk_by_pkcs11(cd, name, key_file, key_data, key_data_size, until, flags, pass_volume_key);
1585 if (key_data)
1586 return attach_luks_or_plain_or_bitlk_by_key_data(cd, name, key_data, key_data_size, flags, pass_volume_key);
1587 if (key_file)
1588 return attach_luks_or_plain_or_bitlk_by_key_file(cd, name, key_file, flags, pass_volume_key);
10fb4e35 1589
b8c80b56 1590 return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
10fb4e35
JJ
1591}
1592
dd5e696d 1593static int help(void) {
37ec0fdd
LP
1594 _cleanup_free_ char *link = NULL;
1595 int r;
1596
1597 r = terminal_urlify_man("systemd-cryptsetup@.service", "8", &link);
1598 if (r < 0)
1599 return log_oom();
dd5e696d
LP
1600
1601 printf("%s attach VOLUME SOURCEDEVICE [PASSWORD] [OPTIONS]\n"
1602 "%s detach VOLUME\n\n"
37ec0fdd 1603 "Attaches or detaches an encrypted block device.\n"
bc556335
DDM
1604 "\nSee the %s for details.\n",
1605 program_invocation_short_name,
1606 program_invocation_short_name,
1607 link);
dd5e696d
LP
1608
1609 return 0;
1610}
1611
d5d1ae15
LP
1612static uint32_t determine_flags(void) {
1613 uint32_t flags = 0;
1614
1615 if (arg_readonly)
1616 flags |= CRYPT_ACTIVATE_READONLY;
1617
1618 if (arg_discards)
1619 flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
1620
1621 if (arg_same_cpu_crypt)
1622 flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
1623
1624 if (arg_submit_from_crypt_cpus)
1625 flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
1626
227acf00
JU
1627 if (arg_no_read_workqueue)
1628 flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
1629
1630 if (arg_no_write_workqueue)
1631 flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
1632
408c81f6
MS
1633#ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
1634 /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
1635 /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
1636 flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF;
1637#endif
1638
d5d1ae15
LP
1639 return flags;
1640}
1641
d3d49e76
LP
1642static void remove_and_erasep(const char **p) {
1643 int r;
1644
1645 if (!*p)
1646 return;
1647
1648 r = unlinkat_deallocate(AT_FDCWD, *p, UNLINK_ERASE);
1649 if (r < 0 && r != -ENOENT)
1650 log_warning_errno(r, "Unable to erase key file '%s', ignoring: %m", *p);
1651}
1652
3a40f366 1653static int run(int argc, char *argv[]) {
294bd454 1654 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
da2268f9 1655 const char *verb;
3a40f366 1656 int r;
e23a0ce8 1657
3a40f366
YW
1658 if (argc <= 1)
1659 return help();
dd5e696d 1660
d7a0f1f4
FS
1661 if (argc < 3)
1662 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1663 "This program requires at least two arguments.");
e23a0ce8 1664
d2acb93d 1665 log_setup();
e23a0ce8 1666
2f678640 1667 cryptsetup_enable_logging(NULL);
568a8404 1668
4c12626c
LP
1669 umask(0022);
1670
da2268f9
LP
1671 verb = argv[1];
1672
1673 if (streq(verb, "attach")) {
d3d49e76 1674 _cleanup_(remove_and_erasep) const char *destroy_key_file = NULL;
7407f689 1675 _cleanup_(erase_and_freep) void *key_data = NULL;
da2268f9
LP
1676 const char *volume, *source, *key_file, *options;
1677 crypt_status_info status;
7407f689 1678 size_t key_data_size = 0;
da2268f9
LP
1679 uint32_t flags = 0;
1680 unsigned tries;
1681 usec_t until;
7f4e0805 1682
b61e476f
LP
1683 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [PASSWORD] [OPTIONS] */
1684
0ffff81a
LP
1685 if (argc < 4)
1686 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "attach requires at least two arguments.");
7f4e0805 1687
da2268f9
LP
1688 volume = argv[2];
1689 source = argv[3];
1690 key_file = argc >= 5 && !STR_IN_SET(argv[4], "", "-", "none") ? argv[4] : NULL;
1691 options = argc >= 6 && !STR_IN_SET(argv[5], "", "-", "none") ? argv[5] : NULL;
7407f689 1692
da2268f9
LP
1693 if (!filename_is_valid(volume))
1694 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
1695
1696 if (key_file && !path_is_absolute(key_file)) {
1697 log_warning("Password file path '%s' is not absolute. Ignoring.", key_file);
1698 key_file = NULL;
7f4e0805
LP
1699 }
1700
da2268f9
LP
1701 if (options) {
1702 r = parse_options(options);
3a40f366
YW
1703 if (r < 0)
1704 return r;
74b1c371 1705 }
e23a0ce8 1706
7bb553bb 1707 log_debug("%s %s ← %s type=%s cipher=%s", __func__,
da2268f9 1708 volume, source, strempty(arg_type), strempty(arg_cipher));
7bb553bb 1709
b853f6e9 1710 /* A delicious drop of snake oil */
9c5253ff 1711 (void) mlockall(MCL_FUTURE);
b853f6e9 1712
7407f689 1713 if (!key_file) {
e060ed32 1714 _cleanup_free_ char *bindname = NULL;
7407f689
LP
1715 const char *fn;
1716
da2268f9 1717 bindname = make_bindname(volume);
e060ed32
LP
1718 if (!bindname)
1719 return log_oom();
1720
7407f689
LP
1721 /* If a key file is not explicitly specified, search for a key in a well defined
1722 * search path, and load it. */
1723
da2268f9 1724 fn = strjoina(volume, ".key");
e060ed32
LP
1725 r = find_key_file(
1726 fn,
1727 STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"),
1728 bindname,
1729 &key_data, &key_data_size);
7407f689
LP
1730 if (r < 0)
1731 return r;
1732 if (r > 0)
da2268f9 1733 log_debug("Automatically discovered key for volume '%s'.", volume);
7407f689 1734 } else if (arg_keyfile_erase)
d3d49e76
LP
1735 destroy_key_file = key_file; /* let's get this baby erased when we leave */
1736
7376e835
AC
1737 if (arg_header) {
1738 log_debug("LUKS header: %s", arg_header);
5f4bfe56 1739 r = crypt_init(&cd, arg_header);
7376e835 1740 } else
da2268f9 1741 r = crypt_init(&cd, source);
3a40f366
YW
1742 if (r < 0)
1743 return log_error_errno(r, "crypt_init() failed: %m");
e23a0ce8 1744
efc3b12f 1745 cryptsetup_enable_logging(cd);
7f4e0805 1746
da2268f9 1747 status = crypt_status(cd, volume);
3742095b 1748 if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) {
da2268f9 1749 log_info("Volume %s already active.", volume);
3a40f366 1750 return 0;
7f4e0805
LP
1751 }
1752
d5d1ae15 1753 flags = determine_flags();
2c65512e 1754
496db330
YW
1755 until = usec_add(now(CLOCK_MONOTONIC), arg_timeout);
1756 if (until == USEC_INFINITY)
7dcda352 1757 until = 0;
260ab287 1758
6131a78b 1759 arg_key_size = (arg_key_size > 0 ? arg_key_size : (256 / 8));
e2d480b9 1760
10fb4e35
JJ
1761 if (key_file) {
1762 struct stat st;
e2d480b9 1763
10fb4e35
JJ
1764 /* Ideally we'd do this on the open fd, but since this is just a
1765 * warning it's OK to do this in two steps. */
3f4d56a0
MP
1766 if (stat(key_file, &st) >= 0 && S_ISREG(st.st_mode) && (st.st_mode & 0005))
1767 log_warning("Key file %s is world-readable. This is not a good idea!", key_file);
e2d480b9
LP
1768 }
1769
6930d069
LP
1770 if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2)) {
1771 r = crypt_load(cd, !arg_type || streq(arg_type, ANY_LUKS) ? CRYPT_LUKS : arg_type, NULL);
ea9a9d49
MB
1772 if (r < 0)
1773 return log_error_errno(r, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd));
1774
1775 if (arg_header) {
da2268f9 1776 r = crypt_set_data_device(cd, source);
ea9a9d49 1777 if (r < 0)
da2268f9 1778 return log_error_errno(r, "Failed to set LUKS data device %s: %m", source);
ea9a9d49 1779 }
d90874b4 1780
894bb3ca 1781 /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
7407f689 1782 if (!key_file && !key_data) {
da2268f9 1783 r = crypt_activate_by_token(cd, volume, CRYPT_ANY_TOKEN, NULL, flags);
894bb3ca 1784 if (r >= 0) {
da2268f9 1785 log_debug("Volume %s activated with LUKS token id %i.", volume, r);
894bb3ca
MB
1786 return 0;
1787 }
1788
1789 log_debug_errno(r, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd));
1790 }
ea9a9d49
MB
1791 }
1792
6cc27c29
MF
1793/* since cryptsetup 2.3.0 (Feb 2020) */
1794#ifdef CRYPT_BITLK
5af39ac8 1795 if (streq_ptr(arg_type, CRYPT_BITLK)) {
6cc27c29
MF
1796 r = crypt_load(cd, CRYPT_BITLK, NULL);
1797 if (r < 0)
1798 return log_error_errno(r, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd));
1799 }
1800#endif
1801
f75cac37 1802 for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) {
ab84f5b9 1803 _cleanup_strv_free_erase_ char **passwords = NULL;
260ab287 1804
0ba6f85e
LP
1805 /* When we were able to acquire multiple keys, let's always process them in this order:
1806 *
18843ecc 1807 * 1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
0ba6f85e
LP
1808 * 2. The discovered key: i.e. key_data + key_data_size
1809 * 3. The configured key: i.e. key_file + arg_keyfile_offset + arg_keyfile_size
1810 * 4. The empty password, in case arg_try_empty_password is set
1811 * 5. We enquire the user for a password
1812 */
1813
18843ecc 1814 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
1815
1816 if (arg_try_empty_password) {
1817 /* Hmm, let's try an empty password now, but only once */
1818 arg_try_empty_password = false;
1819
1820 key_data = strdup("");
1821 if (!key_data)
1822 return log_oom();
1823
1824 key_data_size = 0;
1825 } else {
1826 /* Ask the user for a passphrase only as last resort, if we have
1827 * nothing else to check for */
1828
da2268f9 1829 r = get_password(volume, source, until, tries == 0 && !arg_verify, &passwords);
0ba6f85e
LP
1830 if (r == -EAGAIN)
1831 continue;
1832 if (r < 0)
1833 return r;
1834 }
260ab287
LP
1835 }
1836
f75cac37 1837 if (streq_ptr(arg_type, CRYPT_TCRYPT))
da2268f9 1838 r = attach_tcrypt(cd, volume, key_file, key_data, key_data_size, passwords, flags);
8cf3ca80 1839 else
da2268f9 1840 r = attach_luks_or_plain_or_bitlk(cd, volume, key_file, key_data, key_data_size, passwords, flags, until);
5f4bfe56 1841 if (r >= 0)
260ab287 1842 break;
6f177c7d
LP
1843 if (r != -EAGAIN)
1844 return r;
260ab287 1845
2424fb7e
LP
1846 /* Key not correct? Let's try again! */
1847
6f177c7d 1848 key_file = NULL;
7407f689
LP
1849 key_data = erase_and_free(key_data);
1850 key_data_size = 0;
2424fb7e 1851 arg_pkcs11_uri = mfree(arg_pkcs11_uri);
b997d111 1852 arg_pkcs11_uri_auto = false;
2bc5c425
LP
1853 arg_fido2_device = mfree(arg_fido2_device);
1854 arg_fido2_device_auto = false;
18843ecc
LP
1855 arg_tpm2_device = mfree(arg_tpm2_device);
1856 arg_tpm2_device_auto = false;
7f4e0805
LP
1857 }
1858
0ffff81a
LP
1859 if (arg_tries != 0 && tries >= arg_tries)
1860 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to activate; giving up.");
7f4e0805 1861
da2268f9
LP
1862 } else if (streq(verb, "detach")) {
1863 const char *volume;
1864
1865 volume = argv[2];
7f4e0805 1866
da2268f9
LP
1867 if (!filename_is_valid(volume))
1868 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
7407f689 1869
da2268f9 1870 r = crypt_init_by_name(&cd, volume);
5f4bfe56 1871 if (r == -ENODEV) {
da2268f9 1872 log_info("Volume %s already inactive.", volume);
3a40f366 1873 return 0;
7f4e0805 1874 }
3a40f366
YW
1875 if (r < 0)
1876 return log_error_errno(r, "crypt_init_by_name() failed: %m");
7f4e0805 1877
efc3b12f 1878 cryptsetup_enable_logging(cd);
7f4e0805 1879
da2268f9 1880 r = crypt_deactivate(cd, volume);
3a40f366
YW
1881 if (r < 0)
1882 return log_error_errno(r, "Failed to deactivate: %m");
e23a0ce8 1883
0ffff81a 1884 } else
da2268f9 1885 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb %s.", verb);
e23a0ce8 1886
3a40f366 1887 return 0;
e23a0ce8 1888}
3a40f366
YW
1889
1890DEFINE_MAIN_FUNCTION(run);