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

systemd / systemd / 19053295430

03 Nov 2025 12:31PM UTC coverage: 72.279% (+0.06%) from 72.222%
19053295430

push

github

DaanDeMeyer
mkosi: update fedora commit reference to 8e2833a5b

* 8e2833a5b6 Automatically figure out the name of the top-level tar dir
* dffbf2beba Make sure fallback source is listed first
* 1d3b892105 Enable sysupdate and sysupdated

306030 of 423401 relevant lines covered (72.28%)

1089556.4 hits per line

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

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

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

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

13
#include "alloc-util.h"
14
#include "argv-util.h"
15
#include "ask-password-api.h"
16
#include "build.h"
17
#include "cryptsetup-fido2.h"
18
#include "cryptsetup-keyfile.h"
19
#include "cryptsetup-pkcs11.h"
20
#include "cryptsetup-tpm2.h"
21
#include "cryptsetup-util.h"
22
#include "efi-api.h"
23
#include "efi-loader.h"
24
#include "efivars.h"
25
#include "env-util.h"
26
#include "errno-util.h"
27
#include "escape.h"
28
#include "extract-word.h"
29
#include "fileio.h"
30
#include "fs-util.h"
31
#include "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_tpm2_measure_keyslot_nvpcr = NULL;
127
static char *arg_link_keyring = NULL;
128
static char *arg_link_key_type = NULL;
129
static char *arg_link_key_description = NULL;
130

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

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

154
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(passphrase_type, PassphraseType);
×
155

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

162
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(token_type, TokenType);
45✔
163

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

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

178
        assert(option);
145✔
179

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

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

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

192
        } else if ((val = startswith(option, "size="))) {
144✔
193

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

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

205
                arg_key_size /= 8;
×
206

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

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

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

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

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

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

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

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

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

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

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

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

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

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

260
                arg_keyfile_erase = r;
2✔
261

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

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

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

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

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

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

286
        } else if ((val = startswith(option, "tries="))) {
123✔
287

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

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

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

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

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

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

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

368
        } else if ((val = startswith(option, "offset="))) {
115✔
369

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

374
        } else if ((val = startswith(option, "skip="))) {
115✔
375

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

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

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

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

393
                        arg_pkcs11_uri_auto = false;
×
394
                }
395

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

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

406
                        arg_fido2_device_auto = false;
×
407
                }
408

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

479
                        arg_tpm2_device_auto = false;
×
480
                }
481

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

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

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

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

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

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

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

506
                arg_tpm2_pin = r;
×
507

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

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

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

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

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

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

535
                arg_tpm2_measure_pcr = pcr;
×
536

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

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

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

546
                STRV_FOREACH(i, l) {
×
547
                        const EVP_MD *implementation;
×
548

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

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

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

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

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

572
                if (free_and_strdup(&arg_tpm2_measure_keyslot_nvpcr, val) < 0)
×
573
                        return log_oom();
×
574

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

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

583
                arg_try_empty_password = r;
1✔
584

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

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

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

599
        else if ((val = startswith(option, "token-timeout="))) {
×
600

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

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

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

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

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

632
                sep += 2;
×
633

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

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

645
                        sep = c + 1;
×
646
                }
647

648
                key_description = strdup(sep);
×
649
                if (!key_description)
×
650
                        return log_oom();
×
651

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

661
        return 0;
662
}
663

664
static int parse_crypt_config(const char *options) {
70✔
665
        assert(options);
70✔
666

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

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

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

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

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

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

701
        return 0;
702
}
703

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

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

714
        assert(path);
10✔
715

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

719
        if (!S_ISBLK(st.st_mode))
10✔
720
                return NULL;
721

722
        if (sd_device_new_from_stat_rdev(&device, &st) < 0)
×
723
                return NULL;
724

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

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

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

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

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

749
        return NULL;
750
}
751

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

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

760
        assert(label);
10✔
761

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

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

770
        for (;;) {
×
771
                struct libmnt_fs *fs;
10✔
772

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

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

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

790
        assert(src);
10✔
791
        assert(vol);
10✔
792

793
        description = disk_description(src);
10✔
794
        mount_point = disk_mount_point(vol);
10✔
795

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

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

811
        return name_buffer;
×
812
}
813

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

819
        assert(cd);
14✔
820

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

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

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

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

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

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

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

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

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

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

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

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

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

889
                                slots[u] = false;
9✔
890
                        }
891
                }
892
        }
893

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

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

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

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

919
        assert(vol);
14✔
920
        assert(src);
14✔
921
        assert(ret);
14✔
922

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

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

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

933
        disk_path = cescape(src);
×
934
        if (!disk_path)
×
935
                return log_oom();
×
936

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

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

952
        if (ignore_cached)
×
953
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
×
954

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

959
        if (arg_verify) {
×
960
                _cleanup_strv_free_erase_ char **passwords2 = NULL;
×
961

962
                assert(strv_length(passwords) == 1);
×
963

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

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

973
                req.message = text;
×
974
                req.id = id;
×
975

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

980
                assert(strv_length(passwords2) == 1);
×
981

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

987
        strv_uniq(passwords);
×
988

989
        STRV_FOREACH(p, passwords) {
×
990
                char *c;
×
991

992
                if (strlen(*p)+1 >= arg_key_size)
×
993
                        continue;
×
994

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

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

1005
        *ret = TAKE_PTR(passwords);
×
1006

1007
        return 0;
×
1008
}
1009

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

1016
        int r;
×
1017

1018
        assert(cd);
×
1019
        assert(name);
×
1020
        assert(volume_key);
×
1021
        assert(volume_key_size > 0);
×
1022

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

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

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

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

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

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

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

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

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

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

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

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

1090
        int r;
21✔
1091

1092
        assert(cd);
21✔
1093
        assert(name);
21✔
1094

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1173
        int r;
×
1174

1175
        assert(cd);
×
1176
        assert(name);
×
1177

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

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

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

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

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

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

1208
        assert(cd);
24✔
1209

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

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

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

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

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

1236
        return measured_crypt_activate_by_volume_key(cd, mechanism, name, keyslot, vk, vks, flags);
×
1237

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

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

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

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

1266
        assert(cd);
×
1267
        assert(name);
×
1268
        assert(key_file || key_data || !strv_isempty(passwords));
×
1269

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

1275
        if (arg_tcrypt_hidden)
×
1276
                params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
×
1277

1278
        if (arg_tcrypt_system)
×
1279
                params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
×
1280

1281
        if (arg_tcrypt_veracrypt)
×
1282
                params.flags |= CRYPT_TCRYPT_VERA_MODES;
×
1283

1284
        if (arg_tcrypt_veracrypt && arg_tcrypt_veracrypt_pim != 0)
×
1285
                params.veracrypt_pim = arg_tcrypt_veracrypt_pim;
×
1286

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

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

1320
                        return r;
×
1321
                }
1322

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

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

1337
        return 0;
1338
}
1339

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

1345
        switch (token_type) {
44✔
1346

1347
        case TOKEN_FIDO2:
1348
                suffix = "-salt";
1349
                break;
1350

1351
        default:
1352
                suffix = NULL;
44✔
1353
        }
1354

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

1365
        return bindname;
44✔
1366
}
1367

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

1375
        assert(ret_event);
×
1376
        assert(ret_monitor);
×
1377

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

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

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

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

1394
        (void) sd_device_monitor_set_description(monitor, "security-device");
×
1395

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

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

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

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

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

1419
        assert(event);
×
1420
        assert(monitor);
×
1421

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

1425
        for (;;) {
×
1426
                int x;
×
1427

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

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

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

1447
                processed = true;
×
1448
        }
1449
}
1450

1451
static bool use_token_plugins(void) {
60✔
1452

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

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

1466
#if HAVE_LIBCRYPTSETUP_PLUGINS
1467
        int r;
60✔
1468

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

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

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

1488
        assert(ret_pins);
21✔
1489

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

1499
        *ret_pins = TAKE_PTR(pins);
21✔
1500

1501
        return 0;
21✔
1502
}
1503
#endif
1504

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

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

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

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

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

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

1546
        for (;;) {
×
1547
                pins = strv_free_erase(pins);
×
1548

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

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

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

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

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

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

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

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

1617
        assert(cd);
×
1618
        assert(name);
×
1619
        assert(arg_fido2_device || arg_fido2_device_auto);
×
1620

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

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

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

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

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

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

1674
                        assert(!event);
×
1675

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

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

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

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

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

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

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

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

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

1729
        return 0;
1730
}
1731

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

1740
#if HAVE_LIBCRYPTSETUP_PLUGINS
1741
        int r;
×
1742

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

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

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

1759
        return r;
1760
#else
1761
        return -EOPNOTSUPP;
1762
#endif
1763
}
1764

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

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

1785
        assert(cd);
×
1786
        assert(name);
×
1787
        assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
×
1788

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

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

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

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

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

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

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

1843
                        assert(!event);
×
1844

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

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

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

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

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

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

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

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

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

1906
        return 0;
1907
}
1908

1909
static int make_tpm2_device_monitor(
×
1910
                sd_event **ret_event,
1911
                sd_device_monitor **ret_monitor) {
1912

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

1917
        assert(ret_event);
×
1918
        assert(ret_monitor);
×
1919

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

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

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

1932
        (void) sd_device_monitor_set_description(monitor, "tpmrm");
×
1933

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

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

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

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

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

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

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

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

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

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

1999
        assert(cd);
10✔
2000
        assert(name);
10✔
2001
        assert(arg_tpm2_device || arg_tpm2_device_auto);
10✔
2002

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

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

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

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

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

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

2078
                                CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
1✔
2079
                                CLEANUP_ARRAY(policy_hash, n_policy_hash, iovec_array_free);
1✔
2080

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

2114
                                found_some = true;
1✔
2115

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

2144
                                token++; /* try a different token next time */
×
2145
                        }
2146

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

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

2160
                        assert(!event);
×
2161

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

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

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

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

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

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

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

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

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

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

2219
        return 0;
2220
}
2221

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

2229
        int r;
3✔
2230

2231
        assert(cd);
3✔
2232
        assert(name);
3✔
2233
        assert(key_data);
3✔
2234

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

2246
        return 0;
2247
}
2248

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

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

2261
        assert(cd);
20✔
2262
        assert(name);
20✔
2263
        assert(key_file);
20✔
2264

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

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

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

2299
        return 0;
2300
}
2301

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

2309
        int r;
×
2310

2311
        assert(cd);
×
2312
        assert(name);
×
2313

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

2330
        return 0;
2331
}
2332

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

2343
        bool pass_volume_key = false;
33✔
2344
        int r;
33✔
2345

2346
        assert(cd);
33✔
2347
        assert(name);
33✔
2348

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

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

2368
                if (arg_cipher) {
×
2369
                        size_t l;
×
2370

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

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

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

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

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

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

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

2413
        return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
×
2414
}
2415

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

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

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

2435
        return 0;
2436
}
2437

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

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

2449
        int c;
125✔
2450

2451
        assert(argc >= 0);
125✔
2452
        assert(argv);
125✔
2453

2454
        if (argv_looks_like_help(argc, argv))
125✔
2455
                return help();
×
2456

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

2460
                case 'h':
×
2461
                        return help();
×
2462

2463
                case ARG_VERSION:
×
2464
                        return version();
×
2465

2466
                case '?':
2467
                        return -EINVAL;
2468

2469
                default:
×
2470
                        assert_not_reached();
×
2471
                }
2472

2473
        return 1;
2474
}
2475

2476
static uint32_t determine_flags(void) {
70✔
2477
        uint32_t flags = 0;
70✔
2478

2479
        if (arg_readonly)
70✔
2480
                flags |= CRYPT_ACTIVATE_READONLY;
×
2481

2482
        if (arg_discards)
70✔
2483
                flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
×
2484

2485
        if (arg_same_cpu_crypt)
70✔
2486
                flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
×
2487

2488
        if (arg_submit_from_crypt_cpus)
70✔
2489
                flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
×
2490

2491
        if (arg_no_read_workqueue)
70✔
2492
                flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
×
2493

2494
        if (arg_no_write_workqueue)
70✔
2495
                flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
×
2496

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

2503
        return flags;
70✔
2504
}
2505

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

2509
        if (!*p)
70✔
2510
                return;
2511

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

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

2525
        return _TOKEN_TYPE_INVALID;
2526
}
2527

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

2533
        assert(key_file);
24✔
2534
        assert(volume);
24✔
2535
        assert(ret_key_data);
24✔
2536

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

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

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

2552
        return r;
2553
}
2554

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

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

2567
        assert(argc >= 3 && argc <= 5);
70✔
2568

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

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

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

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

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

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

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

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

2610
        cryptsetup_enable_logging(cd);
70✔
2611

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

2618
        flags = determine_flags();
70✔
2619

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

2624
        if (arg_key_size == 0)
70✔
2625
                arg_key_size = 256U / 8U;
70✔
2626

2627
        if (key_file) {
70✔
2628
                struct stat st;
20✔
2629

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

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

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

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

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

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

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

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

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

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

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

2712
                if (token_type < 0 && !key_file && !key_data && !passwords) {
47✔
2713

2714
                        /* If we have nothing to try anymore, then acquire a new password */
2715

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

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

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

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

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

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

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

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

2779
                if (key_file) {
3✔
2780
                        key_file = NULL;
3✔
2781
                        continue;
3✔
2782
                }
2783

2784
                if (passwords) {
×
2785
                        passwords = strv_free_erase(passwords);
×
2786
                        continue;
×
2787
                }
2788

2789
                log_debug("Prepared for next attempt to unlock.");
×
2790
        }
2791

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

2795
        return 0;
2796
}
2797

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

2803
        assert(argc == 2);
55✔
2804

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

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

2816
        cryptsetup_enable_logging(cd);
55✔
2817

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

2822
        return 0;
2823
}
2824

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

2828
        log_setup();
125✔
2829

2830
        umask(0022);
125✔
2831

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

2836
        cryptsetup_enable_logging(NULL);
125✔
2837

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

2844
        return dispatch_verb(argc, argv, verbs, NULL);
125✔
2845
}
2846

2847
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