• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 30136241924

24 Jul 2026 07:11PM UTC coverage: 73.643% (+0.5%) from 73.111%
30136241924

push

github

yuwata
man: fix typo

349461 of 474536 relevant lines covered (73.64%)

1337141.63 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

46.02
/src/cryptsetup/cryptsetup.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <sys/mman.h>
4
#include <sys/stat.h>
5
#include <unistd.h>
6

7
#include "sd-device.h"
8
#include "sd-event.h"
9
#include "sd-json.h"
10
#include "sd-messages.h"
11

12
#include "alloc-util.h"
13
#include "ask-password-api.h"
14
#include "build.h"
15
#include "crypto-util.h"
16
#include "cryptsetup-fido2.h"
17
#include "cryptsetup-keyfile.h"
18
#include "cryptsetup-pkcs11.h"
19
#include "cryptsetup-tpm2.h"
20
#include "cryptsetup-util.h"
21
#include "dlopen-note.h"
22
#include "efi-api.h"
23
#include "efi-loader.h"
24
#include "efivars.h"
25
#include "env-util.h"
26
#include "errno-util.h"
27
#include "escape.h"
28
#include "extract-word.h"
29
#include "fileio.h"
30
#include "format-table.h"
31
#include "fs-util.h"
32
#include "hexdecoct.h"
33
#include "json-util.h"
34
#include "libfido2-util.h"
35
#include "libmount-util.h"
36
#include "log.h"
37
#include "main-func.h"
38
#include "memory-util.h"
39
#include "nulstr-util.h"
40
#include "options.h"
41
#include "parse-util.h"
42
#include "path-util.h"
43
#include "pkcs11-util.h"
44
#include "pretty-print.h"
45
#include "process-util.h"
46
#include "random-util.h"
47
#include "string-table.h"
48
#include "string-util.h"
49
#include "strv.h"
50
#include "time-util.h"
51
#include "tpm2-pcr.h"
52
#include "tpm2-util.h"
53
#include "verbs.h"
54

55
/* internal helper */
56
#define ANY_LUKS "LUKS"
57
/* as in src/cryptsetup.h */
58
#define CRYPT_SECTOR_SIZE 512U
59
#define CRYPT_MAX_SECTOR_SIZE 4096U
60

61
typedef enum PassphraseType {
62
        PASSPHRASE_NONE,
63
        PASSPHRASE_REGULAR = 1 << 0,
64
        PASSPHRASE_RECOVERY_KEY = 1 << 1,
65
        PASSPHRASE_BOTH = PASSPHRASE_REGULAR|PASSPHRASE_RECOVERY_KEY,
66
        _PASSPHRASE_TYPE_MAX,
67
        _PASSPHRASE_TYPE_INVALID = -1,
68
} PassphraseType;
69

70
typedef enum TokenType {
71
        TOKEN_TPM2,
72
        TOKEN_FIDO2,
73
        TOKEN_PKCS11,
74
        _TOKEN_TYPE_MAX,
75
        _TOKEN_TYPE_INVALID = -EINVAL,
76
} TokenType;
77

78
static const char *arg_type = NULL; /* ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT, CRYPT_BITLK or CRYPT_PLAIN */
79
static char *arg_cipher = NULL;
80
static unsigned arg_key_size = 0;
81
static unsigned arg_sector_size = CRYPT_SECTOR_SIZE;
82
static int arg_key_slot = CRYPT_ANY_SLOT;
83
static unsigned arg_keyfile_size = 0;
84
static uint64_t arg_keyfile_offset = 0;
85
static bool arg_keyfile_erase = false;
86
static bool arg_try_empty_password = false;
87
static char *arg_hash = NULL;
88
static char *arg_header = NULL;
89
static unsigned arg_tries = 3;
90
static bool arg_readonly = false;
91
static bool arg_verify = false;
92
static bool arg_password_cache_set = false; /* Not the actual argument value, just an indicator that some value is set */
93
static AskPasswordFlags arg_ask_password_flags = ASK_PASSWORD_ACCEPT_CACHED | ASK_PASSWORD_PUSH_CACHE;
94
static bool arg_discards = false;
95
static bool arg_same_cpu_crypt = false;
96
static bool arg_submit_from_crypt_cpus = false;
97
static bool arg_no_read_workqueue = false;
98
static bool arg_no_write_workqueue = false;
99
static bool arg_tcrypt_hidden = false;
100
static bool arg_tcrypt_system = false;
101
static bool arg_tcrypt_veracrypt = false;
102
static uint32_t arg_tcrypt_veracrypt_pim = 0;
103
static char **arg_tcrypt_keyfiles = NULL;
104
static uint64_t arg_offset = 0;
105
static uint64_t arg_skip = 0;
106
static usec_t arg_timeout = USEC_INFINITY;
107
static char *arg_pkcs11_uri = NULL;
108
static bool arg_pkcs11_uri_auto = false;
109
static char *arg_fido2_device = NULL;
110
static bool arg_fido2_device_auto = false;
111
static void *arg_fido2_cid = NULL;
112
static size_t arg_fido2_cid_size = 0;
113
static char *arg_fido2_rp_id = NULL;
114
/* For now and for compatibility, if the user explicitly configured FIDO2 support and we do
115
 * not read FIDO2 metadata off the LUKS2 header, default to the systemd 248 logic, where we
116
 * use PIN + UP when needed, and do not configure UV at all. */
117
static Fido2EnrollFlags arg_fido2_manual_flags = FIDO2ENROLL_PIN_IF_NEEDED | FIDO2ENROLL_UP_IF_NEEDED | FIDO2ENROLL_UV_OMIT;
118
static char *arg_tpm2_device = NULL; /* These and the following fields are about locking an encrypted volume to the local TPM */
119
static bool arg_tpm2_device_auto = false;
120
static uint32_t arg_tpm2_pcr_mask = UINT32_MAX;
121
static char *arg_tpm2_signature = NULL;
122
static bool arg_tpm2_pin = false;
123
static char *arg_tpm2_pcrlock = NULL;
124
static usec_t arg_token_timeout_usec = 30*USEC_PER_SEC;
125
static unsigned arg_tpm2_measure_pcr = UINT_MAX; /* This and the following field is about measuring the unlocked volume key to the local TPM */
126
static char **arg_tpm2_measure_banks = NULL;
127
static char *arg_tpm2_measure_keyslot_nvpcr = NULL;
128
static char *arg_link_keyring = NULL;
129
static char *arg_link_key_type = NULL;
130
static char *arg_link_key_description = NULL;
131
static char *arg_fixate_volume_key = NULL;
132

133
STATIC_DESTRUCTOR_REGISTER(arg_cipher, freep);
151✔
134
STATIC_DESTRUCTOR_REGISTER(arg_hash, freep);
151✔
135
STATIC_DESTRUCTOR_REGISTER(arg_header, freep);
151✔
136
STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles, strv_freep);
151✔
137
STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri, freep);
151✔
138
STATIC_DESTRUCTOR_REGISTER(arg_fido2_device, freep);
151✔
139
STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid, freep);
151✔
140
STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id, freep);
151✔
141
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
151✔
142
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_signature, freep);
151✔
143
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_measure_banks, strv_freep);
151✔
144
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_measure_keyslot_nvpcr, freep);
151✔
145
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_pcrlock, freep);
151✔
146
STATIC_DESTRUCTOR_REGISTER(arg_link_keyring, freep);
151✔
147
STATIC_DESTRUCTOR_REGISTER(arg_link_key_type, freep);
151✔
148
STATIC_DESTRUCTOR_REGISTER(arg_link_key_description, freep);
151✔
149
STATIC_DESTRUCTOR_REGISTER(arg_fixate_volume_key, freep);
151✔
150

151
static const char* const passphrase_type_table[_PASSPHRASE_TYPE_MAX] = {
152
        [PASSPHRASE_REGULAR]      = "passphrase",
153
        [PASSPHRASE_RECOVERY_KEY] = "recovery key",
154
        [PASSPHRASE_BOTH]         = "passphrase or recovery key",
155
};
156

157
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(passphrase_type, PassphraseType);
×
158

159
static const char* const token_type_table[_TOKEN_TYPE_MAX] = {
160
        [TOKEN_TPM2]   = "tpm2",
161
        [TOKEN_FIDO2]  = "fido2",
162
        [TOKEN_PKCS11] = "pkcs11",
163
};
164

165
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(token_type, TokenType);
46✔
166

167
/* Options Debian's crypttab knows we don't:
168
    check=
169
    checkargs=
170
    noearly
171
    loud
172
    quiet
173
    keyscript=
174
    initramfs
175
*/
176

177
static int parse_one_option(const char *option) {
165✔
178
        const char *val;
165✔
179
        int r;
165✔
180

181
        assert(option);
165✔
182

183
        /* Handled outside of this tool */
184
        if (STR_IN_SET(option, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
165✔
185
                return 0;
1✔
186

187
        if (startswith(option, "keyfile-timeout="))
164✔
188
                return 0;
189

190
        if ((val = startswith(option, "cipher="))) {
164✔
191
                r = free_and_strdup(&arg_cipher, val);
×
192
                if (r < 0)
×
193
                        return log_oom();
×
194

195
        } else if ((val = startswith(option, "size="))) {
164✔
196
                unsigned key_size;
×
197

198
                r = safe_atou(val, &key_size);
×
199
                if (r < 0) {
×
200
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
201
                        return 0;
×
202
                }
203

204
                if (key_size % 8) {
×
205
                        log_warning("size= not a multiple of 8, ignoring.");
×
206
                        return 0;
207
                }
208

209
                arg_key_size = key_size / 8;
×
210

211
        } else if ((val = startswith(option, "sector-size="))) {
164✔
212

213
                r = safe_atou(val, &arg_sector_size);
×
214
                if (r < 0) {
×
215
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
216
                        return 0;
217
                }
218

219
                if (arg_sector_size % 2) {
×
220
                        log_warning("sector-size= not a multiple of 2, ignoring.");
×
221
                        return 0;
222
                }
223

224
                if (arg_sector_size < CRYPT_SECTOR_SIZE || arg_sector_size > CRYPT_MAX_SECTOR_SIZE)
×
225
                        log_warning("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE, CRYPT_MAX_SECTOR_SIZE);
×
226

227
        } else if ((val = startswith(option, "key-slot=")) ||
164✔
228
                   (val = startswith(option, "keyslot="))) {
162✔
229

230
                arg_type = ANY_LUKS;
2✔
231
                r = safe_atoi(val, &arg_key_slot);
2✔
232
                if (r < 0)
2✔
233
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
234

235
        } else if ((val = startswith(option, "tcrypt-keyfile="))) {
162✔
236

237
                arg_type = CRYPT_TCRYPT;
×
238
                if (path_is_absolute(val)) {
×
239
                        if (strv_extend(&arg_tcrypt_keyfiles, val) < 0)
×
240
                                return log_oom();
×
241
                } else
242
                        log_warning("Key file path \"%s\" is not absolute, ignoring.", val);
×
243

244
        } else if ((val = startswith(option, "keyfile-size="))) {
162✔
245

246
                r = safe_atou(val, &arg_keyfile_size);
3✔
247
                if (r < 0)
3✔
248
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
249

250
        } else if ((val = startswith(option, "keyfile-offset="))) {
159✔
251

252
                r = safe_atou64(val, &arg_keyfile_offset);
5✔
253
                if (r < 0)
5✔
254
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
255

256
        } else if ((val = startswith(option, "keyfile-erase="))) {
154✔
257

258
                r = parse_boolean(val);
2✔
259
                if (r < 0) {
2✔
260
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
261
                        return 0;
262
                }
263

264
                arg_keyfile_erase = r;
2✔
265

266
        } else if (streq(option, "keyfile-erase"))
152✔
267
                arg_keyfile_erase = true;
×
268

269
        else if ((val = startswith(option, "hash="))) {
152✔
270
                r = free_and_strdup(&arg_hash, val);
×
271
                if (r < 0)
×
272
                        return log_oom();
×
273

274
        } else if ((val = startswith(option, "header="))) {
152✔
275
                if (!arg_type || !STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT))
9✔
276
                        arg_type = ANY_LUKS;
7✔
277

278
                if (!path_is_absolute(val))
9✔
279
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
280
                                               "Header path \"%s\" is not absolute, refusing.", val);
281

282
                if (arg_header)
9✔
283
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
284
                                               "Duplicate header= option, refusing.");
285

286
                arg_header = strdup(val);
9✔
287
                if (!arg_header)
9✔
288
                        return log_oom();
×
289

290
        } else if ((val = startswith(option, "tries="))) {
143✔
291

292
                r = safe_atou(val, &arg_tries);
×
293
                if (r < 0)
×
294
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
165✔
295

296
        } else if (STR_IN_SET(option, "readonly", "read-only"))
143✔
297
                arg_readonly = true;
×
298
        else if (streq(option, "verify"))
143✔
299
                arg_verify = true;
×
300
        else if ((val = startswith(option, "password-echo="))) {
143✔
301
                if (streq(val, "masked"))
×
302
                        arg_ask_password_flags &= ~(ASK_PASSWORD_ECHO|ASK_PASSWORD_SILENT);
×
303
                else {
304
                        r = parse_boolean(val);
×
305
                        if (r < 0) {
×
306
                                log_warning_errno(r, "Invalid password-echo= option \"%s\", ignoring.", val);
×
307
                                return 0;
×
308
                        }
309

310
                        SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_ECHO, r);
×
311
                        SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_SILENT, !r);
×
312
                }
313
        } else if ((val = startswith(option, "password-cache="))) {
143✔
314
                if (streq(val, "read-only")) {
×
315
                        arg_ask_password_flags |= ASK_PASSWORD_ACCEPT_CACHED;
×
316
                        arg_ask_password_flags &= ~ASK_PASSWORD_PUSH_CACHE;
×
317
                } else {
318
                        r = parse_boolean(val);
×
319
                        if (r < 0) {
×
320
                                log_warning_errno(r, "Invalid password-cache= option \"%s\", ignoring.", val);
×
321
                                return 0;
322
                        }
323

324
                        SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_ACCEPT_CACHED|ASK_PASSWORD_PUSH_CACHE, r);
×
325
                }
326

327
                arg_password_cache_set = true;
×
328
        } else if (STR_IN_SET(option, "allow-discards", "discard"))
143✔
329
                arg_discards = true;
×
330
        else if (streq(option, "same-cpu-crypt"))
143✔
331
                arg_same_cpu_crypt = true;
×
332
        else if (streq(option, "submit-from-crypt-cpus"))
143✔
333
                arg_submit_from_crypt_cpus = true;
×
334
        else if (streq(option, "no-read-workqueue"))
143✔
335
                arg_no_read_workqueue = true;
×
336
        else if (streq(option, "no-write-workqueue"))
143✔
337
                arg_no_write_workqueue = true;
×
338
        else if (streq(option, "luks"))
143✔
339
                arg_type = ANY_LUKS;
8✔
340
        else if (streq(option, "bitlk"))
135✔
341
                arg_type = CRYPT_BITLK;
×
342
        else if (streq(option, "tcrypt"))
135✔
343
                arg_type = CRYPT_TCRYPT;
×
344
        else if (STR_IN_SET(option, "tcrypt-hidden", "tcrypthidden")) {
135✔
345
                arg_type = CRYPT_TCRYPT;
×
346
                arg_tcrypt_hidden = true;
×
347
        } else if (streq(option, "tcrypt-system")) {
135✔
348
                arg_type = CRYPT_TCRYPT;
×
349
                arg_tcrypt_system = true;
×
350
        } else if (STR_IN_SET(option, "tcrypt-veracrypt", "veracrypt")) {
135✔
351
                arg_type = CRYPT_TCRYPT;
×
352
                arg_tcrypt_veracrypt = true;
×
353
        } else if ((val = startswith(option, "veracrypt-pim="))) {
135✔
354

355
                r = safe_atou32(val, &arg_tcrypt_veracrypt_pim);
×
356
                if (r < 0) {
×
357
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
358
                        return 0;
×
359
                }
360
        } else if (STR_IN_SET(option, "plain", "swap", "tmp") ||
270✔
361
                   startswith(option, "tmp="))
135✔
362
                arg_type = CRYPT_PLAIN;
×
363
        else if ((val = startswith(option, "timeout="))) {
135✔
364

365
                r = parse_sec_fix_0(val, &arg_timeout);
×
366
                if (r < 0)
×
367
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
368

369
        } else if ((val = startswith(option, "offset="))) {
135✔
370

371
                r = safe_atou64(val, &arg_offset);
×
372
                if (r < 0)
×
373
                        return log_error_errno(r, "Failed to parse %s: %m", option);
×
374

375
        } else if ((val = startswith(option, "skip="))) {
135✔
376

377
                r = safe_atou64(val, &arg_skip);
×
378
                if (r < 0)
×
379
                        return log_error_errno(r, "Failed to parse %s: %m", option);
×
380

381
        } else if ((val = startswith(option, "pkcs11-uri="))) {
135✔
382

383
                if (streq(val, "auto")) {
9✔
384
                        arg_pkcs11_uri = mfree(arg_pkcs11_uri);
9✔
385
                        arg_pkcs11_uri_auto = true;
9✔
386
                } else {
387
                        if (!pkcs11_uri_valid(val))
×
388
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing.");
×
389

390
                        r = free_and_strdup(&arg_pkcs11_uri, val);
×
391
                        if (r < 0)
×
392
                                return log_oom();
×
393

394
                        arg_pkcs11_uri_auto = false;
×
395
                }
396

397
        } else if ((val = startswith(option, "fido2-device="))) {
126✔
398

399
                if (streq(val, "auto")) {
×
400
                        arg_fido2_device = mfree(arg_fido2_device);
×
401
                        arg_fido2_device_auto = true;
×
402
                } else {
403
                        r = free_and_strdup(&arg_fido2_device, val);
×
404
                        if (r < 0)
×
405
                                return log_oom();
×
406

407
                        arg_fido2_device_auto = false;
×
408
                }
409

410
        } else if ((val = startswith(option, "fido2-cid="))) {
126✔
411

412
                if (streq(val, "auto"))
×
413
                        arg_fido2_cid = mfree(arg_fido2_cid);
×
414
                else {
415
                        _cleanup_free_ void *cid = NULL;
×
416
                        size_t cid_size;
×
417

418
                        r = unbase64mem(val, &cid, &cid_size);
×
419
                        if (r < 0)
×
420
                                return log_error_errno(r, "Failed to decode FIDO2 CID data: %m");
×
421

422
                        free(arg_fido2_cid);
×
423
                        arg_fido2_cid = TAKE_PTR(cid);
×
424
                        arg_fido2_cid_size = cid_size;
×
425
                }
426

427
                /* Turn on FIDO2 as side-effect, if not turned on yet. */
428
                if (!arg_fido2_device && !arg_fido2_device_auto)
×
429
                        arg_fido2_device_auto = true;
×
430

431
        } else if ((val = startswith(option, "fido2-rp="))) {
126✔
432

433
                r = free_and_strdup(&arg_fido2_rp_id, val);
×
434
                if (r < 0)
×
435
                        return log_oom();
×
436

437
        } else if ((val = startswith(option, "fido2-pin="))) {
126✔
438

439
                r = parse_boolean(val);
×
440
                if (r < 0) {
×
441
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
442
                        return 0;
443
                }
444

445
                arg_fido2_manual_flags &= ~FIDO2ENROLL_PIN_IF_NEEDED;
×
446
                SET_FLAG(arg_fido2_manual_flags, FIDO2ENROLL_PIN, r);
×
447

448
        } else if ((val = startswith(option, "fido2-up="))) {
126✔
449

450
                r = parse_boolean(val);
×
451
                if (r < 0) {
×
452
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
453
                        return 0;
454
                }
455

456
                arg_fido2_manual_flags &= ~FIDO2ENROLL_UP_IF_NEEDED;
×
457
                SET_FLAG(arg_fido2_manual_flags, FIDO2ENROLL_UP, r);
×
458

459
        } else if ((val = startswith(option, "fido2-uv="))) {
126✔
460

461
                r = parse_boolean(val);
×
462
                if (r < 0) {
×
463
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
464
                        return 0;
465
                }
466

467
                arg_fido2_manual_flags &= ~FIDO2ENROLL_UV_OMIT;
×
468
                SET_FLAG(arg_fido2_manual_flags, FIDO2ENROLL_UV, r);
×
469

470
        } else if ((val = startswith(option, "tpm2-device="))) {
126✔
471

472
                if (streq(val, "auto")) {
43✔
473
                        arg_tpm2_device = mfree(arg_tpm2_device);
43✔
474
                        arg_tpm2_device_auto = true;
43✔
475
                } else {
476
                        r = free_and_strdup(&arg_tpm2_device, val);
×
477
                        if (r < 0)
×
478
                                return log_oom();
×
479

480
                        arg_tpm2_device_auto = false;
×
481
                }
482

483
        } else if ((val = startswith(option, "tpm2-pcrs="))) {
83✔
484

485
                r = tpm2_parse_pcr_argument_to_mask(val, &arg_tpm2_pcr_mask);
×
486
                if (r < 0)
×
487
                        return r;
488

489
        } else if ((val = startswith(option, "tpm2-signature="))) {
83✔
490

491
                if (!path_is_absolute(val))
3✔
492
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
493
                                               "TPM2 signature path \"%s\" is not absolute, refusing.", val);
494

495
                r = free_and_strdup(&arg_tpm2_signature, val);
3✔
496
                if (r < 0)
3✔
497
                        return log_oom();
×
498

499
        } else if ((val = startswith(option, "tpm2-pin="))) {
80✔
500

501
                r = parse_boolean(val);
×
502
                if (r < 0) {
×
503
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
504
                        return 0;
505
                }
506

507
                arg_tpm2_pin = r;
×
508

509
        } else if ((val = startswith(option, "tpm2-pcrlock="))) {
80✔
510

511
                if (!path_is_absolute(val))
5✔
512
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
513
                                               "TPM2 pcrlock policy path \"%s\" is not absolute, refusing.", val);
514

515
                r = free_and_strdup(&arg_tpm2_pcrlock, val);
5✔
516
                if (r < 0)
5✔
517
                        return log_oom();
×
518

519
        } else if ((val = startswith(option, "tpm2-measure-pcr="))) {
75✔
520
                unsigned pcr;
×
521

522
                r = safe_atou(val, &pcr);
×
523
                if (r < 0) {
×
524
                        r = parse_boolean(val);
×
525
                        if (r < 0) {
×
526
                                log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
527
                                return 0;
×
528
                        }
529

530
                        pcr = r ? TPM2_PCR_SYSTEM_IDENTITY : UINT_MAX;
×
531
                } else if (!TPM2_PCR_INDEX_VALID(pcr)) {
×
532
                        log_warning("Selected TPM index for measurement %u outside of allowed range 0…%u, ignoring.", pcr, TPM2_PCRS_MAX-1);
×
533
                        return 0;
534
                }
535

536
                arg_tpm2_measure_pcr = pcr;
×
537

538
        } else if ((val = startswith(option, "tpm2-measure-bank="))) {
75✔
539

540
#if HAVE_OPENSSL
541
                _cleanup_strv_free_ char **l = NULL;
×
542

543
                r = dlopen_libcrypto(LOG_ERR);
×
544
                if (r < 0)
×
545
                        return r;
546

547
                l = strv_split(val, ":");
×
548
                if (!l)
×
549
                        return log_oom();
×
550

551
                STRV_FOREACH(i, l) {
×
552
                        const EVP_MD *implementation;
×
553

554
                        implementation = sym_EVP_get_digestbyname(*i);
×
555
                        if (!implementation)
×
556
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown bank '%s', refusing.", val);
×
557

558
                        if (strv_extend(&arg_tpm2_measure_banks, sym_EVP_MD_get0_name(implementation)) < 0)
×
559
                                return log_oom();
×
560
                }
561
#else
562
                log_error("Build lacks OpenSSL support, cannot measure to PCR banks, ignoring: %s", option);
563
#endif
564

565
        } else if ((val = startswith(option, "tpm2-measure-keyslot-nvpcr="))) {
75✔
566

567
                r = isempty(val) ? false : parse_boolean(val);
×
568
                if (r == 0) {
×
569
                        arg_tpm2_measure_keyslot_nvpcr = mfree(arg_tpm2_measure_keyslot_nvpcr);
×
570
                        return 0;
×
571
                }
572
                if (r > 0)
×
573
                        val = "cryptsetup";
574
                else if (!tpm2_nvpcr_name_is_valid(val)) {
×
575
                        log_warning("Invalid NvPCR name, ignoring: %s", option);
×
576
                        return 0;
577
                }
578

579
                if (free_and_strdup(&arg_tpm2_measure_keyslot_nvpcr, val) < 0)
×
580
                        return log_oom();
×
581

582
        } else if ((val = startswith(option, "try-empty-password="))) {
75✔
583

584
                r = parse_boolean(val);
1✔
585
                if (r < 0) {
1✔
586
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
587
                        return 0;
588
                }
589

590
                arg_try_empty_password = r;
1✔
591

592
        } else if (streq(option, "try-empty-password"))
74✔
593
                arg_try_empty_password = true;
1✔
594
        else if ((val = startswith(option, "headless="))) {
73✔
595

596
                r = parse_boolean(val);
62✔
597
                if (r < 0) {
62✔
598
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
599
                        return 0;
600
                }
601

602
                SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_HEADLESS, r);
62✔
603
        } else if (streq(option, "headless"))
11✔
604
                arg_ask_password_flags |= ASK_PASSWORD_HEADLESS;
7✔
605

606
        else if ((val = startswith(option, "token-timeout="))) {
4✔
607

608
                r = parse_sec_fix_0(val, &arg_token_timeout_usec);
×
609
                if (r < 0)
×
610
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
135✔
611

612
        } else if ((val = startswith(option, "link-volume-key="))) {
4✔
613
                _cleanup_free_ char *keyring = NULL, *key_type = NULL, *key_description = NULL;
×
614
                const char *sep;
×
615

616
                /* Stick with cryptsetup --link-vk-to-keyring format
617
                 * <keyring_description>::%<key_type>:<key_description>,
618
                 * where %<key_type> is optional and defaults to 'user'.
619
                 */
620
                sep = strstr(val, "::");
×
621
                if (!sep)
×
622
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse link-volume-key= option value: %s", val);
×
623

624
                /* cryptsetup (cli) supports <keyring_description> passed in various formats:
625
                 * - well-known keyrings prefixed with '@' (@u user, @s session, etc)
626
                 * - text descriptions prefixed with "%:" or "%keyring:".
627
                 * - text description with no prefix.
628
                 * - numeric keyring id (ignored in current patch set). */
629
                keyring = strndup(val, sep - val);
×
630
                if (!keyring)
×
631
                        return log_oom();
×
632

633
                /* add type prefix if missing (crypt_set_keyring_to_link() expects it) */
634
                if (!IN_SET(*keyring, '@', '%'))
×
635
                        if (!strprepend(&keyring, "%:"))
×
636
                                return log_oom();
×
637

638
                sep += 2;
×
639

640
                /* %<key_type> is optional (and defaults to 'user') */
641
                if (*sep == '%') {
×
642
                        /* must be separated by colon */
643
                        const char *c = strchr(sep, ':');
×
644
                        if (!c)
×
645
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse link-volume-key= option value: %s", val);
×
646

647
                        key_type = strndup(sep + 1, c - sep - 1);
×
648
                        if (!key_type)
×
649
                                return log_oom();
×
650

651
                        sep = c + 1;
×
652
                }
653

654
                key_description = strdup(sep);
×
655
                if (!key_description)
×
656
                        return log_oom();
×
657

658
                free_and_replace(arg_link_keyring, keyring);
×
659
                free_and_replace(arg_link_key_type, key_type);
×
660
                free_and_replace(arg_link_key_description, key_description);
×
661
        } else if ((val = startswith(option, "fixate-volume-key="))) {
4✔
662
                r = free_and_strdup(&arg_fixate_volume_key, val);
4✔
663
                if (r < 0)
4✔
664
                        return log_oom();
×
665

666
        } else if (!streq(option, "x-initrd.attach"))
×
667
                log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
×
668

669
        return 0;
670
}
671

672
static int parse_crypt_config(const char *options) {
81✔
673
        assert(options);
81✔
674

675
        for (;;) {
411✔
676
                _cleanup_free_ char *word = NULL;
165✔
677
                int r;
246✔
678

679
                r = extract_first_word(&options, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS | EXTRACT_UNESCAPE_SEPARATORS);
246✔
680
                if (r < 0)
246✔
681
                        return log_error_errno(r, "Failed to parse options: %m");
×
682
                if (r == 0)
246✔
683
                        break;
684

685
                r = parse_one_option(word);
165✔
686
                if (r < 0)
165✔
687
                        return r;
688
        }
689

690
        /* sanity-check options */
691
        if (arg_type && !streq(arg_type, CRYPT_PLAIN)) {
81✔
692
                if (arg_offset != 0)
17✔
693
                      log_warning("offset= ignored with type %s", arg_type);
×
694
                if (arg_skip != 0)
17✔
695
                      log_warning("skip= ignored with type %s", arg_type);
×
696
        }
697

698
        if (arg_pkcs11_uri || arg_pkcs11_uri_auto) {
81✔
699
                /* If password-cache was not configured explicitly, default to no cache for PKCS#11 */
700
                if (!arg_password_cache_set)
9✔
701
                        arg_ask_password_flags &= ~(ASK_PASSWORD_ACCEPT_CACHED|ASK_PASSWORD_PUSH_CACHE);
9✔
702

703
                /* This prevents future backward-compatibility issues if we decide to allow caching for PKCS#11 */
704
                if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_ACCEPT_CACHED))
9✔
705
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
706
                                               "Password cache is not supported for PKCS#11 security tokens.");
707
        }
708

709
        return 0;
710
}
711

712
static char* disk_description(const char *path) {
14✔
713
        static const char name_fields[] =
14✔
714
                "DM_NAME\0"
715
                "ID_MODEL_FROM_DATABASE\0"
716
                "ID_MODEL\0";
717

718
        _cleanup_(sd_device_unrefp) sd_device *device = NULL;
14✔
719
        const char *name;
14✔
720
        struct stat st;
14✔
721

722
        assert(path);
14✔
723

724
        if (stat(path, &st) < 0)
14✔
725
                return NULL;
726

727
        if (!S_ISBLK(st.st_mode))
14✔
728
                return NULL;
729

730
        if (sd_device_new_from_stat_rdev(&device, &st) < 0)
×
731
                return NULL;
732

733
        if (sd_device_get_property_value(device, "ID_PART_ENTRY_NAME", &name) >= 0) {
×
734
                _cleanup_free_ char *unescaped = NULL;
×
735
                ssize_t l;
×
736

737
                /* ID_PART_ENTRY_NAME uses \x style escaping, using libblkid's blkid_encode_string(). Let's
738
                 * reverse this here to make the string more human friendly in case people embed spaces or
739
                 * other weird stuff. */
740

741
                l = cunescape(name, UNESCAPE_RELAX, &unescaped);
×
742
                if (l < 0) {
×
743
                        log_debug_errno(l, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
×
744
                        return NULL;
745
                }
746

747
                if (!isempty(unescaped) && !string_has_cc(unescaped, NULL))
×
748
                        return TAKE_PTR(unescaped);
×
749
        }
750

751
        /* These need no unescaping. */
752
        NULSTR_FOREACH(i, name_fields)
×
753
                if (sd_device_get_property_value(device, i, &name) >= 0 &&
×
754
                    !isempty(name))
×
755
                        return strdup(name);
×
756

757
        return NULL;
758
}
759

760
static char* disk_mount_point(const char *label) {
14✔
761
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
14✔
762
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
×
763
        _cleanup_free_ char *device = NULL;
14✔
764
        int r;
14✔
765

766
        /* Yeah, we don't support native systemd unit files here for now */
767

768
        assert(label);
14✔
769

770
        device = strjoin("/dev/mapper/", label);
14✔
771
        if (!device)
14✔
772
                return NULL;
773

774
        r = libmount_parse_fstab(&table, &iter);
14✔
775
        if (r < 0)
14✔
776
                return NULL;
777

778
        for (;;) {
×
779
                struct libmnt_fs *fs;
14✔
780

781
                r = sym_mnt_table_next_fs(table, iter, &fs);
14✔
782
                if (r != 0)
14✔
783
                        return NULL;
14✔
784

785
                if (path_equal(sym_mnt_fs_get_source(fs), device)) {
×
786
                        const char *target = sym_mnt_fs_get_target(fs);
×
787
                        if (target)
×
788
                                return strdup(target);
×
789
                }
790
        }
791
}
792

793
static char *friendly_disk_name(const char *src, const char *vol) {
14✔
794
        _cleanup_free_ char *description = NULL, *mount_point = NULL;
14✔
795
        char *name_buffer = NULL;
14✔
796
        int r;
14✔
797

798
        assert(src);
14✔
799
        assert(vol);
14✔
800

801
        description = disk_description(src);
14✔
802
        mount_point = disk_mount_point(vol);
14✔
803

804
        /* If the description string is simply the volume name, then let's not show this twice */
805
        if (description && streq(vol, description))
14✔
806
                description = mfree(description);
×
807

808
        if (mount_point && description)
14✔
809
                r = asprintf(&name_buffer, "%s (%s) on %s", description, vol, mount_point);
×
810
        else if (mount_point)
×
811
                r = asprintf(&name_buffer, "%s on %s", vol, mount_point);
×
812
        else if (description)
14✔
813
                r = asprintf(&name_buffer, "%s (%s)", description, vol);
×
814
        else
815
                return strdup(vol);
14✔
816
        if (r < 0)
×
817
                return NULL;
818

819
        return name_buffer;
×
820
}
821

822
static PassphraseType check_registered_passwords(struct crypt_device *cd) {
15✔
823
        _cleanup_free_ bool *slots = NULL;
15✔
824
        int slot_max;
15✔
825
        PassphraseType passphrase_type = PASSPHRASE_NONE;
15✔
826

827
        assert(cd);
15✔
828

829
        if (!streq_ptr(sym_crypt_get_type(cd), CRYPT_LUKS2)) {
15✔
830
                log_debug("%s: not a LUKS2 device, only passphrases are supported", sym_crypt_get_device_name(cd));
×
831
                return PASSPHRASE_REGULAR;
832
        }
833

834
        /* Search all used slots */
835
        assert_se((slot_max = sym_crypt_keyslot_max(CRYPT_LUKS2)) > 0);
15✔
836
        slots = new(bool, slot_max);
15✔
837
        if (!slots)
15✔
838
                return log_oom();
×
839

840
        for (int slot = 0; slot < slot_max; slot++)
495✔
841
                slots[slot] = IN_SET(sym_crypt_keyslot_status(cd, slot), CRYPT_SLOT_ACTIVE, CRYPT_SLOT_ACTIVE_LAST);
480✔
842

843
        /* Iterate all LUKS2 tokens and keep track of all their slots */
844
        for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
495✔
845
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
480✔
846
                const char *type;
480✔
847
                sd_json_variant *w, *z;
480✔
848
                int tk;
480✔
849

850
                tk = cryptsetup_get_token_as_json(cd, token, NULL, &v);
480✔
851
                if (IN_SET(tk, -ENOENT, -EINVAL))
480✔
852
                        continue;
470✔
853
                if (tk < 0) {
10✔
854
                        log_warning_errno(tk, "Failed to read JSON token data, ignoring: %m");
×
855
                        continue;
×
856
                }
857

858
                w = sd_json_variant_by_key(v, "type");
10✔
859
                if (!w || !sd_json_variant_is_string(w)) {
10✔
860
                        log_warning("Token JSON data lacks type field, ignoring.");
×
861
                        continue;
×
862
                }
863

864
                type = sd_json_variant_string(w);
10✔
865
                if (STR_IN_SET(type, "systemd-recovery", "systemd-pkcs11", "systemd-fido2", "systemd-tpm2")) {
10✔
866

867
                        /* At least exists one recovery key */
868
                        if (streq(type, "systemd-recovery"))
10✔
869
                                passphrase_type |= PASSPHRASE_RECOVERY_KEY;
×
870

871
                        w = sd_json_variant_by_key(v, "keyslots");
10✔
872
                        if (!w || !sd_json_variant_is_array(w)) {
10✔
873
                                log_warning("Token JSON data lacks keyslots field, ignoring.");
×
874
                                continue;
×
875
                        }
876

877
                        JSON_VARIANT_ARRAY_FOREACH(z, w) {
20✔
878
                                unsigned u;
10✔
879
                                int at;
10✔
880

881
                                if (!sd_json_variant_is_string(z)) {
10✔
882
                                        log_warning("Token JSON data's keyslot field is not an array of strings, ignoring.");
×
883
                                        continue;
×
884
                                }
885

886
                                at = safe_atou(sd_json_variant_string(z), &u);
10✔
887
                                if (at < 0) {
10✔
888
                                        log_warning_errno(at, "Token JSON data's keyslot field is not an integer formatted as string, ignoring.");
×
889
                                        continue;
×
890
                                }
891

892
                                if (u >= (unsigned) slot_max) {
10✔
893
                                        log_warning_errno(at, "Token JSON data's keyslot field exceeds the maximum value allowed, ignoring.");
×
894
                                        continue;
×
895
                                }
896

897
                                slots[u] = false;
10✔
898
                        }
899
                }
900
        }
901

902
        /* Check if any of the slots is not referenced by systemd tokens */
903
        for (int slot = 0; slot < slot_max; slot++)
15✔
904
                if (slots[slot]) {
15✔
905
                        passphrase_type |= PASSPHRASE_REGULAR;
15✔
906
                        break;
15✔
907
                }
908

909
        /* All the slots are referenced by systemd tokens, so if a recovery key is not enrolled,
910
         * we will not be able to enter a passphrase. */
911
        return passphrase_type;
912
}
913

914
static int get_password(
15✔
915
                const char *vol,
916
                const char *src,
917
                usec_t until,
918
                bool ignore_cached,
919
                PassphraseType passphrase_type,
920
                char ***ret) {
921

922
        _cleanup_free_ char *friendly = NULL, *text = NULL, *disk_path = NULL, *id = NULL;
15✔
923
        _cleanup_strv_free_erase_ char **passwords = NULL;
×
924
        AskPasswordFlags flags = arg_ask_password_flags;
15✔
925
        int r;
15✔
926

927
        assert(vol);
15✔
928
        assert(src);
15✔
929
        assert(ret);
15✔
930

931
        if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_HEADLESS))
15✔
932
                return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Password querying disabled via 'headless' option.");
15✔
933

934
        friendly = friendly_disk_name(src, vol);
×
935
        if (!friendly)
×
936
                return log_oom();
×
937

938
        if (asprintf(&text, "Please enter %s for disk %s:", passphrase_type_to_string(passphrase_type), friendly) < 0)
×
939
                return log_oom();
×
940

941
        disk_path = cescape(src);
×
942
        if (!disk_path)
×
943
                return log_oom();
×
944

945
        id = strjoin("cryptsetup:", disk_path);
×
946
        if (!id)
×
947
                return log_oom();
×
948

949
        AskPasswordRequest req = {
×
950
                .tty_fd = -EBADF,
951
                .message = text,
952
                .icon = "drive-harddisk",
953
                .id = id,
954
                .keyring = "cryptsetup",
955
                .credential = "cryptsetup.passphrase",
956
                .until = until,
957
                .hup_fd = -EBADF,
958
        };
959

960
        if (ignore_cached)
×
961
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
×
962

963
        r = ask_password_auto(&req, flags, &passwords);
×
964
        if (r < 0)
×
965
                return log_error_errno(r, "Failed to query password: %m");
×
966

967
        if (arg_verify) {
×
968
                _cleanup_strv_free_erase_ char **passwords2 = NULL;
×
969

970
                assert(strv_length(passwords) == 1);
×
971

972
                text = mfree(text);
×
973
                if (asprintf(&text, "Please enter %s for disk %s (verification):", passphrase_type_to_string(passphrase_type), friendly) < 0)
×
974
                        return log_oom();
×
975

976
                free(id);
×
977
                id = strjoin("cryptsetup-verification:", disk_path);
×
978
                if (!id)
×
979
                        return log_oom();
×
980

981
                req.message = text;
×
982
                req.id = id;
×
983

984
                r = ask_password_auto(&req, flags, &passwords2);
×
985
                if (r < 0)
×
986
                        return log_error_errno(r, "Failed to query verification password: %m");
×
987

988
                assert(strv_length(passwords2) == 1);
×
989

990
                if (!streq(passwords[0], passwords2[0]))
×
991
                        return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN),
×
992
                                                 "Passwords did not match, retrying.");
993
        }
994

995
        strv_uniq(passwords);
×
996

997
        STRV_FOREACH(p, passwords) {
×
998
                char *c;
×
999

1000
                if (strlen(*p)+1 >= arg_key_size)
×
1001
                        continue;
×
1002

1003
                /* Pad password if necessary */
1004
                c = new(char, arg_key_size);
×
1005
                if (!c)
×
1006
                        return log_oom();
15✔
1007

1008
                strncpy(c, *p, arg_key_size);
×
1009
                erase_and_free(*p);
×
1010
                *p = TAKE_PTR(c);
×
1011
        }
1012

1013
        *ret = TAKE_PTR(passwords);
×
1014

1015
        return 0;
×
1016
}
1017

1018
static int measure_volume_key(
×
1019
                struct crypt_device *cd,
1020
                const char *name,
1021
                const void *volume_key,
1022
                size_t volume_key_size) {
1023

1024
        int r;
×
1025

1026
        assert(cd);
×
1027
        assert(name);
×
1028
        assert(volume_key);
×
1029
        assert(volume_key_size > 0);
×
1030

1031
        if (arg_tpm2_measure_pcr == UINT_MAX) {
×
1032
                log_debug("Not measuring volume key, deactivated.");
×
1033
                return 0;
×
1034
        }
1035

1036
        r = efi_measured_os(LOG_WARNING);
×
1037
        if (r < 0)
×
1038
                return r;
1039
        if (r == 0) {
×
1040
                log_debug("OS measurements not explicitly requested and kernel stub did not measure kernel image into the expected PCR, skipping userspace volume key measurement, too.");
×
1041
                return 0;
1042
        }
1043

1044
#if HAVE_TPM2
1045
        _cleanup_(tpm2_context_unrefp) Tpm2Context *c = NULL;
×
1046
        r = tpm2_context_new_or_warn(arg_tpm2_device, &c);
×
1047
        if (r < 0)
×
1048
                return r;
1049

1050
        _cleanup_strv_free_ char **l = NULL;
×
1051
        if (strv_isempty(arg_tpm2_measure_banks)) {
×
1052
                r = tpm2_get_good_pcr_banks_strv(c, UINT32_C(1) << arg_tpm2_measure_pcr, &l);
×
1053
                if (r < 0)
×
1054
                        return log_error_errno(r, "Could not verify pcr banks: %m");
×
1055
        }
1056

1057
        _cleanup_free_ char *joined = strv_join(l ?: arg_tpm2_measure_banks, ", ");
×
1058
        if (!joined)
×
1059
                return log_oom();
×
1060

1061
        /* Note: we don't directly measure the volume key, it might be a security problem to send an
1062
         * unprotected direct hash of the secret volume key over the wire to the TPM. Hence let's instead
1063
         * send a HMAC signature instead. */
1064

1065
        _cleanup_free_ char *prefix = NULL;
×
1066

1067
        /* Note: what is extended to the SHA256 bank here must match the expected hash of 'fixate-volume-key='
1068
         * calculated by cryptsetup_get_volume_key_id(). */
1069
        r = cryptsetup_get_volume_key_prefix(cd, name, &prefix);
×
1070
        if (r)
×
1071
                return log_error_errno(r, "Could not verify pcr banks: %m");
×
1072

1073
        r = tpm2_pcr_extend_bytes(
×
1074
                        c,
1075
                        /* banks= */ l ?: arg_tpm2_measure_banks,
×
1076
                        /* pcr_index = */ arg_tpm2_measure_pcr,
1077
                        /* data = */ &IOVEC_MAKE_STRING(prefix),
×
1078
                        /* secret = */ &IOVEC_MAKE(volume_key, volume_key_size),
×
1079
                        /* event_type = */ TPM2_EVENT_VOLUME_KEY,
1080
                        /* description = */ prefix);
1081
        if (r < 0)
×
1082
                return log_error_errno(r, "Could not extend PCR: %m");
×
1083

1084
        log_struct(LOG_INFO,
×
1085
                   LOG_MESSAGE_ID(SD_MESSAGE_TPM_PCR_EXTEND_STR),
1086
                   LOG_MESSAGE("Successfully extended PCR index %u with '%s' and volume key (banks %s).", arg_tpm2_measure_pcr, prefix, joined),
1087
                   LOG_ITEM("MEASURING=%s", prefix),
1088
                   LOG_ITEM("PCR=%u", arg_tpm2_measure_pcr),
1089
                   LOG_ITEM("BANKS=%s", joined));
1090

1091
        return 0;
1092
#else
1093
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support disabled, not measuring volume key.");
1094
#endif
1095
}
1096

1097
static int measure_keyslot(
25✔
1098
                struct crypt_device *cd,
1099
                const char *name,
1100
                const char *mechanism,
1101
                int keyslot) {
1102

1103
#if HAVE_TPM2
1104
        int r;
25✔
1105
#endif
1106
        assert(cd);
25✔
1107
        assert(name);
25✔
1108

1109
        if (!arg_tpm2_measure_keyslot_nvpcr) {
25✔
1110
                log_debug("Not measuring unlock keyslot, deactivated.");
25✔
1111
                return 0;
25✔
1112
        }
1113

1114
#if HAVE_TPM2
1115
        r = efi_measured_os(LOG_WARNING);
×
1116
        if (r < 0)
×
1117
                return r;
1118
        if (r == 0) {
×
1119
                log_debug("OS measurements not explicitly requested and kernel stub did not measure kernel image into the expected PCR, skipping userspace key slot measurement, too.");
×
1120
                return 0;
1121
        }
1122

1123
        _cleanup_(tpm2_context_unrefp) Tpm2Context *c = NULL;
×
1124
        r = tpm2_context_new_or_warn(arg_tpm2_device, &c);
×
1125
        if (r < 0)
×
1126
                return r;
1127

1128
        _cleanup_free_ char *escaped = NULL;
×
1129
        escaped = xescape(name, ":"); /* avoid ambiguity around ":" once we join things below */
×
1130
        if (!escaped)
×
1131
                return log_oom();
×
1132

1133
        _cleanup_free_ char *k = NULL;
×
1134
        if (keyslot >= 0 && asprintf(&k, "%i", keyslot) < 0)
×
1135
                return log_oom();
×
1136

1137
        _cleanup_free_ char *s = NULL;
×
1138
        s = strjoin("cryptsetup-keyslot:", escaped, ":", strempty(sym_crypt_get_uuid(cd)), ":", strempty(mechanism), ":", strempty(k));
×
1139
        if (!s)
×
1140
                return log_oom();
×
1141

1142
        r = tpm2_nvpcr_extend_bytes(
×
1143
                        c,
1144
                        /* session= */ NULL,
1145
                        arg_tpm2_measure_keyslot_nvpcr,
1146
                        &IOVEC_MAKE_STRING(s),
×
1147
                        /* secret= */ NULL,
1148
                        /* sync_secondary_anchor= */ false,
1149
                        TPM2_EVENT_KEYSLOT,
1150
                        s);
1151
        if (r < 0)
×
1152
                return log_error_errno(r, "Could not extend NvPCR: %m");
×
1153

1154
        log_struct(LOG_INFO,
×
1155
                   "MESSAGE_ID=" SD_MESSAGE_TPM_NVPCR_EXTEND_STR,
1156
                   LOG_MESSAGE("Successfully extended NvPCR index '%s' with '%s'.", arg_tpm2_measure_keyslot_nvpcr, s),
1157
                   "MEASURING=%s", s,
1158
                   "NVPCR=%s", arg_tpm2_measure_keyslot_nvpcr);
1159

1160
        return 0;
1161
#else
1162
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support disabled, not measuring keyslot.");
1163
#endif
1164
}
1165

1166
static int log_external_activation(int r, const char *volume) {
×
1167
        assert(volume);
×
1168

1169
        log_notice_errno(r, "Volume '%s' has been activated externally while we have been trying to activate it.", volume);
×
1170
        return 0;
×
1171
}
1172

1173
static int measured_crypt_activate_by_volume_key(
4✔
1174
                struct crypt_device *cd,
1175
                const char *name,
1176
                const char *mechanism,
1177
                int keyslot,
1178
                const void *volume_key,
1179
                size_t volume_key_size,
1180
                uint32_t flags) {
1181

1182
        int r;
4✔
1183

1184
        assert(cd);
4✔
1185
        assert(name);
4✔
1186

1187
        /* A wrapper around crypt_activate_by_volume_key() which also measures to a PCR if that's requested. */
1188

1189
        /* First, check if volume key digest matches the expectation. */
1190
        if (arg_fixate_volume_key) {
4✔
1191
                 _cleanup_free_ char *key_id = NULL;
4✔
1192

1193
                 r = cryptsetup_get_volume_key_id(
4✔
1194
                                 cd,
1195
                                 /* volume_name= */ name,
1196
                                 /* volume_key= */ volume_key,
1197
                                 /* volume_key_size= */ volume_key_size,
1198
                                 /* ret= */ &key_id);
1199
                 if (r < 0)
4✔
1200
                         return log_error_errno(r, "Failed to get volume key id.");
×
1201

1202
                 if (!streq(arg_fixate_volume_key, key_id))
4✔
1203
                         return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2✔
1204
                                                "Volume key id: '%s' does not match the expectation: '%s'.",
1205
                                                key_id, arg_fixate_volume_key);
1206
        }
1207

1208
        r = sym_crypt_activate_by_volume_key(cd, name, volume_key, volume_key_size, flags);
2✔
1209
        if (r == -EEXIST) /* volume is already active */
2✔
1210
                return log_external_activation(r, name);
×
1211
        if (r < 0)
2✔
1212
                return r;
1213

1214
        if (arg_tpm2_measure_pcr == UINT_MAX) {
2✔
1215
                log_debug("Not measuring volume key, deactivated.");
2✔
1216
                return 0;
1217
        }
1218

1219
        if (volume_key_size > 0)
×
1220
                (void) measure_volume_key(cd, name, volume_key, volume_key_size); /* OK if fails */
×
1221
        else
1222
                log_debug("Not measuring volume key, none specified.");
×
1223

1224
        (void) measure_keyslot(cd, name, mechanism, keyslot); /* ditto */
×
1225
        return r;
×
1226
}
1227

1228
static int measured_crypt_activate_by_passphrase(
33✔
1229
                struct crypt_device *cd,
1230
                const char *name,
1231
                const char *mechanism,
1232
                int keyslot,
1233
                const char *passphrase,
1234
                size_t passphrase_size,
1235
                uint32_t flags) {
1236

1237
        _cleanup_(erase_and_freep) void *vk = NULL;
33✔
1238
        size_t vks;
33✔
1239
        int r;
33✔
1240

1241
        assert(cd);
33✔
1242

1243
        /* A wrapper around crypt_activate_by_passphrase() which also measures to a PCR if that's
1244
         * requested. Note that we may need the volume key for the measurement and/or for the comparison, and
1245
         * crypt_activate_by_passphrase() doesn't give us access to this. Hence, we operate indirectly, and
1246
         * retrieve the volume key first, and then activate through that. */
1247

1248
        if (arg_tpm2_measure_pcr == UINT_MAX && !arg_fixate_volume_key)
33✔
1249
                goto shortcut;
29✔
1250

1251
        r = sym_crypt_get_volume_key_size(cd);
4✔
1252
        if (r < 0)
4✔
1253
                return r;
1254
        if (r == 0) {
4✔
1255
                log_debug("Not measuring volume key, none defined.");
×
1256
                goto shortcut;
×
1257
        }
1258

1259
        vk = malloc(vks = r);
4✔
1260
        if (!vk)
4✔
1261
                return -ENOMEM;
1262

1263
        keyslot = sym_crypt_volume_key_get(cd, keyslot, vk, &vks, passphrase, passphrase_size);
4✔
1264
        if (keyslot < 0)
4✔
1265
                return keyslot;
1266

1267
        return measured_crypt_activate_by_volume_key(cd, name, mechanism, keyslot, vk, vks, flags);
4✔
1268

1269
shortcut:
29✔
1270
        keyslot = sym_crypt_activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags);
29✔
1271
        if (keyslot == -EEXIST) /* volume is already active */
29✔
1272
                return log_external_activation(keyslot, name);
×
1273
        if (keyslot < 0)
29✔
1274
                return keyslot;
1275

1276
        (void) measure_keyslot(cd, name, mechanism, keyslot);
25✔
1277
        return keyslot;
1278
}
1279

1280
static int attach_tcrypt(
×
1281
                struct crypt_device *cd,
1282
                const char *name,
1283
                TokenType token_type,
1284
                const char *key_file,
1285
                const struct iovec *key_data,
1286
                char **passwords,
1287
                uint32_t flags) {
1288

1289
        int r = 0;
×
1290
        _cleanup_(erase_and_freep) char *passphrase = NULL;
×
1291
        struct crypt_params_tcrypt params = {
×
1292
                .flags = CRYPT_TCRYPT_LEGACY_MODES,
1293
                .keyfiles = (const char **)arg_tcrypt_keyfiles,
1294
                .keyfiles_count = strv_length(arg_tcrypt_keyfiles)
×
1295
        };
1296

1297
        assert(cd);
×
1298
        assert(name);
×
1299
        assert(key_file || key_data || !strv_isempty(passwords));
×
1300

1301
        if (token_type >= 0)
×
1302
                /* Ask for a regular password */
1303
                return log_error_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1304
                                       "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
1305

1306
        if (arg_tcrypt_hidden)
×
1307
                params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
×
1308

1309
        if (arg_tcrypt_system)
×
1310
                params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
×
1311

1312
        if (arg_tcrypt_veracrypt)
×
1313
                params.flags |= CRYPT_TCRYPT_VERA_MODES;
×
1314

1315
        if (arg_tcrypt_veracrypt && arg_tcrypt_veracrypt_pim != 0)
×
1316
                params.veracrypt_pim = arg_tcrypt_veracrypt_pim;
×
1317

1318
        if (key_data) {
×
1319
                params.passphrase = key_data->iov_base;
×
1320
                params.passphrase_size = key_data->iov_len;
×
1321
                r = sym_crypt_load(cd, CRYPT_TCRYPT, &params);
×
1322
        } else if (key_file) {
×
1323
                r = read_one_line_file(key_file, &passphrase);
×
1324
                if (r < 0) {
×
1325
                        log_error_errno(r, "Failed to read password file '%s': %m", key_file);
×
1326
                        return -EAGAIN; /* log with the actual error, but return EAGAIN */
1327
                }
1328
                params.passphrase = passphrase;
×
1329
                params.passphrase_size = strlen(passphrase);
×
1330
                r = sym_crypt_load(cd, CRYPT_TCRYPT, &params);
×
1331
        } else {
1332
                r = -EINVAL;
1333
                STRV_FOREACH(p, passwords){
×
1334
                        params.passphrase = *p;
×
1335
                        params.passphrase_size = strlen(*p);
×
1336
                        r = sym_crypt_load(cd, CRYPT_TCRYPT, &params);
×
1337
                        if (r >= 0)
×
1338
                                break;
1339
                }
1340
        }
1341

1342
        if (r < 0) {
×
1343
                if (r == -EPERM) {
×
1344
                        if (key_data)
×
1345
                                log_error_errno(r, "Failed to activate using discovered key. (Key not correct?)");
×
1346
                        else if (key_file)
×
1347
                                log_error_errno(r, "Failed to activate using password file '%s'. (Key data not correct?)", key_file);
×
1348
                        else
1349
                                log_error_errno(r, "Failed to activate using supplied passwords.");
×
1350

1351
                        return r;
1352
                }
1353

1354
                return log_error_errno(r, "Failed to load tcrypt superblock on device %s: %m", sym_crypt_get_device_name(cd));
×
1355
        }
1356

1357
        r = measured_crypt_activate_by_volume_key(
×
1358
                        cd,
1359
                        name,
1360
                        /* mechanism= */ NULL,
1361
                        /* keyslot= */ -1,
1362
                        /* volume_key= */ NULL,
1363
                        /* volume_key_size= */ 0,
1364
                        flags);
1365
        if (r < 0)
×
1366
                return log_error_errno(r, "Failed to activate tcrypt device %s: %m", sym_crypt_get_device_name(cd));
×
1367

1368
        return 0;
1369
}
1370

1371
static char *make_bindname(const char *volume, TokenType token_type) {
45✔
1372
        const char *token_type_name = token_type_to_string(token_type), *suffix;
45✔
1373
        char *bindname;
45✔
1374
        int r;
45✔
1375

1376
        switch (token_type) {
45✔
1377

1378
        case TOKEN_FIDO2:
1379
                suffix = "-salt";
1380
                break;
1381

1382
        default:
1383
                suffix = NULL;
45✔
1384
        }
1385

1386
        r = asprintf(&bindname,
45✔
1387
                     "@%" PRIx64"/cryptsetup%s%s%s/%s",
1388
                     random_u64(),
1389
                     token_type_name ? "-" : "",
1390
                     strempty(token_type_name),
1391
                     strempty(suffix),
1392
                     volume);
1393
        if (r < 0)
45✔
1394
                return NULL;
45✔
1395

1396
        return bindname;
45✔
1397
}
1398

1399
static int make_security_device_monitor(
×
1400
                sd_event **ret_event,
1401
                sd_device_monitor **ret_monitor) {
1402
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1403
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1404
        int r;
×
1405

1406
        assert(ret_event);
×
1407
        assert(ret_monitor);
×
1408

1409
        /* Waits for a device with "security-device" tag to show up in udev */
1410
        log_debug("Creating device monitor for tag 'security-device' with timeout %s",
×
1411
                  FORMAT_TIMESPAN(arg_token_timeout_usec, 1*USEC_PER_SEC));
1412

1413
        r = sd_event_default(&event);
×
1414
        if (r < 0)
×
1415
                return log_error_errno(r, "Failed to allocate event loop: %m");
×
1416

1417
        r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
×
1418
        if (r < 0)
×
1419
                return log_error_errno(r, "Failed to install timeout event source: %m");
×
1420

1421
        r = sd_device_monitor_new(&monitor);
×
1422
        if (r < 0)
×
1423
                return log_error_errno(r, "Failed to allocate device monitor: %m");
×
1424

1425
        (void) sd_device_monitor_set_description(monitor, "security-device");
×
1426

1427
        r = sd_device_monitor_filter_add_match_tag(monitor, "security-device");
×
1428
        if (r < 0)
×
1429
                return log_error_errno(r, "Failed to configure device monitor: %m");
×
1430

1431
        r = sd_device_monitor_attach_event(monitor, event);
×
1432
        if (r < 0)
×
1433
                return log_error_errno(r, "Failed to attach device monitor: %m");
×
1434

1435
        r = sd_device_monitor_start(monitor, NULL, NULL);
×
1436
        if (r < 0)
×
1437
                return log_error_errno(r, "Failed to start device monitor: %m");
×
1438

1439
        *ret_event = TAKE_PTR(event);
×
1440
        *ret_monitor = TAKE_PTR(monitor);
×
1441
        return 0;
×
1442
}
1443

1444
static int run_security_device_monitor(
×
1445
                sd_event *event,
1446
                sd_device_monitor *monitor) {
1447
        bool processed = false;
×
1448
        int r;
×
1449

1450
        assert(event);
×
1451
        assert(monitor);
×
1452

1453
        /* Runs the event loop for the device monitor until either something happens, or the timeout is
1454
         * hit. */
1455

1456
        for (;;) {
×
1457
                int x;
×
1458

1459
                r = sd_event_get_exit_code(event, &x);
×
1460
                if (r < 0) {
×
1461
                        if (r != -ENODATA)
×
1462
                                return log_error_errno(r, "Failed to query exit code from event loop: %m");
×
1463

1464
                        /* On ENODATA we aren't told to exit yet. */
1465
                } else {
1466
                        assert(x == -ETIMEDOUT);
×
1467
                        return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1468
                                                "Timed out waiting for security device, aborting security device based authentication attempt.");
1469
                }
1470

1471
                /* Wait for one event, and then eat all subsequent events until there are no further ones */
1472
                r = sd_event_run(event, processed ? 0 : UINT64_MAX);
×
1473
                if (r < 0)
×
1474
                        return log_error_errno(r, "Failed to run event loop: %m");
×
1475
                if (r == 0) /* no events queued anymore */
×
1476
                        return 0;
1477

1478
                processed = true;
×
1479
        }
1480
}
1481

1482
static bool use_token_plugins(void) {
67✔
1483

1484
#if HAVE_TPM2
1485
        /* Currently, there's no way for us to query the volume key when plugins are used. Hence don't use
1486
         * plugins, if measurement has been requested. */
1487
        if (arg_tpm2_measure_pcr != UINT_MAX)
67✔
1488
                return false;
1489
        if (arg_tpm2_measure_keyslot_nvpcr)
67✔
1490
                return false;
1491
        /* Volume key is also needed if the expected key id is set */
1492
        if (arg_fixate_volume_key)
67✔
1493
                return false;
1494
#endif
1495

1496
        /* Disable tokens if we're in FIDO2 mode with manual parameters. */
1497
        if (arg_fido2_cid)
67✔
1498
                return false;
1499

1500
#if HAVE_LIBCRYPTSETUP_PLUGINS
1501
        int r;
67✔
1502

1503
        /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
1504
        r = getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
67✔
1505
        if (r < 0 && r != -ENXIO)
67✔
1506
                log_debug_errno(r, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
×
1507
        if (r == 0)
67✔
1508
                return false;
1509

1510
        return sym_crypt_token_external_path();
63✔
1511
#else
1512
        return false;
1513
#endif
1514
}
1515

1516
#if HAVE_LIBCRYPTSETUP_PLUGINS
1517
static int acquire_pins_from_env_variable(char ***ret_pins) {
24✔
1518
        _cleanup_(erase_and_freep) char *envpin = NULL;
24✔
1519
        _cleanup_strv_free_erase_ char **pins = NULL;
24✔
1520
        int r;
24✔
1521

1522
        assert(ret_pins);
24✔
1523

1524
        r = getenv_steal_erase("PIN", &envpin);
24✔
1525
        if (r < 0)
24✔
1526
                return log_error_errno(r, "Failed to acquire PIN from environment: %m");
×
1527
        if (r > 0) {
24✔
1528
                pins = strv_new(envpin);
19✔
1529
                if (!pins)
19✔
1530
                        return log_oom();
×
1531
        }
1532

1533
        *ret_pins = TAKE_PTR(pins);
24✔
1534

1535
        return 0;
24✔
1536
}
1537
#endif
1538

1539
static int crypt_activate_by_token_pin_ask_password(
62✔
1540
                struct crypt_device *cd,
1541
                const char *name,
1542
                const char *type,
1543
                usec_t until,
1544
                void *userdata,
1545
                uint32_t activation_flags,
1546
                const char *message,
1547
                const char *keyring,
1548
                const char *credential) {
1549

1550
#if HAVE_LIBCRYPTSETUP_PLUGINS
1551
        AskPasswordFlags flags = arg_ask_password_flags;
62✔
1552
        _cleanup_strv_free_erase_ char **pins = NULL;
62✔
1553
        int r;
62✔
1554

1555
        r = sym_crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, /* pin= */ NULL, /* pin_size= */ 0, userdata, activation_flags);
62✔
1556
        if (r > 0) /* returns unlocked keyslot id on success */
62✔
1557
                return 0;
1558
        if (r == -EEXIST) /* volume is already active */
38✔
1559
                return log_external_activation(r, name);
×
1560
        if (r != -ENOANO) /* needs pin or pin is wrong */
38✔
1561
                return r;
1562

1563
        r = acquire_pins_from_env_variable(&pins);
24✔
1564
        if (r < 0)
24✔
1565
                return r;
1566

1567
        STRV_FOREACH(p, pins) {
28✔
1568
                r = sym_crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
19✔
1569
                if (r > 0) /* returns unlocked keyslot id on success */
19✔
1570
                        return 0;
1571
                if (r == -EEXIST) /* volume is already active */
6✔
1572
                        return log_external_activation(r, name);
×
1573
                if (r != -ENOANO) /* needs pin or pin is wrong */
6✔
1574
                        return r;
1575
        }
1576

1577
        if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_HEADLESS))
9✔
1578
                return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
9✔
1579

1580
        for (;;) {
×
1581
                pins = strv_free_erase(pins);
×
1582

1583
                AskPasswordRequest req = {
×
1584
                        .tty_fd = -EBADF,
1585
                        .message = message,
1586
                        .icon = "drive-harddisk",
1587
                        .keyring = keyring,
1588
                        .credential = credential,
1589
                        .until = until,
1590
                        .hup_fd = -EBADF,
1591
                };
1592

1593
                r = ask_password_auto(&req, flags, &pins);
×
1594
                if (r < 0)
×
1595
                        return r;
×
1596

1597
                STRV_FOREACH(p, pins) {
×
1598
                        r = sym_crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
×
1599
                        if (r > 0) /* returns unlocked keyslot id on success */
×
1600
                                return 0;
1601
                        if (r == -EEXIST) /* volume is already active */
×
1602
                                return log_external_activation(r, name);
×
1603
                        if (r != -ENOANO) /* needs pin or pin is wrong */
×
1604
                                return r;
1605
                }
1606

1607
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
×
1608
        }
1609
        return r;
1610
#else
1611
        return -EOPNOTSUPP;
1612
#endif
1613
}
1614

1615
static int attach_luks2_by_fido2_via_plugin(
×
1616
                struct crypt_device *cd,
1617
                const char *name,
1618
                usec_t until,
1619
                void *userdata,
1620
                uint32_t activation_flags) {
1621

1622
        return crypt_activate_by_token_pin_ask_password(
×
1623
                        cd,
1624
                        name,
1625
                        "systemd-fido2",
1626
                        until,
1627
                        userdata,
1628
                        activation_flags,
1629
                        "Please enter security token PIN:",
1630
                        "fido2-pin",
1631
                        "cryptsetup.fido2-pin");
1632
}
1633

1634
static int attach_luks_or_plain_or_bitlk_by_fido2(
×
1635
                struct crypt_device *cd,
1636
                const char *name,
1637
                const char *key_file,
1638
                const struct iovec *key_data,
1639
                usec_t until,
1640
                uint32_t flags,
1641
                bool pass_volume_key) {
1642

1643
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1644
        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
×
1645
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1646
        size_t decrypted_key_size;
×
1647
        _cleanup_free_ char *friendly = NULL;
×
1648
        int keyslot = arg_key_slot, r;
×
1649
        bool use_libcryptsetup_plugin = use_token_plugins();
×
1650

1651
        assert(cd);
×
1652
        assert(name);
×
1653
        assert(arg_fido2_device || arg_fido2_device_auto);
×
1654

1655
        if (arg_fido2_cid && !key_file && !iovec_is_set(key_data))
×
1656
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1657
                                        "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
1658

1659
        friendly = friendly_disk_name(sym_crypt_get_device_name(cd), name);
×
1660
        if (!friendly)
×
1661
                return log_oom();
×
1662

1663
        for (;;) {
×
1664
                if (use_libcryptsetup_plugin && !arg_fido2_cid) {
×
1665
                        r = attach_luks2_by_fido2_via_plugin(cd, name, until, arg_fido2_device, flags);
×
1666
                        if (IN_SET(r, -ENOTUNIQ, -ENXIO, -ENOENT))
×
1667
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1668
                                                       "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1669

1670
                } else {
1671
                        if (arg_fido2_cid)
×
1672
                                r = acquire_fido2_key(
×
1673
                                                name,
1674
                                                friendly,
1675
                                                arg_fido2_device,
1676
                                                arg_fido2_rp_id,
1677
                                                arg_fido2_cid, arg_fido2_cid_size,
1678
                                                key_file, arg_keyfile_size, arg_keyfile_offset,
1679
                                                key_data,
1680
                                                until,
1681
                                                arg_fido2_manual_flags,
1682
                                                "cryptsetup.fido2-pin",
1683
                                                arg_ask_password_flags,
1684
                                                &decrypted_key,
1685
                                                &decrypted_key_size);
1686
                        else
1687
                                r = acquire_fido2_key_auto(
×
1688
                                                cd,
1689
                                                name,
1690
                                                friendly,
1691
                                                arg_fido2_device,
1692
                                                until,
1693
                                                "cryptsetup.fido2-pin",
1694
                                                arg_ask_password_flags,
1695
                                                &decrypted_key,
1696
                                                &decrypted_key_size);
1697
                        if (r >= 0)
×
1698
                                break;
1699
                }
1700

1701
                if (r != -EAGAIN) /* EAGAIN means: token not found */
×
1702
                        return r;
1703

1704
                if (!monitor) {
×
1705
                        /* We didn't find the token. In this case, watch for it via udev. Let's
1706
                         * create an event loop and monitor first. */
1707

1708
                        assert(!event);
×
1709

1710
                        r = make_security_device_monitor(&event, &monitor);
×
1711
                        if (r < 0)
×
1712
                                return r;
1713

1714
                        log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly);
×
1715

1716
                        /* Let's immediately rescan in case the token appeared in the time we needed
1717
                         * to create and configure the monitor */
1718
                        continue;
×
1719
                }
1720

1721
                r = run_security_device_monitor(event, monitor);
×
1722
                if (r < 0)
×
1723
                        return r;
1724

1725
                log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
×
1726
        }
1727

1728
        if (pass_volume_key)
×
1729
                r = measured_crypt_activate_by_volume_key(
×
1730
                                cd,
1731
                                name,
1732
                                "fido2",
1733
                                /* keyslot= */ -1,
1734
                                decrypted_key,
1735
                                decrypted_key_size,
1736
                                flags);
1737
        else {
1738
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
×
1739
                ssize_t base64_encoded_size;
×
1740

1741
                /* Before using this key as passphrase we base64 encode it, for compat with homed */
1742

1743
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
×
1744
                if (base64_encoded_size < 0)
×
1745
                        return log_oom();
×
1746

1747
                r = measured_crypt_activate_by_passphrase(
×
1748
                                cd,
1749
                                name,
1750
                                "fido2",
1751
                                keyslot,
1752
                                base64_encoded,
1753
                                base64_encoded_size,
1754
                                flags);
1755
        }
1756
        if (r == -EPERM) {
×
1757
                log_error_errno(r, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
×
1758
                return -EAGAIN; /* log actual error, but return EAGAIN */
1759
        }
1760
        if (r < 0)
×
1761
                return log_error_errno(r, "Failed to activate with FIDO2 acquired key: %m");
×
1762

1763
        return 0;
1764
}
1765

1766
static int attach_luks2_by_pkcs11_via_plugin(
1✔
1767
                struct crypt_device *cd,
1768
                const char *name,
1769
                const char *friendly_name,
1770
                usec_t until,
1771
                const char *askpw_credential,
1772
                uint32_t flags) {
1773

1774
#if HAVE_LIBCRYPTSETUP_PLUGINS
1775
        int r;
1✔
1776

1777
        if (!streq_ptr(sym_crypt_get_type(cd), CRYPT_LUKS2))
1✔
1778
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Automatic PKCS#11 metadata requires LUKS2 device.");
×
1779

1780
        systemd_pkcs11_plugin_params params = {
1✔
1781
                .friendly_name = friendly_name,
1782
                .until = until,
1783
                .askpw_credential = askpw_credential,
1784
                .askpw_flags = arg_ask_password_flags,
1785
        };
1786

1787
        r = sym_crypt_activate_by_token_pin(cd, name, "systemd-pkcs11", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
1✔
1788
        if (r > 0) /* returns unlocked keyslot id on success */
1✔
1789
                r = 0;
1790
        if (r == -EEXIST) /* volume is already active */
1✔
1791
                r = log_external_activation(r, name);
×
1792

1793
        return r;
1794
#else
1795
        return -EOPNOTSUPP;
1796
#endif
1797
}
1798

1799
static int attach_luks_or_plain_or_bitlk_by_pkcs11(
1✔
1800
                struct crypt_device *cd,
1801
                const char *name,
1802
                const char *key_file,
1803
                const struct iovec *key_data,
1804
                usec_t until,
1805
                uint32_t flags,
1806
                bool pass_volume_key) {
1807

1808
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1✔
1809
        _cleanup_free_ char *friendly = NULL, *discovered_uri = NULL;
1✔
1810
        size_t decrypted_key_size = 0, discovered_key_size = 0;
1✔
1811
        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
1✔
1812
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1✔
1813
        _cleanup_free_ void *discovered_key = NULL;
1✔
1814
        struct iovec discovered_key_data = {};
1✔
1815
        Pkcs11RsaPadding rsa_padding = PKCS11_RSA_PADDING_PKCS1V15;
1✔
1816
        int keyslot = arg_key_slot, r;
1✔
1817
        const char *uri = NULL;
1✔
1818
        bool use_libcryptsetup_plugin = use_token_plugins();
1✔
1819

1820
        assert(cd);
1✔
1821
        assert(name);
1✔
1822
        assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
1✔
1823

1824
        if (arg_pkcs11_uri_auto) {
1✔
1825
                if (!use_libcryptsetup_plugin) {
1✔
1826
                        r = find_pkcs11_auto_data(cd, &discovered_uri, &discovered_key, &discovered_key_size, &rsa_padding, &keyslot);
×
1827
                        if (IN_SET(r, -ENOTUNIQ, -ENXIO))
×
1828
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1829
                                                       "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1830
                        if (r < 0)
×
1831
                                return r;
1832

1833
                        uri = discovered_uri;
×
1834
                        discovered_key_data = IOVEC_MAKE(discovered_key, discovered_key_size);
×
1835
                        key_data = &discovered_key_data;
×
1836
                }
1837
        } else {
1838
                uri = arg_pkcs11_uri;
×
1839

1840
                if (!key_file && !iovec_is_set(key_data))
×
1841
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing.");
×
1842
        }
1843

1844
        friendly = friendly_disk_name(sym_crypt_get_device_name(cd), name);
1✔
1845
        if (!friendly)
1✔
1846
                return log_oom();
×
1847

1848
        for (;;) {
1✔
1849
                if (use_libcryptsetup_plugin && arg_pkcs11_uri_auto)
1✔
1850
                        r = attach_luks2_by_pkcs11_via_plugin(
1✔
1851
                                        cd,
1852
                                        name,
1853
                                        friendly,
1854
                                        until,
1855
                                        "cryptsetup.pkcs11-pin",
1856
                                        flags);
1857
                else {
1858
                        r = decrypt_pkcs11_key(
×
1859
                                        name,
1860
                                        friendly,
1861
                                        uri,
1862
                                        rsa_padding,
1863
                                        key_file, arg_keyfile_size, arg_keyfile_offset,
1864
                                        key_data,
1865
                                        until,
1866
                                        arg_ask_password_flags,
1867
                                        &decrypted_key, &decrypted_key_size);
1868
                        if (r >= 0)
×
1869
                                break;
1870
                }
1871

1872
                if (r != -EAGAIN) /* EAGAIN means: token not found */
1✔
1873
                        return r;
1874

1875
                if (!monitor) {
×
1876
                        /* We didn't find the token. In this case, watch for it via udev. Let's
1877
                         * create an event loop and monitor first. */
1878

1879
                        assert(!event);
×
1880

1881
                        r = make_security_device_monitor(&event, &monitor);
×
1882
                        if (r < 0)
×
1883
                                return r;
1884

1885
                        log_notice("Security token%s%s not present for unlocking volume %s, please plug it in.",
×
1886
                                   uri ? " " : "", strempty(uri), friendly);
1887

1888
                        /* Let's immediately rescan in case the token appeared in the time we needed
1889
                         * to create and configure the monitor */
1890
                        continue;
×
1891
                }
1892

1893
                r = run_security_device_monitor(event, monitor);
×
1894
                if (r < 0)
×
1895
                        return r;
1896

1897
                log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
×
1898
        }
1899
        assert(decrypted_key);
×
1900

1901
        if (pass_volume_key)
×
1902
                r = measured_crypt_activate_by_volume_key(
×
1903
                                cd,
1904
                                name,
1905
                                "pkcs11",
1906
                                /* keyslot= */ -1,
1907
                                decrypted_key,
1908
                                decrypted_key_size,
1909
                                flags);
1910
        else {
1911
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
×
1912
                ssize_t base64_encoded_size;
×
1913

1914
                /* Before using this key as passphrase we base64 encode it. Why? For compatibility
1915
                 * with homed's PKCS#11 hookup: there we want to use the key we acquired through
1916
                 * PKCS#11 for other authentication/decryption mechanisms too, and some of them do
1917
                 * not take arbitrary binary blobs, but require NUL-terminated strings — most
1918
                 * importantly UNIX password hashes. Hence, for compatibility we want to use a string
1919
                 * without embedded NUL here too, and that's easiest to generate from a binary blob
1920
                 * via base64 encoding. */
1921

1922
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
×
1923
                if (base64_encoded_size < 0)
×
1924
                        return log_oom();
×
1925

1926
                r = measured_crypt_activate_by_passphrase(
×
1927
                                cd,
1928
                                name,
1929
                                "pkcs11",
1930
                                keyslot,
1931
                                base64_encoded,
1932
                                base64_encoded_size,
1933
                                flags);
1934
        }
1935
        if (r == -EPERM) {
×
1936
                log_error_errno(r, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
1✔
1937
                return -EAGAIN; /* log actual error, but return EAGAIN */
1938
        }
1939
        if (r < 0)
×
1940
                return log_error_errno(r, "Failed to activate with PKCS#11 acquired key: %m");
×
1941

1942
        return 0;
1943
}
1944

1945
static int make_tpm2_device_monitor(
×
1946
                sd_event **ret_event,
1947
                sd_device_monitor **ret_monitor) {
1948

1949
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1950
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1951
        int r;
×
1952

1953
        assert(ret_event);
×
1954
        assert(ret_monitor);
×
1955

1956
        r = sd_event_default(&event);
×
1957
        if (r < 0)
×
1958
                return log_error_errno(r, "Failed to allocate event loop: %m");
×
1959

1960
        r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
×
1961
        if (r < 0)
×
1962
                return log_error_errno(r, "Failed to install timeout event source: %m");
×
1963

1964
        r = sd_device_monitor_new(&monitor);
×
1965
        if (r < 0)
×
1966
                return log_error_errno(r, "Failed to allocate device monitor: %m");
×
1967

1968
        (void) sd_device_monitor_set_description(monitor, "tpmrm");
×
1969

1970
        r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "tpmrm", NULL);
×
1971
        if (r < 0)
×
1972
                return log_error_errno(r, "Failed to configure device monitor: %m");
×
1973

1974
        r = sd_device_monitor_attach_event(monitor, event);
×
1975
        if (r < 0)
×
1976
                return log_error_errno(r, "Failed to attach device monitor: %m");
×
1977

1978
        r = sd_device_monitor_start(monitor, NULL, NULL);
×
1979
        if (r < 0)
×
1980
                return log_error_errno(r, "Failed to start device monitor: %m");
×
1981

1982
        *ret_event = TAKE_PTR(event);
×
1983
        *ret_monitor = TAKE_PTR(monitor);
×
1984
        return 0;
×
1985
}
1986

1987
static int attach_luks2_by_tpm2_via_plugin(
11✔
1988
                struct crypt_device *cd,
1989
                const char *name,
1990
                usec_t until,
1991
                uint32_t flags) {
1992

1993
#if HAVE_LIBCRYPTSETUP_PLUGINS
1994
        systemd_tpm2_plugin_params params = {
11✔
1995
                .search_pcr_mask = arg_tpm2_pcr_mask,
1996
                .device = arg_tpm2_device,
1997
                .signature_path = arg_tpm2_signature,
1998
                .pcrlock_path = arg_tpm2_pcrlock,
1999
        };
2000

2001
        if (!use_token_plugins())
11✔
2002
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2✔
2003
                                       "libcryptsetup has external plugins support disabled.");
2004

2005
        return crypt_activate_by_token_pin_ask_password(
9✔
2006
                        cd,
2007
                        name,
2008
                        "systemd-tpm2",
2009
                        until,
2010
                        &params,
2011
                        flags,
2012
                        "Please enter TPM2 PIN:",
2013
                        "tpm2-pin",
2014
                        "cryptsetup.tpm2-pin");
2015
#else
2016
        return -EOPNOTSUPP;
2017
#endif
2018
}
2019

2020
static int attach_luks_or_plain_or_bitlk_by_tpm2(
13✔
2021
                struct crypt_device *cd,
2022
                const char *name,
2023
                const char *key_file,
2024
                const struct iovec *key_data,
2025
                usec_t until,
2026
                uint32_t flags,
2027
                bool pass_volume_key) {
2028

2029
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
13✔
2030
        _cleanup_(iovec_done_erase) struct iovec decrypted_key = {};
×
2031
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
13✔
2032
        _cleanup_free_ char *friendly = NULL;
13✔
2033
        int keyslot = arg_key_slot, r;
13✔
2034

2035
        assert(cd);
13✔
2036
        assert(name);
13✔
2037
        assert(arg_tpm2_device || arg_tpm2_device_auto);
13✔
2038

2039
        friendly = friendly_disk_name(sym_crypt_get_device_name(cd), name);
13✔
2040
        if (!friendly)
13✔
2041
                return log_oom();
×
2042

2043
        for (;;) {
13✔
2044
                if (key_file || iovec_is_set(key_data)) {
13✔
2045
                        /* If key data is specified, use that */
2046

2047
                        r = acquire_tpm2_key(
4✔
2048
                                        name,
2049
                                        arg_tpm2_device,
2050
                                        arg_tpm2_pcr_mask == UINT32_MAX ? TPM2_PCR_MASK_DEFAULT_LEGACY : arg_tpm2_pcr_mask,
2✔
2051
                                        UINT16_MAX,
2052
                                        /* pubkey= */ NULL,
2053
                                        /* pubkey_policy_ref= */ NULL,
2054
                                        /* pubkey_pcr_mask= */ 0,
2055
                                        /* signature_path= */ NULL,
2056
                                        /* pcrlock_path= */ NULL,
2057
                                        /* primary_alg= */ 0,
2058
                                        key_file, arg_keyfile_size, arg_keyfile_offset,
2059
                                        key_data, /* n_blobs= */ iovec_is_set(key_data) ? 1 : 0,
2✔
2060
                                        /* policy_hash= */ NULL, /* we don't know the policy hash */
2061
                                        /* n_policy_hash= */ 0,
2062
                                        /* salt= */ NULL,
2063
                                        /* srk= */ NULL,
2064
                                        /* pcrlock_nv= */ NULL,
2065
                                        arg_tpm2_pin ? TPM2_FLAGS_USE_PIN : 0,
2066
                                        until,
2067
                                        "cryptsetup.tpm2-pin",
2068
                                        arg_ask_password_flags,
2069
                                        /* argon2id_params= */ NULL,
2070
                                        &decrypted_key);
2071
                        if (r >= 0)
2✔
2072
                                break;
2073
                        if (IN_SET(r, -EACCES, -ENOLCK))
2✔
2074
                                return log_error_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
×
2075
                        if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
2✔
2076
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");
×
2077
                        /* EAGAIN means: no tpm2 chip found */
2078
                        if (r != -EAGAIN) {
2✔
2079
                                log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
2✔
2080
                                return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
2081
                        }
2082
                } else {
2083
                        r = attach_luks2_by_tpm2_via_plugin(cd, name, until, flags);
11✔
2084
                        if (r >= 0)
11✔
2085
                                return 0;
2086
                        /* EAGAIN     means: no tpm2 chip found
2087
                         * EOPNOTSUPP means: no libcryptsetup plugins support */
2088
                        if (r == -ENXIO)
11✔
2089
                                return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
×
2090
                                                        "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
2091
                        if (r == -ENOENT)
11✔
2092
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
4✔
2093
                                                       "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
2094
                        if (!IN_SET(r, -EOPNOTSUPP, -EAGAIN)) {
7✔
2095
                                log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
5✔
2096
                                return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
2097
                        }
2098
                }
2099

2100
                if (r == -EOPNOTSUPP) { /* Plugin not available, let's process TPM2 stuff right here instead */
2✔
2101
                        bool found_some = false;
2✔
2102
                        int token = 0; /* first token to look at */
2✔
2103

2104
                        /* If no key data is specified, look for it in the header. In order to support
2105
                         * software upgrades we'll iterate through all suitable tokens, maybe one of them
2106
                         * works. */
2107

2108
                        for (;;) {
6✔
2109
                                _cleanup_(iovec_done) struct iovec pubkey = {}, salt = {}, srk = {}, pcrlock_nv = {};
2✔
2110
                                _cleanup_free_ char *pubkey_policy_ref = NULL;
4✔
2111
                                struct iovec *blobs = NULL, *policy_hash = NULL;
4✔
2112
                                uint32_t hash_pcr_mask, pubkey_pcr_mask;
4✔
2113
                                size_t n_blobs = 0, n_policy_hash = 0;
4✔
2114
                                uint16_t pcr_bank, primary_alg;
4✔
2115
                                Argon2IdParameters argon2id_params = {};
4✔
2116
                                TPM2Flags tpm2_flags;
4✔
2117

2118
                                CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
4✔
2119
                                CLEANUP_ARRAY(policy_hash, n_policy_hash, iovec_array_free);
×
2120

2121
                                r = find_tpm2_auto_data(
4✔
2122
                                                cd,
2123
                                                arg_tpm2_pcr_mask, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
2124
                                                token, /* search for the token with this index, or any later index than this */
2125
                                                &hash_pcr_mask,
2126
                                                &pcr_bank,
2127
                                                &pubkey,
2128
                                                &pubkey_policy_ref,
2129
                                                &pubkey_pcr_mask,
2130
                                                &primary_alg,
2131
                                                &blobs,
2132
                                                &n_blobs,
2133
                                                &policy_hash,
2134
                                                &n_policy_hash,
2135
                                                &salt,
2136
                                                &srk,
2137
                                                &pcrlock_nv,
2138
                                                &tpm2_flags,
2139
                                                &keyslot,
2140
                                                &token,
2141
                                                &argon2id_params);
2142
                                if (r == -ENXIO)
4✔
2143
                                        /* No further TPM2 tokens found in the LUKS2 header. */
2144
                                        return log_full_errno(found_some ? LOG_NOTICE : LOG_DEBUG,
×
2145
                                                              SYNTHETIC_ERRNO(EAGAIN),
2146
                                                              found_some
2147
                                                              ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
2148
                                                              : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
2149
                                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
4✔
2150
                                        /* TPM2 support not compiled in? */
2151
                                        return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
2152
                                                               "TPM2 support not available, falling back to traditional unlocking.");
2153
                                if (r < 0)
4✔
2154
                                        return r;
2155

2156
                                found_some = true;
4✔
2157

2158
                                r = acquire_tpm2_key(
4✔
2159
                                                name,
2160
                                                arg_tpm2_device,
2161
                                                hash_pcr_mask,
2162
                                                pcr_bank,
2163
                                                &pubkey,
2164
                                                pubkey_policy_ref,
2165
                                                pubkey_pcr_mask,
2166
                                                arg_tpm2_signature,
2167
                                                arg_tpm2_pcrlock,
2168
                                                primary_alg,
2169
                                                /* key_file= */ NULL, /* key_file_size= */ 0, /* key_file_offset= */ 0, /* no key file */
2170
                                                blobs,
2171
                                                n_blobs,
2172
                                                policy_hash,
2173
                                                n_policy_hash,
2174
                                                &salt,
2175
                                                &srk,
2176
                                                &pcrlock_nv,
2177
                                                tpm2_flags,
2178
                                                until,
2179
                                                "cryptsetup.tpm2-pin",
2180
                                                arg_ask_password_flags,
2181
                                                &argon2id_params,
2182
                                                &decrypted_key);
2183
                                if (IN_SET(r, -EACCES, -ENOLCK))
4✔
2184
                                        return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
×
2185
                                /* Stop unless we should keep iterating to next token because the tried one
2186
                                 * does not match boot state. For now without -EUCLEAN because currently the
2187
                                 * only error it reports won't be solved by moving to another token. */
2188
                                if (!ERRNO_IS_NEG_TPM2_TOKEN_MISMATCH(r))
4✔
2189
                                        break;
2190

2191
                                token++; /* try a different token next time */
2✔
2192
                        }
2193

2194
                        if (r >= 0)
2✔
2195
                                break;
2196
                        /* EAGAIN means: no tpm2 chip found */
2197
                        if (r != -EAGAIN) {
×
2198
                                log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
×
2199
                                return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
2200
                        }
2201
                }
2202

2203
                if (!monitor) {
×
2204
                        /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
2205
                         * an event loop and monitor first. */
2206

2207
                        assert(!event);
×
2208

2209
                        if (is_efi_boot() && !efi_has_tpm2())
×
2210
                                return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
×
2211
                                                        "No TPM2 hardware discovered and EFI firmware does not see it either, falling back to traditional unlocking.");
2212

2213
                        r = make_tpm2_device_monitor(&event, &monitor);
×
2214
                        if (r < 0)
×
2215
                                return r;
2216

2217
                        log_info("TPM2 device not present for unlocking %s, waiting for it to become available.", friendly);
×
2218

2219
                        /* Let's immediately rescan in case the device appeared in the time we needed
2220
                         * to create and configure the monitor */
2221
                        continue;
×
2222
                }
2223

2224
                r = run_security_device_monitor(event, monitor);
×
2225
                if (r < 0)
×
2226
                        return r;
2227

2228
                log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
×
2229
        }
2230

2231
        if (pass_volume_key)
2✔
2232
                r = measured_crypt_activate_by_volume_key(
×
2233
                                cd,
2234
                                name,
2235
                                "tpm2",
2236
                                /* keyslot= */ -1,
2237
                                decrypted_key.iov_base,
×
2238
                                decrypted_key.iov_len,
2239
                                flags);
2240
        else {
2241
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
2✔
2242
                ssize_t base64_encoded_size;
2✔
2243

2244
                /* Before using this key as passphrase we base64 encode it, for compat with homed */
2245

2246
                base64_encoded_size = base64mem(decrypted_key.iov_base, decrypted_key.iov_len, &base64_encoded);
2✔
2247
                if (base64_encoded_size < 0)
2✔
2248
                        return log_oom();
×
2249

2250
                r = measured_crypt_activate_by_passphrase(
2✔
2251
                                cd,
2252
                                name,
2253
                                "tpm2",
2254
                                keyslot,
2255
                                base64_encoded,
2256
                                base64_encoded_size,
2257
                                flags);
2258
        }
2259
        if (r == -EPERM) {
2✔
2260
                log_error_errno(r, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
13✔
2261
                return -EAGAIN; /* log actual error, but return EAGAIN */
2262
        }
2263
        if (r < 0)
2✔
2264
                return log_error_errno(r, "Failed to activate with TPM2 acquired key: %m");
×
2265

2266
        return 0;
2267
}
2268

2269
static int attach_luks_or_plain_or_bitlk_by_key_data(
3✔
2270
                struct crypt_device *cd,
2271
                const char *name,
2272
                const struct iovec *key_data,
2273
                uint32_t flags,
2274
                bool pass_volume_key) {
2275

2276
        int r;
3✔
2277

2278
        assert(cd);
3✔
2279
        assert(name);
3✔
2280
        assert(key_data);
3✔
2281

2282
        if (pass_volume_key)
3✔
2283
                r = measured_crypt_activate_by_volume_key(cd, name, /* mechanism= */ NULL, /* keyslot= */ -1, key_data->iov_base, key_data->iov_len, flags);
×
2284
        else
2285
                r = measured_crypt_activate_by_passphrase(cd, name, /* mechanism= */ NULL, arg_key_slot, key_data->iov_base, key_data->iov_len, flags);
3✔
2286
        if (r == -EPERM) {
3✔
2287
                log_error_errno(r, "Failed to activate. (Key incorrect?)");
×
2288
                return -EAGAIN; /* Log actual error, but return EAGAIN */
2289
        }
2290
        if (r < 0)
3✔
2291
                return log_error_errno(r, "Failed to activate: %m");
×
2292

2293
        return 0;
2294
}
2295

2296
static int attach_luks_or_plain_or_bitlk_by_key_file(
28✔
2297
                struct crypt_device *cd,
2298
                const char *name,
2299
                const char *key_file,
2300
                uint32_t flags,
2301
                bool pass_volume_key) {
2302

2303
        _cleanup_(erase_and_freep) char *kfdata = NULL;
28✔
2304
        _cleanup_free_ char *bindname = NULL;
28✔
2305
        size_t kfsize;
28✔
2306
        int r;
28✔
2307

2308
        assert(cd);
28✔
2309
        assert(name);
28✔
2310
        assert(key_file);
28✔
2311

2312
        /* If we read the key via AF_UNIX, make this client recognizable */
2313
        bindname = make_bindname(name, /* token_type= */ _TOKEN_TYPE_INVALID);
28✔
2314
        if (!bindname)
28✔
2315
                return log_oom();
×
2316

2317
        r = read_full_file_full(
31✔
2318
                        AT_FDCWD, key_file,
2319
                        arg_keyfile_offset == 0 ? UINT64_MAX : arg_keyfile_offset,
28✔
2320
                        arg_keyfile_size == 0 ? SIZE_MAX : arg_keyfile_size,
28✔
2321
                        READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
2322
                        bindname,
2323
                        &kfdata, &kfsize);
2324
        if (r == -E2BIG) {
28✔
2325
                log_error_errno(r, "Failed to activate, key file '%s' too large.", key_file);
×
2326
                return -EAGAIN;
2327
        }
2328
        if (r == -ENOENT) {
28✔
2329
                log_error_errno(r, "Failed to activate, key file '%s' missing.", key_file);
×
2330
                return -EAGAIN; /* Log actual error, but return EAGAIN */
2331
        }
2332
        if (r < 0)
28✔
2333
                return log_error_errno(r, "Failed to read key file '%s': %m", key_file);
×
2334

2335
        if (pass_volume_key)
28✔
2336
                r = measured_crypt_activate_by_volume_key(cd, name, /* mechanism= */ NULL, /* keyslot= */ -1, kfdata, kfsize, flags);
×
2337
        else
2338
                r = measured_crypt_activate_by_passphrase(cd, name, /* mechanism= */ NULL, arg_key_slot, kfdata, kfsize, flags);
28✔
2339
        if (r == -EPERM) {
28✔
2340
                log_error_errno(r, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file);
28✔
2341
                return -EAGAIN; /* Log actual error, but return EAGAIN */
2342
        }
2343
        if (r < 0)
24✔
2344
                return log_error_errno(r, "Failed to activate with key file '%s': %m", key_file);
2✔
2345

2346
        return 0;
2347
}
2348

2349
static int attach_luks_or_plain_or_bitlk_by_passphrase(
×
2350
                struct crypt_device *cd,
2351
                const char *name,
2352
                char **passwords,
2353
                uint32_t flags,
2354
                bool pass_volume_key) {
2355

2356
        int r;
×
2357

2358
        assert(cd);
×
2359
        assert(name);
×
2360

2361
        r = -EINVAL;
2362
        STRV_FOREACH(p, passwords) {
×
2363
                if (pass_volume_key)
×
2364
                        r = measured_crypt_activate_by_volume_key(cd, name, /* mechanism= */ NULL, /* keyslot= */ -1, *p, arg_key_size, flags);
×
2365
                else
2366
                        r = measured_crypt_activate_by_passphrase(cd, name, /* mechanism= */ NULL, arg_key_slot, *p, strlen(*p), flags);
×
2367
                if (r >= 0)
×
2368
                        break;
2369
        }
2370
        if (r == -EPERM) {
×
2371
                log_error_errno(r, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
×
2372
                return -EAGAIN; /* log actual error, but return EAGAIN */
2373
        }
2374
        if (r < 0)
×
2375
                return log_error_errno(r, "Failed to activate with specified passphrase: %m");
×
2376

2377
        return 0;
2378
}
2379

2380
static int attach_luks_or_plain_or_bitlk(
45✔
2381
                struct crypt_device *cd,
2382
                const char *name,
2383
                TokenType token_type,
2384
                const char *key_file,
2385
                const struct iovec *key_data,
2386
                char **passwords,
2387
                uint32_t flags,
2388
                usec_t until) {
2389

2390
        bool pass_volume_key = false;
45✔
2391
        int r;
45✔
2392

2393
        assert(cd);
45✔
2394
        assert(name);
45✔
2395

2396
        if ((!arg_type && !sym_crypt_get_type(cd)) || streq_ptr(arg_type, CRYPT_PLAIN)) {
45✔
2397
                struct crypt_params_plain params = {
×
2398
                        .offset = arg_offset,
2399
                        .skip = arg_skip,
2400
                        .sector_size = arg_sector_size,
2401
                };
2402
                const char *cipher, *cipher_mode;
×
2403
                _cleanup_free_ char *truncated_cipher = NULL;
×
2404

2405
                if (streq_ptr(arg_hash, "plain"))
×
2406
                        /* plain isn't a real hash type. it just means "use no hash" */
2407
                        params.hash = NULL;
2408
                else if (arg_hash)
×
2409
                        params.hash = arg_hash;
×
2410
                else if (!key_file)
×
2411
                        /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
2412
                         * file is provided */
2413
                        params.hash = "ripemd160";
×
2414

2415
                if (arg_cipher) {
×
2416
                        size_t l;
×
2417

2418
                        l = strcspn(arg_cipher, "-");
×
2419
                        truncated_cipher = strndup(arg_cipher, l);
×
2420
                        if (!truncated_cipher)
×
2421
                                return log_oom();
×
2422

2423
                        cipher = truncated_cipher;
×
2424
                        cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain";
×
2425
                } else {
2426
                        cipher = "aes";
2427
                        cipher_mode = "cbc-essiv:sha256";
2428
                }
2429

2430
                /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
2431
                arg_keyfile_size = arg_key_size;
×
2432

2433
                /* In contrast to what the name crypt_format() might suggest this doesn't actually format
2434
                 * anything, it just configures encryption parameters when used for plain mode. */
2435
                r = sym_crypt_format(cd, CRYPT_PLAIN, cipher, cipher_mode, NULL, NULL, arg_keyfile_size, &params);
×
2436
                if (r < 0)
×
2437
                        return log_error_errno(r, "Loading of cryptographic parameters failed: %m");
×
2438

2439
                /* hash == NULL implies the user passed "plain" */
2440
                pass_volume_key = !params.hash;
×
2441
        }
2442

2443
        log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
45✔
2444
                 sym_crypt_get_cipher(cd),
2445
                 sym_crypt_get_cipher_mode(cd),
2446
                 sym_crypt_get_volume_key_size(cd)*8,
2447
                 sym_crypt_get_device_name(cd));
2448

2449
        if (token_type == TOKEN_TPM2)
45✔
2450
                return attach_luks_or_plain_or_bitlk_by_tpm2(cd, name, key_file, key_data, until, flags, pass_volume_key);
13✔
2451
        if (token_type == TOKEN_FIDO2)
32✔
2452
                return attach_luks_or_plain_or_bitlk_by_fido2(cd, name, key_file, key_data, until, flags, pass_volume_key);
×
2453
        if (token_type == TOKEN_PKCS11)
32✔
2454
                return attach_luks_or_plain_or_bitlk_by_pkcs11(cd, name, key_file, key_data, until, flags, pass_volume_key);
1✔
2455
        if (key_data)
31✔
2456
                return attach_luks_or_plain_or_bitlk_by_key_data(cd, name, key_data, flags, pass_volume_key);
3✔
2457
        if (key_file)
28✔
2458
                return attach_luks_or_plain_or_bitlk_by_key_file(cd, name, key_file, flags, pass_volume_key);
28✔
2459

2460
        return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
×
2461
}
2462

2463
static int help(void) {
×
2464
        _cleanup_free_ char *link = NULL;
×
2465
        _cleanup_(table_unrefp) Table *options = NULL, *verbs = NULL;
×
2466
        int r;
×
2467

2468
        r = terminal_urlify_man("systemd-cryptsetup", "8", &link);
×
2469
        if (r < 0)
×
2470
                return log_oom();
×
2471

2472
        r = verbs_get_help_table(&verbs);
×
2473
        if (r < 0)
×
2474
                return r;
2475

2476
        r = option_parser_get_help_table(&options);
×
2477
        if (r < 0)
×
2478
                return r;
2479

2480
        (void) table_sync_column_widths(0, verbs, options);
×
2481

2482
        printf("%s [OPTIONS...] {COMMAND} ...\n\n"
×
2483
               "%sAttach or detach an encrypted block device.%s\n"
2484
               "\n%sCommands:%s\n",
2485
               program_invocation_short_name,
2486
               ansi_highlight(),
2487
               ansi_normal(),
2488
               ansi_underline(),
2489
               ansi_normal());
2490

2491
        r = table_print_or_warn(verbs);
×
2492
        if (r < 0)
×
2493
                return r;
2494

2495
        printf("\n%sOptions:%s\n",
×
2496
               ansi_underline(),
2497
               ansi_normal());
2498

2499
        r = table_print_or_warn(options);
×
2500
        if (r < 0)
×
2501
                return r;
2502

2503
        printf("\nSee the %s for details.\n", link);
×
2504
        return 0;
2505
}
2506

2507
VERB_COMMON_HELP_HIDDEN(help);
×
2508

2509
static int parse_argv(int argc, char *argv[], char ***ret_args) {
151✔
2510
        assert(argc >= 0);
151✔
2511
        assert(argv);
151✔
2512
        assert(ret_args);
151✔
2513

2514
        OptionParser opts = { argc, argv };
151✔
2515

2516
        FOREACH_OPTION_OR_RETURN(c, &opts)
151✔
2517
                switch (c) {
×
2518

2519
                OPTION_COMMON_HELP:
×
2520
                        return help();
×
2521

2522
                OPTION_COMMON_VERSION:
×
2523
                        return version();
×
2524
                }
2525

2526
        *ret_args = option_parser_get_args(&opts);
151✔
2527
        return 1;
151✔
2528
}
2529

2530
static uint32_t determine_flags(void) {
83✔
2531
        uint32_t flags = 0;
83✔
2532

2533
        if (arg_readonly)
83✔
2534
                flags |= CRYPT_ACTIVATE_READONLY;
×
2535

2536
        if (arg_discards)
83✔
2537
                flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
×
2538

2539
        if (arg_same_cpu_crypt)
83✔
2540
                flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
×
2541

2542
        if (arg_submit_from_crypt_cpus)
83✔
2543
                flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
×
2544

2545
        if (arg_no_read_workqueue)
83✔
2546
                flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
×
2547

2548
        if (arg_no_write_workqueue)
83✔
2549
                flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
×
2550

2551
        /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
2552
        /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
2553
        flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF;
83✔
2554

2555
        return flags;
83✔
2556
}
2557

2558
static void remove_and_erasep(const char **p) {
83✔
2559
        int r;
83✔
2560

2561
        assert(p);
83✔
2562

2563
        if (!*p)
83✔
2564
                return;
2565

2566
        r = unlinkat_deallocate(AT_FDCWD, *p, UNLINK_ERASE);
2✔
2567
        if (r < 0 && r != -ENOENT)
2✔
2568
                log_warning_errno(r, "Unable to erase key file '%s', ignoring: %m", *p);
×
2569
}
2570

2571
static TokenType determine_token_type(void) {
60✔
2572
        if (arg_tpm2_device || arg_tpm2_device_auto)
60✔
2573
                return TOKEN_TPM2;
2574
        if (arg_fido2_device || arg_fido2_device_auto)
47✔
2575
                return TOKEN_FIDO2;
2576
        if (arg_pkcs11_uri || arg_pkcs11_uri_auto)
47✔
2577
                return TOKEN_PKCS11;
1✔
2578

2579
        return _TOKEN_TYPE_INVALID;
2580
}
2581

2582
static int discover_key(const char *key_file, const char *volume, TokenType token_type, struct iovec *ret_key_data) {
17✔
2583
        _cleanup_free_ char *bindname = NULL;
17✔
2584
        const char *token_type_name;
17✔
2585
        int r;
17✔
2586

2587
        assert(key_file);
17✔
2588
        assert(volume);
17✔
2589
        assert(ret_key_data);
17✔
2590

2591
        bindname = make_bindname(volume, token_type);
17✔
2592
        if (!bindname)
17✔
2593
                return log_oom();
×
2594

2595
        /* If a key file is not explicitly specified, search for a key in a well defined search path, and load it. */
2596
        r = find_key_file(key_file, STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"), bindname, ret_key_data);
17✔
2597
        if (r <= 0)
17✔
2598
                return r;
2599

2600
        token_type_name = token_type_to_string(token_type);
1✔
2601
        if (token_type_name)
1✔
2602
                log_debug("Automatically discovered encrypted key for volume '%s' (token type: %s).", volume, token_type_name);
×
2603
        else
2604
                log_debug("Automatically discovered key for volume '%s'.", volume);
1✔
2605

2606
        return r;
2607
}
2608

2609
VERB(verb_attach, "attach", "VOLUME SOURCE-DEVICE [KEY-FILE] [CONFIG]", 3, 5, 0,
2610
     "Attach an encrypted block device");
2611
static int verb_attach(int argc, char *argv[], uintptr_t _data, void *userdata) {
83✔
2612
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
83✔
2613
        _unused_ _cleanup_(remove_and_erasep) const char *destroy_key_file = NULL;
83✔
2614
        crypt_status_info status;
83✔
2615
        uint32_t flags = 0;
83✔
2616
        unsigned tries;
83✔
2617
        usec_t until;
83✔
2618
        PassphraseType passphrase_type = PASSPHRASE_NONE;
83✔
2619
        int r;
83✔
2620

2621
        /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [KEY-FILE] [CONFIG] */
2622

2623
        assert(argc >= 3 && argc <= 5);
83✔
2624

2625
        const char *volume = ASSERT_PTR(argv[1]),
83✔
2626
                *source = ASSERT_PTR(argv[2]),
83✔
2627
                *key_file = argc >= 4 ? mangle_none(argv[3]) : NULL,
83✔
2628
                *config = argc >= 5 ? mangle_none(argv[4]) : NULL;
83✔
2629

2630
        if (!filename_is_valid(volume))
83✔
2631
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
×
2632

2633
        if (key_file && !path_is_absolute(key_file)) {
83✔
2634
                log_warning("Password file path '%s' is not absolute. Ignoring.", key_file);
×
2635
                key_file = NULL;
2636
        }
2637

2638
        if (config) {
83✔
2639
                r = parse_crypt_config(config);
81✔
2640
                if (r < 0)
81✔
2641
                        return r;
2642
        }
2643

2644
        log_debug("%s %s ← %s type=%s cipher=%s", __func__,
232✔
2645
                  volume, source, strempty(arg_type), strempty(arg_cipher));
2646

2647
        /* A delicious drop of snake oil */
2648
        (void) safe_mlockall(MCL_CURRENT|MCL_FUTURE|MCL_ONFAULT);
83✔
2649

2650
        /* Only erase key files explicitly configured on the command line, never the ones we
2651
         * auto-discover in /etc/cryptsetup-keys.d/ and /run/cryptsetup-keys.d/: those are shared
2652
         * resources not owned by an individual volume. (key_file is NULL when auto-discovery is used.) */
2653
        if (key_file && arg_keyfile_erase)
83✔
2654
                destroy_key_file = key_file; /* let's get this baby erased when we leave */
2✔
2655

2656
        if (arg_header) {
83✔
2657
                if (streq_ptr(arg_type, CRYPT_TCRYPT)){
9✔
2658
                        log_debug("tcrypt header: %s", arg_header);
×
2659
                        r = sym_crypt_init_data_device(&cd, arg_header, source);
×
2660
                } else {
2661
                        log_debug("LUKS header: %s", arg_header);
9✔
2662
                        r = sym_crypt_init(&cd, arg_header);
9✔
2663
                }
2664
        } else
2665
                r = sym_crypt_init(&cd, source);
74✔
2666
        if (r < 0)
83✔
2667
                return log_error_errno(r, "crypt_init() failed: %m");
×
2668

2669
        cryptsetup_enable_logging(cd);
83✔
2670

2671
        status = sym_crypt_status(cd, volume);
83✔
2672
        if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) {
83✔
2673
                log_info("Volume %s already active.", volume);
×
2674
                return 0;
2675
        }
2676

2677
        flags = determine_flags();
83✔
2678

2679
        until = usec_add(now(CLOCK_MONOTONIC), arg_timeout);
83✔
2680
        if (until == USEC_INFINITY)
×
2681
                until = 0;
83✔
2682

2683
        if (arg_key_size == 0)
83✔
2684
                arg_key_size = 256U / 8U;
83✔
2685

2686
        if (key_file) {
83✔
2687
                struct stat st;
28✔
2688

2689
                /* Ideally we'd do this on the open fd, but since this is just a warning it's OK to do this
2690
                 * in two steps. */
2691
                if (stat(key_file, &st) >= 0 && S_ISREG(st.st_mode) && (st.st_mode & 0005))
28✔
2692
                        log_warning("Key file %s is world-readable. This is not a good idea!", key_file);
6✔
2693
        }
2694

2695
        if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2)) {
83✔
2696
                r = sym_crypt_load(cd, !arg_type || streq(arg_type, ANY_LUKS) ? CRYPT_LUKS : arg_type, NULL);
83✔
2697
                if (r < 0)
83✔
2698
                        return log_error_errno(r, "Failed to load LUKS superblock on device %s: %m", sym_crypt_get_device_name(cd));
38✔
2699

2700
                /* since cryptsetup 2.7.0 (Jan 2024) */
2701
                if (arg_link_key_description) {
83✔
2702
                        r = sym_crypt_set_keyring_to_link(cd, arg_link_key_description, NULL, arg_link_key_type, arg_link_keyring);
×
2703
                        if (r == -ENOSYS)
×
2704
                                log_warning("Loaded libcryptsetup does not support linking volume keys in user specified kernel keyrings upon device activation, ignoring.");
×
2705
                        else if (r < 0)
×
2706
                                log_warning_errno(r, "Failed to set keyring or key description to link volume key in, ignoring: %m");
×
2707
                }
2708

2709
                if (arg_header) {
83✔
2710
                        r = sym_crypt_set_data_device(cd, source);
9✔
2711
                        if (r < 0)
9✔
2712
                                return log_error_errno(r, "Failed to set LUKS data device %s: %m", source);
×
2713
                }
2714

2715
                /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
2716
                if (!key_file && use_token_plugins()) {
83✔
2717
                        r = crypt_activate_by_token_pin_ask_password(
53✔
2718
                                        cd,
2719
                                        volume,
2720
                                        /* type= */ NULL,
2721
                                        until,
2722
                                        /* userdata= */ NULL,
2723
                                        flags,
2724
                                        "Please enter LUKS2 token PIN:",
2725
                                        "luks2-pin",
2726
                                        "cryptsetup.luks2-pin");
2727
                        if (r >= 0) {
53✔
2728
                                log_debug("Volume %s activated with a LUKS token.", volume);
38✔
2729
                                return 0;
2730
                        }
2731

2732
                        log_debug_errno(r, "Token activation unsuccessful for device %s: %m", sym_crypt_get_device_name(cd));
15✔
2733
                }
2734
        }
2735

2736
        if (streq_ptr(arg_type, CRYPT_BITLK)) {
45✔
2737
                r = sym_crypt_load(cd, CRYPT_BITLK, NULL);
×
2738
                if (r < 0)
×
2739
                        return log_error_errno(r, "Failed to load Bitlocker superblock on device %s: %m", sym_crypt_get_device_name(cd));
×
2740
        }
2741

2742
        bool use_cached_passphrase = true, try_discover_key = !key_file;
45✔
2743
        const char *discovered_key_fn = strjoina(volume, ".key");
225✔
2744
        _cleanup_strv_free_erase_ char **passwords = NULL;
45✔
2745
        for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) {
60✔
2746
                _cleanup_(iovec_done_erase) struct iovec discovered_key_data = {};
60✔
2747
                const struct iovec *key_data = NULL;
60✔
2748
                TokenType token_type = determine_token_type();
60✔
2749

2750
                log_debug("Beginning attempt %u to unlock.", tries);
60✔
2751

2752
                /* When we were able to acquire multiple keys, let's always process them in this order:
2753
                 *
2754
                 *    1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
2755
                 *    2. The configured or discovered key, of which both are exclusive and optional
2756
                 *    3. The empty password, in case arg_try_empty_password is set
2757
                 *    4. We enquire the user for a password
2758
                 */
2759

2760
                if (try_discover_key) {
60✔
2761
                        r = discover_key(discovered_key_fn, volume, token_type, &discovered_key_data);
17✔
2762
                        if (r < 0)
17✔
2763
                                return r;
2764
                        if (r > 0)
17✔
2765
                                key_data = &discovered_key_data;
2766
                        else
2767
                                try_discover_key = false;
16✔
2768
                }
2769

2770
                if (token_type < 0 && !key_file && !key_data && !passwords) {
60✔
2771

2772
                        /* If we have nothing to try anymore, then acquire a new password */
2773

2774
                        if (arg_try_empty_password) {
17✔
2775
                                /* Hmm, let's try an empty password now, but only once */
2776
                                arg_try_empty_password = false;
2✔
2777
                                key_data = &iovec_empty;
2✔
2778
                        } else {
2779
                                /* Ask the user for a passphrase or recovery key only as last resort, if we
2780
                                 * have nothing else to check for */
2781
                                if (passphrase_type == PASSPHRASE_NONE) {
15✔
2782
                                        passphrase_type = check_registered_passwords(cd);
15✔
2783
                                        if (passphrase_type == PASSPHRASE_NONE)
15✔
2784
                                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No passphrase or recovery key registered.");
×
2785
                                }
2786

2787
                                r = get_password(
15✔
2788
                                                volume,
2789
                                                source,
2790
                                                until,
2791
                                                /* ignore_cached= */ !use_cached_passphrase || arg_verify,
15✔
2792
                                                passphrase_type,
2793
                                                &passwords);
2794
                                use_cached_passphrase = false;
15✔
2795
                                if (r == -EAGAIN)
15✔
2796
                                        continue;
×
2797
                                if (r < 0)
15✔
2798
                                        return r;
2799
                        }
2800
                }
2801

2802
                if (streq_ptr(arg_type, CRYPT_TCRYPT))
45✔
2803
                        r = attach_tcrypt(cd, volume, token_type, key_file, key_data, passwords, flags);
×
2804
                else
2805
                        r = attach_luks_or_plain_or_bitlk(cd, volume, token_type, key_file, key_data, passwords, flags, until);
45✔
2806
                if (r >= 0)
45✔
2807
                        break;
2808
                if (r != -EAGAIN)
18✔
2809
                        return r;
2810

2811
                /* Key not correct? Let's try again, but let's invalidate one of the passed fields, so that
2812
                 * we fall back to the next best thing. */
2813

2814
                if (token_type == TOKEN_TPM2) {
15✔
2815
                        arg_tpm2_device = mfree(arg_tpm2_device);
11✔
2816
                        arg_tpm2_device_auto = false;
11✔
2817
                        continue;
11✔
2818
                }
2819

2820
                if (token_type == TOKEN_FIDO2) {
4✔
2821
                        arg_fido2_device = mfree(arg_fido2_device);
×
2822
                        arg_fido2_device_auto = false;
×
2823
                        continue;
×
2824
                }
2825

2826
                if (token_type == TOKEN_PKCS11) {
4✔
2827
                        arg_pkcs11_uri = mfree(arg_pkcs11_uri);
×
2828
                        arg_pkcs11_uri_auto = false;
×
2829
                        continue;
×
2830
                }
2831

2832
                if (try_discover_key) {
4✔
2833
                        try_discover_key = false;
×
2834
                        continue;
×
2835
                }
2836

2837
                if (key_file) {
4✔
2838
                        key_file = NULL;
4✔
2839
                        continue;
4✔
2840
                }
2841

2842
                if (passwords) {
×
2843
                        passwords = strv_free_erase(passwords);
×
2844
                        continue;
×
2845
                }
2846

2847
                log_debug("Prepared for next attempt to unlock.");
×
2848
        }
2849

2850
        if (arg_tries != 0 && tries >= arg_tries)
27✔
2851
                return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to activate; giving up.");
×
2852

2853
        return 0;
2854
}
2855

2856
VERB(verb_detach, "detach", "VOLUME", 2, 2, 0,
2857
     "Detach an encrypted block device");
2858
static int verb_detach(int argc, char *argv[], uintptr_t _data, void *userdata) {
68✔
2859
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
68✔
2860
        const char *volume = ASSERT_PTR(argv[1]);
68✔
2861
        int r;
68✔
2862

2863
        assert(argc == 2);
68✔
2864

2865
        if (!filename_is_valid(volume))
68✔
2866
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
×
2867

2868
        r = sym_crypt_init_by_name(&cd, volume);
68✔
2869
        if (r == -ENODEV) {
68✔
2870
                log_info("Volume %s already inactive.", volume);
3✔
2871
                return 0;
2872
        }
2873
        if (r < 0)
65✔
2874
                return log_error_errno(r, "crypt_init_by_name() for volume '%s' failed: %m", volume);
×
2875

2876
        cryptsetup_enable_logging(cd);
65✔
2877

2878
        r = sym_crypt_deactivate(cd, volume);
65✔
2879
        if (r < 0)
65✔
2880
                return log_error_errno(r, "Failed to deactivate '%s': %m", volume);
×
2881

2882
        return 0;
2883
}
2884

2885
static int run(int argc, char *argv[]) {
151✔
2886
        int r;
151✔
2887

2888
        LIBBLKID_NOTE(recommended);
151✔
2889
        LIBCRYPTO_NOTE(recommended);
151✔
2890
        LIBCRYPTSETUP_NOTE(required);
151✔
2891
        LIBFIDO2_NOTE(suggested);
151✔
2892
        LIBMOUNT_NOTE(recommended);
151✔
2893
        LIBP11KIT_NOTE(suggested);
151✔
2894
        TPM2_NOTE(suggested);
151✔
2895

2896
        log_setup();
151✔
2897

2898
        umask(0022);
151✔
2899

2900
        char **args = NULL;
151✔
2901
        r = parse_argv(argc, argv, &args);
151✔
2902
        if (r <= 0)
151✔
2903
                return r;
151✔
2904

2905
        r = dlopen_cryptsetup(LOG_ERR);
151✔
2906
        if (r < 0)
151✔
2907
                return r;
2908

2909
        return dispatch_verb(args, NULL);
151✔
2910
}
2911

2912
DEFINE_MAIN_FUNCTION(run);
151✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc