Debian Codegraph @

src/shared/tpm2-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/file.h>
4 #include <unistd.h>
5
6 #include "sd-device.h"
7 #include "sd-dlopen.h"
8
9 #include "alloc-util.h"
10 #include "ansi-color.h"
11 #include "bitfield.h"
12 #include "boot-entry.h"
13 #include "chase.h"
14 #include "constants.h"
15 #include "creds-util.h"
16 #include "crypto-util.h"
17 #include "cryptsetup-util.h"
18 #include "device-private.h"
19 #include "device-util.h"
20 #include "dirent-util.h"
21 #include "dlfcn-util.h"
22 #include "efi-api.h"
23 #include "errno-util.h"
24 #include "extract-word.h"
25 #include "fd-util.h"
26 #include "fileio.h"
27 #include "format-table.h"
28 #include "fs-util.h"
29 #include "hexdecoct.h"
30 #include "hmac.h"
31 #include "initrd-util.h"
32 #include "io-util.h"
33 #include "json-util.h"
34 #include "log.h"
35 #include "logarithm.h"
36 #include "memory-util.h"
37 #include "mkdir.h"
38 #include "ordered-set.h"
39 #include "random-util.h"
40 #include "recurse-dir.h"
41 #include "siphash24.h"
42 #include "sort-util.h"
43 #include "sparse-endian.h"
44 #include "stat-util.h"
45 #include "string-table.h"
46 #include "string-util.h"
47 #include "strv.h"
48 #include "sync-util.h"
49 #include "time-util.h"
50 #include "tpm2-pcr.h"
51 #include "tpm2-util.h"
52 #include "unaligned.h"
53 #include "virt.h"
54
55 #if HAVE_TPM2
56 static DLSYM_PROTOTYPE(Esys_Create) = NULL;
57 static DLSYM_PROTOTYPE(Esys_CreateLoaded) = NULL;
58 static DLSYM_PROTOTYPE(Esys_CreatePrimary) = NULL;
59 static DLSYM_PROTOTYPE(Esys_EvictControl) = NULL;
60 static DLSYM_PROTOTYPE(Esys_Finalize) = NULL;
61 static DLSYM_PROTOTYPE(Esys_FlushContext) = NULL;
62 static DLSYM_PROTOTYPE(Esys_Free) = NULL;
63 static DLSYM_PROTOTYPE(Esys_GetCapability) = NULL;
64 static DLSYM_PROTOTYPE(Esys_GetRandom) = NULL;
65 static DLSYM_PROTOTYPE(Esys_Import) = NULL;
66 static DLSYM_PROTOTYPE(Esys_Initialize) = NULL;
67 static DLSYM_PROTOTYPE(Esys_Load) = NULL;
68 static DLSYM_PROTOTYPE(Esys_LoadExternal) = NULL;
69 static DLSYM_PROTOTYPE(Esys_NV_DefineSpace) = NULL;
70 static DLSYM_PROTOTYPE(Esys_NV_Extend) = NULL;
71 static DLSYM_PROTOTYPE(Esys_NV_Read) = NULL;
72 static DLSYM_PROTOTYPE(Esys_NV_ReadPublic) = NULL;
73 static DLSYM_PROTOTYPE(Esys_NV_UndefineSpace) = NULL;
74 static DLSYM_PROTOTYPE(Esys_NV_Write) = NULL;
75 static DLSYM_PROTOTYPE(Esys_PCR_Extend) = NULL;
76 static DLSYM_PROTOTYPE(Esys_PCR_Read) = NULL;
77 static DLSYM_PROTOTYPE(Esys_PolicyAuthValue) = NULL;
78 static DLSYM_PROTOTYPE(Esys_PolicyAuthorize) = NULL;
79 static DLSYM_PROTOTYPE(Esys_PolicyAuthorizeNV) = NULL;
80 static DLSYM_PROTOTYPE(Esys_PolicyGetDigest) = NULL;
81 static DLSYM_PROTOTYPE(Esys_PolicyOR) = NULL;
82 static DLSYM_PROTOTYPE(Esys_PolicyPCR) = NULL;
83 static DLSYM_PROTOTYPE(Esys_PolicySigned) = NULL;
84 static DLSYM_PROTOTYPE(Esys_ReadPublic) = NULL;
85 static DLSYM_PROTOTYPE(Esys_StartAuthSession) = NULL;
86 static DLSYM_PROTOTYPE(Esys_Startup) = NULL;
87 static DLSYM_PROTOTYPE(Esys_TestParms) = NULL;
88 static DLSYM_PROTOTYPE(Esys_TR_Close) = NULL;
89 static DLSYM_PROTOTYPE(Esys_TR_Deserialize) = NULL;
90 static DLSYM_PROTOTYPE(Esys_TR_FromTPMPublic) = NULL;
91 static DLSYM_PROTOTYPE(Esys_TR_GetName) = NULL;
92 static DLSYM_PROTOTYPE(Esys_TR_GetTpmHandle) = NULL;
93 static DLSYM_PROTOTYPE(Esys_TR_Serialize) = NULL;
94 static DLSYM_PROTOTYPE(Esys_TR_SetAuth) = NULL;
95 static DLSYM_PROTOTYPE(Esys_TRSess_GetAttributes) = NULL;
96 static DLSYM_PROTOTYPE(Esys_TRSess_GetNonceTPM) = NULL;
97 static DLSYM_PROTOTYPE(Esys_TRSess_SetAttributes) = NULL;
98 static DLSYM_PROTOTYPE(Esys_Unseal) = NULL;
99 static DLSYM_PROTOTYPE(Esys_VerifySignature) = NULL;
100
101 static DLSYM_PROTOTYPE(Tss2_MU_TPM2_CC_Marshal) = NULL;
102 static DLSYM_PROTOTYPE(Tss2_MU_TPM2_HANDLE_Marshal) = NULL;
103 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_DIGEST_Marshal) = NULL;
104 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_ENCRYPTED_SECRET_Marshal) = NULL;
105 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_ENCRYPTED_SECRET_Unmarshal) = NULL;
106 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_NAME_Marshal) = NULL;
107 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_PRIVATE_Marshal) = NULL;
108 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_PRIVATE_Unmarshal) = NULL;
109 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_PUBLIC_Marshal) = NULL;
110 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_PUBLIC_Unmarshal) = NULL;
111 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_SENSITIVE_Marshal) = NULL;
112 static DLSYM_PROTOTYPE(Tss2_MU_TPML_PCR_SELECTION_Marshal) = NULL;
113 static DLSYM_PROTOTYPE(Tss2_MU_TPMS_NV_PUBLIC_Marshal) = NULL;
114 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_NV_PUBLIC_Marshal) = NULL;
115 static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_NV_PUBLIC_Unmarshal) = NULL;
116 static DLSYM_PROTOTYPE(Tss2_MU_TPMS_ECC_POINT_Marshal) = NULL;
117 static DLSYM_PROTOTYPE(Tss2_MU_TPMT_HA_Marshal) = NULL;
118 static DLSYM_PROTOTYPE(Tss2_MU_TPMT_PUBLIC_Marshal) = NULL;
119 static DLSYM_PROTOTYPE(Tss2_MU_UINT32_Marshal) = NULL;
120
121 static DLSYM_PROTOTYPE(Tss2_RC_Decode) = NULL;
122
123 static int dlopen_tpm2_esys(int log_level) {
124 static void *libtss2_esys_dl = NULL;
125 int r;
126
127 TPM2_ESYS_NOTE(SD_ELF_NOTE_DLOPEN_PRIORITY_SUGGESTED);
128
129 r = dlopen_many_sym_or_warn(
130 &libtss2_esys_dl, "libtss2-esys.so.0", log_level,
131 DLSYM_ARG(Esys_Create),
132 DLSYM_ARG(Esys_CreateLoaded),
133 DLSYM_ARG(Esys_CreatePrimary),
134 DLSYM_ARG(Esys_EvictControl),
135 DLSYM_ARG(Esys_Finalize),
136 DLSYM_ARG(Esys_FlushContext),
137 DLSYM_ARG(Esys_Free),
138 DLSYM_ARG(Esys_GetCapability),
139 DLSYM_ARG(Esys_GetRandom),
140 DLSYM_ARG(Esys_Import),
141 DLSYM_ARG(Esys_Initialize),
142 DLSYM_ARG(Esys_Load),
143 DLSYM_ARG(Esys_LoadExternal),
144 DLSYM_ARG(Esys_NV_DefineSpace),
145 DLSYM_ARG(Esys_NV_Extend),
146 DLSYM_ARG(Esys_NV_Read),
147 DLSYM_ARG(Esys_NV_ReadPublic),
148 DLSYM_ARG(Esys_NV_UndefineSpace),
149 DLSYM_ARG(Esys_NV_Write),
150 DLSYM_ARG(Esys_PCR_Extend),
151 DLSYM_ARG(Esys_PCR_Read),
152 DLSYM_ARG(Esys_PolicyAuthValue),
153 DLSYM_ARG(Esys_PolicyAuthorize),
154 DLSYM_ARG(Esys_PolicyAuthorizeNV),
155 DLSYM_ARG(Esys_PolicyGetDigest),
156 DLSYM_ARG(Esys_PolicyOR),
157 DLSYM_ARG(Esys_PolicyPCR),
158 DLSYM_ARG(Esys_PolicySigned),
159 DLSYM_ARG(Esys_ReadPublic),
160 DLSYM_ARG(Esys_StartAuthSession),
161 DLSYM_ARG(Esys_Startup),
162 DLSYM_ARG(Esys_TestParms),
163 DLSYM_ARG(Esys_TR_Close),
164 DLSYM_ARG(Esys_TR_Deserialize),
165 DLSYM_ARG(Esys_TR_FromTPMPublic),
166 DLSYM_ARG(Esys_TR_GetName),
167 DLSYM_ARG(Esys_TR_Serialize),
168 DLSYM_ARG(Esys_TR_SetAuth),
169 DLSYM_ARG(Esys_TRSess_GetAttributes),
170 DLSYM_ARG(Esys_TRSess_GetNonceTPM),
171 DLSYM_ARG(Esys_TRSess_SetAttributes),
172 DLSYM_ARG(Esys_Unseal),
173 DLSYM_ARG(Esys_VerifySignature));
174 if (r < 0)
175 return r;
176
177 /* Esys_TR_GetTpmHandle was added to tpm2-tss in version 2.4.0. Once we can set a minimum tpm2-tss
178 * version of 2.4.0 this sym can be moved up to the normal list above. */
179 r = dlsym_many_or_warn(libtss2_esys_dl, LOG_DEBUG, DLSYM_ARG_FORCE(Esys_TR_GetTpmHandle));
180 if (r < 0)
181 log_debug("libtss2-esys too old, does not include Esys_TR_GetTpmHandle.");
182
183 return 0;
184 }
185
186 static int dlopen_tpm2_rc(int log_level) {
187 static void *libtss2_rc_dl = NULL;
188
189 TPM2_RC_NOTE(SD_ELF_NOTE_DLOPEN_PRIORITY_SUGGESTED);
190
191 return dlopen_many_sym_or_warn(
192 &libtss2_rc_dl, "libtss2-rc.so.0", log_level,
193 DLSYM_ARG(Tss2_RC_Decode));
194 }
195
196 static int dlopen_tpm2_mu(int log_level) {
197 static void *libtss2_mu_dl = NULL;
198
199 TPM2_MU_NOTE(SD_ELF_NOTE_DLOPEN_PRIORITY_SUGGESTED);
200
201 return dlopen_many_sym_or_warn(
202 &libtss2_mu_dl, "libtss2-mu.so.0", log_level,
203 DLSYM_ARG(Tss2_MU_TPM2_CC_Marshal),
204 DLSYM_ARG(Tss2_MU_TPM2_HANDLE_Marshal),
205 DLSYM_ARG(Tss2_MU_TPM2B_DIGEST_Marshal),
206 DLSYM_ARG(Tss2_MU_TPM2B_ENCRYPTED_SECRET_Marshal),
207 DLSYM_ARG(Tss2_MU_TPM2B_ENCRYPTED_SECRET_Unmarshal),
208 DLSYM_ARG(Tss2_MU_TPM2B_NAME_Marshal),
209 DLSYM_ARG(Tss2_MU_TPM2B_PRIVATE_Marshal),
210 DLSYM_ARG(Tss2_MU_TPM2B_PRIVATE_Unmarshal),
211 DLSYM_ARG(Tss2_MU_TPM2B_PUBLIC_Marshal),
212 DLSYM_ARG(Tss2_MU_TPM2B_PUBLIC_Unmarshal),
213 DLSYM_ARG(Tss2_MU_TPM2B_SENSITIVE_Marshal),
214 DLSYM_ARG(Tss2_MU_TPML_PCR_SELECTION_Marshal),
215 DLSYM_ARG(Tss2_MU_TPMS_NV_PUBLIC_Marshal),
216 DLSYM_ARG(Tss2_MU_TPM2B_NV_PUBLIC_Marshal),
217 DLSYM_ARG(Tss2_MU_TPM2B_NV_PUBLIC_Unmarshal),
218 DLSYM_ARG(Tss2_MU_TPMS_ECC_POINT_Marshal),
219 DLSYM_ARG(Tss2_MU_TPMT_HA_Marshal),
220 DLSYM_ARG(Tss2_MU_TPMT_PUBLIC_Marshal),
221 DLSYM_ARG(Tss2_MU_UINT32_Marshal));
222 }
223
224 static int dlopen_tpm2_tcti_device(int log_level) {
225 static void *libtss2_tcti_device_dl = NULL;
226
227 /* The "device" TCTI is the most relevant one, let's also load it explicitly on dlopen_tpm2(), even
228 * if we don't resolve any symbols here. */
229
230 TPM2_TCTI_DEVICE_NOTE(SD_ELF_NOTE_DLOPEN_PRIORITY_SUGGESTED);
231
232 return dlopen_verbose(
233 &libtss2_tcti_device_dl,
234 "libtss2-tcti-device.so.0",
235 log_level);
236 }
237
238 #endif
239
240 int dlopen_tpm2(int log_level) {
241 #if HAVE_TPM2
242 int r;
243
244 r = dlopen_tpm2_esys(log_level);
245 if (r < 0)
246 return r;
247
248 r = dlopen_tpm2_rc(log_level);
249 if (r < 0)
250 return r;
251
252 r = dlopen_tpm2_mu(log_level);
253 if (r < 0)
254 return r;
255
256 r = dlopen_tpm2_tcti_device(log_level);
257 if (r < 0)
258 return r;
259
260 return 0;
261 #else
262 return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
263 "TPM2 support is not compiled in.");
264 #endif
265 }
266
267 #if HAVE_TPM2
268
269 void Esys_Freep(void *p) {
270 assert(p);
271
272 if (*(void**) p)
273 sym_Esys_Free(*(void**) p);
274 }
275
276 static void tpm2b_sensitive_data_erase_and_esys_freep(TPM2B_SENSITIVE_DATA **p) {
277 assert(p);
278
279 if (!*p)
280 return;
281
282 explicit_bzero_safe((*p)->buffer, (*p)->size);
283 sym_Esys_Free(*p);
284 }
285
286 /* Get a specific TPM capability (or capabilities).
287 *
288 * Returns 0 if there are no more capability properties of the requested type, or 1 if there are more, or < 0
289 * on any error. Both 0 and 1 indicate this completed successfully, but do not indicate how many capability
290 * properties were provided in 'ret_capability_data'. To find the number of provided properties, check the
291 * specific type's 'count' field (e.g. for TPM2_CAP_ALGS, check ret_capability_data->algorithms.count).
292 *
293 * This calls TPM2_GetCapability() and does not alter the provided data, so it is important to understand how
294 * that TPM function works. It is recommended to check the TCG TPM specification Part 3 ("Commands") section
295 * on TPM2_GetCapability() for full details, but a short summary is: if this returns 0, all available
296 * properties have been provided in ret_capability_data, or no properties were available. If this returns 1,
297 * there are between 1 and "count" properties provided in ret_capability_data, and there are more available.
298 * Note that this may provide less than "count" properties even if the TPM has more available. Also, each
299 * capability category may have more specific requirements than described here; see the spec for exact
300 * details. */
301 static int tpm2_get_capability(
302 Tpm2Context *c,
303 TPM2_CAP capability,
304 uint32_t property,
305 uint32_t count,
306 TPMU_CAPABILITIES *ret_capability_data) {
307
308 _cleanup_(Esys_Freep) TPMS_CAPABILITY_DATA *capabilities = NULL;
309 TPMI_YES_NO more;
310 TSS2_RC rc;
311
312 assert(c);
313
314 log_debug("Getting TPM2 capability 0x%04" PRIx32 " property 0x%04" PRIx32 " count %" PRIu32 ".",
315 capability, property, count);
316
317 rc = sym_Esys_GetCapability(
318 c->esys_context,
319 ESYS_TR_NONE,
320 ESYS_TR_NONE,
321 ESYS_TR_NONE,
322 capability,
323 property,
324 count,
325 &more,
326 &capabilities);
327 if (rc == TPM2_RC_VALUE)
328 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO),
329 "Requested TPM2 capability 0x%04" PRIx32 " property 0x%04" PRIx32 " apparently doesn't exist: %s",
330 capability, property, sym_Tss2_RC_Decode(rc));
331 if (rc != TSS2_RC_SUCCESS)
332 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
333 "Failed to get TPM2 capability 0x%04" PRIx32 " property 0x%04" PRIx32 ": %s",
334 capability, property, sym_Tss2_RC_Decode(rc));
335 if (capabilities->capability != capability)
336 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
337 "TPM provided wrong capability: 0x%04" PRIx32 " instead of 0x%04" PRIx32 ".",
338 capabilities->capability, capability);
339
340 if (ret_capability_data)
341 *ret_capability_data = capabilities->data;
342
343 return more == TPM2_YES;
344 }
345
346 int tpm2_vendor_info_to_modalias(const Tpm2VendorInfo *info, char **ret) {
347 _cleanup_free_ char *m = NULL;
348
349 assert(info);
350 assert(ret);
351
352 /* Closely inspired by kernel modalias strings, this distills information from the TPM vendor data
353 * into a string suitable for matching hwdb */
354
355 if (asprintf(&m,
356 "fi%s:"
357 "lv%" PRIu32 ":"
358 "rv%" PRIu32 ".%" PRIu32 ":"
359 "sy%" PRIu32 ":"
360 "sd%" PRIu32 ":"
361 "mf%s:"
362 "vs%s:"
363 "ty%" PRIx32 ":"
364 "fw%" PRIu16 ".%" PRIu16 ".%" PRIu32 ":",
365 info->family_indicator,
366 info->level,
367 info->revision_major,
368 info->revision_minor,
369 info->year,
370 info->day_of_year,
371 info->manufacturer,
372 info->vendor_string,
373 info->vendor_tpm_type,
374 info->firmware_version_major,
375 info->firmware_version_minor,
376 info->firmware_version2) < 0)
377 return -ENOMEM;
378
379 *ret = TAKE_PTR(m);
380 return 0;
381 }
382
383 static char *mangle_vendor_chars(char *c, size_t n) {
384 char *end = c;
385 assert(c || n == 0);
386
387 /* Suppress all control characters, whitespace and non-ASCII bytes */
388 for (char *x = c; x < c + n; x++) {
389 if (!IN_SET(*x, ' ', 0))
390 end = x + 1;
391
392 if ((unsigned char) *x <= (unsigned char) ' ' ||
393 (unsigned char) *x >= 127)
394 *x = '_';
395 }
396
397 /* Drop trailing spaces and NUL bytes */
398 *end = 0;
399 return c;
400 }
401
402 int tpm2_get_vendor_info(
403 Tpm2Context *c,
404 Tpm2VendorInfo *ret) {
405
406 int r;
407
408 assert(c);
409 assert(ret);
410
411 TPMU_CAPABILITIES capabilities = {};
412 r = tpm2_get_capability(
413 c,
414 TPM2_CAP_TPM_PROPERTIES,
415 TPM2_PT_FAMILY_INDICATOR,
416 TPM2_PT_FIRMWARE_VERSION_2 - TPM2_PT_FAMILY_INDICATOR + 1, /* get all relevant fields at once */
417 &capabilities);
418 if (r < 0)
419 return r;
420
421 Tpm2VendorInfo info = {};
422
423 for (uint32_t i = 0; i < capabilities.tpmProperties.count; i++) {
424 TPMS_TAGGED_PROPERTY *p = capabilities.tpmProperties.tpmProperty + i;
425
426 switch (p->property) {
427
428 case TPM2_PT_FAMILY_INDICATOR:
429 unaligned_write_be32(info.family_indicator, p->value);
430 mangle_vendor_chars(info.family_indicator, sizeof(info.family_indicator));
431 break;
432
433 case TPM2_PT_LEVEL:
434 info.level = p->value;
435 break;
436
437 case TPM2_PT_REVISION:
438 info.revision_major = p->value / 100;
439 info.revision_minor = p->value % 100;
440 break;
441
442 case TPM2_PT_DAY_OF_YEAR:
443 info.day_of_year = p->value;
444 break;
445
446 case TPM2_PT_YEAR:
447 info.year = p->value;
448 break;
449
450 case TPM2_PT_MANUFACTURER:
451 unaligned_write_be32(info.manufacturer, p->value);
452 mangle_vendor_chars(info.manufacturer, sizeof(info.manufacturer));
453 break;
454
455 case TPM2_PT_VENDOR_STRING_1:
456 unaligned_write_be32(info.vendor_string+0, p->value);
457 break;
458
459 case TPM2_PT_VENDOR_STRING_2:
460 unaligned_write_be32(info.vendor_string+4, p->value);
461 break;
462
463 case TPM2_PT_VENDOR_STRING_3:
464 unaligned_write_be32(info.vendor_string+8, p->value);
465 break;
466
467 case TPM2_PT_VENDOR_STRING_4:
468 unaligned_write_be32(info.vendor_string+12, p->value);
469 break;
470
471 case TPM2_PT_VENDOR_TPM_TYPE:
472 info.vendor_tpm_type = p->value;
473 break;
474
475 case TPM2_PT_FIRMWARE_VERSION_1:
476 info.firmware_version_major = p->value >> 16;
477 info.firmware_version_minor = p->value & 0xFFFFU;
478 break;
479
480 case TPM2_PT_FIRMWARE_VERSION_2:
481 info.firmware_version2 = p->value;
482 break;
483 }
484 }
485
486 mangle_vendor_chars(info.vendor_string, sizeof(info.vendor_string));
487 *ret = TAKE_STRUCT(info);
488 return 0;
489 }
490
491 #define TPMA_CC_TO_TPM2_CC(cca) (((cca) & TPMA_CC_COMMANDINDEX_MASK) >> TPMA_CC_COMMANDINDEX_SHIFT)
492
493 static int tpm2_cache_capabilities(Tpm2Context *c) {
494 TPMU_CAPABILITIES capability;
495 int r;
496
497 assert(c);
498
499 /* Cache the algorithms. The spec indicates supported algorithms can only be modified during runtime
500 * by the SetAlgorithmSet() command. Unfortunately, the spec doesn't require a TPM reinitialization
501 * after changing the algorithm set (unless the PCR algorithms are changed). However, the spec also
502 * indicates the TPM behavior after SetAlgorithmSet() is "vendor-dependent", giving the example of
503 * flushing sessions and objects, erasing policies, etc. So, if the algorithm set is programmatically
504 * changed while we are performing some operation, it's reasonable to assume it will break us even if
505 * we don't cache the algorithms, thus they should be "safe" to cache. */
506 TPM2_ALG_ID current_alg = TPM2_ALG_FIRST;
507 for (;;) {
508 r = tpm2_get_capability(
509 c,
510 TPM2_CAP_ALGS,
511 (uint32_t) current_alg, /* The spec states to cast TPM2_ALG_ID to uint32_t. */
512 TPM2_MAX_CAP_ALGS,
513 &capability);
514 if (r < 0)
515 return r;
516
517 TPML_ALG_PROPERTY algorithms = capability.algorithms;
518
519 /* We should never get 0; the TPM must support some algorithms, and it must not set 'more' if
520 * there are no more. */
521 assert(algorithms.count > 0);
522
523 if (!GREEDY_REALLOC_APPEND(
524 c->capability_algorithms,
525 c->n_capability_algorithms,
526 algorithms.algProperties,
527 algorithms.count))
528 return log_oom_debug();
529
530 if (r == 0)
531 break;
532
533 /* Set current_alg to alg id after last alg id the TPM provided */
534 current_alg = algorithms.algProperties[algorithms.count - 1].alg + 1;
535 }
536
537 /* Cache the command capabilities. The spec isn't actually clear if commands can be added/removed
538 * while running, but that would be crazy, so let's hope it is not possible. */
539 TPM2_CC current_cc = TPM2_CC_FIRST;
540 for (;;) {
541 r = tpm2_get_capability(
542 c,
543 TPM2_CAP_COMMANDS,
544 current_cc,
545 TPM2_MAX_CAP_CC,
546 &capability);
547 if (r < 0)
548 return r;
549
550 TPML_CCA commands = capability.command;
551
552 /* We should never get 0; the TPM must support some commands, and it must not set 'more' if
553 * there are no more. */
554 assert(commands.count > 0);
555
556 if (!GREEDY_REALLOC_APPEND(
557 c->capability_commands,
558 c->n_capability_commands,
559 commands.commandAttributes,
560 commands.count))
561 return log_oom_debug();
562
563 if (r == 0)
564 break;
565
566 /* Set current_cc to index after last cc the TPM provided */
567 current_cc = TPMA_CC_TO_TPM2_CC(commands.commandAttributes[commands.count - 1]) + 1;
568 }
569
570 /* Cache the ECC curves. The spec isn't actually clear if ECC curves can be added/removed
571 * while running, but that would be crazy, so let's hope it is not possible. */
572 TPM2_ECC_CURVE current_ecc_curve = TPM2_ECC_NONE;
573 for (;;) {
574 r = tpm2_get_capability(
575 c,
576 TPM2_CAP_ECC_CURVES,
577 current_ecc_curve,
578 TPM2_MAX_ECC_CURVES,
579 &capability);
580 if (r == -ENXIO) /* If the TPM doesn't support ECC, it might return TPM2_RC_VALUE rather than capability.eccCurves == 0 */
581 break;
582 if (r < 0)
583 return r;
584
585 TPML_ECC_CURVE ecc_curves = capability.eccCurves;
586
587 /* ECC support isn't required */
588 if (ecc_curves.count == 0)
589 break;
590
591 if (!GREEDY_REALLOC_APPEND(
592 c->capability_ecc_curves,
593 c->n_capability_ecc_curves,
594 ecc_curves.eccCurves,
595 ecc_curves.count))
596 return log_oom_debug();
597
598 if (r == 0)
599 break;
600
601 /* Set current_ecc_curve to index after last ecc curve the TPM provided */
602 current_ecc_curve = ecc_curves.eccCurves[ecc_curves.count - 1] + 1;
603 }
604
605 /* Cache the PCR capabilities, which are safe to cache, as the only way they can change is
606 * TPM2_PCR_Allocate(), which changes the allocation after the next _TPM_Init(). If the TPM is
607 * reinitialized while we are using it, all our context and sessions will be invalid, so we can
608 * safely assume the TPM PCR allocation will not change while we are using it. */
609 r = tpm2_get_capability(
610 c,
611 TPM2_CAP_PCRS,
612 /* property= */ 0,
613 /* count= */ 1,
614 &capability);
615 if (r < 0)
616 return r;
617 if (r == 1)
618 /* This should never happen. Part 3 ("Commands") of the TCG TPM2 spec in the section for
619 * TPM2_GetCapability states: "TPM_CAP_PCRS – Returns the current allocation of PCR in a
620 * TPML_PCR_SELECTION. The property parameter shall be zero. The TPM will always respond to
621 * this command with the full PCR allocation and moreData will be NO." */
622 log_debug("TPM bug: reported multiple PCR sets; using only first set.");
623 c->capability_pcrs = capability.assignedPCR;
624
625 return 0;
626 }
627
628 /* Get the TPMA_ALGORITHM for a TPM2_ALG_ID. Returns true if the TPM supports the algorithm and the
629 * TPMA_ALGORITHM is provided, otherwise false. */
630 static bool tpm2_get_capability_alg(Tpm2Context *c, TPM2_ALG_ID alg, TPMA_ALGORITHM *ret) {
631 assert(c);
632
633 FOREACH_ARRAY(alg_prop, c->capability_algorithms, c->n_capability_algorithms)
634 if (alg_prop->alg == alg) {
635 if (ret)
636 *ret = alg_prop->algProperties;
637 return true;
638 }
639
640 log_debug("TPM does not support alg 0x%02" PRIx16 ".", alg);
641 if (ret)
642 *ret = 0;
643
644 return false;
645 }
646
647 bool tpm2_supports_alg(Tpm2Context *c, TPM2_ALG_ID alg) {
648 return tpm2_get_capability_alg(c, alg, NULL);
649 }
650
651 /* Get the TPMA_CC for a TPM2_CC. Returns true if the TPM supports the command and the TPMA_CC is provided,
652 * otherwise false. */
653 static bool tpm2_get_capability_command(Tpm2Context *c, TPM2_CC command, TPMA_CC *ret) {
654 assert(c);
655
656 FOREACH_ARRAY(cca, c->capability_commands, c->n_capability_commands)
657 if (TPMA_CC_TO_TPM2_CC(*cca) == command) {
658 if (ret)
659 *ret = *cca;
660 return true;
661 }
662
663 log_debug("TPM does not support command 0x%04" PRIx32 ".", command);
664 if (ret)
665 *ret = 0;
666
667 return false;
668 }
669
670 bool tpm2_supports_command(Tpm2Context *c, TPM2_CC command) {
671 return tpm2_get_capability_command(c, command, NULL);
672 }
673
674 /* Returns true if the TPM supports the ECC curve, otherwise false. */
675 bool tpm2_supports_ecc_curve(Tpm2Context *c, TPM2_ECC_CURVE ecc_curve) {
676 assert(c);
677
678 FOREACH_ARRAY(curve, c->capability_ecc_curves, c->n_capability_ecc_curves)
679 if (*curve == ecc_curve)
680 return true;
681
682 log_debug("TPM does not support ECC curve 0x%" PRIx16 ".", ecc_curve);
683 return false;
684 }
685
686 /* Query the TPM for populated handles.
687 *
688 * This provides an array of handle indexes populated in the TPM, starting at the requested handle. The array will
689 * contain only populated handle addresses (which might not include the requested handle). The number of
690 * handles will be no more than the 'max' number requested. This will not search past the end of the handle
691 * range (i.e. handle & 0xff000000).
692 *
693 * Returns 0 if all populated handles in the range (starting at the requested handle) were provided (or no
694 * handles were in the range), or 1 if there are more populated handles in the range, or < 0 on any error. */
695 static int tpm2_get_capability_handles(
696 Tpm2Context *c,
697 TPM2_HANDLE start,
698 size_t max,
699 TPM2_HANDLE **ret_handles,
700 size_t *ret_n_handles) {
701
702 _cleanup_free_ TPM2_HANDLE *handles = NULL;
703 size_t n_handles = 0;
704 TPM2_HANDLE current = start;
705 int r = 0;
706
707 assert(c);
708 assert(ret_handles);
709 assert(ret_n_handles);
710
711 max = MIN(max, UINT32_MAX);
712
713 while (max > 0) {
714 TPMU_CAPABILITIES capability;
715 r = tpm2_get_capability(c, TPM2_CAP_HANDLES, current, (uint32_t) max, &capability);
716 if (r < 0)
717 return r;
718
719 TPML_HANDLE handle_list = capability.handles;
720 if (handle_list.count == 0)
721 break;
722
723 assert(handle_list.count <= max);
724
725 if (n_handles > SIZE_MAX - handle_list.count)
726 return log_oom_debug();
727
728 if (!GREEDY_REALLOC_APPEND(handles, n_handles, handle_list.handle, handle_list.count))
729 return log_oom_debug();
730
731 max -= handle_list.count;
732
733 /* Update current to the handle index after the last handle in the list. */
734 current = handles[n_handles - 1] + 1;
735
736 if (r == 0)
737 /* No more handles in this range. */
738 break;
739 }
740
741 *ret_handles = TAKE_PTR(handles);
742 *ret_n_handles = n_handles;
743
744 return r;
745 }
746
747 #define TPM2_HANDLE_RANGE(h) ((TPM2_HANDLE)((h) & TPM2_HR_RANGE_MASK))
748 #define TPM2_HANDLE_TYPE(h) ((TPM2_HT)(TPM2_HANDLE_RANGE(h) >> TPM2_HR_SHIFT))
749
750 /* Returns 1 if the handle is populated in the TPM, 0 if not, and < 0 on any error. */
751 static int tpm2_get_capability_handle(Tpm2Context *c, TPM2_HANDLE handle) {
752 _cleanup_free_ TPM2_HANDLE *handles = NULL;
753 size_t n_handles = 0;
754 int r;
755
756 r = tpm2_get_capability_handles(c, handle, 1, &handles, &n_handles);
757 if (r < 0)
758 return r;
759
760 return n_handles == 0 ? false : handles[0] == handle;
761 }
762
763 /* Returns 1 if the TPM supports the parms, or 0 if the TPM does not support the parms. */
764 bool tpm2_test_parms(Tpm2Context *c, TPMI_ALG_PUBLIC alg, const TPMU_PUBLIC_PARMS *parms) {
765 TSS2_RC rc;
766
767 assert(c);
768 assert(parms);
769
770 TPMT_PUBLIC_PARMS parameters = {
771 .type = alg,
772 .parameters = *parms,
773 };
774
775 rc = sym_Esys_TestParms(c->esys_context, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, &parameters);
776 if (rc != TSS2_RC_SUCCESS)
777 /* The spec says if the parms are not supported the TPM returns "...the appropriate
778 * unmarshaling error if a parameter is not valid". Since the spec (currently) defines 15
779 * unmarshaling errors, instead of checking for them all here, let's just assume any error
780 * indicates unsupported parms, and log the specific error text. */
781 log_debug("TPM does not support tested parms: %s", sym_Tss2_RC_Decode(rc));
782
783 return rc == TSS2_RC_SUCCESS;
784 }
785
786 static bool tpm2_supports_tpmt_public(Tpm2Context *c, const TPMT_PUBLIC *public) {
787 assert(c);
788 assert(public);
789
790 return tpm2_test_parms(c, public->type, &public->parameters);
791 }
792
793 static bool tpm2_supports_tpmt_sym_def_object(Tpm2Context *c, const TPMT_SYM_DEF_OBJECT *parameters) {
794 assert(c);
795 assert(parameters);
796
797 TPMU_PUBLIC_PARMS parms = {
798 .symDetail.sym = *parameters,
799 };
800
801 return tpm2_test_parms(c, TPM2_ALG_SYMCIPHER, &parms);
802 }
803
804 static bool tpm2_supports_tpmt_sym_def(Tpm2Context *c, const TPMT_SYM_DEF *parameters) {
805 assert(c);
806 assert(parameters);
807
808 /* Unfortunately, TPMT_SYM_DEF and TPMT_SYM_DEF_OBJECT are separately defined, even though they are
809 * functionally identical. */
810 TPMT_SYM_DEF_OBJECT object = {
811 .algorithm = parameters->algorithm,
812 .keyBits = parameters->keyBits,
813 .mode = parameters->mode,
814 };
815
816 return tpm2_supports_tpmt_sym_def_object(c, &object);
817 }
818
819 static Tpm2Context *tpm2_context_free(Tpm2Context *c) {
820 if (!c)
821 return NULL;
822
823 if (c->esys_context)
824 sym_Esys_Finalize(&c->esys_context);
825
826 c->tcti_context = mfree(c->tcti_context);
827 c->tcti_dl = safe_dlclose(c->tcti_dl);
828
829 c->capability_algorithms = mfree(c->capability_algorithms);
830 c->capability_commands = mfree(c->capability_commands);
831 c->capability_ecc_curves = mfree(c->capability_ecc_curves);
832
833 c->tcti_driver = mfree(c->tcti_driver);
834 c->tcti_param = mfree(c->tcti_param);
835
836 return mfree(c);
837 }
838
839 DEFINE_TRIVIAL_REF_UNREF_FUNC(Tpm2Context, tpm2_context, tpm2_context_free);
840
841 static const TPMT_SYM_DEF SESSION_TEMPLATE_SYM_AES_128_CFB = {
842 .algorithm = TPM2_ALG_AES,
843 .keyBits.aes = 128,
844 .mode.aes = TPM2_ALG_CFB, /* The spec requires sessions to use CFB. */
845 };
846
847 int tpm2_context_new(const char *device, Tpm2Context **ret_context) {
848 _cleanup_(tpm2_context_unrefp) Tpm2Context *context = NULL;
849 TSS2_RC rc;
850 int r;
851
852 assert(ret_context);
853
854 context = new(Tpm2Context, 1);
855 if (!context)
856 return log_oom_debug();
857
858 *context = (Tpm2Context) {
859 .n_ref = 1,
860 };
861
862 r = dlopen_tpm2(LOG_DEBUG);
863 if (r < 0)
864 return r;
865
866 if (!device) {
867 device = secure_getenv("SYSTEMD_TPM2_DEVICE");
868 if (device)
869 /* Setting the env var to an empty string forces tpm2-tss' own device picking
870 * logic to be used. */
871 device = empty_to_null(device);
872 else
873 /* If nothing was specified explicitly, we'll use a hardcoded default: the "device" tcti
874 * driver and the "/dev/tpmrm0" device. We do this since on some distributions the tpm2-abrmd
875 * might be used and we really don't want that, since it is a system service and that creates
876 * various ordering issues/deadlocks during early boot. */
877 device = "device:/dev/tpmrm0";
878 }
879
880 if (device) {
881 _cleanup_free_ char *_driver = NULL;
882 const char *param, *driver;
883 const TSS2_TCTI_INFO* info;
884 TSS2_TCTI_INFO_FUNC func;
885 size_t sz = 0;
886
887 param = strchr(device, ':');
888 if (param) {
889 /* Syntax #1: Pair of driver string and arbitrary parameter */
890 driver = _driver = strndup(device, param - device);
891 if (!driver)
892 return log_oom_debug();
893 if (isempty(driver))
894 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 driver name is empty, refusing.");
895
896 param++;
897 } else if (path_is_absolute(device) && path_is_valid(device)) {
898 /* Syntax #2: TPM device node */
899 driver = "device";
900 param = device;
901 } else
902 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid TPM2 driver string, refusing.");
903
904 log_debug("Using TPM2 TCTI driver '%s' with device '%s'.", driver, param);
905
906 _cleanup_free_ char *fn = strjoin("libtss2-tcti-", driver, ".so.0");
907 if (!fn)
908 return log_oom_debug();
909
910 /* Better safe than sorry, let's refuse strings that cannot possibly be valid driver early, before going to disk. */
911 if (!filename_is_valid(fn))
912 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 driver name '%s' not valid, refusing.", driver);
913
914 const char *dle = NULL;
915 r = dlopen_safe(fn, &context->tcti_dl, &dle);
916 if (r < 0) {
917 log_debug_errno(r, "Failed to load %s: %s", fn, dle ?: STRERROR(r));
918 return -ENOPKG; /* Turn into recognizable error */
919 }
920
921 log_debug("Loaded '%s' via dlopen()", fn);
922
923 func = dlsym(context->tcti_dl, TSS2_TCTI_INFO_SYMBOL);
924 if (!func)
925 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
926 "Failed to find TCTI info symbol " TSS2_TCTI_INFO_SYMBOL ": %s",
927 dlerror());
928
929 info = func();
930 if (!info)
931 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Unable to get TCTI info data.");
932
933 log_debug("Loaded TCTI module '%s' (%s) [Version %" PRIu32 "]", info->name, info->description, info->version);
934
935 rc = info->init(/* context= */ NULL, &sz, /* param= */ NULL);
936 if (rc != TPM2_RC_SUCCESS)
937 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
938 "Failed to initialize TCTI context: %s", sym_Tss2_RC_Decode(rc));
939
940 context->tcti_context = malloc0(sz);
941 if (!context->tcti_context)
942 return log_oom_debug();
943
944 rc = info->init(context->tcti_context, &sz, param);
945 if (rc != TPM2_RC_SUCCESS)
946 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
947 "Failed to initialize TCTI context: %s", sym_Tss2_RC_Decode(rc));
948
949 context->tcti_driver = strdup(driver);
950 if (!context->tcti_driver)
951 return log_oom_debug();
952
953 context->tcti_param = strdup(param);
954 if (!context->tcti_param)
955 return log_oom_debug();
956 }
957
958 rc = sym_Esys_Initialize(&context->esys_context, context->tcti_context, NULL);
959 if (rc != TSS2_RC_SUCCESS)
960 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
961 "Failed to initialize TPM context: %s", sym_Tss2_RC_Decode(rc));
962
963 rc = sym_Esys_Startup(context->esys_context, TPM2_SU_CLEAR);
964 if (rc == TPM2_RC_INITIALIZE)
965 log_debug("TPM already started up.");
966 else if (rc == TSS2_RC_SUCCESS)
967 log_debug("TPM successfully started up.");
968 else
969 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
970 "Failed to start up TPM: %s", sym_Tss2_RC_Decode(rc));
971
972 r = tpm2_cache_capabilities(context);
973 if (r < 0)
974 return log_debug_errno(r, "Failed to cache TPM capabilities: %m");
975
976 /* We require AES and CFB support for session encryption. */
977 if (!tpm2_supports_alg(context, TPM2_ALG_AES))
978 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM does not support AES.");
979
980 if (!tpm2_supports_alg(context, TPM2_ALG_CFB))
981 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM does not support CFB.");
982
983 if (!tpm2_supports_tpmt_sym_def(context, &SESSION_TEMPLATE_SYM_AES_128_CFB))
984 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM does not support AES-128-CFB.");
985
986 *ret_context = TAKE_PTR(context);
987
988 return 0;
989 }
990
991 int tpm2_context_new_or_warn(const char *device, Tpm2Context **ret_context) {
992 int r;
993
994 assert(ret_context);
995
996 r = tpm2_context_new(device, ret_context);
997 if (r == -EOPNOTSUPP)
998 return log_error_errno(r, "TPM device not usable as it does not support the required functionality (AES-128-CFB missing?).");
999 if (r == -ENOPKG)
1000 return log_error_errno(r, "TPM TCTI driver not available.");
1001 if (r == -ENOENT)
1002 return log_error_errno(r, "TPM device not found.");
1003 if (r < 0)
1004 return log_error_errno(r, "Failed to create TPM2 context: %m");
1005
1006 return 0;
1007 }
1008
1009 static void tpm2_handle_cleanup(ESYS_CONTEXT *esys_context, ESYS_TR esys_handle, bool flush) {
1010 TSS2_RC rc;
1011
1012 if (!esys_context || esys_handle == ESYS_TR_NONE)
1013 return;
1014
1015 /* Closing the handle removes its reference from the esys_context, but leaves the corresponding
1016 * handle in the actual TPM. Flushing the handle removes its reference from the esys_context as well
1017 * as removing its corresponding handle from the actual TPM. */
1018 if (flush)
1019 rc = sym_Esys_FlushContext(esys_context, esys_handle);
1020 else
1021 /* We can't use Esys_TR_Close() because the tpm2-tss library does not use reference counting
1022 * for handles, and a single Esys_TR_Close() will remove the handle (internal to the tpm2-tss
1023 * library) that might be in use by other code that is using the same ESYS_CONTEXT. This
1024 * directly affects us; for example the src/test/test-tpm2.c test function
1025 * check_seal_unseal() will encounter this issue and will result in a failure when trying to
1026 * cleanup (i.e. Esys_FlushContext) the transient primary key that the test function
1027 * generates. However, not calling Esys_TR_Close() here should be ok, since any leaked handle
1028 * references will be cleaned up when we free our ESYS_CONTEXT.
1029 *
1030 * An upstream bug is open here: https://github.com/tpm2-software/tpm2-tss/issues/2693 */
1031 rc = TSS2_RC_SUCCESS; // FIXME: restore sym_Esys_TR_Close() use once tpm2-tss is fixed and adopted widely enough
1032 if (rc != TSS2_RC_SUCCESS)
1033 /* We ignore failures here (besides debug logging), since this is called in error paths,
1034 * where we cannot do anything about failures anymore. And when it is called in successful
1035 * codepaths by this time we already did what we wanted to do, and got the results we wanted
1036 * so there's no reason to make this fail more loudly than necessary. */
1037 log_debug("Failed to %s TPM handle, ignoring: %s", flush ? "flush" : "close", sym_Tss2_RC_Decode(rc));
1038 }
1039
1040 Tpm2Handle *tpm2_handle_free(Tpm2Handle *handle) {
1041 if (!handle)
1042 return NULL;
1043
1044 _cleanup_(tpm2_context_unrefp) Tpm2Context *context = handle->tpm2_context;
1045 if (context)
1046 tpm2_handle_cleanup(context->esys_context, handle->esys_handle, handle->flush);
1047
1048 return mfree(handle);
1049 }
1050
1051 int tpm2_handle_new(Tpm2Context *context, Tpm2Handle **ret_handle) {
1052 _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
1053
1054 assert(ret_handle);
1055
1056 handle = new(Tpm2Handle, 1);
1057 if (!handle)
1058 return log_oom_debug();
1059
1060 *handle = (Tpm2Handle) {
1061 .tpm2_context = tpm2_context_ref(context),
1062 .esys_handle = ESYS_TR_NONE,
1063 .flush = true,
1064 };
1065
1066 *ret_handle = TAKE_PTR(handle);
1067
1068 return 0;
1069 }
1070
1071 static int tpm2_read_public(
1072 Tpm2Context *c,
1073 const Tpm2Handle *session,
1074 const Tpm2Handle *handle,
1075 TPM2B_PUBLIC **ret_public,
1076 TPM2B_NAME **ret_name,
1077 TPM2B_NAME **ret_qname) {
1078
1079 TSS2_RC rc;
1080
1081 assert(c);
1082 assert(handle);
1083
1084 rc = sym_Esys_ReadPublic(
1085 c->esys_context,
1086 handle->esys_handle,
1087 session ? session->esys_handle : ESYS_TR_NONE,
1088 ESYS_TR_NONE,
1089 ESYS_TR_NONE,
1090 ret_public,
1091 ret_name,
1092 ret_qname);
1093 if (rc != TSS2_RC_SUCCESS)
1094 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1095 "Failed to read public info: %s", sym_Tss2_RC_Decode(rc));
1096
1097 return 0;
1098 }
1099
1100 /* Create a Tpm2Handle object that references a pre-existing handle in the TPM, at the handle index provided.
1101 * This should be used only for persistent, transient, or NV handles; and the handle must already exist in
1102 * the TPM at the specified handle index. The handle index should not be 0. Returns 1 if found, 0 if the
1103 * index is empty, or < 0 on error. Also see tpm2_get_srk() below; the SRK is a commonly used persistent
1104 * Tpm2Handle. */
1105 int tpm2_index_to_handle(
1106 Tpm2Context *c,
1107 TPM2_HANDLE index,
1108 const Tpm2Handle *session,
1109 TPM2B_PUBLIC **ret_public,
1110 TPM2B_NAME **ret_name,
1111 TPM2B_NAME **ret_qname,
1112 Tpm2Handle **ret_handle) {
1113
1114 TSS2_RC rc;
1115 int r;
1116
1117 assert(c);
1118
1119 /* Only allow persistent, transient, or NV index handle types. */
1120 switch (TPM2_HANDLE_TYPE(index)) {
1121 case TPM2_HT_PERSISTENT:
1122 case TPM2_HT_NV_INDEX:
1123 case TPM2_HT_TRANSIENT:
1124 break;
1125 case TPM2_HT_PCR:
1126 /* PCR handles are referenced by their actual index number and do not need a Tpm2Handle */
1127 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1128 "Invalid handle 0x%08" PRIx32 " (in PCR range).", index);
1129 case TPM2_HT_HMAC_SESSION:
1130 case TPM2_HT_POLICY_SESSION:
1131 /* Session indexes are only used internally by tpm2-tss (or lower code) */
1132 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1133 "Invalid handle 0x%08" PRIx32 " (in session range).", index);
1134 case TPM2_HT_PERMANENT:
1135 /* Permanent handles are defined, e.g. ESYS_TR_RH_OWNER. */
1136 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1137 "Invalid handle 0x%08" PRIx32 " (in permanent range).", index);
1138 default:
1139 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1140 "Invalid handle 0x%08" PRIx32 " (in unknown range).", index);
1141 }
1142
1143 /* For transient handles, the kernel tpm "resource manager" (i.e. /dev/tpmrm0) performs mapping
1144 * which breaks GetCapability requests, so only check GetCapability if it's not a transient handle.
1145 * https://bugzilla.kernel.org/show_bug.cgi?id=218009 */
1146 if (TPM2_HANDLE_TYPE(index) != TPM2_HT_TRANSIENT) { // FIXME: once kernel bug is fixed, check transient handles too
1147 r = tpm2_get_capability_handle(c, index);
1148 if (r < 0)
1149 return r;
1150 if (r == 0) {
1151 log_debug("TPM handle 0x%08" PRIx32 " not populated.", index);
1152 if (ret_public)
1153 *ret_public = NULL;
1154 if (ret_name)
1155 *ret_name = NULL;
1156 if (ret_qname)
1157 *ret_qname = NULL;
1158 if (ret_handle)
1159 *ret_handle = NULL;
1160 return 0;
1161 }
1162 }
1163
1164 _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
1165 r = tpm2_handle_new(c, &handle);
1166 if (r < 0)
1167 return r;
1168
1169 /* Since we didn't create this handle in the TPM (this is only creating an ESYS_TR handle for the
1170 * pre-existing TPM handle), we shouldn't flush (or evict) it on cleanup. */
1171 handle->flush = false;
1172
1173 rc = sym_Esys_TR_FromTPMPublic(
1174 c->esys_context,
1175 index,
1176 session ? session->esys_handle : ESYS_TR_NONE,
1177 ESYS_TR_NONE,
1178 ESYS_TR_NONE,
1179 &handle->esys_handle);
1180 if (rc != TSS2_RC_SUCCESS)
1181 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1182 "Failed to read public info: %s", sym_Tss2_RC_Decode(rc));
1183
1184 if (ret_public || ret_name || ret_qname) {
1185 r = tpm2_read_public(c, session, handle, ret_public, ret_name, ret_qname);
1186 if (r < 0)
1187 return r;
1188 }
1189
1190 if (ret_handle)
1191 *ret_handle = TAKE_PTR(handle);
1192
1193 return 1;
1194 }
1195
1196 /* Get the handle index for the provided Tpm2Handle. */
1197 int tpm2_index_from_handle(Tpm2Context *c, const Tpm2Handle *handle, TPM2_HANDLE *ret_index) {
1198 TSS2_RC rc;
1199
1200 assert(c);
1201 assert(handle);
1202 assert(ret_index);
1203
1204 /* Esys_TR_GetTpmHandle was added to tpm2-tss in version 2.4.0. Once we can set a minimum tpm2-tss
1205 * version of 2.4.0 this check can be removed. */
1206 if (!sym_Esys_TR_GetTpmHandle)
1207 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1208 "libtss2-esys too old, does not include Esys_TR_GetTpmHandle.");
1209
1210 rc = sym_Esys_TR_GetTpmHandle(c->esys_context, handle->esys_handle, ret_index);
1211 if (rc != TSS2_RC_SUCCESS)
1212 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1213 "Failed to get handle index: %s", sym_Tss2_RC_Decode(rc));
1214
1215 return 0;
1216 }
1217
1218 /* Copy an object in the TPM at a transient handle to a persistent handle.
1219 *
1220 * The provided transient handle must exist in the TPM in the transient range. The persistent handle may be 0
1221 * or any handle in the persistent range. If 0, this will try each handle in the persistent range, in
1222 * ascending order, until an available one is found. If non-zero, only the requested persistent handle will
1223 * be used.
1224 *
1225 * Note that the persistent handle parameter is an handle index (i.e. number), while the transient handle is
1226 * a Tpm2Handle object. The returned persistent handle will be a Tpm2Handle object that is located in the TPM
1227 * at the requested persistent handle index (or the first available if none was requested).
1228 *
1229 * Returns 1 if the object was successfully persisted, or 0 if there is already a key at the requested
1230 * handle, or < 0 on error. Theoretically, this would also return 0 if no specific persistent handle is
1231 * requested but all persistent handles are used, but it is extremely unlikely the TPM has enough internal
1232 * memory to store the entire persistent range, in which case an error will be returned if the TPM is out of
1233 * memory for persistent storage. The persistent handle is only provided when returning 1. */
1234 static int tpm2_persist_handle(
1235 Tpm2Context *c,
1236 const Tpm2Handle *transient_handle,
1237 const Tpm2Handle *session,
1238 TPMI_DH_PERSISTENT persistent_handle_index,
1239 Tpm2Handle **ret_persistent_handle) {
1240
1241 /* We don't use TPM2_PERSISTENT_FIRST and TPM2_PERSISTENT_LAST here due to:
1242 * https://github.com/systemd/systemd/pull/27713#issuecomment-1591864753 */
1243 TPMI_DH_PERSISTENT first = UINT32_C(0x81000000), last = UINT32_C(0x81ffffff);
1244 TSS2_RC rc;
1245 int r;
1246
1247 assert(c);
1248 assert(transient_handle);
1249
1250 /* If persistent handle index specified, only try that. */
1251 if (persistent_handle_index != 0) {
1252 if (TPM2_HANDLE_TYPE(persistent_handle_index) != TPM2_HT_PERSISTENT)
1253 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1254 "Handle not in persistent range: 0x%x", persistent_handle_index);
1255
1256 first = last = persistent_handle_index;
1257 }
1258
1259 for (TPMI_DH_PERSISTENT requested = first; requested <= last; requested++) {
1260 _cleanup_(tpm2_handle_freep) Tpm2Handle *persistent_handle = NULL;
1261 r = tpm2_handle_new(c, &persistent_handle);
1262 if (r < 0)
1263 return r;
1264
1265 /* Since this is a persistent handle, don't flush it. */
1266 persistent_handle->flush = false;
1267
1268 rc = sym_Esys_EvictControl(
1269 c->esys_context,
1270 ESYS_TR_RH_OWNER,
1271 transient_handle->esys_handle,
1272 session ? session->esys_handle : ESYS_TR_PASSWORD,
1273 ESYS_TR_NONE,
1274 ESYS_TR_NONE,
1275 requested,
1276 &persistent_handle->esys_handle);
1277 if (rc == TSS2_RC_SUCCESS) {
1278 if (ret_persistent_handle)
1279 *ret_persistent_handle = TAKE_PTR(persistent_handle);
1280
1281 return 1;
1282 }
1283 if (rc != TPM2_RC_NV_DEFINED)
1284 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1285 "Failed to persist handle: %s", sym_Tss2_RC_Decode(rc));
1286 }
1287
1288 if (ret_persistent_handle)
1289 *ret_persistent_handle = NULL;
1290
1291 return 0;
1292 }
1293
1294 #define TPM2_CREDIT_RANDOM_FLAG_PATH "/run/systemd/tpm-rng-credited"
1295
1296 static int tpm2_credit_random(Tpm2Context *c) {
1297 size_t rps, done = 0;
1298 TSS2_RC rc;
1299 usec_t t;
1300 int r;
1301
1302 assert(c);
1303
1304 /* Pulls some entropy from the TPM and adds it into the kernel RNG pool. That way we can say that the
1305 * key we will ultimately generate with the kernel random pool is at least as good as the TPM's RNG,
1306 * but likely better. Note that we don't trust the TPM RNG very much, hence do not actually credit
1307 * any entropy. */
1308
1309 if (access(TPM2_CREDIT_RANDOM_FLAG_PATH, F_OK) < 0) {
1310 if (errno != ENOENT)
1311 log_debug_errno(errno, "Failed to detect if '" TPM2_CREDIT_RANDOM_FLAG_PATH "' exists, ignoring: %m");
1312 } else {
1313 log_debug("Not adding TPM2 entropy to the kernel random pool again.");
1314 return 0; /* Already done */
1315 }
1316
1317 t = now(CLOCK_MONOTONIC);
1318
1319 for (rps = random_pool_size(); rps > 0;) {
1320 _cleanup_(Esys_Freep) TPM2B_DIGEST *buffer = NULL;
1321
1322 rc = sym_Esys_GetRandom(
1323 c->esys_context,
1324 ESYS_TR_NONE,
1325 ESYS_TR_NONE,
1326 ESYS_TR_NONE,
1327 MIN(rps, 32U), /* 32 is supposedly a safe choice, given that AES 256bit keys are this long, and TPM2 baseline requires support for those. */
1328 &buffer);
1329 if (rc != TSS2_RC_SUCCESS)
1330 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1331 "Failed to acquire entropy from TPM: %s", sym_Tss2_RC_Decode(rc));
1332
1333 if (buffer->size == 0)
1334 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1335 "Zero-sized entropy returned from TPM.");
1336
1337 r = random_write_entropy(-1, buffer->buffer, buffer->size, /* credit= */ false);
1338 if (r < 0)
1339 return log_debug_errno(r, "Failed to write entropy to kernel: %m");
1340
1341 done += buffer->size;
1342 rps = LESS_BY(rps, buffer->size);
1343 }
1344
1345 log_debug("Added %zu bytes of TPM2 entropy to the kernel random pool in %s.", done, FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - t, 0));
1346
1347 r = touch(TPM2_CREDIT_RANDOM_FLAG_PATH);
1348 if (r < 0)
1349 log_debug_errno(r, "Failed to touch '" TPM2_CREDIT_RANDOM_FLAG_PATH "', ignoring: %m");
1350
1351 return 0;
1352 }
1353
1354 /* Get one of the legacy primary key templates.
1355 *
1356 * The legacy templates should only be used for older sealed data that did not use the SRK. Instead of a
1357 * persistent SRK, a transient key was created to seal the data and then flushed; and the exact same template
1358 * must be used to recreate the same transient key to unseal the data. The alg parameter must be TPM2_ALG_RSA
1359 * or TPM2_ALG_ECC. This does not check if the alg is actually supported on this TPM. */
1360 static int tpm2_get_legacy_template(TPMI_ALG_PUBLIC alg, TPMT_PUBLIC *ret_template) {
1361 /* Do not modify. */
1362 static const TPMT_PUBLIC legacy_ecc = {
1363 .type = TPM2_ALG_ECC,
1364 .nameAlg = TPM2_ALG_SHA256,
1365 .objectAttributes =
1366 TPMA_OBJECT_RESTRICTED|
1367 TPMA_OBJECT_DECRYPT|
1368 TPMA_OBJECT_FIXEDTPM|
1369 TPMA_OBJECT_FIXEDPARENT|
1370 TPMA_OBJECT_SENSITIVEDATAORIGIN|
1371 TPMA_OBJECT_USERWITHAUTH,
1372 .parameters.eccDetail = {
1373 .symmetric = {
1374 .algorithm = TPM2_ALG_AES,
1375 .keyBits.aes = 128,
1376 .mode.aes = TPM2_ALG_CFB,
1377 },
1378 .scheme.scheme = TPM2_ALG_NULL,
1379 .curveID = TPM2_ECC_NIST_P256,
1380 .kdf.scheme = TPM2_ALG_NULL,
1381 },
1382 };
1383
1384 /* Do not modify. */
1385 static const TPMT_PUBLIC legacy_rsa = {
1386 .type = TPM2_ALG_RSA,
1387 .nameAlg = TPM2_ALG_SHA256,
1388 .objectAttributes = TPMA_OBJECT_RESTRICTED|TPMA_OBJECT_DECRYPT|TPMA_OBJECT_FIXEDTPM|TPMA_OBJECT_FIXEDPARENT|TPMA_OBJECT_SENSITIVEDATAORIGIN|TPMA_OBJECT_USERWITHAUTH,
1389 .parameters.rsaDetail = {
1390 .symmetric = {
1391 .algorithm = TPM2_ALG_AES,
1392 .keyBits.aes = 128,
1393 .mode.aes = TPM2_ALG_CFB,
1394 },
1395 .scheme.scheme = TPM2_ALG_NULL,
1396 .keyBits = 2048,
1397 },
1398 };
1399
1400 assert(ret_template);
1401
1402 if (alg == TPM2_ALG_ECC)
1403 *ret_template = legacy_ecc;
1404 else if (alg == TPM2_ALG_RSA)
1405 *ret_template = legacy_rsa;
1406 else
1407 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1408 "Unsupported legacy SRK alg: 0x%x", alg);
1409
1410 return 0;
1411 }
1412
1413 /* Get a Storage Root Key (SRK) template.
1414 *
1415 * The SRK template values are recommended by the "TCG TPM v2.0 Provisioning Guidance" document in section
1416 * 7.5.1 "Storage Primary Key (SRK) Templates", referencing "TCG EK Credential Profile for TPM Family 2.0".
1417 * The EK Credential Profile version 2.0 provides only a single template each for RSA and ECC, while later EK
1418 * Credential Profile versions provide more templates, and keep the original templates as "L-1" (for RSA) and
1419 * "L-2" (for ECC).
1420 *
1421 * https://trustedcomputinggroup.org/resource/tcg-tpm-v2-0-provisioning-guidance
1422 * https://trustedcomputinggroup.org/resource/http-trustedcomputinggroup-org-wp-content-uploads-tcg-ek-credential-profile
1423 *
1424 * These templates are only needed to create a new persistent SRK (or a new transient key that is
1425 * SRK-compatible). Preferably, the TPM should contain a shared SRK located at the reserved shared SRK handle
1426 * (see TPM2_SRK_HANDLE in tpm2-util.h, and tpm2_get_srk() below).
1427 *
1428 * Returns 0 if the specified algorithm is ECC or RSA, otherwise -EOPNOTSUPP. */
1429 int tpm2_get_srk_template(TPMI_ALG_PUBLIC alg, TPMT_PUBLIC *ret_template) {
1430 /* The attributes are the same between ECC and RSA templates. This has the changes specified in the
1431 * Provisioning Guidance document, specifically:
1432 * TPMA_OBJECT_USERWITHAUTH is added.
1433 * TPMA_OBJECT_ADMINWITHPOLICY is removed.
1434 * TPMA_OBJECT_NODA is added. */
1435 TPMA_OBJECT srk_attributes =
1436 TPMA_OBJECT_DECRYPT |
1437 TPMA_OBJECT_FIXEDPARENT |
1438 TPMA_OBJECT_FIXEDTPM |
1439 TPMA_OBJECT_NODA |
1440 TPMA_OBJECT_RESTRICTED |
1441 TPMA_OBJECT_SENSITIVEDATAORIGIN |
1442 TPMA_OBJECT_USERWITHAUTH;
1443
1444 /* The symmetric configuration is the same between ECC and RSA templates. */
1445 TPMT_SYM_DEF_OBJECT srk_symmetric = {
1446 .algorithm = TPM2_ALG_AES,
1447 .keyBits.aes = 128,
1448 .mode.aes = TPM2_ALG_CFB,
1449 };
1450
1451 /* Both templates have an empty authPolicy as specified by the Provisioning Guidance document. */
1452
1453 /* From the EK Credential Profile template "L-2". */
1454 TPMT_PUBLIC srk_ecc = {
1455 .type = TPM2_ALG_ECC,
1456 .nameAlg = TPM2_ALG_SHA256,
1457 .objectAttributes = srk_attributes,
1458 .parameters.eccDetail = {
1459 .symmetric = srk_symmetric,
1460 .scheme.scheme = TPM2_ALG_NULL,
1461 .curveID = TPM2_ECC_NIST_P256,
1462 .kdf.scheme = TPM2_ALG_NULL,
1463 },
1464 };
1465
1466 /* From the EK Credential Profile template "L-1". */
1467 TPMT_PUBLIC srk_rsa = {
1468 .type = TPM2_ALG_RSA,
1469 .nameAlg = TPM2_ALG_SHA256,
1470 .objectAttributes = srk_attributes,
1471 .parameters.rsaDetail = {
1472 .symmetric = srk_symmetric,
1473 .scheme.scheme = TPM2_ALG_NULL,
1474 .keyBits = 2048,
1475 },
1476 };
1477
1478 assert(ret_template);
1479
1480 switch (alg) {
1481 case TPM2_ALG_ECC:
1482 *ret_template = srk_ecc;
1483 return 0;
1484 case TPM2_ALG_RSA:
1485 *ret_template = srk_rsa;
1486 return 0;
1487 }
1488
1489 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "No SRK for algorithm 0x%" PRIx16, alg);
1490 }
1491
1492 /* Get the best supported SRK template. ECC is preferred, then RSA. */
1493 int tpm2_get_best_srk_template(Tpm2Context *c, TPMT_PUBLIC *ret_template) {
1494 TPMT_PUBLIC template;
1495 int r;
1496
1497 assert(c);
1498 assert(ret_template);
1499
1500 r = tpm2_get_srk_template(TPM2_ALG_ECC, &template);
1501 if (r < 0)
1502 return r;
1503
1504 if (!tpm2_supports_alg(c, TPM2_ALG_ECC))
1505 log_debug("TPM does not support ECC.");
1506 else if (!tpm2_supports_ecc_curve(c, template.parameters.eccDetail.curveID))
1507 log_debug("TPM does not support ECC-NIST-P256 curve.");
1508 else if (!tpm2_supports_tpmt_public(c, &template))
1509 log_debug("TPM does not support SRK ECC template L-2.");
1510 else {
1511 *ret_template = template;
1512 return 0;
1513 }
1514
1515 r = tpm2_get_srk_template(TPM2_ALG_RSA, &template);
1516 if (r < 0)
1517 return r;
1518
1519 if (!tpm2_supports_alg(c, TPM2_ALG_RSA))
1520 log_debug("TPM does not support RSA.");
1521 else if (!tpm2_supports_tpmt_public(c, &template))
1522 log_debug("TPM does not support SRK RSA template L-1.");
1523 else {
1524 *ret_template = template;
1525 return 0;
1526 }
1527
1528 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1529 "TPM does not support either SRK template L-1 (RSA) or L-2 (ECC).");
1530 }
1531
1532 /* Get the SRK. Returns 1 if SRK is found, 0 if there is no SRK, or < 0 on error. Also see
1533 * tpm2_get_or_create_srk() below. */
1534 int tpm2_get_srk(
1535 Tpm2Context *c,
1536 const Tpm2Handle *session,
1537 TPM2B_PUBLIC **ret_public,
1538 TPM2B_NAME **ret_name,
1539 TPM2B_NAME **ret_qname,
1540 Tpm2Handle **ret_handle) {
1541
1542 return tpm2_index_to_handle(c, TPM2_SRK_HANDLE, session, ret_public, ret_name, ret_qname, ret_handle);
1543 }
1544
1545 /* Get the SRK, creating one if needed. Returns 1 if a new SRK was created and persisted, 0 if an SRK already
1546 * exists, or < 0 on error. */
1547 int tpm2_get_or_create_srk(
1548 Tpm2Context *c,
1549 const Tpm2Handle *session,
1550 TPM2B_PUBLIC **ret_public,
1551 TPM2B_NAME **ret_name,
1552 TPM2B_NAME **ret_qname,
1553 Tpm2Handle **ret_handle) {
1554
1555 int r;
1556
1557 r = tpm2_get_srk(c, session, ret_public, ret_name, ret_qname, ret_handle);
1558 if (r < 0)
1559 return r;
1560 if (r == 1)
1561 return 0; /* 0 → SRK already set up */
1562
1563 /* No SRK, create and persist one */
1564 TPM2B_PUBLIC template = {
1565 .size = sizeof(TPMT_PUBLIC),
1566 };
1567 r = tpm2_get_best_srk_template(c, &template.publicArea);
1568 if (r < 0)
1569 return log_debug_errno(r, "Could not get best SRK template: %m");
1570
1571 _cleanup_(tpm2_handle_freep) Tpm2Handle *transient_handle = NULL;
1572 r = tpm2_create_primary(
1573 c,
1574 session,
1575 &template,
1576 /* sensitive= */ NULL,
1577 /* ret_public= */ NULL,
1578 &transient_handle);
1579 if (r < 0)
1580 return r;
1581
1582 /* Try to persist the transient SRK we created. No locking needed; if multiple threads are trying to
1583 * persist SRKs concurrently, only one will succeed (r == 1) while the rest will fail (r == 0). In
1584 * either case, all threads will get the persistent SRK below. */
1585 r = tpm2_persist_handle(c, transient_handle, session, TPM2_SRK_HANDLE, /* ret_persistent_handle= */ NULL);
1586 if (r < 0)
1587 return r;
1588
1589 /* The SRK should exist now. */
1590 r = tpm2_get_srk(c, session, ret_public, ret_name, ret_qname, ret_handle);
1591 if (r < 0)
1592 return r;
1593 if (r == 0)
1594 /* This should never happen. */
1595 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "SRK we just persisted couldn't be found.");
1596
1597 return 1; /* > 0 → SRK newly set up */
1598 }
1599
1600 /* Utility functions for TPMS_PCR_SELECTION. */
1601
1602 /* Convert a TPMS_PCR_SELECTION object to a mask. */
1603 uint32_t tpm2_tpms_pcr_selection_to_mask(const TPMS_PCR_SELECTION *s) {
1604 assert(s);
1605 assert(s->sizeofSelect <= sizeof(s->pcrSelect));
1606
1607 uint32_t mask = 0;
1608 for (unsigned i = 0; i < s->sizeofSelect; i++)
1609 SET_FLAG(mask, (uint32_t)s->pcrSelect[i] << (i * 8), true);
1610 return mask;
1611 }
1612
1613 /* Convert a mask and hash alg to a TPMS_PCR_SELECTION object. */
1614 void tpm2_tpms_pcr_selection_from_mask(uint32_t mask, TPMI_ALG_HASH hash_alg, TPMS_PCR_SELECTION *ret) {
1615 assert(ret);
1616
1617 /* This is currently hardcoded at 24 PCRs, above. */
1618 if (!TPM2_PCR_MASK_VALID(mask))
1619 log_debug("PCR mask selections (%x) out of range, ignoring.",
1620 mask & ~((uint32_t)TPM2_PCRS_MASK));
1621
1622 *ret = (TPMS_PCR_SELECTION){
1623 .hash = hash_alg,
1624 .sizeofSelect = TPM2_PCRS_MAX / 8,
1625 .pcrSelect[0] = mask & 0xff,
1626 .pcrSelect[1] = (mask >> 8) & 0xff,
1627 .pcrSelect[2] = (mask >> 16) & 0xff,
1628 };
1629 }
1630
1631 /* Test if all bits in the mask are set in the TPMS_PCR_SELECTION. */
1632 bool tpm2_tpms_pcr_selection_has_mask(const TPMS_PCR_SELECTION *s, uint32_t mask) {
1633 assert(s);
1634
1635 return FLAGS_SET(tpm2_tpms_pcr_selection_to_mask(s), mask);
1636 }
1637
1638 static void tpm2_tpms_pcr_selection_update_mask(TPMS_PCR_SELECTION *s, uint32_t mask, bool b) {
1639 assert(s);
1640
1641 tpm2_tpms_pcr_selection_from_mask(UPDATE_FLAG(tpm2_tpms_pcr_selection_to_mask(s), mask, b), s->hash, s);
1642 }
1643
1644 /* Add all PCR selections in the mask. */
1645 void tpm2_tpms_pcr_selection_add_mask(TPMS_PCR_SELECTION *s, uint32_t mask) {
1646 tpm2_tpms_pcr_selection_update_mask(s, mask, 1);
1647 }
1648
1649 /* Remove all PCR selections in the mask. */
1650 void tpm2_tpms_pcr_selection_sub_mask(TPMS_PCR_SELECTION *s, uint32_t mask) {
1651 tpm2_tpms_pcr_selection_update_mask(s, mask, 0);
1652 }
1653
1654 /* Add all PCR selections in 'b' to 'a'. Both must have the same hash alg. */
1655 void tpm2_tpms_pcr_selection_add(TPMS_PCR_SELECTION *a, const TPMS_PCR_SELECTION *b) {
1656 assert(a);
1657 assert(b);
1658 assert(a->hash == b->hash);
1659
1660 tpm2_tpms_pcr_selection_add_mask(a, tpm2_tpms_pcr_selection_to_mask(b));
1661 }
1662
1663 /* Remove all PCR selections in 'b' from 'a'. Both must have the same hash alg. */
1664 void tpm2_tpms_pcr_selection_sub(TPMS_PCR_SELECTION *a, const TPMS_PCR_SELECTION *b) {
1665 assert(a);
1666 assert(b);
1667 assert(a->hash == b->hash);
1668
1669 tpm2_tpms_pcr_selection_sub_mask(a, tpm2_tpms_pcr_selection_to_mask(b));
1670 }
1671
1672 /* Move all PCR selections in 'b' to 'a'. Both must have the same hash alg. */
1673 void tpm2_tpms_pcr_selection_move(TPMS_PCR_SELECTION *a, TPMS_PCR_SELECTION *b) {
1674 if (a == b)
1675 return;
1676
1677 tpm2_tpms_pcr_selection_add(a, b);
1678 tpm2_tpms_pcr_selection_from_mask(0, b->hash, b);
1679 }
1680
1681 #define FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(tpms, tpml) \
1682 _FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(tpms, tpml, UNIQ_T(l, UNIQ))
1683 #define _FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(tpms, tpml, l) \
1684 for (typeof(tpml) (l) = (tpml); (l); (l) = NULL) \
1685 FOREACH_ARRAY(tpms, (l)->pcrSelections, (l)->count)
1686
1687 #define FOREACH_PCR_IN_TPMS_PCR_SELECTION(pcr, tpms) \
1688 FOREACH_PCR_IN_MASK(pcr, tpm2_tpms_pcr_selection_to_mask(tpms))
1689
1690 #define FOREACH_PCR_IN_TPML_PCR_SELECTION(pcr, tpms, tpml) \
1691 FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(tpms, tpml) \
1692 FOREACH_PCR_IN_TPMS_PCR_SELECTION(pcr, tpms)
1693
1694 char* tpm2_tpms_pcr_selection_to_string(const TPMS_PCR_SELECTION *s) {
1695 assert(s);
1696
1697 const char *algstr = strna(tpm2_hash_alg_to_string(s->hash));
1698
1699 _cleanup_free_ char *mask = tpm2_pcr_mask_to_string(tpm2_tpms_pcr_selection_to_mask(s));
1700 if (!mask)
1701 return NULL;
1702
1703 return strjoin(algstr, "(", mask, ")");
1704 }
1705
1706 size_t tpm2_tpms_pcr_selection_weight(const TPMS_PCR_SELECTION *s) {
1707 assert(s);
1708
1709 return popcount(tpm2_tpms_pcr_selection_to_mask(s));
1710 }
1711
1712 /* Utility functions for TPML_PCR_SELECTION. */
1713
1714 /* Remove the (0-based) index entry from 'l', shift all following entries, and update the count. */
1715 static void tpm2_tpml_pcr_selection_remove_index(TPML_PCR_SELECTION *l, uint32_t index) {
1716 assert(l);
1717 assert(l->count <= ELEMENTSOF(l->pcrSelections));
1718 assert(index < l->count);
1719
1720 size_t s = l->count - (index + 1);
1721 memmove(&l->pcrSelections[index], &l->pcrSelections[index + 1], s * sizeof(l->pcrSelections[0]));
1722 l->count--;
1723 }
1724
1725 /* Get a TPMS_PCR_SELECTION from a TPML_PCR_SELECTION for the given hash alg. Returns NULL if there is no
1726 * entry for the hash alg. This guarantees the returned entry contains all the PCR selections for the given
1727 * hash alg, which may require modifying the TPML_PCR_SELECTION by removing duplicate entries. */
1728 static TPMS_PCR_SELECTION *tpm2_tpml_pcr_selection_get_tpms_pcr_selection(
1729 TPML_PCR_SELECTION *l,
1730 TPMI_ALG_HASH hash_alg) {
1731
1732 assert(l);
1733 assert(l->count <= ELEMENTSOF(l->pcrSelections));
1734
1735 TPMS_PCR_SELECTION *selection = NULL;
1736 FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(s, l)
1737 if (s->hash == hash_alg) {
1738 selection = s;
1739 break;
1740 }
1741
1742 if (!selection)
1743 return NULL;
1744
1745 /* Iterate backwards through the entries, removing any other entries for the hash alg. */
1746 for (uint32_t i = l->count - 1; i > 0; i--) {
1747 TPMS_PCR_SELECTION *s = &l->pcrSelections[i];
1748
1749 if (selection == s)
1750 break;
1751
1752 if (s->hash == hash_alg) {
1753 tpm2_tpms_pcr_selection_move(selection, s);
1754 tpm2_tpml_pcr_selection_remove_index(l, i);
1755 }
1756 }
1757
1758 return selection;
1759 }
1760
1761 /* Combine all duplicate (same hash alg) TPMS_PCR_SELECTION entries in 'l'. */
1762 static void tpm2_tpml_pcr_selection_cleanup(TPML_PCR_SELECTION *l) {
1763 /* Can't use FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION() because we might modify l->count */
1764 for (uint32_t i = 0; i < l->count; i++)
1765 /* This removes all duplicate TPMS_PCR_SELECTION entries for this hash. */
1766 (void) tpm2_tpml_pcr_selection_get_tpms_pcr_selection(l, l->pcrSelections[i].hash);
1767 }
1768
1769 /* Convert a TPML_PCR_SELECTION object to a mask. Returns empty mask (i.e. 0) if 'hash_alg' is not in the object. */
1770 uint32_t tpm2_tpml_pcr_selection_to_mask(const TPML_PCR_SELECTION *l, TPMI_ALG_HASH hash_alg) {
1771 assert(l);
1772
1773 /* Make a copy, as tpm2_tpml_pcr_selection_get_tpms_pcr_selection() will modify the object if there
1774 * are multiple entries with the requested hash alg. */
1775 TPML_PCR_SELECTION lcopy = *l;
1776
1777 TPMS_PCR_SELECTION *s;
1778 s = tpm2_tpml_pcr_selection_get_tpms_pcr_selection(&lcopy, hash_alg);
1779 if (!s)
1780 return 0;
1781
1782 return tpm2_tpms_pcr_selection_to_mask(s);
1783 }
1784
1785 /* Convert a mask and hash alg to a TPML_PCR_SELECTION object. */
1786 void tpm2_tpml_pcr_selection_from_mask(uint32_t mask, TPMI_ALG_HASH hash_alg, TPML_PCR_SELECTION *ret) {
1787 assert(ret);
1788
1789 TPMS_PCR_SELECTION s;
1790 tpm2_tpms_pcr_selection_from_mask(mask, hash_alg, &s);
1791
1792 *ret = (TPML_PCR_SELECTION){
1793 .count = 1,
1794 .pcrSelections[0] = s,
1795 };
1796 }
1797
1798 /* Add the PCR selections in 's' to the corresponding hash alg TPMS_PCR_SELECTION entry in 'l'. Adds a new
1799 * TPMS_PCR_SELECTION entry for the hash alg if needed. This may modify the TPML_PCR_SELECTION by combining
1800 * entries with the same hash alg. */
1801 void tpm2_tpml_pcr_selection_add_tpms_pcr_selection(TPML_PCR_SELECTION *l, const TPMS_PCR_SELECTION *s) {
1802 assert(l);
1803 assert(s);
1804
1805 if (tpm2_tpms_pcr_selection_is_empty(s))
1806 return;
1807
1808 TPMS_PCR_SELECTION *selection = tpm2_tpml_pcr_selection_get_tpms_pcr_selection(l, s->hash);
1809 if (selection) {
1810 tpm2_tpms_pcr_selection_add(selection, s);
1811 return;
1812 }
1813
1814 /* It's already broken if the count is higher than the array has size for. */
1815 assert(l->count <= ELEMENTSOF(l->pcrSelections));
1816
1817 /* If full, the cleanup should result in at least one available entry. */
1818 if (l->count == ELEMENTSOF(l->pcrSelections))
1819 tpm2_tpml_pcr_selection_cleanup(l);
1820
1821 assert(l->count < ELEMENTSOF(l->pcrSelections));
1822 l->pcrSelections[l->count++] = *s;
1823 }
1824
1825 /* Remove the PCR selections in 's' from the corresponding hash alg TPMS_PCR_SELECTION entry in 'l'. This
1826 * will combine all entries for 's->hash' in 'l'. */
1827 void tpm2_tpml_pcr_selection_sub_tpms_pcr_selection(TPML_PCR_SELECTION *l, const TPMS_PCR_SELECTION *s) {
1828 assert(l);
1829 assert(s);
1830
1831 if (tpm2_tpms_pcr_selection_is_empty(s))
1832 return;
1833
1834 TPMS_PCR_SELECTION *selection = tpm2_tpml_pcr_selection_get_tpms_pcr_selection(l, s->hash);
1835 if (selection)
1836 tpm2_tpms_pcr_selection_sub(selection, s);
1837 }
1838
1839 /* Test if all bits in the mask for the hash are set in the TPML_PCR_SELECTION. */
1840 bool tpm2_tpml_pcr_selection_has_mask(const TPML_PCR_SELECTION *l, TPMI_ALG_HASH hash, uint32_t mask) {
1841 assert(l);
1842
1843 return FLAGS_SET(tpm2_tpml_pcr_selection_to_mask(l, hash), mask);
1844 }
1845
1846 /* Add the PCR selections in the mask, with the provided hash. */
1847 void tpm2_tpml_pcr_selection_add_mask(TPML_PCR_SELECTION *l, TPMI_ALG_HASH hash, uint32_t mask) {
1848 TPMS_PCR_SELECTION tpms;
1849
1850 assert(l);
1851
1852 tpm2_tpms_pcr_selection_from_mask(mask, hash, &tpms);
1853 tpm2_tpml_pcr_selection_add_tpms_pcr_selection(l, &tpms);
1854 }
1855
1856 /* Add all PCR selections in 'b' to 'a'. */
1857 void tpm2_tpml_pcr_selection_add(TPML_PCR_SELECTION *a, const TPML_PCR_SELECTION *b) {
1858 assert(a);
1859 assert(b);
1860
1861 FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(selection_b, b)
1862 tpm2_tpml_pcr_selection_add_tpms_pcr_selection(a, selection_b);
1863 }
1864
1865 /* Remove all PCR selections in 'b' from 'a'. */
1866 void tpm2_tpml_pcr_selection_sub(TPML_PCR_SELECTION *a, const TPML_PCR_SELECTION *b) {
1867 assert(a);
1868 assert(b);
1869
1870 FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(selection_b, b)
1871 tpm2_tpml_pcr_selection_sub_tpms_pcr_selection(a, selection_b);
1872 }
1873
1874 char* tpm2_tpml_pcr_selection_to_string(const TPML_PCR_SELECTION *l) {
1875 assert(l);
1876
1877 _cleanup_free_ char *banks = NULL;
1878 FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(s, l) {
1879 if (tpm2_tpms_pcr_selection_is_empty(s))
1880 continue;
1881
1882 _cleanup_free_ char *str = tpm2_tpms_pcr_selection_to_string(s);
1883 if (!str || !strextend_with_separator(&banks, ",", str))
1884 return NULL;
1885 }
1886
1887 return strjoin("[", strempty(banks), "]");
1888 }
1889
1890 size_t tpm2_tpml_pcr_selection_weight(const TPML_PCR_SELECTION *l) {
1891 assert(l);
1892 assert(l->count <= ELEMENTSOF(l->pcrSelections));
1893
1894 size_t weight = 0;
1895 FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(s, l) {
1896 size_t w = tpm2_tpms_pcr_selection_weight(s);
1897 assert(weight <= SIZE_MAX - w);
1898 weight += w;
1899 }
1900
1901 return weight;
1902 }
1903
1904 bool tpm2_pcr_value_valid(const Tpm2PCRValue *pcr_value) {
1905 int r;
1906
1907 if (!pcr_value)
1908 return false;
1909
1910 if (!TPM2_PCR_INDEX_VALID(pcr_value->index)) {
1911 log_debug("PCR index %u invalid.", pcr_value->index);
1912 return false;
1913 }
1914
1915 /* If it contains a value, the value size must match the hash size. */
1916 if (pcr_value->value.size > 0) {
1917 r = tpm2_hash_alg_to_size(pcr_value->hash);
1918 if (r < 0)
1919 return false;
1920
1921 if (pcr_value->value.size != (size_t) r) {
1922 log_debug("PCR hash 0x%" PRIx16 " expected size %d does not match actual size %" PRIu16 ".",
1923 pcr_value->hash, r, pcr_value->value.size);
1924 return false;
1925 }
1926 }
1927
1928 return true;
1929 }
1930
1931 /* Verify all entries are valid, and consistent with each other. The requirements for consistency are:
1932 *
1933 * 1) all entries must be sorted in ascending order (e.g. using tpm2_sort_pcr_values())
1934 * 2) all entries must be unique, i.e. there cannot be 2 entries with the same hash and index
1935 *
1936 * Returns true if all entries are valid (or if no entries are provided), false otherwise.
1937 */
1938 bool tpm2_pcr_values_valid(const Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
1939 if (!pcr_values && n_pcr_values > 0)
1940 return false;
1941
1942 const Tpm2PCRValue *previous = NULL;
1943 FOREACH_ARRAY(current, pcr_values, n_pcr_values) {
1944 if (!tpm2_pcr_value_valid(current))
1945 return false;
1946
1947 if (!previous) {
1948 previous = current;
1949 continue;
1950 }
1951
1952 /* Hashes must be sorted in ascending order */
1953 if (current->hash < previous->hash) {
1954 log_debug("PCR values not in ascending order, hash %" PRIu16 " is after %" PRIu16 ".",
1955 current->hash, previous->hash);
1956 return false;
1957 }
1958
1959 if (current->hash == previous->hash) {
1960 /* Indexes (for the same hash) must be sorted in ascending order */
1961 if (current->index < previous->index) {
1962 log_debug("PCR values not in ascending order, hash %" PRIu16 " index %u is after %u.",
1963 current->hash, current->index, previous->index);
1964 return false;
1965 }
1966
1967 /* Indexes (for the same hash) must not be duplicates */
1968 if (current->index == previous->index) {
1969 log_debug("PCR values contain duplicates for hash %" PRIu16 " index %u.",
1970 current->hash, previous->index);
1971 return false;
1972 }
1973 }
1974 }
1975
1976 return true;
1977 }
1978
1979 /* Returns true if any of the provided PCR values has an actual hash value included, false otherwise. */
1980 bool tpm2_pcr_values_has_any_values(const Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
1981 assert(pcr_values || n_pcr_values == 0);
1982
1983 FOREACH_ARRAY(v, pcr_values, n_pcr_values)
1984 if (v->value.size > 0)
1985 return true;
1986
1987 return false;
1988 }
1989
1990 /* Returns true if all of the provided PCR values has an actual hash value included, false otherwise. */
1991 bool tpm2_pcr_values_has_all_values(const Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
1992 assert(pcr_values || n_pcr_values == 0);
1993
1994 FOREACH_ARRAY(v, pcr_values, n_pcr_values)
1995 if (v->value.size == 0)
1996 return false;
1997
1998 return true;
1999 }
2000
2001 static int cmp_pcr_values(const Tpm2PCRValue *a, const Tpm2PCRValue *b) {
2002 assert(a);
2003 assert(b);
2004
2005 return CMP(a->hash, b->hash) ?: CMP(a->index, b->index);
2006 }
2007
2008 /* Sort the array of Tpm2PCRValue entries in-place. This sorts first in ascending order of hash algorithm
2009 * (sorting simply by the TPM2 hash algorithm number), and then sorting by pcr index. */
2010 void tpm2_sort_pcr_values(Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
2011 typesafe_qsort(pcr_values, n_pcr_values, cmp_pcr_values);
2012 }
2013
2014 int tpm2_pcr_values_to_mask(
2015 const Tpm2PCRValue *pcr_values,
2016 size_t n_pcr_values,
2017 TPMI_ALG_HASH hash,
2018 uint32_t *ret_mask) {
2019
2020 assert(pcr_values || n_pcr_values == 0);
2021 assert(ret_mask);
2022
2023 if (!tpm2_pcr_values_valid(pcr_values, n_pcr_values))
2024 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PCR values.");
2025
2026 uint32_t mask = 0;
2027 FOREACH_ARRAY(v, pcr_values, n_pcr_values)
2028 if (hash == 0 || v->hash == hash)
2029 SET_BIT(mask, v->index);
2030
2031 *ret_mask = mask;
2032 return 0;
2033 }
2034
2035 int tpm2_tpml_pcr_selection_from_pcr_values(
2036 const Tpm2PCRValue *pcr_values,
2037 size_t n_pcr_values,
2038 TPML_PCR_SELECTION *ret_selection,
2039 TPM2B_DIGEST **ret_values,
2040 size_t *ret_n_values) {
2041
2042 TPML_PCR_SELECTION selection = {};
2043 _cleanup_free_ TPM2B_DIGEST *values = NULL;
2044 size_t n_values = 0;
2045
2046 assert(pcr_values || n_pcr_values == 0);
2047
2048 if (!tpm2_pcr_values_valid(pcr_values, n_pcr_values))
2049 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "PCR values are not valid.");
2050
2051 FOREACH_ARRAY(v, pcr_values, n_pcr_values) {
2052 tpm2_tpml_pcr_selection_add_mask(&selection, v->hash, INDEX_TO_MASK(uint32_t, v->index));
2053
2054 if (!GREEDY_REALLOC_APPEND(values, n_values, &v->value, 1))
2055 return log_oom_debug();
2056 }
2057
2058 if (ret_selection)
2059 *ret_selection = selection;
2060 if (ret_values)
2061 *ret_values = TAKE_PTR(values);
2062 if (ret_n_values)
2063 *ret_n_values = n_values;
2064
2065 return 0;
2066 }
2067
2068 /* Count the number of different hash algorithms for all the entries. */
2069 int tpm2_pcr_values_hash_count(const Tpm2PCRValue *pcr_values, size_t n_pcr_values, size_t *ret_count) {
2070 TPML_PCR_SELECTION selection;
2071 int r;
2072
2073 assert(pcr_values);
2074 assert(ret_count);
2075
2076 r = tpm2_tpml_pcr_selection_from_pcr_values(
2077 pcr_values,
2078 n_pcr_values,
2079 &selection,
2080 /* ret_values= */ NULL,
2081 /* ret_n_values= */ NULL);
2082 if (r < 0)
2083 return r;
2084
2085 *ret_count = selection.count;
2086
2087 return 0;
2088 }
2089
2090 /* Parse a string argument into a Tpm2PCRValue object.
2091 *
2092 * The format is <index>[:hash[=value]] where index is the index number (or name) of the PCR, e.g. 0 (or
2093 * platform-code), hash is the name of the hash algorithm (e.g. sha256) and value is the hex hash digest
2094 * value, optionally with a leading 0x. This does not check for validity of the fields. */
2095 int tpm2_pcr_value_from_string(const char *arg, Tpm2PCRValue *ret_pcr_value) {
2096 Tpm2PCRValue pcr_value = {};
2097 const char *p = arg;
2098 int r;
2099
2100 assert(arg);
2101 assert(ret_pcr_value);
2102
2103 _cleanup_free_ char *index = NULL;
2104 r = extract_first_word(&p, &index, ":", /* flags= */ 0);
2105 if (r < 1)
2106 return log_debug_errno(r, "Could not parse pcr value '%s': %m", p);
2107
2108 r = tpm2_pcr_index_from_string(index);
2109 if (r < 0)
2110 return log_debug_errno(r, "Invalid pcr index '%s': %m", index);
2111 pcr_value.index = (unsigned) r;
2112
2113 if (!isempty(p)) {
2114 _cleanup_free_ char *hash = NULL;
2115 r = extract_first_word(&p, &hash, "=", /* flags= */ 0);
2116 if (r < 1)
2117 return log_debug_errno(r, "Could not parse pcr hash algorithm '%s': %m", p);
2118
2119 r = tpm2_hash_alg_from_string(hash);
2120 if (r < 0)
2121 return log_debug_errno(r, "Invalid pcr hash algorithm '%s': %m", hash);
2122 pcr_value.hash = (TPMI_ALG_HASH) r;
2123
2124 if (!isempty(p)) {
2125 /* Remove leading 0x if present */
2126 p = startswith_no_case(p, "0x") ?: p;
2127
2128 _cleanup_free_ void *buf = NULL;
2129 size_t buf_size = 0;
2130 r = unhexmem(p, &buf, &buf_size);
2131 if (r < 0)
2132 return log_debug_errno(r, "Invalid pcr hash value '%s': %m", p);
2133
2134 r = TPM2B_DIGEST_CHECK_SIZE(buf_size);
2135 if (r < 0)
2136 return log_debug_errno(r, "PCR hash value size %zu too large.", buf_size);
2137
2138 pcr_value.value = TPM2B_DIGEST_MAKE(buf, buf_size);
2139 }
2140 }
2141
2142 *ret_pcr_value = pcr_value;
2143
2144 return 0;
2145 }
2146
2147 /* Return a string for the PCR value. The format is described in tpm2_pcr_value_from_string(). Note that if
2148 * the hash algorithm is not recognized, neither hash name nor hash digest value is included in the
2149 * string. This does not check for validity. */
2150 char* tpm2_pcr_value_to_string(const Tpm2PCRValue *pcr_value) {
2151 _cleanup_free_ char *index = NULL, *value = NULL;
2152
2153 if (asprintf(&index, "%u", pcr_value->index) < 0)
2154 return NULL;
2155
2156 const char *hash = pcr_value->hash > 0 ? tpm2_hash_alg_to_string(pcr_value->hash) : NULL;
2157
2158 if (hash && pcr_value->value.size > 0) {
2159 value = hexmem(pcr_value->value.buffer, pcr_value->value.size);
2160 if (!value)
2161 return NULL;
2162 }
2163
2164 return strjoin(index, hash ? ":" : "", strempty(hash), value ? "=" : "", strempty(value));
2165 }
2166
2167 /* Parse a string argument into an array of Tpm2PCRValue objects.
2168 *
2169 * The format is zero or more entries separated by ',' or '+'. The format of each entry is described in
2170 * tpm2_pcr_value_from_string(). This does not check for validity of the entries. */
2171 int tpm2_pcr_values_from_string(const char *arg, Tpm2PCRValue **ret_pcr_values, size_t *ret_n_pcr_values) {
2172 const char *p = arg;
2173 int r;
2174
2175 assert(arg);
2176 assert(ret_pcr_values);
2177 assert(ret_n_pcr_values);
2178
2179 _cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
2180 size_t n_pcr_values = 0;
2181
2182 for (;;) {
2183 _cleanup_free_ char *pcr_arg = NULL;
2184 r = extract_first_word(&p, &pcr_arg, ",+", /* flags= */ 0);
2185 if (r < 0)
2186 return log_debug_errno(r, "Could not parse pcr values '%s': %m", p);
2187 if (r == 0)
2188 break;
2189
2190 Tpm2PCRValue pcr_value;
2191 r = tpm2_pcr_value_from_string(pcr_arg, &pcr_value);
2192 if (r < 0)
2193 return r;
2194
2195 if (!GREEDY_REALLOC_APPEND(pcr_values, n_pcr_values, &pcr_value, 1))
2196 return log_oom_debug();
2197 }
2198
2199 *ret_pcr_values = TAKE_PTR(pcr_values);
2200 *ret_n_pcr_values = n_pcr_values;
2201
2202 return 0;
2203 }
2204
2205 void tpm2_log_debug_tpml_pcr_selection(const TPML_PCR_SELECTION *l, const char *msg) {
2206 if (!DEBUG_LOGGING || !l)
2207 return;
2208
2209 _cleanup_free_ char *s = tpm2_tpml_pcr_selection_to_string(l);
2210 log_debug("%s: %s", msg ?: "PCR selection", strna(s));
2211 }
2212
2213 void tpm2_log_debug_pcr_value(const Tpm2PCRValue *pcr_value, const char *msg) {
2214 if (!DEBUG_LOGGING || !pcr_value)
2215 return;
2216
2217 _cleanup_free_ char *s = tpm2_pcr_value_to_string(pcr_value);
2218 log_debug("%s: %s", msg ?: "PCR value", strna(s));
2219 }
2220
2221 void tpm2_log_debug_buffer(const void *buffer, size_t size, const char *msg) {
2222 if (!DEBUG_LOGGING || !buffer || size == 0)
2223 return;
2224
2225 _cleanup_free_ char *h = hexmem(buffer, size);
2226 log_debug("%s: %s", msg ?: "Buffer", strna(h));
2227 }
2228
2229 void tpm2_log_debug_digest(const TPM2B_DIGEST *digest, const char *msg) {
2230 if (digest)
2231 tpm2_log_debug_buffer(digest->buffer, digest->size, msg ?: "Digest");
2232 }
2233
2234 void tpm2_log_debug_name(const TPM2B_NAME *name, const char *msg) {
2235 if (name)
2236 tpm2_log_debug_buffer(name->name, name->size, msg ?: "Name");
2237 }
2238
2239 static int tpm2_get_policy_digest(
2240 Tpm2Context *c,
2241 const Tpm2Handle *session,
2242 TPM2B_DIGEST **ret_policy_digest) {
2243
2244 TSS2_RC rc;
2245
2246 if (!DEBUG_LOGGING && !ret_policy_digest)
2247 return 0;
2248
2249 assert(c);
2250 assert(session);
2251
2252 log_debug("Acquiring policy digest.");
2253
2254 _cleanup_(Esys_Freep) TPM2B_DIGEST *policy_digest = NULL;
2255 rc = sym_Esys_PolicyGetDigest(
2256 c->esys_context,
2257 session->esys_handle,
2258 ESYS_TR_NONE,
2259 ESYS_TR_NONE,
2260 ESYS_TR_NONE,
2261 &policy_digest);
2262 if (rc != TSS2_RC_SUCCESS)
2263 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2264 "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc));
2265
2266 tpm2_log_debug_digest(policy_digest, "Session policy digest");
2267
2268 if (ret_policy_digest)
2269 *ret_policy_digest = TAKE_PTR(policy_digest);
2270
2271 return 0;
2272 }
2273
2274 int tpm2_create_primary(
2275 Tpm2Context *c,
2276 const Tpm2Handle *session,
2277 const TPM2B_PUBLIC *template,
2278 const TPM2B_SENSITIVE_CREATE *sensitive,
2279 TPM2B_PUBLIC **ret_public,
2280 Tpm2Handle **ret_handle) {
2281
2282 usec_t ts;
2283 TSS2_RC rc;
2284 int r;
2285
2286 assert(c);
2287 assert(template);
2288
2289 log_debug("Creating primary key on TPM.");
2290
2291 ts = now(CLOCK_MONOTONIC);
2292
2293 _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
2294 r = tpm2_handle_new(c, &handle);
2295 if (r < 0)
2296 return r;
2297
2298 _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
2299 rc = sym_Esys_CreatePrimary(
2300 c->esys_context,
2301 ESYS_TR_RH_OWNER,
2302 session ? session->esys_handle : ESYS_TR_PASSWORD,
2303 ESYS_TR_NONE,
2304 ESYS_TR_NONE,
2305 sensitive ?: &(TPM2B_SENSITIVE_CREATE) {},
2306 template,
2307 /* outsideInfo= */ NULL,
2308 &(TPML_PCR_SELECTION) {},
2309 &handle->esys_handle,
2310 &public,
2311 /* creationData= */ NULL,
2312 /* creationHash= */ NULL,
2313 /* creationTicket= */ NULL);
2314 if (rc == TPM2_RC_BAD_AUTH)
2315 return log_debug_errno(SYNTHETIC_ERRNO(EDEADLK), "Authorization failure while attempting to create primary key.");
2316 if (rc != TSS2_RC_SUCCESS)
2317 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2318 "Failed to generate primary key in TPM: %s",
2319 sym_Tss2_RC_Decode(rc));
2320
2321 log_debug("Successfully created primary key on TPM in %s.",
2322 FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - ts, USEC_PER_MSEC));
2323
2324 if (ret_public)
2325 *ret_public = TAKE_PTR(public);
2326 if (ret_handle)
2327 *ret_handle = TAKE_PTR(handle);
2328
2329 return 0;
2330 }
2331
2332 /* Create a TPM object. Do not use this to create primary keys, because some HW TPMs refuse to allow that;
2333 * instead use tpm2_create_primary(). */
2334 int tpm2_create(Tpm2Context *c,
2335 const Tpm2Handle *parent,
2336 const Tpm2Handle *session,
2337 const TPMT_PUBLIC *template,
2338 const TPMS_SENSITIVE_CREATE *sensitive,
2339 TPM2B_PUBLIC **ret_public,
2340 TPM2B_PRIVATE **ret_private) {
2341
2342 usec_t ts;
2343 TSS2_RC rc;
2344
2345 assert(c);
2346 assert(parent);
2347 assert(template);
2348
2349 log_debug("Creating object on TPM.");
2350
2351 ts = now(CLOCK_MONOTONIC);
2352
2353 TPM2B_PUBLIC tpm2b_public = {
2354 .size = sizeof(*template) - sizeof(template->unique),
2355 .publicArea = *template,
2356 };
2357
2358 /* Zero the unique area. */
2359 zero(tpm2b_public.publicArea.unique);
2360
2361 TPM2B_SENSITIVE_CREATE tpm2b_sensitive;
2362 if (sensitive)
2363 tpm2b_sensitive = (TPM2B_SENSITIVE_CREATE) {
2364 .size = sizeof(*sensitive),
2365 .sensitive = *sensitive,
2366 };
2367 else
2368 tpm2b_sensitive = (TPM2B_SENSITIVE_CREATE) {};
2369
2370 _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
2371 _cleanup_(Esys_Freep) TPM2B_PRIVATE *private = NULL;
2372 rc = sym_Esys_Create(
2373 c->esys_context,
2374 parent->esys_handle,
2375 session ? session->esys_handle : ESYS_TR_PASSWORD,
2376 ESYS_TR_NONE,
2377 ESYS_TR_NONE,
2378 &tpm2b_sensitive,
2379 &tpm2b_public,
2380 /* outsideInfo= */ NULL,
2381 &(TPML_PCR_SELECTION) {},
2382 &private,
2383 &public,
2384 /* creationData= */ NULL,
2385 /* creationHash= */ NULL,
2386 /* creationTicket= */ NULL);
2387 if (rc != TSS2_RC_SUCCESS)
2388 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2389 "Failed to generate object in TPM: %s",
2390 sym_Tss2_RC_Decode(rc));
2391
2392 log_debug("Successfully created object on TPM in %s.",
2393 FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - ts, USEC_PER_MSEC));
2394
2395 if (ret_public)
2396 *ret_public = TAKE_PTR(public);
2397 if (ret_private)
2398 *ret_private = TAKE_PTR(private);
2399
2400 return 0;
2401 }
2402
2403 int tpm2_load(
2404 Tpm2Context *c,
2405 const Tpm2Handle *parent,
2406 const Tpm2Handle *session,
2407 const TPM2B_PUBLIC *public,
2408 const TPM2B_PRIVATE *private,
2409 Tpm2Handle **ret_handle) {
2410
2411 TSS2_RC rc;
2412 int r;
2413
2414 assert(c);
2415 assert(public);
2416 assert(private);
2417 assert(ret_handle);
2418
2419 log_debug("Loading object into TPM.");
2420
2421 _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
2422 r = tpm2_handle_new(c, &handle);
2423 if (r < 0)
2424 return r;
2425
2426 rc = sym_Esys_Load(
2427 c->esys_context,
2428 parent ? parent->esys_handle : ESYS_TR_RH_OWNER,
2429 session ? session->esys_handle : ESYS_TR_PASSWORD,
2430 ESYS_TR_NONE,
2431 ESYS_TR_NONE,
2432 private,
2433 public,
2434 &handle->esys_handle);
2435 if (rc == TPM2_RC_LOCKOUT)
2436 return log_debug_errno(SYNTHETIC_ERRNO(ENOLCK),
2437 "TPM2 device is in dictionary attack lockout mode.");
2438 if ((rc & ~(TPM2_RC_N_MASK|TPM2_RC_P)) == TPM2_RC_INTEGRITY) /* Return a recognizable error if this key does not belong to the local TPM */
2439 return log_debug_errno(SYNTHETIC_ERRNO(EREMOTE),
2440 "Key invalid or does not belong to current TPM.");
2441 if (rc != TSS2_RC_SUCCESS)
2442 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2443 "Failed to load key into TPM: %s", sym_Tss2_RC_Decode(rc));
2444
2445 *ret_handle = TAKE_PTR(handle);
2446
2447 return 0;
2448 }
2449
2450 static int tpm2_load_external(
2451 Tpm2Context *c,
2452 const Tpm2Handle *session,
2453 const TPM2B_PUBLIC *public,
2454 const TPM2B_SENSITIVE *private,
2455 Tpm2Handle **ret_handle) {
2456
2457 TSS2_RC rc;
2458 int r;
2459
2460 assert(c);
2461 assert(ret_handle);
2462
2463 log_debug("Loading external key into TPM.");
2464
2465 _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
2466 r = tpm2_handle_new(c, &handle);
2467 if (r < 0)
2468 return r;
2469
2470 rc = sym_Esys_LoadExternal(
2471 c->esys_context,
2472 session ? session->esys_handle : ESYS_TR_NONE,
2473 ESYS_TR_NONE,
2474 ESYS_TR_NONE,
2475 private,
2476 public,
2477 #if HAVE_TSS2_ESYS3
2478 /* tpm2-tss >= 3.0.0 requires a ESYS_TR_RH_* constant specifying the requested
2479 * hierarchy, older versions need TPM2_RH_* instead. */
2480 private ? ESYS_TR_RH_NULL : ESYS_TR_RH_OWNER,
2481 #else
2482 private ? TPM2_RH_NULL : TPM2_RH_OWNER,
2483 #endif
2484 &handle->esys_handle);
2485 if (rc != TSS2_RC_SUCCESS)
2486 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2487 "Failed to load public key into TPM: %s", sym_Tss2_RC_Decode(rc));
2488
2489 *ret_handle = TAKE_PTR(handle);
2490
2491 return 0;
2492 }
2493
2494 static int tpm2_marshal_private(const TPM2B_PRIVATE *private, void **ret, size_t *ret_size) {
2495 size_t max_size = SIZEOF(*private), blob_size = 0;
2496 _cleanup_free_ void *blob = NULL;
2497 TSS2_RC rc;
2498
2499 assert(private);
2500 assert(ret);
2501 assert(ret_size);
2502
2503 blob = malloc0(max_size);
2504 if (!blob)
2505 return log_oom_debug();
2506
2507 rc = sym_Tss2_MU_TPM2B_PRIVATE_Marshal(private, blob, max_size, &blob_size);
2508 if (rc != TSS2_RC_SUCCESS)
2509 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2510 "Failed to marshal private key: %s", sym_Tss2_RC_Decode(rc));
2511
2512 *ret = TAKE_PTR(blob);
2513 *ret_size = blob_size;
2514 return 0;
2515 }
2516
2517 static int tpm2_unmarshal_private(const void *data, size_t size, TPM2B_PRIVATE *ret_private) {
2518 TPM2B_PRIVATE private = {};
2519 size_t offset = 0;
2520 TSS2_RC rc;
2521
2522 assert(data || size == 0);
2523 assert(ret_private);
2524
2525 rc = sym_Tss2_MU_TPM2B_PRIVATE_Unmarshal(data, size, &offset, &private);
2526 if (rc != TSS2_RC_SUCCESS)
2527 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2528 "Failed to unmarshal private key: %s", sym_Tss2_RC_Decode(rc));
2529 if (offset != size)
2530 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2531 "Garbage at end of private key marshal data.");
2532
2533 *ret_private = private;
2534 return 0;
2535 }
2536
2537 int tpm2_marshal_public(const TPM2B_PUBLIC *public, void **ret, size_t *ret_size) {
2538 size_t max_size = SIZEOF(*public), blob_size = 0;
2539 _cleanup_free_ void *blob = NULL;
2540 TSS2_RC rc;
2541
2542 assert(public);
2543 assert(ret);
2544 assert(ret_size);
2545
2546 blob = malloc0(max_size);
2547 if (!blob)
2548 return log_oom_debug();
2549
2550 rc = sym_Tss2_MU_TPM2B_PUBLIC_Marshal(public, blob, max_size, &blob_size);
2551 if (rc != TSS2_RC_SUCCESS)
2552 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2553 "Failed to marshal public key: %s", sym_Tss2_RC_Decode(rc));
2554
2555 *ret = TAKE_PTR(blob);
2556 *ret_size = blob_size;
2557 return 0;
2558 }
2559
2560 static int tpm2_unmarshal_public(const void *data, size_t size, TPM2B_PUBLIC *ret_public) {
2561 TPM2B_PUBLIC public = {};
2562 size_t offset = 0;
2563 TSS2_RC rc;
2564
2565 assert(data || size == 0);
2566 assert(ret_public);
2567
2568 rc = sym_Tss2_MU_TPM2B_PUBLIC_Unmarshal(data, size, &offset, &public);
2569 if (rc != TSS2_RC_SUCCESS)
2570 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2571 "Failed to unmarshal public key: %s", sym_Tss2_RC_Decode(rc));
2572 if (offset != size)
2573 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2574 "Garbage at end of public key marshal data.");
2575
2576 *ret_public = public;
2577 return 0;
2578 }
2579
2580 int tpm2_marshal_nv_public(const TPM2B_NV_PUBLIC *nv_public, void **ret, size_t *ret_size) {
2581 size_t max_size = SIZEOF(*nv_public), blob_size = 0;
2582 _cleanup_free_ void *blob = NULL;
2583 TSS2_RC rc;
2584
2585 assert(nv_public);
2586 assert(ret);
2587 assert(ret_size);
2588
2589 blob = malloc0(max_size);
2590 if (!blob)
2591 return log_oom_debug();
2592
2593 rc = sym_Tss2_MU_TPM2B_NV_PUBLIC_Marshal(nv_public, blob, max_size, &blob_size);
2594 if (rc != TSS2_RC_SUCCESS)
2595 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2596 "Failed to marshal NV public structure: %s", sym_Tss2_RC_Decode(rc));
2597
2598 *ret = TAKE_PTR(blob);
2599 *ret_size = blob_size;
2600 return 0;
2601 }
2602
2603 int tpm2_unmarshal_nv_public(const void *data, size_t size, TPM2B_NV_PUBLIC *ret_nv_public) {
2604 TPM2B_NV_PUBLIC nv_public = {};
2605 size_t offset = 0;
2606 TSS2_RC rc;
2607
2608 assert(data || size == 0);
2609 assert(ret_nv_public);
2610
2611 rc = sym_Tss2_MU_TPM2B_NV_PUBLIC_Unmarshal(data, size, &offset, &nv_public);
2612 if (rc != TSS2_RC_SUCCESS)
2613 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2614 "Failed to unmarshal NV public structure: %s", sym_Tss2_RC_Decode(rc));
2615 if (offset != size)
2616 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2617 "Garbage at end of NV public structure marshal data.");
2618
2619 *ret_nv_public = nv_public;
2620 return 0;
2621 }
2622
2623 static int tpm2_import(
2624 Tpm2Context *c,
2625 const Tpm2Handle *parent,
2626 const Tpm2Handle *session,
2627 const TPM2B_PUBLIC *public,
2628 const TPM2B_PRIVATE *private,
2629 const TPM2B_ENCRYPTED_SECRET *seed,
2630 const TPM2B_DATA *encryption_key,
2631 const TPMT_SYM_DEF_OBJECT *symmetric,
2632 TPM2B_PRIVATE **ret_private) {
2633
2634 TSS2_RC rc;
2635
2636 assert(c);
2637 assert(parent);
2638 assert(!!encryption_key == !!symmetric);
2639 assert(public);
2640 assert(private);
2641 assert(seed);
2642 assert(ret_private);
2643
2644 log_debug("Importing key into TPM.");
2645
2646 rc = sym_Esys_Import(
2647 c->esys_context,
2648 parent->esys_handle,
2649 session ? session->esys_handle : ESYS_TR_PASSWORD,
2650 ESYS_TR_NONE,
2651 ESYS_TR_NONE,
2652 encryption_key,
2653 public,
2654 private,
2655 seed,
2656 symmetric ?: &(TPMT_SYM_DEF_OBJECT){ .algorithm = TPM2_ALG_NULL, },
2657 ret_private);
2658 if (rc != TSS2_RC_SUCCESS)
2659 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2660 "Failed to import key into TPM: %s", sym_Tss2_RC_Decode(rc));
2661
2662 return 0;
2663 }
2664
2665 /* Read hash values from the specified PCR selection. Provides a Tpm2PCRValue array that contains all
2666 * requested PCR values, in the order provided by the TPM. Normally, the provided pcr values will match
2667 * exactly what is in the provided selection, but the TPM may ignore some selected PCRs (for example, if an
2668 * unimplemented PCR index is requested), in which case those PCRs will be absent from the provided pcr
2669 * values. */
2670 int tpm2_pcr_read(
2671 Tpm2Context *c,
2672 const TPML_PCR_SELECTION *pcr_selection,
2673 Tpm2PCRValue **ret_pcr_values,
2674 size_t *ret_n_pcr_values) {
2675
2676 _cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
2677 size_t n_pcr_values = 0;
2678 TSS2_RC rc;
2679
2680 assert(c);
2681 assert(pcr_selection);
2682 assert(ret_pcr_values);
2683 assert(ret_n_pcr_values);
2684
2685 TPML_PCR_SELECTION remaining = *pcr_selection;
2686 while (!tpm2_tpml_pcr_selection_is_empty(&remaining)) {
2687 _cleanup_(Esys_Freep) TPML_PCR_SELECTION *current_read = NULL;
2688 _cleanup_(Esys_Freep) TPML_DIGEST *current_values = NULL;
2689
2690 tpm2_log_debug_tpml_pcr_selection(&remaining, "Reading PCR selection");
2691
2692 /* Unfortunately, PCR_Read will not return more than 8 values. */
2693 rc = sym_Esys_PCR_Read(
2694 c->esys_context,
2695 ESYS_TR_NONE,
2696 ESYS_TR_NONE,
2697 ESYS_TR_NONE,
2698 &remaining,
2699 NULL,
2700 &current_read,
2701 &current_values);
2702 if (rc != TSS2_RC_SUCCESS)
2703 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2704 "Failed to read TPM2 PCRs: %s", sym_Tss2_RC_Decode(rc));
2705
2706 tpm2_log_debug_tpml_pcr_selection(current_read, "Read PCR selection");
2707
2708 if (tpm2_tpml_pcr_selection_is_empty(current_read)) {
2709 log_debug("TPM2 refused to read possibly unimplemented PCRs, ignoring.");
2710 break;
2711 }
2712
2713 unsigned i = 0;
2714 FOREACH_PCR_IN_TPML_PCR_SELECTION(index, tpms, current_read) {
2715 assert(i < current_values->count);
2716 Tpm2PCRValue pcr_value = {
2717 .index = index,
2718 .hash = tpms->hash,
2719 .value = current_values->digests[i++],
2720 };
2721
2722 tpm2_log_debug_pcr_value(&pcr_value, /* msg= */ NULL);
2723
2724 if (!GREEDY_REALLOC_APPEND(pcr_values, n_pcr_values, &pcr_value, 1))
2725 return log_oom_debug();
2726 }
2727 assert(i == current_values->count);
2728
2729 tpm2_tpml_pcr_selection_sub(&remaining, current_read);
2730 }
2731
2732 tpm2_sort_pcr_values(pcr_values, n_pcr_values);
2733
2734 if (!tpm2_pcr_values_valid(pcr_values, n_pcr_values))
2735 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "PCR values read from TPM are not valid.");
2736
2737 *ret_pcr_values = TAKE_PTR(pcr_values);
2738 *ret_n_pcr_values = n_pcr_values;
2739
2740 return 0;
2741 }
2742
2743 /* Read the PCR value for each TPM2PCRValue entry in the array that does not have a value set. If all entries
2744 * have an unset hash (i.e. hash == 0), this first detects the "best" PCR bank to use; otherwise, all entries
2745 * must have a valid hash set. All entries must have a valid index. If this cannot read a PCR value for all
2746 * appropriate entries, this returns an error. This does not check the array for validity. */
2747 int tpm2_pcr_read_missing_values(Tpm2Context *c, Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
2748 TPMI_ALG_HASH pcr_bank = 0;
2749 int r;
2750
2751 assert(c);
2752 assert(pcr_values || n_pcr_values == 0);
2753
2754 if (n_pcr_values > 0) {
2755 size_t hash_count;
2756 r = tpm2_pcr_values_hash_count(pcr_values, n_pcr_values, &hash_count);
2757 if (r < 0)
2758 return log_debug_errno(r, "Could not get hash count from pcr values: %m");
2759
2760 if (hash_count == 1 && pcr_values[0].hash == 0) {
2761 uint32_t mask;
2762 r = tpm2_pcr_values_to_mask(pcr_values, n_pcr_values, 0, &mask);
2763 if (r < 0)
2764 return r;
2765
2766 r = tpm2_get_best_pcr_bank(c, mask, &pcr_bank);
2767 if (r < 0)
2768 return r;
2769 }
2770 }
2771
2772 FOREACH_ARRAY(v, pcr_values, n_pcr_values) {
2773 if (v->hash == 0)
2774 v->hash = pcr_bank;
2775
2776 if (v->value.size > 0)
2777 continue;
2778
2779 TPML_PCR_SELECTION selection;
2780 r = tpm2_tpml_pcr_selection_from_pcr_values(v, 1, &selection, NULL, NULL);
2781 if (r < 0)
2782 return r;
2783
2784 _cleanup_free_ Tpm2PCRValue *read_values = NULL;
2785 size_t n_read_values;
2786 r = tpm2_pcr_read(c, &selection, &read_values, &n_read_values);
2787 if (r < 0)
2788 return r;
2789
2790 if (n_read_values == 0)
2791 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
2792 "Could not read PCR hash 0x%" PRIu16 " index %u",
2793 v->hash, v->index);
2794
2795 assert(n_read_values == 1);
2796 assert(read_values[0].hash == v->hash);
2797 assert(read_values[0].index == v->index);
2798
2799 v->value = read_values[0].value;
2800 }
2801
2802 return 0;
2803 }
2804
2805 static int tpm2_pcr_mask_good(
2806 Tpm2Context *c,
2807 TPMI_ALG_HASH bank,
2808 uint32_t mask) {
2809
2810 TPML_PCR_SELECTION selection;
2811 int r;
2812
2813 assert(c);
2814
2815 /* So we have the problem that some systems might have working TPM2 chips, but the firmware doesn't
2816 * actually measure into them, or only into a suboptimal bank. If so, the PCRs should be all zero or
2817 * all 0xFF. Detect that, so that we can warn and maybe pick a better bank. */
2818
2819 tpm2_tpml_pcr_selection_from_mask(mask, bank, &selection);
2820
2821 _cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
2822 size_t n_pcr_values;
2823 r = tpm2_pcr_read(c, &selection, &pcr_values, &n_pcr_values);
2824 if (r < 0)
2825 return r;
2826
2827 /* If at least one of the selected PCR values is something other than all 0x00 or all 0xFF we are happy. */
2828 FOREACH_ARRAY(v, pcr_values, n_pcr_values)
2829 if (!memeqbyte(0x00, v->value.buffer, v->value.size) &&
2830 !memeqbyte(0xFF, v->value.buffer, v->value.size))
2831 return true;
2832
2833 return false;
2834 }
2835
2836 static int tpm2_bank_has24(const TPMS_PCR_SELECTION *selection) {
2837
2838 assert(selection);
2839
2840 /* As per https://trustedcomputinggroup.org/wp-content/uploads/TCG_PCClient_PFP_r1p05_v23_pub.pdf a
2841 * TPM2 on a Client PC must have at least 24 PCRs. If this TPM has less, just skip over it. */
2842 if (selection->sizeofSelect < TPM2_PCRS_MAX/8) {
2843 log_debug("Skipping TPM2 PCR bank %s with fewer than 24 PCRs.",
2844 strna(tpm2_hash_alg_to_string(selection->hash)));
2845 return false;
2846 }
2847
2848 assert_cc(TPM2_PCRS_MAX % 8 == 0);
2849
2850 /* It's not enough to check how many PCRs there are, we also need to check that the 24 are
2851 * enabled for this bank. Otherwise this TPM doesn't qualify. */
2852 bool valid = true;
2853 for (size_t j = 0; j < TPM2_PCRS_MAX/8; j++)
2854 if (selection->pcrSelect[j] != 0xFF) {
2855 valid = false;
2856 break;
2857 }
2858
2859 if (!valid)
2860 log_debug("TPM2 PCR bank %s has fewer than 24 PCR bits enabled, ignoring.",
2861 strna(tpm2_hash_alg_to_string(selection->hash)));
2862
2863 return valid;
2864 }
2865
2866 int tpm2_get_best_pcr_bank(
2867 Tpm2Context *c,
2868 uint32_t pcr_mask,
2869 TPMI_ALG_HASH *ret) {
2870
2871 TPMI_ALG_HASH supported_hash = 0, hash_with_valid_pcr = 0;
2872 int r;
2873
2874 assert(c);
2875 assert(ret);
2876
2877 uint32_t efi_banks;
2878 r = efi_get_active_pcr_banks(&efi_banks);
2879 if (r < 0) {
2880 if (!IN_SET(r, -ENOENT, -EOPNOTSUPP))
2881 return r;
2882
2883 /* If variable is not set use guesswork below */
2884 log_debug("Boot loader didn't set the LoaderTpm2ActivePcrBanks EFI variable or EFI support is unavailable, we have to guess the used PCR banks.");
2885 } else if (efi_banks == UINT32_MAX)
2886 log_debug("Boot loader set the LoaderTpm2ActivePcrBanks EFI variable to indicate that the GetActivePcrBanks() API is not available in the firmware. We have to guess the used PCR banks.");
2887 else if (efi_banks == 0)
2888 log_debug("Boot loader set the LoaderTpm2ActivePcrBanks EFI variable to zero to indicate that TPM support is not available in the firmware. We'll have to guess the used PCR banks.");
2889 else {
2890 if (BIT_SET(efi_banks, TPM2_ALG_SHA256))
2891 *ret = TPM2_ALG_SHA256;
2892 else if (BIT_SET(efi_banks, TPM2_ALG_SHA1))
2893 *ret = TPM2_ALG_SHA1;
2894 else
2895 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Firmware reports neither SHA1 nor SHA256 PCR banks, cannot operate.");
2896
2897 log_debug("Picked best PCR bank %s based on firmware reported banks.", tpm2_hash_alg_to_string(*ret));
2898 return 0;
2899 }
2900
2901 if (pcr_mask == 0) {
2902 log_debug("Asked to pick best PCR bank but no PCRs selected we could derive this from. Defaulting to SHA256.");
2903 *ret = TPM2_ALG_SHA256; /* if no PCRs are selected this doesn't matter anyway... */
2904 return 0;
2905 }
2906
2907 FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(selection, &c->capability_pcrs) {
2908 TPMI_ALG_HASH hash = selection->hash;
2909 int good;
2910
2911 /* For now we are only interested in the SHA1 and SHA256 banks */
2912 if (!IN_SET(hash, TPM2_ALG_SHA256, TPM2_ALG_SHA1))
2913 continue;
2914
2915 r = tpm2_bank_has24(selection);
2916 if (r < 0)
2917 return r;
2918 if (!r)
2919 continue;
2920
2921 good = tpm2_pcr_mask_good(c, hash, pcr_mask);
2922 if (good < 0)
2923 return good;
2924
2925 if (hash == TPM2_ALG_SHA256) {
2926 supported_hash = TPM2_ALG_SHA256;
2927 if (good) {
2928 /* Great, SHA256 is supported and has initialized PCR values, we are done. */
2929 hash_with_valid_pcr = TPM2_ALG_SHA256;
2930 break;
2931 }
2932 } else {
2933 assert(hash == TPM2_ALG_SHA1);
2934
2935 if (supported_hash == 0)
2936 supported_hash = TPM2_ALG_SHA1;
2937
2938 if (good && hash_with_valid_pcr == 0)
2939 hash_with_valid_pcr = TPM2_ALG_SHA1;
2940 }
2941 }
2942
2943 /* We preferably pick SHA256, but only if its PCRs are initialized or neither the SHA1 nor the SHA256
2944 * PCRs are initialized. If SHA256 is not supported but SHA1 is and its PCRs are too, we prefer
2945 * SHA1.
2946 *
2947 * We log at LOG_NOTICE level whenever we end up using the SHA1 bank or when the PCRs we bind to are
2948 * not initialized. */
2949
2950 if (hash_with_valid_pcr == TPM2_ALG_SHA256) {
2951 assert(supported_hash == TPM2_ALG_SHA256);
2952 log_debug("TPM2 device supports SHA256 PCR bank and SHA256 PCRs are valid, yay!");
2953 *ret = TPM2_ALG_SHA256;
2954 } else if (hash_with_valid_pcr == TPM2_ALG_SHA1) {
2955 if (supported_hash == TPM2_ALG_SHA256)
2956 log_notice("TPM2 device supports both SHA1 and SHA256 PCR banks, but only SHA1 PCRs are valid, falling back to SHA1 bank. This reduces the security level substantially.");
2957 else {
2958 assert(supported_hash == TPM2_ALG_SHA1);
2959 log_notice("TPM2 device lacks support for SHA256 PCR bank, but SHA1 bank is supported and SHA1 PCRs are valid, falling back to SHA1 bank. This reduces the security level substantially.");
2960 }
2961
2962 *ret = TPM2_ALG_SHA1;
2963 } else if (supported_hash == TPM2_ALG_SHA256) {
2964 log_notice("TPM2 device supports SHA256 PCR bank but none of the selected PCRs are valid! Firmware apparently did not initialize any of the selected PCRs. Proceeding anyway with SHA256 bank. PCR policy effectively unenforced!");
2965 *ret = TPM2_ALG_SHA256;
2966 } else if (supported_hash == TPM2_ALG_SHA1) {
2967 log_notice("TPM2 device lacks support for SHA256 bank, but SHA1 bank is supported, but none of the selected PCRs are valid! Firmware apparently did not initialize any of the selected PCRs. Proceeding anyway with SHA1 bank. PCR policy effectively unenforced!");
2968 *ret = TPM2_ALG_SHA1;
2969 } else
2970 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2971 "TPM2 module supports neither SHA1 nor SHA256 PCR banks, cannot operate.");
2972
2973 return 0;
2974 }
2975
2976 int tpm2_get_good_pcr_banks(
2977 Tpm2Context *c,
2978 uint32_t pcr_mask,
2979 TPMI_ALG_HASH **ret) {
2980
2981 _cleanup_free_ TPMI_ALG_HASH *good_banks = NULL, *fallback_banks = NULL;
2982 size_t n_good_banks = 0, n_fallback_banks = 0;
2983 int r;
2984
2985 assert(c);
2986 assert(ret);
2987
2988 uint32_t efi_banks;
2989 r = efi_get_active_pcr_banks(&efi_banks);
2990 if (r < 0) {
2991 if (!IN_SET(r, -ENOENT, -EOPNOTSUPP))
2992 return r;
2993
2994 /* If the variable is not set we have to guess via the code below */
2995 log_debug("Boot loader didn't set the LoaderTpm2ActivePcrBanks EFI variable or EFI support is unavailable, we have to guess the used PCR banks.");
2996 } else if (efi_banks == UINT32_MAX)
2997 log_debug("Boot loader set the LoaderTpm2ActivePcrBanks EFI variable to indicate that the GetActivePcrBanks() API is not available in the firmware. We have to guess the used PCR banks.");
2998 else if (efi_banks == 0)
2999 log_debug("Boot loader set the LoaderTpm2ActivePcrBanks EFI variable to zero to indicate that TPM support is not available in the firmware. We'll have to guess the used PCR banks.");
3000 else {
3001 FOREACH_ARRAY(hash, tpm2_hash_algorithms, TPM2_N_HASH_ALGORITHMS) {
3002 if (!BIT_SET(efi_banks, *hash))
3003 continue;
3004
3005 if (!GREEDY_REALLOC(good_banks, n_good_banks+1))
3006 return log_oom_debug();
3007
3008 good_banks[n_good_banks++] = *hash;
3009 }
3010
3011 log_debug("Found %zu initialized TPM2 banks reported by firmware.", n_good_banks);
3012 *ret = TAKE_PTR(good_banks);
3013 return (int) n_good_banks;
3014 }
3015
3016 FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(selection, &c->capability_pcrs) {
3017 TPMI_ALG_HASH hash = selection->hash;
3018
3019 /* Let's see if this bank is superficially OK, i.e. has at least 24 enabled registers */
3020 r = tpm2_bank_has24(selection);
3021 if (r < 0)
3022 return r;
3023 if (!r)
3024 continue;
3025
3026 /* Let's now see if this bank has any of the selected PCRs actually initialized */
3027 r = tpm2_pcr_mask_good(c, hash, pcr_mask);
3028 if (r < 0)
3029 return r;
3030
3031 if (n_good_banks + n_fallback_banks >= INT_MAX)
3032 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Too many good TPM2 banks?");
3033
3034 if (r) {
3035 if (!GREEDY_REALLOC(good_banks, n_good_banks+1))
3036 return log_oom_debug();
3037
3038 good_banks[n_good_banks++] = hash;
3039 } else {
3040 if (!GREEDY_REALLOC(fallback_banks, n_fallback_banks+1))
3041 return log_oom_debug();
3042
3043 fallback_banks[n_fallback_banks++] = hash;
3044 }
3045 }
3046
3047 /* Preferably, use the good banks (i.e. the ones the PCR values are actually initialized so
3048 * far). Otherwise use the fallback banks (i.e. which exist and are enabled, but so far not used. */
3049 if (n_good_banks > 0) {
3050 log_debug("Found %zu fully initialized TPM2 banks.", n_good_banks);
3051 *ret = TAKE_PTR(good_banks);
3052 return (int) n_good_banks;
3053 }
3054 if (n_fallback_banks > 0) {
3055 log_debug("Found %zu enabled but un-initialized TPM2 banks.", n_fallback_banks);
3056 *ret = TAKE_PTR(fallback_banks);
3057 return (int) n_fallback_banks;
3058 }
3059
3060 /* No suitable banks found. */
3061 *ret = NULL;
3062 return 0;
3063 }
3064
3065 int tpm2_get_good_pcr_banks_strv(
3066 Tpm2Context *c,
3067 uint32_t pcr_mask,
3068 char ***ret) {
3069
3070 #if HAVE_OPENSSL
3071 _cleanup_free_ TPMI_ALG_HASH *algs = NULL;
3072 _cleanup_strv_free_ char **l = NULL;
3073 int n_algs, r;
3074
3075 assert(c);
3076 assert(ret);
3077
3078 r = dlopen_libcrypto(LOG_DEBUG);
3079 if (r < 0)
3080 return r;
3081
3082 n_algs = tpm2_get_good_pcr_banks(c, pcr_mask, &algs);
3083 if (n_algs < 0)
3084 return n_algs;
3085
3086 FOREACH_ARRAY(a, algs, n_algs) {
3087 _cleanup_free_ char *n = NULL;
3088 const EVP_MD *implementation;
3089 const char *salg;
3090
3091 salg = tpm2_hash_alg_to_string(*a);
3092 if (!salg)
3093 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "TPM2 operates with unknown PCR algorithm, can't measure.");
3094
3095 implementation = sym_EVP_get_digestbyname(salg);
3096 if (!implementation)
3097 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "TPM2 operates with unsupported PCR algorithm, can't measure.");
3098
3099 n = strdup(ASSERT_PTR(sym_EVP_MD_get0_name(implementation)));
3100 if (!n)
3101 return log_oom_debug();
3102
3103 ascii_strlower(n); /* OpenSSL uses uppercase digest names, we prefer them lower case. */
3104
3105 if (strv_consume(&l, TAKE_PTR(n)) < 0)
3106 return log_oom_debug();
3107 }
3108
3109 *ret = TAKE_PTR(l);
3110 return 0;
3111 #else /* HAVE_OPENSSL */
3112 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
3113 #endif
3114 }
3115
3116 /* Hash data into the digest.
3117 *
3118 * If 'extend' is true, the hashing operation starts with the existing digest hash (and the digest is
3119 * required to have a hash and its size must be correct). If 'extend' is false, the digest size is
3120 * initialized to the correct size for 'alg' and the hashing operation does not include any existing digest
3121 * hash. If 'extend' is false and no data is provided, the digest is initialized to a zero digest.
3122 *
3123 * On success, the digest hash will be updated with the hashing operation result and the digest size will be
3124 * correct for 'alg'.
3125 *
3126 * This currently only provides SHA256, so 'alg' must be TPM2_ALG_SHA256. */
3127 int tpm2_digest_many(
3128 TPMI_ALG_HASH alg,
3129 TPM2B_DIGEST *digest,
3130 const struct iovec data[],
3131 size_t n_data,
3132 bool extend) {
3133
3134 struct sha256_ctx ctx;
3135
3136 assert(digest);
3137 assert(data || n_data == 0);
3138
3139 if (alg != TPM2_ALG_SHA256)
3140 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3141 "Hash algorithm not supported: 0x%x", alg);
3142
3143 if (extend && digest->size != SHA256_DIGEST_SIZE)
3144 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3145 "Digest size 0x%x, require 0x%x",
3146 digest->size, (unsigned)SHA256_DIGEST_SIZE);
3147
3148 /* Since we're hardcoding SHA256 (for now), we can check this at compile time. */
3149 assert_cc(sizeof(digest->buffer) >= SHA256_DIGEST_SIZE);
3150
3151 CLEANUP_ERASE(ctx);
3152
3153 sha256_init_ctx(&ctx);
3154
3155 if (extend)
3156 sha256_process_bytes(digest->buffer, digest->size, &ctx);
3157 else {
3158 *digest = (TPM2B_DIGEST) {
3159 .size = SHA256_DIGEST_SIZE,
3160 };
3161 if (n_data == 0) /* If not extending and no data, return zero hash */
3162 return 0;
3163 }
3164
3165 FOREACH_ARRAY(d, data, n_data)
3166 sha256_process_bytes(d->iov_base, d->iov_len, &ctx);
3167
3168 sha256_finish_ctx(&ctx, digest->buffer);
3169
3170 return 0;
3171 }
3172
3173 /* Same as tpm2_digest_many() but data is contained in TPM2B_DIGEST[]. The digests may be any size digests. */
3174 int tpm2_digest_many_digests(
3175 TPMI_ALG_HASH alg,
3176 TPM2B_DIGEST *digest,
3177 const TPM2B_DIGEST data[],
3178 size_t n_data,
3179 bool extend) {
3180
3181 _cleanup_free_ struct iovec *iovecs = NULL;
3182
3183 assert(data || n_data == 0);
3184
3185 iovecs = new(struct iovec, n_data);
3186 if (!iovecs)
3187 return log_oom_debug();
3188
3189 for (size_t i = 0; i < n_data; i++)
3190 iovecs[i] = IOVEC_MAKE((void*) data[i].buffer, data[i].size);
3191
3192 return tpm2_digest_many(alg, digest, iovecs, n_data, extend);
3193 }
3194
3195 /* This hashes the provided pin into a digest value, but also verifies that the final byte is not 0, because
3196 * the TPM specification Part 1 ("Architecture") section Authorization Values (subsection "Authorization Size
3197 * Convention") states "Trailing octets of zero are to be removed from any string before it is used as an
3198 * authValue". Since the TPM doesn't know if the auth value is a "string" or just a hash digest, any hash
3199 * digest that randomly happens to end in 0 must have the final 0(s) trimmed.
3200 *
3201 * This is required at 2 points. First, when setting the authValue during creation of new sealed objects, in
3202 * tpm2_seal(). This only applies to newly created objects, of course. Second, when using a previously
3203 * created sealed object that has an authValue set, we use the sealed objects as the session bind key. This
3204 * requires calling SetAuth so tpm2-tss can correctly calculate the HMAC to use for the encryption session.
3205 *
3206 * TPM implementations will perform the trimming for any authValue for existing sealed objects, so the
3207 * tpm2-tss library must also perform the trimming before HMAC calculation, but it does not yet; this bug is
3208 * open to add the trimming: https://github.com/tpm2-software/tpm2-tss/issues/2664
3209 *
3210 * Until our minimum tpm2-tss version contains a fix for that bug, we must perform the trimming
3211 * ourselves. Note that since we are trimming, which is exactly what a TPM implementation would do, this will
3212 * work for both existing objects with a authValue ending in 0(s) as well as new sealed objects we create,
3213 * which we will trim the 0(s) from before sending to the TPM.
3214 */
3215 static void tpm2_trim_auth_value(TPM2B_AUTH *auth) {
3216 bool trimmed = false;
3217
3218 assert(auth);
3219
3220 while (auth->size > 0 && auth->buffer[auth->size - 1] == 0) {
3221 trimmed = true;
3222 auth->size--;
3223 }
3224
3225 if (trimmed)
3226 log_debug("authValue ends in 0, trimming as required by the TPM2 specification Part 1 section 'HMAC Computation' authValue Note 2.");
3227 }
3228
3229 int tpm2_auth_value_from_pin(TPMI_ALG_HASH hash, const char *pin, TPM2B_AUTH *ret_auth) {
3230 TPM2B_AUTH auth = {};
3231 int r;
3232
3233 assert(pin);
3234 assert(ret_auth);
3235
3236 r = tpm2_digest_buffer(hash, &auth, pin, strlen(pin), /* extend= */ false);
3237 if (r < 0)
3238 return r;
3239
3240 tpm2_trim_auth_value(&auth);
3241
3242 *ret_auth = TAKE_STRUCT(auth);
3243
3244 return 0;
3245 }
3246
3247 int tpm2_set_auth_binary(Tpm2Context *c, const Tpm2Handle *handle, const TPM2B_AUTH *auth) {
3248 TSS2_RC rc;
3249
3250 assert(c);
3251 assert(handle);
3252
3253 if (!auth)
3254 return 0;
3255
3256 rc = sym_Esys_TR_SetAuth(c->esys_context, handle->esys_handle, auth);
3257 if (rc != TSS2_RC_SUCCESS)
3258 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3259 "Failed to load PIN in TPM: %s", sym_Tss2_RC_Decode(rc));
3260
3261 return 0;
3262 }
3263
3264 int tpm2_set_auth(Tpm2Context *c, const Tpm2Handle *handle, const char *pin) {
3265 TPM2B_AUTH auth = {};
3266 int r;
3267
3268 assert(c);
3269 assert(handle);
3270
3271 if (!pin)
3272 return 0;
3273
3274 CLEANUP_ERASE(auth);
3275
3276 r = tpm2_auth_value_from_pin(TPM2_ALG_SHA256, pin, &auth);
3277 if (r < 0)
3278 return r;
3279
3280 return tpm2_set_auth_binary(c, handle, &auth);
3281 }
3282
3283 static bool tpm2_is_encryption_session(Tpm2Context *c, const Tpm2Handle *session) {
3284 TPMA_SESSION flags = 0;
3285 TSS2_RC rc;
3286
3287 assert(c);
3288 assert(session);
3289
3290 rc = sym_Esys_TRSess_GetAttributes(c->esys_context, session->esys_handle, &flags);
3291 if (rc != TSS2_RC_SUCCESS)
3292 return false;
3293
3294 return (flags & TPMA_SESSION_DECRYPT) && (flags & TPMA_SESSION_ENCRYPT);
3295 }
3296
3297 int tpm2_make_encryption_session(
3298 Tpm2Context *c,
3299 const Tpm2Handle *primary,
3300 const Tpm2Handle *bind_key,
3301 Tpm2Handle **ret_session) {
3302
3303 const TPMA_SESSION sessionAttributes = TPMA_SESSION_DECRYPT | TPMA_SESSION_ENCRYPT |
3304 TPMA_SESSION_CONTINUESESSION;
3305 TSS2_RC rc;
3306 int r;
3307
3308 assert(c);
3309 assert(primary);
3310 assert(ret_session);
3311
3312 log_debug("Starting HMAC encryption session.");
3313
3314 /* Start a salted, unbound HMAC session with a well-known key (e.g. primary key) as tpmKey, which
3315 * means that the random salt will be encrypted with the well-known key. That way, only the TPM can
3316 * recover the salt, which is then used for key derivation. */
3317 _cleanup_(tpm2_handle_freep) Tpm2Handle *session = NULL;
3318 r = tpm2_handle_new(c, &session);
3319 if (r < 0)
3320 return r;
3321
3322 rc = sym_Esys_StartAuthSession(
3323 c->esys_context,
3324 primary->esys_handle,
3325 bind_key ? bind_key->esys_handle : ESYS_TR_NONE,
3326 ESYS_TR_NONE,
3327 ESYS_TR_NONE,
3328 ESYS_TR_NONE,
3329 NULL,
3330 TPM2_SE_HMAC,
3331 &SESSION_TEMPLATE_SYM_AES_128_CFB,
3332 TPM2_ALG_SHA256,
3333 &session->esys_handle);
3334 if (rc != TSS2_RC_SUCCESS)
3335 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3336 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc));
3337
3338 /* Enable parameter encryption/decryption with AES in CFB mode. Together with HMAC digests (which are
3339 * always used for sessions), this provides confidentiality, integrity and replay protection for
3340 * operations that use this session. */
3341 rc = sym_Esys_TRSess_SetAttributes(c->esys_context, session->esys_handle, sessionAttributes, 0xff);
3342 if (rc != TSS2_RC_SUCCESS)
3343 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3344 "Failed to configure TPM session: %s", sym_Tss2_RC_Decode(rc));
3345
3346 *ret_session = TAKE_PTR(session);
3347
3348 return 0;
3349 }
3350
3351 int tpm2_make_policy_session(
3352 Tpm2Context *c,
3353 const Tpm2Handle *primary,
3354 const Tpm2Handle *encryption_session,
3355 Tpm2Handle **ret_session) {
3356
3357 TSS2_RC rc;
3358 int r;
3359
3360 assert(c);
3361 assert(primary);
3362 assert(encryption_session);
3363 assert(ret_session);
3364
3365 if (!tpm2_is_encryption_session(c, encryption_session))
3366 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
3367 "Missing encryption session");
3368
3369 log_debug("Starting policy session.");
3370
3371 _cleanup_(tpm2_handle_freep) Tpm2Handle *session = NULL;
3372 r = tpm2_handle_new(c, &session);
3373 if (r < 0)
3374 return r;
3375
3376 rc = sym_Esys_StartAuthSession(
3377 c->esys_context,
3378 primary->esys_handle,
3379 ESYS_TR_NONE,
3380 encryption_session->esys_handle,
3381 ESYS_TR_NONE,
3382 ESYS_TR_NONE,
3383 NULL,
3384 TPM2_SE_POLICY,
3385 &SESSION_TEMPLATE_SYM_AES_128_CFB,
3386 TPM2_ALG_SHA256,
3387 &session->esys_handle);
3388 if ((rc & ~TPM2_RC_N_MASK) == TPM2_RC_AUTH_FAIL)
3389 return log_debug_errno(SYNTHETIC_ERRNO(EILSEQ),
3390 "Authorization failure from TPM: %s", sym_Tss2_RC_Decode(rc));
3391 if (rc == TPM2_RC_LOCKOUT)
3392 return log_debug_errno(SYNTHETIC_ERRNO(ENOLCK),
3393 "TPM2 device is in dictionary attack lockout mode.");
3394 if (rc != TSS2_RC_SUCCESS)
3395 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3396 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc));
3397
3398 *ret_session = TAKE_PTR(session);
3399
3400 return 0;
3401 }
3402
3403 static int find_signature(
3404 sd_json_variant *v,
3405 const TPML_PCR_SELECTION *pcr_selection,
3406 const void *fp,
3407 size_t fp_size,
3408 const void *policy,
3409 size_t policy_size,
3410 void *ret_signature,
3411 size_t *ret_signature_size) {
3412
3413 #if HAVE_OPENSSL
3414 sd_json_variant *b, *i;
3415 const char *k;
3416 int r;
3417
3418 /* Searches for a signature blob in the specified JSON object. Search keys are PCR bank, PCR mask,
3419 * public key, and policy digest. */
3420
3421 if (!sd_json_variant_is_object(v))
3422 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature is not a JSON object.");
3423
3424 uint16_t pcr_bank = pcr_selection->pcrSelections[0].hash;
3425 uint32_t pcr_mask = tpm2_tpml_pcr_selection_to_mask(pcr_selection, pcr_bank);
3426
3427 k = tpm2_hash_alg_to_string(pcr_bank);
3428 if (!k)
3429 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Don't know PCR bank %" PRIu16, pcr_bank);
3430
3431 /* First, find field by bank */
3432 b = sd_json_variant_by_key(v, k);
3433 if (!b)
3434 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO), "Signature lacks data for PCR bank '%s'.", k);
3435
3436 if (!sd_json_variant_is_array(b))
3437 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Bank data is not a JSON array.");
3438
3439 /* Now iterate through all signatures known for this bank */
3440 JSON_VARIANT_ARRAY_FOREACH(i, b) {
3441 _cleanup_free_ void *fpj_data = NULL, *polj_data = NULL;
3442 sd_json_variant *maskj, *fpj, *sigj, *polj;
3443 size_t fpj_size, polj_size;
3444 uint32_t parsed_mask;
3445
3446 if (!sd_json_variant_is_object(i))
3447 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Bank data element is not a JSON object");
3448
3449 /* Check if the PCR mask matches our expectations */
3450 maskj = sd_json_variant_by_key(i, "pcrs");
3451 if (!maskj)
3452 continue;
3453
3454 r = tpm2_parse_pcr_json_array(maskj, &parsed_mask);
3455 if (r < 0)
3456 return log_debug_errno(r, "Failed to parse JSON PCR mask");
3457
3458 if (parsed_mask != pcr_mask)
3459 continue; /* Not for this PCR mask */
3460
3461 /* Then check if this is for the public key we operate with */
3462 fpj = sd_json_variant_by_key(i, "pkfp");
3463 if (!fpj)
3464 continue;
3465
3466 r = sd_json_variant_unhex(fpj, &fpj_data, &fpj_size);
3467 if (r < 0)
3468 return log_debug_errno(r, "Failed to decode fingerprint in JSON data: %m");
3469
3470 if (memcmp_nn(fp, fp_size, fpj_data, fpj_size) != 0)
3471 continue; /* Not for this public key */
3472
3473 /* Finally, check if this is for the PCR policy we expect this to be */
3474 polj = sd_json_variant_by_key(i, "pol");
3475 if (!polj)
3476 continue;
3477
3478 r = sd_json_variant_unhex(polj, &polj_data, &polj_size);
3479 if (r < 0)
3480 return log_debug_errno(r, "Failed to decode policy hash JSON data: %m");
3481
3482 if (memcmp_nn(policy, policy_size, polj_data, polj_size) != 0)
3483 continue;
3484
3485 /* This entry matches all our expectations, now return the signature included in it */
3486 sigj = sd_json_variant_by_key(i, "sig");
3487 if (!sigj)
3488 continue;
3489
3490 return sd_json_variant_unbase64(sigj, ret_signature, ret_signature_size);
3491 }
3492
3493 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO), "Couldn't find signature for this PCR bank, PCR index and public key.");
3494 #else /* HAVE_OPENSSL */
3495 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
3496 #endif
3497 }
3498
3499 /* Calculates the "name" of a public key.
3500 *
3501 * As specified in TPM2 spec "Part 1: Architecture", a key's "name" is its nameAlg value followed by a hash
3502 * of its TPM2 public area, all properly marshalled. This allows a key's "name" to be dependent not only on
3503 * the key fingerprint, but also on the TPM2-specific fields that associated with the key (i.e. all fields in
3504 * TPMT_PUBLIC). Note that this means an existing key may not change any of its TPMT_PUBLIC fields, since
3505 * that would also change the key name.
3506 *
3507 * Since we (currently) hardcode to always using SHA256 for hashing, this returns an error if the public key
3508 * nameAlg is not TPM2_ALG_SHA256. */
3509 int tpm2_calculate_pubkey_name(const TPMT_PUBLIC *public, TPM2B_NAME *ret_name) {
3510 TSS2_RC rc;
3511 int r;
3512
3513 assert(public);
3514 assert(ret_name);
3515
3516 r = dlopen_tpm2(LOG_DEBUG);
3517 if (r < 0)
3518 return r;
3519
3520 if (public->nameAlg != TPM2_ALG_SHA256)
3521 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3522 "Unsupported nameAlg: 0x%x",
3523 public->nameAlg);
3524
3525 _cleanup_free_ uint8_t *buf = NULL;
3526 size_t size = 0;
3527
3528 buf = (uint8_t*) new(TPMT_PUBLIC, 1);
3529 if (!buf)
3530 return log_oom_debug();
3531
3532 rc = sym_Tss2_MU_TPMT_PUBLIC_Marshal(public, buf, sizeof(TPMT_PUBLIC), &size);
3533 if (rc != TSS2_RC_SUCCESS)
3534 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3535 "Failed to marshal public key: %s", sym_Tss2_RC_Decode(rc));
3536
3537 TPM2B_DIGEST digest = {};
3538 r = tpm2_digest_buffer(TPM2_ALG_SHA256, &digest, buf, size, /* extend= */ false);
3539 if (r < 0)
3540 return r;
3541
3542 TPMT_HA ha = {
3543 .hashAlg = TPM2_ALG_SHA256,
3544 };
3545 assert(digest.size <= sizeof(ha.digest.sha256));
3546 memcpy_safe(ha.digest.sha256, digest.buffer, digest.size);
3547
3548 TPM2B_NAME name;
3549 size = 0;
3550 rc = sym_Tss2_MU_TPMT_HA_Marshal(&ha, name.name, sizeof(name.name), &size);
3551 if (rc != TSS2_RC_SUCCESS)
3552 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3553 "Failed to marshal key name: %s", sym_Tss2_RC_Decode(rc));
3554 name.size = size;
3555
3556 tpm2_log_debug_name(&name, "Calculated public key name");
3557
3558 *ret_name = name;
3559
3560 return 0;
3561 }
3562
3563 /* Get the "name" of a key from the TPM.
3564 *
3565 * The "name" of a key is explained above in tpm2_calculate_pubkey_name().
3566 *
3567 * The handle must reference a key already present in the TPM. It may be either a public key only, or a
3568 * public/private keypair. */
3569 int tpm2_get_name(
3570 Tpm2Context *c,
3571 const Tpm2Handle *handle,
3572 TPM2B_NAME **ret_name) {
3573
3574 _cleanup_(Esys_Freep) TPM2B_NAME *name = NULL;
3575 TSS2_RC rc;
3576
3577 assert(c);
3578 assert(handle);
3579 assert(ret_name);
3580
3581 rc = sym_Esys_TR_GetName(c->esys_context, handle->esys_handle, &name);
3582 if (rc != TSS2_RC_SUCCESS)
3583 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3584 "Failed to get name of public key from TPM: %s", sym_Tss2_RC_Decode(rc));
3585
3586 tpm2_log_debug_name(name, "Object name");
3587
3588 *ret_name = TAKE_PTR(name);
3589
3590 return 0;
3591 }
3592
3593 int tpm2_calculate_nv_index_name(const TPMS_NV_PUBLIC *nvpublic, TPM2B_NAME *ret_name) {
3594 TSS2_RC rc;
3595 int r;
3596
3597 assert(nvpublic);
3598 assert(ret_name);
3599
3600 r = dlopen_tpm2(LOG_DEBUG);
3601 if (r < 0)
3602 return r;
3603
3604 if (nvpublic->nameAlg != TPM2_ALG_SHA256)
3605 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3606 "Unsupported nameAlg: 0x%x",
3607 nvpublic->nameAlg);
3608
3609 _cleanup_free_ uint8_t *buf = NULL;
3610 size_t size = 0;
3611
3612 buf = (uint8_t*) new(TPMS_NV_PUBLIC, 1);
3613 if (!buf)
3614 return log_oom_debug();
3615
3616 rc = sym_Tss2_MU_TPMS_NV_PUBLIC_Marshal(nvpublic, buf, sizeof(TPMS_NV_PUBLIC), &size);
3617 if (rc != TSS2_RC_SUCCESS)
3618 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3619 "Failed to marshal NV index: %s", sym_Tss2_RC_Decode(rc));
3620
3621 TPM2B_DIGEST digest = {};
3622 r = tpm2_digest_buffer(TPM2_ALG_SHA256, &digest, buf, size, /* extend= */ false);
3623 if (r < 0)
3624 return r;
3625
3626 TPMT_HA ha = {
3627 .hashAlg = TPM2_ALG_SHA256,
3628 };
3629 assert(digest.size <= sizeof(ha.digest.sha256));
3630 memcpy_safe(ha.digest.sha256, digest.buffer, digest.size);
3631
3632 TPM2B_NAME name;
3633 size = 0;
3634 rc = sym_Tss2_MU_TPMT_HA_Marshal(&ha, name.name, sizeof(name.name), &size);
3635 if (rc != TSS2_RC_SUCCESS)
3636 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3637 "Failed to marshal NV index name: %s", sym_Tss2_RC_Decode(rc));
3638 name.size = size;
3639
3640 tpm2_log_debug_name(&name, "Calculated NV index name");
3641
3642 *ret_name = name;
3643
3644 return 0;
3645 }
3646
3647 /* Extend 'digest' with the PolicyAuthValue calculated hash. */
3648 int tpm2_calculate_policy_auth_value(TPM2B_DIGEST *digest) {
3649 TPM2_CC command = TPM2_CC_PolicyAuthValue;
3650 TSS2_RC rc;
3651 int r;
3652
3653 assert(digest);
3654 assert(digest->size == SHA256_DIGEST_SIZE);
3655
3656 r = dlopen_tpm2(LOG_DEBUG);
3657 if (r < 0)
3658 return r;
3659
3660 uint8_t buf[sizeof(command)];
3661 size_t offset = 0;
3662
3663 rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, sizeof(buf), &offset);
3664 if (rc != TSS2_RC_SUCCESS)
3665 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3666 "Failed to marshal PolicyAuthValue command: %s", sym_Tss2_RC_Decode(rc));
3667
3668 if (offset != sizeof(command))
3669 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3670 "Offset 0x%zx wrong after marshalling PolicyAuthValue command", offset);
3671
3672 r = tpm2_digest_buffer(TPM2_ALG_SHA256, digest, buf, offset, /* extend= */ true);
3673 if (r < 0)
3674 return r;
3675
3676 tpm2_log_debug_digest(digest, "PolicyAuthValue calculated digest");
3677
3678 return 0;
3679 }
3680
3681 int tpm2_policy_auth_value(
3682 Tpm2Context *c,
3683 const Tpm2Handle *session,
3684 TPM2B_DIGEST **ret_policy_digest) {
3685
3686 TSS2_RC rc;
3687
3688 assert(c);
3689 assert(session);
3690
3691 log_debug("Submitting AuthValue policy.");
3692
3693 rc = sym_Esys_PolicyAuthValue(
3694 c->esys_context,
3695 session->esys_handle,
3696 ESYS_TR_NONE,
3697 ESYS_TR_NONE,
3698 ESYS_TR_NONE);
3699 if (rc != TSS2_RC_SUCCESS)
3700 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3701 "Failed to add authValue policy to TPM: %s",
3702 sym_Tss2_RC_Decode(rc));
3703
3704 return tpm2_get_policy_digest(c, session, ret_policy_digest);
3705 }
3706
3707 /* Extend 'digest' with the PolicySigned calculated hash. */
3708 int tpm2_calculate_policy_signed(TPM2B_DIGEST *digest, const TPM2B_NAME *name) {
3709 TPM2_CC command = TPM2_CC_PolicySigned;
3710 TSS2_RC rc;
3711 int r;
3712
3713 assert(digest);
3714 assert(digest->size == SHA256_DIGEST_SIZE);
3715 assert(name);
3716
3717 r = dlopen_tpm2(LOG_DEBUG);
3718 if (r < 0)
3719 return r;
3720
3721 uint8_t buf[sizeof(command)];
3722 size_t offset = 0;
3723
3724 rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, sizeof(buf), &offset);
3725 if (rc != TSS2_RC_SUCCESS)
3726 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3727 "Failed to marshal PolicySigned command: %s", sym_Tss2_RC_Decode(rc));
3728
3729 if (offset != sizeof(command))
3730 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3731 "Offset 0x%zx wrong after marshalling PolicySigned command", offset);
3732
3733 struct iovec data[] = {
3734 IOVEC_MAKE(buf, offset),
3735 IOVEC_MAKE(name->name, name->size),
3736 };
3737
3738 r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, ELEMENTSOF(data), /* extend= */ true);
3739 if (r < 0)
3740 return r;
3741
3742 const TPM2B_NONCE policyRef = {}; /* For now, we do not make use of the policyRef stuff */
3743
3744 r = tpm2_digest_buffer(TPM2_ALG_SHA256, digest, policyRef.buffer, policyRef.size, /* extend= */ true);
3745 if (r < 0)
3746 return r;
3747
3748 tpm2_log_debug_digest(digest, "PolicySigned calculated digest");
3749
3750 return 0;
3751 }
3752
3753 int tpm2_policy_signed_hmac_sha256(
3754 Tpm2Context *c,
3755 const Tpm2Handle *session,
3756 const Tpm2Handle *hmac_key_handle,
3757 const struct iovec *hmac_key,
3758 TPM2B_DIGEST **ret_policy_digest) {
3759
3760 #if HAVE_OPENSSL
3761 TSS2_RC rc;
3762 int r;
3763
3764 assert(c);
3765 assert(session);
3766 assert(hmac_key_handle);
3767 assert(iovec_is_set(hmac_key));
3768
3769 /* This sends a TPM2_PolicySigned command to the tpm. As signature key we use an HMAC-SHA256 key
3770 * specified in the hmac_key parameter. The secret key must be loaded into the TPM already and
3771 * referenced in hmac_key_handle. */
3772
3773 r = dlopen_libcrypto(LOG_DEBUG);
3774 if (r < 0)
3775 return r;
3776
3777 log_debug("Submitting PolicySigned policy for HMAC-SHA256.");
3778
3779 /* Acquire the nonce from the TPM that we shall sign */
3780 _cleanup_(Esys_Freep) TPM2B_NONCE *nonce = NULL;
3781 rc = sym_Esys_TRSess_GetNonceTPM(
3782 c->esys_context,
3783 session->esys_handle,
3784 &nonce);
3785 if (rc != TSS2_RC_SUCCESS)
3786 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3787 "Failed to determine NoneTPM of auth session: %s",
3788 sym_Tss2_RC_Decode(rc));
3789
3790 be32_t expiration = htobe64(0);
3791 const TPM2B_DIGEST cpHashA = {}; /* For now, we do not make use of the cpHashA stuff */
3792 const TPM2B_NONCE policyRef = {}; /* ditto, we do not bother with policyRef */
3793
3794 /* Put together the data to sign, as per TPM2 Spec Part 3, 23.3.1 */
3795 struct iovec data_to_sign[] = {
3796 IOVEC_MAKE(nonce->buffer, nonce->size),
3797 IOVEC_MAKE(&expiration, sizeof(expiration)),
3798 IOVEC_MAKE(cpHashA.buffer, cpHashA.size),
3799 IOVEC_MAKE(policyRef.buffer, policyRef.size),
3800 };
3801
3802 /* Now calculate the digest of the data we put together */
3803 TPM2B_DIGEST digest_to_sign;
3804 r = tpm2_digest_many(TPM2_ALG_SHA256, &digest_to_sign, data_to_sign, ELEMENTSOF(data_to_sign), /* extend= */ false);
3805 if (r < 0)
3806 return r;
3807
3808 unsigned char hmac_signature[SHA256_DIGEST_SIZE];
3809 unsigned hmac_signature_size = sizeof(hmac_signature);
3810
3811 /* And sign this with our key */
3812 if (!sym_HMAC(sym_EVP_sha256(),
3813 hmac_key->iov_base,
3814 hmac_key->iov_len,
3815 digest_to_sign.buffer,
3816 digest_to_sign.size,
3817 hmac_signature,
3818 &hmac_signature_size))
3819 return -ENOTRECOVERABLE;
3820
3821 /* Now bring the signature into a format that the TPM understands */
3822 TPMT_SIGNATURE sig = {
3823 .sigAlg = TPM2_ALG_HMAC,
3824 .signature.hmac.hashAlg = TPM2_ALG_SHA256,
3825 };
3826 assert(hmac_signature_size == sizeof(sig.signature.hmac.digest.sha256));
3827 memcpy(sig.signature.hmac.digest.sha256, hmac_signature, hmac_signature_size);
3828
3829 /* And submit the whole shebang to the TPM */
3830 rc = sym_Esys_PolicySigned(
3831 c->esys_context,
3832 hmac_key_handle->esys_handle,
3833 session->esys_handle,
3834 /* shandle1= */ ESYS_TR_NONE,
3835 /* shandle2= */ ESYS_TR_NONE,
3836 /* shandle3= */ ESYS_TR_NONE,
3837 nonce,
3838 &cpHashA,
3839 &policyRef,
3840 expiration,
3841 &sig,
3842 /* timeout= */ NULL,
3843 /* policyTicket= */ NULL);
3844 if (rc != TSS2_RC_SUCCESS)
3845 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3846 "Failed to add PolicySigned policy to TPM: %s",
3847 sym_Tss2_RC_Decode(rc));
3848
3849 return tpm2_get_policy_digest(c, session, ret_policy_digest);
3850 #else /* HAVE_OPENSSL */
3851 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
3852 #endif
3853 }
3854
3855 int tpm2_calculate_policy_authorize_nv(
3856 const TPM2B_NV_PUBLIC *public_info,
3857 TPM2B_DIGEST *digest) {
3858 TPM2_CC command = TPM2_CC_PolicyAuthorizeNV;
3859 TSS2_RC rc;
3860 int r;
3861
3862 assert(public_info);
3863 assert(digest);
3864 assert(digest->size == SHA256_DIGEST_SIZE);
3865
3866 r = dlopen_tpm2(LOG_DEBUG);
3867 if (r < 0)
3868 return r;
3869
3870 uint8_t buf[sizeof(command)];
3871 size_t offset = 0;
3872
3873 rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, sizeof(buf), &offset);
3874 if (rc != TSS2_RC_SUCCESS)
3875 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3876 "Failed to marshal PolicyAuthorizeNV command: %s", sym_Tss2_RC_Decode(rc));
3877
3878 if (offset != sizeof(command))
3879 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3880 "Offset 0x%zx wrong after marshalling PolicyAuthorizeNV command", offset);
3881
3882 TPM2B_NV_PUBLIC public_info_copy = *public_info; /* Make a copy, since we must set TPMA_NV_WRITTEN for the calculation */
3883 public_info_copy.nvPublic.attributes |= TPMA_NV_WRITTEN;
3884
3885 TPM2B_NAME name = {};
3886 r = tpm2_calculate_nv_index_name(&public_info_copy.nvPublic, &name);
3887 if (r < 0)
3888 return r;
3889
3890 struct iovec data[] = {
3891 IOVEC_MAKE(buf, offset),
3892 IOVEC_MAKE(name.name, name.size),
3893 };
3894
3895 r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, ELEMENTSOF(data), /* extend= */ true);
3896 if (r < 0)
3897 return r;
3898
3899 tpm2_log_debug_digest(digest, "PolicyAuthorizeNV calculated digest");
3900
3901 return 0;
3902 }
3903
3904 int tpm2_policy_authorize_nv(
3905 Tpm2Context *c,
3906 const Tpm2Handle *session,
3907 const Tpm2Handle *nv_handle,
3908 TPM2B_DIGEST **ret_policy_digest) {
3909
3910 TSS2_RC rc;
3911
3912 assert(c);
3913 assert(session);
3914
3915 log_debug("Submitting AuthorizeNV policy.");
3916
3917 rc = sym_Esys_PolicyAuthorizeNV(
3918 c->esys_context,
3919 ESYS_TR_RH_OWNER,
3920 nv_handle->esys_handle,
3921 session->esys_handle,
3922 ESYS_TR_PASSWORD,
3923 ESYS_TR_NONE,
3924 ESYS_TR_NONE);
3925 if ((rc & ~(TPM2_RC_N_MASK|TPM2_RC_P)) == TPM2_RC_VALUE) /* Return a recognizable error if the policy
3926 * in the NV index does not match what we
3927 * just put together */
3928 return log_debug_errno(SYNTHETIC_ERRNO(EREMCHG),
3929 "Submitted policy does not match policy stored in PolicyAuthorizeNV.");
3930 if (rc != TSS2_RC_SUCCESS)
3931 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3932 "Failed to add AuthorizeNV policy to TPM: %s",
3933 sym_Tss2_RC_Decode(rc));
3934
3935 return tpm2_get_policy_digest(c, session, ret_policy_digest);
3936 }
3937
3938 int tpm2_policy_or(
3939 Tpm2Context *c,
3940 const Tpm2Handle *session,
3941 const TPM2B_DIGEST *branches, size_t n_branches,
3942 TPM2B_DIGEST **ret_policy_digest) {
3943
3944 TPML_DIGEST hash_list;
3945 TSS2_RC rc;
3946
3947 assert(c);
3948 assert(session);
3949
3950 if (n_branches > ELEMENTSOF(hash_list.digests))
3951 return -EOPNOTSUPP;
3952
3953 log_debug("Submitting OR policy.");
3954
3955 hash_list = (TPML_DIGEST) {
3956 .count = n_branches,
3957 };
3958
3959 memcpy(hash_list.digests, branches, n_branches * sizeof(TPM2B_DIGEST));
3960
3961 if (DEBUG_LOGGING)
3962 for (size_t i = 0; i < hash_list.count; i++) {
3963 _cleanup_free_ char *h = hexmem(hash_list.digests[i].buffer, hash_list.digests[i].size);
3964 log_debug("Submitting OR Branch #%zu: %s", i, h);
3965 }
3966
3967 rc = sym_Esys_PolicyOR(
3968 c->esys_context,
3969 session->esys_handle,
3970 ESYS_TR_NONE,
3971 ESYS_TR_NONE,
3972 ESYS_TR_NONE,
3973 &hash_list);
3974 if ((rc & ~(TPM2_RC_N_MASK|TPM2_RC_P)) == TPM2_RC_VALUE) /* Return a recognizable error if none of the OR branches matched */
3975 return log_debug_errno(SYNTHETIC_ERRNO(ENOANO),
3976 "None of the PolicyOR branches matched the current policy state.");
3977 if (rc != TSS2_RC_SUCCESS)
3978 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
3979 "Failed to add OR policy to TPM: %s",
3980 sym_Tss2_RC_Decode(rc));
3981
3982 return tpm2_get_policy_digest(c, session, ret_policy_digest);
3983 }
3984
3985 /* Extend 'digest' with the PolicyOR calculated hash. */
3986 int tpm2_calculate_policy_or(const TPM2B_DIGEST *branches, size_t n_branches, TPM2B_DIGEST *digest) {
3987 TPM2_CC command = TPM2_CC_PolicyOR;
3988 TSS2_RC rc;
3989 int r;
3990
3991 assert(digest);
3992 assert(digest->size == SHA256_DIGEST_SIZE);
3993
3994 if (n_branches == 0)
3995 return -EINVAL;
3996 if (n_branches == 1)
3997 log_warning("PolicyOR with a single branch submitted, this is weird.");
3998 if (n_branches > 8)
3999 return -E2BIG;
4000
4001 r = dlopen_tpm2(LOG_ERR);
4002 if (r < 0)
4003 return r;
4004
4005 uint8_t buf[sizeof(command)];
4006 size_t offset = 0;
4007
4008 rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, sizeof(buf), &offset);
4009 if (rc != TSS2_RC_SUCCESS)
4010 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4011 "Failed to marshal PolicyOR command: %s", sym_Tss2_RC_Decode(rc));
4012
4013 if (offset != sizeof(command))
4014 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4015 "Offset 0x%zx wrong after marshalling PolicyOR command", offset);
4016 _cleanup_free_ struct iovec *data = new(struct iovec, 1 + n_branches);
4017 if (!data)
4018 return log_oom();
4019
4020 data[0] = IOVEC_MAKE(buf, offset);
4021 for (size_t i = 0; i < n_branches; i++) {
4022 data[1 + i] = IOVEC_MAKE((void*) branches[i].buffer, branches[i].size);
4023
4024 if (DEBUG_LOGGING) {
4025 _cleanup_free_ char *h = hexmem(branches[i].buffer, branches[i].size);
4026 log_debug("OR Branch #%zu: %s", i, h);
4027 }
4028 }
4029
4030 /* PolicyOR does not use the previous hash value; we must zero and then extend it. */
4031 zero(digest->buffer);
4032
4033 r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, 1 + n_branches, /* extend= */ true);
4034 if (r < 0)
4035 return r;
4036
4037 tpm2_log_debug_digest(digest, "PolicyOR calculated digest");
4038
4039 return 0;
4040 }
4041
4042 /* Extend 'digest' with the PolicyPCR calculated hash. */
4043 int tpm2_calculate_policy_pcr(
4044 const Tpm2PCRValue *pcr_values,
4045 size_t n_pcr_values,
4046 TPM2B_DIGEST *digest) {
4047
4048 TPM2_CC command = TPM2_CC_PolicyPCR;
4049 TSS2_RC rc;
4050 int r;
4051
4052 assert(pcr_values || n_pcr_values == 0);
4053 assert(digest);
4054 assert(digest->size == SHA256_DIGEST_SIZE);
4055
4056 r = dlopen_tpm2(LOG_DEBUG);
4057 if (r < 0)
4058 return r;
4059
4060 TPML_PCR_SELECTION pcr_selection;
4061 _cleanup_free_ TPM2B_DIGEST *values = NULL;
4062 size_t n_values;
4063 r = tpm2_tpml_pcr_selection_from_pcr_values(pcr_values, n_pcr_values, &pcr_selection, &values, &n_values);
4064 if (r < 0)
4065 return log_debug_errno(r, "Could not convert PCR values to TPML_PCR_SELECTION: %m");
4066
4067 TPM2B_DIGEST hash = {};
4068 r = tpm2_digest_many_digests(TPM2_ALG_SHA256, &hash, values, n_values, /* extend= */ false);
4069 if (r < 0)
4070 return r;
4071
4072 _cleanup_free_ uint8_t *buf = NULL;
4073 size_t size = 0, maxsize = sizeof(command) + sizeof(pcr_selection);
4074
4075 buf = malloc(maxsize);
4076 if (!buf)
4077 return log_oom_debug();
4078
4079 rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, maxsize, &size);
4080 if (rc != TSS2_RC_SUCCESS)
4081 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4082 "Failed to marshal PolicyPCR command: %s", sym_Tss2_RC_Decode(rc));
4083
4084 rc = sym_Tss2_MU_TPML_PCR_SELECTION_Marshal(&pcr_selection, buf, maxsize, &size);
4085 if (rc != TSS2_RC_SUCCESS)
4086 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4087 "Failed to marshal PCR selection: %s", sym_Tss2_RC_Decode(rc));
4088
4089 struct iovec data[] = {
4090 IOVEC_MAKE(buf, size),
4091 IOVEC_MAKE(hash.buffer, hash.size),
4092 };
4093 r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, ELEMENTSOF(data), /* extend= */ true);
4094 if (r < 0)
4095 return r;
4096
4097 tpm2_log_debug_digest(digest, "PolicyPCR calculated digest");
4098
4099 return 0;
4100 }
4101
4102 int tpm2_policy_pcr(
4103 Tpm2Context *c,
4104 const Tpm2Handle *session,
4105 const TPML_PCR_SELECTION *pcr_selection,
4106 TPM2B_DIGEST **ret_policy_digest) {
4107
4108 TSS2_RC rc;
4109
4110 assert(c);
4111 assert(session);
4112 assert(pcr_selection);
4113
4114 log_debug("Submitting PCR hash policy.");
4115
4116 rc = sym_Esys_PolicyPCR(
4117 c->esys_context,
4118 session->esys_handle,
4119 ESYS_TR_NONE,
4120 ESYS_TR_NONE,
4121 ESYS_TR_NONE,
4122 NULL,
4123 pcr_selection);
4124 if (rc == TPM2_RC_PCR_CHANGED)
4125 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
4126 "Failed to add PCR policy to TPM: %s", sym_Tss2_RC_Decode(rc));
4127 if (rc != TSS2_RC_SUCCESS)
4128 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4129 "Failed to add PCR policy to TPM: %s", sym_Tss2_RC_Decode(rc));
4130
4131 return tpm2_get_policy_digest(c, session, ret_policy_digest);
4132 }
4133
4134 /* Extend 'digest' with the PolicyAuthorize calculated hash. */
4135 int tpm2_calculate_policy_authorize(
4136 const TPM2B_PUBLIC *public,
4137 const TPM2B_DIGEST *policy_ref,
4138 TPM2B_DIGEST *digest) {
4139
4140 TPM2_CC command = TPM2_CC_PolicyAuthorize;
4141 TSS2_RC rc;
4142 int r;
4143
4144 assert(public);
4145 assert(digest);
4146 assert(digest->size == SHA256_DIGEST_SIZE);
4147
4148 r = dlopen_tpm2(LOG_DEBUG);
4149 if (r < 0)
4150 return r;
4151
4152 uint8_t buf[sizeof(command)];
4153 size_t offset = 0;
4154
4155 rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, sizeof(buf), &offset);
4156 if (rc != TSS2_RC_SUCCESS)
4157 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4158 "Failed to marshal PolicyAuthorize command: %s", sym_Tss2_RC_Decode(rc));
4159
4160 if (offset != sizeof(command))
4161 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4162 "Offset 0x%zx wrong after marshalling PolicyAuthorize command", offset);
4163
4164 TPM2B_NAME name = {};
4165 r = tpm2_calculate_pubkey_name(&public->publicArea, &name);
4166 if (r < 0)
4167 return r;
4168
4169 /* PolicyAuthorize does not use the previous hash value; we must zero and then extend it. */
4170 zero(digest->buffer);
4171
4172 struct iovec data[] = {
4173 IOVEC_MAKE(buf, offset),
4174 IOVEC_MAKE(name.name, name.size),
4175 };
4176 r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, ELEMENTSOF(data), /* extend= */ true);
4177 if (r < 0)
4178 return r;
4179
4180 /* PolicyAuthorize requires hashing twice; this is either an extension or rehashing. */
4181 if (policy_ref)
4182 r = tpm2_digest_many_digests(TPM2_ALG_SHA256, digest, policy_ref, 1, /* extend= */ true);
4183 else
4184 r = tpm2_digest_rehash(TPM2_ALG_SHA256, digest);
4185 if (r < 0)
4186 return r;
4187
4188 tpm2_log_debug_digest(digest, "PolicyAuthorize calculated digest");
4189
4190 return 0;
4191 }
4192
4193 static int tpm2_policy_authorize(
4194 Tpm2Context *c,
4195 const Tpm2Handle *session,
4196 TPML_PCR_SELECTION *pcr_selection,
4197 const TPM2B_PUBLIC *public,
4198 const void *fp,
4199 size_t fp_size,
4200 sd_json_variant *signature_json,
4201 TPM2B_DIGEST **ret_policy_digest) {
4202
4203 TSS2_RC rc;
4204 int r;
4205
4206 assert(c);
4207 assert(session);
4208 assert(pcr_selection);
4209 assert(public);
4210 assert(fp && fp_size > 0);
4211
4212 log_debug("Adding PCR signature policy.");
4213
4214 _cleanup_(tpm2_handle_freep) Tpm2Handle *pubkey_handle = NULL;
4215 r = tpm2_load_external(c, NULL, public, NULL, &pubkey_handle);
4216 if (r < 0)
4217 return r;
4218
4219 /* Acquire the "name" of what we just loaded */
4220 _cleanup_(Esys_Freep) TPM2B_NAME *pubkey_name = NULL;
4221 r = tpm2_get_name(c, pubkey_handle, &pubkey_name);
4222 if (r < 0)
4223 return r;
4224
4225 /* If we have a signature, proceed with verifying the PCR digest */
4226 const TPMT_TK_VERIFIED *check_ticket;
4227 _cleanup_(Esys_Freep) TPMT_TK_VERIFIED *check_ticket_buffer = NULL;
4228 _cleanup_(Esys_Freep) TPM2B_DIGEST *approved_policy = NULL;
4229 if (signature_json) {
4230 r = tpm2_policy_pcr(
4231 c,
4232 session,
4233 pcr_selection,
4234 &approved_policy);
4235 if (r < 0)
4236 return r;
4237
4238 _cleanup_free_ void *signature_raw = NULL;
4239 size_t signature_size;
4240
4241 r = find_signature(
4242 signature_json,
4243 pcr_selection,
4244 fp, fp_size,
4245 approved_policy->buffer,
4246 approved_policy->size,
4247 &signature_raw,
4248 &signature_size);
4249 if (r < 0)
4250 return r;
4251
4252 /* TPM2_VerifySignature() will only verify the RSA part of the RSA+SHA256 signature,
4253 * hence we need to do the SHA256 part ourselves, first */
4254 TPM2B_DIGEST signature_hash = *approved_policy;
4255 r = tpm2_digest_rehash(TPM2_ALG_SHA256, &signature_hash);
4256 if (r < 0)
4257 return r;
4258
4259 r = TPM2B_PUBLIC_KEY_RSA_CHECK_SIZE(signature_size);
4260 if (r < 0)
4261 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Signature larger than buffer.");
4262
4263 TPMT_SIGNATURE policy_signature = {
4264 .sigAlg = TPM2_ALG_RSASSA,
4265 .signature.rsassa = {
4266 .hash = TPM2_ALG_SHA256,
4267 .sig = TPM2B_PUBLIC_KEY_RSA_MAKE(signature_raw, signature_size),
4268 },
4269 };
4270
4271 rc = sym_Esys_VerifySignature(
4272 c->esys_context,
4273 pubkey_handle->esys_handle,
4274 ESYS_TR_NONE,
4275 ESYS_TR_NONE,
4276 ESYS_TR_NONE,
4277 &signature_hash,
4278 &policy_signature,
4279 &check_ticket_buffer);
4280 if (rc != TSS2_RC_SUCCESS)
4281 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4282 "Failed to validate signature in TPM: %s", sym_Tss2_RC_Decode(rc));
4283
4284 check_ticket = check_ticket_buffer;
4285 } else {
4286 /* When enrolling, we pass a NULL ticket */
4287 static const TPMT_TK_VERIFIED check_ticket_null = {
4288 .tag = TPM2_ST_VERIFIED,
4289 .hierarchy = TPM2_RH_OWNER,
4290 };
4291
4292 check_ticket = &check_ticket_null;
4293 }
4294
4295 rc = sym_Esys_PolicyAuthorize(
4296 c->esys_context,
4297 session->esys_handle,
4298 ESYS_TR_NONE,
4299 ESYS_TR_NONE,
4300 ESYS_TR_NONE,
4301 approved_policy,
4302 /* policyRef= */ &(const TPM2B_NONCE) {},
4303 pubkey_name,
4304 check_ticket);
4305 if (rc != TSS2_RC_SUCCESS)
4306 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4307 "Failed to push Authorize policy into TPM: %s", sym_Tss2_RC_Decode(rc));
4308
4309 return tpm2_get_policy_digest(c, session, ret_policy_digest);
4310 }
4311
4312 /* Extend 'digest' with the calculated policy hash. */
4313 int tpm2_calculate_sealing_policy(
4314 const Tpm2PCRValue *pcr_values,
4315 size_t n_pcr_values,
4316 const TPM2B_PUBLIC *public,
4317 bool use_pin,
4318 const Tpm2PCRLockPolicy *pcrlock_policy,
4319 TPM2B_DIGEST *digest) {
4320
4321 int r;
4322
4323 assert(pcr_values || n_pcr_values == 0);
4324 assert(digest);
4325
4326 /* The combination of signed PCR policies and pcrlock is not supported (because we cannot combine
4327 * PolicyAuthorize and PolicyAuthorizeNV in one policy). Callers need to use "sharding" of the
4328 * symmetric FDE unlock key to make policies like that work. */
4329 if (public && pcrlock_policy)
4330 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Policies that combined signed PCR and pcrlock are not supported.");
4331
4332 if (public) {
4333 r = tpm2_calculate_policy_authorize(public, NULL, digest);
4334 if (r < 0)
4335 return r;
4336 }
4337
4338 if (pcrlock_policy) {
4339 TPM2B_NV_PUBLIC nv_public;
4340
4341 r = tpm2_unmarshal_nv_public(
4342 pcrlock_policy->nv_public.iov_base,
4343 pcrlock_policy->nv_public.iov_len,
4344 &nv_public);
4345 if (r < 0)
4346 return r;
4347
4348 r = tpm2_calculate_policy_authorize_nv(&nv_public, digest);
4349 if (r < 0)
4350 return r;
4351 }
4352
4353 if (n_pcr_values > 0) {
4354 r = tpm2_calculate_policy_pcr(pcr_values, n_pcr_values, digest);
4355 if (r < 0)
4356 return r;
4357 }
4358
4359 if (use_pin) {
4360 r = tpm2_calculate_policy_auth_value(digest);
4361 if (r < 0)
4362 return r;
4363 }
4364
4365 return 0;
4366 }
4367
4368 static int tpm2_build_sealing_policy(
4369 Tpm2Context *c,
4370 const Tpm2Handle *session,
4371 uint32_t hash_pcr_mask,
4372 uint16_t pcr_bank,
4373 const TPM2B_PUBLIC *public,
4374 const void *fp,
4375 size_t fp_size,
4376 uint32_t pubkey_pcr_mask,
4377 sd_json_variant *signature_json,
4378 bool use_pin,
4379 const Tpm2PCRLockPolicy *pcrlock_policy,
4380 TPM2B_DIGEST **ret_policy_digest) {
4381
4382 int r;
4383
4384 assert(c);
4385 assert(session);
4386 assert(pubkey_pcr_mask == 0 || public);
4387
4388 log_debug("Building sealing policy.");
4389
4390 if ((hash_pcr_mask | pubkey_pcr_mask) != 0) {
4391 r = tpm2_pcr_mask_good(c, pcr_bank, hash_pcr_mask|pubkey_pcr_mask);
4392 if (r < 0)
4393 return r;
4394 if (r == 0)
4395 log_debug("Selected TPM2 PCRs are not initialized on this system.");
4396 }
4397
4398 if (pubkey_pcr_mask != 0 && pcrlock_policy)
4399 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Policies with both signed PCR and pcrlock are currently not supported.");
4400
4401 if (pubkey_pcr_mask != 0) {
4402 TPML_PCR_SELECTION pcr_selection;
4403 tpm2_tpml_pcr_selection_from_mask(pubkey_pcr_mask, (TPMI_ALG_HASH)pcr_bank, &pcr_selection);
4404 r = tpm2_policy_authorize(c, session, &pcr_selection, public, fp, fp_size, signature_json, NULL);
4405 if (r < 0)
4406 return r;
4407 }
4408
4409 if (pcrlock_policy) {
4410 _cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
4411
4412 r = tpm2_policy_super_pcr(
4413 c,
4414 session,
4415 &pcrlock_policy->prediction,
4416 pcrlock_policy->algorithm);
4417 if (r < 0)
4418 return r;
4419
4420 r = tpm2_deserialize(
4421 c,
4422 &pcrlock_policy->nv_handle,
4423 &nv_handle);
4424 if (r < 0)
4425 return r;
4426
4427 r = tpm2_policy_authorize_nv(
4428 c,
4429 session,
4430 nv_handle,
4431 NULL);
4432 if (r < 0)
4433 return r;
4434 }
4435
4436 if (hash_pcr_mask != 0) {
4437 TPML_PCR_SELECTION pcr_selection;
4438 tpm2_tpml_pcr_selection_from_mask(hash_pcr_mask, (TPMI_ALG_HASH)pcr_bank, &pcr_selection);
4439 r = tpm2_policy_pcr(c, session, &pcr_selection, NULL);
4440 if (r < 0)
4441 return r;
4442 }
4443
4444 if (use_pin) {
4445 r = tpm2_policy_auth_value(c, session, NULL);
4446 if (r < 0)
4447 return r;
4448 }
4449
4450 r = tpm2_get_policy_digest(c, session, ret_policy_digest);
4451 if (r < 0)
4452 return r;
4453
4454 return 0;
4455 }
4456
4457 #if HAVE_OPENSSL
4458 static const struct {
4459 TPM2_ECC_CURVE tpm2_ecc_curve_id;
4460 int openssl_ecc_curve_id;
4461 } tpm2_openssl_ecc_curve_table[] = {
4462 { TPM2_ECC_NIST_P192, NID_X9_62_prime192v1, },
4463 { TPM2_ECC_NIST_P224, NID_secp224r1, },
4464 { TPM2_ECC_NIST_P256, NID_X9_62_prime256v1, },
4465 { TPM2_ECC_NIST_P384, NID_secp384r1, },
4466 { TPM2_ECC_NIST_P521, NID_secp521r1, },
4467 { TPM2_ECC_SM2_P256, NID_sm2, },
4468 };
4469
4470 static int tpm2_ecc_curve_from_openssl_curve_id(int openssl_ecc_curve_id, TPM2_ECC_CURVE *ret) {
4471 assert(ret);
4472
4473 FOREACH_ELEMENT(t, tpm2_openssl_ecc_curve_table)
4474 if (t->openssl_ecc_curve_id == openssl_ecc_curve_id) {
4475 *ret = t->tpm2_ecc_curve_id;
4476 return 0;
4477 }
4478
4479 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
4480 "OpenSSL ECC curve id %d not supported.", openssl_ecc_curve_id);
4481 }
4482
4483 static int tpm2_ecc_curve_to_openssl_curve_id(TPM2_ECC_CURVE tpm2_ecc_curve_id, int *ret) {
4484 assert(ret);
4485
4486 FOREACH_ELEMENT(t, tpm2_openssl_ecc_curve_table)
4487 if (t->tpm2_ecc_curve_id == tpm2_ecc_curve_id) {
4488 *ret = t->openssl_ecc_curve_id;
4489 return 0;
4490 }
4491
4492 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
4493 "TPM2 ECC curve %u not supported.", tpm2_ecc_curve_id);
4494 }
4495
4496 #define TPM2_RSA_DEFAULT_EXPONENT UINT32_C(0x10001)
4497
4498 int tpm2_tpm2b_public_to_openssl_pkey(const TPM2B_PUBLIC *public, EVP_PKEY **ret) {
4499 int r;
4500
4501 assert(public);
4502 assert(ret);
4503
4504 const TPMT_PUBLIC *p = &public->publicArea;
4505 switch (p->type) {
4506 case TPM2_ALG_ECC: {
4507 int curve_id;
4508 r = tpm2_ecc_curve_to_openssl_curve_id(p->parameters.eccDetail.curveID, &curve_id);
4509 if (r < 0)
4510 return r;
4511
4512 const TPMS_ECC_POINT *point = &p->unique.ecc;
4513 return ecc_pkey_from_curve_x_y(
4514 curve_id,
4515 point->x.buffer,
4516 point->x.size,
4517 point->y.buffer,
4518 point->y.size,
4519 ret);
4520 }
4521 case TPM2_ALG_RSA: {
4522 /* TPM specification Part 2 ("Structures") section for TPMS_RSA_PARAMS states "An exponent of
4523 * zero indicates that the exponent is the default of 2^16 + 1". */
4524 uint32_t exponent = htobe32(p->parameters.rsaDetail.exponent ?: TPM2_RSA_DEFAULT_EXPONENT);
4525 return rsa_pkey_from_n_e(
4526 p->unique.rsa.buffer,
4527 p->unique.rsa.size,
4528 &exponent,
4529 sizeof(exponent),
4530 ret);
4531 }
4532 default:
4533 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
4534 "TPM2 asymmetric algorithm 0x%" PRIx16 " not supported.", p->type);
4535 }
4536 }
4537
4538 /* Be careful before changing anything in this function, as the TPM key "name" is calculated using the entire
4539 * TPMT_PUBLIC (after marshalling), and that "name" is used (for example) to calculate the policy hash for
4540 * the Authorize policy. So we must ensure this conversion of a PEM to TPM2B_PUBLIC does not change the
4541 * "name", because it would break unsealing of previously-sealed objects that used (for example)
4542 * tpm2_calculate_policy_authorize(). See bug #30546. */
4543 int tpm2_tpm2b_public_from_openssl_pkey(const EVP_PKEY *pkey, TPM2B_PUBLIC *ret) {
4544 int r;
4545
4546 assert(pkey);
4547 assert(ret);
4548
4549 r = dlopen_libcrypto(LOG_DEBUG);
4550 if (r < 0)
4551 return r;
4552
4553 TPMT_PUBLIC public = {
4554 .nameAlg = TPM2_ALG_SHA256,
4555 .objectAttributes = TPMA_OBJECT_DECRYPT | TPMA_OBJECT_SIGN_ENCRYPT | TPMA_OBJECT_USERWITHAUTH,
4556 .parameters.asymDetail = {
4557 .symmetric.algorithm = TPM2_ALG_NULL,
4558 .scheme.scheme = TPM2_ALG_NULL,
4559 },
4560 };
4561
4562 int key_id = sym_EVP_PKEY_get_id(pkey);
4563 switch (key_id) {
4564 case EVP_PKEY_EC: {
4565 public.type = TPM2_ALG_ECC;
4566
4567 int curve_id;
4568 _cleanup_free_ void *x = NULL, *y = NULL;
4569 size_t x_size, y_size;
4570 r = ecc_pkey_to_curve_x_y(pkey, &curve_id, &x, &x_size, &y, &y_size);
4571 if (r < 0)
4572 return log_debug_errno(r, "Could not get ECC key curve/x/y: %m");
4573
4574 TPM2_ECC_CURVE curve;
4575 r = tpm2_ecc_curve_from_openssl_curve_id(curve_id, &curve);
4576 if (r < 0)
4577 return r;
4578
4579 public.parameters.eccDetail.curveID = curve;
4580
4581 public.parameters.eccDetail.kdf.scheme = TPM2_ALG_NULL;
4582
4583 r = TPM2B_ECC_PARAMETER_CHECK_SIZE(x_size);
4584 if (r < 0)
4585 return log_debug_errno(r, "ECC key x size %zu too large.", x_size);
4586
4587 public.unique.ecc.x = TPM2B_ECC_PARAMETER_MAKE(x, x_size);
4588
4589 r = TPM2B_ECC_PARAMETER_CHECK_SIZE(y_size);
4590 if (r < 0)
4591 return log_debug_errno(r, "ECC key y size %zu too large.", y_size);
4592
4593 public.unique.ecc.y = TPM2B_ECC_PARAMETER_MAKE(y, y_size);
4594
4595 break;
4596 }
4597 case EVP_PKEY_RSA: {
4598 public.type = TPM2_ALG_RSA;
4599
4600 _cleanup_free_ void *n = NULL, *e = NULL;
4601 size_t n_size, e_size;
4602 r = rsa_pkey_to_n_e(pkey, &n, &n_size, &e, &e_size);
4603 if (r < 0)
4604 return log_debug_errno(r, "Could not get RSA key n/e: %m");
4605
4606 r = TPM2B_PUBLIC_KEY_RSA_CHECK_SIZE(n_size);
4607 if (r < 0)
4608 return log_debug_errno(r, "RSA key n size %zu too large.", n_size);
4609
4610 public.unique.rsa = TPM2B_PUBLIC_KEY_RSA_MAKE(n, n_size);
4611 public.parameters.rsaDetail.keyBits = n_size * 8;
4612
4613 if (sizeof(uint32_t) < e_size)
4614 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
4615 "RSA key e size %zu too large.", e_size);
4616
4617 uint32_t exponent = 0;
4618 memcpy(&exponent, e, e_size);
4619 exponent = be32toh(exponent) >> (32 - e_size * 8);
4620
4621 /* TPM specification Part 2 ("Structures") section for TPMS_RSA_PARAMS states "An exponent of
4622 * zero indicates that the exponent is the default of 2^16 + 1". However, we have no reason
4623 * to special case it in our PEM->TPM2B_PUBLIC conversion, and doing so could break backwards
4624 * compatibility, so even if it is the "default" value of 0x10001, we do not set it to 0. */
4625 public.parameters.rsaDetail.exponent = exponent;
4626
4627 break;
4628 }
4629 default:
4630 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
4631 "EVP_PKEY type %d not supported.", key_id);
4632 }
4633
4634 *ret = (TPM2B_PUBLIC) {
4635 .size = sizeof(public),
4636 .publicArea = public,
4637 };
4638
4639 return 0;
4640 }
4641 #endif
4642
4643 int tpm2_tpm2b_public_to_fingerprint(
4644 const TPM2B_PUBLIC *public,
4645 void **ret_fingerprint,
4646 size_t *ret_fingerprint_size) {
4647
4648 #if HAVE_OPENSSL
4649 int r;
4650
4651 assert(public);
4652 assert(ret_fingerprint);
4653 assert(ret_fingerprint_size);
4654
4655 _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
4656 r = tpm2_tpm2b_public_to_openssl_pkey(public, &pkey);
4657 if (r < 0)
4658 return r;
4659
4660 r = dlopen_libcrypto(LOG_DEBUG);
4661 if (r < 0)
4662 return r;
4663
4664 /* Hardcode fingerprint to SHA256 */
4665 return pubkey_fingerprint(pkey, sym_EVP_sha256(), ret_fingerprint, ret_fingerprint_size);
4666 #else
4667 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
4668 #endif
4669 }
4670
4671 int tpm2_tpm2b_public_from_pem(const void *pem, size_t pem_size, TPM2B_PUBLIC *ret) {
4672 #if HAVE_OPENSSL
4673 int r;
4674
4675 assert(pem);
4676 assert(ret);
4677
4678 _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
4679 r = openssl_pubkey_from_pem(pem, pem_size, &pkey);
4680 if (r < 0)
4681 return r;
4682
4683 return tpm2_tpm2b_public_from_openssl_pkey(pkey, ret);
4684 #else
4685 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
4686 #endif
4687 }
4688
4689 /* Marshal the public, private, and seed objects into a single nonstandard 'blob'. The public and private
4690 * objects are required, while the seed is optional. This is not a (publicly) standard format, this is
4691 * specific to how we currently store the sealed object. This 'blob' can be unmarshalled by
4692 * tpm2_unmarshal_blob(). */
4693 int tpm2_marshal_blob(
4694 const TPM2B_PUBLIC *public,
4695 const TPM2B_PRIVATE *private,
4696 const TPM2B_ENCRYPTED_SECRET *seed,
4697 void **ret_blob,
4698 size_t *ret_blob_size) {
4699
4700 TSS2_RC rc;
4701
4702 assert(public);
4703 assert(private);
4704 assert(ret_blob);
4705 assert(ret_blob_size);
4706
4707 size_t max_size = sizeof(*private) + sizeof(*public);
4708 if (seed)
4709 max_size += sizeof(*seed);
4710
4711 _cleanup_free_ void *blob = malloc(max_size);
4712 if (!blob)
4713 return log_oom_debug();
4714
4715 size_t blob_size = 0;
4716 rc = sym_Tss2_MU_TPM2B_PRIVATE_Marshal(private, blob, max_size, &blob_size);
4717 if (rc != TSS2_RC_SUCCESS)
4718 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4719 "Failed to marshal private key: %s", sym_Tss2_RC_Decode(rc));
4720
4721 rc = sym_Tss2_MU_TPM2B_PUBLIC_Marshal(public, blob, max_size, &blob_size);
4722 if (rc != TSS2_RC_SUCCESS)
4723 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4724 "Failed to marshal public key: %s", sym_Tss2_RC_Decode(rc));
4725
4726 if (seed) {
4727 rc = sym_Tss2_MU_TPM2B_ENCRYPTED_SECRET_Marshal(seed, blob, max_size, &blob_size);
4728 if (rc != TSS2_RC_SUCCESS)
4729 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4730 "Failed to marshal encrypted seed: %s", sym_Tss2_RC_Decode(rc));
4731 }
4732
4733 *ret_blob = TAKE_PTR(blob);
4734 *ret_blob_size = blob_size;
4735
4736 return 0;
4737 }
4738
4739 /* Unmarshal the 'blob' into public, private, and seed objects. The public and private objects are required
4740 * in the 'blob', while the seed is optional. This is not a (publicly) standard format, this is specific to
4741 * how we currently store the sealed object. This expects the 'blob' to have been created by
4742 * tpm2_marshal_blob(). */
4743 int tpm2_unmarshal_blob(
4744 const void *blob,
4745 size_t blob_size,
4746 TPM2B_PUBLIC *ret_public,
4747 TPM2B_PRIVATE *ret_private,
4748 TPM2B_ENCRYPTED_SECRET *ret_seed) {
4749
4750 TSS2_RC rc;
4751
4752 assert(blob);
4753 assert(ret_public);
4754 assert(ret_private);
4755 assert(ret_seed);
4756
4757 TPM2B_PRIVATE private = {};
4758 size_t offset = 0;
4759 rc = sym_Tss2_MU_TPM2B_PRIVATE_Unmarshal(blob, blob_size, &offset, &private);
4760 if (rc != TSS2_RC_SUCCESS)
4761 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4762 "Failed to unmarshal private key: %s", sym_Tss2_RC_Decode(rc));
4763
4764 TPM2B_PUBLIC public = {};
4765 rc = sym_Tss2_MU_TPM2B_PUBLIC_Unmarshal(blob, blob_size, &offset, &public);
4766 if (rc != TSS2_RC_SUCCESS)
4767 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4768 "Failed to unmarshal public key: %s", sym_Tss2_RC_Decode(rc));
4769
4770 TPM2B_ENCRYPTED_SECRET seed = {};
4771 if (blob_size > offset) {
4772 rc = sym_Tss2_MU_TPM2B_ENCRYPTED_SECRET_Unmarshal(blob, blob_size, &offset, &seed);
4773 if (rc != TSS2_RC_SUCCESS)
4774 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4775 "Failed to unmarshal encrypted seed: %s", sym_Tss2_RC_Decode(rc));
4776 }
4777
4778 *ret_public = public;
4779 *ret_private = private;
4780 *ret_seed = seed;
4781
4782 return 0;
4783 }
4784
4785 /* Calculate a serialized handle. Once the upstream tpm2-tss library provides an api to do this, we can
4786 * remove this function. The addition of this functionality in tpm2-tss may be tracked here:
4787 * https://github.com/tpm2-software/tpm2-tss/issues/2575 */
4788 int tpm2_calculate_serialize(
4789 TPM2_HANDLE handle,
4790 const TPM2B_NAME *name,
4791 const TPM2B_PUBLIC *public,
4792 void **ret_serialized,
4793 size_t *ret_serialized_size) {
4794
4795 TSS2_RC rc;
4796
4797 assert(name);
4798 assert(public);
4799 assert(ret_serialized);
4800 assert(ret_serialized_size);
4801
4802 size_t max_size = sizeof(TPM2_HANDLE) + sizeof(TPM2B_NAME) + sizeof(uint32_t) + sizeof(TPM2B_PUBLIC);
4803 _cleanup_free_ void *serialized = malloc(max_size);
4804 if (!serialized)
4805 return log_oom_debug();
4806
4807 size_t serialized_size = 0;
4808 rc = sym_Tss2_MU_TPM2_HANDLE_Marshal(handle, serialized, max_size, &serialized_size);
4809 if (rc != TSS2_RC_SUCCESS)
4810 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4811 "Failed to marshal tpm handle: %s", sym_Tss2_RC_Decode(rc));
4812
4813 rc = sym_Tss2_MU_TPM2B_NAME_Marshal(name, serialized, max_size, &serialized_size);
4814 if (rc != TSS2_RC_SUCCESS)
4815 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4816 "Failed to marshal name: %s", sym_Tss2_RC_Decode(rc));
4817
4818 /* This is defined (non-publicly) in the tpm2-tss source as IESYSC_KEY_RSRC, to a value of "1". */
4819 rc = sym_Tss2_MU_UINT32_Marshal(UINT32_C(1), serialized, max_size, &serialized_size);
4820 if (rc != TSS2_RC_SUCCESS)
4821 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4822 "Failed to marshal esys resource id: %s", sym_Tss2_RC_Decode(rc));
4823
4824 rc = sym_Tss2_MU_TPM2B_PUBLIC_Marshal(public, serialized, max_size, &serialized_size);
4825 if (rc != TSS2_RC_SUCCESS)
4826 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4827 "Failed to marshal public: %s", sym_Tss2_RC_Decode(rc));
4828
4829 *ret_serialized = TAKE_PTR(serialized);
4830 *ret_serialized_size = serialized_size;
4831
4832 return 0;
4833 }
4834
4835 /* Serialize a handle. This produces a binary object that can be later deserialized (by the same TPM), even
4836 * across restarts of the TPM or reboots (assuming the handle is persistent). */
4837 int tpm2_serialize(
4838 Tpm2Context *c,
4839 const Tpm2Handle *handle,
4840 struct iovec *ret) {
4841
4842 TSS2_RC rc;
4843
4844 assert(c);
4845 assert(handle);
4846 assert(ret);
4847
4848 _cleanup_(Esys_Freep) unsigned char *serialized = NULL;
4849 size_t size = 0;
4850 rc = sym_Esys_TR_Serialize(c->esys_context, handle->esys_handle, &serialized, &size);
4851 if (rc != TSS2_RC_SUCCESS)
4852 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4853 "Failed to serialize: %s", sym_Tss2_RC_Decode(rc));
4854
4855 /* Make a copy since we don't want the caller to understand that ESYS allocated the pointer.
4856 * It would make tracking what deallocator to use for the result in which context a PITA. */
4857 struct iovec v;
4858 v.iov_base = memdup(serialized, size);
4859 if (!v.iov_base)
4860 return log_oom_debug();
4861 v.iov_len = size;
4862
4863 *ret = v;
4864 return 0;
4865 }
4866
4867 int tpm2_deserialize(
4868 Tpm2Context *c,
4869 const struct iovec *serialized,
4870 Tpm2Handle **ret_handle) {
4871
4872 TSS2_RC rc;
4873 int r;
4874
4875 assert(c);
4876 assert(ret_handle);
4877
4878 if (!iovec_is_set(serialized)) {
4879 *ret_handle = NULL;
4880 return 0;
4881 }
4882
4883 _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
4884 r = tpm2_handle_new(c, &handle);
4885 if (r < 0)
4886 return r;
4887
4888 /* Since this is an existing handle in the TPM we should not implicitly flush it. */
4889 handle->flush = false;
4890
4891 rc = sym_Esys_TR_Deserialize(c->esys_context, serialized->iov_base, serialized->iov_len, &handle->esys_handle);
4892 if (rc != TSS2_RC_SUCCESS)
4893 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
4894 "Failed to deserialize: %s", sym_Tss2_RC_Decode(rc));
4895
4896 *ret_handle = TAKE_PTR(handle);
4897 return 1;
4898 }
4899
4900 #if HAVE_OPENSSL
4901
4902 /* KDFa() as defined by the TPM spec. */
4903 static int tpm2_kdfa(
4904 TPMI_ALG_HASH hash_alg,
4905 const void *key,
4906 size_t key_len,
4907 const char *label,
4908 const void *context,
4909 size_t context_len,
4910 size_t bits,
4911 void **ret_key,
4912 size_t *ret_key_len) {
4913
4914 int r;
4915
4916 assert(key);
4917 assert(label);
4918 assert(context || context_len == 0);
4919 assert(bits > 0);
4920 assert(bits <= SIZE_MAX - 7);
4921 assert(ret_key);
4922 assert(ret_key_len);
4923
4924 log_debug("Calculating KDFa().");
4925
4926 size_t len = DIV_ROUND_UP(bits, 8);
4927
4928 const char *hash_alg_name = tpm2_hash_alg_to_string(hash_alg);
4929 if (!hash_alg_name)
4930 return -EOPNOTSUPP;
4931
4932 _cleanup_(erase_and_freep) void *buf = NULL;
4933 r = kdf_kb_hmac_derive(
4934 "COUNTER",
4935 hash_alg_name,
4936 key,
4937 key_len,
4938 label,
4939 strlen(label),
4940 context,
4941 context_len,
4942 /* seed= */ NULL,
4943 /* seed_size= */ 0,
4944 len,
4945 &buf);
4946 if (r < 0)
4947 return r;
4948
4949 /* If the number of bits results in a partial byte, the TPM spec requires we zero the unrequested
4950 * bits in the MSB (i.e. at index 0). From the spec Part 1 ("Architecture") section on Key
4951 * Derivation Function, specifically KDFa():
4952 *
4953 * "The implied return from this function is a sequence of octets with a length equal to (bits + 7) /
4954 * 8. If bits is not an even multiple of 8, then the returned value occupies the least significant
4955 * bits of the returned octet array, and the additional, high-order bits in the 0th octet are
4956 * CLEAR. The unused bits of the most significant octet (MSO) are masked off and not shifted." */
4957 size_t partial = bits % 8;
4958 if (partial > 0)
4959 ((uint8_t*) buf)[0] &= 0xffu >> (8 - partial);
4960
4961 *ret_key = TAKE_PTR(buf);
4962 *ret_key_len = len;
4963
4964 return 0;
4965 }
4966
4967 /* KDFe() as defined by the TPM spec. */
4968 static int tpm2_kdfe(
4969 TPMI_ALG_HASH hash_alg,
4970 const void *shared_secret,
4971 size_t shared_secret_len,
4972 const char *label,
4973 const void *context_u,
4974 size_t context_u_size,
4975 const void *context_v,
4976 size_t context_v_size,
4977 size_t bits,
4978 void **ret_key,
4979 size_t *ret_key_len) {
4980
4981 int r;
4982
4983 assert(shared_secret);
4984 assert(label);
4985 assert(context_u);
4986 assert(context_v);
4987 assert(bits > 0);
4988 assert(bits <= SIZE_MAX - 7);
4989 assert(ret_key);
4990 assert(ret_key_len);
4991
4992 log_debug("Calculating KDFe().");
4993
4994 size_t len = DIV_ROUND_UP(bits, 8);
4995
4996 const char *hash_alg_name = tpm2_hash_alg_to_string(hash_alg);
4997 if (!hash_alg_name)
4998 return -EOPNOTSUPP;
4999
5000 size_t info_len = strlen(label) + 1 + context_u_size + context_v_size;
5001 _cleanup_free_ void *info = malloc(info_len);
5002 if (!info)
5003 return log_oom_debug();
5004
5005 _unused_ void *end = mempcpy(mempcpy(stpcpy(info, label) + 1, context_u, context_u_size),
5006 context_v, context_v_size);
5007 /* assert we copied exactly the right amount that we allocated */
5008 assert(end > info && (uintptr_t) end - (uintptr_t) info == info_len);
5009
5010 _cleanup_(erase_and_freep) void *buf = NULL;
5011 r = kdf_ss_derive(
5012 hash_alg_name,
5013 shared_secret,
5014 shared_secret_len,
5015 /* salt= */ NULL,
5016 /* salt_size= */ 0,
5017 info,
5018 info_len,
5019 len,
5020 &buf);
5021 if (r < 0)
5022 return r;
5023
5024 *ret_key = TAKE_PTR(buf);
5025 *ret_key_len = len;
5026
5027 return 0;
5028 }
5029
5030 static int tpm2_calculate_seal_public(
5031 const TPM2B_PUBLIC *parent,
5032 const TPMA_OBJECT *attributes,
5033 const TPM2B_DIGEST *policy,
5034 const TPM2B_DIGEST *seed,
5035 const void *secret,
5036 size_t secret_size,
5037 TPM2B_PUBLIC *ret) {
5038
5039 int r;
5040
5041 assert(parent);
5042 POINTER_MAY_BE_NULL(attributes);
5043 POINTER_MAY_BE_NULL(policy);
5044 assert(seed);
5045 assert(secret);
5046 assert(ret);
5047
5048 log_debug("Calculating public part of sealed object.");
5049
5050 struct iovec data[] = {
5051 IOVEC_MAKE((void*) seed->buffer, seed->size),
5052 IOVEC_MAKE((void*) secret, secret_size),
5053 };
5054 TPM2B_DIGEST unique;
5055 r = tpm2_digest_many(
5056 parent->publicArea.nameAlg,
5057 &unique,
5058 data,
5059 ELEMENTSOF(data),
5060 /* extend= */ false);
5061 if (r < 0)
5062 return r;
5063
5064 *ret = (TPM2B_PUBLIC) {
5065 .size = sizeof(TPMT_PUBLIC),
5066 .publicArea = {
5067 .type = TPM2_ALG_KEYEDHASH,
5068 .nameAlg = parent->publicArea.nameAlg,
5069 .objectAttributes = attributes ? *attributes : 0,
5070 .authPolicy = policy ? *policy : TPM2B_DIGEST_MAKE(NULL, unique.size),
5071 .parameters.keyedHashDetail.scheme.scheme = TPM2_ALG_NULL,
5072 .unique.keyedHash = unique,
5073 },
5074 };
5075
5076 return 0;
5077 }
5078
5079 static int tpm2_calculate_seal_private(
5080 const TPM2B_PUBLIC *parent,
5081 const TPM2B_NAME *name,
5082 const char *pin,
5083 const TPM2B_DIGEST *seed,
5084 const void *secret,
5085 size_t secret_size,
5086 TPM2B_PRIVATE *ret) {
5087
5088 TSS2_RC rc;
5089 int r;
5090
5091 assert(parent);
5092 assert(name);
5093 assert(seed);
5094 assert(secret);
5095 assert(ret);
5096
5097 log_debug("Calculating private part of sealed object.");
5098
5099 _cleanup_(erase_and_freep) void *storage_key = NULL;
5100 size_t storage_key_size;
5101 r = tpm2_kdfa(parent->publicArea.nameAlg,
5102 seed->buffer,
5103 seed->size,
5104 "STORAGE",
5105 name->name,
5106 name->size,
5107 (size_t) parent->publicArea.parameters.asymDetail.symmetric.keyBits.sym,
5108 &storage_key,
5109 &storage_key_size);
5110 if (r < 0)
5111 return log_debug_errno(r, "Could not calculate storage key KDFa: %m");
5112
5113 r = tpm2_hash_alg_to_size(parent->publicArea.nameAlg);
5114 if (r < 0)
5115 return -EOPNOTSUPP;
5116
5117 size_t bits = (size_t) r * 8;
5118
5119 _cleanup_(erase_and_freep) void *integrity_key = NULL;
5120 size_t integrity_key_size;
5121 r = tpm2_kdfa(parent->publicArea.nameAlg,
5122 seed->buffer,
5123 seed->size,
5124 "INTEGRITY",
5125 /* context= */ NULL,
5126 /* context_len= */ 0,
5127 bits,
5128 &integrity_key,
5129 &integrity_key_size);
5130 if (r < 0)
5131 return log_debug_errno(r, "Could not calculate integrity key KDFa: %m");
5132
5133 TPM2B_AUTH auth = {};
5134 CLEANUP_ERASE(auth);
5135 if (pin) {
5136 r = tpm2_auth_value_from_pin(parent->publicArea.nameAlg, pin, &auth);
5137 if (r < 0)
5138 return r;
5139 }
5140
5141 TPM2B_SENSITIVE sensitive = {
5142 .size = sizeof(TPMT_SENSITIVE),
5143 .sensitiveArea = {
5144 .sensitiveType = TPM2_ALG_KEYEDHASH,
5145 .authValue = auth,
5146 .seedValue = *seed,
5147 .sensitive.bits = TPM2B_SENSITIVE_DATA_MAKE(secret, secret_size),
5148 },
5149 };
5150 CLEANUP_ERASE(sensitive);
5151
5152 _cleanup_(erase_and_freep) void *marshalled_sensitive = malloc(sizeof(sensitive));
5153 if (!marshalled_sensitive)
5154 return log_oom_debug();
5155
5156 size_t marshalled_sensitive_size = 0;
5157 rc = sym_Tss2_MU_TPM2B_SENSITIVE_Marshal(
5158 &sensitive,
5159 marshalled_sensitive,
5160 sizeof(sensitive),
5161 &marshalled_sensitive_size);
5162 if (rc != TSS2_RC_SUCCESS)
5163 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
5164 "Failed to marshal sensitive: %s", sym_Tss2_RC_Decode(rc));
5165
5166 const char *sym_alg = tpm2_sym_alg_to_string(parent->publicArea.parameters.asymDetail.symmetric.algorithm);
5167 if (!sym_alg)
5168 return -EOPNOTSUPP;
5169
5170 const char *sym_mode = tpm2_sym_mode_to_string(parent->publicArea.parameters.asymDetail.symmetric.mode.sym);
5171 if (!sym_mode)
5172 return -EOPNOTSUPP;
5173
5174 _cleanup_free_ void *encrypted_sensitive = NULL;
5175 size_t encrypted_sensitive_size;
5176 r = openssl_cipher(
5177 sym_alg,
5178 parent->publicArea.parameters.asymDetail.symmetric.keyBits.sym,
5179 sym_mode,
5180 storage_key, storage_key_size,
5181 /* iv= */ NULL, /* iv_size= */ 0,
5182 marshalled_sensitive, marshalled_sensitive_size,
5183 &encrypted_sensitive, &encrypted_sensitive_size);
5184 if (r < 0)
5185 return r;
5186
5187 const char *hash_alg_name = tpm2_hash_alg_to_string(parent->publicArea.nameAlg);
5188 if (!hash_alg_name)
5189 return -EOPNOTSUPP;
5190
5191 _cleanup_free_ void *hmac_buffer = NULL;
5192 size_t hmac_size = 0;
5193 struct iovec hmac_data[] = {
5194 IOVEC_MAKE((void*) encrypted_sensitive, encrypted_sensitive_size),
5195 IOVEC_MAKE((void*) name->name, name->size),
5196 };
5197 r = openssl_hmac_many(
5198 hash_alg_name,
5199 integrity_key,
5200 integrity_key_size,
5201 hmac_data,
5202 ELEMENTSOF(hmac_data),
5203 &hmac_buffer,
5204 &hmac_size);
5205 if (r < 0)
5206 return r;
5207
5208 TPM2B_DIGEST outer_hmac = TPM2B_DIGEST_MAKE(hmac_buffer, hmac_size);
5209
5210 TPM2B_PRIVATE private = {};
5211 size_t private_size = 0;
5212 rc = sym_Tss2_MU_TPM2B_DIGEST_Marshal(
5213 &outer_hmac,
5214 private.buffer,
5215 sizeof(private.buffer),
5216 &private_size);
5217 if (rc != TSS2_RC_SUCCESS)
5218 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
5219 "Failed to marshal digest: %s", sym_Tss2_RC_Decode(rc));
5220 private.size = private_size;
5221
5222 assert(sizeof(private.buffer) - private.size >= encrypted_sensitive_size);
5223 memcpy_safe(&private.buffer[private.size], encrypted_sensitive, encrypted_sensitive_size);
5224 private.size += encrypted_sensitive_size;
5225
5226 *ret = private;
5227
5228 return 0;
5229 }
5230
5231 static int tpm2_calculate_seal_rsa_seed(
5232 const TPM2B_PUBLIC *parent,
5233 void **ret_seed,
5234 size_t *ret_seed_size,
5235 void **ret_encrypted_seed,
5236 size_t *ret_encrypted_seed_size) {
5237
5238 int r;
5239
5240 assert(parent);
5241 assert(ret_seed);
5242 assert(ret_seed_size);
5243 assert(ret_encrypted_seed);
5244 assert(ret_encrypted_seed_size);
5245
5246 log_debug("Calculating encrypted seed for RSA sealed object.");
5247
5248 _cleanup_(EVP_PKEY_freep) EVP_PKEY *parent_pkey = NULL;
5249 r = tpm2_tpm2b_public_to_openssl_pkey(parent, &parent_pkey);
5250 if (r < 0)
5251 return log_debug_errno(r, "Could not convert TPM2B_PUBLIC to OpenSSL PKEY: %m");
5252
5253 r = tpm2_hash_alg_to_size(parent->publicArea.nameAlg);
5254 if (r < 0)
5255 return -EOPNOTSUPP;
5256
5257 size_t seed_size = (size_t) r;
5258
5259 _cleanup_(erase_and_freep) void *seed = malloc(seed_size);
5260 if (!seed)
5261 return log_oom_debug();
5262
5263 r = crypto_random_bytes(seed, seed_size);
5264 if (r < 0)
5265 return log_debug_errno(r, "Failed to generate random seed: %m");
5266
5267 const char *hash_alg_name = tpm2_hash_alg_to_string(parent->publicArea.nameAlg);
5268 if (!hash_alg_name)
5269 return -EOPNOTSUPP;
5270
5271 _cleanup_free_ void *encrypted_seed = NULL;
5272 size_t encrypted_seed_size;
5273 r = rsa_oaep_encrypt_bytes(
5274 parent_pkey,
5275 hash_alg_name,
5276 "DUPLICATE",
5277 seed,
5278 seed_size,
5279 &encrypted_seed,
5280 &encrypted_seed_size);
5281 if (r < 0)
5282 return log_debug_errno(r, "Could not RSA-OAEP encrypt random seed: %m");
5283
5284 *ret_seed = TAKE_PTR(seed);
5285 *ret_seed_size = seed_size;
5286 *ret_encrypted_seed = TAKE_PTR(encrypted_seed);
5287 *ret_encrypted_seed_size = encrypted_seed_size;
5288
5289 return 0;
5290 }
5291
5292 static int tpm2_calculate_seal_ecc_seed(
5293 const TPM2B_PUBLIC *parent,
5294 void **ret_seed,
5295 size_t *ret_seed_size,
5296 void **ret_encrypted_seed,
5297 size_t *ret_encrypted_seed_size) {
5298
5299 TSS2_RC rc;
5300 int r;
5301
5302 assert(parent);
5303 assert(ret_seed);
5304 assert(ret_seed_size);
5305 assert(ret_encrypted_seed);
5306 assert(ret_encrypted_seed_size);
5307
5308 log_debug("Calculating encrypted seed for ECC sealed object.");
5309
5310 _cleanup_(EVP_PKEY_freep) EVP_PKEY *parent_pkey = NULL;
5311 r = tpm2_tpm2b_public_to_openssl_pkey(parent, &parent_pkey);
5312 if (r < 0)
5313 return log_debug_errno(r, "Could not convert TPM2B_PUBLIC to OpenSSL PKEY: %m");
5314
5315 int curve_id;
5316 r = ecc_pkey_to_curve_x_y(
5317 parent_pkey,
5318 &curve_id,
5319 /* ret_x= */ NULL, /* ret_x_size= */ NULL,
5320 /* ret_y= */ NULL, /* ret_y_size= */ NULL);
5321 if (r < 0)
5322 return r;
5323
5324 _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
5325 r = ecc_pkey_new(curve_id, &pkey);
5326 if (r < 0)
5327 return r;
5328
5329 _cleanup_(erase_and_freep) void *shared_secret = NULL;
5330 size_t shared_secret_size;
5331 r = ecc_ecdh(pkey, parent_pkey, &shared_secret, &shared_secret_size);
5332 if (r < 0)
5333 return log_debug_errno(r, "Could not generate ECC shared secret: %m");
5334
5335 _cleanup_free_ void *x = NULL, *y = NULL;
5336 size_t x_size, y_size;
5337 r = ecc_pkey_to_curve_x_y(pkey, /* ret_curve_id= */ NULL, &x, &x_size, &y, &y_size);
5338 if (r < 0)
5339 return log_debug_errno(r, "Could not get ECC get x/y: %m");
5340
5341 r = TPM2B_ECC_PARAMETER_CHECK_SIZE(x_size);
5342 if (r < 0)
5343 return log_debug_errno(r, "ECC point x size %zu is too large: %m", x_size);
5344
5345 r = TPM2B_ECC_PARAMETER_CHECK_SIZE(y_size);
5346 if (r < 0)
5347 return log_debug_errno(r, "ECC point y size %zu is too large: %m", y_size);
5348
5349 TPMS_ECC_POINT point = {
5350 .x = TPM2B_ECC_PARAMETER_MAKE(x, x_size),
5351 .y = TPM2B_ECC_PARAMETER_MAKE(y, y_size),
5352 };
5353
5354 _cleanup_free_ void *encrypted_seed = malloc(sizeof(point));
5355 if (!encrypted_seed)
5356 return log_oom_debug();
5357
5358 size_t encrypted_seed_size = 0;
5359 rc = sym_Tss2_MU_TPMS_ECC_POINT_Marshal(&point, encrypted_seed, sizeof(point), &encrypted_seed_size);
5360 if (rc != TPM2_RC_SUCCESS)
5361 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
5362 "Failed to marshal ECC point: %s", sym_Tss2_RC_Decode(rc));
5363
5364 r = tpm2_hash_alg_to_size(parent->publicArea.nameAlg);
5365 if (r < 0)
5366 return -EOPNOTSUPP;
5367
5368 size_t bits = (size_t) r * 8;
5369
5370 _cleanup_(erase_and_freep) void *seed = NULL;
5371 size_t seed_size = 0; /* Explicit initialization to appease gcc */
5372 r = tpm2_kdfe(parent->publicArea.nameAlg,
5373 shared_secret,
5374 shared_secret_size,
5375 "DUPLICATE",
5376 x,
5377 x_size,
5378 parent->publicArea.unique.ecc.x.buffer,
5379 parent->publicArea.unique.ecc.x.size,
5380 bits,
5381 &seed,
5382 &seed_size);
5383 if (r < 0)
5384 return log_debug_errno(r, "Could not calculate KDFe: %m");
5385
5386 *ret_seed = TAKE_PTR(seed);
5387 *ret_seed_size = seed_size;
5388 *ret_encrypted_seed = TAKE_PTR(encrypted_seed);
5389 *ret_encrypted_seed_size = encrypted_seed_size;
5390
5391 return 0;
5392 }
5393
5394 static int tpm2_calculate_seal_seed(
5395 const TPM2B_PUBLIC *parent,
5396 TPM2B_DIGEST *ret_seed,
5397 TPM2B_ENCRYPTED_SECRET *ret_encrypted_seed) {
5398
5399 int r;
5400
5401 assert(parent);
5402 assert(ret_seed);
5403 assert(ret_encrypted_seed);
5404
5405 log_debug("Calculating encrypted seed for sealed object.");
5406
5407 _cleanup_(erase_and_freep) void *seed = NULL;
5408 _cleanup_free_ void *encrypted_seed = NULL;
5409 size_t seed_size = 0, encrypted_seed_size = 0; /* Explicit initialization to appease gcc */
5410 if (parent->publicArea.type == TPM2_ALG_RSA)
5411 r = tpm2_calculate_seal_rsa_seed(parent, &seed, &seed_size, &encrypted_seed, &encrypted_seed_size);
5412 else if (parent->publicArea.type == TPM2_ALG_ECC)
5413 r = tpm2_calculate_seal_ecc_seed(parent, &seed, &seed_size, &encrypted_seed, &encrypted_seed_size);
5414 else
5415 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
5416 "Unsupported parent key type 0x%" PRIx16, parent->publicArea.type);
5417 if (r < 0)
5418 return log_debug_errno(r, "Could not calculate encrypted seed: %m");
5419
5420 *ret_seed = TPM2B_DIGEST_MAKE(seed, seed_size);
5421 *ret_encrypted_seed = TPM2B_ENCRYPTED_SECRET_MAKE(encrypted_seed, encrypted_seed_size);
5422
5423 return 0;
5424 }
5425
5426 #endif /* HAVE_OPENSSL */
5427
5428 int tpm2_calculate_seal(
5429 TPM2_HANDLE parent_handle,
5430 const TPM2B_PUBLIC *parent_public,
5431 const TPMA_OBJECT *attributes,
5432 const struct iovec *secret,
5433 const TPM2B_DIGEST *policy,
5434 const char *pin,
5435 struct iovec *ret_secret,
5436 struct iovec *ret_blob,
5437 struct iovec *ret_serialized_parent) {
5438
5439 #if HAVE_OPENSSL
5440 int r;
5441
5442 assert(parent_public);
5443 assert(iovec_is_valid(secret));
5444 assert(secret || ret_secret);
5445 assert(!(secret && ret_secret)); /* Either provide a secret, or we create one, but not both */
5446 assert(ret_blob);
5447 assert(ret_serialized_parent);
5448
5449 log_debug("Calculating sealed object.");
5450
5451 /* Default to the SRK. */
5452 if (parent_handle == 0)
5453 parent_handle = TPM2_SRK_HANDLE;
5454
5455 switch (TPM2_HANDLE_TYPE(parent_handle)) {
5456 case TPM2_HT_PERSISTENT:
5457 case TPM2_HT_NV_INDEX:
5458 break;
5459 case TPM2_HT_TRANSIENT:
5460 log_warning("Handle is transient, sealed secret may not be recoverable.");
5461 break;
5462 default:
5463 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
5464 "Handle 0x%" PRIx32 " not persistent, transient, or NV.",
5465 parent_handle);
5466 }
5467
5468 _cleanup_(iovec_done_erase) struct iovec generated_secret = {};
5469 if (!secret) {
5470 /* No secret provided, generate a random secret. We use SHA256 digest length, though it can
5471 * be up to TPM2_MAX_SEALED_DATA. The secret length is not limited to the nameAlg hash
5472 * size. */
5473 r = crypto_random_bytes_allocate_iovec(TPM2_SHA256_DIGEST_SIZE, &generated_secret);
5474 if (r < 0)
5475 return log_debug_errno(r, "Failed to generate secret key: %m");
5476
5477 secret = &generated_secret;
5478 }
5479
5480 if (secret->iov_len > TPM2_MAX_SEALED_DATA)
5481 return log_debug_errno(SYNTHETIC_ERRNO(EOVERFLOW),
5482 "Secret size %zu too large, limit is %d bytes.",
5483 secret->iov_len, TPM2_MAX_SEALED_DATA);
5484
5485 TPM2B_DIGEST random_seed;
5486 TPM2B_ENCRYPTED_SECRET seed;
5487 r = tpm2_calculate_seal_seed(parent_public, &random_seed, &seed);
5488 if (r < 0)
5489 return r;
5490
5491 TPM2B_PUBLIC public;
5492 r = tpm2_calculate_seal_public(parent_public, attributes, policy, &random_seed, secret->iov_base, secret->iov_len, &public);
5493 if (r < 0)
5494 return r;
5495
5496 TPM2B_NAME name;
5497 r = tpm2_calculate_pubkey_name(&public.publicArea, &name);
5498 if (r < 0)
5499 return r;
5500
5501 TPM2B_PRIVATE private;
5502 r = tpm2_calculate_seal_private(parent_public, &name, pin, &random_seed, secret->iov_base, secret->iov_len, &private);
5503 if (r < 0)
5504 return r;
5505
5506 _cleanup_(iovec_done) struct iovec blob = {};
5507 r = tpm2_marshal_blob(&public, &private, &seed, &blob.iov_base, &blob.iov_len);
5508 if (r < 0)
5509 return log_debug_errno(r, "Could not create sealed blob: %m");
5510
5511 TPM2B_NAME parent_name;
5512 r = tpm2_calculate_pubkey_name(&parent_public->publicArea, &parent_name);
5513 if (r < 0)
5514 return r;
5515
5516 _cleanup_(iovec_done) struct iovec serialized_parent = {};
5517 r = tpm2_calculate_serialize(
5518 parent_handle,
5519 &parent_name,
5520 parent_public,
5521 &serialized_parent.iov_base,
5522 &serialized_parent.iov_len);
5523 if (r < 0)
5524 return r;
5525
5526 if (ret_secret)
5527 *ret_secret = TAKE_STRUCT(generated_secret);
5528 *ret_blob = TAKE_STRUCT(blob);
5529 *ret_serialized_parent = TAKE_STRUCT(serialized_parent);
5530
5531 return 0;
5532 #else /* HAVE_OPENSSL */
5533 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
5534 #endif
5535 }
5536
5537 int tpm2_seal(Tpm2Context *c,
5538 uint32_t seal_key_handle,
5539 const TPM2B_DIGEST policy[],
5540 size_t n_policy,
5541 const char *pin,
5542 struct iovec *ret_secret,
5543 struct iovec **ret_blobs,
5544 size_t *ret_n_blobs,
5545 uint16_t *ret_primary_alg,
5546 struct iovec *ret_srk) {
5547
5548 uint16_t primary_alg = 0;
5549 int r;
5550
5551 assert(ret_secret);
5552 assert(ret_blobs);
5553 assert(ret_n_blobs);
5554
5555 /* So here's what we do here: we connect to the TPM2 chip. It persistently contains a "seed" key that
5556 * is randomized when the TPM2 is first initialized or reset and remains stable across boots. We
5557 * generate a "primary" key pair derived from that (ECC if possible, RSA as fallback). Given the seed
5558 * remains fixed this will result in the same key pair whenever we specify the exact same parameters
5559 * for it. We then create a PCR-bound policy session, which calculates a hash on the current PCR
5560 * values of the indexes we specify. We then generate a randomized key on the host (which is the key
5561 * we actually enroll in the LUKS2 keyslots), which we upload into the TPM2, where it is encrypted
5562 * with the "primary" key, taking the PCR policy session into account. We then download the encrypted
5563 * key from the TPM2 ("sealing") and marshall it into binary form, which is ultimately placed in the
5564 * LUKS2 JSON header.
5565 *
5566 * The TPM2 "seed" key and "primary" keys never leave the TPM2 chip (and cannot be extracted at
5567 * all). The random key we enroll in LUKS2 we generate on the host using the Linux random device. It
5568 * is stored in the LUKS2 JSON only in encrypted form with the "primary" key of the TPM2 chip, thus
5569 * binding the unlocking to the TPM2 chip. */
5570
5571 usec_t start = now(CLOCK_MONOTONIC);
5572
5573 TPMA_OBJECT hmac_attributes =
5574 TPMA_OBJECT_FIXEDTPM |
5575 TPMA_OBJECT_FIXEDPARENT;
5576
5577 /* If protected by PIN, a user-selected low-entropy password, enable DA protection.
5578 Without a PIN, the key's left protected only by a PCR policy, which does not benefit
5579 from DA protection. */
5580 hmac_attributes |= pin ? 0 : TPMA_OBJECT_NODA;
5581
5582 /* We use a keyed hash object (i.e. HMAC) to store the secret key we want to use for unlocking the
5583 * LUKS2 volume with. We don't ever use for HMAC/keyed hash operations however, we just use it
5584 * because it's a key type that is universally supported and suitable for symmetric binary blobs. */
5585 TPMT_PUBLIC hmac_template = {
5586 .type = TPM2_ALG_KEYEDHASH,
5587 .nameAlg = TPM2_ALG_SHA256,
5588 .objectAttributes = hmac_attributes,
5589 .parameters.keyedHashDetail.scheme.scheme = TPM2_ALG_NULL,
5590 .unique.keyedHash.size = SHA256_DIGEST_SIZE,
5591 };
5592
5593 TPMS_SENSITIVE_CREATE hmac_sensitive = {
5594 .data.size = hmac_template.unique.keyedHash.size,
5595 };
5596
5597 CLEANUP_ERASE(hmac_sensitive);
5598
5599 if (pin) {
5600 r = tpm2_auth_value_from_pin(TPM2_ALG_SHA256, pin, &hmac_sensitive.userAuth);
5601 if (r < 0)
5602 return r;
5603 }
5604
5605 assert(sizeof(hmac_sensitive.data.buffer) >= hmac_sensitive.data.size);
5606
5607 (void) tpm2_credit_random(c);
5608
5609 _cleanup_(tpm2_handle_freep) Tpm2Handle *primary_handle = NULL;
5610 if (ret_srk) {
5611 _cleanup_(Esys_Freep) TPM2B_PUBLIC *primary_public = NULL;
5612
5613 if (IN_SET(seal_key_handle, 0, TPM2_SRK_HANDLE)) {
5614 r = tpm2_get_or_create_srk(
5615 c,
5616 /* session= */ NULL,
5617 &primary_public,
5618 /* ret_name= */ NULL,
5619 /* ret_qname= */ NULL,
5620 &primary_handle);
5621 if (r < 0)
5622 return r;
5623 } else if (IN_SET(TPM2_HANDLE_TYPE(seal_key_handle), TPM2_HT_TRANSIENT, TPM2_HT_PERSISTENT)) {
5624 r = tpm2_index_to_handle(
5625 c,
5626 seal_key_handle,
5627 /* session= */ NULL,
5628 &primary_public,
5629 /* ret_name= */ NULL,
5630 /* ret_qname= */ NULL,
5631 &primary_handle);
5632 if (r < 0)
5633 return r;
5634 if (r == 0)
5635 /* We do NOT automatically create anything other than the SRK */
5636 return log_debug_errno(SYNTHETIC_ERRNO(ENOENT),
5637 "No handle found at index 0x%" PRIx32, seal_key_handle);
5638 } else
5639 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
5640 "Seal key handle 0x%" PRIx32 " is neither transient nor persistent.",
5641 seal_key_handle);
5642
5643 primary_alg = primary_public->publicArea.type;
5644
5645 /* Propagate fixedTPM/fixedParent flags from sealing key to hmac key */
5646 hmac_template.objectAttributes = (hmac_template.objectAttributes & ~(TPMA_OBJECT_FIXEDTPM|TPMA_OBJECT_FIXEDPARENT)) |
5647 (primary_public->publicArea.objectAttributes & (TPMA_OBJECT_FIXEDTPM|TPMA_OBJECT_FIXEDPARENT));
5648
5649 } else {
5650 if (seal_key_handle != 0)
5651 log_debug("Using primary alg sealing, but seal key handle also provided; ignoring seal key handle.");
5652
5653 /* TODO: force all callers to provide ret_srk, so we can stop sealing with the legacy templates. */
5654 primary_alg = TPM2_ALG_ECC;
5655
5656 TPM2B_PUBLIC template = {
5657 .size = sizeof(TPMT_PUBLIC),
5658 };
5659 r = tpm2_get_legacy_template(primary_alg, &template.publicArea);
5660 if (r < 0)
5661 return log_debug_errno(r, "Could not get legacy ECC template: %m");
5662
5663 if (!tpm2_supports_tpmt_public(c, &template.publicArea)) {
5664 primary_alg = TPM2_ALG_RSA;
5665
5666 r = tpm2_get_legacy_template(primary_alg, &template.publicArea);
5667 if (r < 0)
5668 return log_debug_errno(r, "Could not get legacy RSA template: %m");
5669
5670 if (!tpm2_supports_tpmt_public(c, &template.publicArea))
5671 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
5672 "TPM does not support either ECC or RSA legacy template.");
5673 }
5674
5675 r = tpm2_create_primary(
5676 c,
5677 /* session= */ NULL,
5678 &template,
5679 /* sensitive= */ NULL,
5680 /* ret_public= */ NULL,
5681 &primary_handle);
5682 if (r < 0)
5683 return r;
5684 }
5685
5686 _cleanup_(tpm2_handle_freep) Tpm2Handle *encryption_session = NULL;
5687 r = tpm2_make_encryption_session(c, primary_handle, /* bind_key= */ NULL, &encryption_session);
5688 if (r < 0)
5689 return r;
5690
5691 log_debug("Generating secret key data.");
5692
5693 /* At least one shard, and if we have multiple policies, then we need one shard for each */
5694 size_t n_shards = MAX(n_policy, 1U);
5695
5696 /* Create a large secret which covers all shards we need */
5697 _cleanup_(iovec_done_erase) struct iovec secret = {};
5698 r = crypto_random_bytes_allocate_iovec(hmac_sensitive.data.size * n_shards, &secret);
5699 if (r < 0)
5700 return log_debug_errno(r, "Failed to generate secret key: %m");
5701
5702 struct iovec *blobs = new0(struct iovec, n_shards);
5703 size_t n_blobs = 0;
5704
5705 CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
5706
5707 for (size_t shard = 0; shard < n_shards; shard++) {
5708
5709 /* Patch this shard's policy into the template */
5710 if (shard < n_policy)
5711 hmac_template.authPolicy = policy[shard];
5712 else
5713 hmac_template.authPolicy = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
5714
5715 /* Copy in this shard's secret key */
5716 memcpy(hmac_sensitive.data.buffer,
5717 (const uint8_t*) secret.iov_base + (hmac_sensitive.data.size * shard),
5718 hmac_sensitive.data.size);
5719
5720 log_debug("Creating HMAC key on TPM for shard %zu.", shard);
5721
5722 _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
5723 _cleanup_(Esys_Freep) TPM2B_PRIVATE *private = NULL;
5724 r = tpm2_create(c, primary_handle, encryption_session, &hmac_template, &hmac_sensitive, &public, &private);
5725 if (r < 0)
5726 return r;
5727
5728 log_debug("Marshalling private and public part of HMAC key for shard %zu.", shard);
5729
5730 r = tpm2_marshal_blob(public, private, /* seed= */ NULL, &blobs[n_blobs].iov_base, &blobs[n_blobs].iov_len);
5731 if (r < 0)
5732 return log_debug_errno(r, "Could not create sealed blob: %m");
5733
5734 n_blobs++;
5735 }
5736
5737 if (DEBUG_LOGGING)
5738 log_debug("Completed TPM2 key sealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - start, 1));
5739
5740 if (ret_srk) {
5741 r = tpm2_serialize(c, primary_handle, ret_srk);
5742 if (r < 0)
5743 return r;
5744 }
5745
5746 *ret_secret = TAKE_STRUCT(secret);
5747 *ret_blobs = TAKE_PTR(blobs);
5748 *ret_n_blobs = n_blobs;
5749
5750 if (ret_primary_alg)
5751 *ret_primary_alg = primary_alg;
5752
5753 return 0;
5754 }
5755
5756 #define RETRY_UNSEAL_MAX 30u
5757
5758 int tpm2_unseal(Tpm2Context *c,
5759 uint32_t hash_pcr_mask,
5760 uint16_t pcr_bank,
5761 const struct iovec *pubkey,
5762 uint32_t pubkey_pcr_mask,
5763 sd_json_variant *signature,
5764 const char *pin,
5765 const Tpm2PCRLockPolicy *pcrlock_policy,
5766 uint16_t primary_alg,
5767 const struct iovec blobs[],
5768 size_t n_blobs,
5769 const struct iovec known_policy_hash[],
5770 size_t n_known_policy_hash,
5771 const struct iovec *srk,
5772 struct iovec *ret_secret) {
5773
5774 /* Returns the following errors:
5775 *
5776 * -EREMOTE → blob is from a different TPM
5777 * -EDEADLK → couldn't create primary key because authorization failure
5778 * -ENOLCK → TPM is in dictionary lockout mode
5779 * -EREMCHG → submitted policy doesn't match NV index stored policy (in case of PolicyAuthorizeNV)
5780 * -ENOANO → none of the PolicyOR branches of a policy matched current state
5781 * -EUCLEAN → PCR state doesn't match expectations
5782 * -EPERM → stored policy does not match TPM state
5783 * -ENOTRECOVERABLE → all other kinds of TPM errors
5784 * -EILSEQ → bad PIN
5785 *
5786 * Of these all four of EREMCHG, ENOANO, EUCLEAN, EPERM can all mean that PCR state is not matching
5787 * expectations. */
5788
5789 TSS2_RC rc;
5790 int r;
5791
5792 assert(n_blobs > 0);
5793 assert(blobs);
5794 assert(iovec_is_valid(pubkey));
5795 assert(ret_secret);
5796
5797 assert(TPM2_PCR_MASK_VALID(hash_pcr_mask));
5798 assert(TPM2_PCR_MASK_VALID(pubkey_pcr_mask));
5799
5800 /* So here's what we do here: We connect to the TPM2 chip. As we do when sealing we generate a
5801 * "primary" key on the TPM2 chip, with the same parameters as well as a PCR-bound policy session.
5802 * Given we pass the same parameters, this will result in the same "primary" key, and same policy
5803 * hash (the latter of course, only if the PCR values didn't change in between). We unmarshal the
5804 * encrypted key we stored in the LUKS2 JSON token header and upload it into the TPM2, where it is
5805 * decrypted if the seed and the PCR policy were right ("unsealing"). We then download the result,
5806 * and use it to unlock the LUKS2 volume. */
5807
5808 usec_t start = now(CLOCK_MONOTONIC);
5809
5810 size_t n_shards = pcrlock_policy && iovec_is_set(pubkey) ? 2 : 1;
5811 if (n_blobs != n_shards)
5812 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Number of provided key blobs (%zu) does not match policy requirements (%zu).", n_blobs, n_shards);
5813 if (n_known_policy_hash > 0 && n_known_policy_hash != n_shards)
5814 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Number of provided known policy hashes (%zu) does not match policy requirements (%zu or 0).", n_known_policy_hash, n_shards);
5815
5816 /* Older code did not save the pcr_bank, and unsealing needed to detect the best pcr bank to use,
5817 * so we need to handle that legacy situation. */
5818 if (pcr_bank == UINT16_MAX) {
5819 r = tpm2_get_best_pcr_bank(c, hash_pcr_mask|pubkey_pcr_mask, &pcr_bank);
5820 if (r < 0)
5821 return r;
5822 }
5823
5824 _cleanup_(tpm2_handle_freep) Tpm2Handle *primary_handle = NULL;
5825 r = tpm2_deserialize(c, srk, &primary_handle);
5826 if (r < 0)
5827 return r;
5828 if (r == 0) {
5829 /* ECC was the only supported algorithm in systemd < 250, use that as implied default, for compatibility */
5830 if (primary_alg == 0)
5831 primary_alg = TPM2_ALG_ECC;
5832
5833 TPM2B_PUBLIC template = {
5834 .size = sizeof(TPMT_PUBLIC),
5835 };
5836 r = tpm2_get_legacy_template(primary_alg, &template.publicArea);
5837 if (r < 0)
5838 return log_debug_errno(r, "Could not get legacy template: %m");
5839
5840 r = tpm2_create_primary(
5841 c,
5842 /* session= */ NULL,
5843 &template,
5844 /* sensitive= */ NULL,
5845 /* ret_public= */ NULL,
5846 &primary_handle);
5847 if (r < 0)
5848 return r;
5849 }
5850
5851 TPM2B_PUBLIC pubkey_tpm2b;
5852 _cleanup_(iovec_done) struct iovec fp = {};
5853 if (iovec_is_set(pubkey)) {
5854 r = tpm2_tpm2b_public_from_pem(pubkey->iov_base, pubkey->iov_len, &pubkey_tpm2b);
5855 if (r < 0)
5856 return log_debug_errno(r, "Could not create TPMT_PUBLIC: %m");
5857
5858 r = tpm2_tpm2b_public_to_fingerprint(&pubkey_tpm2b, &fp.iov_base, &fp.iov_len);
5859 if (r < 0)
5860 return log_debug_errno(r, "Could not get key fingerprint: %m");
5861 }
5862
5863 _cleanup_(iovec_done_erase) struct iovec secret = {};
5864 for (unsigned i = RETRY_UNSEAL_MAX;; i--) {
5865 bool retry = false;
5866 iovec_done_erase(&secret); /* clear data from previous unseal attempt */
5867
5868 for (size_t shard = 0; shard < n_blobs; shard++) {
5869 TPM2B_PUBLIC public;
5870 TPM2B_PRIVATE private;
5871 TPM2B_ENCRYPTED_SECRET seed = {};
5872 r = tpm2_unmarshal_blob(blobs[shard].iov_base, blobs[shard].iov_len, &public, &private, &seed);
5873 if (r < 0)
5874 return log_debug_errno(r, "Could not extract parts from blob: %m");
5875
5876 if (seed.size > 0) {
5877 /* This is a calculated (or duplicated) sealed object, and must be imported. */
5878 _cleanup_free_ TPM2B_PRIVATE *imported_private = NULL;
5879 r = tpm2_import(c,
5880 primary_handle,
5881 /* session= */ NULL,
5882 &public,
5883 &private,
5884 &seed,
5885 /* encryption_key= */ NULL,
5886 /* symmetric= */ NULL,
5887 &imported_private);
5888 if (r < 0)
5889 return r;
5890
5891 private = *imported_private;
5892 }
5893
5894 log_debug("Loading HMAC key into TPM for shard %zu.", shard);
5895
5896 /* Nothing sensitive on the bus, no need for encryption. Even if an attacker gives
5897 * you back a different key, the session initiation will fail. In the SRK model, the
5898 * tpmKey is verified. In the non-srk model, with pin, the bindKey provides
5899 * protections. */
5900 _cleanup_(tpm2_handle_freep) Tpm2Handle *hmac_key = NULL;
5901 r = tpm2_load(c, primary_handle, NULL, &public, &private, &hmac_key);
5902 if (r < 0)
5903 return r;
5904
5905 /* If a PIN is set for the seal object, use it to bind the session key to that
5906 * object. This prevents active bus interposers from faking a TPM and seeing the
5907 * unsealed value. An active interposer could fake a TPM, satisfying the encrypted
5908 * session, and just forward everything to the *real* TPM. */
5909 r = tpm2_set_auth(c, hmac_key, pin);
5910 if (r < 0)
5911 return r;
5912
5913 _cleanup_(tpm2_handle_freep) Tpm2Handle *encryption_session = NULL;
5914 r = tpm2_make_encryption_session(c, primary_handle, hmac_key, &encryption_session);
5915 if (r < 0)
5916 return r;
5917
5918 _cleanup_(tpm2_handle_freep) Tpm2Handle *policy_session = NULL;
5919 _cleanup_(Esys_Freep) TPM2B_DIGEST *policy_digest = NULL;
5920 r = tpm2_make_policy_session(
5921 c,
5922 primary_handle,
5923 encryption_session,
5924 &policy_session);
5925 if (r < 0)
5926 return r; /* Will return EILSEQ on auth failure (i.e. bad PIN) */
5927
5928 /* If both public PCR key and pcrlock policies are requested, then generate the
5929 * public PCR policy for the first shared, and the pcrlock policy for the 2nd */
5930 r = tpm2_build_sealing_policy(
5931 c,
5932 policy_session,
5933 hash_pcr_mask,
5934 pcr_bank,
5935 shard == 0 && iovec_is_set(pubkey) ? &pubkey_tpm2b : NULL,
5936 fp.iov_base, fp.iov_len,
5937 shard == 0 ? pubkey_pcr_mask : 0,
5938 signature,
5939 !!pin,
5940 (shard == 1 || !iovec_is_set(pubkey)) ? pcrlock_policy : NULL,
5941 &policy_digest);
5942 if (r == -EUCLEAN && i > 0) {
5943 log_debug("A PCR value changed during the TPM2 policy session, restarting HMAC key unsealing (%u tries left).", i);
5944 retry = true;
5945 break;
5946 }
5947 if (r < 0)
5948 return r;
5949
5950 /* If we know the policy hash to expect, and it doesn't match, we can shortcut things here, and not
5951 * wait until the TPM2 tells us to go away. */
5952 if (n_known_policy_hash > 0 && memcmp_nn(policy_digest->buffer,
5953 policy_digest->size,
5954 known_policy_hash[shard].iov_base,
5955 known_policy_hash[shard].iov_len) != 0) {
5956 #if HAVE_OPENSSL
5957 if (shard == 0 &&
5958 iovec_is_set(pubkey) &&
5959 pubkey_tpm2b.publicArea.type == TPM2_ALG_RSA &&
5960 pubkey_tpm2b.publicArea.parameters.rsaDetail.exponent == TPM2_RSA_DEFAULT_EXPONENT) {
5961 /* Due to bug #30546, if using RSA pubkey with the default exponent, we may
5962 * need to set the exponent to the TPM special-case value of 0 and retry. */
5963 log_debug("Policy hash mismatch, retrying with RSA pubkey exponent set to 0.");
5964 pubkey_tpm2b.publicArea.parameters.rsaDetail.exponent = 0;
5965 retry = true;
5966 break;
5967 }
5968 #endif
5969 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
5970 "Current policy digest does not match stored policy digest, cancelling "
5971 "TPM2 authentication attempt.");
5972 }
5973
5974 log_debug("Unsealing HMAC key for shard %zu.", shard);
5975
5976 _cleanup_(tpm2b_sensitive_data_erase_and_esys_freep) TPM2B_SENSITIVE_DATA* unsealed = NULL;
5977 rc = sym_Esys_Unseal(
5978 c->esys_context,
5979 hmac_key->esys_handle,
5980 policy_session->esys_handle,
5981 encryption_session->esys_handle, /* use HMAC session to enable parameter encryption */
5982 ESYS_TR_NONE,
5983 &unsealed);
5984 if (rc == TPM2_RC_PCR_CHANGED && i > 0) {
5985 log_debug("A PCR value changed during the TPM2 policy session, restarting HMAC key unsealing (%u tries left).", i);
5986 retry = true;
5987 break;
5988 }
5989 if (rc != TPM2_RC_SUCCESS)
5990 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
5991 "Failed to unseal HMAC key in TPM: %s", sym_Tss2_RC_Decode(rc));
5992
5993 if (!iovec_append(&secret, &IOVEC_MAKE(unsealed->buffer, unsealed->size)))
5994 return log_oom_debug();
5995 }
5996
5997 if (!retry)
5998 break;
5999 }
6000
6001 if (DEBUG_LOGGING)
6002 log_debug("Completed TPM2 key unsealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - start, 1));
6003
6004 *ret_secret = TAKE_STRUCT(secret);
6005 return 0;
6006 }
6007
6008 static TPM2_HANDLE generate_random_nv_index(void) {
6009 return TPM2_NV_INDEX_UNASSIGNED_FIRST +
6010 (TPM2_HANDLE) random_u64_range(TPM2_NV_INDEX_UNASSIGNED_LAST - TPM2_NV_INDEX_UNASSIGNED_FIRST + 1);
6011 }
6012
6013 int tpm2_define_policy_nv_index(
6014 Tpm2Context *c,
6015 const Tpm2Handle *session,
6016 TPM2_HANDLE requested_nv_index,
6017 const TPM2B_DIGEST *write_policy,
6018 TPM2_HANDLE *ret_nv_index,
6019 Tpm2Handle **ret_nv_handle,
6020 TPM2B_NV_PUBLIC *ret_nv_public) {
6021
6022 _cleanup_(tpm2_handle_freep) Tpm2Handle *new_handle = NULL;
6023 TSS2_RC rc;
6024 int r;
6025
6026 assert(c);
6027
6028 /* Allocates an nvindex to store a policy for use in PolicyAuthorizeNV in. This is where pcrlock then
6029 * stores its predicted PCR policies in. If 'requested_nv_index' will try to allocate the specified
6030 * nvindex, otherwise will find a free one, and use that. */
6031
6032 r = tpm2_handle_new(c, &new_handle);
6033 if (r < 0)
6034 return r;
6035
6036 new_handle->flush = false; /* This is a persistent NV index, don't flush hence */
6037
6038 for (unsigned try = 0; try < 25U; try++) {
6039 TPM2_HANDLE nv_index;
6040
6041 if (requested_nv_index != 0)
6042 nv_index = requested_nv_index;
6043 else
6044 nv_index = generate_random_nv_index();
6045
6046 TPM2B_NV_PUBLIC public_info = {
6047 .size = sizeof_field(TPM2B_NV_PUBLIC, nvPublic),
6048 .nvPublic = {
6049 .nvIndex = nv_index,
6050 .nameAlg = TPM2_ALG_SHA256,
6051 .attributes = TPM2_NT_ORDINARY | TPMA_NV_WRITEALL | TPMA_NV_POLICYWRITE | TPMA_NV_OWNERREAD,
6052 .dataSize = offsetof(TPMT_HA, digest) + tpm2_hash_alg_to_size(TPM2_ALG_SHA256),
6053 },
6054 };
6055
6056 if (write_policy)
6057 public_info.nvPublic.authPolicy = *write_policy;
6058
6059 rc = sym_Esys_NV_DefineSpace(
6060 c->esys_context,
6061 /* authHandle= */ ESYS_TR_RH_OWNER,
6062 /* shandle1= */ session ? session->esys_handle : ESYS_TR_PASSWORD,
6063 /* shandle2= */ ESYS_TR_NONE,
6064 /* shandle3= */ ESYS_TR_NONE,
6065 /* auth= */ NULL,
6066 &public_info,
6067 &new_handle->esys_handle);
6068
6069 if (rc == TSS2_RC_SUCCESS) {
6070 log_debug("NV Index 0x%" PRIx32 " successfully allocated.", nv_index);
6071
6072 if (ret_nv_index)
6073 *ret_nv_index = nv_index;
6074
6075 if (ret_nv_handle)
6076 *ret_nv_handle = TAKE_PTR(new_handle);
6077
6078 if (ret_nv_public)
6079 *ret_nv_public = public_info;
6080
6081 return 0;
6082 }
6083 if (rc != TPM2_RC_NV_DEFINED)
6084 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6085 "Failed to allocate NV index: %s", sym_Tss2_RC_Decode(rc));
6086
6087 if (requested_nv_index != 0) {
6088 assert(nv_index == requested_nv_index);
6089 return log_debug_errno(SYNTHETIC_ERRNO(EEXIST),
6090 "Requested NV index 0x%" PRIx32 " already taken.", requested_nv_index);
6091 }
6092
6093 log_debug("NV index 0x%" PRIu32 " already taken, trying another one (%u tries left)", nv_index, try);
6094 }
6095
6096 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6097 "Too many attempts trying to allocate NV index: %s", sym_Tss2_RC_Decode(rc));
6098 }
6099
6100 int tpm2_write_policy_nv_index(
6101 Tpm2Context *c,
6102 const Tpm2Handle *policy_session,
6103 TPM2_HANDLE nv_index,
6104 const Tpm2Handle *nv_handle,
6105 const TPM2B_DIGEST *policy_digest) {
6106
6107 TSS2_RC rc;
6108
6109 assert(c);
6110 assert(policy_session);
6111 assert(nv_handle);
6112 assert(policy_digest);
6113
6114 if (policy_digest->size != tpm2_hash_alg_to_size(TPM2_ALG_SHA256))
6115 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Policy to store in NV index has wrong size.");
6116
6117 TPMT_HA ha = {
6118 .hashAlg = TPM2_ALG_SHA256,
6119 };
6120 assert(policy_digest->size <= sizeof_field(TPMT_HA, digest));
6121 memcpy_safe(&ha.digest, policy_digest->buffer, policy_digest->size);
6122
6123 TPM2B_MAX_NV_BUFFER buffer = {};
6124 size_t written = 0;
6125 rc = sym_Tss2_MU_TPMT_HA_Marshal(&ha, buffer.buffer, sizeof(buffer.buffer), &written);
6126 if (rc != TSS2_RC_SUCCESS)
6127 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6128 "Failed to marshal policy digest.");
6129
6130 buffer.size = written;
6131
6132 rc = sym_Esys_NV_Write(
6133 c->esys_context,
6134 /* authHandle= */ nv_handle->esys_handle,
6135 /* nvIndex= */ nv_handle->esys_handle,
6136 /* shandle1= */ policy_session->esys_handle,
6137 /* shandle2= */ ESYS_TR_NONE,
6138 /* shandle3= */ ESYS_TR_NONE,
6139 &buffer,
6140 /* offset= */ 0);
6141 if (rc != TSS2_RC_SUCCESS)
6142 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6143 "Failed to write NV index: %s", sym_Tss2_RC_Decode(rc));
6144
6145 if (DEBUG_LOGGING) {
6146 _cleanup_free_ char *h = NULL;
6147 h = hexmem(policy_digest->buffer, policy_digest->size);
6148 log_debug("Written policy digest %s to NV index 0x%x", strnull(h), nv_index);
6149 }
6150
6151 return 0;
6152 }
6153
6154 int tpm2_undefine_nv_index(
6155 Tpm2Context *c,
6156 const Tpm2Handle *session,
6157 TPM2_HANDLE nv_index,
6158 const Tpm2Handle *nv_handle) {
6159
6160 TSS2_RC rc;
6161
6162 assert(c);
6163 assert(nv_handle);
6164
6165 rc = sym_Esys_NV_UndefineSpace(
6166 c->esys_context,
6167 /* authHandle= */ ESYS_TR_RH_OWNER,
6168 /* nvIndex= */ nv_handle->esys_handle,
6169 /* shandle1= */ session ? session->esys_handle : ESYS_TR_PASSWORD,
6170 /* shandle2= */ ESYS_TR_NONE,
6171 /* shandle3= */ ESYS_TR_NONE);
6172 if (rc != TSS2_RC_SUCCESS)
6173 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6174 "Failed to undefine NV index: %s", sym_Tss2_RC_Decode(rc));
6175
6176 log_debug("Successfully undefined NV index 0x%x.", nv_index);
6177 return 0;
6178 }
6179
6180 #if HAVE_OPENSSL
6181 static int tpm2_define_nvpcr_nv_index(
6182 Tpm2Context *c,
6183 const Tpm2Handle *session,
6184 TPM2_HANDLE nv_index,
6185 TPMI_ALG_HASH algorithm,
6186 Tpm2Handle **ret_nv_handle) {
6187
6188 _cleanup_(tpm2_handle_freep) Tpm2Handle *new_handle = NULL;
6189 TSS2_RC rc;
6190 int r;
6191
6192 assert(c);
6193
6194 /* Allocates an nvindex to use as a "fake" PCR. We call these "NvPCR" in our codebase */
6195
6196 if (algorithm == 0)
6197 algorithm = TPM2_ALG_SHA256;
6198
6199 int digest_size = tpm2_hash_alg_to_size(algorithm);
6200 if (digest_size < 0)
6201 return digest_size;
6202
6203 if ((size_t) digest_size > sizeof_field(TPM2B_MAX_NV_BUFFER, buffer))
6204 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Digest too large for extension.");
6205
6206 r = tpm2_handle_new(c, &new_handle);
6207 if (r < 0)
6208 return r;
6209
6210 new_handle->flush = false; /* This is a persistent NV index, don't flush hence */
6211
6212 TPM2B_NV_PUBLIC public_info = {
6213 .size = sizeof_field(TPM2B_NV_PUBLIC, nvPublic),
6214 .nvPublic = {
6215 .nvIndex = nv_index,
6216 .nameAlg = algorithm,
6217 .attributes = TPMA_NV_CLEAR_STCLEAR |
6218 TPMA_NV_ORDERLY |
6219 TPMA_NV_OWNERWRITE |
6220 TPMA_NV_AUTHWRITE |
6221 TPMA_NV_OWNERREAD |
6222 TPMA_NV_AUTHREAD |
6223 (TPM2_NT_EXTEND << TPMA_NV_TPM2_NT_SHIFT),
6224 .dataSize = digest_size,
6225 },
6226 };
6227
6228 rc = sym_Esys_NV_DefineSpace(
6229 c->esys_context,
6230 /* authHandle= */ ESYS_TR_RH_OWNER,
6231 /* shandle1= */ session ? session->esys_handle : ESYS_TR_PASSWORD,
6232 /* shandle2= */ ESYS_TR_NONE,
6233 /* shandle3= */ ESYS_TR_NONE,
6234 /* auth= */ NULL,
6235 &public_info,
6236 &new_handle->esys_handle);
6237 if (rc == TPM2_RC_NV_SPACE)
6238 return log_debug_errno(SYNTHETIC_ERRNO(ENOSPC),
6239 "NV index space on TPM exhausted, cannot allocate NvPCR.");
6240 if (rc == TPM2_RC_NV_DEFINED) {
6241 log_debug("NV index 0x%" PRIu32 " already registered.", nv_index);
6242
6243 new_handle = tpm2_handle_free(new_handle);
6244
6245 r = tpm2_index_to_handle(
6246 c,
6247 nv_index,
6248 session,
6249 /* ret_public= */ NULL,
6250 /* ret_name= */ NULL,
6251 /* ret_qname= */ NULL,
6252 &new_handle);
6253 if (r < 0)
6254 return log_debug_errno(r, "Failed to acquire handle to existing NV index 0x%" PRIu32 ".", nv_index);
6255
6256 log_debug("Successfully acquired handle to existing NV index 0x%" PRIx32 ".", nv_index);
6257
6258 _cleanup_(Esys_Freep) TPM2B_NV_PUBLIC *nv_public_real = NULL;
6259 rc = sym_Esys_NV_ReadPublic(
6260 c->esys_context,
6261 /* nvIndex= */ new_handle->esys_handle,
6262 /* shandle1= */ ESYS_TR_NONE,
6263 /* shandle2= */ ESYS_TR_NONE,
6264 /* shandle3= */ ESYS_TR_NONE,
6265 &nv_public_real,
6266 /* ret_nv_name= */ NULL);
6267 if (rc != TSS2_RC_SUCCESS)
6268 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6269 "Failed read public data of nvindex 0x%x: %s", nv_index, sym_Tss2_RC_Decode(rc));
6270
6271 log_debug("Read public info for nvindex 0x%x.", nv_index);
6272
6273 if (nv_public_real->size < endoffsetof_field(TPMS_NV_PUBLIC, attributes) + sizeof_field(TPMS_NV_PUBLIC, dataSize) ||
6274 nv_public_real->nvPublic.nvIndex != public_info.nvPublic.nvIndex ||
6275 nv_public_real->nvPublic.nameAlg != public_info.nvPublic.nameAlg ||
6276 ((nv_public_real->nvPublic.attributes ^ public_info.nvPublic.attributes) & ~TPMA_NV_WRITTEN) != 0 ||
6277 nv_public_real->nvPublic.dataSize != public_info.nvPublic.dataSize)
6278 return log_debug_errno(SYNTHETIC_ERRNO(EEXIST),
6279 "Public data of nvindex 0x%x does not match our expectations.", nv_index);
6280
6281 log_debug("Public info for nvindex 0x%x checks out, using.", nv_index);
6282
6283 if (ret_nv_handle)
6284 *ret_nv_handle = TAKE_PTR(new_handle);
6285
6286 return 0;
6287 }
6288 if (rc != TSS2_RC_SUCCESS)
6289 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6290 "Failed to allocate NV index: %s", sym_Tss2_RC_Decode(rc));
6291
6292 log_debug("NV Index 0x%" PRIx32 " successfully allocated.", nv_index);
6293
6294 if (ret_nv_handle)
6295 *ret_nv_handle = TAKE_PTR(new_handle);
6296
6297 return 1;
6298 }
6299
6300 static int tpm2_extend_nvpcr_nv_index(
6301 Tpm2Context *c,
6302 TPM2_HANDLE nv_index,
6303 const Tpm2Handle *nv_handle,
6304 const struct iovec *digest) {
6305
6306 TPM2_RC rc;
6307
6308 assert(c);
6309 assert(nv_index);
6310 assert(nv_handle);
6311 assert(iovec_is_set(digest));
6312
6313 if (digest->iov_len > sizeof_field(TPM2B_MAX_NV_BUFFER, buffer))
6314 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Hash value to extend too long.");
6315
6316 TPM2B_MAX_NV_BUFFER buf = {
6317 .size = digest->iov_len,
6318 };
6319 memcpy(buf.buffer, digest->iov_base, digest->iov_len);
6320
6321 rc = sym_Esys_NV_Extend(
6322 c->esys_context,
6323 /* authHandle= */ nv_handle->esys_handle,
6324 /* nvIndex= */ nv_handle->esys_handle,
6325 /* shandle1= */ ESYS_TR_PASSWORD,
6326 /* shandle2= */ ESYS_TR_NONE,
6327 /* shandle3= */ ESYS_TR_NONE,
6328 &buf);
6329 if (rc != TSS2_RC_SUCCESS)
6330 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6331 "Failed to extend NV index: %s", sym_Tss2_RC_Decode(rc));
6332
6333 if (DEBUG_LOGGING) {
6334 _cleanup_free_ char *h = NULL;
6335 h = hexmem(digest->iov_base, digest->iov_len);
6336 log_debug("Written hash %s to NV index 0x%x", strnull(h), nv_index);
6337 }
6338
6339 return 0;
6340 }
6341 #endif
6342
6343 int tpm2_read_nv_index(
6344 Tpm2Context *c,
6345 const Tpm2Handle *session,
6346 TPM2_HANDLE nv_index,
6347 const Tpm2Handle *nv_handle,
6348 struct iovec *ret_value) {
6349
6350 TPM2_RC rc;
6351
6352 assert(c);
6353 assert(nv_index);
6354 assert(nv_handle);
6355
6356 _cleanup_(Esys_Freep) TPM2B_NV_PUBLIC *nv_public = NULL;
6357 rc = sym_Esys_NV_ReadPublic(
6358 c->esys_context,
6359 /* nvIndex= */ nv_handle->esys_handle,
6360 /* shandle1= */ ESYS_TR_NONE,
6361 /* shandle2= */ ESYS_TR_NONE,
6362 /* shandle3= */ ESYS_TR_NONE,
6363 &nv_public,
6364 /* ret_nv_name= */ NULL);
6365 if (rc != TSS2_RC_SUCCESS)
6366 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6367 "Failed read public data of nvindex 0x%x: %s", nv_index, sym_Tss2_RC_Decode(rc));
6368
6369 log_debug("Read public info for nvindex 0x%x, value size is %zu", nv_index, (size_t) nv_public->nvPublic.dataSize);
6370
6371 _cleanup_(Esys_Freep) TPM2B_MAX_NV_BUFFER *value = NULL;
6372 rc = sym_Esys_NV_Read(
6373 c->esys_context,
6374 /* authHandle= */ nv_handle->esys_handle,
6375 /* nvIndex= */ nv_handle->esys_handle,
6376 /* shandle1= */ session ? session->esys_handle : ESYS_TR_PASSWORD,
6377 /* shandle2= */ ESYS_TR_NONE,
6378 /* shandle3= */ ESYS_TR_NONE,
6379 nv_public->nvPublic.dataSize,
6380 /* offset= */ 0,
6381 &value);
6382 if (rc != TSS2_RC_SUCCESS)
6383 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6384 "Failed read contents of nvindex 0x%x: %s", nv_index, sym_Tss2_RC_Decode(rc));
6385
6386 if (ret_value) {
6387 assert(value);
6388
6389 struct iovec result = {
6390 .iov_base = memdup(value->buffer, value->size),
6391 .iov_len = value->size,
6392 };
6393
6394 if (!result.iov_base)
6395 return log_oom_debug();
6396
6397 *ret_value = TAKE_STRUCT(result);
6398 }
6399
6400 return 0;
6401 }
6402
6403 int tpm2_seal_data(
6404 Tpm2Context *c,
6405 const struct iovec *data,
6406 const Tpm2Handle *primary_handle,
6407 const Tpm2Handle *encryption_session,
6408 const TPM2B_DIGEST *policy,
6409 struct iovec *ret_public,
6410 struct iovec *ret_private) {
6411
6412 int r;
6413
6414 assert(c);
6415 assert(data);
6416 assert(primary_handle);
6417 POINTER_MAY_BE_NULL(policy);
6418
6419 /* This is a generic version of tpm2_seal(), that doesn't imply any policy or any specific
6420 * combination of the two keypairs in their marshalling. tpm2_seal() is somewhat specific to the FDE
6421 * usecase. We probably should migrate tpm2_seal() to use tpm2_seal_data() eventually. */
6422
6423 if (data->iov_len >= sizeof_field(TPMS_SENSITIVE_CREATE, data.buffer))
6424 return -E2BIG;
6425
6426 TPMT_PUBLIC hmac_template = {
6427 .type = TPM2_ALG_KEYEDHASH,
6428 .nameAlg = TPM2_ALG_SHA256,
6429 .objectAttributes = TPMA_OBJECT_FIXEDTPM | TPMA_OBJECT_FIXEDPARENT,
6430 .parameters.keyedHashDetail.scheme.scheme = TPM2_ALG_NULL,
6431 .unique.keyedHash.size = data->iov_len,
6432 .authPolicy = policy ? *policy : TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE),
6433 };
6434
6435 TPMS_SENSITIVE_CREATE hmac_sensitive = {
6436 .data.size = hmac_template.unique.keyedHash.size,
6437 };
6438
6439 CLEANUP_ERASE(hmac_sensitive);
6440
6441 memcpy_safe(hmac_sensitive.data.buffer, data->iov_base, data->iov_len);
6442
6443 _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
6444 _cleanup_(Esys_Freep) TPM2B_PRIVATE *private = NULL;
6445 r = tpm2_create(c, primary_handle, encryption_session, &hmac_template, &hmac_sensitive, &public, &private);
6446 if (r < 0)
6447 return r;
6448
6449 _cleanup_(iovec_done) struct iovec public_blob = {}, private_blob = {};
6450
6451 r = tpm2_marshal_private(private, &private_blob.iov_base, &private_blob.iov_len);
6452 if (r < 0)
6453 return r;
6454
6455 r = tpm2_marshal_public(public, &public_blob.iov_base, &public_blob.iov_len);
6456 if (r < 0)
6457 return r;
6458
6459 if (ret_public)
6460 *ret_public = TAKE_STRUCT(public_blob);
6461 if (ret_private)
6462 *ret_private = TAKE_STRUCT(private_blob);
6463
6464 return 0;
6465 }
6466
6467 int tpm2_unseal_data(
6468 Tpm2Context *c,
6469 const struct iovec *public_blob,
6470 const struct iovec *private_blob,
6471 const Tpm2Handle *primary_handle,
6472 const Tpm2Handle *policy_session,
6473 const Tpm2Handle *encryption_session,
6474 struct iovec *ret_data) {
6475
6476 TSS2_RC rc;
6477 int r;
6478
6479 assert(c);
6480 assert(public_blob);
6481 assert(private_blob);
6482 assert(primary_handle);
6483 assert(ret_data);
6484
6485 TPM2B_PUBLIC public;
6486 r = tpm2_unmarshal_public(public_blob->iov_base, public_blob->iov_len, &public);
6487 if (r < 0)
6488 return r;
6489
6490 TPM2B_PRIVATE private;
6491 r = tpm2_unmarshal_private(private_blob->iov_base, private_blob->iov_len, &private);
6492 if (r < 0)
6493 return r;
6494
6495 _cleanup_(tpm2_handle_freep) Tpm2Handle *what = NULL;
6496 r = tpm2_load(c, primary_handle, NULL, &public, &private, &what);
6497 if (r < 0)
6498 return r;
6499
6500 _cleanup_(tpm2b_sensitive_data_erase_and_esys_freep) TPM2B_SENSITIVE_DATA* unsealed = NULL;
6501 rc = sym_Esys_Unseal(
6502 c->esys_context,
6503 what->esys_handle,
6504 policy_session ? policy_session->esys_handle : ESYS_TR_NONE,
6505 encryption_session ? encryption_session->esys_handle : ESYS_TR_NONE,
6506 ESYS_TR_NONE,
6507 &unsealed);
6508 if (rc == TPM2_RC_PCR_CHANGED)
6509 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE),
6510 "PCR changed while unsealing.");
6511 if (rc != TSS2_RC_SUCCESS)
6512 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6513 "Failed to unseal data: %s", sym_Tss2_RC_Decode(rc));
6514
6515 _cleanup_(iovec_done) struct iovec d = {
6516 .iov_base = memdup(unsealed->buffer, unsealed->size),
6517 .iov_len = unsealed->size,
6518 };
6519 if (!d.iov_base)
6520 return log_oom_debug();
6521
6522 *ret_data = TAKE_STRUCT(d);
6523 return 0;
6524 }
6525 #endif /* HAVE_TPM2 */
6526
6527 int tpm2_list_devices(bool legend, bool quiet) {
6528 #if HAVE_TPM2
6529 _cleanup_(table_unrefp) Table *t = NULL;
6530 _cleanup_closedir_ DIR *d = NULL;
6531 int r;
6532
6533 r = dlopen_tpm2(LOG_ERR);
6534 if (r < 0)
6535 return r;
6536
6537 t = table_new("path", "device", "driver");
6538 if (!t)
6539 return log_oom();
6540
6541 table_set_header(t, legend);
6542
6543 d = opendir("/sys/class/tpmrm");
6544 if (!d) {
6545 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno, "Failed to open %s: %m", "/sys/class/tpmrm");
6546 if (errno != ENOENT)
6547 return -errno;
6548 } else {
6549 for (;;) {
6550 _cleanup_free_ char *device_path = NULL, *device = NULL, *driver_path = NULL, *driver = NULL, *node = NULL;
6551 struct dirent *de;
6552
6553 de = readdir_no_dot(d);
6554 if (!de)
6555 break;
6556
6557 device_path = path_join("/sys/class/tpmrm", de->d_name, "device");
6558 if (!device_path)
6559 return log_oom();
6560
6561 r = readlink_malloc(device_path, &device);
6562 if (r < 0)
6563 log_debug_errno(r, "Failed to read device symlink %s, ignoring: %m", device_path);
6564 else {
6565 driver_path = path_join(device_path, "driver");
6566 if (!driver_path)
6567 return log_oom();
6568
6569 r = readlink_malloc(driver_path, &driver);
6570 if (r < 0)
6571 log_debug_errno(r, "Failed to read driver symlink %s, ignoring: %m", driver_path);
6572 }
6573
6574 node = path_join("/dev", de->d_name);
6575 if (!node)
6576 return log_oom();
6577
6578 r = table_add_many(
6579 t,
6580 TABLE_PATH, node,
6581 TABLE_STRING, device ? last_path_component(device) : NULL,
6582 TABLE_STRING, driver ? last_path_component(driver) : NULL);
6583 if (r < 0)
6584 return table_log_add_error(r);
6585 }
6586 }
6587
6588 if (table_isempty(t) && !quiet) {
6589 log_info("No suitable TPM2 devices found.");
6590 return 0;
6591 }
6592
6593 return table_print_or_warn(t);
6594 #else
6595 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
6596 "TPM2 not supported on this build.");
6597 #endif
6598 }
6599
6600 int tpm2_find_device_auto(char **ret) {
6601 #if HAVE_TPM2
6602 _cleanup_closedir_ DIR *d = NULL;
6603 int r;
6604
6605 r = dlopen_tpm2(LOG_DEBUG);
6606 if (r < 0)
6607 return r;
6608
6609 d = opendir("/sys/class/tpmrm");
6610 if (!d) {
6611 log_debug_errno(errno, "Failed to open %s: %m", "/sys/class/tpmrm");
6612 if (errno != ENOENT)
6613 return -errno;
6614 } else {
6615 _cleanup_free_ char *node = NULL;
6616
6617 for (;;) {
6618 struct dirent *de;
6619
6620 de = readdir_no_dot(d);
6621 if (!de)
6622 break;
6623
6624 if (node)
6625 return log_debug_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
6626 "More than one TPM2 (tpmrm) device found.");
6627
6628 node = path_join("/dev", de->d_name);
6629 if (!node)
6630 return log_oom_debug();
6631 }
6632
6633 if (node) {
6634 *ret = TAKE_PTR(node);
6635 return 0;
6636 }
6637 }
6638
6639 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV), "No TPM2 (tpmrm) device found.");
6640 #else
6641 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
6642 "TPM2 not supported on this build.");
6643 #endif
6644 }
6645
6646 #if HAVE_TPM2
6647 const uint16_t tpm2_hash_algorithms[] = {
6648 TPM2_ALG_SHA1,
6649 TPM2_ALG_SHA256,
6650 TPM2_ALG_SHA384,
6651 TPM2_ALG_SHA512,
6652 0,
6653 };
6654
6655 assert_cc(ELEMENTSOF(tpm2_hash_algorithms) == TPM2_N_HASH_ALGORITHMS + 1);
6656
6657 static size_t tpm2_hash_algorithm_index(uint16_t algorithm) {
6658 for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++)
6659 if (tpm2_hash_algorithms[i] == algorithm)
6660 return i;
6661
6662 return SIZE_MAX;
6663 }
6664
6665 static int json_dispatch_tpm2_algorithm(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
6666 uint16_t *algorithm = ASSERT_PTR(userdata);
6667 int r;
6668
6669 r = tpm2_hash_alg_from_string(sd_json_variant_string(variant));
6670 if (r < 0 || tpm2_hash_algorithm_index(r) == SIZE_MAX)
6671 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "Invalid hash algorithm: %s", sd_json_variant_string(variant));
6672
6673 *algorithm = r;
6674 return 0;
6675 }
6676
6677 static const char* tpm2_userspace_event_type_table[_TPM2_USERSPACE_EVENT_TYPE_MAX] = {
6678 [TPM2_EVENT_PHASE] = "phase",
6679 [TPM2_EVENT_FILESYSTEM] = "filesystem",
6680 [TPM2_EVENT_VOLUME_KEY] = "volume-key",
6681 [TPM2_EVENT_MACHINE_ID] = "machine-id",
6682 [TPM2_EVENT_PRODUCT_ID] = "product-id",
6683 [TPM2_EVENT_KEYSLOT] = "keyslot",
6684 [TPM2_EVENT_NVPCR_INIT] = "nvpcr-init",
6685 [TPM2_EVENT_NVPCR_SEPARATOR] = "nvpcr-separator",
6686 [TPM2_EVENT_DM_VERITY] = "dm-verity",
6687 [TPM2_EVENT_IMDS_USERDATA] = "imds-userdata",
6688 [TPM2_EVENT_OS_SEPARATOR] = "os-separator",
6689 [TPM2_EVENT_LOGIN] = "login",
6690 };
6691
6692 DEFINE_STRING_TABLE_LOOKUP(tpm2_userspace_event_type, Tpm2UserspaceEventType);
6693
6694 const char* tpm2_userspace_log_path(void) {
6695 return secure_getenv("SYSTEMD_MEASURE_LOG_USERSPACE") ?: "/run/log/systemd/tpm2-measure.log";
6696 }
6697
6698 const char* tpm2_firmware_log_path(void) {
6699 return secure_getenv("SYSTEMD_MEASURE_LOG_FIRMWARE") ?: "/sys/kernel/security/tpm0/binary_bios_measurements";
6700 }
6701
6702 #if HAVE_OPENSSL
6703 static int tpm2_userspace_log_open(void) {
6704 _cleanup_close_ int fd = -EBADF;
6705 const char *e;
6706 int r;
6707
6708 e = tpm2_userspace_log_path();
6709 (void) mkdir_parents(e, 0755);
6710
6711 /* We use access mode 0600 here (even though the measurements should not strictly be confidential),
6712 * because we use BSD file locking on it, and if anyone but root can access the file they can also
6713 * lock it, which we want to avoid. */
6714 fd = open(e, O_CREAT|O_WRONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
6715 if (fd < 0)
6716 return log_debug_errno(errno, "Failed to open TPM log file '%s' for writing, ignoring: %m", e);
6717
6718 if (flock(fd, LOCK_EX) < 0)
6719 return log_debug_errno(errno, "Failed to lock TPM log file '%s', ignoring: %m", e);
6720
6721 r = fd_verify_regular(fd);
6722 if (r < 0)
6723 return log_debug_errno(r, "TPM log file '%s' is not regular, ignoring: %m", e);
6724
6725 return TAKE_FD(fd);
6726 }
6727
6728 static int tpm2_userspace_log_dirty(int fd) {
6729 struct stat st;
6730
6731 if (fd < 0) /* Apparently tpm2_local_log_open() failed earlier, let's not complain again */
6732 return 0;
6733
6734 /* We set the sticky bit when we are about to append to the log file. We'll unset it afterwards
6735 * again. If we manage to take a lock on a file that has it set we know we didn't write it fully and
6736 * it is corrupted. Ideally we'd like to use user xattrs for this, but unfortunately tmpfs (which is
6737 * our assumed backend fs) doesn't know user xattrs. */
6738
6739 if (fstat(fd, &st) < 0)
6740 return log_debug_errno(errno, "Failed to fstat TPM log file, ignoring: %m");
6741
6742 if (st.st_mode & S_ISVTX)
6743 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "TPM log file aborted, ignoring.");
6744
6745 if (fchmod(fd, 0600 | S_ISVTX) < 0)
6746 return log_debug_errno(errno, "Failed to chmod() TPM log file, ignoring: %m");
6747
6748 return 0;
6749 }
6750
6751 static int tpm2_userspace_log_clean(int fd) {
6752 int r;
6753
6754 if (fd < 0) /* Apparently tpm2_local_log_open() failed earlier, let's not complain again */
6755 return 0;
6756
6757 if (fsync(fd) < 0)
6758 return log_debug_errno(errno, "Failed to sync JSON data: %m");
6759
6760 /* Unset S_ISVTX again */
6761 if (fchmod(fd, 0600) < 0)
6762 return log_debug_errno(errno, "Failed to chmod() TPM log file, ignoring: %m");
6763
6764 r = fsync_full(fd);
6765 if (r < 0)
6766 return log_debug_errno(r, "Failed to sync JSON log: %m");
6767
6768 return 0;
6769 }
6770
6771 static int tpm2_userspace_log(
6772 int fd,
6773 unsigned pcr_index,
6774 uint32_t nv_index,
6775 const char *nv_index_name,
6776 const TPML_DIGEST_VALUES *values,
6777 Tpm2UserspaceEventType event_type,
6778 const char *description) {
6779
6780 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL, *array = NULL;
6781 _cleanup_free_ char *f = NULL;
6782 sd_id128_t boot_id;
6783 int r;
6784
6785 assert(values);
6786 assert(values->count > 0);
6787
6788 /* We maintain a local PCR measurement log. This implements a subset of the TCG Canonical Event Log
6789 * Format – the JSON flavour –
6790 * (https://trustedcomputinggroup.org/resource/canonical-event-log-format/), but departs in certain
6791 * ways from it, specifically:
6792 *
6793 * - We don't write out a recnum. It's a bit too vaguely defined which means we'd have to read
6794 * through the whole logs (include firmware logs) before knowing what the next value is we should
6795 * use. Hence we simply don't write this out as append-time, and instead expect a consumer to add
6796 * it in when it uses the data.
6797 *
6798 * - We write this out in RFC 7464 application/json-seq rather than as a JSON array. Writing this as
6799 * JSON array would mean that for each appending we'd have to read the whole log file fully into
6800 * memory before writing it out again. We prefer a strictly append-only write pattern however. (RFC
6801 * 7464 is what jq --seq eats.) Conversion into a proper JSON array is trivial.
6802 *
6803 * It should be possible to convert this format in a relatively straight-forward way into the
6804 * official TCG Canonical Event Log Format on read, by simply adding in a few more fields that can be
6805 * determined from the full dataset.
6806 *
6807 * We set the 'content_type' field to "systemd" to make clear this data is generated by us, and
6808 * include various interesting fields in the 'content' subobject, including a CLOCK_BOOTTIME
6809 * timestamp which can be used to order this measurement against possibly other measurements
6810 * independently done by other subsystems on the system.
6811 */
6812
6813 if (fd < 0) /* Apparently tpm2_local_log_open() failed earlier, let's not complain again */
6814 return 0;
6815
6816 r = dlopen_libcrypto(LOG_DEBUG);
6817 if (r < 0)
6818 return r;
6819
6820 for (size_t i = 0; i < values->count; i++) {
6821 const EVP_MD *implementation;
6822 const char *a;
6823
6824 assert_se(a = tpm2_hash_alg_to_string(values->digests[i].hashAlg));
6825 assert_se(implementation = sym_EVP_get_digestbyname(a));
6826
6827 r = sd_json_variant_append_arraybo(
6828 &array,
6829 SD_JSON_BUILD_PAIR_STRING("hashAlg", a),
6830 SD_JSON_BUILD_PAIR_HEX("digest", &values->digests[i].digest, sym_EVP_MD_get_size(implementation)));
6831 if (r < 0)
6832 return log_debug_errno(r, "Failed to append digest object to JSON array: %m");
6833 }
6834
6835 assert(array);
6836
6837 r = sd_id128_get_boot(&boot_id);
6838 if (r < 0)
6839 return log_debug_errno(r, "Failed to acquire boot ID: %m");
6840
6841 r = sd_json_buildo(
6842 &v,
6843 SD_JSON_BUILD_PAIR_CONDITION(pcr_index != UINT_MAX, "pcr", SD_JSON_BUILD_UNSIGNED(pcr_index)),
6844 SD_JSON_BUILD_PAIR_CONDITION(nv_index != UINT32_MAX, "nv_index", SD_JSON_BUILD_UNSIGNED(nv_index)),
6845 SD_JSON_BUILD_PAIR_VARIANT("digests", array),
6846 SD_JSON_BUILD_PAIR_STRING("content_type", "systemd"),
6847 SD_JSON_BUILD_PAIR("content", SD_JSON_BUILD_OBJECT(
6848 SD_JSON_BUILD_PAIR_CONDITION(!!nv_index_name, "nvIndexName", SD_JSON_BUILD_STRING(nv_index_name)),
6849 SD_JSON_BUILD_PAIR_CONDITION(!!description, "string", SD_JSON_BUILD_STRING(description)),
6850 SD_JSON_BUILD_PAIR_ID128("bootId", boot_id),
6851 SD_JSON_BUILD_PAIR_UNSIGNED("timestamp", now(CLOCK_BOOTTIME)),
6852 SD_JSON_BUILD_PAIR_CONDITION(event_type >= 0, "eventType", SD_JSON_BUILD_STRING(tpm2_userspace_event_type_to_string(event_type))))));
6853 if (r < 0)
6854 return log_debug_errno(r, "Failed to build log record JSON: %m");
6855
6856 r = sd_json_variant_format(v, SD_JSON_FORMAT_SEQ, &f);
6857 if (r < 0)
6858 return log_debug_errno(r, "Failed to format JSON: %m");
6859
6860 if (lseek(fd, 0, SEEK_END) < 0)
6861 return log_debug_errno(errno, "Failed to seek to end of JSON log: %m");
6862
6863 r = loop_write(fd, f, SIZE_MAX);
6864 if (r < 0)
6865 return log_debug_errno(r, "Failed to write JSON data to log: %m");
6866
6867 r = tpm2_userspace_log_clean(fd);
6868 if (r < 0)
6869 return r;
6870
6871 return 1;
6872 }
6873 #endif
6874
6875 int tpm2_pcr_extend_bytes(
6876 Tpm2Context *c,
6877 char **banks,
6878 unsigned pcr_index,
6879 const struct iovec *data,
6880 const struct iovec *secret,
6881 Tpm2UserspaceEventType event_type,
6882 const char *description) {
6883
6884 #if HAVE_OPENSSL
6885 _cleanup_close_ int log_fd = -EBADF;
6886 TPML_DIGEST_VALUES values = {};
6887 TSS2_RC rc;
6888 int r;
6889
6890 assert(c);
6891 assert(iovec_is_valid(data));
6892 assert(iovec_is_valid(secret));
6893
6894 if (pcr_index >= TPM2_PCRS_MAX)
6895 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Can't measure into unsupported PCR %u, refusing.", pcr_index);
6896
6897 if (!iovec_is_set(data))
6898 data = &iovec_empty;
6899
6900 if (strv_isempty(banks))
6901 return 0;
6902
6903 r = dlopen_libcrypto(LOG_DEBUG);
6904 if (r < 0)
6905 return r;
6906
6907 STRV_FOREACH(bank, banks) {
6908 const EVP_MD *implementation;
6909 int id;
6910
6911 assert_se(implementation = sym_EVP_get_digestbyname(*bank));
6912
6913 if (values.count >= ELEMENTSOF(values.digests))
6914 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Too many banks selected.");
6915
6916 if ((size_t) sym_EVP_MD_get_size(implementation) > sizeof(values.digests[values.count].digest))
6917 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Hash result too large for TPM2.");
6918
6919 id = tpm2_hash_alg_from_string(sym_EVP_MD_get0_name(implementation));
6920 if (id < 0)
6921 return log_debug_errno(id, "Can't map hash name to TPM2.");
6922
6923 values.digests[values.count].hashAlg = id;
6924
6925 /* So here's a twist: sometimes we want to measure secrets (e.g. root file system volume
6926 * key), but we'd rather not leak a literal hash of the secret to the TPM (given that the
6927 * wire is unprotected, and some other subsystem might use the simple, literal hash of the
6928 * secret for other purposes, maybe because it needs a shorter secret derived from it for
6929 * some unrelated purpose, who knows). Hence we instead measure an HMAC signature of a
6930 * private non-secret string instead. */
6931 if (iovec_is_set(secret) > 0) {
6932 if (!sym_HMAC(implementation, secret->iov_base, secret->iov_len, data->iov_base, data->iov_len, (unsigned char*) &values.digests[values.count].digest, NULL))
6933 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to calculate HMAC of data to measure.");
6934 } else if (sym_EVP_Digest(data->iov_base, data->iov_len, (unsigned char*) &values.digests[values.count].digest, NULL, implementation, NULL) != 1)
6935 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to hash data to measure.");
6936
6937 values.count++;
6938 }
6939
6940 /* Open + lock the log file *before* we start measuring, so that no one else can come between our log
6941 * and our measurement and change either */
6942 log_fd = tpm2_userspace_log_open();
6943
6944 (void) tpm2_userspace_log_dirty(log_fd);
6945 rc = sym_Esys_PCR_Extend(
6946 c->esys_context,
6947 ESYS_TR_PCR0 + pcr_index,
6948 ESYS_TR_PASSWORD,
6949 ESYS_TR_NONE,
6950 ESYS_TR_NONE,
6951 &values);
6952 if (rc != TSS2_RC_SUCCESS)
6953 return log_debug_errno(
6954 SYNTHETIC_ERRNO(ENOTRECOVERABLE),
6955 "Failed to measure into PCR %u: %s",
6956 pcr_index,
6957 sym_Tss2_RC_Decode(rc));
6958
6959 /* Now, write what we just extended to the log, too. */
6960 (void) tpm2_userspace_log(
6961 log_fd,
6962 pcr_index,
6963 /* nv_index= */ UINT32_MAX,
6964 /* nv_index_name= */ NULL,
6965 &values,
6966 event_type,
6967 description);
6968
6969 return 0;
6970 #else /* HAVE_OPENSSL */
6971 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
6972 #endif
6973 }
6974
6975 typedef struct NvPCRData {
6976 char *name;
6977 uint16_t algorithm;
6978 uint32_t nv_index;
6979 uint64_t priority;
6980 } NvPCRData;
6981
6982 static void nvpcr_data_done(NvPCRData *d) {
6983 assert(d);
6984
6985 free(d->name);
6986 }
6987
6988 static int nvpcr_data_load(const char *name, NvPCRData *ret) {
6989 int r;
6990
6991 assert(ret);
6992
6993 if (!tpm2_nvpcr_name_is_valid(name))
6994 return -EINVAL;
6995
6996 const char *fname = strjoina(name, ".nvpcr");
6997
6998 _cleanup_free_ char *path = NULL;
6999 _cleanup_fclose_ FILE *f = NULL;
7000 r = search_and_fopen_nulstr(fname, "re", /* root= */ NULL, CONF_PATHS_NULSTR("nvpcr"), &f, &path);
7001 if (r < 0)
7002 return r;
7003
7004 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
7005 r = sd_json_parse_file(
7006 f,
7007 path,
7008 /* flags= */ 0,
7009 &v,
7010 /* reterr_line= */ NULL,
7011 /* reterr_column= */ NULL);
7012 if (r < 0)
7013 return log_debug_errno(r, "Failed to load '%s': %m", path);
7014
7015 static const sd_json_dispatch_field dispatch_table[] = {
7016 { "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(NvPCRData, name), SD_JSON_MANDATORY },
7017 { "algorithm", _SD_JSON_VARIANT_TYPE_INVALID, json_dispatch_tpm2_algorithm, offsetof(NvPCRData, algorithm), 0 },
7018 { "nvIndex", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint32, offsetof(NvPCRData, nv_index), SD_JSON_MANDATORY },
7019 { "priority", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, offsetof(NvPCRData, priority), 0 },
7020 {},
7021 };
7022
7023 _cleanup_(nvpcr_data_done) NvPCRData p = {
7024 .algorithm = TPM2_ALG_SHA256,
7025 .priority = TPM2_NVPCR_PRIORITY_DEFAULT,
7026 };
7027 r = sd_json_dispatch(v, dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &p);
7028 if (r < 0)
7029 return r;
7030
7031 if (!streq_ptr(p.name, name))
7032 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "NvPCR name doesn't match filename, refusing.");
7033
7034 *ret = TAKE_STRUCT(p);
7035 return 0;
7036 }
7037
7038 int tpm2_nvpcr_get_index(const char *name, uint32_t *ret_nv_index, uint64_t *ret_priority) {
7039 int r;
7040
7041 _cleanup_(nvpcr_data_done) NvPCRData p = {};
7042 r = nvpcr_data_load(name, &p);
7043 if (r < 0)
7044 return r;
7045
7046 if (ret_nv_index)
7047 *ret_nv_index = p.nv_index;
7048 if (ret_priority)
7049 *ret_priority = p.priority;
7050
7051 return 0;
7052 }
7053
7054 int tpm2_nvpcr_extend_bytes(
7055 Tpm2Context *c,
7056 const Tpm2Handle *session,
7057 const char *name,
7058 const struct iovec *data,
7059 const struct iovec *secret,
7060 Tpm2UserspaceEventType event_type,
7061 const char *description) {
7062
7063 #if HAVE_OPENSSL
7064 _cleanup_close_ int log_fd = -EBADF;
7065 int r;
7066
7067 assert(c);
7068 assert(name);
7069 assert(iovec_is_valid(data));
7070 assert(iovec_is_valid(secret));
7071
7072 r = dlopen_libcrypto(LOG_DEBUG);
7073 if (r < 0)
7074 return r;
7075
7076 _cleanup_(nvpcr_data_done) NvPCRData p = {};
7077 r = nvpcr_data_load(name, &p);
7078 if (r < 0)
7079 return r;
7080
7081 /* Open + lock the log file *before* we start measuring, so that no one else can come between our log
7082 * and our measurement and change either */
7083 log_fd = tpm2_userspace_log_open();
7084
7085 /* Check if this NvPCR is already anchored */
7086 const char *anchor_fname = strjoina("/run/systemd/nvpcr/", name, ".anchor");
7087 if (faccessat(AT_FDCWD, anchor_fname, F_OK, AT_SYMLINK_NOFOLLOW) < 0) {
7088 if (errno != ENOENT)
7089 return log_debug_errno(errno, "Failed to check if '%s' exists: %m", anchor_fname);
7090
7091 return log_debug_errno(SYNTHETIC_ERRNO(ENETDOWN), "NvPCR '%s' not anchored yet, refusing.", name);
7092 }
7093
7094 const char *an = tpm2_hash_alg_to_string(p.algorithm);
7095 if (!an)
7096 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unsupported algorithm for NvPCR, refusing.");
7097
7098 const EVP_MD *implementation;
7099 assert_se(implementation = sym_EVP_get_digestbyname(an));
7100
7101 _cleanup_(iovec_done) struct iovec digest = {
7102 .iov_len = sym_EVP_MD_get_size(implementation),
7103 };
7104
7105 digest.iov_base = malloc(digest.iov_len);
7106 if (!digest.iov_base)
7107 return log_oom_debug();
7108
7109 if (!iovec_is_set(data))
7110 data = &iovec_empty;
7111
7112 if (iovec_is_set(secret)) {
7113 if (!sym_HMAC(implementation, secret->iov_base, secret->iov_len, data->iov_base, data->iov_len, digest.iov_base, NULL))
7114 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to calculate HMAC of data to measure.");
7115 } else if (sym_EVP_Digest(data->iov_base, data->iov_len, digest.iov_base, NULL, implementation, NULL) != 1)
7116 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to hash data to measure.");
7117
7118 _cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
7119 r = tpm2_index_to_handle(
7120 c,
7121 p.nv_index,
7122 session,
7123 /* ret_public= */ NULL,
7124 /* ret_name= */ NULL,
7125 /* ret_qname= */ NULL,
7126 &nv_handle);
7127 if (r < 0)
7128 return log_debug_errno(r, "Failed to acquire handle to NV index 0x%" PRIu32 ".", p.nv_index);
7129
7130 log_debug("Successfully acquired handle to existing NV index 0x%" PRIx32 ".", p.nv_index);
7131
7132 (void) tpm2_userspace_log_dirty(log_fd);
7133
7134 r = tpm2_extend_nvpcr_nv_index(
7135 c,
7136 p.nv_index,
7137 nv_handle,
7138 &digest);
7139 if (r < 0)
7140 return r;
7141
7142 TPML_DIGEST_VALUES digest_values = {
7143 .count = 1,
7144 .digests[0].hashAlg = p.algorithm,
7145 };
7146 memcpy(&digest_values.digests[0].digest, digest.iov_base, digest.iov_len);
7147
7148 /* Now, write what we just extended to the log, too. */
7149 (void) tpm2_userspace_log(
7150 log_fd,
7151 /* pcr_index= */ UINT_MAX,
7152 p.nv_index,
7153 name,
7154 &digest_values,
7155 event_type,
7156 description);
7157
7158 return 0;
7159 #else /* HAVE_OPENSSL */
7160 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
7161 #endif
7162 }
7163
7164 #if HAVE_OPENSSL
7165 static int tpm2_nvpcr_write_anchor_secret(
7166 const char *dir,
7167 const char *fname,
7168 const struct iovec *credential) {
7169
7170 int r;
7171
7172 assert(dir);
7173 assert(fname);
7174 assert(iovec_is_set(credential));
7175
7176 /* Writes the encrypted credential of the anchor secret to directory 'dir' and file 'fname' */
7177
7178 _cleanup_close_ int dfd = -EBADF;
7179 r = chase(dir, /* root= */ NULL, CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY, /* ret_path= */ NULL, &dfd);
7180 if (r < 0)
7181 return log_error_errno(r, "Failed to create '%s' directory: %m", dir);
7182
7183 _cleanup_free_ char *joined = path_join(dir, fname);
7184 if (!joined)
7185 return log_oom();
7186
7187 _cleanup_(iovec_done) struct iovec existing = {};
7188 r = read_full_file_full(
7189 dfd,
7190 fname,
7191 /* offset= */ UINT64_MAX,
7192 CREDENTIAL_ENCRYPTED_SIZE_MAX,
7193 READ_FULL_FILE_UNBASE64|READ_FULL_FILE_FAIL_WHEN_LARGER,
7194 /* bind_name= */ NULL,
7195 (char**) &existing.iov_base,
7196 &existing.iov_len);
7197 if (r < 0) {
7198 if (r != -ENOENT)
7199 return log_error_errno(r, "Failed to read '%s' file: %m", joined);
7200 } else if (iovec_equal(&existing, credential)) {
7201 log_debug("Anchor secret file '%s' already matches expectations, not updating.", joined);
7202 return 0;
7203 } else
7204 log_notice("Anchor secret file '%s' different from current anchor secret, updating.", joined);
7205
7206 r = write_base64_file_at(
7207 dfd,
7208 fname,
7209 credential,
7210 WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_SYNC);
7211 if (r < 0)
7212 return log_error_errno(r, "Failed to write anchor secret file to '%s': %m", joined);
7213
7214 log_info("Successfully written anchor secret to '%s'.", joined);
7215 return 1;
7216 }
7217
7218 static int tpm2_nvpcr_write_anchor_secret_to_var(const struct iovec *credential) {
7219 return tpm2_nvpcr_write_anchor_secret("/var/lib/systemd/nvpcr", "nvpcr-anchor.cred", credential);
7220 }
7221
7222 static int tpm2_nvpcr_write_anchor_secret_to_boot(const struct iovec *credential) {
7223 int r;
7224
7225 assert(iovec_is_set(credential));
7226
7227 _cleanup_free_ char *dir = NULL;
7228 r = get_global_boot_credentials_path(&dir);
7229 if (r < 0)
7230 return r;
7231 if (r == 0) {
7232 log_debug("No XBOOTLDR/ESP partition found, not writing boot anchor secret file.");
7233 return 0;
7234 }
7235
7236 sd_id128_t machine_id;
7237 r = sd_id128_get_machine(&machine_id);
7238 if (r < 0)
7239 return log_error_errno(r, "Failed to read machine ID: %m");
7240
7241 BootEntryTokenType entry_token_type = BOOT_ENTRY_TOKEN_AUTO;
7242 _cleanup_free_ char *entry_token = NULL;
7243 r = boot_entry_token_ensure(
7244 /* root= */ NULL,
7245 /* conf_root= */ NULL,
7246 machine_id,
7247 /* machine_id_is_random= */ false,
7248 &entry_token_type,
7249 &entry_token);
7250 if (r < 0)
7251 return r;
7252
7253 _cleanup_free_ char *fname = strjoin("nvpcr-anchor.", entry_token, ".cred");
7254 if (!fname)
7255 return log_oom();
7256
7257 if (!filename_is_valid(fname))
7258 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Credential name '%s' would not be a valid file name, refusing.", fname);
7259
7260 return tpm2_nvpcr_write_anchor_secret(dir, fname, credential);
7261 }
7262
7263 static int tpm2_nvpcr_acquire_anchor_secret_from_var(struct iovec *ret_credential) {
7264 int r;
7265
7266 assert(ret_credential);
7267
7268 r = read_full_file_full(
7269 AT_FDCWD,
7270 "/var/lib/systemd/nvpcr/nvpcr-anchor.cred",
7271 /* offset= */ UINT64_MAX,
7272 CREDENTIAL_ENCRYPTED_SIZE_MAX,
7273 READ_FULL_FILE_UNBASE64|READ_FULL_FILE_FAIL_WHEN_LARGER|READ_FULL_FILE_VERIFY_REGULAR,
7274 /* bind_name= */ NULL,
7275 (char**) &ret_credential->iov_base,
7276 &ret_credential->iov_len);
7277 if (r == -ENOENT) {
7278 log_debug_errno(r, "No '/var/lib/systemd/nvpcr/nvpcr-anchor.cred' file.");
7279 *ret_credential = (struct iovec) {};
7280 return 0;
7281 }
7282 if (r < 0)
7283 return log_error_errno(r, "Failed to read '/var/lib/systemd/nvpcr/nvpcr-anchor.cred': %m");
7284
7285 return 1;
7286 }
7287
7288 static int tpm2_nvpcr_acquire_anchor_secret_from_credential(struct iovec *ret_credential, struct iovec *ret_secret) {
7289 int r;
7290
7291 assert(ret_credential);
7292 assert(ret_secret);
7293
7294 /* We need the anchor secret before the first measurement into an NvPCR. That means very early. Hence
7295 * we'll try to pass it into the system via the system credentials logic. Because we must expect a
7296 * multi-boot scenario it's hard to know which secret to use for which system. Hence we'll just try
7297 * to unlock all of the available ones, until we can decrypt one of them, and then we'll use that. */
7298
7299 const char *dp;
7300 r = get_encrypted_system_credentials_dir(&dp);
7301 if (r < 0)
7302 return log_error_errno(r, "Failed to get encrypted system credentials directory: %m");
7303
7304 /* Define early, so that it is definitely initialized, even if we take "goto not_found" branch below. */
7305 _cleanup_free_ DirectoryEntries *de = NULL;
7306
7307 _cleanup_close_ int dfd = open(dp, O_CLOEXEC|O_DIRECTORY);
7308 if (dfd < 0) {
7309 if (errno == ENOENT) {
7310 log_debug("No encrypted system credentials passed.");
7311 goto not_found;
7312 }
7313
7314 return log_error_errno(errno, "Failed to open system credentials directory.");
7315 }
7316
7317 r = readdir_all(dfd, RECURSE_DIR_IGNORE_DOT, &de);
7318 if (r < 0)
7319 return log_error_errno(r, "Failed to enumerate system credentials: %m");
7320
7321 FOREACH_ARRAY(i, de->entries, de->n_entries) {
7322 _cleanup_(iovec_done) struct iovec credential = {};
7323 struct dirent *d = *i;
7324
7325 if (!startswith_no_case(d->d_name, "nvpcr-anchor.")) /* VFAT is case-insensitive, hence don't be too strict here */
7326 continue;
7327
7328 r = read_full_file_full(
7329 dfd,
7330 d->d_name,
7331 /* offset= */ UINT64_MAX,
7332 CREDENTIAL_ENCRYPTED_SIZE_MAX,
7333 READ_FULL_FILE_UNBASE64|READ_FULL_FILE_FAIL_WHEN_LARGER,
7334 /* bind_name= */ NULL,
7335 (char**) &credential.iov_base,
7336 &credential.iov_len);
7337 if (r == -ENOENT)
7338 continue;
7339 if (r < 0) {
7340 log_warning_errno(r, "Failed to read anchor secret file '%s/%s', skipping: %m", dp, d->d_name);
7341 continue;
7342 }
7343
7344 r = decrypt_credential_and_warn(
7345 "nvpcr-anchor.cred",
7346 now(CLOCK_REALTIME),
7347 /* tpm2_device= */ NULL,
7348 /* tpm2_signature_path= */ NULL,
7349 /* uid= */ UID_INVALID,
7350 &credential,
7351 /* flags= */ 0,
7352 ret_secret);
7353 if (r < 0)
7354 log_debug_errno(r, "Failed to decrypt anchor secret file '%s' passed in as system credential, skipping: %m", d->d_name);
7355 else {
7356 *ret_credential = TAKE_STRUCT(credential);
7357 return 1;
7358 }
7359 }
7360
7361 log_debug("No suitable anchor secret passed as system credential.");
7362
7363 not_found:
7364 *ret_credential = (struct iovec) {};
7365 *ret_secret = (struct iovec) {};
7366 return 0;
7367 }
7368 #endif
7369
7370 #define ANCHOR_SECRET_SIZE 4096U
7371
7372 int tpm2_nvpcr_acquire_anchor_secret(struct iovec *ret, bool sync_secondary) {
7373 #if HAVE_OPENSSL
7374 _cleanup_close_ int fd = -EBADF;
7375 int r;
7376
7377 /* Acquires the anchor secret. We store it in a credential. The primary location (and primary truth)
7378 * for it is /run/systemd/nvpcr/ (i.e. volatile) [this file also doubles as lock file for the whole
7379 * logic]. But something has to place it there once. We do keep two copies of it: one in
7380 * /var/lib/systemd/nvpcr/, which is the persistent place for it, but which is only available at late
7381 * boot, potentially. And one in the ESP/XBOOTLDR which will make it available in the initrd
7382 * already via system credentials. */
7383
7384 _cleanup_close_ int dfd = open_mkdir("/run/systemd/nvpcr", O_CLOEXEC, 0755);
7385 if (dfd < 0)
7386 return log_error_errno(dfd, "Failed to open directory '/run/systemd/nvpcr': %m");
7387
7388 /* Use restrictive access mode of 0600. Not because the data inside needs to be kept inaccessible
7389 * (it's encrypted, hence that'd be fine), but because we need to lock it, and unprivileged clients
7390 * shouldn't be permitted to lock it. */
7391 fd = openat(dfd, "nvpcr-anchor.cred", O_RDWR|O_CLOEXEC|O_CREAT|O_NOCTTY, 0644);
7392 if (fd < 0)
7393 return log_error_errno(errno, "Failed to open anchor secret: %m");
7394
7395 r = lock_generic(fd, LOCK_BSD, LOCK_SH);
7396 if (r < 0)
7397 return log_error_errno(r, "Failed to lock anchor secret file: %m");
7398
7399 struct stat st;
7400 if (fstat(fd, &st) < 0)
7401 return log_error_errno(errno, "Failed to stat() anchor secret: %m");
7402
7403 r = stat_verify_regular(&st);
7404 if (r < 0)
7405 return log_error_errno(r, "Anchor secret file is not a regular file: %m");
7406
7407 if (st.st_size == 0) {
7408 /* If this is not initialized yet, then let's update the lock to an exclusive lock */
7409 r = lock_generic(fd, LOCK_BSD, LOCK_EX);
7410 if (r < 0)
7411 return log_error_errno(r, "Failed to upgrade lock on anchor secret file: %m");
7412
7413 /* Refresh size info, in case someone else has initialized it by now */
7414 if (fstat(fd, &st) < 0)
7415 return log_error_errno(errno, "Failed to stat() anchor secret: %m");
7416 }
7417
7418 bool copy_to_var = true, copy_to_boot = true;
7419
7420 _cleanup_(iovec_done) struct iovec credential = {};
7421 _cleanup_(iovec_done_erase) struct iovec secret = {};
7422 if (st.st_size == 0) { /* No initialized yet? */
7423
7424 /* Check if we have a secret in /var/lib/systemd/nvpcr/. If so, import the secret from there */
7425 if (!sync_secondary) {
7426 r = tpm2_nvpcr_acquire_anchor_secret_from_var(&credential);
7427 if (r < 0)
7428 return r;
7429 if (r > 0)
7430 copy_to_var = false; /* We read the secret from /var/, hence we don't have to copy it there. */
7431 }
7432
7433 /* Did the copy_source logic work? If not, let's search for the secret among passed system credentials. */
7434 if (!iovec_is_set(&credential)) {
7435 r = tpm2_nvpcr_acquire_anchor_secret_from_credential(&credential, &secret);
7436 if (r < 0)
7437 return r;
7438 if (r > 0)
7439 copy_to_boot = false; /* We read the secret from the boot partition, hence we don't have to copy it there. */
7440 }
7441
7442 /* Did the copy_source or system credential logic work? If not, let's generate a new random one */
7443 if (!iovec_is_set(&credential)) {
7444 r = crypto_random_bytes_allocate_iovec(ANCHOR_SECRET_SIZE, &secret);
7445 if (r < 0)
7446 return log_error_errno(r, "Failed to acquire entropy for anchor secret: %m");
7447
7448 r = encrypt_credential_and_warn(
7449 _CRED_AUTO_TPM2,
7450 "nvpcr-anchor.cred",
7451 now(CLOCK_REALTIME),
7452 /* not_after= */ USEC_INFINITY,
7453 /* tpm2_device= */ NULL,
7454 /* tpm2_hash_pcr_mask= */ 0,
7455 /* tpm2_pubkey_path= */ NULL,
7456 /* tpm2_pubkey_pcrs= */ UINT32_MAX,
7457 /* uid= */ UID_INVALID,
7458 &secret,
7459 /* flags= */ 0,
7460 &credential);
7461 if (r < 0)
7462 return r;
7463 }
7464
7465 _cleanup_free_ char *encoded = NULL;
7466 ssize_t n = base64mem_full(credential.iov_base, credential.iov_len, 79, &encoded);
7467 if (n < 0)
7468 return log_error_errno(n, "Failed to base64 encode credential: %m");
7469
7470 if (!strextend(&encoded, "\n"))
7471 return log_oom();
7472
7473 n++;
7474
7475 r = loop_write(fd, encoded, n);
7476 if (r < 0)
7477 return log_error_errno(r, "Failed to write anchor secret to disk: %m");
7478 } else {
7479 /* The file was already initialized? Then just read it. */
7480 r = read_full_file_full(
7481 fd,
7482 /* filename= */ NULL,
7483 /* offset= */ UINT64_MAX,
7484 CREDENTIAL_ENCRYPTED_SIZE_MAX,
7485 READ_FULL_FILE_UNBASE64|READ_FULL_FILE_FAIL_WHEN_LARGER,
7486 /* bind_name= */ NULL,
7487 (char**) &credential.iov_base,
7488 &credential.iov_len);
7489 if (r < 0)
7490 return log_error_errno(r, "Failed to read anchor secret file: %m");
7491 }
7492
7493 /* if we don't have the plaintext secret yet, then decrypt it now. */
7494 if (!iovec_is_set(&secret)) {
7495 assert(iovec_is_set(&credential));
7496
7497 r = decrypt_credential_and_warn(
7498 "nvpcr-anchor.cred",
7499 now(CLOCK_REALTIME),
7500 /* tpm2_device= */ NULL,
7501 /* tpm2_signature_path= */ NULL,
7502 /* uid= */ UID_INVALID,
7503 &credential,
7504 /* flags= */ 0,
7505 &secret);
7506 if (r < 0)
7507 return r;
7508 }
7509
7510 if (sync_secondary) {
7511 if (copy_to_var) {
7512 r = tpm2_nvpcr_write_anchor_secret_to_var(&credential);
7513 if (r < 0)
7514 return r;
7515 }
7516
7517 if (copy_to_boot) {
7518 r = tpm2_nvpcr_write_anchor_secret_to_boot(&credential);
7519 if (r < 0)
7520 return r;
7521 }
7522 }
7523
7524 if (ret)
7525 *ret = TAKE_STRUCT(secret);
7526 return 0;
7527 #else /* HAVE_OPENSSL */
7528 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
7529 #endif
7530 }
7531
7532 #if HAVE_OPENSSL
7533 static int tpm2_context_can_nvindex(Tpm2Context *c) {
7534 int r;
7535
7536 assert(c);
7537
7538 if (!streq_ptr(c->tcti_driver, "device")) {
7539 log_debug("Not checking udev database, because not using 'device' TCTI.");
7540 return 1;
7541 }
7542
7543 if (!c->tcti_param) {
7544 log_debug("No device specified, not checking udev database.");
7545 return 1;
7546 }
7547
7548 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
7549 r = sd_device_new_from_devname(&d, c->tcti_param);
7550 if (r < 0)
7551 return log_debug_errno(r, "Failed to acquire udev entry for device '%s': %m", c->tcti_param);
7552
7553 r = device_get_property_bool(d, "TPM2_BROKEN_NVPCR");
7554 if (r == -ENOENT) {
7555 log_device_debug_errno(d, r, "No TPM2_BROKEN_NVPCR property for '%s', assuming NvPCRs work.", c->tcti_param);
7556 return 1;
7557 }
7558 if (r < 0)
7559 return log_device_debug_errno(d, r, "Failed to query TPM2_BROKEN_NVPCR for '%s': %m", c->tcti_param);
7560 if (r > 0) {
7561 log_device_debug(d, "TPM2_BROKEN_NVPCR property for '%s' explicitly set, NvPCRs do not work.", c->tcti_param);
7562 return 0;
7563 }
7564
7565 log_device_debug(d, "TPM2_BROKEN_NVPCR property for '%s' explicitly set to false, hence NvPCRs work.", c->tcti_param);
7566 return 1;
7567 }
7568 #endif
7569
7570 int tpm2_nvpcr_initialize(
7571 Tpm2Context *c,
7572 const Tpm2Handle *session,
7573 const char *name,
7574 const struct iovec *anchor_secret) {
7575
7576 #if HAVE_OPENSSL
7577 TPM2_RC rc;
7578 int r;
7579
7580 assert(c);
7581 assert(name);
7582
7583 r = tpm2_context_can_nvindex(c);
7584 if (r < 0)
7585 return r;
7586 if (r == 0)
7587 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 device does not support NvPCRs, not initializing.");
7588
7589 _cleanup_(nvpcr_data_done) NvPCRData p = {};
7590 r = nvpcr_data_load(name, &p);
7591 if (r < 0)
7592 return r;
7593
7594 /* Open + lock the log file *before* we check for the *.anchor flag file. */
7595 _cleanup_close_ int log_fd = tpm2_userspace_log_open();
7596
7597 _cleanup_close_ int dfd = open_mkdir("/run/systemd/nvpcr", O_CLOEXEC, 0755);
7598 if (dfd < 0)
7599 return log_debug_errno(dfd, "Failed to open directory '/run/systemd/nvpcr': %m");
7600
7601 const char *anchor_fname = strjoina(name, ".anchor");
7602 if (faccessat(dfd, anchor_fname, F_OK, AT_SYMLINK_NOFOLLOW) < 0) {
7603 if (errno != ENOENT)
7604 return log_debug_errno(errno, "Failed to check if /run/systemd/nvpcr/%s exists: %m", anchor_fname);
7605 } else {
7606 log_debug("NvPCR '%s' is already anchored.", name);
7607 return 0;
7608 }
7609
7610 if (!iovec_is_set(anchor_secret))
7611 return log_debug_errno(SYNTHETIC_ERRNO(EUNATCH), "Need anchor secret.");
7612
7613 const char *an = tpm2_hash_alg_to_string(p.algorithm);
7614 if (!an)
7615 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unsupported algorithm for NvPCR, refusing.");
7616
7617 r = dlopen_libcrypto(LOG_DEBUG);
7618 if (r < 0)
7619 return r;
7620
7621 const EVP_MD *implementation;
7622 assert_se(implementation = sym_EVP_get_digestbyname(an));
7623
7624 int digest_size = sym_EVP_MD_get_size(implementation);
7625 assert_se(digest_size > 0);
7626
7627 if ((size_t) digest_size > sizeof_field(TPM2B_MAX_NV_BUFFER, buffer))
7628 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Hash function result too large for TPM, refusing.");
7629
7630 /* Put together a buffer consisting if the nvindex number and the NvPCR name, that we can calculate an HMAC() off, see below */
7631 size_t hmac_buffer_size = sizeof(le32_t) + strlen(p.name);
7632 _cleanup_free_ void* hmac_buffer = malloc(hmac_buffer_size);
7633 if (!hmac_buffer)
7634 return log_oom_debug();
7635
7636 *(le32_t*) hmac_buffer = htole32(p.nv_index);
7637 memcpy((uint8_t*) hmac_buffer + sizeof(le32_t), name, strlen(name));
7638
7639 TPM2B_MAX_NV_BUFFER buf = {
7640 .size = digest_size,
7641 };
7642 CLEANUP_ERASE(buf);
7643
7644 /* We measure HMAC(anchor_secret, name) into the NvPCR to anchor it on our secret. */
7645 if (!sym_HMAC(implementation, anchor_secret->iov_base, anchor_secret->iov_len, hmac_buffer, hmac_buffer_size, buf.buffer, NULL))
7646 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to calculate HMAC of data to measure.");
7647
7648 _cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
7649 r = tpm2_define_nvpcr_nv_index(
7650 c,
7651 session,
7652 p.nv_index,
7653 p.algorithm,
7654 &nv_handle);
7655 if (r < 0)
7656 return r;
7657
7658 log_debug("Successfully acquired handle to NV index 0x%" PRIx32 ".", p.nv_index);
7659
7660 tpm2_userspace_log_dirty(log_fd);
7661 rc = sym_Esys_NV_Extend(
7662 c->esys_context,
7663 /* authHandle= */ nv_handle->esys_handle,
7664 /* nvIndex= */ nv_handle->esys_handle,
7665 /* shandle1= */ ESYS_TR_PASSWORD,
7666 /* shandle2= */ ESYS_TR_NONE,
7667 /* shandle3= */ ESYS_TR_NONE,
7668 &buf);
7669 if (rc != TSS2_RC_SUCCESS)
7670 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
7671 "Failed to extend NV index: %s", sym_Tss2_RC_Decode(rc));
7672
7673 log_debug("Successfully extended NvPCR '%s' with anchor secret.", name);
7674
7675 /* Now pre-calculate the initial measurement of an "anchor" secret. This makes sure that others
7676 * cannot delete and reproduce the same fake PCR, unless they also know the "anchor" secret. */
7677 TPM2B_DIGEST start = { /* initialize to zero */
7678 .size = digest_size,
7679 };
7680 r = tpm2_digest_buffer(
7681 p.algorithm,
7682 &start,
7683 buf.buffer,
7684 buf.size,
7685 /* extend= */ true);
7686 if (r < 0)
7687 return log_debug_errno(r, "Failed to calculate initial value: %m");
7688
7689 /* Now create the anchor flag file */
7690 _cleanup_free_ char *h = hexmem(start.buffer, start.size);
7691 if (!h)
7692 return log_oom_debug();
7693
7694 r = write_string_file_at(dfd, anchor_fname, h, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
7695 if (r < 0)
7696 return log_debug_errno(r, "Failed to write anchor file: %m");
7697
7698 tpm2_userspace_log_clean(log_fd);
7699 log_fd = safe_close(log_fd);
7700
7701 /* Now also measure the initialization into PCR 9, so that there's a trace of it in regular PCRs. You
7702 * might wonder why PCR 9? Well, we have very few PCRs available, and PCR 9 appears to be the least
7703 * bad for this. It typically contains stuff that in our world is hard to predict anyway
7704 * (i.e. possibly some overly verbose Grub stuff, as well as all initrds – those generated on-the-fly
7705 * and those prepared beforehand – mangled into one), quite differently from all other PCRs we could
7706 * use. Moreover PCR 11 already contains most stuff from PCR 9, as it contains the same data
7707 * (i.e. initrds) in a more sensible fashion, clearly separated from on-the-fly generated ones. Note
7708 * that we only do all this measurement stuff if we are booted as UKI, and hence when PCR 11 is
7709 * available, but PCR 9 is not predictable. */
7710 _cleanup_strv_free_ char **banks = NULL;
7711 r = tpm2_get_good_pcr_banks_strv(c, UINT32_C(1) << TPM2_PCR_KERNEL_INITRD, &banks);
7712 if (r < 0)
7713 return log_error_errno(r, "Could not verify PCR banks: %m");
7714
7715 _cleanup_free_ char *word = NULL;
7716 if (asprintf(&word, "nvpcr-init:%s:0x%x:%s:%s", name, p.nv_index, tpm2_hash_alg_to_string(p.algorithm), h) < 0)
7717 return log_oom();
7718
7719 r = tpm2_pcr_extend_bytes(
7720 c,
7721 banks,
7722 TPM2_PCR_KERNEL_INITRD,
7723 &IOVEC_MAKE_STRING(word),
7724 /* secret= */ NULL,
7725 TPM2_EVENT_NVPCR_INIT,
7726 word);
7727 if (r < 0)
7728 return log_error_errno(r, "Could not extend PCR %i: %m", TPM2_PCR_KERNEL_INITRD);
7729
7730 return 1;
7731 #else /* HAVE_OPENSSL */
7732 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
7733 #endif
7734 }
7735
7736 int tpm2_nvpcr_read(
7737 Tpm2Context *c,
7738 const Tpm2Handle *session,
7739 const char *name,
7740 struct iovec *ret_value,
7741 uint32_t *ret_nv_index,
7742 uint64_t *ret_priority) {
7743
7744 #if HAVE_OPENSSL
7745 int r;
7746
7747 assert(c);
7748 assert(name);
7749
7750 if (!tpm2_nvpcr_name_is_valid(name))
7751 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Attempt to read from NvPCR with invalid name, refusing: %s", name);
7752
7753 _cleanup_(nvpcr_data_done) NvPCRData p = {};
7754 r = nvpcr_data_load(name, &p);
7755 if (r < 0)
7756 return r;
7757
7758 /* Check if the NvPCR is already anchored */
7759 const char *anchor_fname = strjoina("/run/systemd/nvpcr/", name, ".anchor");
7760 r = access_nofollow(anchor_fname, F_OK);
7761 if (r < 0) {
7762 if (r != -ENOENT)
7763 return log_debug_errno(r, "Failed to check if '%s' exists: %m", anchor_fname);
7764
7765 /* valid, but not anchored */
7766 *ret_value = (struct iovec) {};
7767 if (ret_nv_index)
7768 *ret_nv_index = p.nv_index;
7769 if (ret_priority)
7770 *ret_priority = p.priority;
7771
7772 return 0;
7773 }
7774
7775 _cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
7776 r = tpm2_index_to_handle(
7777 c,
7778 p.nv_index,
7779 session,
7780 /* ret_public= */ NULL,
7781 /* ret_name= */ NULL,
7782 /* ret_qname= */ NULL,
7783 &nv_handle);
7784 if (r < 0)
7785 return log_debug_errno(r, "Failed to acquire handle to NV index 0x%" PRIu32 ".", p.nv_index);
7786
7787 log_debug("Successfully acquired handle to NV index 0x%" PRIx32 ".", p.nv_index);
7788
7789 if (r > 0) {
7790 r = tpm2_read_nv_index(
7791 c,
7792 /* session= */ NULL,
7793 p.nv_index,
7794 nv_handle,
7795 ret_value);
7796 if (r < 0)
7797 return r;
7798
7799 r = 1;
7800 } else {
7801 *ret_value = (struct iovec) {};
7802 r = 0;
7803 }
7804
7805 if (ret_nv_index)
7806 *ret_nv_index = p.nv_index;
7807 if (ret_priority)
7808 *ret_priority = p.priority;
7809
7810 return r;
7811 #else /* HAVE_OPENSSL */
7812 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
7813 #endif
7814 }
7815
7816 TPM2B_DIGEST *tpm2_pcr_prediction_result_get_hash(Tpm2PCRPredictionResult *result, uint16_t alg) {
7817 size_t alg_idx;
7818
7819 assert(result);
7820
7821 alg_idx = tpm2_hash_algorithm_index(alg);
7822 if (alg_idx == SIZE_MAX) /* Algorithm not known? */
7823 return NULL;
7824
7825 if (result->hash[alg_idx].size <= 0) /* No hash value for this algorithm? */
7826 return NULL;
7827
7828 return result->hash + alg_idx;
7829 }
7830
7831 void tpm2_pcr_prediction_done(Tpm2PCRPrediction *p) {
7832 assert(p);
7833
7834 for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++)
7835 ordered_set_free(p->results[pcr]);
7836 }
7837
7838 static void tpm2_pcr_prediction_result_hash_func(const Tpm2PCRPredictionResult *banks, struct siphash *state) {
7839 assert(banks);
7840
7841 for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++)
7842 siphash24_compress_safe(banks->hash[i].buffer, banks->hash[i].size, state);
7843 }
7844
7845 static int tpm2_pcr_prediction_result_compare_func(const Tpm2PCRPredictionResult *a, const Tpm2PCRPredictionResult *b) {
7846 int r;
7847
7848 assert(a);
7849 assert(b);
7850
7851 for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
7852 r = memcmp_nn(a->hash[i].buffer, a->hash[i].size,
7853 b->hash[i].buffer, b->hash[i].size);
7854 if (r != 0)
7855 return r;
7856 }
7857
7858 return 0;
7859 }
7860
7861 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(
7862 tpm2_pcr_prediction_result_hash_ops,
7863 Tpm2PCRPredictionResult,
7864 tpm2_pcr_prediction_result_hash_func,
7865 tpm2_pcr_prediction_result_compare_func,
7866 Tpm2PCRPredictionResult,
7867 free);
7868
7869 static Tpm2PCRPredictionResult *find_prediction_result_by_algorithm(OrderedSet *set, Tpm2PCRPredictionResult *result, size_t alg_idx) {
7870 Tpm2PCRPredictionResult *f;
7871
7872 assert(result);
7873 assert(alg_idx != SIZE_MAX);
7874
7875 f = ordered_set_get(set, result); /* Full match? */
7876 if (f)
7877 return f;
7878
7879 /* If this doesn't match full, then see if there an entry that at least matches by the relevant
7880 * algorithm (we are fine if predictions are "incomplete" in some algorithms) */
7881
7882 ORDERED_SET_FOREACH(f, set)
7883 if (memcmp_nn(result->hash[alg_idx].buffer, result->hash[alg_idx].size,
7884 f->hash[alg_idx].buffer, f->hash[alg_idx].size) == 0)
7885 return f;
7886
7887 return NULL;
7888 }
7889
7890 bool tpm2_pcr_prediction_equal(
7891 Tpm2PCRPrediction *a,
7892 Tpm2PCRPrediction *b,
7893 uint16_t algorithm) {
7894
7895 if (a == b)
7896 return true;
7897 if (!a || !b)
7898 return false;
7899
7900 if (a->pcrs != b->pcrs)
7901 return false;
7902
7903 size_t alg_idx = tpm2_hash_algorithm_index(algorithm);
7904 if (alg_idx == SIZE_MAX)
7905 return false;
7906
7907 for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
7908 Tpm2PCRPredictionResult *banks;
7909
7910 ORDERED_SET_FOREACH(banks, a->results[pcr])
7911 if (!find_prediction_result_by_algorithm(b->results[pcr], banks, alg_idx))
7912 return false;
7913
7914 ORDERED_SET_FOREACH(banks, b->results[pcr])
7915 if (!find_prediction_result_by_algorithm(a->results[pcr], banks, alg_idx))
7916 return false;
7917 }
7918
7919 return true;
7920 }
7921
7922 int tpm2_pcr_prediction_to_json(
7923 const Tpm2PCRPrediction *prediction,
7924 uint16_t algorithm,
7925 sd_json_variant **ret) {
7926
7927 _cleanup_(sd_json_variant_unrefp) sd_json_variant *aj = NULL;
7928 int r;
7929
7930 assert(prediction);
7931 assert(ret);
7932
7933 for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
7934 _cleanup_(sd_json_variant_unrefp) sd_json_variant *vj = NULL;
7935 Tpm2PCRPredictionResult *banks;
7936
7937 if (!BIT_SET(prediction->pcrs, pcr))
7938 continue;
7939
7940 ORDERED_SET_FOREACH(banks, prediction->results[pcr]) {
7941
7942 TPM2B_DIGEST *hash = tpm2_pcr_prediction_result_get_hash(banks, algorithm);
7943 if (!hash)
7944 continue;
7945
7946 r = sd_json_variant_append_arrayb(
7947 &vj,
7948 SD_JSON_BUILD_HEX(hash->buffer, hash->size));
7949 if (r < 0)
7950 return log_error_errno(r, "Failed to append hash variant to JSON array: %m");
7951 }
7952
7953 if (!vj)
7954 continue;
7955
7956 r = sd_json_variant_append_arraybo(
7957 &aj,
7958 SD_JSON_BUILD_PAIR_INTEGER("pcr", pcr),
7959 SD_JSON_BUILD_PAIR_VARIANT("values", vj));
7960 if (r < 0)
7961 return log_error_errno(r, "Failed to append PCR variants to JSON array: %m");
7962 }
7963
7964 if (!aj) {
7965 r = sd_json_variant_new_array(&aj, NULL, 0);
7966 if (r < 0)
7967 return r;
7968 }
7969
7970 *ret = TAKE_PTR(aj);
7971 return 0;
7972 }
7973
7974 int tpm2_pcr_prediction_from_json(
7975 Tpm2PCRPrediction *prediction,
7976 uint16_t algorithm,
7977 sd_json_variant *aj) {
7978
7979 int r;
7980
7981 assert(prediction);
7982
7983 size_t alg_index = tpm2_hash_algorithm_index(algorithm);
7984 assert(alg_index < TPM2_N_HASH_ALGORITHMS);
7985
7986 if (!sd_json_variant_is_array(aj))
7987 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "PCR variant array is not an array.");
7988
7989 sd_json_variant *pcr;
7990 JSON_VARIANT_ARRAY_FOREACH(pcr, aj) {
7991 sd_json_variant *nr, *values;
7992
7993 nr = sd_json_variant_by_key(pcr, "pcr");
7994 if (!nr)
7995 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "PCR array entry lacks PCR index field");
7996
7997 if (!sd_json_variant_is_unsigned(nr) ||
7998 sd_json_variant_unsigned(nr) >= TPM2_PCRS_MAX)
7999 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "PCR array entry PCR index is not an integer in the range 0…23");
8000
8001 values = sd_json_variant_by_key(pcr, "values");
8002 if (!values)
8003 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "PCR array entry lacks values field");
8004
8005 if (!sd_json_variant_is_array(values))
8006 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "PCR array entry values field is not an array");
8007
8008 prediction->pcrs |= UINT32_C(1) << sd_json_variant_unsigned(nr);
8009
8010 sd_json_variant *v;
8011 JSON_VARIANT_ARRAY_FOREACH(v, values) {
8012 _cleanup_free_ void *buffer = NULL;
8013 size_t size;
8014
8015 r = sd_json_variant_unhex(v, &buffer, &size);
8016 if (r < 0)
8017 return log_error_errno(r, "Failed to decode PCR policy array hash value");
8018
8019 if (size <= 0)
8020 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PCR policy array hash value is zero.");
8021
8022 if (size > sizeof_field(TPM2B_DIGEST, buffer))
8023 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PCR policy array hash value is too large.");
8024
8025 _cleanup_free_ Tpm2PCRPredictionResult *banks = new0(Tpm2PCRPredictionResult, 1);
8026 if (!banks)
8027 return log_oom();
8028
8029 memcpy(banks->hash[alg_index].buffer, buffer, size);
8030 banks->hash[alg_index].size = size;
8031
8032 r = ordered_set_ensure_put(prediction->results + sd_json_variant_unsigned(nr), &tpm2_pcr_prediction_result_hash_ops, banks);
8033 if (r == -EEXIST) /* Let's allow duplicates */
8034 continue;
8035 if (r < 0)
8036 return log_error_errno(r, "Failed to insert result into set: %m");
8037
8038 TAKE_PTR(banks);
8039 }
8040 }
8041
8042 return 0;
8043 }
8044
8045 int tpm2_calculate_policy_super_pcr(
8046 Tpm2PCRPrediction *prediction,
8047 uint16_t algorithm,
8048 TPM2B_DIGEST *pcr_policy) {
8049
8050 int r;
8051
8052 assert_se(prediction);
8053 assert_se(pcr_policy);
8054
8055 /* Start with a zero policy if not specified otherwise. */
8056 TPM2B_DIGEST super_pcr_policy_digest = *pcr_policy;
8057
8058 /* First we look for all PCRs that have exactly one allowed hash value, and generate a single PolicyPCR policy from them */
8059 _cleanup_free_ Tpm2PCRValue *single_values = NULL;
8060 size_t n_single_values = 0;
8061 BIT_FOREACH(pcr, prediction->pcrs) {
8062 if (ordered_set_size(prediction->results[pcr]) != 1)
8063 continue;
8064
8065 log_debug("Including PCR %i in single value PolicyPCR expression", pcr);
8066
8067 Tpm2PCRPredictionResult *banks = ASSERT_PTR(ordered_set_first(prediction->results[pcr]));
8068
8069 TPM2B_DIGEST *hash = tpm2_pcr_prediction_result_get_hash(banks, algorithm);
8070 if (!hash)
8071 continue;
8072
8073 if (!GREEDY_REALLOC(single_values, n_single_values + 1))
8074 return -ENOMEM;
8075
8076 single_values[n_single_values++] = TPM2_PCR_VALUE_MAKE(pcr, algorithm, *hash);
8077 }
8078
8079 if (n_single_values > 0) {
8080 /* Evolve policy based on the expected PCR value for what we found. */
8081 r = tpm2_calculate_policy_pcr(
8082 single_values,
8083 n_single_values,
8084 &super_pcr_policy_digest);
8085 if (r < 0)
8086 return r;
8087 }
8088
8089 /* Now deal with the PCRs for which we have variants, i.e. more than one allowed values */
8090 for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
8091 _cleanup_free_ TPM2B_DIGEST *pcr_policy_digest_variants = NULL;
8092 size_t n_pcr_policy_digest_variants = 0;
8093 Tpm2PCRPredictionResult *banks;
8094
8095 if (!BIT_SET(prediction->pcrs, pcr))
8096 continue;
8097
8098 if (ordered_set_size(prediction->results[pcr]) <= 1) /* We only care for PCRs with 2 or more variants in this loop */
8099 continue;
8100
8101 if (ordered_set_size(prediction->results[pcr]) > 8)
8102 return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "PCR policies with more than 8 alternatives per PCR are currently not supported.");
8103
8104 ORDERED_SET_FOREACH(banks, prediction->results[pcr]) {
8105 /* Start from the super PCR policy from the previous PCR we looked at so far. */
8106 TPM2B_DIGEST pcr_policy_digest = super_pcr_policy_digest;
8107
8108 TPM2B_DIGEST *hash = tpm2_pcr_prediction_result_get_hash(banks, algorithm);
8109 if (!hash)
8110 continue;
8111
8112 /* Evolve it based on the expected PCR value for this PCR */
8113 r = tpm2_calculate_policy_pcr(
8114 &TPM2_PCR_VALUE_MAKE(
8115 pcr,
8116 algorithm,
8117 *hash),
8118 /* n_pcr_values= */ 1,
8119 &pcr_policy_digest);
8120 if (r < 0)
8121 return r;
8122
8123 /* Store away this new variant */
8124 if (!GREEDY_REALLOC(pcr_policy_digest_variants, n_pcr_policy_digest_variants + 1))
8125 return log_oom();
8126
8127 pcr_policy_digest_variants[n_pcr_policy_digest_variants++] = pcr_policy_digest;
8128
8129 log_debug("Calculated PCR policy variant %zu for PCR %" PRIu32, n_pcr_policy_digest_variants, pcr);
8130 }
8131
8132 assert_se(n_pcr_policy_digest_variants >= 2);
8133 assert_se(n_pcr_policy_digest_variants <= 8);
8134
8135 /* Now combine all our variant into one OR policy */
8136 r = tpm2_calculate_policy_or(
8137 pcr_policy_digest_variants,
8138 n_pcr_policy_digest_variants,
8139 &super_pcr_policy_digest);
8140 if (r < 0)
8141 return r;
8142
8143 log_debug("Combined %zu variants in OR policy.", n_pcr_policy_digest_variants);
8144 }
8145
8146 *pcr_policy = super_pcr_policy_digest;
8147 return 0;
8148 }
8149
8150 int tpm2_policy_super_pcr(
8151 Tpm2Context *c,
8152 const Tpm2Handle *session,
8153 const Tpm2PCRPrediction *prediction,
8154 uint16_t algorithm) {
8155
8156 int r;
8157
8158 assert_se(c);
8159 assert_se(session);
8160 assert_se(prediction);
8161
8162 TPM2B_DIGEST previous_policy_digest = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
8163
8164 uint32_t single_value_pcrs = 0;
8165
8166 /* Look for all PCRs that have only a singled allowed hash value, and synthesize a single PolicyPCR policy item for them */
8167 for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
8168 if (!BIT_SET(prediction->pcrs, pcr))
8169 continue;
8170
8171 if (ordered_set_size(prediction->results[pcr]) != 1)
8172 continue;
8173
8174 log_debug("Including PCR %" PRIu32 " in single value PolicyPCR expression", pcr);
8175
8176 single_value_pcrs |= UINT32_C(1) << pcr;
8177 }
8178
8179 if (single_value_pcrs != 0) {
8180 TPML_PCR_SELECTION pcr_selection;
8181 tpm2_tpml_pcr_selection_from_mask(single_value_pcrs, algorithm, &pcr_selection);
8182
8183 _cleanup_free_ TPM2B_DIGEST *current_policy_digest = NULL;
8184 r = tpm2_policy_pcr(
8185 c,
8186 session,
8187 &pcr_selection,
8188 &current_policy_digest);
8189 if (r == -EUCLEAN) {
8190 _cleanup_free_ char *j = NULL;
8191
8192 for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++)
8193 if (single_value_pcrs & (UINT32_C(1) << pcr))
8194 (void) strextendf_with_separator(&j, ", ", "%" PRIu32, pcr);
8195
8196 return log_error_errno(r, "Combined value for PCR(s) %s encoded in policy does not match the current TPM state. Either the system has been tempered with or the provided policy is incorrect.", strna(j));
8197 }
8198 if (r < 0)
8199 return log_error_errno(r, "Failed to submit PCR policy to TPM: %m");
8200
8201 previous_policy_digest = *current_policy_digest;
8202 }
8203
8204 for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
8205 size_t n_branches;
8206
8207 if (!BIT_SET(prediction->pcrs, pcr))
8208 continue;
8209
8210 n_branches = ordered_set_size(prediction->results[pcr]);
8211 if (n_branches < 1 || n_branches > 8)
8212 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Number of variants per PCR not in range 1…8");
8213
8214 if (n_branches == 1) /* Single choice PCRs are already covered by the loop above */
8215 continue;
8216
8217 log_debug("Submitting PCR/OR policy for PCR %" PRIu32, pcr);
8218
8219 TPML_PCR_SELECTION pcr_selection;
8220 tpm2_tpml_pcr_selection_from_mask(UINT32_C(1) << pcr, algorithm, &pcr_selection);
8221
8222 _cleanup_free_ TPM2B_DIGEST *current_policy_digest = NULL;
8223 r = tpm2_policy_pcr(
8224 c,
8225 session,
8226 &pcr_selection,
8227 &current_policy_digest);
8228 if (r == -EUCLEAN)
8229 return log_error_errno(r, "Value for PCR %" PRIu32 " encoded in policy does not match the current TPM state. Either the system has been tempered with or the provided policy is incorrect.", pcr);
8230 if (r < 0)
8231 return log_error_errno(r, "Failed to submit PCR policy to TPM: %m");
8232
8233 _cleanup_free_ TPM2B_DIGEST *branches = NULL;
8234 branches = new0(TPM2B_DIGEST, n_branches);
8235 if (!branches)
8236 return log_oom();
8237
8238 Tpm2PCRPredictionResult *banks;
8239 size_t i = 0;
8240 ORDERED_SET_FOREACH(banks, prediction->results[pcr]) {
8241 TPM2B_DIGEST pcr_policy_digest = previous_policy_digest;
8242
8243 TPM2B_DIGEST *hash = tpm2_pcr_prediction_result_get_hash(banks, algorithm);
8244 if (!hash)
8245 continue;
8246
8247 /* Evolve it based on the expected PCR value for this PCR */
8248 r = tpm2_calculate_policy_pcr(
8249 &TPM2_PCR_VALUE_MAKE(
8250 pcr,
8251 algorithm,
8252 *hash),
8253 /* n_pcr_values= */ 1,
8254 &pcr_policy_digest);
8255 if (r < 0)
8256 return log_error_errno(r, "Failed to calculate PolicyPCR: %m");
8257
8258 branches[i++] = pcr_policy_digest;
8259 }
8260
8261 assert_se(i == n_branches);
8262
8263 current_policy_digest = mfree(current_policy_digest);
8264 r = tpm2_policy_or(
8265 c,
8266 session,
8267 branches,
8268 n_branches,
8269 &current_policy_digest);
8270 if (r == -ENOANO)
8271 return log_error_errno(r, "None of the alternative values for PCR %" PRIu32 " encoded in policy match the current TPM state. Either the system has been tempered with or the provided policy is incorrect.", pcr);
8272 if (r < 0)
8273 return log_error_errno(r, "Failed to submit OR policy to TPM: %m");
8274
8275 previous_policy_digest = *current_policy_digest;
8276 }
8277
8278 return 0;
8279 }
8280
8281 void tpm2_pcrlock_policy_done(Tpm2PCRLockPolicy *data) {
8282 assert(data);
8283
8284 data->prediction_json = sd_json_variant_unref(data->prediction_json);
8285 tpm2_pcr_prediction_done(&data->prediction);
8286 iovec_done(&data->nv_handle);
8287 iovec_done(&data->nv_public);
8288 iovec_done(&data->srk_handle);
8289 iovec_done(&data->pin_public);
8290 iovec_done(&data->pin_private);
8291 }
8292
8293 int tpm2_pcrlock_search_file(const char *path, FILE **ret_file, char **ret_path) {
8294 static const char search[] =
8295 "/run/systemd\0"
8296 "/var/lib/systemd\0";
8297
8298 int r;
8299
8300 if (!path)
8301 path = "pcrlock.json";
8302
8303 r = search_and_fopen_nulstr(path, ret_file ? "re" : NULL, NULL, search, ret_file, ret_path);
8304 if (r < 0)
8305 return log_debug_errno(r, "Failed to find TPM2 pcrlock policy file '%s': %m", path);
8306
8307 return 0;
8308 }
8309
8310 int tpm2_pcrlock_policy_from_json(
8311 sd_json_variant *v,
8312 Tpm2PCRLockPolicy *ret_policy) {
8313
8314 /* We use a type check of _JSON_VARIANT_TYPE_INVALID for the integer fields to allow
8315 * json_dispatch_uint32() to parse strings as integers to work around the integer type weakness of
8316 * JSON's design. */
8317 static const sd_json_dispatch_field policy_dispatch[] = {
8318 { "pcrBank", SD_JSON_VARIANT_STRING, json_dispatch_tpm2_algorithm, offsetof(Tpm2PCRLockPolicy, algorithm), SD_JSON_MANDATORY },
8319 { "pcrValues", SD_JSON_VARIANT_ARRAY, sd_json_dispatch_variant, offsetof(Tpm2PCRLockPolicy, prediction_json), SD_JSON_MANDATORY },
8320 { "nvIndex", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint32, offsetof(Tpm2PCRLockPolicy, nv_index), SD_JSON_MANDATORY },
8321 { "nvHandle", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, offsetof(Tpm2PCRLockPolicy, nv_handle), SD_JSON_MANDATORY },
8322 { "nvPublic", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, offsetof(Tpm2PCRLockPolicy, nv_public), SD_JSON_MANDATORY },
8323 { "srkHandle", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, offsetof(Tpm2PCRLockPolicy, srk_handle), SD_JSON_MANDATORY },
8324 { "pinPublic", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, offsetof(Tpm2PCRLockPolicy, pin_public), SD_JSON_MANDATORY },
8325 { "pinPrivate", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, offsetof(Tpm2PCRLockPolicy, pin_private), SD_JSON_MANDATORY },
8326 {}
8327 };
8328
8329 _cleanup_(tpm2_pcrlock_policy_done) Tpm2PCRLockPolicy policy = {};
8330 int r;
8331
8332 assert(v);
8333 assert(ret_policy);
8334
8335 r = sd_json_dispatch(v, policy_dispatch, SD_JSON_LOG, &policy);
8336 if (r < 0)
8337 return r;
8338
8339 r = tpm2_pcr_prediction_from_json(&policy.prediction, policy.algorithm, policy.prediction_json);
8340 if (r < 0)
8341 return r;
8342
8343 *ret_policy = TAKE_STRUCT(policy);
8344 return 1;
8345 }
8346
8347 int tpm2_pcrlock_policy_load(
8348 const char *path,
8349 Tpm2PCRLockPolicy *ret_policy) {
8350
8351 _cleanup_free_ char *discovered_path = NULL;
8352 _cleanup_fclose_ FILE *f = NULL;
8353 int r;
8354
8355 assert(ret_policy);
8356
8357 r = tpm2_pcrlock_search_file(path, &f, &discovered_path);
8358 if (r == -ENOENT) {
8359 *ret_policy = (Tpm2PCRLockPolicy) {};
8360 return 0;
8361 }
8362 if (r < 0)
8363 return log_error_errno(r, "Failed to load TPM2 pcrlock policy file: %m");
8364
8365 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
8366 r = sd_json_parse_file(
8367 f,
8368 discovered_path,
8369 /* flags= */ 0,
8370 &v,
8371 /* reterr_line= */ NULL,
8372 /* ret_column= */ NULL);
8373 if (r < 0)
8374 return log_error_errno(r, "Failed to parse existing pcrlock policy file '%s': %m", discovered_path);
8375
8376 return tpm2_pcrlock_policy_from_json(v, ret_policy);
8377 }
8378
8379 static int pcrlock_policy_load_credential(
8380 const char *name,
8381 const struct iovec *data,
8382 Tpm2PCRLockPolicy *ret) {
8383
8384 _cleanup_free_ char *c = NULL;
8385 int r;
8386
8387 assert(name);
8388
8389 c = strdup(name);
8390 if (!c)
8391 return log_oom();
8392
8393 ascii_strlower(c); /* Lowercase, to match what we did at encryption time */
8394
8395 _cleanup_(iovec_done) struct iovec decoded = {};
8396 r = decrypt_credential_and_warn(
8397 c,
8398 now(CLOCK_REALTIME),
8399 /* tpm2_device= */ NULL,
8400 /* tpm2_signature_path= */ NULL,
8401 UID_INVALID,
8402 data,
8403 CREDENTIAL_ALLOW_NULL,
8404 &decoded);
8405 if (r < 0)
8406 return r;
8407
8408 if (memchr(decoded.iov_base, 0, decoded.iov_len))
8409 return log_error_errno(r, "Credential '%s' contains embedded NUL byte, refusing.", name);
8410
8411 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
8412 r = sd_json_parse(decoded.iov_base,
8413 /* flags= */ 0,
8414 &v,
8415 /* reterr_line= */ NULL,
8416 /* ret_column= */ NULL);
8417 if (r < 0)
8418 return log_error_errno(r, "Failed to parse pcrlock policy: %m");
8419
8420 r = tpm2_pcrlock_policy_from_json(v, ret);
8421 if (r < 0)
8422 return r;
8423
8424 return 0;
8425 }
8426
8427 int tpm2_pcrlock_policy_from_credentials(
8428 const struct iovec *srk,
8429 const struct iovec *nv,
8430 Tpm2PCRLockPolicy *ret) {
8431
8432 _cleanup_close_ int dfd = -EBADF;
8433 int r;
8434
8435 /* During boot we'll not have access to the pcrlock.json file in /var/. In order to support
8436 * pcrlock-bound root file systems we'll store a copy of the JSON data, wrapped in an (plaintext)
8437 * credential in the ESP or XBOOTLDR partition. There might be multiple of those however (because of
8438 * multi-boot), hence we use the SRK and NV data from the LUKS2 header as search key, and parse all
8439 * such JSON policies until we find a matching one. */
8440
8441 const char *dp;
8442 r = get_encrypted_system_credentials_dir(&dp);
8443 if (r < 0)
8444 return log_error_errno(r, "Failed to get encrypted system credentials directory: %m");
8445
8446 dfd = open(dp, O_CLOEXEC|O_DIRECTORY);
8447 if (dfd < 0) {
8448 if (errno == ENOENT) {
8449 log_debug("No encrypted system credentials passed.");
8450 return 0;
8451 }
8452
8453 return log_error_errno(errno, "Failed to open system credentials directory.");
8454 }
8455
8456 _cleanup_free_ DirectoryEntries *de = NULL;
8457 r = readdir_all(dfd, RECURSE_DIR_IGNORE_DOT, &de);
8458 if (r < 0)
8459 return log_error_errno(r, "Failed to enumerate system credentials: %m");
8460
8461 FOREACH_ARRAY(i, de->entries, de->n_entries) {
8462 _cleanup_(iovec_done) struct iovec data = {};
8463 struct dirent *d = *i;
8464
8465 if (!startswith_no_case(d->d_name, "pcrlock.")) /* VFAT is case-insensitive, hence don't be too strict here */
8466 continue;
8467
8468 r = read_full_file_full(
8469 dfd, d->d_name,
8470 /* offset= */ UINT64_MAX,
8471 /* size= */ CREDENTIAL_ENCRYPTED_SIZE_MAX,
8472 READ_FULL_FILE_UNBASE64|READ_FULL_FILE_FAIL_WHEN_LARGER,
8473 /* bind_name= */ NULL,
8474 (char**) &data.iov_base,
8475 &data.iov_len);
8476 if (r == -ENOENT)
8477 continue;
8478 if (r < 0) {
8479 log_warning_errno(r, "Failed to read credentials file %s/%s, skipping: %m", dp, d->d_name);
8480 continue;
8481 }
8482
8483 _cleanup_(tpm2_pcrlock_policy_done) Tpm2PCRLockPolicy loaded_policy = {};
8484 r = pcrlock_policy_load_credential(
8485 d->d_name,
8486 &data,
8487 &loaded_policy);
8488 if (r < 0) {
8489 log_warning_errno(r, "Loading of pcrlock policy from credential '%s/%s' failed, skipping.", ENCRYPTED_SYSTEM_CREDENTIALS_DIRECTORY, d->d_name);
8490 continue;
8491 }
8492
8493 if ((!srk || iovec_equal(srk, &loaded_policy.srk_handle)) &&
8494 (!nv || iovec_equal(nv, &loaded_policy.nv_handle))) {
8495 *ret = TAKE_STRUCT(loaded_policy);
8496 return 1;
8497 }
8498 }
8499
8500 log_info("No pcrlock policy found among system credentials.");
8501 *ret = (Tpm2PCRLockPolicy) {};
8502 return 0;
8503 }
8504
8505 int tpm2_load_public_key_file(const char *path, TPM2B_PUBLIC *ret) {
8506 _cleanup_free_ char *device_key_buffer = NULL;
8507 TPM2B_PUBLIC device_key_public = {};
8508 size_t device_key_buffer_size;
8509 TSS2_RC rc;
8510 int r;
8511
8512 assert(path);
8513 assert(ret);
8514
8515 r = dlopen_tpm2(LOG_DEBUG);
8516 if (r < 0)
8517 return r;
8518
8519 r = read_full_file(path, &device_key_buffer, &device_key_buffer_size);
8520 if (r < 0)
8521 return log_error_errno(r, "Failed to read device key from file '%s': %m", path);
8522
8523 size_t offset = 0;
8524 rc = sym_Tss2_MU_TPM2B_PUBLIC_Unmarshal(
8525 (uint8_t*) device_key_buffer,
8526 device_key_buffer_size,
8527 &offset,
8528 &device_key_public);
8529 if (rc != TSS2_RC_SUCCESS)
8530 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8531 "Could not unmarshal public key from file.");
8532
8533 assert(offset <= device_key_buffer_size);
8534 if (offset != device_key_buffer_size)
8535 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8536 "Found %zu bytes of trailing garbage in public key file.",
8537 device_key_buffer_size - offset);
8538
8539 *ret = device_key_public;
8540 return 0;
8541 }
8542
8543 int tpm2_hmac_key_from_pin(Tpm2Context *c, const Tpm2Handle *session, const TPM2B_AUTH *pin, Tpm2Handle **ret) {
8544 int r;
8545
8546 assert(c);
8547 assert(pin);
8548 assert(ret);
8549
8550 log_debug("Converting PIN into TPM2 HMAC-SHA256 object.");
8551
8552 /* Load the PIN (which we have stored in the "auth" TPM2B_AUTH) into the TPM as an HMAC key so that
8553 * we can use it in a TPM2_PolicySigned() to write to the nvindex. For that we'll prep a pair of
8554 * TPM2B_PUBLIC and TPM2B_SENSITIVE that defines an HMAC-SHA256 keyed hash function, and initialize
8555 * it based on the provided PIN data. */
8556
8557 TPM2B_PUBLIC auth_hmac_public = {
8558 .publicArea = {
8559 .type = TPM2_ALG_KEYEDHASH,
8560 .nameAlg = TPM2_ALG_SHA256,
8561 .objectAttributes = TPMA_OBJECT_SIGN_ENCRYPT,
8562 .parameters.keyedHashDetail.scheme = {
8563 .scheme = TPM2_ALG_HMAC,
8564 .details.hmac.hashAlg = TPM2_ALG_SHA256,
8565 },
8566 .unique.keyedHash.size = SHA256_DIGEST_SIZE,
8567 },
8568 };
8569
8570 TPM2B_SENSITIVE auth_hmac_private = {
8571 .sensitiveArea = {
8572 .sensitiveType = TPM2_ALG_KEYEDHASH,
8573 .sensitive.bits.size = pin->size,
8574 .seedValue.size = SHA256_DIGEST_SIZE,
8575 },
8576 };
8577
8578 /* Copy in the key data */
8579 memcpy_safe(auth_hmac_private.sensitiveArea.sensitive.bits.buffer, pin->buffer, pin->size);
8580
8581 /* NB: We initialize the seed of the TPMT_SENSITIVE structure to all zeroes, since we want a stable
8582 * "name" of the PIN object */
8583
8584 /* Now calculate the "unique" field for the public area, based on the sensitive data, according to
8585 * the algorithm in the TPM2 spec, part 1, Section 27.5.3.2 */
8586 struct iovec sensitive_data[] = {
8587 IOVEC_MAKE(auth_hmac_private.sensitiveArea.seedValue.buffer, auth_hmac_private.sensitiveArea.seedValue.size),
8588 IOVEC_MAKE(auth_hmac_private.sensitiveArea.sensitive.bits.buffer, auth_hmac_private.sensitiveArea.sensitive.bits.size),
8589 };
8590 r = tpm2_digest_many(
8591 auth_hmac_public.publicArea.nameAlg,
8592 &auth_hmac_public.publicArea.unique.keyedHash,
8593 sensitive_data,
8594 ELEMENTSOF(sensitive_data),
8595 /* extend= */ false);
8596 if (r < 0)
8597 return r;
8598
8599 /* And now load the public/private parts into the TPM and get a handle back */
8600 r = tpm2_load_external(
8601 c,
8602 session,
8603 &auth_hmac_public,
8604 &auth_hmac_private,
8605 ret);
8606 if (r < 0)
8607 return log_error_errno(r, "Failed to load PIN into TPM2: %m");
8608
8609 return 0;
8610 }
8611 #endif
8612
8613 char* tpm2_pcr_mask_to_string(uint32_t mask) {
8614 _cleanup_free_ char *s = NULL;
8615
8616 FOREACH_PCR_IN_MASK(n, mask)
8617 if (strextendf_with_separator(&s, "+", "%d", n) < 0)
8618 return NULL;
8619
8620 if (!s)
8621 return strdup("");
8622
8623 return TAKE_PTR(s);
8624 }
8625
8626 int tpm2_make_pcr_json_array(uint32_t pcr_mask, sd_json_variant **ret) {
8627 _cleanup_(sd_json_variant_unrefp) sd_json_variant *a = NULL;
8628 int r;
8629
8630 assert(ret);
8631
8632 for (size_t i = 0; i < TPM2_PCRS_MAX; i++) {
8633 _cleanup_(sd_json_variant_unrefp) sd_json_variant *e = NULL;
8634
8635 if ((pcr_mask & (UINT32_C(1) << i)) == 0)
8636 continue;
8637
8638 r = sd_json_variant_new_integer(&e, i);
8639 if (r < 0)
8640 return r;
8641
8642 r = sd_json_variant_append_array(&a, e);
8643 if (r < 0)
8644 return r;
8645 }
8646
8647 if (!a)
8648 return sd_json_variant_new_array(ret, NULL, 0);
8649
8650 *ret = TAKE_PTR(a);
8651 return 0;
8652 }
8653
8654 int tpm2_parse_pcr_json_array(sd_json_variant *v, uint32_t *ret) {
8655 sd_json_variant *e;
8656 uint32_t mask = 0;
8657
8658 if (!sd_json_variant_is_array(v))
8659 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR array is not a JSON array.");
8660
8661 JSON_VARIANT_ARRAY_FOREACH(e, v) {
8662 uint64_t u;
8663
8664 if (!sd_json_variant_is_unsigned(e))
8665 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR is not an unsigned integer.");
8666
8667 u = sd_json_variant_unsigned(e);
8668 if (u >= TPM2_PCRS_MAX)
8669 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR number out of range: %" PRIu64, u);
8670
8671 mask |= UINT32_C(1) << u;
8672 }
8673
8674 if (ret)
8675 *ret = mask;
8676
8677 return 0;
8678 }
8679
8680 static int tpm2_make_shard_array(
8681 const struct iovec data[],
8682 size_t n_data,
8683 int (*encode_iovec)(sd_json_variant **, const void*, size_t n), /* pass sd_json_variant_new_base64() or sd_json_variant_new_hex() */
8684 sd_json_variant **ret) {
8685
8686 int r;
8687
8688 /* Turns a series of struct iovec into either an array of base64/hex strings, or a single string
8689 * thereof. Used for generated "tpm2-blob" or "tpm2-policy-hash" fields. */
8690
8691 assert(data);
8692 assert(n_data > 0);
8693 assert(encode_iovec);
8694 assert(ret);
8695
8696 /* Only one item? Then create only one encoded string, for compatibility with older versions which
8697 * didn't support the "sharding" scheme */
8698 if (n_data == 1)
8699 return encode_iovec(ret, data[0].iov_base, data[0].iov_len);
8700
8701 /* Multiple items? Then generate an array of encoded strings */
8702 _cleanup_(sd_json_variant_unrefp) sd_json_variant *j = NULL;
8703
8704 FOREACH_ARRAY(d, data, n_data) {
8705 _cleanup_(sd_json_variant_unrefp) sd_json_variant *item = NULL;
8706
8707 r = encode_iovec(&item, d->iov_base, d->iov_len);
8708 if (r < 0)
8709 return r;
8710
8711 r = sd_json_variant_append_array(&j, item);
8712 if (r < 0)
8713 return r;
8714 }
8715
8716 *ret = TAKE_PTR(j);
8717 return 0;
8718 }
8719
8720 int tpm2_make_luks2_json(
8721 int keyslot,
8722 uint32_t hash_pcr_mask,
8723 uint16_t pcr_bank,
8724 const struct iovec *pubkey,
8725 uint32_t pubkey_pcr_mask,
8726 uint16_t primary_alg,
8727 const struct iovec blobs[],
8728 size_t n_blobs,
8729 const struct iovec policy_hash[],
8730 size_t n_policy_hash,
8731 const struct iovec *salt,
8732 const struct iovec *srk,
8733 const struct iovec *pcrlock_nv,
8734 TPM2Flags flags,
8735 sd_json_variant **ret) {
8736
8737 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL, *hmj = NULL, *pkmj = NULL;
8738 _cleanup_free_ char *keyslot_as_string = NULL;
8739 int r;
8740
8741 assert(iovec_is_valid(pubkey));
8742 assert(n_blobs >= 1);
8743 assert(n_policy_hash >= 1);
8744
8745 if (asprintf(&keyslot_as_string, "%i", keyslot) < 0)
8746 return -ENOMEM;
8747
8748 r = tpm2_make_pcr_json_array(hash_pcr_mask, &hmj);
8749 if (r < 0)
8750 return r;
8751
8752 if (pubkey_pcr_mask != 0) {
8753 r = tpm2_make_pcr_json_array(pubkey_pcr_mask, &pkmj);
8754 if (r < 0)
8755 return r;
8756 }
8757
8758 _cleanup_(sd_json_variant_unrefp) sd_json_variant *phj = NULL;
8759 r = tpm2_make_shard_array(policy_hash, n_policy_hash, sd_json_variant_new_hex, &phj);
8760 if (r < 0)
8761 return r;
8762
8763 _cleanup_(sd_json_variant_unrefp) sd_json_variant *bj = NULL;
8764 r = tpm2_make_shard_array(blobs, n_blobs, sd_json_variant_new_base64, &bj);
8765 if (r < 0)
8766 return r;
8767
8768 /* Note: We made the mistake of using "-" in the field names, which isn't particular compatible with
8769 * other programming languages. Let's not make things worse though, i.e. future additions to the JSON
8770 * object should use "_" rather than "-" in field names. */
8771
8772 r = sd_json_buildo(
8773 &v,
8774 SD_JSON_BUILD_PAIR("type", JSON_BUILD_CONST_STRING("systemd-tpm2")),
8775 SD_JSON_BUILD_PAIR("keyslots", SD_JSON_BUILD_ARRAY(SD_JSON_BUILD_STRING(keyslot_as_string))),
8776 SD_JSON_BUILD_PAIR_VARIANT("tpm2-blob", bj),
8777 SD_JSON_BUILD_PAIR_VARIANT("tpm2-pcrs", hmj),
8778 SD_JSON_BUILD_PAIR_CONDITION(pcr_bank != 0 && tpm2_hash_alg_to_string(pcr_bank), "tpm2-pcr-bank", SD_JSON_BUILD_STRING(tpm2_hash_alg_to_string(pcr_bank))),
8779 SD_JSON_BUILD_PAIR_CONDITION(primary_alg != 0 && tpm2_asym_alg_to_string(primary_alg), "tpm2-primary-alg", SD_JSON_BUILD_STRING(tpm2_asym_alg_to_string(primary_alg))),
8780 SD_JSON_BUILD_PAIR_VARIANT("tpm2-policy-hash", phj),
8781 SD_JSON_BUILD_PAIR_CONDITION(FLAGS_SET(flags, TPM2_FLAGS_USE_PIN), "tpm2-pin", SD_JSON_BUILD_BOOLEAN(true)),
8782 SD_JSON_BUILD_PAIR_CONDITION(FLAGS_SET(flags, TPM2_FLAGS_USE_PCRLOCK), "tpm2_pcrlock", SD_JSON_BUILD_BOOLEAN(true)),
8783 SD_JSON_BUILD_PAIR_CONDITION(pubkey_pcr_mask != 0, "tpm2_pubkey_pcrs", SD_JSON_BUILD_VARIANT(pkmj)),
8784 SD_JSON_BUILD_PAIR_CONDITION(iovec_is_set(pubkey), "tpm2_pubkey", JSON_BUILD_IOVEC_BASE64(pubkey)),
8785 SD_JSON_BUILD_PAIR_CONDITION(iovec_is_set(salt), "tpm2_salt", JSON_BUILD_IOVEC_BASE64(salt)),
8786 SD_JSON_BUILD_PAIR_CONDITION(iovec_is_set(srk), "tpm2_srk", JSON_BUILD_IOVEC_BASE64(srk)),
8787 SD_JSON_BUILD_PAIR_CONDITION(iovec_is_set(pcrlock_nv), "tpm2_pcrlock_nv", JSON_BUILD_IOVEC_BASE64(pcrlock_nv)));
8788 if (r < 0)
8789 return r;
8790
8791 if (ret)
8792 *ret = TAKE_PTR(v);
8793
8794 return keyslot;
8795 }
8796
8797 static int tpm2_parse_shard_array(
8798 sd_json_variant *v,
8799 const char *name,
8800 int (*decode_iovec)(sd_json_variant*, struct iovec *ret), /* pass json_variant_unbase64_iovec() or json_variant_unhex_iovec() */
8801 struct iovec **ret_data,
8802 size_t *ret_n_data) {
8803
8804 int r;
8805
8806 assert(v);
8807 assert(name);
8808 assert(decode_iovec);
8809 assert(ret_data);
8810 assert(ret_n_data);
8811
8812 /* Parses the "tpm2-blob" or "tpm2-policy-hash" fields of our LUKS JSON serialization. This can
8813 * either be an array of base64/hex strings, or a single such string. The former to allow for sharded
8814 * keys. The latter mostly for compatibility with older versions where we didn't support sharded
8815 * keys. */
8816
8817 struct iovec *data = NULL;
8818 size_t n_data = 0;
8819 CLEANUP_ARRAY(data, n_data, iovec_array_free);
8820
8821 if (sd_json_variant_is_array(v)) {
8822 if (sd_json_variant_elements(v) == 0)
8823 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data contains empty '%s' array.", name);
8824
8825 data = new0(struct iovec, sd_json_variant_elements(v));
8826 if (!data)
8827 return log_oom_debug();
8828
8829 sd_json_variant *i;
8830 JSON_VARIANT_ARRAY_FOREACH(i, v) {
8831 r = decode_iovec(i, data + n_data);
8832 if (r < 0)
8833 return log_debug_errno(r, "Invalid data in '%s' field.", name);
8834
8835 n_data++;
8836 }
8837 } else {
8838 data = new0(struct iovec, 1);
8839 if (!data)
8840 return log_oom_debug();
8841
8842 r = decode_iovec(v, data + 0);
8843 if (r < 0)
8844 return log_debug_errno(r, "Invalid data in '%s' field.", name);
8845
8846 n_data = 1;
8847 }
8848
8849 *ret_data = TAKE_PTR(data);
8850 *ret_n_data = n_data;
8851 return 0;
8852 }
8853
8854 int tpm2_parse_luks2_json(
8855 sd_json_variant *v,
8856 int *ret_keyslot,
8857 uint32_t *ret_hash_pcr_mask,
8858 uint16_t *ret_pcr_bank,
8859 struct iovec *ret_pubkey,
8860 uint32_t *ret_pubkey_pcr_mask,
8861 uint16_t *ret_primary_alg,
8862 struct iovec **ret_blobs,
8863 size_t *ret_n_blobs,
8864 struct iovec **ret_policy_hash,
8865 size_t *ret_n_policy_hash,
8866 struct iovec *ret_salt,
8867 struct iovec *ret_srk,
8868 struct iovec *ret_pcrlock_nv,
8869 TPM2Flags *ret_flags) {
8870
8871 _cleanup_(iovec_done) struct iovec pubkey = {}, salt = {}, srk = {}, pcrlock_nv = {};
8872 uint32_t hash_pcr_mask = 0, pubkey_pcr_mask = 0;
8873 uint16_t primary_alg = 0;
8874 uint16_t pcr_bank = UINT16_MAX; /* default: pick automatically */
8875 int r, keyslot = -1;
8876 TPM2Flags flags = 0;
8877 sd_json_variant *w;
8878
8879 assert(v);
8880
8881 if (ret_keyslot) {
8882 keyslot = cryptsetup_get_keyslot_from_token(v);
8883 if (keyslot < 0) {
8884 /* Return a recognizable error when parsing this field, so that callers can handle parsing
8885 * errors of the keyslots field gracefully, since it's not 'owned' by us, but by the LUKS2
8886 * spec */
8887 log_debug_errno(keyslot, "Failed to extract keyslot index from TPM2 JSON data token, skipping: %m");
8888 return -EUCLEAN;
8889 }
8890 }
8891
8892 w = sd_json_variant_by_key(v, "tpm2-pcrs");
8893 if (!w)
8894 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data lacks 'tpm2-pcrs' field.");
8895
8896 r = tpm2_parse_pcr_json_array(w, &hash_pcr_mask);
8897 if (r < 0)
8898 return log_debug_errno(r, "Failed to parse TPM2 PCR mask: %m");
8899
8900 /* The bank field is optional, since it was added in systemd 250 only. Before the bank was hardcoded
8901 * to SHA256. */
8902 w = sd_json_variant_by_key(v, "tpm2-pcr-bank");
8903 if (w) {
8904 /* The PCR bank field is optional */
8905
8906 if (!sd_json_variant_is_string(w))
8907 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR bank is not a string.");
8908
8909 r = tpm2_hash_alg_from_string(sd_json_variant_string(w));
8910 if (r < 0)
8911 return log_debug_errno(r, "TPM2 PCR bank invalid or not supported: %s", sd_json_variant_string(w));
8912
8913 pcr_bank = r;
8914 }
8915
8916 /* The primary key algorithm field is optional, since it was also added in systemd 250 only. Before
8917 * the algorithm was hardcoded to ECC. */
8918 w = sd_json_variant_by_key(v, "tpm2-primary-alg");
8919 if (w) {
8920 /* The primary key algorithm is optional */
8921
8922 if (!sd_json_variant_is_string(w))
8923 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 primary key algorithm is not a string.");
8924
8925 r = tpm2_asym_alg_from_string(sd_json_variant_string(w));
8926 if (r < 0)
8927 return log_debug_errno(r, "TPM2 asymmetric algorithm invalid or not supported: %s", sd_json_variant_string(w));
8928
8929 primary_alg = r;
8930 }
8931
8932 w = sd_json_variant_by_key(v, "tpm2-blob");
8933 if (!w)
8934 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data lacks 'tpm2-blob' field.");
8935
8936 struct iovec *blobs = NULL;
8937 size_t n_blobs = 0;
8938 CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
8939
8940 r = tpm2_parse_shard_array(w, "tpm2-blob", json_variant_unbase64_iovec, &blobs, &n_blobs);
8941 if (r < 0)
8942 return r;
8943
8944 w = sd_json_variant_by_key(v, "tpm2-policy-hash");
8945 if (!w)
8946 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data lacks 'tpm2-policy-hash' field.");
8947
8948 struct iovec *policy_hash = NULL;
8949 size_t n_policy_hash = 0;
8950 CLEANUP_ARRAY(policy_hash, n_policy_hash, iovec_array_free);
8951
8952 r = tpm2_parse_shard_array(w, "tpm2-policy-hash", json_variant_unhex_iovec, &policy_hash, &n_policy_hash);
8953 if (r < 0)
8954 return r;
8955
8956 w = sd_json_variant_by_key(v, "tpm2-pin");
8957 if (w) {
8958 if (!sd_json_variant_is_boolean(w))
8959 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PIN policy is not a boolean.");
8960
8961 SET_FLAG(flags, TPM2_FLAGS_USE_PIN, sd_json_variant_boolean(w));
8962 }
8963
8964 w = sd_json_variant_by_key(v, "tpm2_pcrlock");
8965 if (w) {
8966 if (!sd_json_variant_is_boolean(w))
8967 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 pclock policy is not a boolean.");
8968
8969 SET_FLAG(flags, TPM2_FLAGS_USE_PCRLOCK, sd_json_variant_boolean(w));
8970 }
8971
8972 w = sd_json_variant_by_key(v, "tpm2_salt");
8973 if (w) {
8974 r = json_variant_unbase64_iovec(w, &salt);
8975 if (r < 0)
8976 return log_debug_errno(r, "Invalid base64 data in 'tpm2_salt' field.");
8977 }
8978
8979 w = sd_json_variant_by_key(v, "tpm2_pubkey_pcrs");
8980 if (w) {
8981 r = tpm2_parse_pcr_json_array(w, &pubkey_pcr_mask);
8982 if (r < 0)
8983 return r;
8984 }
8985
8986 w = sd_json_variant_by_key(v, "tpm2_pubkey");
8987 if (w) {
8988 r = json_variant_unbase64_iovec(w, &pubkey);
8989 if (r < 0)
8990 return log_debug_errno(r, "Failed to decode PCR public key.");
8991 } else if (pubkey_pcr_mask != 0)
8992 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Public key PCR mask set, but not public key included in JSON data, refusing.");
8993
8994 w = sd_json_variant_by_key(v, "tpm2_srk");
8995 if (w) {
8996 r = json_variant_unbase64_iovec(w, &srk);
8997 if (r < 0)
8998 return log_debug_errno(r, "Invalid base64 data in 'tpm2_srk' field.");
8999 }
9000
9001 w = sd_json_variant_by_key(v, "tpm2_pcrlock_nv");
9002 if (w) {
9003 r = json_variant_unbase64_iovec(w, &pcrlock_nv);
9004 if (r < 0)
9005 return log_debug_errno(r, "Invalid base64 data in 'tpm2_pcrlock_nv' field.");
9006 }
9007
9008 if (ret_keyslot)
9009 *ret_keyslot = keyslot;
9010 if (ret_hash_pcr_mask)
9011 *ret_hash_pcr_mask = hash_pcr_mask;
9012 if (ret_pcr_bank)
9013 *ret_pcr_bank = pcr_bank;
9014 if (ret_pubkey)
9015 *ret_pubkey = TAKE_STRUCT(pubkey);
9016 if (ret_pubkey_pcr_mask)
9017 *ret_pubkey_pcr_mask = pubkey_pcr_mask;
9018 if (ret_primary_alg)
9019 *ret_primary_alg = primary_alg;
9020 if (ret_blobs)
9021 *ret_blobs = TAKE_PTR(blobs);
9022 if (ret_n_blobs)
9023 *ret_n_blobs = n_blobs;
9024 if (ret_policy_hash)
9025 *ret_policy_hash = TAKE_PTR(policy_hash);
9026 if (ret_n_policy_hash)
9027 *ret_n_policy_hash = n_policy_hash;
9028 if (ret_salt)
9029 *ret_salt = TAKE_STRUCT(salt);
9030 if (ret_srk)
9031 *ret_srk = TAKE_STRUCT(srk);
9032 if (ret_pcrlock_nv)
9033 *ret_pcrlock_nv = TAKE_STRUCT(pcrlock_nv);
9034 if (ret_flags)
9035 *ret_flags = flags;
9036 return 0;
9037 }
9038
9039 int tpm2_hash_alg_to_size(uint16_t alg) {
9040 switch (alg) {
9041 case TPM2_ALG_SHA1:
9042 return 20;
9043 case TPM2_ALG_SHA256:
9044 return 32;
9045 case TPM2_ALG_SHA384:
9046 return 48;
9047 case TPM2_ALG_SHA512:
9048 return 64;
9049 default:
9050 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown hash algorithm id 0x%" PRIx16, alg);
9051 }
9052 }
9053
9054 const char* tpm2_hash_alg_to_string(uint16_t alg) {
9055 switch (alg) {
9056 case TPM2_ALG_SHA1:
9057 return "sha1";
9058 case TPM2_ALG_SHA256:
9059 return "sha256";
9060 case TPM2_ALG_SHA384:
9061 return "sha384";
9062 case TPM2_ALG_SHA512:
9063 return "sha512";
9064 default:
9065 log_debug("Unknown hash algorithm id 0x%" PRIx16, alg);
9066 return NULL;
9067 }
9068 }
9069
9070 int tpm2_hash_alg_from_string(const char *alg) {
9071 if (strcaseeq_ptr(alg, "sha1"))
9072 return TPM2_ALG_SHA1;
9073 if (strcaseeq_ptr(alg, "sha256"))
9074 return TPM2_ALG_SHA256;
9075 if (strcaseeq_ptr(alg, "sha384"))
9076 return TPM2_ALG_SHA384;
9077 if (strcaseeq_ptr(alg, "sha512"))
9078 return TPM2_ALG_SHA512;
9079 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown hash algorithm name '%s'", alg);
9080 }
9081
9082 const char* tpm2_asym_alg_to_string(uint16_t alg) {
9083 switch (alg) {
9084 case TPM2_ALG_ECC:
9085 return "ecc";
9086 case TPM2_ALG_RSA:
9087 return "rsa";
9088 default:
9089 log_debug("Unknown asymmetric algorithm id 0x%" PRIx16, alg);
9090 return NULL;
9091 }
9092 }
9093
9094 int tpm2_asym_alg_from_string(const char *alg) {
9095 if (strcaseeq_ptr(alg, "ecc"))
9096 return TPM2_ALG_ECC;
9097 if (strcaseeq_ptr(alg, "rsa"))
9098 return TPM2_ALG_RSA;
9099 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown asymmetric algorithm name '%s'", alg);
9100 }
9101
9102 const char* tpm2_sym_alg_to_string(uint16_t alg) {
9103 switch (alg) {
9104 #if HAVE_TPM2
9105 case TPM2_ALG_AES:
9106 return "aes";
9107 #endif
9108 default:
9109 log_debug("Unknown symmetric algorithm id 0x%" PRIx16, alg);
9110 return NULL;
9111 }
9112 }
9113
9114 const char* tpm2_sym_mode_to_string(uint16_t mode) {
9115 switch (mode) {
9116 #if HAVE_TPM2
9117 case TPM2_ALG_CTR:
9118 return "ctr";
9119 case TPM2_ALG_OFB:
9120 return "ofb";
9121 case TPM2_ALG_CBC:
9122 return "cbc";
9123 case TPM2_ALG_CFB:
9124 return "cfb";
9125 case TPM2_ALG_ECB:
9126 return "ecb";
9127 #endif
9128 default:
9129 log_debug("Unknown symmetric mode id 0x%" PRIx16, mode);
9130 return NULL;
9131 }
9132 }
9133
9134 int tpm2_sym_mode_from_string(const char *mode) {
9135 #if HAVE_TPM2
9136 if (strcaseeq_ptr(mode, "ctr"))
9137 return TPM2_ALG_CTR;
9138 if (strcaseeq_ptr(mode, "ofb"))
9139 return TPM2_ALG_OFB;
9140 if (strcaseeq_ptr(mode, "cbc"))
9141 return TPM2_ALG_CBC;
9142 if (strcaseeq_ptr(mode, "cfb"))
9143 return TPM2_ALG_CFB;
9144 if (strcaseeq_ptr(mode, "ecb"))
9145 return TPM2_ALG_ECB;
9146 #endif
9147 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown symmetric mode name '%s'", mode);
9148 }
9149
9150 Tpm2Support tpm2_support_full(Tpm2Support mask) {
9151 Tpm2Support support = TPM2_SUPPORT_NONE;
9152 int r;
9153
9154 if (((mask & (TPM2_SUPPORT_SUBSYSTEM|TPM2_SUPPORT_DRIVER)) != 0) && detect_container() <= 0) {
9155 /* Check if there's a /dev/tpmrm* device via sysfs. If we run in a container we likely just
9156 * got the host sysfs mounted. Since devices are generally not virtualized for containers,
9157 * let's assume containers never have a TPM, at least for now. */
9158
9159 r = dir_is_empty("/sys/class/tpmrm", /* ignore_hidden_or_backup= */ false);
9160 if (r < 0) {
9161 if (r != -ENOENT)
9162 log_debug_errno(r, "Unable to test whether /sys/class/tpmrm/ exists and is populated, assuming it is not: %m");
9163 } else if (r == 0) /* populated! */
9164 support |= TPM2_SUPPORT_SUBSYSTEM|TPM2_SUPPORT_DRIVER;
9165 else
9166 /* If the directory exists but is empty, we know the subsystem is enabled but no
9167 * driver has been loaded yet. */
9168 support |= TPM2_SUPPORT_SUBSYSTEM;
9169 }
9170
9171 if (FLAGS_SET(mask, TPM2_SUPPORT_FIRMWARE) && efi_has_tpm2())
9172 support |= TPM2_SUPPORT_FIRMWARE;
9173
9174 #if HAVE_TPM2
9175 support |= TPM2_SUPPORT_SYSTEM;
9176
9177 if ((mask & (TPM2_SUPPORT_LIBRARIES|TPM2_SUPPORT_LIBTSS2_ALL)) != 0) {
9178 r = dlopen_tpm2_esys(LOG_DEBUG);
9179 if (r >= 0)
9180 support |= TPM2_SUPPORT_LIBTSS2_ESYS;
9181
9182 r = dlopen_tpm2_rc(LOG_DEBUG);
9183 if (r >= 0)
9184 support |= TPM2_SUPPORT_LIBTSS2_RC;
9185
9186 r = dlopen_tpm2_mu(LOG_DEBUG);
9187 if (r >= 0)
9188 support |= TPM2_SUPPORT_LIBTSS2_MU;
9189
9190 if (FLAGS_SET(support, TPM2_SUPPORT_LIBTSS2_ALL))
9191 support |= TPM2_SUPPORT_LIBRARIES;
9192 }
9193 #endif
9194
9195 return support & mask;
9196 }
9197
9198 static void print_field(const char *prefix, const char *s, bool supported) {
9199 printf("%s%s%s%s%s\n", strempty(prefix), supported ? ansi_green() : ansi_red(), plus_minus(supported), s, ansi_normal());
9200 }
9201
9202 int verb_has_tpm2_generic(bool quiet) {
9203 Tpm2Support s;
9204
9205 s = tpm2_support();
9206
9207 if (!quiet) {
9208 if (s == TPM2_SUPPORT_FULL)
9209 printf("%syes%s\n", ansi_green(), ansi_normal());
9210 else if (s == TPM2_SUPPORT_NONE)
9211 printf("%sno%s\n", ansi_red(), ansi_normal());
9212 else
9213 printf("%spartial%s\n", ansi_yellow(), ansi_normal());
9214
9215 print_field(NULL, "firmware", FLAGS_SET(s, TPM2_SUPPORT_FIRMWARE));
9216 print_field(NULL, "driver", FLAGS_SET(s, TPM2_SUPPORT_DRIVER));
9217 print_field(NULL, "system", FLAGS_SET(s, TPM2_SUPPORT_SYSTEM));
9218 print_field(NULL, "subsystem", FLAGS_SET(s, TPM2_SUPPORT_SUBSYSTEM));
9219 print_field(NULL, "libraries", FLAGS_SET(s, TPM2_SUPPORT_LIBRARIES));
9220 print_field(" ", "libtss2-esys.so.0", FLAGS_SET(s, TPM2_SUPPORT_LIBTSS2_ESYS));
9221 print_field(" ", "libtss2-rc.so.0", FLAGS_SET(s, TPM2_SUPPORT_LIBTSS2_RC));
9222 print_field(" ", "libtss2-mu.so.0", FLAGS_SET(s, TPM2_SUPPORT_LIBTSS2_MU));
9223 }
9224
9225 assert_cc(TPM2_SUPPORT_API <= 255); /* make sure this is safe to use as process exit status */
9226
9227 /* Return inverted bit flags. So that TPM2_SUPPORT_FULL becomes EXIT_SUCCESS and the other values
9228 * become some reasonable values 1…7. i.e. the flags we return here tell what is missing rather than
9229 * what is there, acknowledging the fact that for process exit statuses it is customary to return
9230 * zero (EXIT_FAILURE) when all is good, instead of all being bad. */
9231 return ~s & TPM2_SUPPORT_API;
9232 }
9233
9234 #if HAVE_TPM2
9235 static void tpm2_pcr_values_apply_default_hash_alg(Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
9236 TPMI_ALG_HASH default_hash = 0;
9237 FOREACH_ARRAY(v, pcr_values, n_pcr_values)
9238 if (v->hash != 0) {
9239 default_hash = v->hash;
9240 break;
9241 }
9242
9243 if (default_hash != 0)
9244 FOREACH_ARRAY(v, pcr_values, n_pcr_values)
9245 if (v->hash == 0)
9246 v->hash = default_hash;
9247 }
9248 #endif
9249
9250 /* The following tpm2_parse_pcr_argument*() functions all log errors, to match the behavior of system-wide
9251 * parse_*_argument() functions. */
9252
9253 /* Parse the PCR selection/value arg(s) and return a corresponding array of Tpm2PCRValue objects.
9254 *
9255 * The format is the same as tpm2_pcr_values_from_string(). The first provided entry with a hash algorithm
9256 * set will be used as the 'default' hash algorithm. All entries with an unset hash algorithm will be updated
9257 * with the 'default' hash algorithm. The resulting array will be sorted and checked for validity.
9258 *
9259 * This will replace *ret_pcr_values with the new array of pcr values; to append to an existing array, use
9260 * tpm2_parse_pcr_argument_append(). */
9261 int tpm2_parse_pcr_argument(const char *arg, Tpm2PCRValue **ret_pcr_values, size_t *ret_n_pcr_values) {
9262 #if HAVE_TPM2
9263 int r;
9264
9265 assert(arg);
9266 assert(ret_pcr_values);
9267 assert(ret_n_pcr_values);
9268
9269 _cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
9270 size_t n_pcr_values = 0;
9271 r = tpm2_pcr_values_from_string(arg, &pcr_values, &n_pcr_values);
9272 if (r < 0)
9273 return log_error_errno(r, "Could not parse PCR values from '%s': %m", arg);
9274
9275 tpm2_pcr_values_apply_default_hash_alg(pcr_values, n_pcr_values);
9276
9277 tpm2_sort_pcr_values(pcr_values, n_pcr_values);
9278
9279 if (!tpm2_pcr_values_valid(pcr_values, n_pcr_values))
9280 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Parsed PCR values are not valid.");
9281
9282 *ret_pcr_values = TAKE_PTR(pcr_values);
9283 *ret_n_pcr_values = n_pcr_values;
9284
9285 return 0;
9286 #else
9287 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support is disabled.");
9288 #endif
9289 }
9290
9291 /* Same as tpm2_parse_pcr_argument(), but the pcr values array is appended to. If the provided pcr values
9292 * array is not NULL, it must point to an allocated pcr values array and the provided number of pcr values
9293 * must be correct.
9294 *
9295 * Note that 'arg' is parsed into a new array of pcr values independently of any previous pcr values,
9296 * including application of the default hash algorithm. Then the two arrays are combined, the default hash
9297 * algorithm check applied again (in case either the previous or current array had no default hash
9298 * algorithm), and then the resulting array is sorted and rechecked for validity. */
9299 int tpm2_parse_pcr_argument_append(const char *arg, Tpm2PCRValue **pcr_values, size_t *n_pcr_values) {
9300 #if HAVE_TPM2
9301 int r;
9302
9303 assert(arg);
9304 assert(pcr_values);
9305 assert(n_pcr_values);
9306
9307 _cleanup_free_ Tpm2PCRValue *more_pcr_values = NULL;
9308 size_t n_more_pcr_values;
9309 r = tpm2_parse_pcr_argument(arg, &more_pcr_values, &n_more_pcr_values);
9310 if (r < 0)
9311 return r;
9312
9313 /* If we got previous values, append them. */
9314 if (*pcr_values && !GREEDY_REALLOC_APPEND(more_pcr_values, n_more_pcr_values, *pcr_values, *n_pcr_values))
9315 return log_oom();
9316
9317 tpm2_pcr_values_apply_default_hash_alg(more_pcr_values, n_more_pcr_values);
9318
9319 tpm2_sort_pcr_values(more_pcr_values, n_more_pcr_values);
9320
9321 if (!tpm2_pcr_values_valid(more_pcr_values, n_more_pcr_values))
9322 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Parsed PCR values are not valid.");
9323
9324 SWAP_TWO(*pcr_values, more_pcr_values);
9325 *n_pcr_values = n_more_pcr_values;
9326
9327 return 0;
9328 #else
9329 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support is disabled.");
9330 #endif
9331 }
9332
9333 int tpm2_parse_pcr_argument_to_mask(const char *arg, uint32_t *mask) {
9334 #if HAVE_TPM2
9335 int r;
9336
9337 /* Same as tpm2_parse_pcr_argument() but converts the pcr values to a pcr mask. If a hash algorithm or
9338 * hash value is specified an error is generated (after all we only return the mask here, nothing
9339 * else). This retains the previous behavior of tpm2_parse_pcr_argument() of clearing the mask if
9340 * 'arg' is empty, replacing the mask if it is set to UINT32_MAX, and or-ing the mask otherwise. */
9341
9342 assert(arg);
9343 assert(mask);
9344
9345 _cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
9346 size_t n_pcr_values;
9347 r = tpm2_parse_pcr_argument(arg, &pcr_values, &n_pcr_values);
9348 if (r < 0)
9349 return r;
9350
9351 if (n_pcr_values == 0) {
9352 /* This retains the previous behavior of clearing the mask if the arg is empty */
9353 *mask = 0;
9354 return 0;
9355 }
9356
9357 FOREACH_ARRAY(v, pcr_values, n_pcr_values) {
9358 if (v->hash != 0)
9359 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
9360 "Not expecting hash algorithm specification in PCR mask value, refusing: %s", arg);
9361 if (v->value.size != 0)
9362 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
9363 "Not expecting hash value specification in PCR mask value, refusing: %s", arg);
9364 }
9365
9366 uint32_t new_mask;
9367 r = tpm2_pcr_values_to_mask(pcr_values, n_pcr_values, /* hash= */ 0, &new_mask);
9368 if (r < 0)
9369 return log_error_errno(r, "Could not get pcr values mask: %m");
9370
9371 if (*mask == UINT32_MAX)
9372 *mask = new_mask;
9373 else
9374 *mask |= new_mask;
9375
9376 return 0;
9377 #else
9378 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 support is disabled.");
9379 #endif
9380 }
9381
9382 int tpm2_load_pcr_signature(const char *path, sd_json_variant **ret) {
9383 _cleanup_strv_free_ char **search = NULL;
9384 _cleanup_free_ char *discovered_path = NULL;
9385 _cleanup_fclose_ FILE *f = NULL;
9386 int r;
9387
9388 /* Tries to load a JSON PCR signature file. Takes an absolute path, a simple file name or NULL. In
9389 * the latter two cases searches in /etc/, /usr/lib/, /run/, as usual. */
9390
9391 search = strv_new(CONF_PATHS("systemd"));
9392 if (!search)
9393 return log_oom_debug();
9394
9395 if (!path) {
9396 /* If no path is specified, then look for "tpm2-pcr-signature.json" automatically. Also, in
9397 * this case include /.extra/ in the search path, but only in this case, and if we run in the
9398 * initrd. We don't want to be too eager here, after all /.extra/ is untrusted territory. */
9399
9400 path = "tpm2-pcr-signature.json";
9401
9402 if (in_initrd())
9403 if (strv_extend(&search, "/.extra") < 0)
9404 return log_oom_debug();
9405 }
9406
9407 r = search_and_fopen(path, "re", NULL, (const char**) search, &f, &discovered_path);
9408 if (r < 0)
9409 return log_debug_errno(r, "Failed to find TPM PCR signature file '%s': %m", path);
9410
9411 r = sd_json_parse_file(f, discovered_path, 0, ret, NULL, NULL);
9412 if (r < 0)
9413 return log_debug_errno(r, "Failed to parse TPM PCR signature JSON object '%s': %m", discovered_path);
9414
9415 return 0;
9416 }
9417
9418 int tpm2_load_pcr_public_key(const char *path, void **ret_pubkey, size_t *ret_pubkey_size) {
9419 _cleanup_free_ char *discovered_path = NULL;
9420 _cleanup_fclose_ FILE *f = NULL;
9421 int r;
9422
9423 /* Tries to load a PCR public key file. Takes an absolute path, a simple file name or NULL. In the
9424 * latter two cases searches in /etc/, /usr/lib/, /run/, as usual. */
9425
9426 if (!path)
9427 path = "tpm2-pcr-public-key.pem";
9428
9429 r = search_and_fopen(path, "re", NULL, (const char**) CONF_PATHS_STRV("systemd"), &f, &discovered_path);
9430 if (r < 0)
9431 return log_debug_errno(r, "Failed to find TPM PCR public key file '%s': %m", path);
9432
9433 r = read_full_stream(f, (char**) ret_pubkey, ret_pubkey_size);
9434 if (r < 0)
9435 return log_debug_errno(r, "Failed to load TPM PCR public key PEM file '%s': %m", discovered_path);
9436
9437 return 0;
9438 }
9439
9440 #define PBKDF2_HMAC_SHA256_ITERATIONS 10000
9441
9442 /*
9443 * Implements PBKDF2 HMAC SHA256 for a derived keylen of 32
9444 * bytes and for PBKDF2_HMAC_SHA256_ITERATIONS count.
9445 * I found the wikipedia entry relevant and it contains links to
9446 * relevant RFCs:
9447 * - https://en.wikipedia.org/wiki/PBKDF2
9448 * - https://www.rfc-editor.org/rfc/rfc2898#section-5.2
9449 */
9450 int tpm2_util_pbkdf2_hmac_sha256(const void *pass,
9451 size_t passlen,
9452 const void *salt,
9453 size_t saltlen,
9454 uint8_t ret[static SHA256_DIGEST_SIZE]) {
9455
9456 _cleanup_(erase_and_freep) uint8_t *buffer = NULL;
9457 uint8_t u[SHA256_DIGEST_SIZE];
9458
9459 /* To keep this simple, since derived KeyLen (dkLen in docs)
9460 * Is the same as the hash output, we don't need multiple
9461 * blocks. Part of the algorithm is to add the block count
9462 * in, but this can be hardcoded to 1.
9463 */
9464 static const uint8_t block_cnt[] = { 0, 0, 0, 1 };
9465
9466 assert(salt);
9467 assert(saltlen > 0);
9468 assert(saltlen <= (SIZE_MAX - sizeof(block_cnt)));
9469 assert(passlen > 0);
9470
9471 /*
9472 * Build a buffer of salt + block_cnt and hmac_sha256 it we
9473 * do this as we don't have a context builder for HMAC_SHA256.
9474 */
9475 buffer = malloc(saltlen + sizeof(block_cnt));
9476 if (!buffer)
9477 return -ENOMEM;
9478
9479 memcpy(buffer, salt, saltlen);
9480 memcpy(&buffer[saltlen], block_cnt, sizeof(block_cnt));
9481
9482 hmac_sha256(pass, passlen, buffer, saltlen + sizeof(block_cnt), u);
9483
9484 /* dk needs to be an unmodified u as u gets modified in the loop */
9485 memcpy(ret, u, SHA256_DIGEST_SIZE);
9486 uint8_t *dk = ret;
9487
9488 for (size_t i = 1; i < PBKDF2_HMAC_SHA256_ITERATIONS; i++) {
9489 hmac_sha256(pass, passlen, u, sizeof(u), u);
9490
9491 for (size_t j=0; j < sizeof(u); j++)
9492 dk[j] ^= u[j];
9493 }
9494
9495 return 0;
9496 }
9497
9498 static const char* const tpm2_pcr_index_table[_TPM2_PCR_INDEX_MAX_DEFINED] = {
9499 [TPM2_PCR_PLATFORM_CODE] = "platform-code",
9500 [TPM2_PCR_PLATFORM_CONFIG] = "platform-config",
9501 [TPM2_PCR_EXTERNAL_CODE] = "external-code",
9502 [TPM2_PCR_EXTERNAL_CONFIG] = "external-config",
9503 [TPM2_PCR_BOOT_LOADER_CODE] = "boot-loader-code",
9504 [TPM2_PCR_BOOT_LOADER_CONFIG] = "boot-loader-config",
9505 [TPM2_PCR_HOST_PLATFORM] = "host-platform",
9506 [TPM2_PCR_SECURE_BOOT_POLICY] = "secure-boot-policy",
9507 [TPM2_PCR_KERNEL_INITRD] = "kernel-initrd",
9508 [TPM2_PCR_IMA] = "ima",
9509 [TPM2_PCR_KERNEL_BOOT] = "kernel-boot",
9510 [TPM2_PCR_KERNEL_CONFIG] = "kernel-config",
9511 [TPM2_PCR_SYSEXTS] = "sysexts",
9512 [TPM2_PCR_SHIM_POLICY] = "shim-policy",
9513 [TPM2_PCR_SYSTEM_IDENTITY] = "system-identity",
9514 [TPM2_PCR_DEBUG] = "debug",
9515 [TPM2_PCR_APPLICATION_SUPPORT] = "application-support",
9516 };
9517
9518 DEFINE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_FALLBACK(tpm2_pcr_index, int, TPM2_PCRS_MAX - 1);
9519 DEFINE_STRING_TABLE_LOOKUP_TO_STRING(tpm2_pcr_index, int);
9520
9521 bool tpm2_nvpcr_name_is_valid(const char *name) {
9522 return string_is_safe(name, STRING_FILENAME) &&
9523 tpm2_pcr_index_from_string(name) < 0; /* don't allow nvpcrs to be name like pcrs */
9524 }