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

systemd / systemd / 18146889369

30 Sep 2025 06:54PM UTC coverage: 72.162% (+0.1%) from 72.03%
18146889369

push

github

web-flow
units/systemd-battery-check.service: minor cleanup (#39178)

303053 of 419962 relevant lines covered (72.16%)

1082189.47 hits per line

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

40.62
/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 "fstab-util.h"
32
#include "hexdecoct.h"
33
#include "json-util.h"
34
#include "libfido2-util.h"
35
#include "libmount-util.h"
36
#include "log.h"
37
#include "main-func.h"
38
#include "memory-util.h"
39
#include "mount-util.h"
40
#include "nulstr-util.h"
41
#include "parse-util.h"
42
#include "path-util.h"
43
#include "pkcs11-util.h"
44
#include "pretty-print.h"
45
#include "random-util.h"
46
#include "string-table.h"
47
#include "string-util.h"
48
#include "strv.h"
49
#include "time-util.h"
50
#include "tpm2-pcr.h"
51
#include "tpm2-util.h"
52
#include "verbs.h"
53

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

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

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

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

130
STATIC_DESTRUCTOR_REGISTER(arg_cipher, freep);
125✔
131
STATIC_DESTRUCTOR_REGISTER(arg_hash, freep);
125✔
132
STATIC_DESTRUCTOR_REGISTER(arg_header, freep);
125✔
133
STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles, strv_freep);
125✔
134
STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri, freep);
125✔
135
STATIC_DESTRUCTOR_REGISTER(arg_fido2_device, freep);
125✔
136
STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid, freep);
125✔
137
STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id, freep);
125✔
138
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
125✔
139
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_signature, freep);
125✔
140
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_measure_banks, strv_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, "try-empty-password="))) {
64✔
559

560
                r = parse_boolean(val);
1✔
561
                if (r < 0) {
1✔
562
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
563
                        return 0;
×
564
                }
565

566
                arg_try_empty_password = r;
1✔
567

568
        } else if (streq(option, "try-empty-password"))
63✔
569
                arg_try_empty_password = true;
1✔
570
        else if ((val = startswith(option, "headless="))) {
62✔
571

572
                r = parse_boolean(val);
55✔
573
                if (r < 0) {
55✔
574
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
575
                        return 0;
×
576
                }
577

578
                SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_HEADLESS, r);
55✔
579
        } else if (streq(option, "headless"))
7✔
580
                arg_ask_password_flags |= ASK_PASSWORD_HEADLESS;
7✔
581

582
        else if ((val = startswith(option, "token-timeout="))) {
×
583

584
                r = parse_sec_fix_0(val, &arg_token_timeout_usec);
×
585
                if (r < 0)
×
586
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
115✔
587

588
        } else if ((val = startswith(option, "link-volume-key="))) {
×
589
#if HAVE_CRYPT_SET_KEYRING_TO_LINK
590
                _cleanup_free_ char *keyring = NULL, *key_type = NULL, *key_description = NULL;
×
591
                const char *sep;
×
592

593
                /* Stick with cryptsetup --link-vk-to-keyring format
594
                 * <keyring_description>::%<key_type>:<key_description>,
595
                 * where %<key_type> is optional and defaults to 'user'.
596
                 */
597
                sep = strstr(val, "::");
×
598
                if (!sep)
×
599
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse link-volume-key= option value: %s", val);
×
600

601
                /* cryptsetup (cli) supports <keyring_description> passed in various formats:
602
                 * - well-known keyrings prefixed with '@' (@u user, @s session, etc)
603
                 * - text descriptions prefixed with "%:" or "%keyring:".
604
                 * - text description with no prefix.
605
                 * - numeric keyring id (ignored in current patch set). */
606
                keyring = strndup(val, sep - val);
×
607
                if (!keyring)
×
608
                        return log_oom();
×
609

610
                /* add type prefix if missing (crypt_set_keyring_to_link() expects it) */
611
                if (!IN_SET(*keyring, '@', '%'))
×
612
                        if (!strprepend(&keyring, "%:"))
×
613
                                return log_oom();
×
614

615
                sep += 2;
×
616

617
                /* %<key_type> is optional (and defaults to 'user') */
618
                if (*sep == '%') {
×
619
                        /* must be separated by colon */
620
                        const char *c = strchr(sep, ':');
×
621
                        if (!c)
×
622
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse link-volume-key= option value: %s", val);
×
623

624
                        key_type = strndup(sep + 1, c - sep - 1);
×
625
                        if (!key_type)
×
626
                                return log_oom();
×
627

628
                        sep = c + 1;
×
629
                }
630

631
                key_description = strdup(sep);
×
632
                if (!key_description)
×
633
                        return log_oom();
×
634

635
                free_and_replace(arg_link_keyring, keyring);
×
636
                free_and_replace(arg_link_key_type, key_type);
×
637
                free_and_replace(arg_link_key_description, key_description);
×
638
#else
639
                log_error("Build lacks libcryptsetup support for linking volume keys in user specified kernel keyrings upon device activation, ignoring: %s", option);
640
#endif
641
        } else if (!streq(option, "x-initrd.attach"))
×
642
                log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
×
643

644
        return 0;
645
}
646

647
static int parse_crypt_config(const char *options) {
70✔
648
        assert(options);
70✔
649

650
        for (;;) {
360✔
651
                _cleanup_free_ char *word = NULL;
145✔
652
                int r;
215✔
653

654
                r = extract_first_word(&options, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS | EXTRACT_UNESCAPE_SEPARATORS);
215✔
655
                if (r < 0)
215✔
656
                        return log_error_errno(r, "Failed to parse options: %m");
×
657
                if (r == 0)
215✔
658
                        break;
659

660
                r = parse_one_option(word);
145✔
661
                if (r < 0)
145✔
662
                        return r;
663
        }
664

665
        /* sanity-check options */
666
        if (arg_type && !streq(arg_type, CRYPT_PLAIN)) {
70✔
667
                if (arg_offset != 0)
17✔
668
                      log_warning("offset= ignored with type %s", arg_type);
×
669
                if (arg_skip != 0)
17✔
670
                      log_warning("skip= ignored with type %s", arg_type);
×
671
        }
672

673
        if (arg_pkcs11_uri || arg_pkcs11_uri_auto) {
70✔
674
                /* If password-cache was not configured explicitly, default to no cache for PKCS#11 */
675
                if (!arg_password_cache_set)
6✔
676
                        arg_ask_password_flags &= ~(ASK_PASSWORD_ACCEPT_CACHED|ASK_PASSWORD_PUSH_CACHE);
6✔
677

678
                /* This prevents future backward-compatibility issues if we decide to allow caching for PKCS#11 */
679
                if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_ACCEPT_CACHED))
6✔
680
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
681
                                               "Password cache is not supported for PKCS#11 security tokens.");
682
        }
683

684
        return 0;
685
}
686

687
static char* disk_description(const char *path) {
10✔
688
        static const char name_fields[] =
10✔
689
                "DM_NAME\0"
690
                "ID_MODEL_FROM_DATABASE\0"
691
                "ID_MODEL\0";
692

693
        _cleanup_(sd_device_unrefp) sd_device *device = NULL;
10✔
694
        const char *name;
10✔
695
        struct stat st;
10✔
696

697
        assert(path);
10✔
698

699
        if (stat(path, &st) < 0)
10✔
700
                return NULL;
701

702
        if (!S_ISBLK(st.st_mode))
10✔
703
                return NULL;
704

705
        if (sd_device_new_from_stat_rdev(&device, &st) < 0)
×
706
                return NULL;
707

708
        if (sd_device_get_property_value(device, "ID_PART_ENTRY_NAME", &name) >= 0) {
×
709
                _cleanup_free_ char *unescaped = NULL;
×
710
                ssize_t l;
×
711

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

716
                l = cunescape(name, UNESCAPE_RELAX, &unescaped);
×
717
                if (l < 0) {
×
718
                        log_debug_errno(l, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
×
719
                        return NULL;
×
720
                }
721

722
                if (!isempty(unescaped) && !string_has_cc(unescaped, NULL))
×
723
                        return TAKE_PTR(unescaped);
×
724
        }
725

726
        /* These need no unescaping. */
727
        NULSTR_FOREACH(i, name_fields)
×
728
                if (sd_device_get_property_value(device, i, &name) >= 0 &&
×
729
                    !isempty(name))
×
730
                        return strdup(name);
×
731

732
        return NULL;
733
}
734

735
static char* disk_mount_point(const char *label) {
10✔
736
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
10✔
737
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
×
738
        _cleanup_free_ char *device = NULL;
10✔
739
        int r;
10✔
740

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

743
        assert(label);
10✔
744

745
        device = strjoin("/dev/mapper/", label);
10✔
746
        if (!device)
10✔
747
                return NULL;
748

749
        r = libmount_parse_fstab(&table, &iter);
10✔
750
        if (r < 0)
10✔
751
                return NULL;
752

753
        for (;;) {
×
754
                struct libmnt_fs *fs;
10✔
755

756
                r = sym_mnt_table_next_fs(table, iter, &fs);
10✔
757
                if (r != 0)
10✔
758
                        return NULL;
10✔
759

760
                if (path_equal(sym_mnt_fs_get_source(fs), device)) {
×
761
                        const char *target = sym_mnt_fs_get_target(fs);
×
762
                        if (target)
×
763
                                return strdup(target);
×
764
                }
765
        }
766
}
767

768
static char *friendly_disk_name(const char *src, const char *vol) {
10✔
769
        _cleanup_free_ char *description = NULL, *mount_point = NULL;
10✔
770
        char *name_buffer = NULL;
10✔
771
        int r;
10✔
772

773
        assert(src);
10✔
774
        assert(vol);
10✔
775

776
        description = disk_description(src);
10✔
777
        mount_point = disk_mount_point(vol);
10✔
778

779
        /* If the description string is simply the volume name, then let's not show this twice */
780
        if (description && streq(vol, description))
10✔
781
                description = mfree(description);
×
782

783
        if (mount_point && description)
10✔
784
                r = asprintf(&name_buffer, "%s (%s) on %s", description, vol, mount_point);
×
785
        else if (mount_point)
×
786
                r = asprintf(&name_buffer, "%s on %s", vol, mount_point);
×
787
        else if (description)
10✔
788
                r = asprintf(&name_buffer, "%s (%s)", description, vol);
×
789
        else
790
                return strdup(vol);
10✔
791
        if (r < 0)
×
792
                return NULL;
793

794
        return name_buffer;
×
795
}
796

797
static PassphraseType check_registered_passwords(struct crypt_device *cd) {
14✔
798
        _cleanup_free_ bool *slots = NULL;
14✔
799
        int slot_max;
14✔
800
        PassphraseType passphrase_type = PASSPHRASE_NONE;
14✔
801

802
        assert(cd);
14✔
803

804
        if (!streq_ptr(crypt_get_type(cd), CRYPT_LUKS2)) {
14✔
805
                log_debug("%s: not a LUKS2 device, only passphrases are supported", crypt_get_device_name(cd));
×
806
                return PASSPHRASE_REGULAR;
×
807
        }
808

809
        /* Search all used slots */
810
        assert_se((slot_max = crypt_keyslot_max(CRYPT_LUKS2)) > 0);
14✔
811
        slots = new(bool, slot_max);
14✔
812
        if (!slots)
14✔
813
                return log_oom();
×
814

815
        for (int slot = 0; slot < slot_max; slot++)
462✔
816
                slots[slot] = IN_SET(crypt_keyslot_status(cd, slot), CRYPT_SLOT_ACTIVE, CRYPT_SLOT_ACTIVE_LAST);
448✔
817

818
        /* Iterate all LUKS2 tokens and keep track of all their slots */
819
        for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
462✔
820
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
448✔
821
                const char *type;
448✔
822
                sd_json_variant *w, *z;
448✔
823
                int tk;
448✔
824

825
                tk = cryptsetup_get_token_as_json(cd, token, NULL, &v);
448✔
826
                if (IN_SET(tk, -ENOENT, -EINVAL))
448✔
827
                        continue;
439✔
828
                if (tk < 0) {
9✔
829
                        log_warning_errno(tk, "Failed to read JSON token data, ignoring: %m");
×
830
                        continue;
×
831
                }
832

833
                w = sd_json_variant_by_key(v, "type");
9✔
834
                if (!w || !sd_json_variant_is_string(w)) {
9✔
835
                        log_warning("Token JSON data lacks type field, ignoring.");
×
836
                        continue;
×
837
                }
838

839
                type = sd_json_variant_string(w);
9✔
840
                if (STR_IN_SET(type, "systemd-recovery", "systemd-pkcs11", "systemd-fido2", "systemd-tpm2")) {
9✔
841

842
                        /* At least exists one recovery key */
843
                        if (streq(type, "systemd-recovery"))
9✔
844
                                passphrase_type |= PASSPHRASE_RECOVERY_KEY;
×
845

846
                        w = sd_json_variant_by_key(v, "keyslots");
9✔
847
                        if (!w || !sd_json_variant_is_array(w)) {
9✔
848
                                log_warning("Token JSON data lacks keyslots field, ignoring.");
×
849
                                continue;
×
850
                        }
851

852
                        JSON_VARIANT_ARRAY_FOREACH(z, w) {
18✔
853
                                unsigned u;
9✔
854
                                int at;
9✔
855

856
                                if (!sd_json_variant_is_string(z)) {
9✔
857
                                        log_warning("Token JSON data's keyslot field is not an array of strings, ignoring.");
×
858
                                        continue;
×
859
                                }
860

861
                                at = safe_atou(sd_json_variant_string(z), &u);
9✔
862
                                if (at < 0) {
9✔
863
                                        log_warning_errno(at, "Token JSON data's keyslot field is not an integer formatted as string, ignoring.");
×
864
                                        continue;
×
865
                                }
866

867
                                if (u >= (unsigned) slot_max) {
9✔
868
                                        log_warning_errno(at, "Token JSON data's keyslot field exceeds the maximum value allowed, ignoring.");
×
869
                                        continue;
×
870
                                }
871

872
                                slots[u] = false;
9✔
873
                        }
874
                }
875
        }
876

877
        /* Check if any of the slots is not referenced by systemd tokens */
878
        for (int slot = 0; slot < slot_max; slot++)
14✔
879
                if (slots[slot]) {
14✔
880
                        passphrase_type |= PASSPHRASE_REGULAR;
14✔
881
                        break;
14✔
882
                }
883

884
        /* All the slots are referenced by systemd tokens, so if a recovery key is not enrolled,
885
         * we will not be able to enter a passphrase. */
886
        return passphrase_type;
887
}
888

889
static int get_password(
14✔
890
                const char *vol,
891
                const char *src,
892
                usec_t until,
893
                bool ignore_cached,
894
                PassphraseType passphrase_type,
895
                char ***ret) {
896

897
        _cleanup_free_ char *friendly = NULL, *text = NULL, *disk_path = NULL, *id = NULL;
14✔
898
        _cleanup_strv_free_erase_ char **passwords = NULL;
×
899
        AskPasswordFlags flags = arg_ask_password_flags;
14✔
900
        int r;
14✔
901

902
        assert(vol);
14✔
903
        assert(src);
14✔
904
        assert(ret);
14✔
905

906
        if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_HEADLESS))
14✔
907
                return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Password querying disabled via 'headless' option.");
14✔
908

909
        friendly = friendly_disk_name(src, vol);
×
910
        if (!friendly)
×
911
                return log_oom();
×
912

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

916
        disk_path = cescape(src);
×
917
        if (!disk_path)
×
918
                return log_oom();
×
919

920
        id = strjoin("cryptsetup:", disk_path);
×
921
        if (!id)
×
922
                return log_oom();
×
923

924
        AskPasswordRequest req = {
×
925
                .tty_fd = -EBADF,
926
                .message = text,
927
                .icon = "drive-harddisk",
928
                .id = id,
929
                .keyring = "cryptsetup",
930
                .credential = "cryptsetup.passphrase",
931
                .until = until,
932
                .hup_fd = -EBADF,
933
        };
934

935
        if (ignore_cached)
×
936
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
×
937

938
        r = ask_password_auto(&req, flags, &passwords);
×
939
        if (r < 0)
×
940
                return log_error_errno(r, "Failed to query password: %m");
×
941

942
        if (arg_verify) {
×
943
                _cleanup_strv_free_erase_ char **passwords2 = NULL;
×
944

945
                assert(strv_length(passwords) == 1);
×
946

947
                text = mfree(text);
×
948
                if (asprintf(&text, "Please enter %s for disk %s (verification):", passphrase_type_to_string(passphrase_type), friendly) < 0)
×
949
                        return log_oom();
×
950

951
                free(id);
×
952
                id = strjoin("cryptsetup-verification:", disk_path);
×
953
                if (!id)
×
954
                        return log_oom();
×
955

956
                req.message = text;
×
957
                req.id = id;
×
958

959
                r = ask_password_auto(&req, flags, &passwords2);
×
960
                if (r < 0)
×
961
                        return log_error_errno(r, "Failed to query verification password: %m");
×
962

963
                assert(strv_length(passwords2) == 1);
×
964

965
                if (!streq(passwords[0], passwords2[0]))
×
966
                        return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN),
×
967
                                                 "Passwords did not match, retrying.");
968
        }
969

970
        strv_uniq(passwords);
×
971

972
        STRV_FOREACH(p, passwords) {
×
973
                char *c;
×
974

975
                if (strlen(*p)+1 >= arg_key_size)
×
976
                        continue;
×
977

978
                /* Pad password if necessary */
979
                c = new(char, arg_key_size);
×
980
                if (!c)
×
981
                        return log_oom();
14✔
982

983
                strncpy(c, *p, arg_key_size);
×
984
                erase_and_free(*p);
×
985
                *p = TAKE_PTR(c);
×
986
        }
987

988
        *ret = TAKE_PTR(passwords);
×
989

990
        return 0;
×
991
}
992

993
static int measure_volume_key(
×
994
                struct crypt_device *cd,
995
                const char *name,
996
                const void *volume_key,
997
                size_t volume_key_size) {
998

999
        int r;
×
1000

1001
        assert(cd);
×
1002
        assert(name);
×
1003
        assert(volume_key);
×
1004
        assert(volume_key_size > 0);
×
1005

1006
        if (arg_tpm2_measure_pcr == UINT_MAX) {
×
1007
                log_debug("Not measuring volume key, deactivated.");
×
1008
                return 0;
×
1009
        }
1010

1011
        r = efi_measured_uki(LOG_WARNING);
×
1012
        if (r < 0)
×
1013
                return r;
1014
        if (r == 0) {
×
1015
                log_debug("Kernel stub did not measure kernel image into the expected PCR, skipping userspace measurement, too.");
×
1016
                return 0;
×
1017
        }
1018

1019
#if HAVE_TPM2
1020
        _cleanup_(tpm2_context_unrefp) Tpm2Context *c = NULL;
×
1021
        r = tpm2_context_new_or_warn(arg_tpm2_device, &c);
×
1022
        if (r < 0)
×
1023
                return r;
1024

1025
        _cleanup_strv_free_ char **l = NULL;
×
1026
        if (strv_isempty(arg_tpm2_measure_banks)) {
×
1027
                r = tpm2_get_good_pcr_banks_strv(c, UINT32_C(1) << arg_tpm2_measure_pcr, &l);
×
1028
                if (r < 0)
×
1029
                        return log_error_errno(r, "Could not verify pcr banks: %m");
×
1030
        }
1031

1032
        _cleanup_free_ char *joined = strv_join(l ?: arg_tpm2_measure_banks, ", ");
×
1033
        if (!joined)
×
1034
                return log_oom();
×
1035

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

1040
        _cleanup_free_ char *escaped = NULL;
×
1041
        escaped = xescape(name, ":"); /* avoid ambiguity around ":" once we join things below */
×
1042
        if (!escaped)
×
1043
                return log_oom();
×
1044

1045
        _cleanup_free_ char *s = NULL;
×
1046
        s = strjoin("cryptsetup:", escaped, ":", strempty(crypt_get_uuid(cd)));
×
1047
        if (!s)
×
1048
                return log_oom();
×
1049

1050
        r = tpm2_extend_bytes(c, l ?: arg_tpm2_measure_banks, arg_tpm2_measure_pcr, s, SIZE_MAX, volume_key, volume_key_size, TPM2_EVENT_VOLUME_KEY, s);
×
1051
        if (r < 0)
×
1052
                return log_error_errno(r, "Could not extend PCR: %m");
×
1053

1054
        log_struct(LOG_INFO,
×
1055
                   LOG_MESSAGE_ID(SD_MESSAGE_TPM_PCR_EXTEND_STR),
1056
                   LOG_MESSAGE("Successfully extended PCR index %u with '%s' and volume key (banks %s).", arg_tpm2_measure_pcr, s, joined),
1057
                   LOG_ITEM("MEASURING=%s", s),
1058
                   LOG_ITEM("PCR=%u", arg_tpm2_measure_pcr),
1059
                   LOG_ITEM("BANKS=%s", joined));
1060

1061
        return 0;
1062
#else
1063
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support disabled, not measuring.");
1064
#endif
1065
}
1066

1067
static int log_external_activation(int r, const char *volume) {
×
1068
        assert(volume);
×
1069

1070
        log_notice_errno(r, "Volume '%s' has been activated externally while we have been trying to activate it.", volume);
×
1071
        return 0;
×
1072
}
1073

1074
static int measured_crypt_activate_by_volume_key(
×
1075
                struct crypt_device *cd,
1076
                const char *name,
1077
                const void *volume_key,
1078
                size_t volume_key_size,
1079
                uint32_t flags) {
1080

1081
        int r;
×
1082

1083
        assert(cd);
×
1084
        assert(name);
×
1085

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

1088
        r = crypt_activate_by_volume_key(cd, name, volume_key, volume_key_size, flags);
×
1089
        if (r == -EEXIST) /* volume is already active */
×
1090
                return log_external_activation(r, name);
×
1091
        if (r < 0)
×
1092
                return r;
1093

1094
        if (volume_key_size == 0) {
×
1095
                log_debug("Not measuring volume key, none specified.");
×
1096
                return r;
×
1097
        }
1098

1099
        (void) measure_volume_key(cd, name, volume_key, volume_key_size); /* OK if fails */
×
1100
        return r;
×
1101
}
1102

1103
static int measured_crypt_activate_by_passphrase(
24✔
1104
                struct crypt_device *cd,
1105
                const char *name,
1106
                int keyslot,
1107
                const char *passphrase,
1108
                size_t passphrase_size,
1109
                uint32_t flags) {
1110

1111
        _cleanup_(erase_and_freep) void *vk = NULL;
24✔
1112
        size_t vks;
24✔
1113
        int r;
24✔
1114

1115
        assert(cd);
24✔
1116

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

1122
        if (arg_tpm2_measure_pcr == UINT_MAX) {
24✔
1123
                log_debug("Not measuring volume key, deactivated.");
24✔
1124
                goto shortcut;
24✔
1125
        }
1126

1127
        r = crypt_get_volume_key_size(cd);
×
1128
        if (r < 0)
×
1129
                return r;
1130
        if (r == 0) {
×
1131
                log_debug("Not measuring volume key, none defined.");
×
1132
                goto shortcut;
×
1133
        }
1134

1135
        vk = malloc(vks = r);
×
1136
        if (!vk)
×
1137
                return -ENOMEM;
1138

1139
        r = crypt_volume_key_get(cd, keyslot, vk, &vks, passphrase, passphrase_size);
×
1140
        if (r < 0)
×
1141
                return r;
1142

1143
        return measured_crypt_activate_by_volume_key(cd, name, vk, vks, flags);
×
1144

1145
shortcut:
24✔
1146
        r = crypt_activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags);
24✔
1147
        if (r == -EEXIST) /* volume is already active */
24✔
1148
                return log_external_activation(r, name);
×
1149
        return r;
1150
}
1151

1152
static int attach_tcrypt(
×
1153
                struct crypt_device *cd,
1154
                const char *name,
1155
                TokenType token_type,
1156
                const char *key_file,
1157
                const struct iovec *key_data,
1158
                char **passwords,
1159
                uint32_t flags) {
1160

1161
        int r = 0;
×
1162
        _cleanup_(erase_and_freep) char *passphrase = NULL;
×
1163
        struct crypt_params_tcrypt params = {
×
1164
                .flags = CRYPT_TCRYPT_LEGACY_MODES,
1165
                .keyfiles = (const char **)arg_tcrypt_keyfiles,
1166
                .keyfiles_count = strv_length(arg_tcrypt_keyfiles)
×
1167
        };
1168

1169
        assert(cd);
×
1170
        assert(name);
×
1171
        assert(key_file || key_data || !strv_isempty(passwords));
×
1172

1173
        if (token_type >= 0)
×
1174
                /* Ask for a regular password */
1175
                return log_error_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1176
                                       "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
1177

1178
        if (arg_tcrypt_hidden)
×
1179
                params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
×
1180

1181
        if (arg_tcrypt_system)
×
1182
                params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
×
1183

1184
        if (arg_tcrypt_veracrypt)
×
1185
                params.flags |= CRYPT_TCRYPT_VERA_MODES;
×
1186

1187
        if (arg_tcrypt_veracrypt && arg_tcrypt_veracrypt_pim != 0)
×
1188
                params.veracrypt_pim = arg_tcrypt_veracrypt_pim;
×
1189

1190
        if (key_data) {
×
1191
                params.passphrase = key_data->iov_base;
×
1192
                params.passphrase_size = key_data->iov_len;
×
1193
                r = crypt_load(cd, CRYPT_TCRYPT, &params);
×
1194
        } else if (key_file) {
×
1195
                r = read_one_line_file(key_file, &passphrase);
×
1196
                if (r < 0) {
×
1197
                        log_error_errno(r, "Failed to read password file '%s': %m", key_file);
×
1198
                        return -EAGAIN; /* log with the actual error, but return EAGAIN */
×
1199
                }
1200
                params.passphrase = passphrase;
×
1201
                params.passphrase_size = strlen(passphrase);
×
1202
                r = crypt_load(cd, CRYPT_TCRYPT, &params);
×
1203
        } else {
1204
                r = -EINVAL;
1205
                STRV_FOREACH(p, passwords){
×
1206
                        params.passphrase = *p;
×
1207
                        params.passphrase_size = strlen(*p);
×
1208
                        r = crypt_load(cd, CRYPT_TCRYPT, &params);
×
1209
                        if (r >= 0)
×
1210
                                break;
1211
                }
1212
        }
1213

1214
        if (r < 0) {
×
1215
                if (r == -EPERM) {
×
1216
                        if (key_data)
×
1217
                                log_error_errno(r, "Failed to activate using discovered key. (Key not correct?)");
×
1218
                        else if (key_file)
×
1219
                                log_error_errno(r, "Failed to activate using password file '%s'. (Key data not correct?)", key_file);
×
1220
                        else
1221
                                log_error_errno(r, "Failed to activate using supplied passwords.");
×
1222

1223
                        return r;
×
1224
                }
1225

1226
                return log_error_errno(r, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd));
×
1227
        }
1228

1229
        r = measured_crypt_activate_by_volume_key(cd, name, NULL, 0, flags);
×
1230
        if (r < 0)
×
1231
                return log_error_errno(r, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd));
×
1232

1233
        return 0;
1234
}
1235

1236
static char *make_bindname(const char *volume, TokenType token_type) {
44✔
1237
        const char *token_type_name = token_type_to_string(token_type), *suffix;
44✔
1238
        char *bindname;
44✔
1239
        int r;
44✔
1240

1241
        switch (token_type) {
44✔
1242

1243
        case TOKEN_FIDO2:
1244
                suffix = "-salt";
1245
                break;
1246

1247
        default:
1248
                suffix = NULL;
44✔
1249
        }
1250

1251
        r = asprintf(&bindname,
44✔
1252
                     "@%" PRIx64"/cryptsetup%s%s%s/%s",
1253
                     random_u64(),
1254
                     token_type_name ? "-" : "",
1255
                     strempty(token_type_name),
1256
                     strempty(suffix),
1257
                     volume);
1258
        if (r < 0)
44✔
1259
                return NULL;
44✔
1260

1261
        return bindname;
44✔
1262
}
1263

1264
static int make_security_device_monitor(
×
1265
                sd_event **ret_event,
1266
                sd_device_monitor **ret_monitor) {
1267
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1268
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1269
        int r;
×
1270

1271
        assert(ret_event);
×
1272
        assert(ret_monitor);
×
1273

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

1278
        r = sd_event_default(&event);
×
1279
        if (r < 0)
×
1280
                return log_error_errno(r, "Failed to allocate event loop: %m");
×
1281

1282
        r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
×
1283
        if (r < 0)
×
1284
                return log_error_errno(r, "Failed to install timeout event source: %m");
×
1285

1286
        r = sd_device_monitor_new(&monitor);
×
1287
        if (r < 0)
×
1288
                return log_error_errno(r, "Failed to allocate device monitor: %m");
×
1289

1290
        (void) sd_device_monitor_set_description(monitor, "security-device");
×
1291

1292
        r = sd_device_monitor_filter_add_match_tag(monitor, "security-device");
×
1293
        if (r < 0)
×
1294
                return log_error_errno(r, "Failed to configure device monitor: %m");
×
1295

1296
        r = sd_device_monitor_attach_event(monitor, event);
×
1297
        if (r < 0)
×
1298
                return log_error_errno(r, "Failed to attach device monitor: %m");
×
1299

1300
        r = sd_device_monitor_start(monitor, NULL, NULL);
×
1301
        if (r < 0)
×
1302
                return log_error_errno(r, "Failed to start device monitor: %m");
×
1303

1304
        *ret_event = TAKE_PTR(event);
×
1305
        *ret_monitor = TAKE_PTR(monitor);
×
1306
        return 0;
×
1307
}
1308

1309
static int run_security_device_monitor(
×
1310
                sd_event *event,
1311
                sd_device_monitor *monitor) {
1312
        bool processed = false;
×
1313
        int r;
×
1314

1315
        assert(event);
×
1316
        assert(monitor);
×
1317

1318
        /* Runs the event loop for the device monitor until either something happens, or the timeout is
1319
         * hit. */
1320

1321
        for (;;) {
×
1322
                int x;
×
1323

1324
                r = sd_event_get_exit_code(event, &x);
×
1325
                if (r < 0) {
×
1326
                        if (r != -ENODATA)
×
1327
                                return log_error_errno(r, "Failed to query exit code from event loop: %m");
×
1328

1329
                        /* On ENODATA we aren't told to exit yet. */
1330
                } else {
1331
                        assert(x == -ETIMEDOUT);
×
1332
                        return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1333
                                                "Timed out waiting for security device, aborting security device based authentication attempt.");
1334
                }
1335

1336
                /* Wait for one event, and then eat all subsequent events until there are no further ones */
1337
                r = sd_event_run(event, processed ? 0 : UINT64_MAX);
×
1338
                if (r < 0)
×
1339
                        return log_error_errno(r, "Failed to run event loop: %m");
×
1340
                if (r == 0) /* no events queued anymore */
×
1341
                        return 0;
1342

1343
                processed = true;
×
1344
        }
1345
}
1346

1347
static bool use_token_plugins(void) {
60✔
1348

1349
#if HAVE_TPM2
1350
        /* Currently, there's no way for us to query the volume key when plugins are used. Hence don't use
1351
         * plugins, if measurement has been requested. */
1352
        if (arg_tpm2_measure_pcr != UINT_MAX)
60✔
1353
                return false;
1354
#endif
1355

1356
        /* Disable tokens if we're in FIDO2 mode with manual parameters. */
1357
        if (arg_fido2_cid)
60✔
1358
                return false;
1359

1360
#if HAVE_LIBCRYPTSETUP_PLUGINS
1361
        int r;
60✔
1362

1363
        /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
1364
        r = getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
60✔
1365
        if (r < 0 && r != -ENXIO)
60✔
1366
                log_debug_errno(r, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
×
1367
        if (r == 0)
60✔
1368
                return false;
1369

1370
        return crypt_token_external_path();
58✔
1371
#else
1372
        return false;
1373
#endif
1374
}
1375

1376
#if HAVE_LIBCRYPTSETUP_PLUGINS
1377
static int acquire_pins_from_env_variable(char ***ret_pins) {
21✔
1378
        _cleanup_(erase_and_freep) char *envpin = NULL;
21✔
1379
        _cleanup_strv_free_erase_ char **pins = NULL;
21✔
1380
        int r;
21✔
1381

1382
        assert(ret_pins);
21✔
1383

1384
        r = getenv_steal_erase("PIN", &envpin);
21✔
1385
        if (r < 0)
21✔
1386
                return log_error_errno(r, "Failed to acquire PIN from environment: %m");
×
1387
        if (r > 0) {
21✔
1388
                pins = strv_new(envpin);
16✔
1389
                if (!pins)
16✔
1390
                        return log_oom();
×
1391
        }
1392

1393
        *ret_pins = TAKE_PTR(pins);
21✔
1394

1395
        return 0;
21✔
1396
}
1397
#endif
1398

1399
static int crypt_activate_by_token_pin_ask_password(
58✔
1400
                struct crypt_device *cd,
1401
                const char *name,
1402
                const char *type,
1403
                usec_t until,
1404
                void *userdata,
1405
                uint32_t activation_flags,
1406
                const char *message,
1407
                const char *keyring,
1408
                const char *credential) {
1409

1410
#if HAVE_LIBCRYPTSETUP_PLUGINS
1411
        AskPasswordFlags flags = arg_ask_password_flags;
58✔
1412
        _cleanup_strv_free_erase_ char **pins = NULL;
58✔
1413
        int r;
58✔
1414

1415
        r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, /* pin=*/ NULL, /* pin_size= */ 0, userdata, activation_flags);
58✔
1416
        if (r > 0) /* returns unlocked keyslot id on success */
58✔
1417
                return 0;
1418
        if (r == -EEXIST) /* volume is already active */
35✔
1419
                return log_external_activation(r, name);
×
1420
        if (r != -ENOANO) /* needs pin or pin is wrong */
35✔
1421
                return r;
1422

1423
        r = acquire_pins_from_env_variable(&pins);
21✔
1424
        if (r < 0)
21✔
1425
                return r;
1426

1427
        STRV_FOREACH(p, pins) {
25✔
1428
                r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
16✔
1429
                if (r > 0) /* returns unlocked keyslot id on success */
16✔
1430
                        return 0;
1431
                if (r == -EEXIST) /* volume is already active */
5✔
1432
                        return log_external_activation(r, name);
×
1433
                if (r != -ENOANO) /* needs pin or pin is wrong */
5✔
1434
                        return r;
1435
        }
1436

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

1440
        for (;;) {
×
1441
                pins = strv_free_erase(pins);
×
1442

1443
                AskPasswordRequest req = {
×
1444
                        .tty_fd = -EBADF,
1445
                        .message = message,
1446
                        .icon = "drive-harddisk",
1447
                        .keyring = keyring,
1448
                        .credential = credential,
1449
                        .until = until,
1450
                        .hup_fd = -EBADF,
1451
                };
1452

1453
                r = ask_password_auto(&req, flags, &pins);
×
1454
                if (r < 0)
×
1455
                        return r;
×
1456

1457
                STRV_FOREACH(p, pins) {
×
1458
                        r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
×
1459
                        if (r > 0) /* returns unlocked keyslot id on success */
×
1460
                                return 0;
1461
                        if (r == -EEXIST) /* volume is already active */
×
1462
                                return log_external_activation(r, name);
×
1463
                        if (r != -ENOANO) /* needs pin or pin is wrong */
×
1464
                                return r;
1465
                }
1466

1467
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
×
1468
        }
1469
        return r;
1470
#else
1471
        return -EOPNOTSUPP;
1472
#endif
1473
}
1474

1475
static int attach_luks2_by_fido2_via_plugin(
×
1476
                struct crypt_device *cd,
1477
                const char *name,
1478
                usec_t until,
1479
                void *userdata,
1480
                uint32_t activation_flags) {
1481

1482
        return crypt_activate_by_token_pin_ask_password(
×
1483
                        cd,
1484
                        name,
1485
                        "systemd-fido2",
1486
                        until,
1487
                        userdata,
1488
                        activation_flags,
1489
                        "Please enter security token PIN:",
1490
                        "fido2-pin",
1491
                        "cryptsetup.fido2-pin");
1492
}
1493

1494
static int attach_luks_or_plain_or_bitlk_by_fido2(
×
1495
                struct crypt_device *cd,
1496
                const char *name,
1497
                const char *key_file,
1498
                const struct iovec *key_data,
1499
                usec_t until,
1500
                uint32_t flags,
1501
                bool pass_volume_key) {
1502

1503
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1504
        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
×
1505
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1506
        size_t decrypted_key_size;
×
1507
        _cleanup_free_ char *friendly = NULL;
×
1508
        int keyslot = arg_key_slot, r;
×
1509
        bool use_libcryptsetup_plugin = use_token_plugins();
×
1510

1511
        assert(cd);
×
1512
        assert(name);
×
1513
        assert(arg_fido2_device || arg_fido2_device_auto);
×
1514

1515
        if (arg_fido2_cid && !key_file && !iovec_is_set(key_data))
×
1516
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1517
                                        "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
1518

1519
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
×
1520
        if (!friendly)
×
1521
                return log_oom();
×
1522

1523
        for (;;) {
×
1524
                if (use_libcryptsetup_plugin && !arg_fido2_cid) {
×
1525
                        r = attach_luks2_by_fido2_via_plugin(cd, name, until, arg_fido2_device, flags);
×
1526
                        if (IN_SET(r, -ENOTUNIQ, -ENXIO, -ENOENT))
×
1527
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1528
                                                       "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1529

1530
                } else {
1531
                        if (arg_fido2_cid)
×
1532
                                r = acquire_fido2_key(
×
1533
                                                name,
1534
                                                friendly,
1535
                                                arg_fido2_device,
1536
                                                arg_fido2_rp_id,
1537
                                                arg_fido2_cid, arg_fido2_cid_size,
1538
                                                key_file, arg_keyfile_size, arg_keyfile_offset,
1539
                                                key_data,
1540
                                                until,
1541
                                                arg_fido2_manual_flags,
1542
                                                "cryptsetup.fido2-pin",
1543
                                                arg_ask_password_flags,
1544
                                                &decrypted_key,
1545
                                                &decrypted_key_size);
1546
                        else
1547
                                r = acquire_fido2_key_auto(
×
1548
                                                cd,
1549
                                                name,
1550
                                                friendly,
1551
                                                arg_fido2_device,
1552
                                                until,
1553
                                                "cryptsetup.fido2-pin",
1554
                                                arg_ask_password_flags,
1555
                                                &decrypted_key,
1556
                                                &decrypted_key_size);
1557
                        if (r >= 0)
×
1558
                                break;
1559
                }
1560

1561
                if (r != -EAGAIN) /* EAGAIN means: token not found */
×
1562
                        return r;
1563

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

1568
                        assert(!event);
×
1569

1570
                        r = make_security_device_monitor(&event, &monitor);
×
1571
                        if (r < 0)
×
1572
                                return r;
1573

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

1576
                        /* Let's immediately rescan in case the token appeared in the time we needed
1577
                         * to create and configure the monitor */
1578
                        continue;
×
1579
                }
1580

1581
                r = run_security_device_monitor(event, monitor);
×
1582
                if (r < 0)
×
1583
                        return r;
1584

1585
                log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
×
1586
        }
1587

1588
        if (pass_volume_key)
×
1589
                r = measured_crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
×
1590
        else {
1591
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
×
1592
                ssize_t base64_encoded_size;
×
1593

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

1596
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
×
1597
                if (base64_encoded_size < 0)
×
1598
                        return log_oom();
×
1599

1600
                r = measured_crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, base64_encoded_size, flags);
×
1601
        }
1602
        if (r == -EPERM) {
×
1603
                log_error_errno(r, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
×
1604
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
1605
        }
1606
        if (r < 0)
×
1607
                return log_error_errno(r, "Failed to activate with FIDO2 acquired key: %m");
×
1608

1609
        return 0;
1610
}
1611

1612
static int attach_luks2_by_pkcs11_via_plugin(
×
1613
                struct crypt_device *cd,
1614
                const char *name,
1615
                const char *friendly_name,
1616
                usec_t until,
1617
                const char *askpw_credential,
1618
                uint32_t flags) {
1619

1620
#if HAVE_LIBCRYPTSETUP_PLUGINS
1621
        int r;
×
1622

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

1626
        systemd_pkcs11_plugin_params params = {
×
1627
                .friendly_name = friendly_name,
1628
                .until = until,
1629
                .askpw_credential = askpw_credential,
1630
                .askpw_flags = arg_ask_password_flags,
1631
        };
1632

1633
        r = crypt_activate_by_token_pin(cd, name, "systemd-pkcs11", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
×
1634
        if (r > 0) /* returns unlocked keyslot id on success */
×
1635
                r = 0;
1636
        if (r == -EEXIST) /* volume is already active */
×
1637
                r = log_external_activation(r, name);
×
1638

1639
        return r;
1640
#else
1641
        return -EOPNOTSUPP;
1642
#endif
1643
}
1644

1645
static int attach_luks_or_plain_or_bitlk_by_pkcs11(
×
1646
                struct crypt_device *cd,
1647
                const char *name,
1648
                const char *key_file,
1649
                const struct iovec *key_data,
1650
                usec_t until,
1651
                uint32_t flags,
1652
                bool pass_volume_key) {
1653

1654
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1655
        _cleanup_free_ char *friendly = NULL, *discovered_uri = NULL;
×
1656
        size_t decrypted_key_size = 0, discovered_key_size = 0;
×
1657
        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
×
1658
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1659
        _cleanup_free_ void *discovered_key = NULL;
×
1660
        struct iovec discovered_key_data = {};
×
1661
        int keyslot = arg_key_slot, r;
×
1662
        const char *uri = NULL;
×
1663
        bool use_libcryptsetup_plugin = use_token_plugins();
×
1664

1665
        assert(cd);
×
1666
        assert(name);
×
1667
        assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
×
1668

1669
        if (arg_pkcs11_uri_auto) {
×
1670
                if (!use_libcryptsetup_plugin) {
×
1671
                        r = find_pkcs11_auto_data(cd, &discovered_uri, &discovered_key, &discovered_key_size, &keyslot);
×
1672
                        if (IN_SET(r, -ENOTUNIQ, -ENXIO))
×
1673
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1674
                                                       "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1675
                        if (r < 0)
×
1676
                                return r;
1677

1678
                        uri = discovered_uri;
×
1679
                        discovered_key_data = IOVEC_MAKE(discovered_key, discovered_key_size);
×
1680
                        key_data = &discovered_key_data;
×
1681
                }
1682
        } else {
1683
                uri = arg_pkcs11_uri;
×
1684

1685
                if (!key_file && !iovec_is_set(key_data))
×
1686
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing.");
×
1687
        }
1688

1689
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
×
1690
        if (!friendly)
×
1691
                return log_oom();
×
1692

1693
        for (;;) {
×
1694
                if (use_libcryptsetup_plugin && arg_pkcs11_uri_auto)
×
1695
                        r = attach_luks2_by_pkcs11_via_plugin(
×
1696
                                        cd,
1697
                                        name,
1698
                                        friendly,
1699
                                        until,
1700
                                        "cryptsetup.pkcs11-pin",
1701
                                        flags);
1702
                else {
1703
                        r = decrypt_pkcs11_key(
×
1704
                                        name,
1705
                                        friendly,
1706
                                        uri,
1707
                                        key_file, arg_keyfile_size, arg_keyfile_offset,
1708
                                        key_data,
1709
                                        until,
1710
                                        arg_ask_password_flags,
1711
                                        &decrypted_key, &decrypted_key_size);
1712
                        if (r >= 0)
×
1713
                                break;
1714
                }
1715

1716
                if (r != -EAGAIN) /* EAGAIN means: token not found */
×
1717
                        return r;
1718

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

1723
                        assert(!event);
×
1724

1725
                        r = make_security_device_monitor(&event, &monitor);
×
1726
                        if (r < 0)
×
1727
                                return r;
1728

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

1732
                        /* Let's immediately rescan in case the token appeared in the time we needed
1733
                         * to create and configure the monitor */
1734
                        continue;
×
1735
                }
1736

1737
                r = run_security_device_monitor(event, monitor);
×
1738
                if (r < 0)
×
1739
                        return r;
1740

1741
                log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
×
1742
        }
1743
        assert(decrypted_key);
×
1744

1745
        if (pass_volume_key)
×
1746
                r = measured_crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
×
1747
        else {
1748
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
×
1749
                ssize_t base64_encoded_size;
×
1750

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

1759
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
×
1760
                if (base64_encoded_size < 0)
×
1761
                        return log_oom();
×
1762

1763
                r = measured_crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, base64_encoded_size, flags);
×
1764
        }
1765
        if (r == -EPERM) {
×
1766
                log_error_errno(r, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)");
×
1767
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
1768
        }
1769
        if (r < 0)
×
1770
                return log_error_errno(r, "Failed to activate with PKCS#11 acquired key: %m");
×
1771

1772
        return 0;
1773
}
1774

1775
static int make_tpm2_device_monitor(
×
1776
                sd_event **ret_event,
1777
                sd_device_monitor **ret_monitor) {
1778

1779
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1780
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1781
        int r;
×
1782

1783
        assert(ret_event);
×
1784
        assert(ret_monitor);
×
1785

1786
        r = sd_event_default(&event);
×
1787
        if (r < 0)
×
1788
                return log_error_errno(r, "Failed to allocate event loop: %m");
×
1789

1790
        r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
×
1791
        if (r < 0)
×
1792
                return log_error_errno(r, "Failed to install timeout event source: %m");
×
1793

1794
        r = sd_device_monitor_new(&monitor);
×
1795
        if (r < 0)
×
1796
                return log_error_errno(r, "Failed to allocate device monitor: %m");
×
1797

1798
        (void) sd_device_monitor_set_description(monitor, "tpmrm");
×
1799

1800
        r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "tpmrm", NULL);
×
1801
        if (r < 0)
×
1802
                return log_error_errno(r, "Failed to configure device monitor: %m");
×
1803

1804
        r = sd_device_monitor_attach_event(monitor, event);
×
1805
        if (r < 0)
×
1806
                return log_error_errno(r, "Failed to attach device monitor: %m");
×
1807

1808
        r = sd_device_monitor_start(monitor, NULL, NULL);
×
1809
        if (r < 0)
×
1810
                return log_error_errno(r, "Failed to start device monitor: %m");
×
1811

1812
        *ret_event = TAKE_PTR(event);
×
1813
        *ret_monitor = TAKE_PTR(monitor);
×
1814
        return 0;
×
1815
}
1816

1817
static int attach_luks2_by_tpm2_via_plugin(
10✔
1818
                struct crypt_device *cd,
1819
                const char *name,
1820
                usec_t until,
1821
                uint32_t flags) {
1822

1823
#if HAVE_LIBCRYPTSETUP_PLUGINS
1824
        systemd_tpm2_plugin_params params = {
10✔
1825
                .search_pcr_mask = arg_tpm2_pcr_mask,
1826
                .device = arg_tpm2_device,
1827
                .signature_path = arg_tpm2_signature,
1828
                .pcrlock_path = arg_tpm2_pcrlock,
1829
        };
1830

1831
        if (!use_token_plugins())
10✔
1832
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1✔
1833
                                       "libcryptsetup has external plugins support disabled.");
1834

1835
        return crypt_activate_by_token_pin_ask_password(
9✔
1836
                        cd,
1837
                        name,
1838
                        "systemd-tpm2",
1839
                        until,
1840
                        &params,
1841
                        flags,
1842
                        "Please enter TPM2 PIN:",
1843
                        "tpm2-pin",
1844
                        "cryptsetup.tpm2-pin");
1845
#else
1846
        return -EOPNOTSUPP;
1847
#endif
1848
}
1849

1850
static int attach_luks_or_plain_or_bitlk_by_tpm2(
10✔
1851
                struct crypt_device *cd,
1852
                const char *name,
1853
                const char *key_file,
1854
                const struct iovec *key_data,
1855
                usec_t until,
1856
                uint32_t flags,
1857
                bool pass_volume_key) {
1858

1859
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
10✔
1860
        _cleanup_(iovec_done_erase) struct iovec decrypted_key = {};
×
1861
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
10✔
1862
        _cleanup_free_ char *friendly = NULL;
10✔
1863
        int keyslot = arg_key_slot, r;
10✔
1864

1865
        assert(cd);
10✔
1866
        assert(name);
10✔
1867
        assert(arg_tpm2_device || arg_tpm2_device_auto);
10✔
1868

1869
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
10✔
1870
        if (!friendly)
10✔
1871
                return log_oom();
×
1872

1873
        for (;;) {
10✔
1874
                if (key_file || iovec_is_set(key_data)) {
10✔
1875
                        /* If key data is specified, use that */
1876

1877
                        r = acquire_tpm2_key(
×
1878
                                        name,
1879
                                        arg_tpm2_device,
1880
                                        arg_tpm2_pcr_mask == UINT32_MAX ? TPM2_PCR_MASK_DEFAULT_LEGACY : arg_tpm2_pcr_mask,
×
1881
                                        UINT16_MAX,
1882
                                        /* pubkey= */ NULL,
1883
                                        /* pubkey_pcr_mask= */ 0,
1884
                                        /* signature_path= */ NULL,
1885
                                        /* pcrlock_path= */ NULL,
1886
                                        /* primary_alg= */ 0,
1887
                                        key_file, arg_keyfile_size, arg_keyfile_offset,
1888
                                        key_data, /* n_blobs= */ 1,
1889
                                        /* policy_hash= */ NULL, /* we don't know the policy hash */
1890
                                        /* n_policy_hash= */ 0,
1891
                                        /* salt= */ NULL,
1892
                                        /* srk= */ NULL,
1893
                                        /* pcrlock_nv= */ NULL,
1894
                                        arg_tpm2_pin ? TPM2_FLAGS_USE_PIN : 0,
1895
                                        until,
1896
                                        "cryptsetup.tpm2-pin",
1897
                                        arg_ask_password_flags,
1898
                                        &decrypted_key);
1899
                        if (r >= 0)
×
1900
                                break;
1901
                        if (IN_SET(r, -EACCES, -ENOLCK))
×
1902
                                return log_error_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
×
1903
                        if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
×
1904
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");
×
1905
                        /* EAGAIN means: no tpm2 chip found */
1906
                        if (r != -EAGAIN) {
×
1907
                                log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
×
1908
                                return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
×
1909
                        }
1910
                } else {
1911
                        r = attach_luks2_by_tpm2_via_plugin(cd, name, until, flags);
10✔
1912
                        if (r >= 0)
10✔
1913
                                return 0;
1914
                        /* EAGAIN     means: no tpm2 chip found
1915
                         * EOPNOTSUPP means: no libcryptsetup plugins support */
1916
                        if (r == -ENXIO)
10✔
1917
                                return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1918
                                                        "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
1919
                        if (r == -ENOENT)
10✔
1920
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
3✔
1921
                                                       "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
1922
                        if (!IN_SET(r, -EOPNOTSUPP, -EAGAIN)) {
7✔
1923
                                log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
6✔
1924
                                return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
6✔
1925
                        }
1926
                }
1927

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

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

1936
                        for (;;) {
1✔
1937
                                _cleanup_(iovec_done) struct iovec pubkey = {}, salt = {}, srk = {}, pcrlock_nv = {};
×
1938
                                struct iovec *blobs = NULL, *policy_hash = NULL;
1✔
1939
                                uint32_t hash_pcr_mask, pubkey_pcr_mask;
1✔
1940
                                size_t n_blobs = 0, n_policy_hash = 0;
1✔
1941
                                uint16_t pcr_bank, primary_alg;
1✔
1942
                                TPM2Flags tpm2_flags;
1✔
1943

1944
                                CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
1✔
1945
                                CLEANUP_ARRAY(policy_hash, n_policy_hash, iovec_array_free);
1✔
1946

1947
                                r = find_tpm2_auto_data(
1✔
1948
                                                cd,
1949
                                                arg_tpm2_pcr_mask, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1950
                                                token, /* search for the token with this index, or any later index than this */
1951
                                                &hash_pcr_mask,
1952
                                                &pcr_bank,
1953
                                                &pubkey,
1954
                                                &pubkey_pcr_mask,
1955
                                                &primary_alg,
1956
                                                &blobs,
1957
                                                &n_blobs,
1958
                                                &policy_hash,
1959
                                                &n_policy_hash,
1960
                                                &salt,
1961
                                                &srk,
1962
                                                &pcrlock_nv,
1963
                                                &tpm2_flags,
1964
                                                &keyslot,
1965
                                                &token);
1966
                                if (r == -ENXIO)
1✔
1967
                                        /* No further TPM2 tokens found in the LUKS2 header. */
1968
                                        return log_full_errno(found_some ? LOG_NOTICE : LOG_DEBUG,
×
1969
                                                              SYNTHETIC_ERRNO(EAGAIN),
1970
                                                              found_some
1971
                                                              ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
1972
                                                              : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
1973
                                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
1✔
1974
                                        /* TPM2 support not compiled in? */
1975
                                        return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1976
                                                               "TPM2 support not available, falling back to traditional unlocking.");
1977
                                if (r < 0)
1✔
1978
                                        return r;
1979

1980
                                found_some = true;
1✔
1981

1982
                                r = acquire_tpm2_key(
1✔
1983
                                                name,
1984
                                                arg_tpm2_device,
1985
                                                hash_pcr_mask,
1986
                                                pcr_bank,
1987
                                                &pubkey,
1988
                                                pubkey_pcr_mask,
1989
                                                arg_tpm2_signature,
1990
                                                arg_tpm2_pcrlock,
1991
                                                primary_alg,
1992
                                                /* key_file= */ NULL, /* key_file_size= */ 0, /* key_file_offset= */ 0, /* no key file */
1993
                                                blobs,
1994
                                                n_blobs,
1995
                                                policy_hash,
1996
                                                n_policy_hash,
1997
                                                &salt,
1998
                                                &srk,
1999
                                                &pcrlock_nv,
2000
                                                tpm2_flags,
2001
                                                until,
2002
                                                "cryptsetup.tpm2-pin",
2003
                                                arg_ask_password_flags,
2004
                                                &decrypted_key);
2005
                                if (IN_SET(r, -EACCES, -ENOLCK))
1✔
2006
                                        return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
×
2007
                                if (r != -EPERM)
1✔
2008
                                        break;
2009

2010
                                token++; /* try a different token next time */
×
2011
                        }
2012

2013
                        if (r >= 0)
1✔
2014
                                break;
2015
                        /* EAGAIN means: no tpm2 chip found */
2016
                        if (r != -EAGAIN) {
×
2017
                                log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
×
2018
                                return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
×
2019
                        }
2020
                }
2021

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

2026
                        assert(!event);
×
2027

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

2032
                        r = make_tpm2_device_monitor(&event, &monitor);
×
2033
                        if (r < 0)
×
2034
                                return r;
2035

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

2038
                        /* Let's immediately rescan in case the device appeared in the time we needed
2039
                         * to create and configure the monitor */
2040
                        continue;
×
2041
                }
2042

2043
                r = run_security_device_monitor(event, monitor);
×
2044
                if (r < 0)
×
2045
                        return r;
2046

2047
                log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
×
2048
        }
2049

2050
        if (pass_volume_key)
1✔
2051
                r = measured_crypt_activate_by_volume_key(cd, name, decrypted_key.iov_base, decrypted_key.iov_len, flags);
×
2052
        else {
2053
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
1✔
2054
                ssize_t base64_encoded_size;
1✔
2055

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

2058
                base64_encoded_size = base64mem(decrypted_key.iov_base, decrypted_key.iov_len, &base64_encoded);
1✔
2059
                if (base64_encoded_size < 0)
1✔
2060
                        return log_oom();
×
2061

2062
                r = measured_crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, base64_encoded_size, flags);
1✔
2063
        }
2064
        if (r == -EPERM) {
1✔
2065
                log_error_errno(r, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
×
2066
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
2067
        }
2068
        if (r < 0)
1✔
2069
                return log_error_errno(r, "Failed to activate with TPM2 acquired key: %m");
×
2070

2071
        return 0;
2072
}
2073

2074
static int attach_luks_or_plain_or_bitlk_by_key_data(
3✔
2075
                struct crypt_device *cd,
2076
                const char *name,
2077
                const struct iovec *key_data,
2078
                uint32_t flags,
2079
                bool pass_volume_key) {
2080

2081
        int r;
3✔
2082

2083
        assert(cd);
3✔
2084
        assert(name);
3✔
2085
        assert(key_data);
3✔
2086

2087
        if (pass_volume_key)
3✔
2088
                r = measured_crypt_activate_by_volume_key(cd, name, key_data->iov_base, key_data->iov_len, flags);
×
2089
        else
2090
                r = measured_crypt_activate_by_passphrase(cd, name, arg_key_slot, key_data->iov_base, key_data->iov_len, flags);
3✔
2091
        if (r == -EPERM) {
3✔
2092
                log_error_errno(r, "Failed to activate. (Key incorrect?)");
×
2093
                return -EAGAIN; /* Log actual error, but return EAGAIN */
×
2094
        }
2095
        if (r < 0)
3✔
2096
                return log_error_errno(r, "Failed to activate: %m");
×
2097

2098
        return 0;
2099
}
2100

2101
static int attach_luks_or_plain_or_bitlk_by_key_file(
20✔
2102
                struct crypt_device *cd,
2103
                const char *name,
2104
                const char *key_file,
2105
                uint32_t flags,
2106
                bool pass_volume_key) {
2107

2108
        _cleanup_(erase_and_freep) char *kfdata = NULL;
20✔
2109
        _cleanup_free_ char *bindname = NULL;
20✔
2110
        size_t kfsize;
20✔
2111
        int r;
20✔
2112

2113
        assert(cd);
20✔
2114
        assert(name);
20✔
2115
        assert(key_file);
20✔
2116

2117
        /* If we read the key via AF_UNIX, make this client recognizable */
2118
        bindname = make_bindname(name, /* token_type= */ _TOKEN_TYPE_INVALID);
20✔
2119
        if (!bindname)
20✔
2120
                return log_oom();
×
2121

2122
        r = read_full_file_full(
23✔
2123
                        AT_FDCWD, key_file,
2124
                        arg_keyfile_offset == 0 ? UINT64_MAX : arg_keyfile_offset,
20✔
2125
                        arg_keyfile_size == 0 ? SIZE_MAX : arg_keyfile_size,
20✔
2126
                        READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
2127
                        bindname,
2128
                        &kfdata, &kfsize);
2129
        if (r == -E2BIG) {
20✔
2130
                log_error_errno(r, "Failed to activate, key file '%s' too large.", key_file);
×
2131
                return -EAGAIN;
×
2132
        }
2133
        if (r == -ENOENT) {
20✔
2134
                log_error_errno(r, "Failed to activate, key file '%s' missing.", key_file);
×
2135
                return -EAGAIN; /* Log actual error, but return EAGAIN */
×
2136
        }
2137
        if (r < 0)
20✔
2138
                return log_error_errno(r, "Failed to read key file '%s': %m", key_file);
×
2139

2140
        if (pass_volume_key)
20✔
2141
                r = measured_crypt_activate_by_volume_key(cd, name, kfdata, kfsize, flags);
×
2142
        else
2143
                r = measured_crypt_activate_by_passphrase(cd, name, arg_key_slot, kfdata, kfsize, flags);
20✔
2144
        if (r == -EPERM) {
20✔
2145
                log_error_errno(r, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file);
3✔
2146
                return -EAGAIN; /* Log actual error, but return EAGAIN */
3✔
2147
        }
2148
        if (r < 0)
17✔
2149
                return log_error_errno(r, "Failed to activate with key file '%s': %m", key_file);
×
2150

2151
        return 0;
2152
}
2153

2154
static int attach_luks_or_plain_or_bitlk_by_passphrase(
×
2155
                struct crypt_device *cd,
2156
                const char *name,
2157
                char **passwords,
2158
                uint32_t flags,
2159
                bool pass_volume_key) {
2160

2161
        int r;
×
2162

2163
        assert(cd);
×
2164
        assert(name);
×
2165

2166
        r = -EINVAL;
2167
        STRV_FOREACH(p, passwords) {
×
2168
                if (pass_volume_key)
×
2169
                        r = measured_crypt_activate_by_volume_key(cd, name, *p, arg_key_size, flags);
×
2170
                else
2171
                        r = measured_crypt_activate_by_passphrase(cd, name, arg_key_slot, *p, strlen(*p), flags);
×
2172
                if (r >= 0)
×
2173
                        break;
2174
        }
2175
        if (r == -EPERM) {
×
2176
                log_error_errno(r, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
×
2177
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
2178
        }
2179
        if (r < 0)
×
2180
                return log_error_errno(r, "Failed to activate with specified passphrase: %m");
×
2181

2182
        return 0;
2183
}
2184

2185
static int attach_luks_or_plain_or_bitlk(
33✔
2186
                struct crypt_device *cd,
2187
                const char *name,
2188
                TokenType token_type,
2189
                const char *key_file,
2190
                const struct iovec *key_data,
2191
                char **passwords,
2192
                uint32_t flags,
2193
                usec_t until) {
2194

2195
        bool pass_volume_key = false;
33✔
2196
        int r;
33✔
2197

2198
        assert(cd);
33✔
2199
        assert(name);
33✔
2200

2201
        if ((!arg_type && !crypt_get_type(cd)) || streq_ptr(arg_type, CRYPT_PLAIN)) {
33✔
2202
                struct crypt_params_plain params = {
×
2203
                        .offset = arg_offset,
2204
                        .skip = arg_skip,
2205
                        .sector_size = arg_sector_size,
2206
                };
2207
                const char *cipher, *cipher_mode;
×
2208
                _cleanup_free_ char *truncated_cipher = NULL;
×
2209

2210
                if (streq_ptr(arg_hash, "plain"))
×
2211
                        /* plain isn't a real hash type. it just means "use no hash" */
2212
                        params.hash = NULL;
2213
                else if (arg_hash)
×
2214
                        params.hash = arg_hash;
×
2215
                else if (!key_file)
×
2216
                        /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
2217
                         * file is provided */
2218
                        params.hash = "ripemd160";
×
2219

2220
                if (arg_cipher) {
×
2221
                        size_t l;
×
2222

2223
                        l = strcspn(arg_cipher, "-");
×
2224
                        truncated_cipher = strndup(arg_cipher, l);
×
2225
                        if (!truncated_cipher)
×
2226
                                return log_oom();
×
2227

2228
                        cipher = truncated_cipher;
×
2229
                        cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain";
×
2230
                } else {
2231
                        cipher = "aes";
2232
                        cipher_mode = "cbc-essiv:sha256";
2233
                }
2234

2235
                /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
2236
                arg_keyfile_size = arg_key_size;
×
2237

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

2244
                /* hash == NULL implies the user passed "plain" */
2245
                pass_volume_key = !params.hash;
×
2246
        }
2247

2248
        log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
33✔
2249
                 crypt_get_cipher(cd),
2250
                 crypt_get_cipher_mode(cd),
2251
                 crypt_get_volume_key_size(cd)*8,
2252
                 crypt_get_device_name(cd));
2253

2254
        if (token_type == TOKEN_TPM2)
33✔
2255
                return attach_luks_or_plain_or_bitlk_by_tpm2(cd, name, key_file, key_data, until, flags, pass_volume_key);
10✔
2256
        if (token_type == TOKEN_FIDO2)
23✔
2257
                return attach_luks_or_plain_or_bitlk_by_fido2(cd, name, key_file, key_data, until, flags, pass_volume_key);
×
2258
        if (token_type == TOKEN_PKCS11)
23✔
2259
                return attach_luks_or_plain_or_bitlk_by_pkcs11(cd, name, key_file, key_data, until, flags, pass_volume_key);
×
2260
        if (key_data)
23✔
2261
                return attach_luks_or_plain_or_bitlk_by_key_data(cd, name, key_data, flags, pass_volume_key);
3✔
2262
        if (key_file)
20✔
2263
                return attach_luks_or_plain_or_bitlk_by_key_file(cd, name, key_file, flags, pass_volume_key);
20✔
2264

2265
        return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
×
2266
}
2267

2268
static int help(void) {
×
2269
        _cleanup_free_ char *link = NULL;
×
2270
        int r;
×
2271

2272
        r = terminal_urlify_man("systemd-cryptsetup", "8", &link);
×
2273
        if (r < 0)
×
2274
                return log_oom();
×
2275

2276
        printf("%1$s attach VOLUME SOURCE-DEVICE [KEY-FILE] [CONFIG]\n"
×
2277
               "%1$s detach VOLUME\n\n"
2278
               "%2$sAttach or detach an encrypted block device.%3$s\n\n"
2279
               "  -h --help            Show this help\n"
2280
               "     --version         Show package version\n"
2281
               "\nSee the %4$s for details.\n",
2282
               program_invocation_short_name,
2283
               ansi_highlight(),
2284
               ansi_normal(),
2285
               link);
2286

2287
        return 0;
2288
}
2289

2290
static int parse_argv(int argc, char *argv[]) {
125✔
2291
        enum {
125✔
2292
                ARG_VERSION = 0x100,
2293
        };
2294

2295
        static const struct option options[] = {
125✔
2296
                { "help",                         no_argument,       NULL, 'h'                       },
2297
                { "version",                      no_argument,       NULL, ARG_VERSION               },
2298
                {}
2299
        };
2300

2301
        int c;
125✔
2302

2303
        assert(argc >= 0);
125✔
2304
        assert(argv);
125✔
2305

2306
        if (argv_looks_like_help(argc, argv))
125✔
2307
                return help();
×
2308

2309
        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
125✔
2310
                switch (c) {
×
2311

2312
                case 'h':
×
2313
                        return help();
×
2314

2315
                case ARG_VERSION:
×
2316
                        return version();
×
2317

2318
                case '?':
2319
                        return -EINVAL;
2320

2321
                default:
×
2322
                        assert_not_reached();
×
2323
                }
2324

2325
        return 1;
2326
}
2327

2328
static uint32_t determine_flags(void) {
70✔
2329
        uint32_t flags = 0;
70✔
2330

2331
        if (arg_readonly)
70✔
2332
                flags |= CRYPT_ACTIVATE_READONLY;
×
2333

2334
        if (arg_discards)
70✔
2335
                flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
×
2336

2337
        if (arg_same_cpu_crypt)
70✔
2338
                flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
×
2339

2340
        if (arg_submit_from_crypt_cpus)
70✔
2341
                flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
×
2342

2343
        if (arg_no_read_workqueue)
70✔
2344
                flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
×
2345

2346
        if (arg_no_write_workqueue)
70✔
2347
                flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
×
2348

2349
#ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
2350
        /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
2351
        /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
2352
        flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF;
70✔
2353
#endif
2354

2355
        return flags;
70✔
2356
}
2357

2358
static void remove_and_erasep(const char **p) {
70✔
2359
        int r;
70✔
2360

2361
        if (!*p)
70✔
2362
                return;
2363

2364
        r = unlinkat_deallocate(AT_FDCWD, *p, UNLINK_ERASE);
2✔
2365
        if (r < 0 && r != -ENOENT)
2✔
2366
                log_warning_errno(r, "Unable to erase key file '%s', ignoring: %m", *p);
×
2367
}
2368

2369
static TokenType determine_token_type(void) {
47✔
2370
        if (arg_tpm2_device || arg_tpm2_device_auto)
47✔
2371
                return TOKEN_TPM2;
2372
        if (arg_fido2_device || arg_fido2_device_auto)
37✔
2373
                return TOKEN_FIDO2;
2374
        if (arg_pkcs11_uri || arg_pkcs11_uri_auto)
37✔
2375
                return TOKEN_PKCS11;
×
2376

2377
        return _TOKEN_TYPE_INVALID;
2378
}
2379

2380
static int discover_key(const char *key_file, const char *volume, TokenType token_type, struct iovec *ret_key_data) {
24✔
2381
        _cleanup_free_ char *bindname = NULL;
24✔
2382
        const char *token_type_name;
24✔
2383
        int r;
24✔
2384

2385
        assert(key_file);
24✔
2386
        assert(volume);
24✔
2387
        assert(ret_key_data);
24✔
2388

2389
        bindname = make_bindname(volume, token_type);
24✔
2390
        if (!bindname)
24✔
2391
                return log_oom();
×
2392

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

2398
        token_type_name = token_type_to_string(token_type);
1✔
2399
        if (token_type_name)
1✔
2400
                log_debug("Automatically discovered encrypted key for volume '%s' (token type: %s).", volume, token_type_name);
×
2401
        else
2402
                log_debug("Automatically discovered key for volume '%s'.", volume);
1✔
2403

2404
        return r;
2405
}
2406

2407
static int verb_attach(int argc, char *argv[], void *userdata) {
70✔
2408
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
70✔
2409
        _unused_ _cleanup_(remove_and_erasep) const char *destroy_key_file = NULL;
70✔
2410
        crypt_status_info status;
70✔
2411
        uint32_t flags = 0;
70✔
2412
        unsigned tries;
70✔
2413
        usec_t until;
70✔
2414
        PassphraseType passphrase_type = PASSPHRASE_NONE;
70✔
2415
        int r;
70✔
2416

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

2419
        assert(argc >= 3 && argc <= 5);
70✔
2420

2421
        const char *volume = ASSERT_PTR(argv[1]),
70✔
2422
                *source = ASSERT_PTR(argv[2]),
70✔
2423
                *key_file = argc >= 4 ? mangle_none(argv[3]) : NULL,
70✔
2424
                *config = argc >= 5 ? mangle_none(argv[4]) : NULL;
70✔
2425

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

2429
        if (key_file && !path_is_absolute(key_file)) {
70✔
2430
                log_warning("Password file path '%s' is not absolute. Ignoring.", key_file);
×
2431
                key_file = NULL;
2432
        }
2433

2434
        if (config) {
70✔
2435
                r = parse_crypt_config(config);
70✔
2436
                if (r < 0)
70✔
2437
                        return r;
2438
        }
2439

2440
        log_debug("%s %s ← %s type=%s cipher=%s", __func__,
193✔
2441
                  volume, source, strempty(arg_type), strempty(arg_cipher));
2442

2443
        /* A delicious drop of snake oil */
2444
        (void) mlockall(MCL_FUTURE);
70✔
2445

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

2449
        if (arg_header) {
70✔
2450
                if (streq_ptr(arg_type, CRYPT_TCRYPT)){
9✔
2451
                        log_debug("tcrypt header: %s", arg_header);
×
2452
                        r = crypt_init_data_device(&cd, arg_header, source);
×
2453
                } else {
2454
                        log_debug("LUKS header: %s", arg_header);
9✔
2455
                        r = crypt_init(&cd, arg_header);
9✔
2456
                }
2457
        } else
2458
                r = crypt_init(&cd, source);
61✔
2459
        if (r < 0)
70✔
2460
                return log_error_errno(r, "crypt_init() failed: %m");
×
2461

2462
        cryptsetup_enable_logging(cd);
70✔
2463

2464
        status = crypt_status(cd, volume);
70✔
2465
        if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) {
70✔
2466
                log_info("Volume %s already active.", volume);
×
2467
                return 0;
×
2468
        }
2469

2470
        flags = determine_flags();
70✔
2471

2472
        until = usec_add(now(CLOCK_MONOTONIC), arg_timeout);
70✔
2473
        if (until == USEC_INFINITY)
×
2474
                until = 0;
70✔
2475

2476
        if (arg_key_size == 0)
70✔
2477
                arg_key_size = 256U / 8U;
70✔
2478

2479
        if (key_file) {
70✔
2480
                struct stat st;
20✔
2481

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

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

2493
/* since cryptsetup 2.7.0 (Jan 2024) */
2494
#if HAVE_CRYPT_SET_KEYRING_TO_LINK
2495
                if (arg_link_key_description) {
70✔
2496
                        r = crypt_set_keyring_to_link(cd, arg_link_key_description, NULL, arg_link_key_type, arg_link_keyring);
×
2497
                        if (r < 0)
×
2498
                                log_warning_errno(r, "Failed to set keyring or key description to link volume key in, ignoring: %m");
×
2499
                }
2500
#endif
2501

2502
                if (arg_header) {
70✔
2503
                        r = crypt_set_data_device(cd, source);
9✔
2504
                        if (r < 0)
9✔
2505
                                return log_error_errno(r, "Failed to set LUKS data device %s: %m", source);
×
2506
                }
2507

2508
                /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
2509
                if (!key_file && use_token_plugins()) {
70✔
2510
                        r = crypt_activate_by_token_pin_ask_password(
49✔
2511
                                        cd,
2512
                                        volume,
2513
                                        /* type= */ NULL,
2514
                                        until,
2515
                                        /* userdata= */ NULL,
2516
                                        flags,
2517
                                        "Please enter LUKS2 token PIN:",
2518
                                        "luks2-pin",
2519
                                        "cryptsetup.luks2-pin");
2520
                        if (r >= 0) {
49✔
2521
                                log_debug("Volume %s activated with a LUKS token.", volume);
35✔
2522
                                return 0;
35✔
2523
                        }
2524

2525
                        log_debug_errno(r, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd));
14✔
2526
                }
2527
        }
2528

2529
/* since cryptsetup 2.3.0 (Feb 2020) */
2530
#ifdef CRYPT_BITLK
2531
        if (streq_ptr(arg_type, CRYPT_BITLK)) {
35✔
2532
                r = crypt_load(cd, CRYPT_BITLK, NULL);
×
2533
                if (r < 0)
×
2534
                        return log_error_errno(r, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd));
×
2535
        }
2536
#endif
2537

2538
        bool use_cached_passphrase = true, try_discover_key = !key_file;
35✔
2539
        const char *discovered_key_fn = strjoina(volume, ".key");
175✔
2540
        _cleanup_strv_free_erase_ char **passwords = NULL;
35✔
2541
        for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) {
47✔
2542
                _cleanup_(iovec_done_erase) struct iovec discovered_key_data = {};
47✔
2543
                const struct iovec *key_data = NULL;
47✔
2544
                TokenType token_type = determine_token_type();
47✔
2545

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

2548
                /* When we were able to acquire multiple keys, let's always process them in this order:
2549
                 *
2550
                 *    1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
2551
                 *    2. The configured or discovered key, of which both are exclusive and optional
2552
                 *    3. The empty password, in case arg_try_empty_password is set
2553
                 *    4. We enquire the user for a password
2554
                 */
2555

2556
                if (try_discover_key) {
47✔
2557
                        r = discover_key(discovered_key_fn, volume, token_type, &discovered_key_data);
24✔
2558
                        if (r < 0)
24✔
2559
                                return r;
2560
                        if (r > 0)
24✔
2561
                                key_data = &discovered_key_data;
1✔
2562
                }
2563

2564
                if (token_type < 0 && !key_file && !key_data && !passwords) {
47✔
2565

2566
                        /* If we have nothing to try anymore, then acquire a new password */
2567

2568
                        if (arg_try_empty_password) {
16✔
2569
                                /* Hmm, let's try an empty password now, but only once */
2570
                                arg_try_empty_password = false;
2✔
2571
                                key_data = &iovec_empty;
2✔
2572
                        } else {
2573
                                /* Ask the user for a passphrase or recovery key only as last resort, if we
2574
                                 * have nothing else to check for */
2575
                                if (passphrase_type == PASSPHRASE_NONE) {
14✔
2576
                                        passphrase_type = check_registered_passwords(cd);
14✔
2577
                                        if (passphrase_type == PASSPHRASE_NONE)
14✔
2578
                                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No passphrase or recovery key registered.");
×
2579
                                }
2580

2581
                                r = get_password(
14✔
2582
                                                volume,
2583
                                                source,
2584
                                                until,
2585
                                                /* ignore_cached= */ !use_cached_passphrase || arg_verify,
14✔
2586
                                                passphrase_type,
2587
                                                &passwords);
2588
                                use_cached_passphrase = false;
14✔
2589
                                if (r == -EAGAIN)
14✔
2590
                                        continue;
×
2591
                                if (r < 0)
14✔
2592
                                        return r;
2593
                        }
2594
                }
2595

2596
                if (streq_ptr(arg_type, CRYPT_TCRYPT))
33✔
2597
                        r = attach_tcrypt(cd, volume, token_type, key_file, key_data, passwords, flags);
×
2598
                else
2599
                        r = attach_luks_or_plain_or_bitlk(cd, volume, token_type, key_file, key_data, passwords, flags, until);
33✔
2600
                if (r >= 0)
33✔
2601
                        break;
2602
                if (r != -EAGAIN)
12✔
2603
                        return r;
2604

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

2608
                if (token_type == TOKEN_TPM2) {
12✔
2609
                        arg_tpm2_device = mfree(arg_tpm2_device);
9✔
2610
                        arg_tpm2_device_auto = false;
9✔
2611
                        continue;
9✔
2612
                }
2613

2614
                if (token_type == TOKEN_FIDO2) {
3✔
2615
                        arg_fido2_device = mfree(arg_fido2_device);
×
2616
                        arg_fido2_device_auto = false;
×
2617
                        continue;
×
2618
                }
2619

2620
                if (token_type == TOKEN_PKCS11) {
3✔
2621
                        arg_pkcs11_uri = mfree(arg_pkcs11_uri);
×
2622
                        arg_pkcs11_uri_auto = false;
×
2623
                        continue;
×
2624
                }
2625

2626
                if (try_discover_key) {
3✔
2627
                        try_discover_key = false;
×
2628
                        continue;
×
2629
                }
2630

2631
                if (key_file) {
3✔
2632
                        key_file = NULL;
3✔
2633
                        continue;
3✔
2634
                }
2635

2636
                if (passwords) {
×
2637
                        passwords = strv_free_erase(passwords);
×
2638
                        continue;
×
2639
                }
2640

2641
                log_debug("Prepared for next attempt to unlock.");
×
2642
        }
2643

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

2647
        return 0;
2648
}
2649

2650
static int verb_detach(int argc, char *argv[], void *userdata) {
55✔
2651
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
55✔
2652
        const char *volume = ASSERT_PTR(argv[1]);
55✔
2653
        int r;
55✔
2654

2655
        assert(argc == 2);
55✔
2656

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

2660
        r = crypt_init_by_name(&cd, volume);
55✔
2661
        if (r == -ENODEV) {
55✔
2662
                log_info("Volume %s already inactive.", volume);
×
2663
                return 0;
×
2664
        }
2665
        if (r < 0)
55✔
2666
                return log_error_errno(r, "crypt_init_by_name() for volume '%s' failed: %m", volume);
×
2667

2668
        cryptsetup_enable_logging(cd);
55✔
2669

2670
        r = crypt_deactivate(cd, volume);
55✔
2671
        if (r < 0)
55✔
2672
                return log_error_errno(r, "Failed to deactivate '%s': %m", volume);
×
2673

2674
        return 0;
2675
}
2676

2677
static int run(int argc, char *argv[]) {
125✔
2678
        int r;
125✔
2679

2680
        log_setup();
125✔
2681

2682
        umask(0022);
125✔
2683

2684
        r = parse_argv(argc, argv);
125✔
2685
        if (r <= 0)
125✔
2686
                return r;
2687

2688
        cryptsetup_enable_logging(NULL);
125✔
2689

2690
        static const Verb verbs[] = {
125✔
2691
                { "attach", 3, 5, 0, verb_attach },
2692
                { "detach", 2, 2, 0, verb_detach },
2693
                {}
2694
        };
2695

2696
        return dispatch_verb(argc, argv, verbs, NULL);
125✔
2697
}
2698

2699
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