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