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

systemd / systemd / 19877670170

02 Dec 2025 04:56PM UTC coverage: 72.905% (+0.001%) from 72.904%
19877670170

push

github

web-flow
kernel-install: exit with option --json=help (#39974)

In that case, `parse_json_argument()` returns 0.

Follow-up for bdd36c003 (v255).

0 of 1 new or added line in 1 file covered. (0.0%)

367 existing lines in 34 files now uncovered.

310170 of 425446 relevant lines covered (72.9%)

1132258.26 hits per line

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

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

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

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

13
#include "alloc-util.h"
14
#include "argv-util.h"
15
#include "ask-password-api.h"
16
#include "build.h"
17
#include "cryptsetup-fido2.h"
18
#include "cryptsetup-keyfile.h"
19
#include "cryptsetup-pkcs11.h"
20
#include "cryptsetup-tpm2.h"
21
#include "cryptsetup-util.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 "fs-util.h"
31
#include "hexdecoct.h"
32
#include "json-util.h"
33
#include "libfido2-util.h"
34
#include "libmount-util.h"
35
#include "log.h"
36
#include "main-func.h"
37
#include "memory-util.h"
38
#include "nulstr-util.h"
39
#include "parse-util.h"
40
#include "path-util.h"
41
#include "pkcs11-util.h"
42
#include "pretty-print.h"
43
#include "random-util.h"
44
#include "string-table.h"
45
#include "string-util.h"
46
#include "strv.h"
47
#include "time-util.h"
48
#include "tpm2-pcr.h"
49
#include "tpm2-util.h"
50
#include "verbs.h"
51

52
/* internal helper */
53
#define ANY_LUKS "LUKS"
54
/* as in src/cryptsetup.h */
55
#define CRYPT_SECTOR_SIZE 512U
56
#define CRYPT_MAX_SECTOR_SIZE 4096U
57

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

67
typedef enum TokenType {
68
        TOKEN_TPM2,
69
        TOKEN_FIDO2,
70
        TOKEN_PKCS11,
71
        _TOKEN_TYPE_MAX,
72
        _TOKEN_TYPE_INVALID = -EINVAL,
73
} TokenType;
74

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

129
STATIC_DESTRUCTOR_REGISTER(arg_cipher, freep);
125✔
130
STATIC_DESTRUCTOR_REGISTER(arg_hash, freep);
125✔
131
STATIC_DESTRUCTOR_REGISTER(arg_header, freep);
125✔
132
STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles, strv_freep);
125✔
133
STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri, freep);
125✔
134
STATIC_DESTRUCTOR_REGISTER(arg_fido2_device, freep);
125✔
135
STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid, freep);
125✔
136
STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id, freep);
125✔
137
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
125✔
138
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_signature, freep);
125✔
139
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_measure_banks, strv_freep);
125✔
140
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_measure_keyslot_nvpcr, freep);
125✔
141
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_pcrlock, freep);
125✔
142
STATIC_DESTRUCTOR_REGISTER(arg_link_keyring, freep);
125✔
143
STATIC_DESTRUCTOR_REGISTER(arg_link_key_type, freep);
125✔
144
STATIC_DESTRUCTOR_REGISTER(arg_link_key_description, freep);
125✔
145

146
static const char* const passphrase_type_table[_PASSPHRASE_TYPE_MAX] = {
147
        [PASSPHRASE_REGULAR]      = "passphrase",
148
        [PASSPHRASE_RECOVERY_KEY] = "recovery key",
149
        [PASSPHRASE_BOTH]         = "passphrase or recovery key",
150
};
151

152
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(passphrase_type, PassphraseType);
×
153

154
static const char* const token_type_table[_TOKEN_TYPE_MAX] = {
155
        [TOKEN_TPM2]   = "tpm2",
156
        [TOKEN_FIDO2]  = "fido2",
157
        [TOKEN_PKCS11] = "pkcs11",
158
};
159

160
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(token_type, TokenType);
45✔
161

162
/* Options Debian's crypttab knows we don't:
163
    check=
164
    checkargs=
165
    noearly
166
    loud
167
    quiet
168
    keyscript=
169
    initramfs
170
*/
171

172
static int parse_one_option(const char *option) {
145✔
173
        const char *val;
145✔
174
        int r;
145✔
175

176
        assert(option);
145✔
177

178
        /* Handled outside of this tool */
179
        if (STR_IN_SET(option, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
145✔
180
                return 0;
1✔
181

182
        if (startswith(option, "keyfile-timeout="))
144✔
183
                return 0;
184

185
        if ((val = startswith(option, "cipher="))) {
144✔
186
                r = free_and_strdup(&arg_cipher, val);
×
187
                if (r < 0)
×
188
                        return log_oom();
×
189

190
        } else if ((val = startswith(option, "size="))) {
144✔
191

192
                r = safe_atou(val, &arg_key_size);
×
193
                if (r < 0) {
×
194
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
195
                        return 0;
×
196
                }
197

198
                if (arg_key_size % 8) {
×
199
                        log_warning("size= not a multiple of 8, ignoring.");
×
200
                        return 0;
×
201
                }
202

203
                arg_key_size /= 8;
×
204

205
        } else if ((val = startswith(option, "sector-size="))) {
144✔
206

207
                r = safe_atou(val, &arg_sector_size);
×
208
                if (r < 0) {
×
209
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
210
                        return 0;
×
211
                }
212

213
                if (arg_sector_size % 2) {
×
214
                        log_warning("sector-size= not a multiple of 2, ignoring.");
×
215
                        return 0;
×
216
                }
217

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

221
        } else if ((val = startswith(option, "key-slot=")) ||
144✔
222
                   (val = startswith(option, "keyslot="))) {
142✔
223

224
                arg_type = ANY_LUKS;
2✔
225
                r = safe_atoi(val, &arg_key_slot);
2✔
226
                if (r < 0)
2✔
227
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
228

229
        } else if ((val = startswith(option, "tcrypt-keyfile="))) {
142✔
230

231
                arg_type = CRYPT_TCRYPT;
×
232
                if (path_is_absolute(val)) {
×
233
                        if (strv_extend(&arg_tcrypt_keyfiles, val) < 0)
×
234
                                return log_oom();
×
235
                } else
236
                        log_warning("Key file path \"%s\" is not absolute, ignoring.", val);
×
237

238
        } else if ((val = startswith(option, "keyfile-size="))) {
142✔
239

240
                r = safe_atou(val, &arg_keyfile_size);
3✔
241
                if (r < 0)
3✔
242
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
243

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

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

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

252
                r = parse_boolean(val);
2✔
253
                if (r < 0) {
2✔
254
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
255
                        return 0;
×
256
                }
257

258
                arg_keyfile_erase = r;
2✔
259

260
        } else if (streq(option, "keyfile-erase"))
132✔
261
                arg_keyfile_erase = true;
×
262

263
        else if ((val = startswith(option, "hash="))) {
132✔
264
                r = free_and_strdup(&arg_hash, val);
×
265
                if (r < 0)
×
266
                        return log_oom();
×
267

268
        } else if ((val = startswith(option, "header="))) {
132✔
269
                if (!arg_type || !STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT))
9✔
270
                        arg_type = ANY_LUKS;
7✔
271

272
                if (!path_is_absolute(val))
9✔
273
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
274
                                               "Header path \"%s\" is not absolute, refusing.", val);
275

276
                if (arg_header)
9✔
277
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
278
                                               "Duplicate header= option, refusing.");
279

280
                arg_header = strdup(val);
9✔
281
                if (!arg_header)
9✔
282
                        return log_oom();
×
283

284
        } else if ((val = startswith(option, "tries="))) {
123✔
285

286
                r = safe_atou(val, &arg_tries);
×
287
                if (r < 0)
×
288
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
145✔
289

290
        } else if (STR_IN_SET(option, "readonly", "read-only"))
123✔
291
                arg_readonly = true;
×
292
        else if (streq(option, "verify"))
123✔
293
                arg_verify = true;
×
294
        else if ((val = startswith(option, "password-echo="))) {
123✔
295
                if (streq(val, "masked"))
×
296
                        arg_ask_password_flags &= ~(ASK_PASSWORD_ECHO|ASK_PASSWORD_SILENT);
×
297
                else {
298
                        r = parse_boolean(val);
×
299
                        if (r < 0) {
×
300
                                log_warning_errno(r, "Invalid password-echo= option \"%s\", ignoring.", val);
×
301
                                return 0;
×
302
                        }
303

304
                        SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_ECHO, r);
×
305
                        SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_SILENT, !r);
×
306
                }
307
        } else if ((val = startswith(option, "password-cache="))) {
123✔
308
                arg_password_cache_set = true;
×
309

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

320
                        SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_ACCEPT_CACHED|ASK_PASSWORD_PUSH_CACHE, r);
×
321
                }
322
        } else if (STR_IN_SET(option, "allow-discards", "discard"))
123✔
323
                arg_discards = true;
×
324
        else if (streq(option, "same-cpu-crypt"))
123✔
325
                arg_same_cpu_crypt = true;
×
326
        else if (streq(option, "submit-from-crypt-cpus"))
123✔
327
                arg_submit_from_crypt_cpus = true;
×
328
        else if (streq(option, "no-read-workqueue"))
123✔
329
                arg_no_read_workqueue = true;
×
330
        else if (streq(option, "no-write-workqueue"))
123✔
331
                arg_no_write_workqueue = true;
×
332
        else if (streq(option, "luks"))
123✔
333
                arg_type = ANY_LUKS;
8✔
334
/* since cryptsetup 2.3.0 (Feb 2020) */
335
#ifdef CRYPT_BITLK
336
        else if (streq(option, "bitlk"))
115✔
337
                arg_type = CRYPT_BITLK;
×
338
#endif
339
        else if (streq(option, "tcrypt"))
115✔
340
                arg_type = CRYPT_TCRYPT;
×
341
        else if (STR_IN_SET(option, "tcrypt-hidden", "tcrypthidden")) {
115✔
342
                arg_type = CRYPT_TCRYPT;
×
343
                arg_tcrypt_hidden = true;
×
344
        } else if (streq(option, "tcrypt-system")) {
115✔
345
                arg_type = CRYPT_TCRYPT;
×
346
                arg_tcrypt_system = true;
×
347
        } else if (STR_IN_SET(option, "tcrypt-veracrypt", "veracrypt")) {
115✔
348
                arg_type = CRYPT_TCRYPT;
×
349
                arg_tcrypt_veracrypt = true;
×
350
        } else if ((val = startswith(option, "veracrypt-pim="))) {
115✔
351

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

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

366
        } else if ((val = startswith(option, "offset="))) {
115✔
367

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

372
        } else if ((val = startswith(option, "skip="))) {
115✔
373

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

378
        } else if ((val = startswith(option, "pkcs11-uri="))) {
115✔
379

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

387
                        r = free_and_strdup(&arg_pkcs11_uri, val);
×
388
                        if (r < 0)
×
389
                                return log_oom();
×
390

391
                        arg_pkcs11_uri_auto = false;
×
392
                }
393

394
        } else if ((val = startswith(option, "fido2-device="))) {
109✔
395

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

404
                        arg_fido2_device_auto = false;
×
405
                }
406

407
        } else if ((val = startswith(option, "fido2-cid="))) {
109✔
408

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

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

419
                        free(arg_fido2_cid);
×
420
                        arg_fido2_cid = TAKE_PTR(cid);
×
421
                        arg_fido2_cid_size = cid_size;
×
422
                }
423

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

428
        } else if ((val = startswith(option, "fido2-rp="))) {
109✔
429

430
                r = free_and_strdup(&arg_fido2_rp_id, val);
×
431
                if (r < 0)
×
432
                        return log_oom();
×
433

434
        } else if ((val = startswith(option, "fido2-pin="))) {
109✔
435

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

442
                arg_fido2_manual_flags &= ~FIDO2ENROLL_PIN_IF_NEEDED;
×
443
                SET_FLAG(arg_fido2_manual_flags, FIDO2ENROLL_PIN, r);
×
444

445
        } else if ((val = startswith(option, "fido2-up="))) {
109✔
446

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

453
                arg_fido2_manual_flags &= ~FIDO2ENROLL_UP_IF_NEEDED;
×
454
                SET_FLAG(arg_fido2_manual_flags, FIDO2ENROLL_UP, r);
×
455

456
        } else if ((val = startswith(option, "fido2-uv="))) {
109✔
457

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

464
                arg_fido2_manual_flags &= ~FIDO2ENROLL_UV_OMIT;
×
465
                SET_FLAG(arg_fido2_manual_flags, FIDO2ENROLL_UV, r);
×
466

467
        } else if ((val = startswith(option, "tpm2-device="))) {
109✔
468

469
                if (streq(val, "auto")) {
39✔
470
                        arg_tpm2_device = mfree(arg_tpm2_device);
39✔
471
                        arg_tpm2_device_auto = true;
39✔
472
                } else {
473
                        r = free_and_strdup(&arg_tpm2_device, val);
×
474
                        if (r < 0)
×
475
                                return log_oom();
×
476

477
                        arg_tpm2_device_auto = false;
×
478
                }
479

480
        } else if ((val = startswith(option, "tpm2-pcrs="))) {
70✔
481

482
                r = tpm2_parse_pcr_argument_to_mask(val, &arg_tpm2_pcr_mask);
×
483
                if (r < 0)
×
484
                        return r;
485

486
        } else if ((val = startswith(option, "tpm2-signature="))) {
70✔
487

488
                if (!path_is_absolute(val))
1✔
489
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
490
                                               "TPM2 signature path \"%s\" is not absolute, refusing.", val);
491

492
                r = free_and_strdup(&arg_tpm2_signature, val);
1✔
493
                if (r < 0)
1✔
494
                        return log_oom();
×
495

496
        } else if ((val = startswith(option, "tpm2-pin="))) {
69✔
497

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

504
                arg_tpm2_pin = r;
×
505

506
        } else if ((val = startswith(option, "tpm2-pcrlock="))) {
69✔
507

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

512
                r = free_and_strdup(&arg_tpm2_pcrlock, val);
5✔
513
                if (r < 0)
5✔
514
                        return log_oom();
×
515

516
        } else if ((val = startswith(option, "tpm2-measure-pcr="))) {
64✔
517
                unsigned pcr;
×
518

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

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

533
                arg_tpm2_measure_pcr = pcr;
×
534

535
        } else if ((val = startswith(option, "tpm2-measure-bank="))) {
64✔
536

537
#if HAVE_OPENSSL
538
                _cleanup_strv_free_ char **l = NULL;
×
539

540
                l = strv_split(val, ":");
×
541
                if (!l)
×
542
                        return log_oom();
×
543

544
                STRV_FOREACH(i, l) {
×
545
                        const EVP_MD *implementation;
×
546

547
                        implementation = EVP_get_digestbyname(*i);
×
548
                        if (!implementation)
×
549
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown bank '%s', refusing.", val);
×
550

551
                        if (strv_extend(&arg_tpm2_measure_banks, EVP_MD_name(implementation)) < 0)
×
552
                                return log_oom();
×
553
                }
554
#else
555
                log_error("Build lacks OpenSSL support, cannot measure to PCR banks, ignoring: %s", option);
556
#endif
557

558
        } else if ((val = startswith(option, "tpm2-measure-keyslot-nvpcr="))) {
64✔
559

560
                if (isempty(val)) {
×
561
                        arg_tpm2_measure_keyslot_nvpcr = mfree(arg_tpm2_measure_keyslot_nvpcr);
×
562
                        return 0;
×
563
                }
564

565
                if (!tpm2_nvpcr_name_is_valid(val)) {
×
566
                        log_warning("Invalid NvPCR name, ignoring: %s", option);
×
567
                        return 0;
×
568
                }
569

570
                if (free_and_strdup(&arg_tpm2_measure_keyslot_nvpcr, val) < 0)
×
571
                        return log_oom();
×
572

573
        } else if ((val = startswith(option, "try-empty-password="))) {
64✔
574

575
                r = parse_boolean(val);
1✔
576
                if (r < 0) {
1✔
577
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
578
                        return 0;
×
579
                }
580

581
                arg_try_empty_password = r;
1✔
582

583
        } else if (streq(option, "try-empty-password"))
63✔
584
                arg_try_empty_password = true;
1✔
585
        else if ((val = startswith(option, "headless="))) {
62✔
586

587
                r = parse_boolean(val);
55✔
588
                if (r < 0) {
55✔
589
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
590
                        return 0;
×
591
                }
592

593
                SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_HEADLESS, r);
55✔
594
        } else if (streq(option, "headless"))
7✔
595
                arg_ask_password_flags |= ASK_PASSWORD_HEADLESS;
7✔
596

UNCOV
597
        else if ((val = startswith(option, "token-timeout="))) {
×
598

599
                r = parse_sec_fix_0(val, &arg_token_timeout_usec);
×
600
                if (r < 0)
×
601
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
115✔
602

UNCOV
603
        } else if ((val = startswith(option, "link-volume-key="))) {
×
604
#if HAVE_CRYPT_SET_KEYRING_TO_LINK
605
                _cleanup_free_ char *keyring = NULL, *key_type = NULL, *key_description = NULL;
×
606
                const char *sep;
×
607

608
                /* Stick with cryptsetup --link-vk-to-keyring format
609
                 * <keyring_description>::%<key_type>:<key_description>,
610
                 * where %<key_type> is optional and defaults to 'user'.
611
                 */
612
                sep = strstr(val, "::");
×
613
                if (!sep)
×
614
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse link-volume-key= option value: %s", val);
×
615

616
                /* cryptsetup (cli) supports <keyring_description> passed in various formats:
617
                 * - well-known keyrings prefixed with '@' (@u user, @s session, etc)
618
                 * - text descriptions prefixed with "%:" or "%keyring:".
619
                 * - text description with no prefix.
620
                 * - numeric keyring id (ignored in current patch set). */
621
                keyring = strndup(val, sep - val);
×
622
                if (!keyring)
×
623
                        return log_oom();
×
624

625
                /* add type prefix if missing (crypt_set_keyring_to_link() expects it) */
626
                if (!IN_SET(*keyring, '@', '%'))
×
627
                        if (!strprepend(&keyring, "%:"))
×
628
                                return log_oom();
×
629

630
                sep += 2;
×
631

632
                /* %<key_type> is optional (and defaults to 'user') */
633
                if (*sep == '%') {
×
634
                        /* must be separated by colon */
635
                        const char *c = strchr(sep, ':');
×
636
                        if (!c)
×
637
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse link-volume-key= option value: %s", val);
×
638

639
                        key_type = strndup(sep + 1, c - sep - 1);
×
640
                        if (!key_type)
×
641
                                return log_oom();
×
642

643
                        sep = c + 1;
×
644
                }
645

646
                key_description = strdup(sep);
×
647
                if (!key_description)
×
648
                        return log_oom();
×
649

650
                free_and_replace(arg_link_keyring, keyring);
×
651
                free_and_replace(arg_link_key_type, key_type);
×
652
                free_and_replace(arg_link_key_description, key_description);
×
653
#else
654
                log_error("Build lacks libcryptsetup support for linking volume keys in user specified kernel keyrings upon device activation, ignoring: %s", option);
655
#endif
UNCOV
656
        } else if (!streq(option, "x-initrd.attach"))
×
657
                log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
×
658

659
        return 0;
660
}
661

662
static int parse_crypt_config(const char *options) {
70✔
663
        assert(options);
70✔
664

665
        for (;;) {
360✔
666
                _cleanup_free_ char *word = NULL;
145✔
667
                int r;
215✔
668

669
                r = extract_first_word(&options, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS | EXTRACT_UNESCAPE_SEPARATORS);
215✔
670
                if (r < 0)
215✔
671
                        return log_error_errno(r, "Failed to parse options: %m");
×
672
                if (r == 0)
215✔
673
                        break;
674

675
                r = parse_one_option(word);
145✔
676
                if (r < 0)
145✔
677
                        return r;
678
        }
679

680
        /* sanity-check options */
681
        if (arg_type && !streq(arg_type, CRYPT_PLAIN)) {
70✔
682
                if (arg_offset != 0)
17✔
683
                      log_warning("offset= ignored with type %s", arg_type);
×
684
                if (arg_skip != 0)
17✔
685
                      log_warning("skip= ignored with type %s", arg_type);
×
686
        }
687

688
        if (arg_pkcs11_uri || arg_pkcs11_uri_auto) {
70✔
689
                /* If password-cache was not configured explicitly, default to no cache for PKCS#11 */
690
                if (!arg_password_cache_set)
6✔
691
                        arg_ask_password_flags &= ~(ASK_PASSWORD_ACCEPT_CACHED|ASK_PASSWORD_PUSH_CACHE);
6✔
692

693
                /* This prevents future backward-compatibility issues if we decide to allow caching for PKCS#11 */
694
                if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_ACCEPT_CACHED))
6✔
695
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
696
                                               "Password cache is not supported for PKCS#11 security tokens.");
697
        }
698

699
        return 0;
700
}
701

702
static char* disk_description(const char *path) {
10✔
703
        static const char name_fields[] =
10✔
704
                "DM_NAME\0"
705
                "ID_MODEL_FROM_DATABASE\0"
706
                "ID_MODEL\0";
707

708
        _cleanup_(sd_device_unrefp) sd_device *device = NULL;
10✔
709
        const char *name;
10✔
710
        struct stat st;
10✔
711

712
        assert(path);
10✔
713

714
        if (stat(path, &st) < 0)
10✔
715
                return NULL;
716

717
        if (!S_ISBLK(st.st_mode))
10✔
718
                return NULL;
719

720
        if (sd_device_new_from_stat_rdev(&device, &st) < 0)
×
721
                return NULL;
722

723
        if (sd_device_get_property_value(device, "ID_PART_ENTRY_NAME", &name) >= 0) {
×
724
                _cleanup_free_ char *unescaped = NULL;
×
725
                ssize_t l;
×
726

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

731
                l = cunescape(name, UNESCAPE_RELAX, &unescaped);
×
732
                if (l < 0) {
×
733
                        log_debug_errno(l, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
×
734
                        return NULL;
×
735
                }
736

737
                if (!isempty(unescaped) && !string_has_cc(unescaped, NULL))
×
738
                        return TAKE_PTR(unescaped);
×
739
        }
740

741
        /* These need no unescaping. */
742
        NULSTR_FOREACH(i, name_fields)
×
743
                if (sd_device_get_property_value(device, i, &name) >= 0 &&
×
744
                    !isempty(name))
×
745
                        return strdup(name);
×
746

747
        return NULL;
748
}
749

750
static char* disk_mount_point(const char *label) {
10✔
751
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
10✔
752
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
×
753
        _cleanup_free_ char *device = NULL;
10✔
754
        int r;
10✔
755

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

758
        assert(label);
10✔
759

760
        device = strjoin("/dev/mapper/", label);
10✔
761
        if (!device)
10✔
762
                return NULL;
763

764
        r = libmount_parse_fstab(&table, &iter);
10✔
765
        if (r < 0)
10✔
766
                return NULL;
767

768
        for (;;) {
×
769
                struct libmnt_fs *fs;
10✔
770

771
                r = sym_mnt_table_next_fs(table, iter, &fs);
10✔
772
                if (r != 0)
10✔
773
                        return NULL;
10✔
774

775
                if (path_equal(sym_mnt_fs_get_source(fs), device)) {
×
776
                        const char *target = sym_mnt_fs_get_target(fs);
×
777
                        if (target)
×
778
                                return strdup(target);
×
779
                }
780
        }
781
}
782

783
static char *friendly_disk_name(const char *src, const char *vol) {
10✔
784
        _cleanup_free_ char *description = NULL, *mount_point = NULL;
10✔
785
        char *name_buffer = NULL;
10✔
786
        int r;
10✔
787

788
        assert(src);
10✔
789
        assert(vol);
10✔
790

791
        description = disk_description(src);
10✔
792
        mount_point = disk_mount_point(vol);
10✔
793

794
        /* If the description string is simply the volume name, then let's not show this twice */
795
        if (description && streq(vol, description))
10✔
796
                description = mfree(description);
×
797

798
        if (mount_point && description)
10✔
799
                r = asprintf(&name_buffer, "%s (%s) on %s", description, vol, mount_point);
×
800
        else if (mount_point)
×
801
                r = asprintf(&name_buffer, "%s on %s", vol, mount_point);
×
802
        else if (description)
10✔
803
                r = asprintf(&name_buffer, "%s (%s)", description, vol);
×
804
        else
805
                return strdup(vol);
10✔
806
        if (r < 0)
×
807
                return NULL;
808

809
        return name_buffer;
×
810
}
811

812
static PassphraseType check_registered_passwords(struct crypt_device *cd) {
14✔
813
        _cleanup_free_ bool *slots = NULL;
14✔
814
        int slot_max;
14✔
815
        PassphraseType passphrase_type = PASSPHRASE_NONE;
14✔
816

817
        assert(cd);
14✔
818

819
        if (!streq_ptr(crypt_get_type(cd), CRYPT_LUKS2)) {
14✔
820
                log_debug("%s: not a LUKS2 device, only passphrases are supported", crypt_get_device_name(cd));
×
821
                return PASSPHRASE_REGULAR;
×
822
        }
823

824
        /* Search all used slots */
825
        assert_se((slot_max = crypt_keyslot_max(CRYPT_LUKS2)) > 0);
14✔
826
        slots = new(bool, slot_max);
14✔
827
        if (!slots)
14✔
828
                return log_oom();
×
829

830
        for (int slot = 0; slot < slot_max; slot++)
462✔
831
                slots[slot] = IN_SET(crypt_keyslot_status(cd, slot), CRYPT_SLOT_ACTIVE, CRYPT_SLOT_ACTIVE_LAST);
448✔
832

833
        /* Iterate all LUKS2 tokens and keep track of all their slots */
834
        for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
462✔
835
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
448✔
836
                const char *type;
448✔
837
                sd_json_variant *w, *z;
448✔
838
                int tk;
448✔
839

840
                tk = cryptsetup_get_token_as_json(cd, token, NULL, &v);
448✔
841
                if (IN_SET(tk, -ENOENT, -EINVAL))
448✔
842
                        continue;
439✔
843
                if (tk < 0) {
9✔
844
                        log_warning_errno(tk, "Failed to read JSON token data, ignoring: %m");
×
845
                        continue;
×
846
                }
847

848
                w = sd_json_variant_by_key(v, "type");
9✔
849
                if (!w || !sd_json_variant_is_string(w)) {
9✔
850
                        log_warning("Token JSON data lacks type field, ignoring.");
×
851
                        continue;
×
852
                }
853

854
                type = sd_json_variant_string(w);
9✔
855
                if (STR_IN_SET(type, "systemd-recovery", "systemd-pkcs11", "systemd-fido2", "systemd-tpm2")) {
9✔
856

857
                        /* At least exists one recovery key */
858
                        if (streq(type, "systemd-recovery"))
9✔
859
                                passphrase_type |= PASSPHRASE_RECOVERY_KEY;
×
860

861
                        w = sd_json_variant_by_key(v, "keyslots");
9✔
862
                        if (!w || !sd_json_variant_is_array(w)) {
9✔
863
                                log_warning("Token JSON data lacks keyslots field, ignoring.");
×
864
                                continue;
×
865
                        }
866

867
                        JSON_VARIANT_ARRAY_FOREACH(z, w) {
18✔
868
                                unsigned u;
9✔
869
                                int at;
9✔
870

871
                                if (!sd_json_variant_is_string(z)) {
9✔
872
                                        log_warning("Token JSON data's keyslot field is not an array of strings, ignoring.");
×
873
                                        continue;
×
874
                                }
875

876
                                at = safe_atou(sd_json_variant_string(z), &u);
9✔
877
                                if (at < 0) {
9✔
878
                                        log_warning_errno(at, "Token JSON data's keyslot field is not an integer formatted as string, ignoring.");
×
879
                                        continue;
×
880
                                }
881

882
                                if (u >= (unsigned) slot_max) {
9✔
883
                                        log_warning_errno(at, "Token JSON data's keyslot field exceeds the maximum value allowed, ignoring.");
×
884
                                        continue;
×
885
                                }
886

887
                                slots[u] = false;
9✔
888
                        }
889
                }
890
        }
891

892
        /* Check if any of the slots is not referenced by systemd tokens */
893
        for (int slot = 0; slot < slot_max; slot++)
14✔
894
                if (slots[slot]) {
14✔
895
                        passphrase_type |= PASSPHRASE_REGULAR;
14✔
896
                        break;
14✔
897
                }
898

899
        /* All the slots are referenced by systemd tokens, so if a recovery key is not enrolled,
900
         * we will not be able to enter a passphrase. */
901
        return passphrase_type;
902
}
903

904
static int get_password(
14✔
905
                const char *vol,
906
                const char *src,
907
                usec_t until,
908
                bool ignore_cached,
909
                PassphraseType passphrase_type,
910
                char ***ret) {
911

912
        _cleanup_free_ char *friendly = NULL, *text = NULL, *disk_path = NULL, *id = NULL;
14✔
913
        _cleanup_strv_free_erase_ char **passwords = NULL;
×
914
        AskPasswordFlags flags = arg_ask_password_flags;
14✔
915
        int r;
14✔
916

917
        assert(vol);
14✔
918
        assert(src);
14✔
919
        assert(ret);
14✔
920

921
        if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_HEADLESS))
14✔
922
                return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Password querying disabled via 'headless' option.");
14✔
923

924
        friendly = friendly_disk_name(src, vol);
×
925
        if (!friendly)
×
926
                return log_oom();
×
927

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

931
        disk_path = cescape(src);
×
932
        if (!disk_path)
×
933
                return log_oom();
×
934

935
        id = strjoin("cryptsetup:", disk_path);
×
936
        if (!id)
×
937
                return log_oom();
×
938

939
        AskPasswordRequest req = {
×
940
                .tty_fd = -EBADF,
941
                .message = text,
942
                .icon = "drive-harddisk",
943
                .id = id,
944
                .keyring = "cryptsetup",
945
                .credential = "cryptsetup.passphrase",
946
                .until = until,
947
                .hup_fd = -EBADF,
948
        };
949

950
        if (ignore_cached)
×
951
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
×
952

953
        r = ask_password_auto(&req, flags, &passwords);
×
954
        if (r < 0)
×
955
                return log_error_errno(r, "Failed to query password: %m");
×
956

957
        if (arg_verify) {
×
958
                _cleanup_strv_free_erase_ char **passwords2 = NULL;
×
959

960
                assert(strv_length(passwords) == 1);
×
961

962
                text = mfree(text);
×
963
                if (asprintf(&text, "Please enter %s for disk %s (verification):", passphrase_type_to_string(passphrase_type), friendly) < 0)
×
964
                        return log_oom();
×
965

966
                free(id);
×
967
                id = strjoin("cryptsetup-verification:", disk_path);
×
968
                if (!id)
×
969
                        return log_oom();
×
970

971
                req.message = text;
×
972
                req.id = id;
×
973

974
                r = ask_password_auto(&req, flags, &passwords2);
×
975
                if (r < 0)
×
976
                        return log_error_errno(r, "Failed to query verification password: %m");
×
977

978
                assert(strv_length(passwords2) == 1);
×
979

980
                if (!streq(passwords[0], passwords2[0]))
×
981
                        return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN),
×
982
                                                 "Passwords did not match, retrying.");
983
        }
984

985
        strv_uniq(passwords);
×
986

987
        STRV_FOREACH(p, passwords) {
×
988
                char *c;
×
989

990
                if (strlen(*p)+1 >= arg_key_size)
×
991
                        continue;
×
992

993
                /* Pad password if necessary */
994
                c = new(char, arg_key_size);
×
995
                if (!c)
×
996
                        return log_oom();
14✔
997

998
                strncpy(c, *p, arg_key_size);
×
999
                erase_and_free(*p);
×
1000
                *p = TAKE_PTR(c);
×
1001
        }
1002

1003
        *ret = TAKE_PTR(passwords);
×
1004

1005
        return 0;
×
1006
}
1007

1008
static int measure_volume_key(
×
1009
                struct crypt_device *cd,
1010
                const char *name,
1011
                const void *volume_key,
1012
                size_t volume_key_size) {
1013

1014
        int r;
×
1015

1016
        assert(cd);
×
1017
        assert(name);
×
1018
        assert(volume_key);
×
1019
        assert(volume_key_size > 0);
×
1020

1021
        if (arg_tpm2_measure_pcr == UINT_MAX) {
×
1022
                log_debug("Not measuring volume key, deactivated.");
×
1023
                return 0;
×
1024
        }
1025

1026
        r = efi_measured_uki(LOG_WARNING);
×
1027
        if (r < 0)
×
1028
                return r;
1029
        if (r == 0) {
×
1030
                log_debug("Kernel stub did not measure kernel image into the expected PCR, skipping userspace volume key measurement, too.");
×
1031
                return 0;
×
1032
        }
1033

1034
#if HAVE_TPM2
1035
        _cleanup_(tpm2_context_unrefp) Tpm2Context *c = NULL;
×
1036
        r = tpm2_context_new_or_warn(arg_tpm2_device, &c);
×
1037
        if (r < 0)
×
1038
                return r;
1039

1040
        _cleanup_strv_free_ char **l = NULL;
×
1041
        if (strv_isempty(arg_tpm2_measure_banks)) {
×
1042
                r = tpm2_get_good_pcr_banks_strv(c, UINT32_C(1) << arg_tpm2_measure_pcr, &l);
×
1043
                if (r < 0)
×
1044
                        return log_error_errno(r, "Could not verify pcr banks: %m");
×
1045
        }
1046

1047
        _cleanup_free_ char *joined = strv_join(l ?: arg_tpm2_measure_banks, ", ");
×
1048
        if (!joined)
×
1049
                return log_oom();
×
1050

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

1055
        _cleanup_free_ char *escaped = NULL;
×
1056
        escaped = xescape(name, ":"); /* avoid ambiguity around ":" once we join things below */
×
1057
        if (!escaped)
×
1058
                return log_oom();
×
1059

1060
        _cleanup_free_ char *s = NULL;
×
1061
        s = strjoin("cryptsetup:", escaped, ":", strempty(crypt_get_uuid(cd)));
×
1062
        if (!s)
×
1063
                return log_oom();
×
1064

1065
        r = tpm2_pcr_extend_bytes(c, l ?: arg_tpm2_measure_banks, arg_tpm2_measure_pcr, &IOVEC_MAKE_STRING(s), &IOVEC_MAKE(volume_key, volume_key_size), TPM2_EVENT_VOLUME_KEY, s);
×
1066
        if (r < 0)
×
1067
                return log_error_errno(r, "Could not extend PCR: %m");
×
1068

1069
        log_struct(LOG_INFO,
×
1070
                   LOG_MESSAGE_ID(SD_MESSAGE_TPM_PCR_EXTEND_STR),
1071
                   LOG_MESSAGE("Successfully extended PCR index %u with '%s' and volume key (banks %s).", arg_tpm2_measure_pcr, s, joined),
1072
                   LOG_ITEM("MEASURING=%s", s),
1073
                   LOG_ITEM("PCR=%u", arg_tpm2_measure_pcr),
1074
                   LOG_ITEM("BANKS=%s", joined));
1075

1076
        return 0;
1077
#else
1078
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support disabled, not measuring volume key.");
1079
#endif
1080
}
1081

1082
static int measure_keyslot(
21✔
1083
                struct crypt_device *cd,
1084
                const char *name,
1085
                const char *mechanism,
1086
                int keyslot) {
1087

1088
        int r;
21✔
1089

1090
        assert(cd);
21✔
1091
        assert(name);
21✔
1092

1093
        if (!arg_tpm2_measure_keyslot_nvpcr) {
21✔
1094
                log_debug("Not measuring unlock keyslot, deactivated.");
21✔
1095
                return 0;
21✔
1096
        }
1097

1098
        r = efi_measured_uki(LOG_WARNING);
×
1099
        if (r < 0)
×
1100
                return r;
1101
        if (r == 0) {
×
1102
                log_debug("Kernel stub did not measure kernel image into the expected PCR, skipping userspace key slot measurement, too.");
×
1103
                return 0;
×
1104
        }
1105

1106
#if HAVE_TPM2
1107
        _cleanup_(tpm2_context_unrefp) Tpm2Context *c = NULL;
×
1108
        r = tpm2_context_new_or_warn(arg_tpm2_device, &c);
×
1109
        if (r < 0)
×
1110
                return r;
1111

1112
        _cleanup_free_ char *escaped = NULL;
×
1113
        escaped = xescape(name, ":"); /* avoid ambiguity around ":" once we join things below */
×
1114
        if (!escaped)
×
1115
                return log_oom();
×
1116

1117
        _cleanup_free_ char *k = NULL;
×
1118
        if (keyslot >= 0 && asprintf(&k, "%i", keyslot) < 0)
×
1119
                return log_oom();
×
1120

1121
        _cleanup_free_ char *s = NULL;
×
1122
        s = strjoin("cryptsetup-keyslot:", escaped, ":", strempty(crypt_get_uuid(cd)), ":", strempty(mechanism), ":", strempty(k));
×
1123
        if (!s)
×
1124
                return log_oom();
×
1125

1126
        r = tpm2_nvpcr_extend_bytes(c, /* session= */ NULL, arg_tpm2_measure_keyslot_nvpcr, &IOVEC_MAKE_STRING(s), /* secret= */ NULL, TPM2_EVENT_KEYSLOT, s);
×
1127
        if (r == -ENETDOWN) {
×
1128
                /* NvPCR is not initialized yet. Do so now. */
1129
                _cleanup_(iovec_done_erase) struct iovec anchor_secret = {};
×
1130
                r = tpm2_nvpcr_acquire_anchor_secret(&anchor_secret, /* sync_secondary= */ false);
×
1131
                if (r < 0)
×
1132
                        return r;
1133

1134
                r = tpm2_nvpcr_initialize(c, /* session= */ NULL, arg_tpm2_measure_keyslot_nvpcr, &anchor_secret);
×
1135
                if (r < 0)
×
1136
                        return log_error_errno(r, "Failed to extend NvPCR index '%s' with anchor secret: %m", name);
×
1137

1138
                r = tpm2_nvpcr_extend_bytes(c, /* session= */ NULL, arg_tpm2_measure_keyslot_nvpcr, &IOVEC_MAKE_STRING(s), /* secret= */ NULL, TPM2_EVENT_KEYSLOT, s);
×
1139
        }
1140
        if (r < 0)
×
1141
                return log_error_errno(r, "Could not extend NvPCR: %m");
×
1142

1143
        log_struct(LOG_INFO,
×
1144
                   "MESSAGE_ID=" SD_MESSAGE_TPM_NVPCR_EXTEND_STR,
1145
                   LOG_MESSAGE("Successfully extended NvPCR index '%s' with '%s'.", arg_tpm2_measure_keyslot_nvpcr, s),
1146
                   "MEASURING=%s", s,
1147
                   "NVPCR=%s", arg_tpm2_measure_keyslot_nvpcr);
1148

1149
        return 0;
1150
#else
1151
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support disabled, not measuring keyslot.");
1152
#endif
1153
}
1154

1155
static int log_external_activation(int r, const char *volume) {
×
1156
        assert(volume);
×
1157

1158
        log_notice_errno(r, "Volume '%s' has been activated externally while we have been trying to activate it.", volume);
×
1159
        return 0;
×
1160
}
1161

1162
static int measured_crypt_activate_by_volume_key(
×
1163
                struct crypt_device *cd,
1164
                const char *name,
1165
                const char *mechanism,
1166
                int keyslot,
1167
                const void *volume_key,
1168
                size_t volume_key_size,
1169
                uint32_t flags) {
1170

1171
        int r;
×
1172

1173
        assert(cd);
×
1174
        assert(name);
×
1175

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

1178
        r = crypt_activate_by_volume_key(cd, name, volume_key, volume_key_size, flags);
×
1179
        if (r == -EEXIST) /* volume is already active */
×
1180
                return log_external_activation(r, name);
×
1181
        if (r < 0)
×
1182
                return r;
1183

1184
        if (volume_key_size > 0)
×
1185
                (void) measure_volume_key(cd, name, volume_key, volume_key_size); /* OK if fails */
×
1186
        else
1187
                log_debug("Not measuring volume key, none specified.");
×
1188

1189
        (void) measure_keyslot(cd, name, mechanism, keyslot); /* ditto */
×
1190
        return r;
×
1191
}
1192

1193
static int measured_crypt_activate_by_passphrase(
24✔
1194
                struct crypt_device *cd,
1195
                const char *name,
1196
                const char *mechanism,
1197
                int keyslot,
1198
                const char *passphrase,
1199
                size_t passphrase_size,
1200
                uint32_t flags) {
1201

1202
        _cleanup_(erase_and_freep) void *vk = NULL;
24✔
1203
        size_t vks;
24✔
1204
        int r;
24✔
1205

1206
        assert(cd);
24✔
1207

1208
        /* A wrapper around crypt_activate_by_passphrase() which also measures to a PCR if that's
1209
         * requested. Note that we need the volume key for the measurement, and
1210
         * crypt_activate_by_passphrase() doesn't give us access to this. Hence, we operate indirectly, and
1211
         * retrieve the volume key first, and then activate through that. */
1212

1213
        if (arg_tpm2_measure_pcr == UINT_MAX) {
24✔
1214
                log_debug("Not measuring volume key, deactivated.");
24✔
1215
                goto shortcut;
24✔
1216
        }
1217

1218
        r = crypt_get_volume_key_size(cd);
×
1219
        if (r < 0)
×
1220
                return r;
1221
        if (r == 0) {
×
1222
                log_debug("Not measuring volume key, none defined.");
×
1223
                goto shortcut;
×
1224
        }
1225

1226
        vk = malloc(vks = r);
×
1227
        if (!vk)
×
1228
                return -ENOMEM;
1229

1230
        keyslot = crypt_volume_key_get(cd, keyslot, vk, &vks, passphrase, passphrase_size);
×
1231
        if (keyslot < 0)
×
1232
                return keyslot;
1233

1234
        return measured_crypt_activate_by_volume_key(cd, name, mechanism, keyslot, vk, vks, flags);
×
1235

1236
shortcut:
24✔
1237
        keyslot = crypt_activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags);
24✔
1238
        if (keyslot == -EEXIST) /* volume is already active */
24✔
1239
                return log_external_activation(keyslot, name);
×
1240
        if (keyslot < 0)
24✔
1241
                return keyslot;
1242

1243
        (void) measure_keyslot(cd, name, mechanism, keyslot);
21✔
1244
        return keyslot;
1245
}
1246

1247
static int attach_tcrypt(
×
1248
                struct crypt_device *cd,
1249
                const char *name,
1250
                TokenType token_type,
1251
                const char *key_file,
1252
                const struct iovec *key_data,
1253
                char **passwords,
1254
                uint32_t flags) {
1255

1256
        int r = 0;
×
1257
        _cleanup_(erase_and_freep) char *passphrase = NULL;
×
1258
        struct crypt_params_tcrypt params = {
×
1259
                .flags = CRYPT_TCRYPT_LEGACY_MODES,
1260
                .keyfiles = (const char **)arg_tcrypt_keyfiles,
1261
                .keyfiles_count = strv_length(arg_tcrypt_keyfiles)
×
1262
        };
1263

1264
        assert(cd);
×
1265
        assert(name);
×
1266
        assert(key_file || key_data || !strv_isempty(passwords));
×
1267

1268
        if (token_type >= 0)
×
1269
                /* Ask for a regular password */
1270
                return log_error_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1271
                                       "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
1272

1273
        if (arg_tcrypt_hidden)
×
1274
                params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
×
1275

1276
        if (arg_tcrypt_system)
×
1277
                params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
×
1278

1279
        if (arg_tcrypt_veracrypt)
×
1280
                params.flags |= CRYPT_TCRYPT_VERA_MODES;
×
1281

1282
        if (arg_tcrypt_veracrypt && arg_tcrypt_veracrypt_pim != 0)
×
1283
                params.veracrypt_pim = arg_tcrypt_veracrypt_pim;
×
1284

1285
        if (key_data) {
×
1286
                params.passphrase = key_data->iov_base;
×
1287
                params.passphrase_size = key_data->iov_len;
×
1288
                r = crypt_load(cd, CRYPT_TCRYPT, &params);
×
1289
        } else if (key_file) {
×
1290
                r = read_one_line_file(key_file, &passphrase);
×
1291
                if (r < 0) {
×
1292
                        log_error_errno(r, "Failed to read password file '%s': %m", key_file);
×
1293
                        return -EAGAIN; /* log with the actual error, but return EAGAIN */
×
1294
                }
1295
                params.passphrase = passphrase;
×
1296
                params.passphrase_size = strlen(passphrase);
×
1297
                r = crypt_load(cd, CRYPT_TCRYPT, &params);
×
1298
        } else {
1299
                r = -EINVAL;
1300
                STRV_FOREACH(p, passwords){
×
1301
                        params.passphrase = *p;
×
1302
                        params.passphrase_size = strlen(*p);
×
1303
                        r = crypt_load(cd, CRYPT_TCRYPT, &params);
×
1304
                        if (r >= 0)
×
1305
                                break;
1306
                }
1307
        }
1308

1309
        if (r < 0) {
×
1310
                if (r == -EPERM) {
×
1311
                        if (key_data)
×
1312
                                log_error_errno(r, "Failed to activate using discovered key. (Key not correct?)");
×
1313
                        else if (key_file)
×
1314
                                log_error_errno(r, "Failed to activate using password file '%s'. (Key data not correct?)", key_file);
×
1315
                        else
1316
                                log_error_errno(r, "Failed to activate using supplied passwords.");
×
1317

1318
                        return r;
×
1319
                }
1320

1321
                return log_error_errno(r, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd));
×
1322
        }
1323

1324
        r = measured_crypt_activate_by_volume_key(
×
1325
                        cd,
1326
                        name,
1327
                        /* mechanism= */ NULL,
1328
                        /* keyslot= */ -1,
1329
                        /* volume_key= */ NULL,
1330
                        /* volume_key_size= */ 0,
1331
                        flags);
1332
        if (r < 0)
×
1333
                return log_error_errno(r, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd));
×
1334

1335
        return 0;
1336
}
1337

1338
static char *make_bindname(const char *volume, TokenType token_type) {
44✔
1339
        const char *token_type_name = token_type_to_string(token_type), *suffix;
44✔
1340
        char *bindname;
44✔
1341
        int r;
44✔
1342

1343
        switch (token_type) {
44✔
1344

1345
        case TOKEN_FIDO2:
1346
                suffix = "-salt";
1347
                break;
1348

1349
        default:
1350
                suffix = NULL;
44✔
1351
        }
1352

1353
        r = asprintf(&bindname,
44✔
1354
                     "@%" PRIx64"/cryptsetup%s%s%s/%s",
1355
                     random_u64(),
1356
                     token_type_name ? "-" : "",
1357
                     strempty(token_type_name),
1358
                     strempty(suffix),
1359
                     volume);
1360
        if (r < 0)
44✔
1361
                return NULL;
44✔
1362

1363
        return bindname;
44✔
1364
}
1365

1366
static int make_security_device_monitor(
×
1367
                sd_event **ret_event,
1368
                sd_device_monitor **ret_monitor) {
1369
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1370
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1371
        int r;
×
1372

1373
        assert(ret_event);
×
1374
        assert(ret_monitor);
×
1375

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

1380
        r = sd_event_default(&event);
×
1381
        if (r < 0)
×
1382
                return log_error_errno(r, "Failed to allocate event loop: %m");
×
1383

1384
        r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
×
1385
        if (r < 0)
×
1386
                return log_error_errno(r, "Failed to install timeout event source: %m");
×
1387

1388
        r = sd_device_monitor_new(&monitor);
×
1389
        if (r < 0)
×
1390
                return log_error_errno(r, "Failed to allocate device monitor: %m");
×
1391

1392
        (void) sd_device_monitor_set_description(monitor, "security-device");
×
1393

1394
        r = sd_device_monitor_filter_add_match_tag(monitor, "security-device");
×
1395
        if (r < 0)
×
1396
                return log_error_errno(r, "Failed to configure device monitor: %m");
×
1397

1398
        r = sd_device_monitor_attach_event(monitor, event);
×
1399
        if (r < 0)
×
1400
                return log_error_errno(r, "Failed to attach device monitor: %m");
×
1401

1402
        r = sd_device_monitor_start(monitor, NULL, NULL);
×
1403
        if (r < 0)
×
1404
                return log_error_errno(r, "Failed to start device monitor: %m");
×
1405

1406
        *ret_event = TAKE_PTR(event);
×
1407
        *ret_monitor = TAKE_PTR(monitor);
×
1408
        return 0;
×
1409
}
1410

1411
static int run_security_device_monitor(
×
1412
                sd_event *event,
1413
                sd_device_monitor *monitor) {
1414
        bool processed = false;
×
1415
        int r;
×
1416

1417
        assert(event);
×
1418
        assert(monitor);
×
1419

1420
        /* Runs the event loop for the device monitor until either something happens, or the timeout is
1421
         * hit. */
1422

1423
        for (;;) {
×
1424
                int x;
×
1425

1426
                r = sd_event_get_exit_code(event, &x);
×
1427
                if (r < 0) {
×
1428
                        if (r != -ENODATA)
×
1429
                                return log_error_errno(r, "Failed to query exit code from event loop: %m");
×
1430

1431
                        /* On ENODATA we aren't told to exit yet. */
1432
                } else {
1433
                        assert(x == -ETIMEDOUT);
×
1434
                        return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1435
                                                "Timed out waiting for security device, aborting security device based authentication attempt.");
1436
                }
1437

1438
                /* Wait for one event, and then eat all subsequent events until there are no further ones */
1439
                r = sd_event_run(event, processed ? 0 : UINT64_MAX);
×
1440
                if (r < 0)
×
1441
                        return log_error_errno(r, "Failed to run event loop: %m");
×
1442
                if (r == 0) /* no events queued anymore */
×
1443
                        return 0;
1444

1445
                processed = true;
×
1446
        }
1447
}
1448

1449
static bool use_token_plugins(void) {
60✔
1450

1451
#if HAVE_TPM2
1452
        /* Currently, there's no way for us to query the volume key when plugins are used. Hence don't use
1453
         * plugins, if measurement has been requested. */
1454
        if (arg_tpm2_measure_pcr != UINT_MAX)
60✔
1455
                return false;
1456
        if (arg_tpm2_measure_keyslot_nvpcr)
60✔
1457
                return false;
1458
#endif
1459

1460
        /* Disable tokens if we're in FIDO2 mode with manual parameters. */
1461
        if (arg_fido2_cid)
60✔
1462
                return false;
1463

1464
#if HAVE_LIBCRYPTSETUP_PLUGINS
1465
        int r;
60✔
1466

1467
        /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
1468
        r = getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
60✔
1469
        if (r < 0 && r != -ENXIO)
60✔
1470
                log_debug_errno(r, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
×
1471
        if (r == 0)
60✔
1472
                return false;
1473

1474
        return crypt_token_external_path();
58✔
1475
#else
1476
        return false;
1477
#endif
1478
}
1479

1480
#if HAVE_LIBCRYPTSETUP_PLUGINS
1481
static int acquire_pins_from_env_variable(char ***ret_pins) {
21✔
1482
        _cleanup_(erase_and_freep) char *envpin = NULL;
21✔
1483
        _cleanup_strv_free_erase_ char **pins = NULL;
21✔
1484
        int r;
21✔
1485

1486
        assert(ret_pins);
21✔
1487

1488
        r = getenv_steal_erase("PIN", &envpin);
21✔
1489
        if (r < 0)
21✔
1490
                return log_error_errno(r, "Failed to acquire PIN from environment: %m");
×
1491
        if (r > 0) {
21✔
1492
                pins = strv_new(envpin);
16✔
1493
                if (!pins)
16✔
1494
                        return log_oom();
×
1495
        }
1496

1497
        *ret_pins = TAKE_PTR(pins);
21✔
1498

1499
        return 0;
21✔
1500
}
1501
#endif
1502

1503
static int crypt_activate_by_token_pin_ask_password(
58✔
1504
                struct crypt_device *cd,
1505
                const char *name,
1506
                const char *type,
1507
                usec_t until,
1508
                void *userdata,
1509
                uint32_t activation_flags,
1510
                const char *message,
1511
                const char *keyring,
1512
                const char *credential) {
1513

1514
#if HAVE_LIBCRYPTSETUP_PLUGINS
1515
        AskPasswordFlags flags = arg_ask_password_flags;
58✔
1516
        _cleanup_strv_free_erase_ char **pins = NULL;
58✔
1517
        int r;
58✔
1518

1519
        r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, /* pin=*/ NULL, /* pin_size= */ 0, userdata, activation_flags);
58✔
1520
        if (r > 0) /* returns unlocked keyslot id on success */
58✔
1521
                return 0;
1522
        if (r == -EEXIST) /* volume is already active */
35✔
1523
                return log_external_activation(r, name);
×
1524
        if (r != -ENOANO) /* needs pin or pin is wrong */
35✔
1525
                return r;
1526

1527
        r = acquire_pins_from_env_variable(&pins);
21✔
1528
        if (r < 0)
21✔
1529
                return r;
1530

1531
        STRV_FOREACH(p, pins) {
25✔
1532
                r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
16✔
1533
                if (r > 0) /* returns unlocked keyslot id on success */
16✔
1534
                        return 0;
1535
                if (r == -EEXIST) /* volume is already active */
5✔
1536
                        return log_external_activation(r, name);
×
1537
                if (r != -ENOANO) /* needs pin or pin is wrong */
5✔
1538
                        return r;
1539
        }
1540

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

1544
        for (;;) {
×
1545
                pins = strv_free_erase(pins);
×
1546

1547
                AskPasswordRequest req = {
×
1548
                        .tty_fd = -EBADF,
1549
                        .message = message,
1550
                        .icon = "drive-harddisk",
1551
                        .keyring = keyring,
1552
                        .credential = credential,
1553
                        .until = until,
1554
                        .hup_fd = -EBADF,
1555
                };
1556

1557
                r = ask_password_auto(&req, flags, &pins);
×
1558
                if (r < 0)
×
1559
                        return r;
×
1560

1561
                STRV_FOREACH(p, pins) {
×
1562
                        r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
×
1563
                        if (r > 0) /* returns unlocked keyslot id on success */
×
1564
                                return 0;
1565
                        if (r == -EEXIST) /* volume is already active */
×
1566
                                return log_external_activation(r, name);
×
1567
                        if (r != -ENOANO) /* needs pin or pin is wrong */
×
1568
                                return r;
1569
                }
1570

1571
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
×
1572
        }
1573
        return r;
1574
#else
1575
        return -EOPNOTSUPP;
1576
#endif
1577
}
1578

1579
static int attach_luks2_by_fido2_via_plugin(
×
1580
                struct crypt_device *cd,
1581
                const char *name,
1582
                usec_t until,
1583
                void *userdata,
1584
                uint32_t activation_flags) {
1585

1586
        return crypt_activate_by_token_pin_ask_password(
×
1587
                        cd,
1588
                        name,
1589
                        "systemd-fido2",
1590
                        until,
1591
                        userdata,
1592
                        activation_flags,
1593
                        "Please enter security token PIN:",
1594
                        "fido2-pin",
1595
                        "cryptsetup.fido2-pin");
1596
}
1597

1598
static int attach_luks_or_plain_or_bitlk_by_fido2(
×
1599
                struct crypt_device *cd,
1600
                const char *name,
1601
                const char *key_file,
1602
                const struct iovec *key_data,
1603
                usec_t until,
1604
                uint32_t flags,
1605
                bool pass_volume_key) {
1606

1607
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1608
        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
×
1609
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1610
        size_t decrypted_key_size;
×
1611
        _cleanup_free_ char *friendly = NULL;
×
1612
        int keyslot = arg_key_slot, r;
×
1613
        bool use_libcryptsetup_plugin = use_token_plugins();
×
1614

1615
        assert(cd);
×
1616
        assert(name);
×
1617
        assert(arg_fido2_device || arg_fido2_device_auto);
×
1618

1619
        if (arg_fido2_cid && !key_file && !iovec_is_set(key_data))
×
1620
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1621
                                        "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
1622

1623
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
×
1624
        if (!friendly)
×
1625
                return log_oom();
×
1626

1627
        for (;;) {
×
1628
                if (use_libcryptsetup_plugin && !arg_fido2_cid) {
×
1629
                        r = attach_luks2_by_fido2_via_plugin(cd, name, until, arg_fido2_device, flags);
×
1630
                        if (IN_SET(r, -ENOTUNIQ, -ENXIO, -ENOENT))
×
1631
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1632
                                                       "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1633

1634
                } else {
1635
                        if (arg_fido2_cid)
×
1636
                                r = acquire_fido2_key(
×
1637
                                                name,
1638
                                                friendly,
1639
                                                arg_fido2_device,
1640
                                                arg_fido2_rp_id,
1641
                                                arg_fido2_cid, arg_fido2_cid_size,
1642
                                                key_file, arg_keyfile_size, arg_keyfile_offset,
1643
                                                key_data,
1644
                                                until,
1645
                                                arg_fido2_manual_flags,
1646
                                                "cryptsetup.fido2-pin",
1647
                                                arg_ask_password_flags,
1648
                                                &decrypted_key,
1649
                                                &decrypted_key_size);
1650
                        else
1651
                                r = acquire_fido2_key_auto(
×
1652
                                                cd,
1653
                                                name,
1654
                                                friendly,
1655
                                                arg_fido2_device,
1656
                                                until,
1657
                                                "cryptsetup.fido2-pin",
1658
                                                arg_ask_password_flags,
1659
                                                &decrypted_key,
1660
                                                &decrypted_key_size);
1661
                        if (r >= 0)
×
1662
                                break;
1663
                }
1664

1665
                if (r != -EAGAIN) /* EAGAIN means: token not found */
×
1666
                        return r;
1667

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

1672
                        assert(!event);
×
1673

1674
                        r = make_security_device_monitor(&event, &monitor);
×
1675
                        if (r < 0)
×
1676
                                return r;
1677

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

1680
                        /* Let's immediately rescan in case the token appeared in the time we needed
1681
                         * to create and configure the monitor */
1682
                        continue;
×
1683
                }
1684

1685
                r = run_security_device_monitor(event, monitor);
×
1686
                if (r < 0)
×
1687
                        return r;
1688

1689
                log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
×
1690
        }
1691

1692
        if (pass_volume_key)
×
1693
                r = measured_crypt_activate_by_volume_key(
×
1694
                                cd,
1695
                                name,
1696
                                "fido2",
1697
                                /* keyslot= */ -1,
1698
                                decrypted_key,
1699
                                decrypted_key_size,
1700
                                flags);
1701
        else {
1702
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
×
1703
                ssize_t base64_encoded_size;
×
1704

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

1707
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
×
1708
                if (base64_encoded_size < 0)
×
1709
                        return log_oom();
×
1710

1711
                r = measured_crypt_activate_by_passphrase(
×
1712
                                cd,
1713
                                name,
1714
                                "fido2",
1715
                                keyslot,
1716
                                base64_encoded,
1717
                                base64_encoded_size,
1718
                                flags);
1719
        }
1720
        if (r == -EPERM) {
×
1721
                log_error_errno(r, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
×
1722
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
1723
        }
1724
        if (r < 0)
×
1725
                return log_error_errno(r, "Failed to activate with FIDO2 acquired key: %m");
×
1726

1727
        return 0;
1728
}
1729

1730
static int attach_luks2_by_pkcs11_via_plugin(
×
1731
                struct crypt_device *cd,
1732
                const char *name,
1733
                const char *friendly_name,
1734
                usec_t until,
1735
                const char *askpw_credential,
1736
                uint32_t flags) {
1737

1738
#if HAVE_LIBCRYPTSETUP_PLUGINS
1739
        int r;
×
1740

1741
        if (!streq_ptr(crypt_get_type(cd), CRYPT_LUKS2))
×
1742
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Automatic PKCS#11 metadata requires LUKS2 device.");
×
1743

1744
        systemd_pkcs11_plugin_params params = {
×
1745
                .friendly_name = friendly_name,
1746
                .until = until,
1747
                .askpw_credential = askpw_credential,
1748
                .askpw_flags = arg_ask_password_flags,
1749
        };
1750

1751
        r = crypt_activate_by_token_pin(cd, name, "systemd-pkcs11", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
×
1752
        if (r > 0) /* returns unlocked keyslot id on success */
×
1753
                r = 0;
1754
        if (r == -EEXIST) /* volume is already active */
×
1755
                r = log_external_activation(r, name);
×
1756

1757
        return r;
1758
#else
1759
        return -EOPNOTSUPP;
1760
#endif
1761
}
1762

1763
static int attach_luks_or_plain_or_bitlk_by_pkcs11(
×
1764
                struct crypt_device *cd,
1765
                const char *name,
1766
                const char *key_file,
1767
                const struct iovec *key_data,
1768
                usec_t until,
1769
                uint32_t flags,
1770
                bool pass_volume_key) {
1771

1772
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1773
        _cleanup_free_ char *friendly = NULL, *discovered_uri = NULL;
×
1774
        size_t decrypted_key_size = 0, discovered_key_size = 0;
×
1775
        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
×
1776
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1777
        _cleanup_free_ void *discovered_key = NULL;
×
1778
        struct iovec discovered_key_data = {};
×
1779
        int keyslot = arg_key_slot, r;
×
1780
        const char *uri = NULL;
×
1781
        bool use_libcryptsetup_plugin = use_token_plugins();
×
1782

1783
        assert(cd);
×
1784
        assert(name);
×
1785
        assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
×
1786

1787
        if (arg_pkcs11_uri_auto) {
×
1788
                if (!use_libcryptsetup_plugin) {
×
1789
                        r = find_pkcs11_auto_data(cd, &discovered_uri, &discovered_key, &discovered_key_size, &keyslot);
×
1790
                        if (IN_SET(r, -ENOTUNIQ, -ENXIO))
×
1791
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1792
                                                       "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1793
                        if (r < 0)
×
1794
                                return r;
1795

1796
                        uri = discovered_uri;
×
1797
                        discovered_key_data = IOVEC_MAKE(discovered_key, discovered_key_size);
×
1798
                        key_data = &discovered_key_data;
×
1799
                }
1800
        } else {
1801
                uri = arg_pkcs11_uri;
×
1802

1803
                if (!key_file && !iovec_is_set(key_data))
×
1804
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing.");
×
1805
        }
1806

1807
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
×
1808
        if (!friendly)
×
1809
                return log_oom();
×
1810

1811
        for (;;) {
×
1812
                if (use_libcryptsetup_plugin && arg_pkcs11_uri_auto)
×
1813
                        r = attach_luks2_by_pkcs11_via_plugin(
×
1814
                                        cd,
1815
                                        name,
1816
                                        friendly,
1817
                                        until,
1818
                                        "cryptsetup.pkcs11-pin",
1819
                                        flags);
1820
                else {
1821
                        r = decrypt_pkcs11_key(
×
1822
                                        name,
1823
                                        friendly,
1824
                                        uri,
1825
                                        key_file, arg_keyfile_size, arg_keyfile_offset,
1826
                                        key_data,
1827
                                        until,
1828
                                        arg_ask_password_flags,
1829
                                        &decrypted_key, &decrypted_key_size);
1830
                        if (r >= 0)
×
1831
                                break;
1832
                }
1833

1834
                if (r != -EAGAIN) /* EAGAIN means: token not found */
×
1835
                        return r;
1836

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

1841
                        assert(!event);
×
1842

1843
                        r = make_security_device_monitor(&event, &monitor);
×
1844
                        if (r < 0)
×
1845
                                return r;
1846

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

1850
                        /* Let's immediately rescan in case the token appeared in the time we needed
1851
                         * to create and configure the monitor */
1852
                        continue;
×
1853
                }
1854

1855
                r = run_security_device_monitor(event, monitor);
×
1856
                if (r < 0)
×
1857
                        return r;
1858

1859
                log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
×
1860
        }
1861
        assert(decrypted_key);
×
1862

1863
        if (pass_volume_key)
×
1864
                r = measured_crypt_activate_by_volume_key(
×
1865
                                cd,
1866
                                name,
1867
                                "pkcs11",
1868
                                /* keyslot= */ -1,
1869
                                decrypted_key,
1870
                                decrypted_key_size,
1871
                                flags);
1872
        else {
1873
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
×
1874
                ssize_t base64_encoded_size;
×
1875

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

1884
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
×
1885
                if (base64_encoded_size < 0)
×
1886
                        return log_oom();
×
1887

1888
                r = measured_crypt_activate_by_passphrase(
×
1889
                                cd,
1890
                                name,
1891
                                "pkcs11",
1892
                                keyslot,
1893
                                base64_encoded,
1894
                                base64_encoded_size,
1895
                                flags);
1896
        }
1897
        if (r == -EPERM) {
×
1898
                log_error_errno(r, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
×
1899
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
1900
        }
1901
        if (r < 0)
×
1902
                return log_error_errno(r, "Failed to activate with PKCS#11 acquired key: %m");
×
1903

1904
        return 0;
1905
}
1906

1907
static int make_tpm2_device_monitor(
×
1908
                sd_event **ret_event,
1909
                sd_device_monitor **ret_monitor) {
1910

1911
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1912
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1913
        int r;
×
1914

1915
        assert(ret_event);
×
1916
        assert(ret_monitor);
×
1917

1918
        r = sd_event_default(&event);
×
1919
        if (r < 0)
×
1920
                return log_error_errno(r, "Failed to allocate event loop: %m");
×
1921

1922
        r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
×
1923
        if (r < 0)
×
1924
                return log_error_errno(r, "Failed to install timeout event source: %m");
×
1925

1926
        r = sd_device_monitor_new(&monitor);
×
1927
        if (r < 0)
×
1928
                return log_error_errno(r, "Failed to allocate device monitor: %m");
×
1929

1930
        (void) sd_device_monitor_set_description(monitor, "tpmrm");
×
1931

1932
        r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "tpmrm", NULL);
×
1933
        if (r < 0)
×
1934
                return log_error_errno(r, "Failed to configure device monitor: %m");
×
1935

1936
        r = sd_device_monitor_attach_event(monitor, event);
×
1937
        if (r < 0)
×
1938
                return log_error_errno(r, "Failed to attach device monitor: %m");
×
1939

1940
        r = sd_device_monitor_start(monitor, NULL, NULL);
×
1941
        if (r < 0)
×
1942
                return log_error_errno(r, "Failed to start device monitor: %m");
×
1943

1944
        *ret_event = TAKE_PTR(event);
×
1945
        *ret_monitor = TAKE_PTR(monitor);
×
1946
        return 0;
×
1947
}
1948

1949
static int attach_luks2_by_tpm2_via_plugin(
10✔
1950
                struct crypt_device *cd,
1951
                const char *name,
1952
                usec_t until,
1953
                uint32_t flags) {
1954

1955
#if HAVE_LIBCRYPTSETUP_PLUGINS
1956
        systemd_tpm2_plugin_params params = {
10✔
1957
                .search_pcr_mask = arg_tpm2_pcr_mask,
1958
                .device = arg_tpm2_device,
1959
                .signature_path = arg_tpm2_signature,
1960
                .pcrlock_path = arg_tpm2_pcrlock,
1961
        };
1962

1963
        if (!use_token_plugins())
10✔
1964
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1✔
1965
                                       "libcryptsetup has external plugins support disabled.");
1966

1967
        return crypt_activate_by_token_pin_ask_password(
9✔
1968
                        cd,
1969
                        name,
1970
                        "systemd-tpm2",
1971
                        until,
1972
                        &params,
1973
                        flags,
1974
                        "Please enter TPM2 PIN:",
1975
                        "tpm2-pin",
1976
                        "cryptsetup.tpm2-pin");
1977
#else
1978
        return -EOPNOTSUPP;
1979
#endif
1980
}
1981

1982
static int attach_luks_or_plain_or_bitlk_by_tpm2(
10✔
1983
                struct crypt_device *cd,
1984
                const char *name,
1985
                const char *key_file,
1986
                const struct iovec *key_data,
1987
                usec_t until,
1988
                uint32_t flags,
1989
                bool pass_volume_key) {
1990

1991
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
10✔
1992
        _cleanup_(iovec_done_erase) struct iovec decrypted_key = {};
×
1993
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
10✔
1994
        _cleanup_free_ char *friendly = NULL;
10✔
1995
        int keyslot = arg_key_slot, r;
10✔
1996

1997
        assert(cd);
10✔
1998
        assert(name);
10✔
1999
        assert(arg_tpm2_device || arg_tpm2_device_auto);
10✔
2000

2001
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
10✔
2002
        if (!friendly)
10✔
2003
                return log_oom();
×
2004

2005
        for (;;) {
10✔
2006
                if (key_file || iovec_is_set(key_data)) {
10✔
2007
                        /* If key data is specified, use that */
2008

2009
                        r = acquire_tpm2_key(
×
2010
                                        name,
2011
                                        arg_tpm2_device,
2012
                                        arg_tpm2_pcr_mask == UINT32_MAX ? TPM2_PCR_MASK_DEFAULT_LEGACY : arg_tpm2_pcr_mask,
×
2013
                                        UINT16_MAX,
2014
                                        /* pubkey= */ NULL,
2015
                                        /* pubkey_pcr_mask= */ 0,
2016
                                        /* signature_path= */ NULL,
2017
                                        /* pcrlock_path= */ NULL,
2018
                                        /* primary_alg= */ 0,
2019
                                        key_file, arg_keyfile_size, arg_keyfile_offset,
2020
                                        key_data, /* n_blobs= */ 1,
2021
                                        /* policy_hash= */ NULL, /* we don't know the policy hash */
2022
                                        /* n_policy_hash= */ 0,
2023
                                        /* salt= */ NULL,
2024
                                        /* srk= */ NULL,
2025
                                        /* pcrlock_nv= */ NULL,
2026
                                        arg_tpm2_pin ? TPM2_FLAGS_USE_PIN : 0,
2027
                                        until,
2028
                                        "cryptsetup.tpm2-pin",
2029
                                        arg_ask_password_flags,
2030
                                        &decrypted_key);
2031
                        if (r >= 0)
×
2032
                                break;
2033
                        if (IN_SET(r, -EACCES, -ENOLCK))
×
2034
                                return log_error_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
×
2035
                        if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
×
2036
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");
×
2037
                        /* EAGAIN means: no tpm2 chip found */
2038
                        if (r != -EAGAIN) {
×
2039
                                log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
×
2040
                                return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
×
2041
                        }
2042
                } else {
2043
                        r = attach_luks2_by_tpm2_via_plugin(cd, name, until, flags);
10✔
2044
                        if (r >= 0)
10✔
2045
                                return 0;
2046
                        /* EAGAIN     means: no tpm2 chip found
2047
                         * EOPNOTSUPP means: no libcryptsetup plugins support */
2048
                        if (r == -ENXIO)
10✔
2049
                                return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
×
2050
                                                        "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
2051
                        if (r == -ENOENT)
10✔
2052
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
3✔
2053
                                                       "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
2054
                        if (!IN_SET(r, -EOPNOTSUPP, -EAGAIN)) {
7✔
2055
                                log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
6✔
2056
                                return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
6✔
2057
                        }
2058
                }
2059

2060
                if (r == -EOPNOTSUPP) { /* Plugin not available, let's process TPM2 stuff right here instead */
1✔
2061
                        bool found_some = false;
1✔
2062
                        int token = 0; /* first token to look at */
1✔
2063

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

2068
                        for (;;) {
1✔
2069
                                _cleanup_(iovec_done) struct iovec pubkey = {}, salt = {}, srk = {}, pcrlock_nv = {};
×
2070
                                struct iovec *blobs = NULL, *policy_hash = NULL;
1✔
2071
                                uint32_t hash_pcr_mask, pubkey_pcr_mask;
1✔
2072
                                size_t n_blobs = 0, n_policy_hash = 0;
1✔
2073
                                uint16_t pcr_bank, primary_alg;
1✔
2074
                                TPM2Flags tpm2_flags;
1✔
2075

2076
                                CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
1✔
2077
                                CLEANUP_ARRAY(policy_hash, n_policy_hash, iovec_array_free);
1✔
2078

2079
                                r = find_tpm2_auto_data(
1✔
2080
                                                cd,
2081
                                                arg_tpm2_pcr_mask, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
2082
                                                token, /* search for the token with this index, or any later index than this */
2083
                                                &hash_pcr_mask,
2084
                                                &pcr_bank,
2085
                                                &pubkey,
2086
                                                &pubkey_pcr_mask,
2087
                                                &primary_alg,
2088
                                                &blobs,
2089
                                                &n_blobs,
2090
                                                &policy_hash,
2091
                                                &n_policy_hash,
2092
                                                &salt,
2093
                                                &srk,
2094
                                                &pcrlock_nv,
2095
                                                &tpm2_flags,
2096
                                                &keyslot,
2097
                                                &token);
2098
                                if (r == -ENXIO)
1✔
2099
                                        /* No further TPM2 tokens found in the LUKS2 header. */
2100
                                        return log_full_errno(found_some ? LOG_NOTICE : LOG_DEBUG,
×
2101
                                                              SYNTHETIC_ERRNO(EAGAIN),
2102
                                                              found_some
2103
                                                              ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
2104
                                                              : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
2105
                                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
1✔
2106
                                        /* TPM2 support not compiled in? */
2107
                                        return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
2108
                                                               "TPM2 support not available, falling back to traditional unlocking.");
2109
                                if (r < 0)
1✔
2110
                                        return r;
2111

2112
                                found_some = true;
1✔
2113

2114
                                r = acquire_tpm2_key(
1✔
2115
                                                name,
2116
                                                arg_tpm2_device,
2117
                                                hash_pcr_mask,
2118
                                                pcr_bank,
2119
                                                &pubkey,
2120
                                                pubkey_pcr_mask,
2121
                                                arg_tpm2_signature,
2122
                                                arg_tpm2_pcrlock,
2123
                                                primary_alg,
2124
                                                /* key_file= */ NULL, /* key_file_size= */ 0, /* key_file_offset= */ 0, /* no key file */
2125
                                                blobs,
2126
                                                n_blobs,
2127
                                                policy_hash,
2128
                                                n_policy_hash,
2129
                                                &salt,
2130
                                                &srk,
2131
                                                &pcrlock_nv,
2132
                                                tpm2_flags,
2133
                                                until,
2134
                                                "cryptsetup.tpm2-pin",
2135
                                                arg_ask_password_flags,
2136
                                                &decrypted_key);
2137
                                if (IN_SET(r, -EACCES, -ENOLCK))
1✔
2138
                                        return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
×
2139
                                if (r != -EPERM)
1✔
2140
                                        break;
2141

2142
                                token++; /* try a different token next time */
×
2143
                        }
2144

2145
                        if (r >= 0)
1✔
2146
                                break;
2147
                        /* EAGAIN means: no tpm2 chip found */
2148
                        if (r != -EAGAIN) {
×
2149
                                log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
×
2150
                                return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
×
2151
                        }
2152
                }
2153

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

2158
                        assert(!event);
×
2159

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

2164
                        r = make_tpm2_device_monitor(&event, &monitor);
×
2165
                        if (r < 0)
×
2166
                                return r;
2167

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

2170
                        /* Let's immediately rescan in case the device appeared in the time we needed
2171
                         * to create and configure the monitor */
2172
                        continue;
×
2173
                }
2174

2175
                r = run_security_device_monitor(event, monitor);
×
2176
                if (r < 0)
×
2177
                        return r;
2178

2179
                log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
×
2180
        }
2181

2182
        if (pass_volume_key)
1✔
2183
                r = measured_crypt_activate_by_volume_key(
×
2184
                                cd,
2185
                                name,
2186
                                "tpm2",
2187
                                /* keyslot= */ -1,
2188
                                decrypted_key.iov_base,
×
2189
                                decrypted_key.iov_len,
2190
                                flags);
2191
        else {
2192
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
1✔
2193
                ssize_t base64_encoded_size;
1✔
2194

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

2197
                base64_encoded_size = base64mem(decrypted_key.iov_base, decrypted_key.iov_len, &base64_encoded);
1✔
2198
                if (base64_encoded_size < 0)
1✔
2199
                        return log_oom();
×
2200

2201
                r = measured_crypt_activate_by_passphrase(
1✔
2202
                                cd,
2203
                                name,
2204
                                "tpm2",
2205
                                keyslot,
2206
                                base64_encoded,
2207
                                base64_encoded_size,
2208
                                flags);
2209
        }
2210
        if (r == -EPERM) {
1✔
2211
                log_error_errno(r, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
×
2212
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
2213
        }
2214
        if (r < 0)
1✔
2215
                return log_error_errno(r, "Failed to activate with TPM2 acquired key: %m");
×
2216

2217
        return 0;
2218
}
2219

2220
static int attach_luks_or_plain_or_bitlk_by_key_data(
3✔
2221
                struct crypt_device *cd,
2222
                const char *name,
2223
                const struct iovec *key_data,
2224
                uint32_t flags,
2225
                bool pass_volume_key) {
2226

2227
        int r;
3✔
2228

2229
        assert(cd);
3✔
2230
        assert(name);
3✔
2231
        assert(key_data);
3✔
2232

2233
        if (pass_volume_key)
3✔
2234
                r = measured_crypt_activate_by_volume_key(cd, name, /* mechanism= */ NULL, /* keyslot= */ -1, key_data->iov_base, key_data->iov_len, flags);
×
2235
        else
2236
                r = measured_crypt_activate_by_passphrase(cd, name, /* mechanism= */ NULL, arg_key_slot, key_data->iov_base, key_data->iov_len, flags);
3✔
2237
        if (r == -EPERM) {
3✔
2238
                log_error_errno(r, "Failed to activate. (Key incorrect?)");
×
2239
                return -EAGAIN; /* Log actual error, but return EAGAIN */
×
2240
        }
2241
        if (r < 0)
3✔
2242
                return log_error_errno(r, "Failed to activate: %m");
×
2243

2244
        return 0;
2245
}
2246

2247
static int attach_luks_or_plain_or_bitlk_by_key_file(
20✔
2248
                struct crypt_device *cd,
2249
                const char *name,
2250
                const char *key_file,
2251
                uint32_t flags,
2252
                bool pass_volume_key) {
2253

2254
        _cleanup_(erase_and_freep) char *kfdata = NULL;
20✔
2255
        _cleanup_free_ char *bindname = NULL;
20✔
2256
        size_t kfsize;
20✔
2257
        int r;
20✔
2258

2259
        assert(cd);
20✔
2260
        assert(name);
20✔
2261
        assert(key_file);
20✔
2262

2263
        /* If we read the key via AF_UNIX, make this client recognizable */
2264
        bindname = make_bindname(name, /* token_type= */ _TOKEN_TYPE_INVALID);
20✔
2265
        if (!bindname)
20✔
2266
                return log_oom();
×
2267

2268
        r = read_full_file_full(
23✔
2269
                        AT_FDCWD, key_file,
2270
                        arg_keyfile_offset == 0 ? UINT64_MAX : arg_keyfile_offset,
20✔
2271
                        arg_keyfile_size == 0 ? SIZE_MAX : arg_keyfile_size,
20✔
2272
                        READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
2273
                        bindname,
2274
                        &kfdata, &kfsize);
2275
        if (r == -E2BIG) {
20✔
2276
                log_error_errno(r, "Failed to activate, key file '%s' too large.", key_file);
×
2277
                return -EAGAIN;
×
2278
        }
2279
        if (r == -ENOENT) {
20✔
2280
                log_error_errno(r, "Failed to activate, key file '%s' missing.", key_file);
×
2281
                return -EAGAIN; /* Log actual error, but return EAGAIN */
×
2282
        }
2283
        if (r < 0)
20✔
2284
                return log_error_errno(r, "Failed to read key file '%s': %m", key_file);
×
2285

2286
        if (pass_volume_key)
20✔
2287
                r = measured_crypt_activate_by_volume_key(cd, name, /* mechanism= */ NULL, /* keyslot= */ -1, kfdata, kfsize, flags);
×
2288
        else
2289
                r = measured_crypt_activate_by_passphrase(cd, name, /* mechanism= */ NULL, arg_key_slot, kfdata, kfsize, flags);
20✔
2290
        if (r == -EPERM) {
20✔
2291
                log_error_errno(r, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file);
3✔
2292
                return -EAGAIN; /* Log actual error, but return EAGAIN */
3✔
2293
        }
2294
        if (r < 0)
17✔
2295
                return log_error_errno(r, "Failed to activate with key file '%s': %m", key_file);
×
2296

2297
        return 0;
2298
}
2299

2300
static int attach_luks_or_plain_or_bitlk_by_passphrase(
×
2301
                struct crypt_device *cd,
2302
                const char *name,
2303
                char **passwords,
2304
                uint32_t flags,
2305
                bool pass_volume_key) {
2306

2307
        int r;
×
2308

2309
        assert(cd);
×
2310
        assert(name);
×
2311

2312
        r = -EINVAL;
2313
        STRV_FOREACH(p, passwords) {
×
2314
                if (pass_volume_key)
×
2315
                        r = measured_crypt_activate_by_volume_key(cd, name, /* mechanism= */ NULL, /* keyslot= */ -1, *p, arg_key_size, flags);
×
2316
                else
2317
                        r = measured_crypt_activate_by_passphrase(cd, name, /* mechanism= */ NULL, arg_key_slot, *p, strlen(*p), flags);
×
2318
                if (r >= 0)
×
2319
                        break;
2320
        }
2321
        if (r == -EPERM) {
×
2322
                log_error_errno(r, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
×
2323
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
2324
        }
2325
        if (r < 0)
×
2326
                return log_error_errno(r, "Failed to activate with specified passphrase: %m");
×
2327

2328
        return 0;
2329
}
2330

2331
static int attach_luks_or_plain_or_bitlk(
33✔
2332
                struct crypt_device *cd,
2333
                const char *name,
2334
                TokenType token_type,
2335
                const char *key_file,
2336
                const struct iovec *key_data,
2337
                char **passwords,
2338
                uint32_t flags,
2339
                usec_t until) {
2340

2341
        bool pass_volume_key = false;
33✔
2342
        int r;
33✔
2343

2344
        assert(cd);
33✔
2345
        assert(name);
33✔
2346

2347
        if ((!arg_type && !crypt_get_type(cd)) || streq_ptr(arg_type, CRYPT_PLAIN)) {
33✔
2348
                struct crypt_params_plain params = {
×
2349
                        .offset = arg_offset,
2350
                        .skip = arg_skip,
2351
                        .sector_size = arg_sector_size,
2352
                };
2353
                const char *cipher, *cipher_mode;
×
2354
                _cleanup_free_ char *truncated_cipher = NULL;
×
2355

2356
                if (streq_ptr(arg_hash, "plain"))
×
2357
                        /* plain isn't a real hash type. it just means "use no hash" */
2358
                        params.hash = NULL;
2359
                else if (arg_hash)
×
2360
                        params.hash = arg_hash;
×
2361
                else if (!key_file)
×
2362
                        /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
2363
                         * file is provided */
2364
                        params.hash = "ripemd160";
×
2365

2366
                if (arg_cipher) {
×
2367
                        size_t l;
×
2368

2369
                        l = strcspn(arg_cipher, "-");
×
2370
                        truncated_cipher = strndup(arg_cipher, l);
×
2371
                        if (!truncated_cipher)
×
2372
                                return log_oom();
×
2373

2374
                        cipher = truncated_cipher;
×
2375
                        cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain";
×
2376
                } else {
2377
                        cipher = "aes";
2378
                        cipher_mode = "cbc-essiv:sha256";
2379
                }
2380

2381
                /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
2382
                arg_keyfile_size = arg_key_size;
×
2383

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

2390
                /* hash == NULL implies the user passed "plain" */
2391
                pass_volume_key = !params.hash;
×
2392
        }
2393

2394
        log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
33✔
2395
                 crypt_get_cipher(cd),
2396
                 crypt_get_cipher_mode(cd),
2397
                 crypt_get_volume_key_size(cd)*8,
2398
                 crypt_get_device_name(cd));
2399

2400
        if (token_type == TOKEN_TPM2)
33✔
2401
                return attach_luks_or_plain_or_bitlk_by_tpm2(cd, name, key_file, key_data, until, flags, pass_volume_key);
10✔
2402
        if (token_type == TOKEN_FIDO2)
23✔
2403
                return attach_luks_or_plain_or_bitlk_by_fido2(cd, name, key_file, key_data, until, flags, pass_volume_key);
×
2404
        if (token_type == TOKEN_PKCS11)
23✔
2405
                return attach_luks_or_plain_or_bitlk_by_pkcs11(cd, name, key_file, key_data, until, flags, pass_volume_key);
×
2406
        if (key_data)
23✔
2407
                return attach_luks_or_plain_or_bitlk_by_key_data(cd, name, key_data, flags, pass_volume_key);
3✔
2408
        if (key_file)
20✔
2409
                return attach_luks_or_plain_or_bitlk_by_key_file(cd, name, key_file, flags, pass_volume_key);
20✔
2410

2411
        return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
×
2412
}
2413

2414
static int help(void) {
×
2415
        _cleanup_free_ char *link = NULL;
×
2416
        int r;
×
2417

2418
        r = terminal_urlify_man("systemd-cryptsetup", "8", &link);
×
2419
        if (r < 0)
×
2420
                return log_oom();
×
2421

2422
        printf("%1$s attach VOLUME SOURCE-DEVICE [KEY-FILE] [CONFIG]\n"
×
2423
               "%1$s detach VOLUME\n\n"
2424
               "%2$sAttach or detach an encrypted block device.%3$s\n\n"
2425
               "  -h --help            Show this help\n"
2426
               "     --version         Show package version\n"
2427
               "\nSee the %4$s for details.\n",
2428
               program_invocation_short_name,
2429
               ansi_highlight(),
2430
               ansi_normal(),
2431
               link);
2432

2433
        return 0;
2434
}
2435

2436
static int parse_argv(int argc, char *argv[]) {
125✔
2437
        enum {
125✔
2438
                ARG_VERSION = 0x100,
2439
        };
2440

2441
        static const struct option options[] = {
125✔
2442
                { "help",                         no_argument,       NULL, 'h'                       },
2443
                { "version",                      no_argument,       NULL, ARG_VERSION               },
2444
                {}
2445
        };
2446

2447
        int c;
125✔
2448

2449
        assert(argc >= 0);
125✔
2450
        assert(argv);
125✔
2451

2452
        if (argv_looks_like_help(argc, argv))
125✔
2453
                return help();
×
2454

2455
        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
125✔
2456
                switch (c) {
×
2457

2458
                case 'h':
×
2459
                        return help();
×
2460

2461
                case ARG_VERSION:
×
2462
                        return version();
×
2463

2464
                case '?':
2465
                        return -EINVAL;
2466

2467
                default:
×
2468
                        assert_not_reached();
×
2469
                }
2470

2471
        return 1;
2472
}
2473

2474
static uint32_t determine_flags(void) {
70✔
2475
        uint32_t flags = 0;
70✔
2476

2477
        if (arg_readonly)
70✔
2478
                flags |= CRYPT_ACTIVATE_READONLY;
×
2479

2480
        if (arg_discards)
70✔
2481
                flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
×
2482

2483
        if (arg_same_cpu_crypt)
70✔
2484
                flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
×
2485

2486
        if (arg_submit_from_crypt_cpus)
70✔
2487
                flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
×
2488

2489
        if (arg_no_read_workqueue)
70✔
2490
                flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
×
2491

2492
        if (arg_no_write_workqueue)
70✔
2493
                flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
×
2494

2495
#ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
2496
        /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
2497
        /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
2498
        flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF;
70✔
2499
#endif
2500

2501
        return flags;
70✔
2502
}
2503

2504
static void remove_and_erasep(const char **p) {
70✔
2505
        int r;
70✔
2506

2507
        if (!*p)
70✔
2508
                return;
2509

2510
        r = unlinkat_deallocate(AT_FDCWD, *p, UNLINK_ERASE);
2✔
2511
        if (r < 0 && r != -ENOENT)
2✔
2512
                log_warning_errno(r, "Unable to erase key file '%s', ignoring: %m", *p);
×
2513
}
2514

2515
static TokenType determine_token_type(void) {
47✔
2516
        if (arg_tpm2_device || arg_tpm2_device_auto)
47✔
2517
                return TOKEN_TPM2;
2518
        if (arg_fido2_device || arg_fido2_device_auto)
37✔
2519
                return TOKEN_FIDO2;
2520
        if (arg_pkcs11_uri || arg_pkcs11_uri_auto)
37✔
2521
                return TOKEN_PKCS11;
×
2522

2523
        return _TOKEN_TYPE_INVALID;
2524
}
2525

2526
static int discover_key(const char *key_file, const char *volume, TokenType token_type, struct iovec *ret_key_data) {
24✔
2527
        _cleanup_free_ char *bindname = NULL;
24✔
2528
        const char *token_type_name;
24✔
2529
        int r;
24✔
2530

2531
        assert(key_file);
24✔
2532
        assert(volume);
24✔
2533
        assert(ret_key_data);
24✔
2534

2535
        bindname = make_bindname(volume, token_type);
24✔
2536
        if (!bindname)
24✔
2537
                return log_oom();
×
2538

2539
        /* If a key file is not explicitly specified, search for a key in a well defined search path, and load it. */
2540
        r = find_key_file(key_file, STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"), bindname, ret_key_data);
24✔
2541
        if (r <= 0)
24✔
2542
                return r;
2543

2544
        token_type_name = token_type_to_string(token_type);
1✔
2545
        if (token_type_name)
1✔
2546
                log_debug("Automatically discovered encrypted key for volume '%s' (token type: %s).", volume, token_type_name);
×
2547
        else
2548
                log_debug("Automatically discovered key for volume '%s'.", volume);
1✔
2549

2550
        return r;
2551
}
2552

2553
static int verb_attach(int argc, char *argv[], void *userdata) {
70✔
2554
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
70✔
2555
        _unused_ _cleanup_(remove_and_erasep) const char *destroy_key_file = NULL;
70✔
2556
        crypt_status_info status;
70✔
2557
        uint32_t flags = 0;
70✔
2558
        unsigned tries;
70✔
2559
        usec_t until;
70✔
2560
        PassphraseType passphrase_type = PASSPHRASE_NONE;
70✔
2561
        int r;
70✔
2562

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

2565
        assert(argc >= 3 && argc <= 5);
70✔
2566

2567
        const char *volume = ASSERT_PTR(argv[1]),
70✔
2568
                *source = ASSERT_PTR(argv[2]),
70✔
2569
                *key_file = argc >= 4 ? mangle_none(argv[3]) : NULL,
70✔
2570
                *config = argc >= 5 ? mangle_none(argv[4]) : NULL;
70✔
2571

2572
        if (!filename_is_valid(volume))
70✔
2573
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
×
2574

2575
        if (key_file && !path_is_absolute(key_file)) {
70✔
2576
                log_warning("Password file path '%s' is not absolute. Ignoring.", key_file);
×
2577
                key_file = NULL;
2578
        }
2579

2580
        if (config) {
70✔
2581
                r = parse_crypt_config(config);
70✔
2582
                if (r < 0)
70✔
2583
                        return r;
2584
        }
2585

2586
        log_debug("%s %s ← %s type=%s cipher=%s", __func__,
193✔
2587
                  volume, source, strempty(arg_type), strempty(arg_cipher));
2588

2589
        /* A delicious drop of snake oil */
2590
        (void) mlockall(MCL_FUTURE);
70✔
2591

2592
        if (key_file && arg_keyfile_erase)
70✔
2593
                destroy_key_file = key_file; /* let's get this baby erased when we leave */
2✔
2594

2595
        if (arg_header) {
70✔
2596
                if (streq_ptr(arg_type, CRYPT_TCRYPT)){
9✔
2597
                        log_debug("tcrypt header: %s", arg_header);
×
2598
                        r = crypt_init_data_device(&cd, arg_header, source);
×
2599
                } else {
2600
                        log_debug("LUKS header: %s", arg_header);
9✔
2601
                        r = crypt_init(&cd, arg_header);
9✔
2602
                }
2603
        } else
2604
                r = crypt_init(&cd, source);
61✔
2605
        if (r < 0)
70✔
2606
                return log_error_errno(r, "crypt_init() failed: %m");
×
2607

2608
        cryptsetup_enable_logging(cd);
70✔
2609

2610
        status = crypt_status(cd, volume);
70✔
2611
        if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) {
70✔
2612
                log_info("Volume %s already active.", volume);
×
2613
                return 0;
×
2614
        }
2615

2616
        flags = determine_flags();
70✔
2617

2618
        until = usec_add(now(CLOCK_MONOTONIC), arg_timeout);
70✔
2619
        if (until == USEC_INFINITY)
×
2620
                until = 0;
70✔
2621

2622
        if (arg_key_size == 0)
70✔
2623
                arg_key_size = 256U / 8U;
70✔
2624

2625
        if (key_file) {
70✔
2626
                struct stat st;
20✔
2627

2628
                /* Ideally we'd do this on the open fd, but since this is just a warning it's OK to do this
2629
                 * in two steps. */
2630
                if (stat(key_file, &st) >= 0 && S_ISREG(st.st_mode) && (st.st_mode & 0005))
20✔
UNCOV
2631
                        log_warning("Key file %s is world-readable. This is not a good idea!", key_file);
×
2632
        }
2633

2634
        if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2)) {
70✔
2635
                r = crypt_load(cd, !arg_type || streq(arg_type, ANY_LUKS) ? CRYPT_LUKS : arg_type, NULL);
70✔
2636
                if (r < 0)
70✔
2637
                        return log_error_errno(r, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd));
35✔
2638

2639
/* since cryptsetup 2.7.0 (Jan 2024) */
2640
#if HAVE_CRYPT_SET_KEYRING_TO_LINK
2641
                if (arg_link_key_description) {
70✔
2642
                        r = crypt_set_keyring_to_link(cd, arg_link_key_description, NULL, arg_link_key_type, arg_link_keyring);
×
2643
                        if (r < 0)
×
2644
                                log_warning_errno(r, "Failed to set keyring or key description to link volume key in, ignoring: %m");
×
2645
                }
2646
#endif
2647

2648
                if (arg_header) {
70✔
2649
                        r = crypt_set_data_device(cd, source);
9✔
2650
                        if (r < 0)
9✔
2651
                                return log_error_errno(r, "Failed to set LUKS data device %s: %m", source);
×
2652
                }
2653

2654
                /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
2655
                if (!key_file && use_token_plugins()) {
70✔
2656
                        r = crypt_activate_by_token_pin_ask_password(
49✔
2657
                                        cd,
2658
                                        volume,
2659
                                        /* type= */ NULL,
2660
                                        until,
2661
                                        /* userdata= */ NULL,
2662
                                        flags,
2663
                                        "Please enter LUKS2 token PIN:",
2664
                                        "luks2-pin",
2665
                                        "cryptsetup.luks2-pin");
2666
                        if (r >= 0) {
49✔
2667
                                log_debug("Volume %s activated with a LUKS token.", volume);
35✔
2668
                                return 0;
35✔
2669
                        }
2670

2671
                        log_debug_errno(r, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd));
14✔
2672
                }
2673
        }
2674

2675
/* since cryptsetup 2.3.0 (Feb 2020) */
2676
#ifdef CRYPT_BITLK
2677
        if (streq_ptr(arg_type, CRYPT_BITLK)) {
35✔
2678
                r = crypt_load(cd, CRYPT_BITLK, NULL);
×
2679
                if (r < 0)
×
2680
                        return log_error_errno(r, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd));
×
2681
        }
2682
#endif
2683

2684
        bool use_cached_passphrase = true, try_discover_key = !key_file;
35✔
2685
        const char *discovered_key_fn = strjoina(volume, ".key");
175✔
2686
        _cleanup_strv_free_erase_ char **passwords = NULL;
35✔
2687
        for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) {
47✔
2688
                _cleanup_(iovec_done_erase) struct iovec discovered_key_data = {};
47✔
2689
                const struct iovec *key_data = NULL;
47✔
2690
                TokenType token_type = determine_token_type();
47✔
2691

2692
                log_debug("Beginning attempt %u to unlock.", tries);
47✔
2693

2694
                /* When we were able to acquire multiple keys, let's always process them in this order:
2695
                 *
2696
                 *    1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
2697
                 *    2. The configured or discovered key, of which both are exclusive and optional
2698
                 *    3. The empty password, in case arg_try_empty_password is set
2699
                 *    4. We enquire the user for a password
2700
                 */
2701

2702
                if (try_discover_key) {
47✔
2703
                        r = discover_key(discovered_key_fn, volume, token_type, &discovered_key_data);
24✔
2704
                        if (r < 0)
24✔
2705
                                return r;
2706
                        if (r > 0)
24✔
2707
                                key_data = &discovered_key_data;
1✔
2708
                }
2709

2710
                if (token_type < 0 && !key_file && !key_data && !passwords) {
47✔
2711

2712
                        /* If we have nothing to try anymore, then acquire a new password */
2713

2714
                        if (arg_try_empty_password) {
16✔
2715
                                /* Hmm, let's try an empty password now, but only once */
2716
                                arg_try_empty_password = false;
2✔
2717
                                key_data = &iovec_empty;
2✔
2718
                        } else {
2719
                                /* Ask the user for a passphrase or recovery key only as last resort, if we
2720
                                 * have nothing else to check for */
2721
                                if (passphrase_type == PASSPHRASE_NONE) {
14✔
2722
                                        passphrase_type = check_registered_passwords(cd);
14✔
2723
                                        if (passphrase_type == PASSPHRASE_NONE)
14✔
2724
                                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No passphrase or recovery key registered.");
×
2725
                                }
2726

2727
                                r = get_password(
14✔
2728
                                                volume,
2729
                                                source,
2730
                                                until,
2731
                                                /* ignore_cached= */ !use_cached_passphrase || arg_verify,
14✔
2732
                                                passphrase_type,
2733
                                                &passwords);
2734
                                use_cached_passphrase = false;
14✔
2735
                                if (r == -EAGAIN)
14✔
2736
                                        continue;
×
2737
                                if (r < 0)
14✔
2738
                                        return r;
2739
                        }
2740
                }
2741

2742
                if (streq_ptr(arg_type, CRYPT_TCRYPT))
33✔
2743
                        r = attach_tcrypt(cd, volume, token_type, key_file, key_data, passwords, flags);
×
2744
                else
2745
                        r = attach_luks_or_plain_or_bitlk(cd, volume, token_type, key_file, key_data, passwords, flags, until);
33✔
2746
                if (r >= 0)
33✔
2747
                        break;
2748
                if (r != -EAGAIN)
12✔
2749
                        return r;
2750

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

2754
                if (token_type == TOKEN_TPM2) {
12✔
2755
                        arg_tpm2_device = mfree(arg_tpm2_device);
9✔
2756
                        arg_tpm2_device_auto = false;
9✔
2757
                        continue;
9✔
2758
                }
2759

2760
                if (token_type == TOKEN_FIDO2) {
3✔
2761
                        arg_fido2_device = mfree(arg_fido2_device);
×
2762
                        arg_fido2_device_auto = false;
×
2763
                        continue;
×
2764
                }
2765

2766
                if (token_type == TOKEN_PKCS11) {
3✔
2767
                        arg_pkcs11_uri = mfree(arg_pkcs11_uri);
×
2768
                        arg_pkcs11_uri_auto = false;
×
2769
                        continue;
×
2770
                }
2771

2772
                if (try_discover_key) {
3✔
2773
                        try_discover_key = false;
×
2774
                        continue;
×
2775
                }
2776

2777
                if (key_file) {
3✔
2778
                        key_file = NULL;
3✔
2779
                        continue;
3✔
2780
                }
2781

2782
                if (passwords) {
×
2783
                        passwords = strv_free_erase(passwords);
×
2784
                        continue;
×
2785
                }
2786

2787
                log_debug("Prepared for next attempt to unlock.");
×
2788
        }
2789

2790
        if (arg_tries != 0 && tries >= arg_tries)
21✔
2791
                return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to activate; giving up.");
×
2792

2793
        return 0;
2794
}
2795

2796
static int verb_detach(int argc, char *argv[], void *userdata) {
55✔
2797
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
55✔
2798
        const char *volume = ASSERT_PTR(argv[1]);
55✔
2799
        int r;
55✔
2800

2801
        assert(argc == 2);
55✔
2802

2803
        if (!filename_is_valid(volume))
55✔
2804
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
×
2805

2806
        r = crypt_init_by_name(&cd, volume);
55✔
2807
        if (r == -ENODEV) {
55✔
2808
                log_info("Volume %s already inactive.", volume);
×
2809
                return 0;
×
2810
        }
2811
        if (r < 0)
55✔
2812
                return log_error_errno(r, "crypt_init_by_name() for volume '%s' failed: %m", volume);
×
2813

2814
        cryptsetup_enable_logging(cd);
55✔
2815

2816
        r = crypt_deactivate(cd, volume);
55✔
2817
        if (r < 0)
55✔
2818
                return log_error_errno(r, "Failed to deactivate '%s': %m", volume);
×
2819

2820
        return 0;
2821
}
2822

2823
static int run(int argc, char *argv[]) {
125✔
2824
        int r;
125✔
2825

2826
        log_setup();
125✔
2827

2828
        umask(0022);
125✔
2829

2830
        r = parse_argv(argc, argv);
125✔
2831
        if (r <= 0)
125✔
2832
                return r;
2833

2834
        cryptsetup_enable_logging(NULL);
125✔
2835

2836
        static const Verb verbs[] = {
125✔
2837
                { "attach", 3, 5, 0, verb_attach },
2838
                { "detach", 2, 2, 0, verb_detach },
2839
                {}
2840
        };
2841

2842
        return dispatch_verb(argc, argv, verbs, NULL);
125✔
2843
}
2844

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

© 2026 Coveralls, Inc