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

systemd / systemd / 12877533250

20 Jan 2025 11:16PM UTC coverage: 0.117%. Remained the same
12877533250

push

github

web-flow
pidfd: cache our own pidfd inode id, and use it at various places (#36060)

This is split out of and preparation for #35224, but makes a ton of
sense on its own

0 of 95 new or added lines in 10 files covered. (0.0%)

4667 existing lines in 34 files now uncovered.

478 of 408040 relevant lines covered (0.12%)

1.45 hits per line

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

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

3
#include <errno.h>
4
#include <getopt.h>
5
#include <mntent.h>
6
#include <sys/mman.h>
7
#include <sys/stat.h>
8
#include <sys/types.h>
9
#include <unistd.h>
10

11
#include "sd-device.h"
12
#include "sd-json.h"
13
#include "sd-messages.h"
14

15
#include "alloc-util.h"
16
#include "ask-password-api.h"
17
#include "build.h"
18
#include "cryptsetup-fido2.h"
19
#include "cryptsetup-keyfile.h"
20
#include "cryptsetup-pkcs11.h"
21
#include "cryptsetup-tpm2.h"
22
#include "cryptsetup-util.h"
23
#include "device-util.h"
24
#include "efi-api.h"
25
#include "efi-loader.h"
26
#include "env-util.h"
27
#include "escape.h"
28
#include "fileio.h"
29
#include "fs-util.h"
30
#include "fstab-util.h"
31
#include "hexdecoct.h"
32
#include "json-util.h"
33
#include "libfido2-util.h"
34
#include "log.h"
35
#include "main-func.h"
36
#include "memory-util.h"
37
#include "mount-util.h"
38
#include "nulstr-util.h"
39
#include "parse-util.h"
40
#include "path-util.h"
41
#include "pkcs11-util.h"
42
#include "pretty-print.h"
43
#include "process-util.h"
44
#include "random-util.h"
45
#include "string-table.h"
46
#include "strv.h"
47
#include "tpm2-pcr.h"
48
#include "tpm2-util.h"
49
#include "verbs.h"
50

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

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

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

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

127
STATIC_DESTRUCTOR_REGISTER(arg_cipher, freep);
×
128
STATIC_DESTRUCTOR_REGISTER(arg_hash, freep);
×
129
STATIC_DESTRUCTOR_REGISTER(arg_header, freep);
×
130
STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles, strv_freep);
×
131
STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri, freep);
×
132
STATIC_DESTRUCTOR_REGISTER(arg_fido2_device, freep);
×
133
STATIC_DESTRUCTOR_REGISTER(arg_fido2_cid, freep);
×
134
STATIC_DESTRUCTOR_REGISTER(arg_fido2_rp_id, freep);
×
135
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
×
136
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_signature, freep);
×
137
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_measure_banks, strv_freep);
×
138
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_pcrlock, freep);
×
139
STATIC_DESTRUCTOR_REGISTER(arg_link_keyring, freep);
×
140
STATIC_DESTRUCTOR_REGISTER(arg_link_key_type, freep);
×
UNCOV
141
STATIC_DESTRUCTOR_REGISTER(arg_link_key_description, freep);
×
142

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

UNCOV
149
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(passphrase_type, PassphraseType);
×
150

151
static const char* const token_type_table[_TOKEN_TYPE_MAX] = {
152
        [TOKEN_TPM2]   = "tpm2",
153
        [TOKEN_FIDO2]  = "fido2",
154
        [TOKEN_PKCS11] = "pkcs11",
155
};
156

UNCOV
157
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(token_type, TokenType);
×
158

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

169
static int parse_one_option(const char *option) {
×
170
        const char *val;
×
UNCOV
171
        int r;
×
172

UNCOV
173
        assert(option);
×
174

175
        /* Handled outside of this tool */
176
        if (STR_IN_SET(option, "noauto", "auto", "nofail", "fail", "_netdev", "keyfile-timeout"))
×
UNCOV
177
                return 0;
×
178

UNCOV
179
        if (startswith(option, "keyfile-timeout="))
×
180
                return 0;
181

182
        if ((val = startswith(option, "cipher="))) {
×
183
                r = free_and_strdup(&arg_cipher, val);
×
184
                if (r < 0)
×
UNCOV
185
                        return log_oom();
×
186

UNCOV
187
        } else if ((val = startswith(option, "size="))) {
×
188

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

195
                if (arg_key_size % 8) {
×
196
                        log_warning("size= not a multiple of 8, ignoring.");
×
UNCOV
197
                        return 0;
×
198
                }
199

UNCOV
200
                arg_key_size /= 8;
×
201

UNCOV
202
        } else if ((val = startswith(option, "sector-size="))) {
×
203

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

210
                if (arg_sector_size % 2) {
×
211
                        log_warning("sector-size= not a multiple of 2, ignoring.");
×
UNCOV
212
                        return 0;
×
213
                }
214

215
                if (arg_sector_size < CRYPT_SECTOR_SIZE || arg_sector_size > CRYPT_MAX_SECTOR_SIZE)
×
UNCOV
216
                        log_warning("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE, CRYPT_MAX_SECTOR_SIZE);
×
217

218
        } else if ((val = startswith(option, "key-slot=")) ||
×
UNCOV
219
                   (val = startswith(option, "keyslot="))) {
×
220

221
                arg_type = ANY_LUKS;
×
222
                r = safe_atoi(val, &arg_key_slot);
×
223
                if (r < 0)
×
UNCOV
224
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
225

UNCOV
226
        } else if ((val = startswith(option, "tcrypt-keyfile="))) {
×
227

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

UNCOV
235
        } else if ((val = startswith(option, "keyfile-size="))) {
×
236

237
                r = safe_atou(val, &arg_keyfile_size);
×
238
                if (r < 0)
×
UNCOV
239
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
240

UNCOV
241
        } else if ((val = startswith(option, "keyfile-offset="))) {
×
242

243
                r = safe_atou64(val, &arg_keyfile_offset);
×
244
                if (r < 0)
×
UNCOV
245
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
246

UNCOV
247
        } else if ((val = startswith(option, "keyfile-erase="))) {
×
248

249
                r = parse_boolean(val);
×
250
                if (r < 0) {
×
251
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
UNCOV
252
                        return 0;
×
253
                }
254

UNCOV
255
                arg_keyfile_erase = r;
×
256

257
        } else if (streq(option, "keyfile-erase"))
×
UNCOV
258
                arg_keyfile_erase = true;
×
259

260
        else if ((val = startswith(option, "hash="))) {
×
261
                r = free_and_strdup(&arg_hash, val);
×
262
                if (r < 0)
×
UNCOV
263
                        return log_oom();
×
264

265
        } else if ((val = startswith(option, "header="))) {
×
266
                if (!arg_type || !STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT))
×
UNCOV
267
                        arg_type = ANY_LUKS;
×
268

269
                if (!path_is_absolute(val))
×
UNCOV
270
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
271
                                               "Header path \"%s\" is not absolute, refusing.", val);
272

273
                if (arg_header)
×
UNCOV
274
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
275
                                               "Duplicate header= option, refusing.");
276

277
                arg_header = strdup(val);
×
278
                if (!arg_header)
×
UNCOV
279
                        return log_oom();
×
280

UNCOV
281
        } else if ((val = startswith(option, "tries="))) {
×
282

283
                r = safe_atou(val, &arg_tries);
×
284
                if (r < 0)
×
UNCOV
285
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
286

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

301
                        SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_ECHO, r);
×
UNCOV
302
                        SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_SILENT, !r);
×
303
                }
304
        } else if ((val = startswith(option, "password-cache="))) {
×
UNCOV
305
                arg_password_cache_set = true;
×
306

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

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

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

359
                r = parse_sec_fix_0(val, &arg_timeout);
×
360
                if (r < 0)
×
UNCOV
361
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
362

UNCOV
363
        } else if ((val = startswith(option, "offset="))) {
×
364

365
                r = safe_atou64(val, &arg_offset);
×
366
                if (r < 0)
×
UNCOV
367
                        return log_error_errno(r, "Failed to parse %s: %m", option);
×
368

UNCOV
369
        } else if ((val = startswith(option, "skip="))) {
×
370

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

UNCOV
375
        } else if ((val = startswith(option, "pkcs11-uri="))) {
×
376

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

384
                        r = free_and_strdup(&arg_pkcs11_uri, val);
×
385
                        if (r < 0)
×
UNCOV
386
                                return log_oom();
×
387

UNCOV
388
                        arg_pkcs11_uri_auto = false;
×
389
                }
390

UNCOV
391
        } else if ((val = startswith(option, "fido2-device="))) {
×
392

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

UNCOV
401
                        arg_fido2_device_auto = false;
×
402
                }
403

UNCOV
404
        } else if ((val = startswith(option, "fido2-cid="))) {
×
405

406
                if (streq(val, "auto"))
×
UNCOV
407
                        arg_fido2_cid = mfree(arg_fido2_cid);
×
408
                else {
409
                        _cleanup_free_ void *cid = NULL;
×
UNCOV
410
                        size_t cid_size;
×
411

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

416
                        free(arg_fido2_cid);
×
417
                        arg_fido2_cid = TAKE_PTR(cid);
×
UNCOV
418
                        arg_fido2_cid_size = cid_size;
×
419
                }
420

421
                /* Turn on FIDO2 as side-effect, if not turned on yet. */
422
                if (!arg_fido2_device && !arg_fido2_device_auto)
×
UNCOV
423
                        arg_fido2_device_auto = true;
×
424

UNCOV
425
        } else if ((val = startswith(option, "fido2-rp="))) {
×
426

427
                r = free_and_strdup(&arg_fido2_rp_id, val);
×
428
                if (r < 0)
×
UNCOV
429
                        return log_oom();
×
430

UNCOV
431
        } else if ((val = startswith(option, "fido2-pin="))) {
×
432

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

439
                arg_fido2_manual_flags &= ~FIDO2ENROLL_PIN_IF_NEEDED;
×
UNCOV
440
                SET_FLAG(arg_fido2_manual_flags, FIDO2ENROLL_PIN, r);
×
441

UNCOV
442
        } else if ((val = startswith(option, "fido2-up="))) {
×
443

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

450
                arg_fido2_manual_flags &= ~FIDO2ENROLL_UP_IF_NEEDED;
×
UNCOV
451
                SET_FLAG(arg_fido2_manual_flags, FIDO2ENROLL_UP, r);
×
452

UNCOV
453
        } else if ((val = startswith(option, "fido2-uv="))) {
×
454

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

461
                arg_fido2_manual_flags &= ~FIDO2ENROLL_UV_OMIT;
×
UNCOV
462
                SET_FLAG(arg_fido2_manual_flags, FIDO2ENROLL_UV, r);
×
463

UNCOV
464
        } else if ((val = startswith(option, "tpm2-device="))) {
×
465

466
                if (streq(val, "auto")) {
×
467
                        arg_tpm2_device = mfree(arg_tpm2_device);
×
UNCOV
468
                        arg_tpm2_device_auto = true;
×
469
                } else {
470
                        r = free_and_strdup(&arg_tpm2_device, val);
×
471
                        if (r < 0)
×
UNCOV
472
                                return log_oom();
×
473

UNCOV
474
                        arg_tpm2_device_auto = false;
×
475
                }
476

UNCOV
477
        } else if ((val = startswith(option, "tpm2-pcrs="))) {
×
478

479
                r = tpm2_parse_pcr_argument_to_mask(val, &arg_tpm2_pcr_mask);
×
UNCOV
480
                if (r < 0)
×
481
                        return r;
482

UNCOV
483
        } else if ((val = startswith(option, "tpm2-signature="))) {
×
484

485
                if (!path_is_absolute(val))
×
UNCOV
486
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
487
                                               "TPM2 signature path \"%s\" is not absolute, refusing.", val);
488

489
                r = free_and_strdup(&arg_tpm2_signature, val);
×
490
                if (r < 0)
×
UNCOV
491
                        return log_oom();
×
492

UNCOV
493
        } else if ((val = startswith(option, "tpm2-pin="))) {
×
494

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

UNCOV
501
                arg_tpm2_pin = r;
×
502

UNCOV
503
        } else if ((val = startswith(option, "tpm2-pcrlock="))) {
×
504

505
                if (!path_is_absolute(val))
×
UNCOV
506
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
507
                                               "TPM2 pcrlock policy path \"%s\" is not absolute, refusing.", val);
508

509
                r = free_and_strdup(&arg_tpm2_pcrlock, val);
×
510
                if (r < 0)
×
UNCOV
511
                        return log_oom();
×
512

513
        } else if ((val = startswith(option, "tpm2-measure-pcr="))) {
×
UNCOV
514
                unsigned pcr;
×
515

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

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

UNCOV
530
                arg_tpm2_measure_pcr = pcr;
×
531

UNCOV
532
        } else if ((val = startswith(option, "tpm2-measure-bank="))) {
×
533

534
#if HAVE_OPENSSL
UNCOV
535
                _cleanup_strv_free_ char **l = NULL;
×
536

537
                l = strv_split(optarg, ":");
×
538
                if (!l)
×
UNCOV
539
                        return log_oom();
×
540

541
                STRV_FOREACH(i, l) {
×
UNCOV
542
                        const EVP_MD *implementation;
×
543

544
                        implementation = EVP_get_digestbyname(*i);
×
545
                        if (!implementation)
×
UNCOV
546
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown bank '%s', refusing.", val);
×
547

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

UNCOV
555
        } else if ((val = startswith(option, "try-empty-password="))) {
×
556

557
                r = parse_boolean(val);
×
558
                if (r < 0) {
×
559
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
UNCOV
560
                        return 0;
×
561
                }
562

UNCOV
563
                arg_try_empty_password = r;
×
564

565
        } else if (streq(option, "try-empty-password"))
×
566
                arg_try_empty_password = true;
×
UNCOV
567
        else if ((val = startswith(option, "headless="))) {
×
568

569
                r = parse_boolean(val);
×
570
                if (r < 0) {
×
571
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
UNCOV
572
                        return 0;
×
573
                }
574

575
                SET_FLAG(arg_ask_password_flags, ASK_PASSWORD_HEADLESS, r);
×
576
        } else if (streq(option, "headless"))
×
UNCOV
577
                arg_ask_password_flags |= ASK_PASSWORD_HEADLESS;
×
578

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

581
                r = parse_sec_fix_0(val, &arg_token_timeout_usec);
×
582
                if (r < 0)
×
UNCOV
583
                        log_warning_errno(r, "Failed to parse %s, ignoring: %m", option);
×
584

UNCOV
585
        } else if ((val = startswith(option, "link-volume-key="))) {
×
586
#ifdef HAVE_CRYPT_SET_KEYRING_TO_LINK
587
                _cleanup_free_ char *keyring = NULL, *key_type = NULL, *key_description = NULL;
×
UNCOV
588
                const char *sep;
×
589

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

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

UNCOV
611
                sep += 2;
×
612

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

620
                        key_type = strndup(sep + 1, c - sep - 1);
×
621
                        if (!key_type)
×
UNCOV
622
                                return log_oom();
×
623

UNCOV
624
                        sep = c + 1;
×
625
                }
626

627
                key_description = strdup(sep);
×
628
                if (!key_description)
×
UNCOV
629
                        return log_oom();
×
630

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

640
        return 0;
641
}
642

643
static int parse_crypt_config(const char *options) {
×
UNCOV
644
        assert(options);
×
645

646
        for (;;) {
×
647
                _cleanup_free_ char *word = NULL;
×
UNCOV
648
                int r;
×
649

650
                r = extract_first_word(&options, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS | EXTRACT_UNESCAPE_SEPARATORS);
×
651
                if (r < 0)
×
652
                        return log_error_errno(r, "Failed to parse options: %m");
×
UNCOV
653
                if (r == 0)
×
654
                        break;
655

656
                r = parse_one_option(word);
×
UNCOV
657
                if (r < 0)
×
658
                        return r;
659
        }
660

661
        /* sanity-check options */
662
        if (arg_type && !streq(arg_type, CRYPT_PLAIN)) {
×
663
                if (arg_offset != 0)
×
664
                      log_warning("offset= ignored with type %s", arg_type);
×
665
                if (arg_skip != 0)
×
UNCOV
666
                      log_warning("skip= ignored with type %s", arg_type);
×
667
        }
668

UNCOV
669
        if (arg_pkcs11_uri || arg_pkcs11_uri_auto) {
×
670
                /* If password-cache was not configured explicitly, default to no cache for PKCS#11 */
671
                if (!arg_password_cache_set)
×
UNCOV
672
                        arg_ask_password_flags &= ~(ASK_PASSWORD_ACCEPT_CACHED|ASK_PASSWORD_PUSH_CACHE);
×
673

674
                /* This prevents future backward-compatibility issues if we decide to allow caching for PKCS#11 */
675
                if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_ACCEPT_CACHED))
×
UNCOV
676
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
677
                                               "Password cache is not supported for PKCS#11 security tokens.");
678
        }
679

680
        return 0;
681
}
682

683
static char* disk_description(const char *path) {
×
UNCOV
684
        static const char name_fields[] =
×
685
                "DM_NAME\0"
686
                "ID_MODEL_FROM_DATABASE\0"
687
                "ID_MODEL\0";
688

689
        _cleanup_(sd_device_unrefp) sd_device *device = NULL;
×
690
        const char *name;
×
UNCOV
691
        struct stat st;
×
692

UNCOV
693
        assert(path);
×
694

UNCOV
695
        if (stat(path, &st) < 0)
×
696
                return NULL;
697

UNCOV
698
        if (!S_ISBLK(st.st_mode))
×
699
                return NULL;
700

UNCOV
701
        if (sd_device_new_from_stat_rdev(&device, &st) < 0)
×
702
                return NULL;
703

704
        if (sd_device_get_property_value(device, "ID_PART_ENTRY_NAME", &name) >= 0) {
×
705
                _cleanup_free_ char *unescaped = NULL;
×
UNCOV
706
                ssize_t l;
×
707

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

712
                l = cunescape(name, UNESCAPE_RELAX, &unescaped);
×
713
                if (l < 0) {
×
714
                        log_debug_errno(l, "Failed to unescape ID_PART_ENTRY_NAME, skipping device: %m");
×
UNCOV
715
                        return NULL;
×
716
                }
717

718
                if (!isempty(unescaped) && !string_has_cc(unescaped, NULL))
×
UNCOV
719
                        return TAKE_PTR(unescaped);
×
720
        }
721

722
        /* These need no unescaping. */
723
        NULSTR_FOREACH(i, name_fields)
×
724
                if (sd_device_get_property_value(device, i, &name) >= 0 &&
×
725
                    !isempty(name))
×
UNCOV
726
                        return strdup(name);
×
727

728
        return NULL;
729
}
730

731
static char *disk_mount_point(const char *label) {
×
732
        _cleanup_free_ char *device = NULL;
×
733
        _cleanup_endmntent_ FILE *f = NULL;
×
UNCOV
734
        struct mntent *m;
×
735

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

738
        device = strjoin("/dev/mapper/", label);
×
UNCOV
739
        if (!device)
×
740
                return NULL;
741

742
        f = setmntent(fstab_path(), "re");
×
UNCOV
743
        if (!f)
×
744
                return NULL;
745

746
        while ((m = getmntent(f)))
×
747
                if (path_equal(m->mnt_fsname, device))
×
UNCOV
748
                        return strdup(m->mnt_dir);
×
749

750
        return NULL;
751
}
752

753
static char *friendly_disk_name(const char *src, const char *vol) {
×
754
        _cleanup_free_ char *description = NULL, *mount_point = NULL;
×
755
        char *name_buffer = NULL;
×
UNCOV
756
        int r;
×
757

758
        assert(src);
×
UNCOV
759
        assert(vol);
×
760

761
        description = disk_description(src);
×
UNCOV
762
        mount_point = disk_mount_point(vol);
×
763

764
        /* If the description string is simply the volume name, then let's not show this twice */
765
        if (description && streq(vol, description))
×
UNCOV
766
                description = mfree(description);
×
767

768
        if (mount_point && description)
×
769
                r = asprintf(&name_buffer, "%s (%s) on %s", description, vol, mount_point);
×
770
        else if (mount_point)
×
771
                r = asprintf(&name_buffer, "%s on %s", vol, mount_point);
×
772
        else if (description)
×
UNCOV
773
                r = asprintf(&name_buffer, "%s (%s)", description, vol);
×
774
        else
775
                return strdup(vol);
×
UNCOV
776
        if (r < 0)
×
777
                return NULL;
778

UNCOV
779
        return name_buffer;
×
780
}
781

782
static PassphraseType check_registered_passwords(struct crypt_device *cd) {
×
783
        _cleanup_free_ bool *slots = NULL;
×
784
        int slot_max;
×
UNCOV
785
        PassphraseType passphrase_type = PASSPHRASE_NONE;
×
786

UNCOV
787
        assert(cd);
×
788

789
        if (!streq_ptr(crypt_get_type(cd), CRYPT_LUKS2)) {
×
790
                log_debug("%s: not a LUKS2 device, only passphrases are supported", crypt_get_device_name(cd));
×
UNCOV
791
                return PASSPHRASE_REGULAR;
×
792
        }
793

794
        /* Search all used slots */
795
        assert_se((slot_max = crypt_keyslot_max(CRYPT_LUKS2)) > 0);
×
796
        slots = new(bool, slot_max);
×
797
        if (!slots)
×
UNCOV
798
                return log_oom();
×
799

800
        for (int slot = 0; slot < slot_max; slot++)
×
UNCOV
801
                slots[slot] = IN_SET(crypt_keyslot_status(cd, slot), CRYPT_SLOT_ACTIVE, CRYPT_SLOT_ACTIVE_LAST);
×
802

803
        /* Iterate all LUKS2 tokens and keep track of all their slots */
804
        for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
×
805
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
×
806
                const char *type;
×
807
                sd_json_variant *w, *z;
×
UNCOV
808
                int tk;
×
809

810
                tk = cryptsetup_get_token_as_json(cd, token, NULL, &v);
×
811
                if (IN_SET(tk, -ENOENT, -EINVAL))
×
812
                        continue;
×
813
                if (tk < 0) {
×
814
                        log_warning_errno(tk, "Failed to read JSON token data, ignoring: %m");
×
UNCOV
815
                        continue;
×
816
                }
817

818
                w = sd_json_variant_by_key(v, "type");
×
819
                if (!w || !sd_json_variant_is_string(w)) {
×
820
                        log_warning("Token JSON data lacks type field, ignoring.");
×
UNCOV
821
                        continue;
×
822
                }
823

824
                type = sd_json_variant_string(w);
×
UNCOV
825
                if (STR_IN_SET(type, "systemd-recovery", "systemd-pkcs11", "systemd-fido2", "systemd-tpm2")) {
×
826

827
                        /* At least exists one recovery key */
828
                        if (streq(type, "systemd-recovery"))
×
UNCOV
829
                                passphrase_type |= PASSPHRASE_RECOVERY_KEY;
×
830

831
                        w = sd_json_variant_by_key(v, "keyslots");
×
832
                        if (!w || !sd_json_variant_is_array(w)) {
×
833
                                log_warning("Token JSON data lacks keyslots field, ignoring.");
×
UNCOV
834
                                continue;
×
835
                        }
836

837
                        JSON_VARIANT_ARRAY_FOREACH(z, w) {
×
838
                                unsigned u;
×
UNCOV
839
                                int at;
×
840

841
                                if (!sd_json_variant_is_string(z)) {
×
842
                                        log_warning("Token JSON data's keyslot field is not an array of strings, ignoring.");
×
UNCOV
843
                                        continue;
×
844
                                }
845

846
                                at = safe_atou(sd_json_variant_string(z), &u);
×
847
                                if (at < 0) {
×
848
                                        log_warning_errno(at, "Token JSON data's keyslot field is not an integer formatted as string, ignoring.");
×
UNCOV
849
                                        continue;
×
850
                                }
851

852
                                if (u >= (unsigned) slot_max) {
×
853
                                        log_warning_errno(at, "Token JSON data's keyslot field exceeds the maximum value allowed, ignoring.");
×
UNCOV
854
                                        continue;
×
855
                                }
856

UNCOV
857
                                slots[u] = false;
×
858
                        }
859
                }
860
        }
861

862
        /* Check if any of the slots is not referenced by systemd tokens */
863
        for (int slot = 0; slot < slot_max; slot++)
×
864
                if (slots[slot]) {
×
865
                        passphrase_type |= PASSPHRASE_REGULAR;
×
UNCOV
866
                        break;
×
867
                }
868

869
        /* All the slots are referenced by systemd tokens, so if a recovery key is not enrolled,
870
         * we will not be able to enter a passphrase. */
871
        return passphrase_type;
872
}
873

UNCOV
874
static int get_password(
×
875
                const char *vol,
876
                const char *src,
877
                usec_t until,
878
                bool ignore_cached,
879
                PassphraseType passphrase_type,
880
                char ***ret) {
881

882
        _cleanup_free_ char *friendly = NULL, *text = NULL, *disk_path = NULL, *id = NULL;
×
883
        _cleanup_strv_free_erase_ char **passwords = NULL;
×
884
        AskPasswordFlags flags = arg_ask_password_flags;
×
UNCOV
885
        int r;
×
886

887
        assert(vol);
×
888
        assert(src);
×
UNCOV
889
        assert(ret);
×
890

891
        if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_HEADLESS))
×
UNCOV
892
                return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Password querying disabled via 'headless' option.");
×
893

894
        friendly = friendly_disk_name(src, vol);
×
895
        if (!friendly)
×
UNCOV
896
                return log_oom();
×
897

898
        if (asprintf(&text, "Please enter %s for disk %s:", passphrase_type_to_string(passphrase_type), friendly) < 0)
×
UNCOV
899
                return log_oom();
×
900

901
        disk_path = cescape(src);
×
902
        if (!disk_path)
×
UNCOV
903
                return log_oom();
×
904

905
        id = strjoin("cryptsetup:", disk_path);
×
906
        if (!id)
×
UNCOV
907
                return log_oom();
×
908

UNCOV
909
        AskPasswordRequest req = {
×
910
                .tty_fd = -EBADF,
911
                .message = text,
912
                .icon = "drive-harddisk",
913
                .id = id,
914
                .keyring = "cryptsetup",
915
                .credential = "cryptsetup.passphrase",
916
                .until = until,
917
                .hup_fd = -EBADF,
918
        };
919

920
        if (ignore_cached)
×
UNCOV
921
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
×
922

923
        r = ask_password_auto(&req, flags, &passwords);
×
924
        if (r < 0)
×
UNCOV
925
                return log_error_errno(r, "Failed to query password: %m");
×
926

927
        if (arg_verify) {
×
UNCOV
928
                _cleanup_strv_free_erase_ char **passwords2 = NULL;
×
929

UNCOV
930
                assert(strv_length(passwords) == 1);
×
931

932
                text = mfree(text);
×
933
                if (asprintf(&text, "Please enter %s for disk %s (verification):", passphrase_type_to_string(passphrase_type), friendly) < 0)
×
UNCOV
934
                        return log_oom();
×
935

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

941
                req.message = text;
×
UNCOV
942
                req.id = id;
×
943

944
                r = ask_password_auto(&req, flags, &passwords2);
×
945
                if (r < 0)
×
UNCOV
946
                        return log_error_errno(r, "Failed to query verification password: %m");
×
947

UNCOV
948
                assert(strv_length(passwords2) == 1);
×
949

950
                if (!streq(passwords[0], passwords2[0]))
×
UNCOV
951
                        return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN),
×
952
                                                 "Passwords did not match, retrying.");
953
        }
954

UNCOV
955
        strv_uniq(passwords);
×
956

957
        STRV_FOREACH(p, passwords) {
×
UNCOV
958
                char *c;
×
959

960
                if (strlen(*p)+1 >= arg_key_size)
×
UNCOV
961
                        continue;
×
962

963
                /* Pad password if necessary */
964
                c = new(char, arg_key_size);
×
965
                if (!c)
×
UNCOV
966
                        return log_oom();
×
967

968
                strncpy(c, *p, arg_key_size);
×
969
                erase_and_free(*p);
×
UNCOV
970
                *p = TAKE_PTR(c);
×
971
        }
972

UNCOV
973
        *ret = TAKE_PTR(passwords);
×
974

UNCOV
975
        return 0;
×
976
}
977

UNCOV
978
static int measure_volume_key(
×
979
                struct crypt_device *cd,
980
                const char *name,
981
                const void *volume_key,
982
                size_t volume_key_size) {
983

UNCOV
984
        int r;
×
985

986
        assert(cd);
×
987
        assert(name);
×
988
        assert(volume_key);
×
UNCOV
989
        assert(volume_key_size > 0);
×
990

991
        if (arg_tpm2_measure_pcr == UINT_MAX) {
×
992
                log_debug("Not measuring volume key, deactivated.");
×
UNCOV
993
                return 0;
×
994
        }
995

996
        r = efi_measured_uki(LOG_WARNING);
×
UNCOV
997
        if (r < 0)
×
998
                return r;
999
        if (r == 0) {
×
1000
                log_debug("Kernel stub did not measure kernel image into the expected PCR, skipping userspace measurement, too.");
×
UNCOV
1001
                return 0;
×
1002
        }
1003

1004
#if HAVE_TPM2
1005
        _cleanup_(tpm2_context_unrefp) Tpm2Context *c = NULL;
×
1006
        r = tpm2_context_new_or_warn(arg_tpm2_device, &c);
×
UNCOV
1007
        if (r < 0)
×
1008
                return r;
1009

1010
        _cleanup_strv_free_ char **l = NULL;
×
1011
        if (strv_isempty(arg_tpm2_measure_banks)) {
×
1012
                r = tpm2_get_good_pcr_banks_strv(c, UINT32_C(1) << arg_tpm2_measure_pcr, &l);
×
1013
                if (r < 0)
×
UNCOV
1014
                        return log_error_errno(r, "Could not verify pcr banks: %m");
×
1015
        }
1016

1017
        _cleanup_free_ char *joined = strv_join(l ?: arg_tpm2_measure_banks, ", ");
×
1018
        if (!joined)
×
UNCOV
1019
                return log_oom();
×
1020

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

1025
        _cleanup_free_ char *escaped = NULL;
×
1026
        escaped = xescape(name, ":"); /* avoid ambiguity around ":" once we join things below */
×
1027
        if (!escaped)
×
UNCOV
1028
                return log_oom();
×
1029

1030
        _cleanup_free_ char *s = NULL;
×
1031
        s = strjoin("cryptsetup:", escaped, ":", strempty(crypt_get_uuid(cd)));
×
1032
        if (!s)
×
UNCOV
1033
                return log_oom();
×
1034

1035
        r = tpm2_extend_bytes(c, l ?: arg_tpm2_measure_banks, arg_tpm2_measure_pcr, s, SIZE_MAX, volume_key, volume_key_size, TPM2_EVENT_VOLUME_KEY, s);
×
1036
        if (r < 0)
×
UNCOV
1037
                return log_error_errno(r, "Could not extend PCR: %m");
×
1038

UNCOV
1039
        log_struct(LOG_INFO,
×
1040
                   "MESSAGE_ID=" SD_MESSAGE_TPM_PCR_EXTEND_STR,
1041
                   LOG_MESSAGE("Successfully extended PCR index %u with '%s' and volume key (banks %s).", arg_tpm2_measure_pcr, s, joined),
1042
                   "MEASURING=%s", s,
1043
                   "PCR=%u", arg_tpm2_measure_pcr,
1044
                   "BANKS=%s", joined);
1045

1046
        return 0;
1047
#else
1048
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support disabled, not measuring.");
1049
#endif
1050
}
1051

1052
static int log_external_activation(int r, const char *volume) {
×
UNCOV
1053
        assert(volume);
×
1054

1055
        log_notice_errno(r, "Volume '%s' has been activated externally while we have been trying to activate it.", volume);
×
UNCOV
1056
        return 0;
×
1057
}
1058

UNCOV
1059
static int measured_crypt_activate_by_volume_key(
×
1060
                struct crypt_device *cd,
1061
                const char *name,
1062
                const void *volume_key,
1063
                size_t volume_key_size,
1064
                uint32_t flags) {
1065

UNCOV
1066
        int r;
×
1067

1068
        assert(cd);
×
UNCOV
1069
        assert(name);
×
1070

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

1073
        r = crypt_activate_by_volume_key(cd, name, volume_key, volume_key_size, flags);
×
1074
        if (r == -EEXIST) /* volume is already active */
×
1075
                return log_external_activation(r, name);
×
UNCOV
1076
        if (r < 0)
×
1077
                return r;
1078

1079
        if (volume_key_size == 0) {
×
1080
                log_debug("Not measuring volume key, none specified.");
×
UNCOV
1081
                return r;
×
1082
        }
1083

1084
        (void) measure_volume_key(cd, name, volume_key, volume_key_size); /* OK if fails */
×
UNCOV
1085
        return r;
×
1086
}
1087

UNCOV
1088
static int measured_crypt_activate_by_passphrase(
×
1089
                struct crypt_device *cd,
1090
                const char *name,
1091
                int keyslot,
1092
                const char *passphrase,
1093
                size_t passphrase_size,
1094
                uint32_t flags) {
1095

1096
        _cleanup_(erase_and_freep) void *vk = NULL;
×
1097
        size_t vks;
×
UNCOV
1098
        int r;
×
1099

UNCOV
1100
        assert(cd);
×
1101

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

1107
        if (arg_tpm2_measure_pcr == UINT_MAX) {
×
1108
                log_debug("Not measuring volume key, deactivated.");
×
UNCOV
1109
                goto shortcut;
×
1110
        }
1111

1112
        r = crypt_get_volume_key_size(cd);
×
UNCOV
1113
        if (r < 0)
×
1114
                return r;
1115
        if (r == 0) {
×
1116
                log_debug("Not measuring volume key, none defined.");
×
UNCOV
1117
                goto shortcut;
×
1118
        }
1119

1120
        vk = malloc(vks = r);
×
UNCOV
1121
        if (!vk)
×
1122
                return -ENOMEM;
1123

1124
        r = crypt_volume_key_get(cd, keyslot, vk, &vks, passphrase, passphrase_size);
×
UNCOV
1125
        if (r < 0)
×
1126
                return r;
1127

UNCOV
1128
        return measured_crypt_activate_by_volume_key(cd, name, vk, vks, flags);
×
1129

1130
shortcut:
×
1131
        r = crypt_activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags);
×
1132
        if (r == -EEXIST) /* volume is already active */
×
UNCOV
1133
                return log_external_activation(r, name);
×
1134
        return r;
1135
}
1136

UNCOV
1137
static int attach_tcrypt(
×
1138
                struct crypt_device *cd,
1139
                const char *name,
1140
                TokenType token_type,
1141
                const char *key_file,
1142
                const struct iovec *key_data,
1143
                char **passwords,
1144
                uint32_t flags) {
1145

1146
        int r = 0;
×
1147
        _cleanup_(erase_and_freep) char *passphrase = NULL;
×
UNCOV
1148
        struct crypt_params_tcrypt params = {
×
1149
                .flags = CRYPT_TCRYPT_LEGACY_MODES,
1150
                .keyfiles = (const char **)arg_tcrypt_keyfiles,
UNCOV
1151
                .keyfiles_count = strv_length(arg_tcrypt_keyfiles)
×
1152
        };
1153

1154
        assert(cd);
×
1155
        assert(name);
×
UNCOV
1156
        assert(key_file || key_data || !strv_isempty(passwords));
×
1157

UNCOV
1158
        if (token_type >= 0)
×
1159
                /* Ask for a regular password */
UNCOV
1160
                return log_error_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1161
                                       "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 support.");
1162

1163
        if (arg_tcrypt_hidden)
×
UNCOV
1164
                params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
×
1165

1166
        if (arg_tcrypt_system)
×
UNCOV
1167
                params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
×
1168

1169
        if (arg_tcrypt_veracrypt)
×
UNCOV
1170
                params.flags |= CRYPT_TCRYPT_VERA_MODES;
×
1171

1172
        if (arg_tcrypt_veracrypt && arg_tcrypt_veracrypt_pim != 0)
×
UNCOV
1173
                params.veracrypt_pim = arg_tcrypt_veracrypt_pim;
×
1174

1175
        if (key_data) {
×
1176
                params.passphrase = key_data->iov_base;
×
1177
                params.passphrase_size = key_data->iov_len;
×
1178
                r = crypt_load(cd, CRYPT_TCRYPT, &params);
×
1179
        } else if (key_file) {
×
1180
                r = read_one_line_file(key_file, &passphrase);
×
1181
                if (r < 0) {
×
1182
                        log_error_errno(r, "Failed to read password file '%s': %m", key_file);
×
UNCOV
1183
                        return -EAGAIN; /* log with the actual error, but return EAGAIN */
×
1184
                }
1185
                params.passphrase = passphrase;
×
1186
                params.passphrase_size = strlen(passphrase);
×
UNCOV
1187
                r = crypt_load(cd, CRYPT_TCRYPT, &params);
×
1188
        } else {
1189
                r = -EINVAL;
1190
                STRV_FOREACH(p, passwords){
×
1191
                        params.passphrase = *p;
×
1192
                        params.passphrase_size = strlen(*p);
×
1193
                        r = crypt_load(cd, CRYPT_TCRYPT, &params);
×
UNCOV
1194
                        if (r >= 0)
×
1195
                                break;
1196
                }
1197
        }
1198

1199
        if (r < 0) {
×
1200
                if (r == -EPERM) {
×
1201
                        if (key_data)
×
1202
                                log_error_errno(r, "Failed to activate using discovered key. (Key not correct?)");
×
1203
                        else if (key_file)
×
UNCOV
1204
                                log_error_errno(r, "Failed to activate using password file '%s'. (Key data not correct?)", key_file);
×
1205
                        else
UNCOV
1206
                                log_error_errno(r, "Failed to activate using supplied passwords.");
×
1207

UNCOV
1208
                        return r;
×
1209
                }
1210

UNCOV
1211
                return log_error_errno(r, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd));
×
1212
        }
1213

1214
        r = measured_crypt_activate_by_volume_key(cd, name, NULL, 0, flags);
×
1215
        if (r < 0)
×
UNCOV
1216
                return log_error_errno(r, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd));
×
1217

1218
        return 0;
1219
}
1220

1221
static char *make_bindname(const char *volume, TokenType token_type) {
×
1222
        const char *token_type_name = token_type_to_string(token_type), *suffix;
×
1223
        char *bindname;
×
UNCOV
1224
        int r;
×
1225

UNCOV
1226
        switch (token_type) {
×
1227

1228
        case TOKEN_FIDO2:
1229
                suffix = "-salt";
1230
                break;
1231

1232
        default:
UNCOV
1233
                suffix = NULL;
×
1234
        }
1235

UNCOV
1236
        r = asprintf(&bindname,
×
1237
                     "@%" PRIx64"/cryptsetup%s%s%s/%s",
1238
                     random_u64(),
1239
                     token_type_name ? "-" : "",
1240
                     strempty(token_type_name),
1241
                     strempty(suffix),
1242
                     volume);
1243
        if (r < 0)
×
UNCOV
1244
                return NULL;
×
1245

UNCOV
1246
        return bindname;
×
1247
}
1248

UNCOV
1249
static int make_security_device_monitor(
×
1250
                sd_event **ret_event,
1251
                sd_device_monitor **ret_monitor) {
1252
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1253
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
UNCOV
1254
        int r;
×
1255

1256
        assert(ret_event);
×
UNCOV
1257
        assert(ret_monitor);
×
1258

1259
        /* Waits for a device with "security-device" tag to show up in udev */
UNCOV
1260
        log_debug("Creating device monitor for tag 'security-device' with timeout %s",
×
1261
                  FORMAT_TIMESPAN(arg_token_timeout_usec, 1*USEC_PER_SEC));
1262

1263
        r = sd_event_default(&event);
×
1264
        if (r < 0)
×
UNCOV
1265
                return log_error_errno(r, "Failed to allocate event loop: %m");
×
1266

1267
        r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
×
1268
        if (r < 0)
×
UNCOV
1269
                return log_error_errno(r, "Failed to install timeout event source: %m");
×
1270

1271
        r = sd_device_monitor_new(&monitor);
×
1272
        if (r < 0)
×
UNCOV
1273
                return log_error_errno(r, "Failed to allocate device monitor: %m");
×
1274

UNCOV
1275
        (void) sd_device_monitor_set_description(monitor, "security-device");
×
1276

1277
        r = sd_device_monitor_filter_add_match_tag(monitor, "security-device");
×
1278
        if (r < 0)
×
UNCOV
1279
                return log_error_errno(r, "Failed to configure device monitor: %m");
×
1280

1281
        r = sd_device_monitor_attach_event(monitor, event);
×
1282
        if (r < 0)
×
UNCOV
1283
                return log_error_errno(r, "Failed to attach device monitor: %m");
×
1284

1285
        r = sd_device_monitor_start(monitor, NULL, NULL);
×
1286
        if (r < 0)
×
UNCOV
1287
                return log_error_errno(r, "Failed to start device monitor: %m");
×
1288

1289
        *ret_event = TAKE_PTR(event);
×
1290
        *ret_monitor = TAKE_PTR(monitor);
×
UNCOV
1291
        return 0;
×
1292
}
1293

UNCOV
1294
static int run_security_device_monitor(
×
1295
                sd_event *event,
1296
                sd_device_monitor *monitor) {
1297
        bool processed = false;
×
UNCOV
1298
        int r;
×
1299

1300
        assert(event);
×
UNCOV
1301
        assert(monitor);
×
1302

1303
        /* Runs the event loop for the device monitor until either something happens, or the timeout is
1304
         * hit. */
1305

1306
        for (;;) {
×
UNCOV
1307
                int x;
×
1308

1309
                r = sd_event_get_exit_code(event, &x);
×
1310
                if (r < 0) {
×
1311
                        if (r != -ENODATA)
×
UNCOV
1312
                                return log_error_errno(r, "Failed to query exit code from event loop: %m");
×
1313

1314
                        /* On ENODATA we aren't told to exit yet. */
1315
                } else {
1316
                        assert(x == -ETIMEDOUT);
×
UNCOV
1317
                        return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1318
                                                "Timed out waiting for security device, aborting security device based authentication attempt.");
1319
                }
1320

1321
                /* Wait for one event, and then eat all subsequent events until there are no further ones */
1322
                r = sd_event_run(event, processed ? 0 : UINT64_MAX);
×
1323
                if (r < 0)
×
1324
                        return log_error_errno(r, "Failed to run event loop: %m");
×
UNCOV
1325
                if (r == 0) /* no events queued anymore */
×
1326
                        return 0;
1327

UNCOV
1328
                processed = true;
×
1329
        }
1330
}
1331

UNCOV
1332
static bool use_token_plugins(void) {
×
1333

1334
#if HAVE_TPM2
1335
        /* Currently, there's no way for us to query the volume key when plugins are used. Hence don't use
1336
         * plugins, if measurement has been requested. */
UNCOV
1337
        if (arg_tpm2_measure_pcr != UINT_MAX)
×
1338
                return false;
1339
#endif
1340

1341
        /* Disable tokens if we're in FIDO2 mode with manual parameters. */
UNCOV
1342
        if (arg_fido2_cid)
×
1343
                return false;
1344

1345
#if HAVE_LIBCRYPTSETUP_PLUGINS
UNCOV
1346
        int r;
×
1347

1348
        /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
1349
        r = getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
×
1350
        if (r < 0 && r != -ENXIO)
×
1351
                log_debug_errno(r, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
×
UNCOV
1352
        if (r == 0)
×
1353
                return false;
1354

UNCOV
1355
        return crypt_token_external_path();
×
1356
#else
1357
        return false;
1358
#endif
1359
}
1360

1361
#if HAVE_LIBCRYPTSETUP_PLUGINS
1362
static int acquire_pins_from_env_variable(char ***ret_pins) {
×
1363
        _cleanup_(erase_and_freep) char *envpin = NULL;
×
1364
        _cleanup_strv_free_erase_ char **pins = NULL;
×
UNCOV
1365
        int r;
×
1366

UNCOV
1367
        assert(ret_pins);
×
1368

1369
        r = getenv_steal_erase("PIN", &envpin);
×
1370
        if (r < 0)
×
1371
                return log_error_errno(r, "Failed to acquire PIN from environment: %m");
×
1372
        if (r > 0) {
×
1373
                pins = strv_new(envpin);
×
1374
                if (!pins)
×
UNCOV
1375
                        return log_oom();
×
1376
        }
1377

UNCOV
1378
        *ret_pins = TAKE_PTR(pins);
×
1379

UNCOV
1380
        return 0;
×
1381
}
1382
#endif
1383

UNCOV
1384
static int crypt_activate_by_token_pin_ask_password(
×
1385
                struct crypt_device *cd,
1386
                const char *name,
1387
                const char *type,
1388
                usec_t until,
1389
                void *userdata,
1390
                uint32_t activation_flags,
1391
                const char *message,
1392
                const char *keyring,
1393
                const char *credential) {
1394

1395
#if HAVE_LIBCRYPTSETUP_PLUGINS
1396
        AskPasswordFlags flags = arg_ask_password_flags;
×
1397
        _cleanup_strv_free_erase_ char **pins = NULL;
×
UNCOV
1398
        int r;
×
1399

1400
        r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, /* pin=*/ NULL, /* pin_size= */ 0, userdata, activation_flags);
×
UNCOV
1401
        if (r > 0) /* returns unlocked keyslot id on success */
×
1402
                return 0;
1403
        if (r == -EEXIST) /* volume is already active */
×
1404
                return log_external_activation(r, name);
×
UNCOV
1405
        if (r != -ENOANO) /* needs pin or pin is wrong */
×
1406
                return r;
1407

1408
        r = acquire_pins_from_env_variable(&pins);
×
UNCOV
1409
        if (r < 0)
×
1410
                return r;
1411

1412
        STRV_FOREACH(p, pins) {
×
1413
                r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
×
UNCOV
1414
                if (r > 0) /* returns unlocked keyslot id on success */
×
1415
                        return 0;
1416
                if (r == -EEXIST) /* volume is already active */
×
1417
                        return log_external_activation(r, name);
×
UNCOV
1418
                if (r != -ENOANO) /* needs pin or pin is wrong */
×
1419
                        return r;
1420
        }
1421

1422
        if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_HEADLESS))
×
UNCOV
1423
                return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
×
1424

1425
        for (;;) {
×
UNCOV
1426
                pins = strv_free_erase(pins);
×
1427

UNCOV
1428
                AskPasswordRequest req = {
×
1429
                        .tty_fd = -EBADF,
1430
                        .message = message,
1431
                        .icon = "drive-harddisk",
1432
                        .keyring = keyring,
1433
                        .credential = credential,
1434
                        .until = until,
1435
                        .hup_fd = -EBADF,
1436
                };
1437

1438
                r = ask_password_auto(&req, flags, &pins);
×
1439
                if (r < 0)
×
UNCOV
1440
                        return r;
×
1441

1442
                STRV_FOREACH(p, pins) {
×
1443
                        r = crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
×
UNCOV
1444
                        if (r > 0) /* returns unlocked keyslot id on success */
×
1445
                                return 0;
1446
                        if (r == -EEXIST) /* volume is already active */
×
1447
                                return log_external_activation(r, name);
×
UNCOV
1448
                        if (r != -ENOANO) /* needs pin or pin is wrong */
×
1449
                                return r;
1450
                }
1451

UNCOV
1452
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
×
1453
        }
1454
        return r;
1455
#else
1456
        return -EOPNOTSUPP;
1457
#endif
1458
}
1459

UNCOV
1460
static int attach_luks2_by_fido2_via_plugin(
×
1461
                struct crypt_device *cd,
1462
                const char *name,
1463
                usec_t until,
1464
                void *userdata,
1465
                uint32_t activation_flags) {
1466

UNCOV
1467
        return crypt_activate_by_token_pin_ask_password(
×
1468
                        cd,
1469
                        name,
1470
                        "systemd-fido2",
1471
                        until,
1472
                        userdata,
1473
                        activation_flags,
1474
                        "Please enter security token PIN:",
1475
                        "fido2-pin",
1476
                        "cryptsetup.fido2-pin");
1477
}
1478

UNCOV
1479
static int attach_luks_or_plain_or_bitlk_by_fido2(
×
1480
                struct crypt_device *cd,
1481
                const char *name,
1482
                const char *key_file,
1483
                const struct iovec *key_data,
1484
                usec_t until,
1485
                uint32_t flags,
1486
                bool pass_volume_key) {
1487

1488
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1489
        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
×
1490
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1491
        size_t decrypted_key_size;
×
1492
        _cleanup_free_ char *friendly = NULL;
×
1493
        int keyslot = arg_key_slot, r;
×
UNCOV
1494
        bool use_libcryptsetup_plugin = use_token_plugins();
×
1495

1496
        assert(cd);
×
1497
        assert(name);
×
UNCOV
1498
        assert(arg_fido2_device || arg_fido2_device_auto);
×
1499

1500
        if (arg_fido2_cid && !key_file && !iovec_is_set(key_data))
×
UNCOV
1501
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1502
                                        "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
1503

1504
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
×
1505
        if (!friendly)
×
UNCOV
1506
                return log_oom();
×
1507

1508
        for (;;) {
×
1509
                if (use_libcryptsetup_plugin && !arg_fido2_cid) {
×
1510
                        r = attach_luks2_by_fido2_via_plugin(cd, name, until, arg_fido2_device, flags);
×
1511
                        if (IN_SET(r, -ENOTUNIQ, -ENXIO, -ENOENT))
×
UNCOV
1512
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1513
                                                       "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
1514

1515
                } else {
1516
                        if (arg_fido2_cid)
×
UNCOV
1517
                                r = acquire_fido2_key(
×
1518
                                                name,
1519
                                                friendly,
1520
                                                arg_fido2_device,
1521
                                                arg_fido2_rp_id,
1522
                                                arg_fido2_cid, arg_fido2_cid_size,
1523
                                                key_file, arg_keyfile_size, arg_keyfile_offset,
1524
                                                key_data,
1525
                                                until,
1526
                                                arg_fido2_manual_flags,
1527
                                                "cryptsetup.fido2-pin",
1528
                                                arg_ask_password_flags,
1529
                                                &decrypted_key,
1530
                                                &decrypted_key_size);
1531
                        else
UNCOV
1532
                                r = acquire_fido2_key_auto(
×
1533
                                                cd,
1534
                                                name,
1535
                                                friendly,
1536
                                                arg_fido2_device,
1537
                                                until,
1538
                                                "cryptsetup.fido2-pin",
1539
                                                arg_ask_password_flags,
1540
                                                &decrypted_key,
1541
                                                &decrypted_key_size);
UNCOV
1542
                        if (r >= 0)
×
1543
                                break;
1544
                }
1545

UNCOV
1546
                if (r != -EAGAIN) /* EAGAIN means: token not found */
×
1547
                        return r;
1548

UNCOV
1549
                if (!monitor) {
×
1550
                        /* We didn't find the token. In this case, watch for it via udev. Let's
1551
                         * create an event loop and monitor first. */
1552

UNCOV
1553
                        assert(!event);
×
1554

1555
                        r = make_security_device_monitor(&event, &monitor);
×
UNCOV
1556
                        if (r < 0)
×
1557
                                return r;
1558

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

1561
                        /* Let's immediately rescan in case the token appeared in the time we needed
1562
                         * to create and configure the monitor */
UNCOV
1563
                        continue;
×
1564
                }
1565

1566
                r = run_security_device_monitor(event, monitor);
×
UNCOV
1567
                if (r < 0)
×
1568
                        return r;
1569

UNCOV
1570
                log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
×
1571
        }
1572

1573
        if (pass_volume_key)
×
UNCOV
1574
                r = measured_crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
×
1575
        else {
1576
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
×
UNCOV
1577
                ssize_t base64_encoded_size;
×
1578

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

1581
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
×
1582
                if (base64_encoded_size < 0)
×
UNCOV
1583
                        return log_oom();
×
1584

UNCOV
1585
                r = measured_crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, base64_encoded_size, flags);
×
1586
        }
1587
        if (r == -EPERM) {
×
1588
                log_error_errno(r, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
×
UNCOV
1589
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
1590
        }
1591
        if (r < 0)
×
UNCOV
1592
                return log_error_errno(r, "Failed to activate with FIDO2 acquired key: %m");
×
1593

1594
        return 0;
1595
}
1596

UNCOV
1597
static int attach_luks2_by_pkcs11_via_plugin(
×
1598
                struct crypt_device *cd,
1599
                const char *name,
1600
                const char *friendly_name,
1601
                usec_t until,
1602
                const char *askpw_credential,
1603
                uint32_t flags) {
1604

1605
#if HAVE_LIBCRYPTSETUP_PLUGINS
UNCOV
1606
        int r;
×
1607

1608
        if (!streq_ptr(crypt_get_type(cd), CRYPT_LUKS2))
×
UNCOV
1609
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Automatic PKCS#11 metadata requires LUKS2 device.");
×
1610

UNCOV
1611
        systemd_pkcs11_plugin_params params = {
×
1612
                .friendly_name = friendly_name,
1613
                .until = until,
1614
                .askpw_credential = askpw_credential,
1615
                .askpw_flags = arg_ask_password_flags,
1616
        };
1617

1618
        r = crypt_activate_by_token_pin(cd, name, "systemd-pkcs11", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
×
UNCOV
1619
        if (r > 0) /* returns unlocked keyslot id on success */
×
1620
                r = 0;
1621
        if (r == -EEXIST) /* volume is already active */
×
UNCOV
1622
                r = log_external_activation(r, name);
×
1623

1624
        return r;
1625
#else
1626
        return -EOPNOTSUPP;
1627
#endif
1628
}
1629

UNCOV
1630
static int attach_luks_or_plain_or_bitlk_by_pkcs11(
×
1631
                struct crypt_device *cd,
1632
                const char *name,
1633
                const char *key_file,
1634
                const struct iovec *key_data,
1635
                usec_t until,
1636
                uint32_t flags,
1637
                bool pass_volume_key) {
1638

1639
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1640
        _cleanup_free_ char *friendly = NULL, *discovered_uri = NULL;
×
1641
        size_t decrypted_key_size = 0, discovered_key_size = 0;
×
1642
        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
×
1643
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1644
        _cleanup_free_ void *discovered_key = NULL;
×
1645
        struct iovec discovered_key_data = {};
×
1646
        int keyslot = arg_key_slot, r;
×
1647
        const char *uri = NULL;
×
UNCOV
1648
        bool use_libcryptsetup_plugin = use_token_plugins();
×
1649

1650
        assert(cd);
×
1651
        assert(name);
×
UNCOV
1652
        assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
×
1653

1654
        if (arg_pkcs11_uri_auto) {
×
1655
                if (!use_libcryptsetup_plugin) {
×
1656
                        r = find_pkcs11_auto_data(cd, &discovered_uri, &discovered_key, &discovered_key_size, &keyslot);
×
1657
                        if (IN_SET(r, -ENOTUNIQ, -ENXIO))
×
UNCOV
1658
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1659
                                                       "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
UNCOV
1660
                        if (r < 0)
×
1661
                                return r;
1662

1663
                        uri = discovered_uri;
×
1664
                        discovered_key_data = IOVEC_MAKE(discovered_key, discovered_key_size);
×
UNCOV
1665
                        key_data = &discovered_key_data;
×
1666
                }
1667
        } else {
UNCOV
1668
                uri = arg_pkcs11_uri;
×
1669

1670
                if (!key_file && !iovec_is_set(key_data))
×
UNCOV
1671
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing.");
×
1672
        }
1673

1674
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
×
1675
        if (!friendly)
×
UNCOV
1676
                return log_oom();
×
1677

1678
        for (;;) {
×
1679
                if (use_libcryptsetup_plugin && arg_pkcs11_uri_auto)
×
UNCOV
1680
                        r = attach_luks2_by_pkcs11_via_plugin(
×
1681
                                        cd,
1682
                                        name,
1683
                                        friendly,
1684
                                        until,
1685
                                        "cryptsetup.pkcs11-pin",
1686
                                        flags);
1687
                else {
UNCOV
1688
                        r = decrypt_pkcs11_key(
×
1689
                                        name,
1690
                                        friendly,
1691
                                        uri,
1692
                                        key_file, arg_keyfile_size, arg_keyfile_offset,
1693
                                        key_data,
1694
                                        until,
1695
                                        arg_ask_password_flags,
1696
                                        &decrypted_key, &decrypted_key_size);
UNCOV
1697
                        if (r >= 0)
×
1698
                                break;
1699
                }
1700

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

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

UNCOV
1708
                        assert(!event);
×
1709

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

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

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

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

UNCOV
1726
                log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
×
1727
        }
UNCOV
1728
        assert(decrypted_key);
×
1729

1730
        if (pass_volume_key)
×
UNCOV
1731
                r = measured_crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags);
×
1732
        else {
1733
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
×
UNCOV
1734
                ssize_t base64_encoded_size;
×
1735

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

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

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

1757
        return 0;
1758
}
1759

UNCOV
1760
static int make_tpm2_device_monitor(
×
1761
                sd_event **ret_event,
1762
                sd_device_monitor **ret_monitor) {
1763

1764
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1765
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
UNCOV
1766
        int r;
×
1767

1768
        assert(ret_event);
×
UNCOV
1769
        assert(ret_monitor);
×
1770

1771
        r = sd_event_default(&event);
×
1772
        if (r < 0)
×
UNCOV
1773
                return log_error_errno(r, "Failed to allocate event loop: %m");
×
1774

1775
        r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
×
1776
        if (r < 0)
×
UNCOV
1777
                return log_error_errno(r, "Failed to install timeout event source: %m");
×
1778

1779
        r = sd_device_monitor_new(&monitor);
×
1780
        if (r < 0)
×
UNCOV
1781
                return log_error_errno(r, "Failed to allocate device monitor: %m");
×
1782

UNCOV
1783
        (void) sd_device_monitor_set_description(monitor, "tpmrm");
×
1784

1785
        r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "tpmrm", NULL);
×
1786
        if (r < 0)
×
UNCOV
1787
                return log_error_errno(r, "Failed to configure device monitor: %m");
×
1788

1789
        r = sd_device_monitor_attach_event(monitor, event);
×
1790
        if (r < 0)
×
UNCOV
1791
                return log_error_errno(r, "Failed to attach device monitor: %m");
×
1792

1793
        r = sd_device_monitor_start(monitor, NULL, NULL);
×
1794
        if (r < 0)
×
UNCOV
1795
                return log_error_errno(r, "Failed to start device monitor: %m");
×
1796

1797
        *ret_event = TAKE_PTR(event);
×
1798
        *ret_monitor = TAKE_PTR(monitor);
×
UNCOV
1799
        return 0;
×
1800
}
1801

UNCOV
1802
static int attach_luks2_by_tpm2_via_plugin(
×
1803
                struct crypt_device *cd,
1804
                const char *name,
1805
                usec_t until,
1806
                uint32_t flags) {
1807

1808
#if HAVE_LIBCRYPTSETUP_PLUGINS
UNCOV
1809
        systemd_tpm2_plugin_params params = {
×
1810
                .search_pcr_mask = arg_tpm2_pcr_mask,
1811
                .device = arg_tpm2_device,
1812
                .signature_path = arg_tpm2_signature,
1813
                .pcrlock_path = arg_tpm2_pcrlock,
1814
        };
1815

1816
        if (!use_token_plugins())
×
UNCOV
1817
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
×
1818
                                       "libcryptsetup has external plugins support disabled.");
1819

UNCOV
1820
        return crypt_activate_by_token_pin_ask_password(
×
1821
                        cd,
1822
                        name,
1823
                        "systemd-tpm2",
1824
                        until,
1825
                        &params,
1826
                        flags,
1827
                        "Please enter TPM2 PIN:",
1828
                        "tpm2-pin",
1829
                        "cryptsetup.tpm2-pin");
1830
#else
1831
        return -EOPNOTSUPP;
1832
#endif
1833
}
1834

UNCOV
1835
static int attach_luks_or_plain_or_bitlk_by_tpm2(
×
1836
                struct crypt_device *cd,
1837
                const char *name,
1838
                const char *key_file,
1839
                const struct iovec *key_data,
1840
                usec_t until,
1841
                uint32_t flags,
1842
                bool pass_volume_key) {
1843

1844
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1845
        _cleanup_(iovec_done_erase) struct iovec decrypted_key = {};
×
1846
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1847
        _cleanup_free_ char *friendly = NULL;
×
UNCOV
1848
        int keyslot = arg_key_slot, r;
×
1849

1850
        assert(cd);
×
1851
        assert(name);
×
UNCOV
1852
        assert(arg_tpm2_device || arg_tpm2_device_auto);
×
1853

1854
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
×
1855
        if (!friendly)
×
UNCOV
1856
                return log_oom();
×
1857

1858
        for (;;) {
×
UNCOV
1859
                if (key_file || iovec_is_set(key_data)) {
×
1860
                        /* If key data is specified, use that */
1861

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

1913
                if (r == -EOPNOTSUPP) { /* Plugin not available, let's process TPM2 stuff right here instead */
×
1914
                        bool found_some = false;
×
UNCOV
1915
                        int token = 0; /* first token to look at */
×
1916

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

1921
                        for (;;) {
×
1922
                                _cleanup_(iovec_done) struct iovec pubkey = {}, salt = {}, srk = {}, pcrlock_nv = {};
×
1923
                                struct iovec *blobs = NULL, *policy_hash = NULL;
×
1924
                                uint32_t hash_pcr_mask, pubkey_pcr_mask;
×
1925
                                size_t n_blobs = 0, n_policy_hash = 0;
×
1926
                                uint16_t pcr_bank, primary_alg;
×
UNCOV
1927
                                TPM2Flags tpm2_flags;
×
1928

1929
                                CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
×
UNCOV
1930
                                CLEANUP_ARRAY(policy_hash, n_policy_hash, iovec_array_free);
×
1931

UNCOV
1932
                                r = find_tpm2_auto_data(
×
1933
                                                cd,
1934
                                                arg_tpm2_pcr_mask, /* if != UINT32_MAX we'll only look for tokens with this PCR mask */
1935
                                                token, /* search for the token with this index, or any later index than this */
1936
                                                &hash_pcr_mask,
1937
                                                &pcr_bank,
1938
                                                &pubkey,
1939
                                                &pubkey_pcr_mask,
1940
                                                &primary_alg,
1941
                                                &blobs,
1942
                                                &n_blobs,
1943
                                                &policy_hash,
1944
                                                &n_policy_hash,
1945
                                                &salt,
1946
                                                &srk,
1947
                                                &pcrlock_nv,
1948
                                                &tpm2_flags,
1949
                                                &keyslot,
1950
                                                &token);
UNCOV
1951
                                if (r == -ENXIO)
×
1952
                                        /* No further TPM2 tokens found in the LUKS2 header. */
UNCOV
1953
                                        return log_full_errno(found_some ? LOG_NOTICE : LOG_DEBUG,
×
1954
                                                              SYNTHETIC_ERRNO(EAGAIN),
1955
                                                              found_some
1956
                                                              ? "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking."
1957
                                                              : "No TPM2 metadata enrolled in LUKS2 header, falling back to traditional unlocking.");
UNCOV
1958
                                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
×
1959
                                        /* TPM2 support not compiled in? */
UNCOV
1960
                                        return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
×
1961
                                                               "TPM2 support not available, falling back to traditional unlocking.");
UNCOV
1962
                                if (r < 0)
×
1963
                                        return r;
1964

UNCOV
1965
                                found_some = true;
×
1966

UNCOV
1967
                                r = acquire_tpm2_key(
×
1968
                                                name,
1969
                                                arg_tpm2_device,
1970
                                                hash_pcr_mask,
1971
                                                pcr_bank,
1972
                                                &pubkey,
1973
                                                pubkey_pcr_mask,
1974
                                                arg_tpm2_signature,
1975
                                                arg_tpm2_pcrlock,
1976
                                                primary_alg,
1977
                                                /* key_file= */ NULL, /* key_file_size= */ 0, /* key_file_offset= */ 0, /* no key file */
1978
                                                blobs,
1979
                                                n_blobs,
1980
                                                policy_hash,
1981
                                                n_policy_hash,
1982
                                                &salt,
1983
                                                &srk,
1984
                                                &pcrlock_nv,
1985
                                                tpm2_flags,
1986
                                                until,
1987
                                                "cryptsetup.tpm2-pin",
1988
                                                arg_ask_password_flags,
1989
                                                &decrypted_key);
1990
                                if (IN_SET(r, -EACCES, -ENOLCK))
×
1991
                                        return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
×
UNCOV
1992
                                if (r != -EPERM)
×
1993
                                        break;
1994

UNCOV
1995
                                token++; /* try a different token next time */
×
1996
                        }
1997

UNCOV
1998
                        if (r >= 0)
×
1999
                                break;
2000
                        /* EAGAIN means: no tpm2 chip found */
2001
                        if (r != -EAGAIN) {
×
2002
                                log_notice_errno(r, "TPM2 operation failed, falling back to traditional unlocking: %m");
×
UNCOV
2003
                                return -EAGAIN; /* Mangle error code: let's make any form of TPM2 failure non-fatal. */
×
2004
                        }
2005
                }
2006

UNCOV
2007
                if (!monitor) {
×
2008
                        /* We didn't find the TPM2 device. In this case, watch for it via udev. Let's create
2009
                         * an event loop and monitor first. */
2010

UNCOV
2011
                        assert(!event);
×
2012

2013
                        if (is_efi_boot() && !efi_has_tpm2())
×
UNCOV
2014
                                return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
×
2015
                                                        "No TPM2 hardware discovered and EFI firmware does not see it either, falling back to traditional unlocking.");
2016

2017
                        r = make_tpm2_device_monitor(&event, &monitor);
×
UNCOV
2018
                        if (r < 0)
×
2019
                                return r;
2020

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

2023
                        /* Let's immediately rescan in case the device appeared in the time we needed
2024
                         * to create and configure the monitor */
UNCOV
2025
                        continue;
×
2026
                }
2027

2028
                r = run_security_device_monitor(event, monitor);
×
UNCOV
2029
                if (r < 0)
×
2030
                        return r;
2031

UNCOV
2032
                log_debug("Got one or more potentially relevant udev events, rescanning for TPM2...");
×
2033
        }
2034

2035
        if (pass_volume_key)
×
UNCOV
2036
                r = measured_crypt_activate_by_volume_key(cd, name, decrypted_key.iov_base, decrypted_key.iov_len, flags);
×
2037
        else {
2038
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
×
UNCOV
2039
                ssize_t base64_encoded_size;
×
2040

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

2043
                base64_encoded_size = base64mem(decrypted_key.iov_base, decrypted_key.iov_len, &base64_encoded);
×
2044
                if (base64_encoded_size < 0)
×
UNCOV
2045
                        return log_oom();
×
2046

UNCOV
2047
                r = measured_crypt_activate_by_passphrase(cd, name, keyslot, base64_encoded, base64_encoded_size, flags);
×
2048
        }
2049
        if (r == -EPERM) {
×
2050
                log_error_errno(r, "Failed to activate with TPM2 decrypted key. (Key incorrect?)");
×
UNCOV
2051
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
2052
        }
2053
        if (r < 0)
×
UNCOV
2054
                return log_error_errno(r, "Failed to activate with TPM2 acquired key: %m");
×
2055

2056
        return 0;
2057
}
2058

UNCOV
2059
static int attach_luks_or_plain_or_bitlk_by_key_data(
×
2060
                struct crypt_device *cd,
2061
                const char *name,
2062
                const struct iovec *key_data,
2063
                uint32_t flags,
2064
                bool pass_volume_key) {
2065

UNCOV
2066
        int r;
×
2067

2068
        assert(cd);
×
2069
        assert(name);
×
UNCOV
2070
        assert(key_data);
×
2071

2072
        if (pass_volume_key)
×
UNCOV
2073
                r = measured_crypt_activate_by_volume_key(cd, name, key_data->iov_base, key_data->iov_len, flags);
×
2074
        else
2075
                r = measured_crypt_activate_by_passphrase(cd, name, arg_key_slot, key_data->iov_base, key_data->iov_len, flags);
×
2076
        if (r == -EPERM) {
×
2077
                log_error_errno(r, "Failed to activate. (Key incorrect?)");
×
UNCOV
2078
                return -EAGAIN; /* Log actual error, but return EAGAIN */
×
2079
        }
2080
        if (r < 0)
×
UNCOV
2081
                return log_error_errno(r, "Failed to activate: %m");
×
2082

2083
        return 0;
2084
}
2085

UNCOV
2086
static int attach_luks_or_plain_or_bitlk_by_key_file(
×
2087
                struct crypt_device *cd,
2088
                const char *name,
2089
                const char *key_file,
2090
                uint32_t flags,
2091
                bool pass_volume_key) {
2092

2093
        _cleanup_(erase_and_freep) char *kfdata = NULL;
×
2094
        _cleanup_free_ char *bindname = NULL;
×
2095
        size_t kfsize;
×
UNCOV
2096
        int r;
×
2097

2098
        assert(cd);
×
2099
        assert(name);
×
UNCOV
2100
        assert(key_file);
×
2101

2102
        /* If we read the key via AF_UNIX, make this client recognizable */
2103
        bindname = make_bindname(name, /* token_type= */ _TOKEN_TYPE_INVALID);
×
2104
        if (!bindname)
×
UNCOV
2105
                return log_oom();
×
2106

UNCOV
2107
        r = read_full_file_full(
×
2108
                        AT_FDCWD, key_file,
2109
                        arg_keyfile_offset == 0 ? UINT64_MAX : arg_keyfile_offset,
×
UNCOV
2110
                        arg_keyfile_size == 0 ? SIZE_MAX : arg_keyfile_size,
×
2111
                        READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
2112
                        bindname,
2113
                        &kfdata, &kfsize);
2114
        if (r == -E2BIG) {
×
2115
                log_error_errno(r, "Failed to activate, key file '%s' too large.", key_file);
×
UNCOV
2116
                return -EAGAIN;
×
2117
        }
2118
        if (r == -ENOENT) {
×
2119
                log_error_errno(r, "Failed to activate, key file '%s' missing.", key_file);
×
UNCOV
2120
                return -EAGAIN; /* Log actual error, but return EAGAIN */
×
2121
        }
2122
        if (r < 0)
×
UNCOV
2123
                return log_error_errno(r, "Failed to read key file '%s': %m", key_file);
×
2124

2125
        if (pass_volume_key)
×
UNCOV
2126
                r = measured_crypt_activate_by_volume_key(cd, name, kfdata, kfsize, flags);
×
2127
        else
2128
                r = measured_crypt_activate_by_passphrase(cd, name, arg_key_slot, kfdata, kfsize, flags);
×
2129
        if (r == -EPERM) {
×
2130
                log_error_errno(r, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file);
×
UNCOV
2131
                return -EAGAIN; /* Log actual error, but return EAGAIN */
×
2132
        }
2133
        if (r < 0)
×
UNCOV
2134
                return log_error_errno(r, "Failed to activate with key file '%s': %m", key_file);
×
2135

2136
        return 0;
2137
}
2138

UNCOV
2139
static int attach_luks_or_plain_or_bitlk_by_passphrase(
×
2140
                struct crypt_device *cd,
2141
                const char *name,
2142
                char **passwords,
2143
                uint32_t flags,
2144
                bool pass_volume_key) {
2145

UNCOV
2146
        int r;
×
2147

2148
        assert(cd);
×
UNCOV
2149
        assert(name);
×
2150

2151
        r = -EINVAL;
2152
        STRV_FOREACH(p, passwords) {
×
2153
                if (pass_volume_key)
×
UNCOV
2154
                        r = measured_crypt_activate_by_volume_key(cd, name, *p, arg_key_size, flags);
×
2155
                else
2156
                        r = measured_crypt_activate_by_passphrase(cd, name, arg_key_slot, *p, strlen(*p), flags);
×
UNCOV
2157
                if (r >= 0)
×
2158
                        break;
2159
        }
2160
        if (r == -EPERM) {
×
2161
                log_error_errno(r, "Failed to activate with specified passphrase. (Passphrase incorrect?)");
×
UNCOV
2162
                return -EAGAIN; /* log actual error, but return EAGAIN */
×
2163
        }
2164
        if (r < 0)
×
UNCOV
2165
                return log_error_errno(r, "Failed to activate with specified passphrase: %m");
×
2166

2167
        return 0;
2168
}
2169

UNCOV
2170
static int attach_luks_or_plain_or_bitlk(
×
2171
                struct crypt_device *cd,
2172
                const char *name,
2173
                TokenType token_type,
2174
                const char *key_file,
2175
                const struct iovec *key_data,
2176
                char **passwords,
2177
                uint32_t flags,
2178
                usec_t until) {
2179

2180
        bool pass_volume_key = false;
×
UNCOV
2181
        int r;
×
2182

2183
        assert(cd);
×
UNCOV
2184
        assert(name);
×
2185

2186
        if ((!arg_type && !crypt_get_type(cd)) || streq_ptr(arg_type, CRYPT_PLAIN)) {
×
UNCOV
2187
                struct crypt_params_plain params = {
×
2188
                        .offset = arg_offset,
2189
                        .skip = arg_skip,
2190
                        .sector_size = arg_sector_size,
2191
                };
2192
                const char *cipher, *cipher_mode;
×
UNCOV
2193
                _cleanup_free_ char *truncated_cipher = NULL;
×
2194

UNCOV
2195
                if (streq_ptr(arg_hash, "plain"))
×
2196
                        /* plain isn't a real hash type. it just means "use no hash" */
2197
                        params.hash = NULL;
2198
                else if (arg_hash)
×
2199
                        params.hash = arg_hash;
×
UNCOV
2200
                else if (!key_file)
×
2201
                        /* for CRYPT_PLAIN, the behaviour of cryptsetup package is to not hash when a key
2202
                         * file is provided */
UNCOV
2203
                        params.hash = "ripemd160";
×
2204

2205
                if (arg_cipher) {
×
UNCOV
2206
                        size_t l;
×
2207

2208
                        l = strcspn(arg_cipher, "-");
×
2209
                        truncated_cipher = strndup(arg_cipher, l);
×
2210
                        if (!truncated_cipher)
×
UNCOV
2211
                                return log_oom();
×
2212

2213
                        cipher = truncated_cipher;
×
UNCOV
2214
                        cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain";
×
2215
                } else {
2216
                        cipher = "aes";
2217
                        cipher_mode = "cbc-essiv:sha256";
2218
                }
2219

2220
                /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */
UNCOV
2221
                arg_keyfile_size = arg_key_size;
×
2222

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

2229
                /* hash == NULL implies the user passed "plain" */
UNCOV
2230
                pass_volume_key = !params.hash;
×
2231
        }
2232

UNCOV
2233
        log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
×
2234
                 crypt_get_cipher(cd),
2235
                 crypt_get_cipher_mode(cd),
2236
                 crypt_get_volume_key_size(cd)*8,
2237
                 crypt_get_device_name(cd));
2238

2239
        if (token_type == TOKEN_TPM2)
×
2240
                return attach_luks_or_plain_or_bitlk_by_tpm2(cd, name, key_file, key_data, until, flags, pass_volume_key);
×
2241
        if (token_type == TOKEN_FIDO2)
×
2242
                return attach_luks_or_plain_or_bitlk_by_fido2(cd, name, key_file, key_data, until, flags, pass_volume_key);
×
2243
        if (token_type == TOKEN_PKCS11)
×
2244
                return attach_luks_or_plain_or_bitlk_by_pkcs11(cd, name, key_file, key_data, until, flags, pass_volume_key);
×
2245
        if (key_data)
×
2246
                return attach_luks_or_plain_or_bitlk_by_key_data(cd, name, key_data, flags, pass_volume_key);
×
2247
        if (key_file)
×
UNCOV
2248
                return attach_luks_or_plain_or_bitlk_by_key_file(cd, name, key_file, flags, pass_volume_key);
×
2249

UNCOV
2250
        return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
×
2251
}
2252

2253
static int help(void) {
×
2254
        _cleanup_free_ char *link = NULL;
×
UNCOV
2255
        int r;
×
2256

2257
        r = terminal_urlify_man("systemd-cryptsetup", "8", &link);
×
2258
        if (r < 0)
×
UNCOV
2259
                return log_oom();
×
2260

UNCOV
2261
        printf("%1$s attach VOLUME SOURCE-DEVICE [KEY-FILE] [CONFIG]\n"
×
2262
               "%1$s detach VOLUME\n\n"
2263
               "%2$sAttach or detach an encrypted block device.%3$s\n\n"
2264
               "  -h --help            Show this help\n"
2265
               "     --version         Show package version\n"
2266
               "\nSee the %4$s for details.\n",
2267
               program_invocation_short_name,
2268
               ansi_highlight(),
2269
               ansi_normal(),
2270
               link);
2271

2272
        return 0;
2273
}
2274

2275
static int parse_argv(int argc, char *argv[]) {
×
UNCOV
2276
        enum {
×
2277
                ARG_VERSION = 0x100,
2278
        };
2279

UNCOV
2280
        static const struct option options[] = {
×
2281
                { "help",                         no_argument,       NULL, 'h'                       },
2282
                { "version",                      no_argument,       NULL, ARG_VERSION               },
2283
                {}
2284
        };
2285

UNCOV
2286
        int c;
×
2287

2288
        assert(argc >= 0);
×
UNCOV
2289
        assert(argv);
×
2290

2291
        if (argv_looks_like_help(argc, argv))
×
UNCOV
2292
                return help();
×
2293

2294
        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
×
UNCOV
2295
                switch (c) {
×
2296

2297
                case 'h':
×
UNCOV
2298
                        return help();
×
2299

2300
                case ARG_VERSION:
×
UNCOV
2301
                        return version();
×
2302

2303
                case '?':
2304
                        return -EINVAL;
2305

2306
                default:
×
UNCOV
2307
                        assert_not_reached();
×
2308
                }
2309

2310
        return 1;
2311
}
2312

2313
static uint32_t determine_flags(void) {
×
UNCOV
2314
        uint32_t flags = 0;
×
2315

2316
        if (arg_readonly)
×
UNCOV
2317
                flags |= CRYPT_ACTIVATE_READONLY;
×
2318

2319
        if (arg_discards)
×
UNCOV
2320
                flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
×
2321

2322
        if (arg_same_cpu_crypt)
×
UNCOV
2323
                flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
×
2324

2325
        if (arg_submit_from_crypt_cpus)
×
UNCOV
2326
                flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
×
2327

2328
        if (arg_no_read_workqueue)
×
UNCOV
2329
                flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
×
2330

2331
        if (arg_no_write_workqueue)
×
UNCOV
2332
                flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
×
2333

2334
#ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF
2335
        /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */
2336
        /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */
UNCOV
2337
        flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF;
×
2338
#endif
2339

UNCOV
2340
        return flags;
×
2341
}
2342

2343
static void remove_and_erasep(const char **p) {
×
UNCOV
2344
        int r;
×
2345

UNCOV
2346
        if (!*p)
×
2347
                return;
2348

2349
        r = unlinkat_deallocate(AT_FDCWD, *p, UNLINK_ERASE);
×
2350
        if (r < 0 && r != -ENOENT)
×
UNCOV
2351
                log_warning_errno(r, "Unable to erase key file '%s', ignoring: %m", *p);
×
2352
}
2353

2354
static TokenType determine_token_type(void) {
×
UNCOV
2355
        if (arg_tpm2_device || arg_tpm2_device_auto)
×
2356
                return TOKEN_TPM2;
UNCOV
2357
        if (arg_fido2_device || arg_fido2_device_auto)
×
2358
                return TOKEN_FIDO2;
2359
        if (arg_pkcs11_uri || arg_pkcs11_uri_auto)
×
UNCOV
2360
                return TOKEN_PKCS11;
×
2361

2362
        return _TOKEN_TYPE_INVALID;
2363
}
2364

2365
static int discover_key(const char *key_file, const char *volume, TokenType token_type, struct iovec *ret_key_data) {
×
2366
        _cleanup_free_ char *bindname = NULL;
×
2367
        const char *token_type_name;
×
UNCOV
2368
        int r;
×
2369

2370
        assert(key_file);
×
2371
        assert(volume);
×
UNCOV
2372
        assert(ret_key_data);
×
2373

2374
        bindname = make_bindname(volume, token_type);
×
2375
        if (!bindname)
×
UNCOV
2376
                return log_oom();
×
2377

2378
        /* If a key file is not explicitly specified, search for a key in a well defined search path, and load it. */
2379
        r = find_key_file(key_file, STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"), bindname, ret_key_data);
×
UNCOV
2380
        if (r <= 0)
×
2381
                return r;
2382

2383
        token_type_name = token_type_to_string(token_type);
×
2384
        if (token_type_name)
×
UNCOV
2385
                log_debug("Automatically discovered encrypted key for volume '%s' (token type: %s).", volume, token_type_name);
×
2386
        else
UNCOV
2387
                log_debug("Automatically discovered key for volume '%s'.", volume);
×
2388

2389
        return r;
2390
}
2391

2392
static int verb_attach(int argc, char *argv[], void *userdata) {
×
2393
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
×
2394
        _unused_ _cleanup_(remove_and_erasep) const char *destroy_key_file = NULL;
×
UNCOV
2395
        crypt_status_info status;
×
2396
        uint32_t flags = 0;
×
UNCOV
2397
        unsigned tries;
×
2398
        usec_t until;
×
UNCOV
2399
        PassphraseType passphrase_type = PASSPHRASE_NONE;
×
2400
        int r;
×
2401

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

2404
        assert(argc >= 3 && argc <= 5);
×
2405

2406
        const char *volume = ASSERT_PTR(argv[1]),
×
2407
                *source = ASSERT_PTR(argv[2]),
×
UNCOV
2408
                *key_file = argc >= 4 ? mangle_none(argv[3]) : NULL,
×
2409
                *config = argc >= 5 ? mangle_none(argv[4]) : NULL;
×
2410

2411
        if (!filename_is_valid(volume))
×
2412
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
×
2413

2414
        if (key_file && !path_is_absolute(key_file)) {
×
2415
                log_warning("Password file path '%s' is not absolute. Ignoring.", key_file);
×
2416
                key_file = NULL;
2417
        }
2418

UNCOV
2419
        if (config) {
×
UNCOV
2420
                r = parse_crypt_config(config);
×
2421
                if (r < 0)
×
2422
                        return r;
2423
        }
2424

UNCOV
2425
        log_debug("%s %s ← %s type=%s cipher=%s", __func__,
×
2426
                  volume, source, strempty(arg_type), strempty(arg_cipher));
2427

2428
        /* A delicious drop of snake oil */
2429
        (void) mlockall(MCL_FUTURE);
×
2430

2431
        if (key_file && arg_keyfile_erase)
×
2432
                destroy_key_file = key_file; /* let's get this baby erased when we leave */
×
2433

2434
        if (arg_header) {
×
2435
                if (streq_ptr(arg_type, CRYPT_TCRYPT)){
×
UNCOV
2436
                        log_debug("tcrypt header: %s", arg_header);
×
UNCOV
2437
                        r = crypt_init_data_device(&cd, arg_header, source);
×
2438
                } else {
2439
                        log_debug("LUKS header: %s", arg_header);
×
2440
                        r = crypt_init(&cd, arg_header);
×
2441
                }
2442
        } else
UNCOV
2443
                r = crypt_init(&cd, source);
×
UNCOV
2444
        if (r < 0)
×
2445
                return log_error_errno(r, "crypt_init() failed: %m");
×
2446

UNCOV
2447
        cryptsetup_enable_logging(cd);
×
2448

2449
        status = crypt_status(cd, volume);
×
UNCOV
2450
        if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) {
×
2451
                log_info("Volume %s already active.", volume);
×
2452
                return 0;
×
2453
        }
2454

2455
        flags = determine_flags();
×
2456

2457
        until = usec_add(now(CLOCK_MONOTONIC), arg_timeout);
×
UNCOV
2458
        if (until == USEC_INFINITY)
×
2459
                until = 0;
×
2460

UNCOV
2461
        if (arg_key_size == 0)
×
UNCOV
2462
                arg_key_size = 256U / 8U;
×
2463

2464
        if (key_file) {
×
2465
                struct stat st;
×
2466

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

UNCOV
2473
        if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2)) {
×
UNCOV
2474
                r = crypt_load(cd, !arg_type || streq(arg_type, ANY_LUKS) ? CRYPT_LUKS : arg_type, NULL);
×
2475
                if (r < 0)
×
UNCOV
2476
                        return log_error_errno(r, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd));
×
2477

2478
/* since cryptsetup 2.7.0 (Jan 2024) */
2479
#if HAVE_CRYPT_SET_KEYRING_TO_LINK
UNCOV
2480
                if (arg_link_key_description) {
×
2481
                        r = crypt_set_keyring_to_link(cd, arg_link_key_description, NULL, arg_link_key_type, arg_link_keyring);
×
2482
                        if (r < 0)
×
UNCOV
2483
                                log_warning_errno(r, "Failed to set keyring or key description to link volume key in, ignoring: %m");
×
2484
                }
2485
#endif
2486

UNCOV
2487
                if (arg_header) {
×
UNCOV
2488
                        r = crypt_set_data_device(cd, source);
×
2489
                        if (r < 0)
×
2490
                                return log_error_errno(r, "Failed to set LUKS data device %s: %m", source);
×
2491
                }
2492

2493
                /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */
2494
                if (!key_file && use_token_plugins()) {
×
2495
                        r = crypt_activate_by_token_pin_ask_password(
×
2496
                                        cd,
2497
                                        volume,
2498
                                        /* type= */ NULL,
2499
                                        until,
2500
                                        /* userdata= */ NULL,
2501
                                        flags,
2502
                                        "Please enter LUKS2 token PIN:",
2503
                                        "luks2-pin",
2504
                                        "cryptsetup.luks2-pin");
UNCOV
2505
                        if (r >= 0) {
×
UNCOV
2506
                                log_debug("Volume %s activated with a LUKS token.", volume);
×
2507
                                return 0;
×
2508
                        }
2509

2510
                        log_debug_errno(r, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd));
×
2511
                }
2512
        }
2513

2514
/* since cryptsetup 2.3.0 (Feb 2020) */
2515
#ifdef CRYPT_BITLK
UNCOV
2516
        if (streq_ptr(arg_type, CRYPT_BITLK)) {
×
UNCOV
2517
                r = crypt_load(cd, CRYPT_BITLK, NULL);
×
UNCOV
2518
                if (r < 0)
×
UNCOV
2519
                        return log_error_errno(r, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd));
×
2520
        }
2521
#endif
2522

UNCOV
2523
        bool use_cached_passphrase = true, try_discover_key = !key_file;
×
UNCOV
2524
        const char *discovered_key_fn = strjoina(volume, ".key");
×
2525
        _cleanup_strv_free_erase_ char **passwords = NULL;
×
2526
        for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) {
×
2527
                _cleanup_(iovec_done_erase) struct iovec discovered_key_data = {};
×
UNCOV
2528
                const struct iovec *key_data = NULL;
×
UNCOV
2529
                TokenType token_type = determine_token_type();
×
2530

UNCOV
2531
                log_debug("Beginning attempt %u to unlock.", tries);
×
2532

2533
                /* When we were able to acquire multiple keys, let's always process them in this order:
2534
                 *
2535
                 *    1. A key acquired via PKCS#11 or FIDO2 token, or TPM2 chip
2536
                 *    2. The configured or discovered key, of which both are exclusive and optional
2537
                 *    3. The empty password, in case arg_try_empty_password is set
2538
                 *    4. We enquire the user for a password
2539
                 */
2540

UNCOV
2541
                if (try_discover_key) {
×
UNCOV
2542
                        r = discover_key(discovered_key_fn, volume, token_type, &discovered_key_data);
×
2543
                        if (r < 0)
×
2544
                                return r;
2545
                        if (r > 0)
×
2546
                                key_data = &discovered_key_data;
×
2547
                }
2548

2549
                if (token_type < 0 && !key_file && !key_data && !passwords) {
×
2550

2551
                        /* If we have nothing to try anymore, then acquire a new password */
2552

UNCOV
2553
                        if (arg_try_empty_password) {
×
2554
                                /* Hmm, let's try an empty password now, but only once */
UNCOV
2555
                                arg_try_empty_password = false;
×
UNCOV
2556
                                key_data = &iovec_empty;
×
2557
                        } else {
2558
                                /* Ask the user for a passphrase or recovery key only as last resort, if we
2559
                                 * have nothing else to check for */
UNCOV
2560
                                if (passphrase_type == PASSPHRASE_NONE) {
×
2561
                                        passphrase_type = check_registered_passwords(cd);
×
2562
                                        if (passphrase_type == PASSPHRASE_NONE)
×
2563
                                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No passphrase or recovery key registered.");
×
2564
                                }
2565

2566
                                r = get_password(
×
2567
                                                volume,
2568
                                                source,
2569
                                                until,
UNCOV
2570
                                                /* ignore_cached= */ !use_cached_passphrase || arg_verify,
×
2571
                                                passphrase_type,
2572
                                                &passwords);
2573
                                use_cached_passphrase = false;
×
UNCOV
2574
                                if (r == -EAGAIN)
×
2575
                                        continue;
×
2576
                                if (r < 0)
×
2577
                                        return r;
2578
                        }
2579
                }
2580

2581
                if (streq_ptr(arg_type, CRYPT_TCRYPT))
×
2582
                        r = attach_tcrypt(cd, volume, token_type, key_file, key_data, passwords, flags);
×
2583
                else
UNCOV
2584
                        r = attach_luks_or_plain_or_bitlk(cd, volume, token_type, key_file, key_data, passwords, flags, until);
×
UNCOV
2585
                if (r >= 0)
×
2586
                        break;
UNCOV
2587
                if (r != -EAGAIN)
×
2588
                        return r;
2589

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

2593
                if (token_type == TOKEN_TPM2) {
×
2594
                        arg_tpm2_device = mfree(arg_tpm2_device);
×
2595
                        arg_tpm2_device_auto = false;
×
2596
                        continue;
×
2597
                }
2598

UNCOV
2599
                if (token_type == TOKEN_FIDO2) {
×
UNCOV
2600
                        arg_fido2_device = mfree(arg_fido2_device);
×
2601
                        arg_fido2_device_auto = false;
×
2602
                        continue;
×
2603
                }
2604

2605
                if (token_type == TOKEN_PKCS11) {
×
UNCOV
2606
                        arg_pkcs11_uri = mfree(arg_pkcs11_uri);
×
2607
                        arg_pkcs11_uri_auto = false;
×
UNCOV
2608
                        continue;
×
2609
                }
2610

UNCOV
2611
                if (try_discover_key) {
×
UNCOV
2612
                        try_discover_key = false;
×
2613
                        continue;
×
2614
                }
2615

2616
                if (key_file) {
×
UNCOV
2617
                        key_file = NULL;
×
UNCOV
2618
                        continue;
×
2619
                }
2620

2621
                if (passwords) {
×
2622
                        passwords = strv_free_erase(passwords);
×
UNCOV
2623
                        continue;
×
2624
                }
2625

2626
                log_debug("Prepared for next attempt to unlock.");
×
2627
        }
2628

UNCOV
2629
        if (arg_tries != 0 && tries >= arg_tries)
×
UNCOV
2630
                return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to activate; giving up.");
×
2631

2632
        return 0;
2633
}
2634

UNCOV
2635
static int verb_detach(int argc, char *argv[], void *userdata) {
×
2636
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
×
2637
        const char *volume = ASSERT_PTR(argv[1]);
×
2638
        int r;
×
2639

UNCOV
2640
        assert(argc == 2);
×
2641

2642
        if (!filename_is_valid(volume))
×
2643
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", volume);
×
2644

UNCOV
2645
        r = crypt_init_by_name(&cd, volume);
×
2646
        if (r == -ENODEV) {
×
UNCOV
2647
                log_info("Volume %s already inactive.", volume);
×
UNCOV
2648
                return 0;
×
2649
        }
2650
        if (r < 0)
×
UNCOV
2651
                return log_error_errno(r, "crypt_init_by_name() for volume '%s' failed: %m", volume);
×
2652

2653
        cryptsetup_enable_logging(cd);
×
2654

2655
        r = crypt_deactivate(cd, volume);
×
2656
        if (r < 0)
×
UNCOV
2657
                return log_error_errno(r, "Failed to deactivate '%s': %m", volume);
×
2658

2659
        return 0;
2660
}
2661

2662
static int run(int argc, char *argv[]) {
×
2663
        int r;
×
2664

UNCOV
2665
        log_setup();
×
2666

2667
        umask(0022);
×
2668

2669
        r = parse_argv(argc, argv);
×
UNCOV
2670
        if (r <= 0)
×
2671
                return r;
2672

2673
        cryptsetup_enable_logging(NULL);
×
2674

UNCOV
2675
        static const Verb verbs[] = {
×
2676
                { "attach", 3, 5, 0, verb_attach },
2677
                { "detach", 2, 2, 0, verb_detach },
2678
                {}
2679
        };
2680

2681
        return dispatch_verb(argc, argv, verbs, NULL);
×
2682
}
2683

UNCOV
2684
DEFINE_MAIN_FUNCTION(run);
×
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