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