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

systemd / systemd / 14872145375

06 May 2025 09:07PM UTC coverage: 72.232% (+0.02%) from 72.214%
14872145375

push

github

DaanDeMeyer
string-table: annotate _to_string and _from_string with _const_ and _pure_, respectively

Follow-up for c94f6ab1b

297286 of 411572 relevant lines covered (72.23%)

695615.99 hits per line

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

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

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

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

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

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

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

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

150
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(passphrase_type, PassphraseType);
×
151

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

158
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(token_type, TokenType);
46✔
159

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

170
static int parse_one_option(const char *option) {
146✔
171
        const char *val;
146✔
172
        int r;
146✔
173

174
        assert(option);
146✔
175

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

180
        if (startswith(option, "keyfile-timeout="))
145✔
181
                return 0;
182

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

188
        } else if ((val = startswith(option, "size="))) {
145✔
189

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

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

201
                arg_key_size /= 8;
×
202

203
        } else if ((val = startswith(option, "sector-size="))) {
145✔
204

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

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

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

219
        } else if ((val = startswith(option, "key-slot=")) ||
145✔
220
                   (val = startswith(option, "keyslot="))) {
143✔
221

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

227
        } else if ((val = startswith(option, "tcrypt-keyfile="))) {
143✔
228

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

236
        } else if ((val = startswith(option, "keyfile-size="))) {
143✔
237

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

242
        } else if ((val = startswith(option, "keyfile-offset="))) {
140✔
243

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

248
        } else if ((val = startswith(option, "keyfile-erase="))) {
135✔
249

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

256
                arg_keyfile_erase = r;
2✔
257

258
        } else if (streq(option, "keyfile-erase"))
133✔
259
                arg_keyfile_erase = true;
×
260

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

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

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

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

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

282
        } else if ((val = startswith(option, "tries="))) {
124✔
283

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

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

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

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

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

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

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

364
        } else if ((val = startswith(option, "offset="))) {
116✔
365

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

370
        } else if ((val = startswith(option, "skip="))) {
116✔
371

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

376
        } else if ((val = startswith(option, "pkcs11-uri="))) {
116✔
377

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

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

389
                        arg_pkcs11_uri_auto = false;
×
390
                }
391

392
        } else if ((val = startswith(option, "fido2-device="))) {
110✔
393

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

402
                        arg_fido2_device_auto = false;
×
403
                }
404

405
        } else if ((val = startswith(option, "fido2-cid="))) {
110✔
406

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

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

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

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

426
        } else if ((val = startswith(option, "fido2-rp="))) {
110✔
427

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

432
        } else if ((val = startswith(option, "fido2-pin="))) {
110✔
433

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

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

443
        } else if ((val = startswith(option, "fido2-up="))) {
110✔
444

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

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

454
        } else if ((val = startswith(option, "fido2-uv="))) {
110✔
455

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

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

465
        } else if ((val = startswith(option, "tpm2-device="))) {
110✔
466

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

475
                        arg_tpm2_device_auto = false;
×
476
                }
477

478
        } else if ((val = startswith(option, "tpm2-pcrs="))) {
71✔
479

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

484
        } else if ((val = startswith(option, "tpm2-signature="))) {
71✔
485

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

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

494
        } else if ((val = startswith(option, "tpm2-pin="))) {
70✔
495

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

502
                arg_tpm2_pin = r;
×
503

504
        } else if ((val = startswith(option, "tpm2-pcrlock="))) {
70✔
505

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

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

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

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

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

531
                arg_tpm2_measure_pcr = pcr;
×
532

533
        } else if ((val = startswith(option, "tpm2-measure-bank="))) {
65✔
534

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

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

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

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

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

556
        } else if ((val = startswith(option, "try-empty-password="))) {
65✔
557

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

564
                arg_try_empty_password = r;
1✔
565

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

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

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

580
        else if ((val = startswith(option, "token-timeout="))) {
1✔
581

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

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

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

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

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

613
                sep += 2;
×
614

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

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

626
                        sep = c + 1;
×
627
                }
628

629
                key_description = strdup(sep);
×
630
                if (!key_description)
×
631
                        return log_oom();
×
632

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

642
        return 0;
643
}
644

645
static int parse_crypt_config(const char *options) {
71✔
646
        assert(options);
71✔
647

648
        for (;;) {
363✔
649
                _cleanup_free_ char *word = NULL;
146✔
650
                int r;
217✔
651

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

658
                r = parse_one_option(word);
146✔
659
                if (r < 0)
146✔
660
                        return r;
661
        }
662

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

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

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

682
        return 0;
683
}
684

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

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

695
        assert(path);
10✔
696

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

700
        if (!S_ISBLK(st.st_mode))
10✔
701
                return NULL;
702

703
        if (sd_device_new_from_stat_rdev(&device, &st) < 0)
×
704
                return NULL;
705

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

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

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

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

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

730
        return NULL;
731
}
732

733
static char *disk_mount_point(const char *label) {
10✔
734
        _cleanup_free_ char *device = NULL;
10✔
735
        _cleanup_endmntent_ FILE *f = NULL;
10✔
736
        struct mntent *m;
10✔
737

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

740
        device = strjoin("/dev/mapper/", label);
10✔
741
        if (!device)
10✔
742
                return NULL;
743

744
        f = setmntent(fstab_path(), "re");
20✔
745
        if (!f)
10✔
746
                return NULL;
747

748
        while ((m = getmntent(f)))
10✔
749
                if (path_equal(m->mnt_fsname, device))
×
750
                        return strdup(m->mnt_dir);
×
751

752
        return NULL;
753
}
754

755
static char *friendly_disk_name(const char *src, const char *vol) {
10✔
756
        _cleanup_free_ char *description = NULL, *mount_point = NULL;
10✔
757
        char *name_buffer = NULL;
10✔
758
        int r;
10✔
759

760
        assert(src);
10✔
761
        assert(vol);
10✔
762

763
        description = disk_description(src);
10✔
764
        mount_point = disk_mount_point(vol);
10✔
765

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

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

781
        return name_buffer;
×
782
}
783

784
static PassphraseType check_registered_passwords(struct crypt_device *cd) {
14✔
785
        _cleanup_free_ bool *slots = NULL;
14✔
786
        int slot_max;
14✔
787
        PassphraseType passphrase_type = PASSPHRASE_NONE;
14✔
788

789
        assert(cd);
14✔
790

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

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

802
        for (int slot = 0; slot < slot_max; slot++)
462✔
803
                slots[slot] = IN_SET(crypt_keyslot_status(cd, slot), CRYPT_SLOT_ACTIVE, CRYPT_SLOT_ACTIVE_LAST);
448✔
804

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

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

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

826
                type = sd_json_variant_string(w);
9✔
827
                if (STR_IN_SET(type, "systemd-recovery", "systemd-pkcs11", "systemd-fido2", "systemd-tpm2")) {
9✔
828

829
                        /* At least exists one recovery key */
830
                        if (streq(type, "systemd-recovery"))
9✔
831
                                passphrase_type |= PASSPHRASE_RECOVERY_KEY;
×
832

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

839
                        JSON_VARIANT_ARRAY_FOREACH(z, w) {
18✔
840
                                unsigned u;
9✔
841
                                int at;
9✔
842

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

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

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

859
                                slots[u] = false;
9✔
860
                        }
861
                }
862
        }
863

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

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

876
static int get_password(
14✔
877
                const char *vol,
878
                const char *src,
879
                usec_t until,
880
                bool ignore_cached,
881
                PassphraseType passphrase_type,
882
                char ***ret) {
883

884
        _cleanup_free_ char *friendly = NULL, *text = NULL, *disk_path = NULL, *id = NULL;
14✔
885
        _cleanup_strv_free_erase_ char **passwords = NULL;
×
886
        AskPasswordFlags flags = arg_ask_password_flags;
14✔
887
        int r;
14✔
888

889
        assert(vol);
14✔
890
        assert(src);
14✔
891
        assert(ret);
14✔
892

893
        if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_HEADLESS))
14✔
894
                return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Password querying disabled via 'headless' option.");
14✔
895

896
        friendly = friendly_disk_name(src, vol);
×
897
        if (!friendly)
×
898
                return log_oom();
×
899

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

903
        disk_path = cescape(src);
×
904
        if (!disk_path)
×
905
                return log_oom();
×
906

907
        id = strjoin("cryptsetup:", disk_path);
×
908
        if (!id)
×
909
                return log_oom();
×
910

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

922
        if (ignore_cached)
×
923
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
×
924

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

929
        if (arg_verify) {
×
930
                _cleanup_strv_free_erase_ char **passwords2 = NULL;
×
931

932
                assert(strv_length(passwords) == 1);
×
933

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

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

943
                req.message = text;
×
944
                req.id = id;
×
945

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

950
                assert(strv_length(passwords2) == 1);
×
951

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

957
        strv_uniq(passwords);
×
958

959
        STRV_FOREACH(p, passwords) {
×
960
                char *c;
×
961

962
                if (strlen(*p)+1 >= arg_key_size)
×
963
                        continue;
×
964

965
                /* Pad password if necessary */
966
                c = new(char, arg_key_size);
×
967
                if (!c)
×
968
                        return log_oom();
14✔
969

970
                strncpy(c, *p, arg_key_size);
×
971
                erase_and_free(*p);
×
972
                *p = TAKE_PTR(c);
×
973
        }
974

975
        *ret = TAKE_PTR(passwords);
×
976

977
        return 0;
×
978
}
979

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

986
        int r;
×
987

988
        assert(cd);
×
989
        assert(name);
×
990
        assert(volume_key);
×
991
        assert(volume_key_size > 0);
×
992

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

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

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

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

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

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

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

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

1037
        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);
×
1038
        if (r < 0)
×
1039
                return log_error_errno(r, "Could not extend PCR: %m");
×
1040

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

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

1054
static int log_external_activation(int r, const char *volume) {
×
1055
        assert(volume);
×
1056

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

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

1068
        int r;
×
1069

1070
        assert(cd);
×
1071
        assert(name);
×
1072

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

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

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

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

1090
static int measured_crypt_activate_by_passphrase(
25✔
1091
                struct crypt_device *cd,
1092
                const char *name,
1093
                int keyslot,
1094
                const char *passphrase,
1095
                size_t passphrase_size,
1096
                uint32_t flags) {
1097

1098
        _cleanup_(erase_and_freep) void *vk = NULL;
25✔
1099
        size_t vks;
25✔
1100
        int r;
25✔
1101

1102
        assert(cd);
25✔
1103

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

1109
        if (arg_tpm2_measure_pcr == UINT_MAX) {
25✔
1110
                log_debug("Not measuring volume key, deactivated.");
25✔
1111
                goto shortcut;
25✔
1112
        }
1113

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

1122
        vk = malloc(vks = r);
×
1123
        if (!vk)
×
1124
                return -ENOMEM;
1125

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

1130
        return measured_crypt_activate_by_volume_key(cd, name, vk, vks, flags);
×
1131

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

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

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

1156
        assert(cd);
×
1157
        assert(name);
×
1158
        assert(key_file || key_data || !strv_isempty(passwords));
×
1159

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

1165
        if (arg_tcrypt_hidden)
×
1166
                params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
×
1167

1168
        if (arg_tcrypt_system)
×
1169
                params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
×
1170

1171
        if (arg_tcrypt_veracrypt)
×
1172
                params.flags |= CRYPT_TCRYPT_VERA_MODES;
×
1173

1174
        if (arg_tcrypt_veracrypt && arg_tcrypt_veracrypt_pim != 0)
×
1175
                params.veracrypt_pim = arg_tcrypt_veracrypt_pim;
×
1176

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

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

1210
                        return r;
×
1211
                }
1212

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

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

1220
        return 0;
1221
}
1222

1223
static char *make_bindname(const char *volume, TokenType token_type) {
45✔
1224
        const char *token_type_name = token_type_to_string(token_type), *suffix;
45✔
1225
        char *bindname;
45✔
1226
        int r;
45✔
1227

1228
        switch (token_type) {
45✔
1229

1230
        case TOKEN_FIDO2:
1231
                suffix = "-salt";
1232
                break;
1233

1234
        default:
1235
                suffix = NULL;
45✔
1236
        }
1237

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

1248
        return bindname;
45✔
1249
}
1250

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

1258
        assert(ret_event);
×
1259
        assert(ret_monitor);
×
1260

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

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

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

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

1277
        (void) sd_device_monitor_set_description(monitor, "security-device");
×
1278

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

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

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

1291
        *ret_event = TAKE_PTR(event);
×
1292
        *ret_monitor = TAKE_PTR(monitor);
×
1293
        return 0;
×
1294
}
1295

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

1302
        assert(event);
×
1303
        assert(monitor);
×
1304

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

1308
        for (;;) {
×
1309
                int x;
×
1310

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

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

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

1330
                processed = true;
×
1331
        }
1332
}
1333

1334
static bool use_token_plugins(void) {
60✔
1335

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

1343
        /* Disable tokens if we're in FIDO2 mode with manual parameters. */
1344
        if (arg_fido2_cid)
60✔
1345
                return false;
1346

1347
#if HAVE_LIBCRYPTSETUP_PLUGINS
1348
        int r;
60✔
1349

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

1357
        return crypt_token_external_path();
58✔
1358
#else
1359
        return false;
1360
#endif
1361
}
1362

1363
#if HAVE_LIBCRYPTSETUP_PLUGINS
1364
static int acquire_pins_from_env_variable(char ***ret_pins) {
21✔
1365
        _cleanup_(erase_and_freep) char *envpin = NULL;
21✔
1366
        _cleanup_strv_free_erase_ char **pins = NULL;
21✔
1367
        int r;
21✔
1368

1369
        assert(ret_pins);
21✔
1370

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

1380
        *ret_pins = TAKE_PTR(pins);
21✔
1381

1382
        return 0;
21✔
1383
}
1384
#endif
1385

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

1397
#if HAVE_LIBCRYPTSETUP_PLUGINS
1398
        AskPasswordFlags flags = arg_ask_password_flags;
58✔
1399
        _cleanup_strv_free_erase_ char **pins = NULL;
58✔
1400
        int r;
58✔
1401

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

1410
        r = acquire_pins_from_env_variable(&pins);
21✔
1411
        if (r < 0)
21✔
1412
                return r;
1413

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

1424
        if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_HEADLESS))
5✔
1425
                return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
5✔
1426

1427
        for (;;) {
×
1428
                pins = strv_free_erase(pins);
×
1429

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

1440
                r = ask_password_auto(&req, flags, &pins);
×
1441
                if (r < 0)
×
1442
                        return r;
×
1443

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

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

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

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

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

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

1498
        assert(cd);
×
1499
        assert(name);
×
1500
        assert(arg_fido2_device || arg_fido2_device_auto);
×
1501

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

1506
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
×
1507
        if (!friendly)
×
1508
                return log_oom();
×
1509

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

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

1548
                if (r != -EAGAIN) /* EAGAIN means: token not found */
×
1549
                        return r;
1550

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

1555
                        assert(!event);
×
1556

1557
                        r = make_security_device_monitor(&event, &monitor);
×
1558
                        if (r < 0)
×
1559
                                return r;
1560

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

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

1568
                r = run_security_device_monitor(event, monitor);
×
1569
                if (r < 0)
×
1570
                        return r;
1571

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

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

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

1583
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
×
1584
                if (base64_encoded_size < 0)
×
1585
                        return log_oom();
×
1586

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

1596
        return 0;
1597
}
1598

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

1607
#if HAVE_LIBCRYPTSETUP_PLUGINS
1608
        int r;
×
1609

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

1613
        systemd_pkcs11_plugin_params params = {
×
1614
                .friendly_name = friendly_name,
1615
                .until = until,
1616
                .askpw_credential = askpw_credential,
1617
                .askpw_flags = arg_ask_password_flags,
1618
        };
1619

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

1626
        return r;
1627
#else
1628
        return -EOPNOTSUPP;
1629
#endif
1630
}
1631

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

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

1652
        assert(cd);
×
1653
        assert(name);
×
1654
        assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
×
1655

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

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

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

1676
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
×
1677
        if (!friendly)
×
1678
                return log_oom();
×
1679

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

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

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

1710
                        assert(!event);
×
1711

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

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

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

1724
                r = run_security_device_monitor(event, monitor);
×
1725
                if (r < 0)
×
1726
                        return r;
1727

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

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

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

1746
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
×
1747
                if (base64_encoded_size < 0)
×
1748
                        return log_oom();
×
1749

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

1759
        return 0;
1760
}
1761

1762
static int make_tpm2_device_monitor(
×
1763
                sd_event **ret_event,
1764
                sd_device_monitor **ret_monitor) {
1765

1766
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
×
1767
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1768
        int r;
×
1769

1770
        assert(ret_event);
×
1771
        assert(ret_monitor);
×
1772

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

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

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

1785
        (void) sd_device_monitor_set_description(monitor, "tpmrm");
×
1786

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

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

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

1799
        *ret_event = TAKE_PTR(event);
×
1800
        *ret_monitor = TAKE_PTR(monitor);
×
1801
        return 0;
×
1802
}
1803

1804
static int attach_luks2_by_tpm2_via_plugin(
10✔
1805
                struct crypt_device *cd,
1806
                const char *name,
1807
                usec_t until,
1808
                uint32_t flags) {
1809

1810
#if HAVE_LIBCRYPTSETUP_PLUGINS
1811
        systemd_tpm2_plugin_params params = {
10✔
1812
                .search_pcr_mask = arg_tpm2_pcr_mask,
1813
                .device = arg_tpm2_device,
1814
                .signature_path = arg_tpm2_signature,
1815
                .pcrlock_path = arg_tpm2_pcrlock,
1816
        };
1817

1818
        if (!use_token_plugins())
10✔
1819
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1✔
1820
                                       "libcryptsetup has external plugins support disabled.");
1821

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

1837
static int attach_luks_or_plain_or_bitlk_by_tpm2(
10✔
1838
                struct crypt_device *cd,
1839
                const char *name,
1840
                const char *key_file,
1841
                const struct iovec *key_data,
1842
                usec_t until,
1843
                uint32_t flags,
1844
                bool pass_volume_key) {
1845

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

1852
        assert(cd);
10✔
1853
        assert(name);
10✔
1854
        assert(arg_tpm2_device || arg_tpm2_device_auto);
10✔
1855

1856
        friendly = friendly_disk_name(crypt_get_device_name(cd), name);
10✔
1857
        if (!friendly)
10✔
1858
                return log_oom();
×
1859

1860
        for (;;) {
10✔
1861
                if (key_file || iovec_is_set(key_data)) {
10✔
1862
                        /* If key data is specified, use that */
1863

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

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

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

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

1931
                                CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
1✔
1932
                                CLEANUP_ARRAY(policy_hash, n_policy_hash, iovec_array_free);
1✔
1933

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

1967
                                found_some = true;
1✔
1968

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

1997
                                token++; /* try a different token next time */
×
1998
                        }
1999

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

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

2013
                        assert(!event);
×
2014

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

2019
                        r = make_tpm2_device_monitor(&event, &monitor);
×
2020
                        if (r < 0)
×
2021
                                return r;
2022

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

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

2030
                r = run_security_device_monitor(event, monitor);
×
2031
                if (r < 0)
×
2032
                        return r;
2033

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

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

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

2045
                base64_encoded_size = base64mem(decrypted_key.iov_base, decrypted_key.iov_len, &base64_encoded);
1✔
2046
                if (base64_encoded_size < 0)
1✔
2047
                        return log_oom();
×
2048

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

2058
        return 0;
2059
}
2060

2061
static int attach_luks_or_plain_or_bitlk_by_key_data(
3✔
2062
                struct crypt_device *cd,
2063
                const char *name,
2064
                const struct iovec *key_data,
2065
                uint32_t flags,
2066
                bool pass_volume_key) {
2067

2068
        int r;
3✔
2069

2070
        assert(cd);
3✔
2071
        assert(name);
3✔
2072
        assert(key_data);
3✔
2073

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

2085
        return 0;
2086
}
2087

2088
static int attach_luks_or_plain_or_bitlk_by_key_file(
21✔
2089
                struct crypt_device *cd,
2090
                const char *name,
2091
                const char *key_file,
2092
                uint32_t flags,
2093
                bool pass_volume_key) {
2094

2095
        _cleanup_(erase_and_freep) char *kfdata = NULL;
21✔
2096
        _cleanup_free_ char *bindname = NULL;
21✔
2097
        size_t kfsize;
21✔
2098
        int r;
21✔
2099

2100
        assert(cd);
21✔
2101
        assert(name);
21✔
2102
        assert(key_file);
21✔
2103

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

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

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

2138
        return 0;
2139
}
2140

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

2148
        int r;
×
2149

2150
        assert(cd);
×
2151
        assert(name);
×
2152

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

2169
        return 0;
2170
}
2171

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

2182
        bool pass_volume_key = false;
34✔
2183
        int r;
34✔
2184

2185
        assert(cd);
34✔
2186
        assert(name);
34✔
2187

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

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

2207
                if (arg_cipher) {
×
2208
                        size_t l;
×
2209

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

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

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

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

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

2235
        log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
34✔
2236
                 crypt_get_cipher(cd),
2237
                 crypt_get_cipher_mode(cd),
2238
                 crypt_get_volume_key_size(cd)*8,
2239
                 crypt_get_device_name(cd));
2240

2241
        if (token_type == TOKEN_TPM2)
34✔
2242
                return attach_luks_or_plain_or_bitlk_by_tpm2(cd, name, key_file, key_data, until, flags, pass_volume_key);
10✔
2243
        if (token_type == TOKEN_FIDO2)
24✔
2244
                return attach_luks_or_plain_or_bitlk_by_fido2(cd, name, key_file, key_data, until, flags, pass_volume_key);
×
2245
        if (token_type == TOKEN_PKCS11)
24✔
2246
                return attach_luks_or_plain_or_bitlk_by_pkcs11(cd, name, key_file, key_data, until, flags, pass_volume_key);
×
2247
        if (key_data)
24✔
2248
                return attach_luks_or_plain_or_bitlk_by_key_data(cd, name, key_data, flags, pass_volume_key);
3✔
2249
        if (key_file)
21✔
2250
                return attach_luks_or_plain_or_bitlk_by_key_file(cd, name, key_file, flags, pass_volume_key);
21✔
2251

2252
        return attach_luks_or_plain_or_bitlk_by_passphrase(cd, name, passwords, flags, pass_volume_key);
×
2253
}
2254

2255
static int help(void) {
×
2256
        _cleanup_free_ char *link = NULL;
×
2257
        int r;
×
2258

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

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

2274
        return 0;
2275
}
2276

2277
static int parse_argv(int argc, char *argv[]) {
126✔
2278
        enum {
126✔
2279
                ARG_VERSION = 0x100,
2280
        };
2281

2282
        static const struct option options[] = {
126✔
2283
                { "help",                         no_argument,       NULL, 'h'                       },
2284
                { "version",                      no_argument,       NULL, ARG_VERSION               },
2285
                {}
2286
        };
2287

2288
        int c;
126✔
2289

2290
        assert(argc >= 0);
126✔
2291
        assert(argv);
126✔
2292

2293
        if (argv_looks_like_help(argc, argv))
126✔
2294
                return help();
×
2295

2296
        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
126✔
2297
                switch (c) {
×
2298

2299
                case 'h':
×
2300
                        return help();
×
2301

2302
                case ARG_VERSION:
×
2303
                        return version();
×
2304

2305
                case '?':
2306
                        return -EINVAL;
2307

2308
                default:
×
2309
                        assert_not_reached();
×
2310
                }
2311

2312
        return 1;
2313
}
2314

2315
static uint32_t determine_flags(void) {
71✔
2316
        uint32_t flags = 0;
71✔
2317

2318
        if (arg_readonly)
71✔
2319
                flags |= CRYPT_ACTIVATE_READONLY;
×
2320

2321
        if (arg_discards)
71✔
2322
                flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
×
2323

2324
        if (arg_same_cpu_crypt)
71✔
2325
                flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT;
×
2326

2327
        if (arg_submit_from_crypt_cpus)
71✔
2328
                flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS;
×
2329

2330
        if (arg_no_read_workqueue)
71✔
2331
                flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE;
×
2332

2333
        if (arg_no_write_workqueue)
71✔
2334
                flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE;
×
2335

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

2342
        return flags;
71✔
2343
}
2344

2345
static void remove_and_erasep(const char **p) {
71✔
2346
        int r;
71✔
2347

2348
        if (!*p)
71✔
2349
                return;
2350

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

2356
static TokenType determine_token_type(void) {
48✔
2357
        if (arg_tpm2_device || arg_tpm2_device_auto)
48✔
2358
                return TOKEN_TPM2;
2359
        if (arg_fido2_device || arg_fido2_device_auto)
38✔
2360
                return TOKEN_FIDO2;
2361
        if (arg_pkcs11_uri || arg_pkcs11_uri_auto)
38✔
2362
                return TOKEN_PKCS11;
×
2363

2364
        return _TOKEN_TYPE_INVALID;
2365
}
2366

2367
static int discover_key(const char *key_file, const char *volume, TokenType token_type, struct iovec *ret_key_data) {
24✔
2368
        _cleanup_free_ char *bindname = NULL;
24✔
2369
        const char *token_type_name;
24✔
2370
        int r;
24✔
2371

2372
        assert(key_file);
24✔
2373
        assert(volume);
24✔
2374
        assert(ret_key_data);
24✔
2375

2376
        bindname = make_bindname(volume, token_type);
24✔
2377
        if (!bindname)
24✔
2378
                return log_oom();
×
2379

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

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

2391
        return r;
2392
}
2393

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

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

2406
        assert(argc >= 3 && argc <= 5);
71✔
2407

2408
        const char *volume = ASSERT_PTR(argv[1]),
71✔
2409
                *source = ASSERT_PTR(argv[2]),
71✔
2410
                *key_file = argc >= 4 ? mangle_none(argv[3]) : NULL,
71✔
2411
                *config = argc >= 5 ? mangle_none(argv[4]) : NULL;
71✔
2412

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

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

2421
        if (config) {
71✔
2422
                r = parse_crypt_config(config);
71✔
2423
                if (r < 0)
71✔
2424
                        return r;
2425
        }
2426

2427
        log_debug("%s %s ← %s type=%s cipher=%s", __func__,
196✔
2428
                  volume, source, strempty(arg_type), strempty(arg_cipher));
2429

2430
        /* A delicious drop of snake oil */
2431
        (void) mlockall(MCL_FUTURE);
71✔
2432

2433
        if (key_file && arg_keyfile_erase)
71✔
2434
                destroy_key_file = key_file; /* let's get this baby erased when we leave */
2✔
2435

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

2449
        cryptsetup_enable_logging(cd);
71✔
2450

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

2457
        flags = determine_flags();
71✔
2458

2459
        until = usec_add(now(CLOCK_MONOTONIC), arg_timeout);
71✔
2460
        if (until == USEC_INFINITY)
×
2461
                until = 0;
71✔
2462

2463
        if (arg_key_size == 0)
71✔
2464
                arg_key_size = 256U / 8U;
71✔
2465

2466
        if (key_file) {
71✔
2467
                struct stat st;
21✔
2468

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

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

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

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

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

2512
                        log_debug_errno(r, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd));
14✔
2513
                }
2514
        }
2515

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

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

2533
                log_debug("Beginning attempt %u to unlock.", tries);
48✔
2534

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

2543
                if (try_discover_key) {
48✔
2544
                        r = discover_key(discovered_key_fn, volume, token_type, &discovered_key_data);
24✔
2545
                        if (r < 0)
24✔
2546
                                return r;
2547
                        if (r > 0)
24✔
2548
                                key_data = &discovered_key_data;
1✔
2549
                }
2550

2551
                if (token_type < 0 && !key_file && !key_data && !passwords) {
48✔
2552

2553
                        /* If we have nothing to try anymore, then acquire a new password */
2554

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

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

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

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

2595
                if (token_type == TOKEN_TPM2) {
12✔
2596
                        arg_tpm2_device = mfree(arg_tpm2_device);
9✔
2597
                        arg_tpm2_device_auto = false;
9✔
2598
                        continue;
9✔
2599
                }
2600

2601
                if (token_type == TOKEN_FIDO2) {
3✔
2602
                        arg_fido2_device = mfree(arg_fido2_device);
×
2603
                        arg_fido2_device_auto = false;
×
2604
                        continue;
×
2605
                }
2606

2607
                if (token_type == TOKEN_PKCS11) {
3✔
2608
                        arg_pkcs11_uri = mfree(arg_pkcs11_uri);
×
2609
                        arg_pkcs11_uri_auto = false;
×
2610
                        continue;
×
2611
                }
2612

2613
                if (try_discover_key) {
3✔
2614
                        try_discover_key = false;
×
2615
                        continue;
×
2616
                }
2617

2618
                if (key_file) {
3✔
2619
                        key_file = NULL;
3✔
2620
                        continue;
3✔
2621
                }
2622

2623
                if (passwords) {
×
2624
                        passwords = strv_free_erase(passwords);
×
2625
                        continue;
×
2626
                }
2627

2628
                log_debug("Prepared for next attempt to unlock.");
×
2629
        }
2630

2631
        if (arg_tries != 0 && tries >= arg_tries)
22✔
2632
                return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to activate; giving up.");
×
2633

2634
        return 0;
2635
}
2636

2637
static int verb_detach(int argc, char *argv[], void *userdata) {
55✔
2638
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
55✔
2639
        const char *volume = ASSERT_PTR(argv[1]);
55✔
2640
        int r;
55✔
2641

2642
        assert(argc == 2);
55✔
2643

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

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

2655
        cryptsetup_enable_logging(cd);
55✔
2656

2657
        r = crypt_deactivate(cd, volume);
55✔
2658
        if (r < 0)
55✔
2659
                return log_error_errno(r, "Failed to deactivate '%s': %m", volume);
×
2660

2661
        return 0;
2662
}
2663

2664
static int run(int argc, char *argv[]) {
126✔
2665
        int r;
126✔
2666

2667
        log_setup();
126✔
2668

2669
        umask(0022);
126✔
2670

2671
        r = parse_argv(argc, argv);
126✔
2672
        if (r <= 0)
126✔
2673
                return r;
2674

2675
        cryptsetup_enable_logging(NULL);
126✔
2676

2677
        static const Verb verbs[] = {
126✔
2678
                { "attach", 3, 5, 0, verb_attach },
2679
                { "detach", 2, 2, 0, verb_detach },
2680
                {}
2681
        };
2682

2683
        return dispatch_verb(argc, argv, verbs, NULL);
126✔
2684
}
2685

2686
DEFINE_MAIN_FUNCTION(run);
126✔
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