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

systemd / systemd / 14766779411

30 Apr 2025 04:55PM UTC coverage: 72.225% (-0.06%) from 72.282%
14766779411

push

github

web-flow
wait-online: handle varlink connection errors while waiting for DNS (#37283)

Currently, if systemd-networkd-wait-online is started with --dns, and
systemd-resolved is not running, it will exit with an error right away.
Similarly, if systemd-resolved is restarted while waiting for DNS
configuration, systemd-networkd-wait-online will not attempt to
re-connect, and will potentially never see subsequent DNS
configurations.

Improve this by adding socket units for the systemd-resolved varlink
servers, and re-establish the connection in systemd-networkd-wait-online
when we receive `SD_VARLINK_ERROR_DISCONNECTED`.

8 of 16 new or added lines in 2 files covered. (50.0%)

5825 existing lines in 217 files now uncovered.

297168 of 411450 relevant lines covered (72.22%)

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

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

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

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

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

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

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

149
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(passphrase_type, PassphraseType);
×
150

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

157
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(token_type, TokenType);
46✔
158

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

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

173
        assert(option);
146✔
174

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

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

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

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

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

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

200
                arg_key_size /= 8;
×
201

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

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

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

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

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

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

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

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

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

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

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

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

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

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

255
                arg_keyfile_erase = r;
2✔
256

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

388
                        arg_pkcs11_uri_auto = false;
×
389
                }
390

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

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

401
                        arg_fido2_device_auto = false;
×
402
                }
403

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

474
                        arg_tpm2_device_auto = false;
×
475
                }
476

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

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

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

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

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

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

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

501
                arg_tpm2_pin = r;
×
502

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

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

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

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

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

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

530
                arg_tpm2_measure_pcr = pcr;
×
531

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

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

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

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

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

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

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

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

563
                arg_try_empty_password = r;
1✔
564

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

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

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

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

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

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

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

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

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

612
                sep += 2;
×
613

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

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

625
                        sep = c + 1;
×
626
                }
627

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

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

641
        return 0;
642
}
643

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

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

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

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

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

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

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

681
        return 0;
682
}
683

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

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

694
        assert(path);
10✔
695

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

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

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

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

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

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

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

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

729
        return NULL;
730
}
731

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

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

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

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

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

751
        return NULL;
752
}
753

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

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

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

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

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

780
        return name_buffer;
×
781
}
782

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

788
        assert(cd);
14✔
789

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

956
        strv_uniq(passwords);
×
957

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

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

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

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

974
        *ret = TAKE_PTR(passwords);
×
975

976
        return 0;
×
977
}
978

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

985
        int r;
×
986

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1067
        int r;
×
1068

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

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

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

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

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

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

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

1101
        assert(cd);
25✔
1102

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1209
                        return r;
×
1210
                }
1211

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

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

1219
        return 0;
1220
}
1221

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

1227
        switch (token_type) {
45✔
1228

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

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

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

1247
        return bindname;
45✔
1248
}
1249

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1329
                processed = true;
×
1330
        }
1331
}
1332

1333
static bool use_token_plugins(void) {
60✔
1334

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

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

1346
#if HAVE_LIBCRYPTSETUP_PLUGINS
1347
        int r;
60✔
1348

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

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

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

1368
        assert(ret_pins);
21✔
1369

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1554
                        assert(!event);
×
1555

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

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

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

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

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

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

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

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

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

1595
        return 0;
1596
}
1597

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

1606
#if HAVE_LIBCRYPTSETUP_PLUGINS
1607
        int r;
×
1608

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1709
                        assert(!event);
×
1710

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

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

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

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

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

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

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

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

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

1758
        return 0;
1759
}
1760

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1966
                                found_some = true;
1✔
1967

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

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

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

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

2012
                        assert(!event);
×
2013

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

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

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

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

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

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

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

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

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

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

2057
        return 0;
2058
}
2059

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

2067
        int r;
3✔
2068

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

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

2084
        return 0;
2085
}
2086

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

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

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

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

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

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

2137
        return 0;
2138
}
2139

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

2147
        int r;
×
2148

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

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

2168
        return 0;
2169
}
2170

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2273
        return 0;
2274
}
2275

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

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

2287
        int c;
126✔
2288

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

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

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

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

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

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

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

2311
        return 1;
2312
}
2313

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

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

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

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

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

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

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

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

2341
        return flags;
71✔
2342
}
2343

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

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

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

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

2363
        return _TOKEN_TYPE_INVALID;
2364
}
2365

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

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

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

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

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

2390
        return r;
2391
}
2392

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

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

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

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

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

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

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

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

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

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

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

2448
        cryptsetup_enable_logging(cd);
71✔
2449

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

2456
        flags = determine_flags();
71✔
2457

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2633
        return 0;
2634
}
2635

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

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

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

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

2654
        cryptsetup_enable_logging(cd);
55✔
2655

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

2660
        return 0;
2661
}
2662

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

2666
        log_setup();
126✔
2667

2668
        umask(0022);
126✔
2669

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

2674
        cryptsetup_enable_logging(NULL);
126✔
2675

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

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

2685
DEFINE_MAIN_FUNCTION(run);
252✔
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