]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/tpm2-util.c
ba8dfb041d8b07ffb2e177b19cc6326c8359b159
[thirdparty/systemd.git] / src / shared / tpm2-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "alloc-util.h"
4 #include "constants.h"
5 #include "cryptsetup-util.h"
6 #include "dirent-util.h"
7 #include "dlfcn-util.h"
8 #include "efi-api.h"
9 #include "extract-word.h"
10 #include "fd-util.h"
11 #include "fileio.h"
12 #include "format-table.h"
13 #include "fs-util.h"
14 #include "hexdecoct.h"
15 #include "memory-util.h"
16 #include "openssl-util.h"
17 #include "parse-util.h"
18 #include "random-util.h"
19 #include "sha256.h"
20 #include "stat-util.h"
21 #include "time-util.h"
22 #include "tpm2-util.h"
23 #include "virt.h"
24
25 #if HAVE_TPM2
26 static void *libtss2_esys_dl = NULL;
27 static void *libtss2_rc_dl = NULL;
28 static void *libtss2_mu_dl = NULL;
29
30 TSS2_RC (*sym_Esys_Create)(ESYS_CONTEXT *esysContext, ESYS_TR parentHandle, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, const TPM2B_SENSITIVE_CREATE *inSensitive, const TPM2B_PUBLIC *inPublic, const TPM2B_DATA *outsideInfo, const TPML_PCR_SELECTION *creationPCR, TPM2B_PRIVATE **outPrivate, TPM2B_PUBLIC **outPublic, TPM2B_CREATION_DATA **creationData, TPM2B_DIGEST **creationHash, TPMT_TK_CREATION **creationTicket) = NULL;
31 TSS2_RC (*sym_Esys_CreatePrimary)(ESYS_CONTEXT *esysContext, ESYS_TR primaryHandle, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, const TPM2B_SENSITIVE_CREATE *inSensitive, const TPM2B_PUBLIC *inPublic, const TPM2B_DATA *outsideInfo, const TPML_PCR_SELECTION *creationPCR, ESYS_TR *objectHandle, TPM2B_PUBLIC **outPublic, TPM2B_CREATION_DATA **creationData, TPM2B_DIGEST **creationHash, TPMT_TK_CREATION **creationTicket) = NULL;
32 void (*sym_Esys_Finalize)(ESYS_CONTEXT **context) = NULL;
33 TSS2_RC (*sym_Esys_FlushContext)(ESYS_CONTEXT *esysContext, ESYS_TR flushHandle) = NULL;
34 void (*sym_Esys_Free)(void *ptr) = NULL;
35 TSS2_RC (*sym_Esys_GetCapability)(ESYS_CONTEXT *esysContext, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, TPM2_CAP capability, UINT32 property, UINT32 propertyCount, TPMI_YES_NO *moreData, TPMS_CAPABILITY_DATA **capabilityData);
36 TSS2_RC (*sym_Esys_GetRandom)(ESYS_CONTEXT *esysContext, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, UINT16 bytesRequested, TPM2B_DIGEST **randomBytes) = NULL;
37 TSS2_RC (*sym_Esys_Initialize)(ESYS_CONTEXT **esys_context, TSS2_TCTI_CONTEXT *tcti, TSS2_ABI_VERSION *abiVersion) = NULL;
38 TSS2_RC (*sym_Esys_Load)(ESYS_CONTEXT *esysContext, ESYS_TR parentHandle, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, const TPM2B_PRIVATE *inPrivate, const TPM2B_PUBLIC *inPublic, ESYS_TR *objectHandle) = NULL;
39 TSS2_RC (*sym_Esys_LoadExternal)(ESYS_CONTEXT *esysContext, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, const TPM2B_SENSITIVE *inPrivate, const TPM2B_PUBLIC *inPublic, ESYS_TR hierarchy, ESYS_TR *objectHandle);
40 TSS2_RC (*sym_Esys_PCR_Extend)(ESYS_CONTEXT *esysContext, ESYS_TR pcrHandle, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, const TPML_DIGEST_VALUES *digests);
41 TSS2_RC (*sym_Esys_PCR_Read)(ESYS_CONTEXT *esysContext, ESYS_TR shandle1,ESYS_TR shandle2, ESYS_TR shandle3, const TPML_PCR_SELECTION *pcrSelectionIn, UINT32 *pcrUpdateCounter, TPML_PCR_SELECTION **pcrSelectionOut, TPML_DIGEST **pcrValues);
42 TSS2_RC (*sym_Esys_PolicyAuthorize)(ESYS_CONTEXT *esysContext, ESYS_TR policySession, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, const TPM2B_DIGEST *approvedPolicy, const TPM2B_NONCE *policyRef, const TPM2B_NAME *keySign, const TPMT_TK_VERIFIED *checkTicket);
43 TSS2_RC (*sym_Esys_PolicyAuthValue)(ESYS_CONTEXT *esysContext, ESYS_TR policySession, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3) = NULL;
44 TSS2_RC (*sym_Esys_PolicyGetDigest)(ESYS_CONTEXT *esysContext, ESYS_TR policySession, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, TPM2B_DIGEST **policyDigest) = NULL;
45 TSS2_RC (*sym_Esys_PolicyPCR)(ESYS_CONTEXT *esysContext, ESYS_TR policySession, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, const TPM2B_DIGEST *pcrDigest, const TPML_PCR_SELECTION *pcrs) = NULL;
46 TSS2_RC (*sym_Esys_StartAuthSession)(ESYS_CONTEXT *esysContext, ESYS_TR tpmKey, ESYS_TR bind, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, const TPM2B_NONCE *nonceCaller, TPM2_SE sessionType, const TPMT_SYM_DEF *symmetric, TPMI_ALG_HASH authHash, ESYS_TR *sessionHandle) = NULL;
47 TSS2_RC (*sym_Esys_Startup)(ESYS_CONTEXT *esysContext, TPM2_SU startupType) = NULL;
48 TSS2_RC (*sym_Esys_TRSess_SetAttributes)(ESYS_CONTEXT *esysContext, ESYS_TR session, TPMA_SESSION flags, TPMA_SESSION mask);
49 TSS2_RC (*sym_Esys_TR_GetName)(ESYS_CONTEXT *esysContext, ESYS_TR handle, TPM2B_NAME **name);
50 TSS2_RC (*sym_Esys_TR_SetAuth)(ESYS_CONTEXT *esysContext, ESYS_TR handle, TPM2B_AUTH const *authValue) = NULL;
51 TSS2_RC (*sym_Esys_Unseal)(ESYS_CONTEXT *esysContext, ESYS_TR itemHandle, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, TPM2B_SENSITIVE_DATA **outData) = NULL;
52 TSS2_RC (*sym_Esys_VerifySignature)(ESYS_CONTEXT *esysContext, ESYS_TR keyHandle, ESYS_TR shandle1, ESYS_TR shandle2, ESYS_TR shandle3, const TPM2B_DIGEST *digest, const TPMT_SIGNATURE *signature, TPMT_TK_VERIFIED **validation);
53
54 const char* (*sym_Tss2_RC_Decode)(TSS2_RC rc) = NULL;
55
56 TSS2_RC (*sym_Tss2_MU_TPM2B_PRIVATE_Marshal)(TPM2B_PRIVATE const *src, uint8_t buffer[], size_t buffer_size, size_t *offset) = NULL;
57 TSS2_RC (*sym_Tss2_MU_TPM2B_PRIVATE_Unmarshal)(uint8_t const buffer[], size_t buffer_size, size_t *offset, TPM2B_PRIVATE *dest) = NULL;
58 TSS2_RC (*sym_Tss2_MU_TPM2B_PUBLIC_Marshal)(TPM2B_PUBLIC const *src, uint8_t buffer[], size_t buffer_size, size_t *offset) = NULL;
59 TSS2_RC (*sym_Tss2_MU_TPM2B_PUBLIC_Unmarshal)(uint8_t const buffer[], size_t buffer_size, size_t *offset, TPM2B_PUBLIC *dest) = NULL;
60
61 int dlopen_tpm2(void) {
62 int r;
63
64 r = dlopen_many_sym_or_warn(
65 &libtss2_esys_dl, "libtss2-esys.so.0", LOG_DEBUG,
66 DLSYM_ARG(Esys_Create),
67 DLSYM_ARG(Esys_CreatePrimary),
68 DLSYM_ARG(Esys_Finalize),
69 DLSYM_ARG(Esys_FlushContext),
70 DLSYM_ARG(Esys_Free),
71 DLSYM_ARG(Esys_GetCapability),
72 DLSYM_ARG(Esys_GetRandom),
73 DLSYM_ARG(Esys_Initialize),
74 DLSYM_ARG(Esys_Load),
75 DLSYM_ARG(Esys_LoadExternal),
76 DLSYM_ARG(Esys_PCR_Extend),
77 DLSYM_ARG(Esys_PCR_Read),
78 DLSYM_ARG(Esys_PolicyAuthorize),
79 DLSYM_ARG(Esys_PolicyAuthValue),
80 DLSYM_ARG(Esys_PolicyGetDigest),
81 DLSYM_ARG(Esys_PolicyPCR),
82 DLSYM_ARG(Esys_StartAuthSession),
83 DLSYM_ARG(Esys_Startup),
84 DLSYM_ARG(Esys_TRSess_SetAttributes),
85 DLSYM_ARG(Esys_TR_GetName),
86 DLSYM_ARG(Esys_TR_SetAuth),
87 DLSYM_ARG(Esys_Unseal),
88 DLSYM_ARG(Esys_VerifySignature));
89 if (r < 0)
90 return r;
91
92 r = dlopen_many_sym_or_warn(
93 &libtss2_rc_dl, "libtss2-rc.so.0", LOG_DEBUG,
94 DLSYM_ARG(Tss2_RC_Decode));
95 if (r < 0)
96 return r;
97
98 return dlopen_many_sym_or_warn(
99 &libtss2_mu_dl, "libtss2-mu.so.0", LOG_DEBUG,
100 DLSYM_ARG(Tss2_MU_TPM2B_PRIVATE_Marshal),
101 DLSYM_ARG(Tss2_MU_TPM2B_PRIVATE_Unmarshal),
102 DLSYM_ARG(Tss2_MU_TPM2B_PUBLIC_Marshal),
103 DLSYM_ARG(Tss2_MU_TPM2B_PUBLIC_Unmarshal));
104 }
105
106 void tpm2_context_destroy(struct tpm2_context *c) {
107 assert(c);
108
109 if (c->esys_context)
110 sym_Esys_Finalize(&c->esys_context);
111
112 c->tcti_context = mfree(c->tcti_context);
113
114 if (c->tcti_dl) {
115 dlclose(c->tcti_dl);
116 c->tcti_dl = NULL;
117 }
118 }
119
120 static inline void Esys_Finalize_wrapper(ESYS_CONTEXT **c) {
121 /* A wrapper around Esys_Finalize() for use with _cleanup_(). Only reasons we need this wrapper is
122 * because the function itself warn logs if we'd pass a pointer to NULL, and we don't want that. */
123 if (*c)
124 sym_Esys_Finalize(c);
125 }
126
127 ESYS_TR tpm2_flush_context_verbose(ESYS_CONTEXT *c, ESYS_TR handle) {
128 TSS2_RC rc;
129
130 if (!c || handle == ESYS_TR_NONE)
131 return ESYS_TR_NONE;
132
133 rc = sym_Esys_FlushContext(c, handle);
134 if (rc != TSS2_RC_SUCCESS) /* We ignore failures here (besides debug logging), since this is called
135 * in error paths, where we cannot do anything about failures anymore. And
136 * when it is called in successful codepaths by this time we already did
137 * what we wanted to do, and got the results we wanted so there's no
138 * reason to make this fail more loudly than necessary. */
139 log_debug("Failed to get flush context of TPM, ignoring: %s", sym_Tss2_RC_Decode(rc));
140
141 return ESYS_TR_NONE;
142 }
143
144 int tpm2_context_init(const char *device, struct tpm2_context *ret) {
145 _cleanup_(Esys_Finalize_wrapper) ESYS_CONTEXT *c = NULL;
146 _cleanup_free_ TSS2_TCTI_CONTEXT *tcti = NULL;
147 _cleanup_(dlclosep) void *dl = NULL;
148 TSS2_RC rc;
149 int r;
150
151 r = dlopen_tpm2();
152 if (r < 0)
153 return log_error_errno(r, "TPM2 support not installed: %m");
154
155 if (!device) {
156 device = secure_getenv("SYSTEMD_TPM2_DEVICE");
157 if (device)
158 /* Setting the env var to an empty string forces tpm2-tss' own device picking
159 * logic to be used. */
160 device = empty_to_null(device);
161 else
162 /* If nothing was specified explicitly, we'll use a hardcoded default: the "device" tcti
163 * driver and the "/dev/tpmrm0" device. We do this since on some distributions the tpm2-abrmd
164 * might be used and we really don't want that, since it is a system service and that creates
165 * various ordering issues/deadlocks during early boot. */
166 device = "device:/dev/tpmrm0";
167 }
168
169 if (device) {
170 const char *param, *driver, *fn;
171 const TSS2_TCTI_INFO* info;
172 TSS2_TCTI_INFO_FUNC func;
173 size_t sz = 0;
174
175 param = strchr(device, ':');
176 if (param) {
177 /* Syntax #1: Pair of driver string and arbitrary parameter */
178 driver = strndupa_safe(device, param - device);
179 if (isempty(driver))
180 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 driver name is empty, refusing.");
181
182 param++;
183 } else if (path_is_absolute(device) && path_is_valid(device)) {
184 /* Syntax #2: TPM device node */
185 driver = "device";
186 param = device;
187 } else
188 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid TPM2 driver string, refusing.");
189
190 log_debug("Using TPM2 TCTI driver '%s' with device '%s'.", driver, param);
191
192 fn = strjoina("libtss2-tcti-", driver, ".so.0");
193
194 /* Better safe than sorry, let's refuse strings that cannot possibly be valid driver early, before going to disk. */
195 if (!filename_is_valid(fn))
196 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 driver name '%s' not valid, refusing.", driver);
197
198 dl = dlopen(fn, RTLD_NOW);
199 if (!dl)
200 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to load %s: %s", fn, dlerror());
201
202 func = dlsym(dl, TSS2_TCTI_INFO_SYMBOL);
203 if (!func)
204 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
205 "Failed to find TCTI info symbol " TSS2_TCTI_INFO_SYMBOL ": %s",
206 dlerror());
207
208 info = func();
209 if (!info)
210 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Unable to get TCTI info data.");
211
212
213 log_debug("Loaded TCTI module '%s' (%s) [Version %" PRIu32 "]", info->name, info->description, info->version);
214
215 rc = info->init(NULL, &sz, NULL);
216 if (rc != TPM2_RC_SUCCESS)
217 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
218 "Failed to initialize TCTI context: %s", sym_Tss2_RC_Decode(rc));
219
220 tcti = malloc0(sz);
221 if (!tcti)
222 return log_oom();
223
224 rc = info->init(tcti, &sz, param);
225 if (rc != TPM2_RC_SUCCESS)
226 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
227 "Failed to initialize TCTI context: %s", sym_Tss2_RC_Decode(rc));
228 }
229
230 rc = sym_Esys_Initialize(&c, tcti, NULL);
231 if (rc != TSS2_RC_SUCCESS)
232 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
233 "Failed to initialize TPM context: %s", sym_Tss2_RC_Decode(rc));
234
235 rc = sym_Esys_Startup(c, TPM2_SU_CLEAR);
236 if (rc == TPM2_RC_INITIALIZE)
237 log_debug("TPM already started up.");
238 else if (rc == TSS2_RC_SUCCESS)
239 log_debug("TPM successfully started up.");
240 else
241 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
242 "Failed to start up TPM: %s", sym_Tss2_RC_Decode(rc));
243
244 *ret = (struct tpm2_context) {
245 .esys_context = TAKE_PTR(c),
246 .tcti_context = TAKE_PTR(tcti),
247 .tcti_dl = TAKE_PTR(dl),
248 };
249
250 return 0;
251 }
252
253 #define TPM2_CREDIT_RANDOM_FLAG_PATH "/run/systemd/tpm-rng-credited"
254
255 static int tpm2_credit_random(ESYS_CONTEXT *c) {
256 size_t rps, done = 0;
257 TSS2_RC rc;
258 usec_t t;
259 int r;
260
261 assert(c);
262
263 /* Pulls some entropy from the TPM and adds it into the kernel RNG pool. That way we can say that the
264 * key we will ultimately generate with the kernel random pool is at least as good as the TPM's RNG,
265 * but likely better. Note that we don't trust the TPM RNG very much, hence do not actually credit
266 * any entropy. */
267
268 if (access(TPM2_CREDIT_RANDOM_FLAG_PATH, F_OK) < 0) {
269 if (errno != ENOENT)
270 log_debug_errno(errno, "Failed to detect if '" TPM2_CREDIT_RANDOM_FLAG_PATH "' exists, ignoring: %m");
271 } else {
272 log_debug("Not adding TPM2 entropy to the kernel random pool again.");
273 return 0; /* Already done */
274 }
275
276 t = now(CLOCK_MONOTONIC);
277
278 for (rps = random_pool_size(); rps > 0;) {
279 _cleanup_(Esys_Freep) TPM2B_DIGEST *buffer = NULL;
280
281 rc = sym_Esys_GetRandom(
282 c,
283 ESYS_TR_NONE,
284 ESYS_TR_NONE,
285 ESYS_TR_NONE,
286 MIN(rps, 32U), /* 32 is supposedly a safe choice, given that AES 256bit keys are this long, and TPM2 baseline requires support for those. */
287 &buffer);
288 if (rc != TSS2_RC_SUCCESS)
289 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
290 "Failed to acquire entropy from TPM: %s", sym_Tss2_RC_Decode(rc));
291
292 if (buffer->size == 0)
293 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
294 "Zero-sized entropy returned from TPM.");
295
296 r = random_write_entropy(-1, buffer->buffer, buffer->size, /* credit= */ false);
297 if (r < 0)
298 return log_error_errno(r, "Failed wo write entropy to kernel: %m");
299
300 done += buffer->size;
301 rps = LESS_BY(rps, buffer->size);
302 }
303
304 log_debug("Added %zu bytes of TPM2 entropy to the kernel random pool in %s.", done, FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - t, 0));
305
306 r = touch(TPM2_CREDIT_RANDOM_FLAG_PATH);
307 if (r < 0)
308 log_debug_errno(r, "Failed to touch '" TPM2_CREDIT_RANDOM_FLAG_PATH "', ignoring: %m");
309
310 return 0;
311 }
312
313 static int tpm2_make_primary(
314 ESYS_CONTEXT *c,
315 ESYS_TR *ret_primary,
316 TPMI_ALG_PUBLIC alg,
317 TPMI_ALG_PUBLIC *ret_alg) {
318
319 static const TPM2B_SENSITIVE_CREATE primary_sensitive = {};
320 static const TPM2B_PUBLIC primary_template_ecc = {
321 .size = sizeof(TPMT_PUBLIC),
322 .publicArea = {
323 .type = TPM2_ALG_ECC,
324 .nameAlg = TPM2_ALG_SHA256,
325 .objectAttributes = TPMA_OBJECT_RESTRICTED|TPMA_OBJECT_DECRYPT|TPMA_OBJECT_FIXEDTPM|TPMA_OBJECT_FIXEDPARENT|TPMA_OBJECT_SENSITIVEDATAORIGIN|TPMA_OBJECT_USERWITHAUTH,
326 .parameters.eccDetail = {
327 .symmetric = {
328 .algorithm = TPM2_ALG_AES,
329 .keyBits.aes = 128,
330 .mode.aes = TPM2_ALG_CFB,
331 },
332 .scheme.scheme = TPM2_ALG_NULL,
333 .curveID = TPM2_ECC_NIST_P256,
334 .kdf.scheme = TPM2_ALG_NULL,
335 },
336 },
337 };
338 static const TPM2B_PUBLIC primary_template_rsa = {
339 .size = sizeof(TPMT_PUBLIC),
340 .publicArea = {
341 .type = TPM2_ALG_RSA,
342 .nameAlg = TPM2_ALG_SHA256,
343 .objectAttributes = TPMA_OBJECT_RESTRICTED|TPMA_OBJECT_DECRYPT|TPMA_OBJECT_FIXEDTPM|TPMA_OBJECT_FIXEDPARENT|TPMA_OBJECT_SENSITIVEDATAORIGIN|TPMA_OBJECT_USERWITHAUTH,
344 .parameters.rsaDetail = {
345 .symmetric = {
346 .algorithm = TPM2_ALG_AES,
347 .keyBits.aes = 128,
348 .mode.aes = TPM2_ALG_CFB,
349 },
350 .scheme.scheme = TPM2_ALG_NULL,
351 .keyBits = 2048,
352 },
353 },
354 };
355
356 static const TPML_PCR_SELECTION creation_pcr = {};
357 ESYS_TR primary = ESYS_TR_NONE;
358 TSS2_RC rc;
359 usec_t ts;
360
361 log_debug("Creating primary key on TPM.");
362
363 /* So apparently not all TPM2 devices support ECC. ECC is generally preferably, because it's so much
364 * faster, noticeably so (~10s vs. ~240ms on my system). Hence, unless explicitly configured let's
365 * try to use ECC first, and if that does not work, let's fall back to RSA. */
366
367 ts = now(CLOCK_MONOTONIC);
368
369 if (IN_SET(alg, 0, TPM2_ALG_ECC)) {
370 rc = sym_Esys_CreatePrimary(
371 c,
372 ESYS_TR_RH_OWNER,
373 ESYS_TR_PASSWORD,
374 ESYS_TR_NONE,
375 ESYS_TR_NONE,
376 &primary_sensitive,
377 &primary_template_ecc,
378 NULL,
379 &creation_pcr,
380 &primary,
381 NULL,
382 NULL,
383 NULL,
384 NULL);
385
386 if (rc != TSS2_RC_SUCCESS) {
387 if (alg != 0)
388 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
389 "Failed to generate ECC primary key in TPM: %s", sym_Tss2_RC_Decode(rc));
390
391 log_debug("Failed to generate ECC primary key in TPM, trying RSA: %s", sym_Tss2_RC_Decode(rc));
392 } else {
393 log_debug("Successfully created ECC primary key on TPM.");
394 alg = TPM2_ALG_ECC;
395 }
396 }
397
398 if (IN_SET(alg, 0, TPM2_ALG_RSA)) {
399 rc = sym_Esys_CreatePrimary(
400 c,
401 ESYS_TR_RH_OWNER,
402 ESYS_TR_PASSWORD,
403 ESYS_TR_NONE,
404 ESYS_TR_NONE,
405 &primary_sensitive,
406 &primary_template_rsa,
407 NULL,
408 &creation_pcr,
409 &primary,
410 NULL,
411 NULL,
412 NULL,
413 NULL);
414 if (rc != TSS2_RC_SUCCESS)
415 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
416 "Failed to generate RSA primary key in TPM: %s", sym_Tss2_RC_Decode(rc));
417 else if (alg == 0) {
418 log_notice("TPM2 chip apparently does not support ECC primary keys, falling back to RSA. "
419 "This likely means TPM2 operations will be relatively slow, please be patient.");
420 alg = TPM2_ALG_RSA;
421 }
422
423 log_debug("Successfully created RSA primary key on TPM.");
424 }
425
426 log_debug("Generating primary key on TPM2 took %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - ts, USEC_PER_MSEC));
427
428 *ret_primary = primary;
429 if (ret_alg)
430 *ret_alg = alg;
431
432 return 0;
433 }
434
435 void tpm2_pcr_mask_to_selection(uint32_t mask, uint16_t bank, TPML_PCR_SELECTION *ret) {
436 assert(ret);
437
438 /* We only do 24bit here, as that's what PC TPMs are supposed to support */
439 assert(mask <= 0xFFFFFFU);
440
441 *ret = (TPML_PCR_SELECTION) {
442 .count = 1,
443 .pcrSelections[0] = {
444 .hash = bank,
445 .sizeofSelect = 3,
446 .pcrSelect[0] = mask & 0xFF,
447 .pcrSelect[1] = (mask >> 8) & 0xFF,
448 .pcrSelect[2] = (mask >> 16) & 0xFF,
449 }
450 };
451 }
452
453 static unsigned find_nth_bit(uint32_t mask, unsigned n) {
454 uint32_t bit = 1;
455
456 assert(n < 32);
457
458 /* Returns the bit index of the nth set bit, e.g. mask=0b101001, n=3 → 5 */
459
460 for (unsigned i = 0; i < sizeof(mask)*8; i++) {
461
462 if (bit & mask) {
463 if (n == 0)
464 return i;
465
466 n--;
467 }
468
469 bit <<= 1;
470 }
471
472 return UINT_MAX;
473 }
474
475 static int tpm2_pcr_mask_good(
476 ESYS_CONTEXT *c,
477 TPMI_ALG_HASH bank,
478 uint32_t mask) {
479
480 _cleanup_(Esys_Freep) TPML_DIGEST *pcr_values = NULL;
481 TPML_PCR_SELECTION selection;
482 bool good = false;
483 TSS2_RC rc;
484
485 assert(c);
486
487 /* So we have the problem that some systems might have working TPM2 chips, but the firmware doesn't
488 * actually measure into them, or only into a suboptimal bank. If so, the PCRs should be all zero or
489 * all 0xFF. Detect that, so that we can warn and maybe pick a better bank. */
490
491 tpm2_pcr_mask_to_selection(mask, bank, &selection);
492
493 rc = sym_Esys_PCR_Read(
494 c,
495 ESYS_TR_NONE,
496 ESYS_TR_NONE,
497 ESYS_TR_NONE,
498 &selection,
499 NULL,
500 NULL,
501 &pcr_values);
502 if (rc != TSS2_RC_SUCCESS)
503 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
504 "Failed to read TPM2 PCRs: %s", sym_Tss2_RC_Decode(rc));
505
506 /* If at least one of the selected PCR values is something other than all 0x00 or all 0xFF we are happy. */
507 for (unsigned i = 0; i < pcr_values->count; i++) {
508 if (DEBUG_LOGGING) {
509 _cleanup_free_ char *h = NULL;
510 unsigned j;
511
512 h = hexmem(pcr_values->digests[i].buffer, pcr_values->digests[i].size);
513 j = find_nth_bit(mask, i);
514 assert(j != UINT_MAX);
515
516 log_debug("PCR %u value: %s", j, strna(h));
517 }
518
519 if (!memeqbyte(0x00, pcr_values->digests[i].buffer, pcr_values->digests[i].size) &&
520 !memeqbyte(0xFF, pcr_values->digests[i].buffer, pcr_values->digests[i].size))
521 good = true;
522 }
523
524 return good;
525 }
526
527 static int tpm2_bank_has24(const TPMS_PCR_SELECTION *selection) {
528
529 assert(selection);
530
531 /* As per https://trustedcomputinggroup.org/wp-content/uploads/TCG_PCClient_PFP_r1p05_v23_pub.pdf a
532 * TPM2 on a Client PC must have at least 24 PCRs. If this TPM has less, just skip over it. */
533 if (selection->sizeofSelect < TPM2_PCRS_MAX/8) {
534 log_debug("Skipping TPM2 PCR bank %s with fewer than 24 PCRs.",
535 strna(tpm2_pcr_bank_to_string(selection->hash)));
536 return false;
537 }
538
539 assert_cc(TPM2_PCRS_MAX % 8 == 0);
540
541 /* It's not enough to check how many PCRs there are, we also need to check that the 24 are
542 * enabled for this bank. Otherwise this TPM doesn't qualify. */
543 bool valid = true;
544 for (size_t j = 0; j < TPM2_PCRS_MAX/8; j++)
545 if (selection->pcrSelect[j] != 0xFF) {
546 valid = false;
547 break;
548 }
549
550 if (!valid)
551 log_debug("TPM2 PCR bank %s has fewer than 24 PCR bits enabled, ignoring.",
552 strna(tpm2_pcr_bank_to_string(selection->hash)));
553
554 return valid;
555 }
556
557 static int tpm2_get_best_pcr_bank(
558 ESYS_CONTEXT *c,
559 uint32_t pcr_mask,
560 TPMI_ALG_HASH *ret) {
561
562 _cleanup_(Esys_Freep) TPMS_CAPABILITY_DATA *pcap = NULL;
563 TPMI_ALG_HASH supported_hash = 0, hash_with_valid_pcr = 0;
564 TPMI_YES_NO more;
565 TSS2_RC rc;
566 int r;
567
568 assert(c);
569
570 rc = sym_Esys_GetCapability(
571 c,
572 ESYS_TR_NONE,
573 ESYS_TR_NONE,
574 ESYS_TR_NONE,
575 TPM2_CAP_PCRS,
576 0,
577 1,
578 &more,
579 &pcap);
580 if (rc != TSS2_RC_SUCCESS)
581 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
582 "Failed to determine TPM2 PCR bank capabilities: %s", sym_Tss2_RC_Decode(rc));
583
584 assert(pcap->capability == TPM2_CAP_PCRS);
585
586 for (size_t i = 0; i < pcap->data.assignedPCR.count; i++) {
587 int good;
588
589 /* For now we are only interested in the SHA1 and SHA256 banks */
590 if (!IN_SET(pcap->data.assignedPCR.pcrSelections[i].hash, TPM2_ALG_SHA256, TPM2_ALG_SHA1))
591 continue;
592
593 r = tpm2_bank_has24(pcap->data.assignedPCR.pcrSelections + i);
594 if (r < 0)
595 return r;
596 if (!r)
597 continue;
598
599 good = tpm2_pcr_mask_good(c, pcap->data.assignedPCR.pcrSelections[i].hash, pcr_mask);
600 if (good < 0)
601 return good;
602
603 if (pcap->data.assignedPCR.pcrSelections[i].hash == TPM2_ALG_SHA256) {
604 supported_hash = TPM2_ALG_SHA256;
605 if (good) {
606 /* Great, SHA256 is supported and has initialized PCR values, we are done. */
607 hash_with_valid_pcr = TPM2_ALG_SHA256;
608 break;
609 }
610 } else {
611 assert(pcap->data.assignedPCR.pcrSelections[i].hash == TPM2_ALG_SHA1);
612
613 if (supported_hash == 0)
614 supported_hash = TPM2_ALG_SHA1;
615
616 if (good && hash_with_valid_pcr == 0)
617 hash_with_valid_pcr = TPM2_ALG_SHA1;
618 }
619 }
620
621 /* We preferably pick SHA256, but only if its PCRs are initialized or neither the SHA1 nor the SHA256
622 * PCRs are initialized. If SHA256 is not supported but SHA1 is and its PCRs are too, we prefer
623 * SHA1.
624 *
625 * We log at LOG_NOTICE level whenever we end up using the SHA1 bank or when the PCRs we bind to are
626 * not initialized. */
627
628 if (hash_with_valid_pcr == TPM2_ALG_SHA256) {
629 assert(supported_hash == TPM2_ALG_SHA256);
630 log_debug("TPM2 device supports SHA256 PCR bank and SHA256 PCRs are valid, yay!");
631 *ret = TPM2_ALG_SHA256;
632 } else if (hash_with_valid_pcr == TPM2_ALG_SHA1) {
633 if (supported_hash == TPM2_ALG_SHA256)
634 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.");
635 else {
636 assert(supported_hash == TPM2_ALG_SHA1);
637 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.");
638 }
639
640 *ret = TPM2_ALG_SHA1;
641 } else if (supported_hash == TPM2_ALG_SHA256) {
642 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!");
643 *ret = TPM2_ALG_SHA256;
644 } else if (supported_hash == TPM2_ALG_SHA1) {
645 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!");
646 *ret = TPM2_ALG_SHA1;
647 } else
648 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
649 "TPM2 module supports neither SHA1 nor SHA256 PCR banks, cannot operate.");
650
651 return 0;
652 }
653
654 int tpm2_get_good_pcr_banks(
655 ESYS_CONTEXT *c,
656 uint32_t pcr_mask,
657 TPMI_ALG_HASH **ret) {
658
659 _cleanup_free_ TPMI_ALG_HASH *good_banks = NULL, *fallback_banks = NULL;
660 _cleanup_(Esys_Freep) TPMS_CAPABILITY_DATA *pcap = NULL;
661 size_t n_good_banks = 0, n_fallback_banks = 0;
662 TPMI_YES_NO more;
663 TSS2_RC rc;
664 int r;
665
666 assert(c);
667 assert(ret);
668
669 rc = sym_Esys_GetCapability(
670 c,
671 ESYS_TR_NONE,
672 ESYS_TR_NONE,
673 ESYS_TR_NONE,
674 TPM2_CAP_PCRS,
675 0,
676 1,
677 &more,
678 &pcap);
679 if (rc != TSS2_RC_SUCCESS)
680 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
681 "Failed to determine TPM2 PCR bank capabilities: %s", sym_Tss2_RC_Decode(rc));
682
683 assert(pcap->capability == TPM2_CAP_PCRS);
684
685 for (size_t i = 0; i < pcap->data.assignedPCR.count; i++) {
686
687 /* Let's see if this bank is superficially OK, i.e. has at least 24 enabled registers */
688 r = tpm2_bank_has24(pcap->data.assignedPCR.pcrSelections + i);
689 if (r < 0)
690 return r;
691 if (!r)
692 continue;
693
694 /* Let's now see if this bank has any of the selected PCRs actually initialized */
695 r = tpm2_pcr_mask_good(c, pcap->data.assignedPCR.pcrSelections[i].hash, pcr_mask);
696 if (r < 0)
697 return r;
698
699 if (n_good_banks + n_fallback_banks >= INT_MAX)
700 return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "Too many good TPM2 banks?");
701
702 if (r) {
703 if (!GREEDY_REALLOC(good_banks, n_good_banks+1))
704 return log_oom();
705
706 good_banks[n_good_banks++] = pcap->data.assignedPCR.pcrSelections[i].hash;
707 } else {
708 if (!GREEDY_REALLOC(fallback_banks, n_fallback_banks+1))
709 return log_oom();
710
711 fallback_banks[n_fallback_banks++] = pcap->data.assignedPCR.pcrSelections[i].hash;
712 }
713 }
714
715 /* Preferably, use the good banks (i.e. the ones the PCR values are actually initialized so
716 * far). Otherwise use the fallback banks (i.e. which exist and are enabled, but so far not used. */
717 if (n_good_banks > 0) {
718 log_debug("Found %zu fully initialized TPM2 banks.", n_good_banks);
719 *ret = TAKE_PTR(good_banks);
720 return (int) n_good_banks;
721 }
722 if (n_fallback_banks > 0) {
723 log_debug("Found %zu enabled but un-initialized TPM2 banks.", n_fallback_banks);
724 *ret = TAKE_PTR(fallback_banks);
725 return (int) n_fallback_banks;
726 }
727
728 /* No suitable banks found. */
729 *ret = NULL;
730 return 0;
731 }
732
733 static void hash_pin(const char *pin, size_t len, TPM2B_AUTH *auth) {
734 struct sha256_ctx hash;
735
736 assert(auth);
737 assert(pin);
738 auth->size = SHA256_DIGEST_SIZE;
739
740 sha256_init_ctx(&hash);
741 sha256_process_bytes(pin, len, &hash);
742 sha256_finish_ctx(&hash, auth->buffer);
743
744 explicit_bzero_safe(&hash, sizeof(hash));
745 }
746
747 static int tpm2_make_encryption_session(
748 ESYS_CONTEXT *c,
749 ESYS_TR primary,
750 ESYS_TR bind_key,
751 const char *pin,
752 ESYS_TR *ret_session) {
753
754 static const TPMT_SYM_DEF symmetric = {
755 .algorithm = TPM2_ALG_AES,
756 .keyBits.aes = 128,
757 .mode.aes = TPM2_ALG_CFB,
758 };
759 const TPMA_SESSION sessionAttributes = TPMA_SESSION_DECRYPT | TPMA_SESSION_ENCRYPT |
760 TPMA_SESSION_CONTINUESESSION;
761 ESYS_TR session = ESYS_TR_NONE;
762 TSS2_RC rc;
763
764 assert(c);
765
766 /*
767 * if a pin is set for the seal object, use it to bind the session
768 * key to that object. This prevents active bus interposers from
769 * faking a TPM and seeing the unsealed value. An active interposer
770 * could fake a TPM, satisfying the encrypted session, and just
771 * forward everything to the *real* TPM.
772 */
773 if (pin) {
774 TPM2B_AUTH auth = {};
775
776 hash_pin(pin, strlen(pin), &auth);
777
778 rc = sym_Esys_TR_SetAuth(c, bind_key, &auth);
779 /* ESAPI knows about it, so clear it from our memory */
780 explicit_bzero_safe(&auth, sizeof(auth));
781 if (rc != TSS2_RC_SUCCESS)
782 return log_error_errno(
783 SYNTHETIC_ERRNO(ENOTRECOVERABLE),
784 "Failed to load PIN in TPM: %s",
785 sym_Tss2_RC_Decode(rc));
786 }
787
788 log_debug("Starting HMAC encryption session.");
789
790 /* Start a salted, unbound HMAC session with a well-known key (e.g. primary key) as tpmKey, which
791 * means that the random salt will be encrypted with the well-known key. That way, only the TPM can
792 * recover the salt, which is then used for key derivation. */
793 rc = sym_Esys_StartAuthSession(
794 c,
795 primary,
796 bind_key,
797 ESYS_TR_NONE,
798 ESYS_TR_NONE,
799 ESYS_TR_NONE,
800 NULL,
801 TPM2_SE_HMAC,
802 &symmetric,
803 TPM2_ALG_SHA256,
804 &session);
805 if (rc != TSS2_RC_SUCCESS)
806 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
807 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc));
808
809 /* Enable parameter encryption/decryption with AES in CFB mode. Together with HMAC digests (which are
810 * always used for sessions), this provides confidentiality, integrity and replay protection for
811 * operations that use this session. */
812 rc = sym_Esys_TRSess_SetAttributes(c, session, sessionAttributes, 0xff);
813 if (rc != TSS2_RC_SUCCESS)
814 return log_error_errno(
815 SYNTHETIC_ERRNO(ENOTRECOVERABLE),
816 "Failed to configure TPM session: %s",
817 sym_Tss2_RC_Decode(rc));
818
819 if (ret_session) {
820 *ret_session = session;
821 session = ESYS_TR_NONE;
822 }
823
824 session = tpm2_flush_context_verbose(c, session);
825 return 0;
826 }
827
828 #if HAVE_OPENSSL
829 static int openssl_pubkey_to_tpm2_pubkey(EVP_PKEY *input, TPM2B_PUBLIC *output) {
830 #if OPENSSL_VERSION_MAJOR >= 3
831 _cleanup_(BN_freep) BIGNUM *n = NULL, *e = NULL;
832 #else
833 const BIGNUM *n = NULL, *e = NULL;
834 const RSA *rsa = NULL;
835 #endif
836 int n_bytes, e_bytes;
837
838 assert(input);
839 assert(output);
840
841 /* Converts an OpenSSL public key to a structure that the TPM chip can process. */
842
843 if (EVP_PKEY_base_id(input) != EVP_PKEY_RSA)
844 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Provided public key is not an RSA key.");
845
846 #if OPENSSL_VERSION_MAJOR >= 3
847 if (!EVP_PKEY_get_bn_param(input, OSSL_PKEY_PARAM_RSA_N, &n))
848 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to get RSA modulus from public key.");
849 #else
850 rsa = EVP_PKEY_get0_RSA(input);
851 if (!rsa)
852 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to extract RSA key from public key.");
853
854 n = RSA_get0_n(rsa);
855 if (!n)
856 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to get RSA modulus from public key.");
857 #endif
858
859 n_bytes = BN_num_bytes(n);
860 assert_se(n_bytes > 0);
861 if ((size_t) n_bytes > sizeof_field(TPM2B_PUBLIC, publicArea.unique.rsa.buffer))
862 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "RSA modulus too large for TPM2 public key object.");
863
864 #if OPENSSL_VERSION_MAJOR >= 3
865 if (!EVP_PKEY_get_bn_param(input, OSSL_PKEY_PARAM_RSA_E, &e))
866 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to get RSA exponent from public key.");
867 #else
868 e = RSA_get0_e(rsa);
869 if (!e)
870 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to get RSA exponent from public key.");
871 #endif
872
873 e_bytes = BN_num_bytes(e);
874 assert_se(e_bytes > 0);
875 if ((size_t) e_bytes > sizeof_field(TPM2B_PUBLIC, publicArea.parameters.rsaDetail.exponent))
876 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "RSA exponent too large for TPM2 public key object.");
877
878 *output = (TPM2B_PUBLIC) {
879 .size = sizeof(TPMT_PUBLIC),
880 .publicArea = {
881 .type = TPM2_ALG_RSA,
882 .nameAlg = TPM2_ALG_SHA256,
883 .objectAttributes = TPMA_OBJECT_DECRYPT | TPMA_OBJECT_SIGN_ENCRYPT | TPMA_OBJECT_USERWITHAUTH,
884 .parameters.rsaDetail = {
885 .scheme = {
886 .scheme = TPM2_ALG_NULL,
887 .details.anySig.hashAlg = TPM2_ALG_NULL,
888 },
889 .symmetric = {
890 .algorithm = TPM2_ALG_NULL,
891 .mode.sym = TPM2_ALG_NULL,
892 },
893 .keyBits = n_bytes * 8,
894 /* .exponent will be filled in below. */
895 },
896 .unique = {
897 .rsa.size = n_bytes,
898 /* .rsa.buffer will be filled in below. */
899 },
900 },
901 };
902
903 if (BN_bn2bin(n, output->publicArea.unique.rsa.buffer) <= 0)
904 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to convert RSA modulus.");
905
906 if (BN_bn2bin(e, (unsigned char*) &output->publicArea.parameters.rsaDetail.exponent) <= 0)
907 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to convert RSA exponent.");
908
909 return 0;
910 }
911
912 static int find_signature(
913 JsonVariant *v,
914 uint16_t pcr_bank,
915 uint32_t pcr_mask,
916 EVP_PKEY *pk,
917 const void *policy,
918 size_t policy_size,
919 void *ret_signature,
920 size_t *ret_signature_size) {
921
922 _cleanup_free_ void *fp = NULL;
923 JsonVariant *b, *i;
924 size_t fp_size;
925 const char *k;
926 int r;
927
928 /* Searches for a signature blob in the specified JSON object. Search keys are PCR bank, PCR mask,
929 * public key, and policy digest. */
930
931 if (!json_variant_is_object(v))
932 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Signature is not a JSON object.");
933
934 k = tpm2_pcr_bank_to_string(pcr_bank);
935 if (!k)
936 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Don't know PCR bank %" PRIu16, pcr_bank);
937
938 /* First, find field by bank */
939 b = json_variant_by_key(v, k);
940 if (!b)
941 return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "Signature lacks data for PCR bank '%s'.", k);
942
943 if (!json_variant_is_array(b))
944 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Bank data is not a JSON array.");
945
946 /* Now iterate through all signatures known for this bank */
947 JSON_VARIANT_ARRAY_FOREACH(i, b) {
948 _cleanup_free_ void *fpj_data = NULL, *polj_data = NULL;
949 JsonVariant *maskj, *fpj, *sigj, *polj;
950 size_t fpj_size, polj_size;
951 uint32_t parsed_mask;
952
953 if (!json_variant_is_object(i))
954 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Bank data element is not a JSON object");
955
956 /* Check if the PCR mask matches our expectations */
957 maskj = json_variant_by_key(i, "pcrs");
958 if (!maskj)
959 continue;
960
961 r = tpm2_parse_pcr_json_array(maskj, &parsed_mask);
962 if (r < 0)
963 return log_error_errno(r, "Failed to parse JSON PCR mask");
964
965 if (parsed_mask != pcr_mask)
966 continue; /* Not for this PCR mask */
967
968 /* Then check if this is for the public key we operate with */
969 fpj = json_variant_by_key(i, "pkfp");
970 if (!fpj)
971 continue;
972
973 r = json_variant_unhex(fpj, &fpj_data, &fpj_size);
974 if (r < 0)
975 return log_error_errno(r, "Failed to decode fingerprint in JSON data: %m");
976
977 if (!fp) {
978 r = pubkey_fingerprint(pk, EVP_sha256(), &fp, &fp_size);
979 if (r < 0)
980 return log_error_errno(r, "Failed to calculate public key fingerprint: %m");
981 }
982
983 if (memcmp_nn(fp, fp_size, fpj_data, fpj_size) != 0)
984 continue; /* Not for this public key */
985
986 /* Finally, check if this is for the PCR policy we expect this to be */
987 polj = json_variant_by_key(i, "pol");
988 if (!polj)
989 continue;
990
991 r = json_variant_unhex(polj, &polj_data, &polj_size);
992 if (r < 0)
993 return log_error_errno(r, "Failed to decode policy hash JSON data: %m");
994
995 if (memcmp_nn(policy, policy_size, polj_data, polj_size) != 0)
996 continue;
997
998 /* This entry matches all our expectations, now return the signature included in it */
999 sigj = json_variant_by_key(i, "sig");
1000 if (!sigj)
1001 continue;
1002
1003 return json_variant_unbase64(sigj, ret_signature, ret_signature_size);
1004 }
1005
1006 return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "Couldn't find signature for this PCR bank, PCR index and public key.");
1007 }
1008 #endif
1009
1010 static int tpm2_make_policy_session(
1011 ESYS_CONTEXT *c,
1012 ESYS_TR primary,
1013 ESYS_TR parent_session,
1014 TPM2_SE session_type,
1015 uint32_t hash_pcr_mask,
1016 uint16_t pcr_bank, /* If UINT16_MAX, pick best bank automatically, otherwise specify bank explicitly. */
1017 const void *pubkey,
1018 size_t pubkey_size,
1019 uint32_t pubkey_pcr_mask,
1020 JsonVariant *signature_json,
1021 bool use_pin,
1022 ESYS_TR *ret_session,
1023 TPM2B_DIGEST **ret_policy_digest,
1024 TPMI_ALG_HASH *ret_pcr_bank) {
1025
1026 static const TPMT_SYM_DEF symmetric = {
1027 .algorithm = TPM2_ALG_AES,
1028 .keyBits.aes = 128,
1029 .mode.aes = TPM2_ALG_CFB,
1030 };
1031 _cleanup_(Esys_Freep) TPM2B_DIGEST *policy_digest = NULL;
1032 ESYS_TR session = ESYS_TR_NONE, pubkey_handle = ESYS_TR_NONE;
1033 TSS2_RC rc;
1034 int r;
1035
1036 assert(c);
1037 assert(pubkey || pubkey_size == 0);
1038 assert(pubkey_pcr_mask == 0 || pubkey_size > 0);
1039
1040 log_debug("Starting authentication session.");
1041
1042 /* So apparently some TPM implementations don't implement trial mode correctly. To avoid issues let's
1043 * avoid it when it is easy to. At the moment we only really need trial mode for the signed PCR
1044 * policies (since only then we need to shove PCR values into the policy that don't match current
1045 * state anyway), hence if we have none of those we don't need to bother. Hence, let's patch in
1046 * TPM2_SE_POLICY even if trial mode is requested unless a pubkey PCR mask is specified that is
1047 * non-zero, i.e. signed PCR policy is requested.
1048 *
1049 * One day we should switch to calculating policy hashes client side when trial mode is requested, to
1050 * avoid this mess. */
1051 if (session_type == TPM2_SE_TRIAL && pubkey_pcr_mask == 0)
1052 session_type = TPM2_SE_POLICY;
1053
1054 if ((hash_pcr_mask | pubkey_pcr_mask) != 0) {
1055 /* We are told to configure a PCR policy of some form, let's determine/validate the PCR bank to use. */
1056
1057 if (pcr_bank != UINT16_MAX) {
1058 r = tpm2_pcr_mask_good(c, pcr_bank, hash_pcr_mask|pubkey_pcr_mask);
1059 if (r < 0)
1060 return r;
1061 if (r == 0)
1062 log_warning("Selected TPM2 PCRs are not initialized on this system, most likely due to a firmware issue. PCR policy is effectively not enforced. Proceeding anyway.");
1063 } else {
1064 /* No bank configured, pick automatically. Some TPM2 devices only can do SHA1. If we
1065 * detect that use that, but preferably use SHA256 */
1066 r = tpm2_get_best_pcr_bank(c, hash_pcr_mask|pubkey_pcr_mask, &pcr_bank);
1067 if (r < 0)
1068 return r;
1069 }
1070 }
1071
1072 #if HAVE_OPENSSL
1073 _cleanup_(EVP_PKEY_freep) EVP_PKEY *pk = NULL;
1074 if (pubkey_size > 0) {
1075 /* If a pubkey is specified, load it to validate it, even if the PCR mask for this is
1076 * actually zero, and we are thus not going to use it. */
1077 _cleanup_fclose_ FILE *f = fmemopen((void*) pubkey, pubkey_size, "r");
1078 if (!f)
1079 return log_oom();
1080
1081 pk = PEM_read_PUBKEY(f, NULL, NULL, NULL);
1082 if (!pk)
1083 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse PEM public key.");
1084 }
1085 #endif
1086
1087 rc = sym_Esys_StartAuthSession(
1088 c,
1089 primary,
1090 ESYS_TR_NONE,
1091 parent_session,
1092 ESYS_TR_NONE,
1093 ESYS_TR_NONE,
1094 NULL,
1095 session_type,
1096 &symmetric,
1097 TPM2_ALG_SHA256,
1098 &session);
1099 if (rc != TSS2_RC_SUCCESS)
1100 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1101 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc));
1102
1103 if (pubkey_pcr_mask != 0) {
1104 #if HAVE_OPENSSL
1105 log_debug("Configuring public key based PCR policy.");
1106
1107 /* First: load public key into the TPM */
1108 TPM2B_PUBLIC pubkey_tpm2;
1109 r = openssl_pubkey_to_tpm2_pubkey(pk, &pubkey_tpm2);
1110 if (r < 0)
1111 goto finish;
1112
1113 rc = sym_Esys_LoadExternal(
1114 c,
1115 ESYS_TR_NONE,
1116 ESYS_TR_NONE,
1117 ESYS_TR_NONE,
1118 NULL,
1119 &pubkey_tpm2,
1120 #if HAVE_TSS2_ESYS3
1121 /* tpm2-tss >= 3.0.0 requires a ESYS_TR_RH_* constant specifying the requested
1122 * hierarchy, older versions need TPM2_RH_* instead. */
1123 ESYS_TR_RH_OWNER,
1124 #else
1125 TPM2_RH_OWNER,
1126 #endif
1127 &pubkey_handle);
1128 if (rc != TSS2_RC_SUCCESS) {
1129 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1130 "Failed to load public key into TPM: %s", sym_Tss2_RC_Decode(rc));
1131 goto finish;
1132 }
1133
1134 /* Acquire the "name" of what we just loaded */
1135 _cleanup_(Esys_Freep) TPM2B_NAME *pubkey_name = NULL;
1136 rc = sym_Esys_TR_GetName(
1137 c,
1138 pubkey_handle,
1139 &pubkey_name);
1140 if (rc != TSS2_RC_SUCCESS) {
1141 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1142 "Failed to get name of public key from TPM: %s", sym_Tss2_RC_Decode(rc));
1143 goto finish;
1144 }
1145
1146 /* Put together the PCR policy we want to use */
1147 TPML_PCR_SELECTION pcr_selection;
1148 tpm2_pcr_mask_to_selection(pubkey_pcr_mask, pcr_bank, &pcr_selection);
1149 rc = sym_Esys_PolicyPCR(
1150 c,
1151 session,
1152 ESYS_TR_NONE,
1153 ESYS_TR_NONE,
1154 ESYS_TR_NONE,
1155 NULL,
1156 &pcr_selection);
1157 if (rc != TSS2_RC_SUCCESS) {
1158 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1159 "Failed to add PCR policy to TPM: %s", sym_Tss2_RC_Decode(rc));
1160 goto finish;
1161 }
1162
1163 /* Get the policy hash of the PCR policy */
1164 _cleanup_(Esys_Freep) TPM2B_DIGEST *approved_policy = NULL;
1165 rc = sym_Esys_PolicyGetDigest(
1166 c,
1167 session,
1168 ESYS_TR_NONE,
1169 ESYS_TR_NONE,
1170 ESYS_TR_NONE,
1171 &approved_policy);
1172 if (rc != TSS2_RC_SUCCESS) {
1173 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1174 "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc));
1175 goto finish;
1176 }
1177
1178 /* When we are unlocking and have a signature, let's pass it to the TPM */
1179 _cleanup_(Esys_Freep) TPMT_TK_VERIFIED *check_ticket_buffer = NULL;
1180 const TPMT_TK_VERIFIED *check_ticket;
1181 if (signature_json) {
1182 _cleanup_free_ void *signature_raw = NULL;
1183 size_t signature_size;
1184
1185 r = find_signature(
1186 signature_json,
1187 pcr_bank,
1188 pubkey_pcr_mask,
1189 pk,
1190 approved_policy->buffer,
1191 approved_policy->size,
1192 &signature_raw,
1193 &signature_size);
1194 if (r < 0)
1195 goto finish;
1196
1197 /* TPM2_VerifySignature() will only verify the RSA part of the RSA+SHA256 signature,
1198 * hence we need to do the SHA256 part ourselves, first */
1199 TPM2B_DIGEST signature_hash = {
1200 .size = SHA256_DIGEST_SIZE,
1201 };
1202 assert(sizeof(signature_hash.buffer) >= SHA256_DIGEST_SIZE);
1203 sha256_direct(approved_policy->buffer, approved_policy->size, signature_hash.buffer);
1204
1205 TPMT_SIGNATURE policy_signature = {
1206 .sigAlg = TPM2_ALG_RSASSA,
1207 .signature.rsassa = {
1208 .hash = TPM2_ALG_SHA256,
1209 .sig.size = signature_size,
1210 },
1211 };
1212 if (signature_size > sizeof(policy_signature.signature.rsassa.sig.buffer)) {
1213 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Signature larger than buffer.");
1214 goto finish;
1215 }
1216 memcpy(policy_signature.signature.rsassa.sig.buffer, signature_raw, signature_size);
1217
1218 rc = sym_Esys_VerifySignature(
1219 c,
1220 pubkey_handle,
1221 ESYS_TR_NONE,
1222 ESYS_TR_NONE,
1223 ESYS_TR_NONE,
1224 &signature_hash,
1225 &policy_signature,
1226 &check_ticket_buffer);
1227 if (rc != TSS2_RC_SUCCESS) {
1228 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1229 "Failed to validate signature in TPM: %s", sym_Tss2_RC_Decode(rc));
1230 goto finish;
1231 }
1232
1233 check_ticket = check_ticket_buffer;
1234 } else {
1235 /* When enrolling, we pass a NULL ticket */
1236 static const TPMT_TK_VERIFIED check_ticket_null = {
1237 .tag = TPM2_ST_VERIFIED,
1238 .hierarchy = TPM2_RH_OWNER,
1239 };
1240
1241 check_ticket = &check_ticket_null;
1242 }
1243
1244 rc = sym_Esys_PolicyAuthorize(
1245 c,
1246 session,
1247 ESYS_TR_NONE,
1248 ESYS_TR_NONE,
1249 ESYS_TR_NONE,
1250 approved_policy,
1251 /* policyRef= */ &(const TPM2B_NONCE) {},
1252 pubkey_name,
1253 check_ticket);
1254 if (rc != TSS2_RC_SUCCESS) {
1255 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1256 "Failed to push Authorize policy into TPM: %s", sym_Tss2_RC_Decode(rc));
1257 goto finish;
1258 }
1259 #else
1260 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
1261 #endif
1262 }
1263
1264 if (hash_pcr_mask != 0) {
1265 log_debug("Configuring hash-based PCR policy.");
1266
1267 TPML_PCR_SELECTION pcr_selection;
1268 tpm2_pcr_mask_to_selection(hash_pcr_mask, pcr_bank, &pcr_selection);
1269 rc = sym_Esys_PolicyPCR(
1270 c,
1271 session,
1272 ESYS_TR_NONE,
1273 ESYS_TR_NONE,
1274 ESYS_TR_NONE,
1275 NULL,
1276 &pcr_selection);
1277 if (rc != TSS2_RC_SUCCESS) {
1278 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1279 "Failed to add PCR policy to TPM: %s", sym_Tss2_RC_Decode(rc));
1280 goto finish;
1281 }
1282 }
1283
1284 if (use_pin) {
1285 log_debug("Configuring PIN policy.");
1286
1287 rc = sym_Esys_PolicyAuthValue(
1288 c,
1289 session,
1290 ESYS_TR_NONE,
1291 ESYS_TR_NONE,
1292 ESYS_TR_NONE);
1293 if (rc != TSS2_RC_SUCCESS) {
1294 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1295 "Failed to add authValue policy to TPM: %s",
1296 sym_Tss2_RC_Decode(rc));
1297 goto finish;
1298 }
1299 }
1300
1301 if (DEBUG_LOGGING || ret_policy_digest) {
1302 log_debug("Acquiring policy digest.");
1303
1304 rc = sym_Esys_PolicyGetDigest(
1305 c,
1306 session,
1307 ESYS_TR_NONE,
1308 ESYS_TR_NONE,
1309 ESYS_TR_NONE,
1310 &policy_digest);
1311
1312 if (rc != TSS2_RC_SUCCESS) {
1313 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1314 "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc));
1315 goto finish;
1316 }
1317
1318 if (DEBUG_LOGGING) {
1319 _cleanup_free_ char *h = NULL;
1320
1321 h = hexmem(policy_digest->buffer, policy_digest->size);
1322 if (!h) {
1323 r = log_oom();
1324 goto finish;
1325 }
1326
1327 log_debug("Session policy digest: %s", h);
1328 }
1329 }
1330
1331 if (ret_session) {
1332 *ret_session = session;
1333 session = ESYS_TR_NONE;
1334 }
1335
1336 if (ret_policy_digest)
1337 *ret_policy_digest = TAKE_PTR(policy_digest);
1338
1339 if (ret_pcr_bank)
1340 *ret_pcr_bank = pcr_bank;
1341
1342 r = 0;
1343
1344 finish:
1345 session = tpm2_flush_context_verbose(c, session);
1346 pubkey_handle = tpm2_flush_context_verbose(c, pubkey_handle);
1347 return r;
1348 }
1349
1350 int tpm2_seal(const char *device,
1351 uint32_t hash_pcr_mask,
1352 const void *pubkey,
1353 const size_t pubkey_size,
1354 uint32_t pubkey_pcr_mask,
1355 const char *pin,
1356 void **ret_secret,
1357 size_t *ret_secret_size,
1358 void **ret_blob,
1359 size_t *ret_blob_size,
1360 void **ret_pcr_hash,
1361 size_t *ret_pcr_hash_size,
1362 uint16_t *ret_pcr_bank,
1363 uint16_t *ret_primary_alg) {
1364
1365 _cleanup_(tpm2_context_destroy) struct tpm2_context c = {};
1366 _cleanup_(Esys_Freep) TPM2B_DIGEST *policy_digest = NULL;
1367 _cleanup_(Esys_Freep) TPM2B_PRIVATE *private = NULL;
1368 _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
1369 static const TPML_PCR_SELECTION creation_pcr = {};
1370 _cleanup_(erase_and_freep) void *secret = NULL;
1371 _cleanup_free_ void *blob = NULL, *hash = NULL;
1372 TPM2B_SENSITIVE_CREATE hmac_sensitive;
1373 ESYS_TR primary = ESYS_TR_NONE, session = ESYS_TR_NONE;
1374 TPMI_ALG_PUBLIC primary_alg;
1375 TPM2B_PUBLIC hmac_template;
1376 TPMI_ALG_HASH pcr_bank;
1377 size_t k, blob_size;
1378 usec_t start;
1379 TSS2_RC rc;
1380 int r;
1381
1382 assert(pubkey || pubkey_size == 0);
1383
1384 assert(ret_secret);
1385 assert(ret_secret_size);
1386 assert(ret_blob);
1387 assert(ret_blob_size);
1388 assert(ret_pcr_hash);
1389 assert(ret_pcr_hash_size);
1390 assert(ret_pcr_bank);
1391
1392 assert(TPM2_PCR_MASK_VALID(hash_pcr_mask));
1393 assert(TPM2_PCR_MASK_VALID(pubkey_pcr_mask));
1394
1395 /* So here's what we do here: we connect to the TPM2 chip. It persistently contains a "seed" key that
1396 * is randomized when the TPM2 is first initialized or reset and remains stable across boots. We
1397 * generate a "primary" key pair derived from that (ECC if possible, RSA as fallback). Given the seed
1398 * remains fixed this will result in the same key pair whenever we specify the exact same parameters
1399 * for it. We then create a PCR-bound policy session, which calculates a hash on the current PCR
1400 * values of the indexes we specify. We then generate a randomized key on the host (which is the key
1401 * we actually enroll in the LUKS2 keyslots), which we upload into the TPM2, where it is encrypted
1402 * with the "primary" key, taking the PCR policy session into account. We then download the encrypted
1403 * key from the TPM2 ("sealing") and marshall it into binary form, which is ultimately placed in the
1404 * LUKS2 JSON header.
1405 *
1406 * The TPM2 "seed" key and "primary" keys never leave the TPM2 chip (and cannot be extracted at
1407 * all). The random key we enroll in LUKS2 we generate on the host using the Linux random device. It
1408 * is stored in the LUKS2 JSON only in encrypted form with the "primary" key of the TPM2 chip, thus
1409 * binding the unlocking to the TPM2 chip. */
1410
1411 start = now(CLOCK_MONOTONIC);
1412
1413 r = tpm2_context_init(device, &c);
1414 if (r < 0)
1415 return r;
1416
1417 r = tpm2_make_primary(c.esys_context, &primary, 0, &primary_alg);
1418 if (r < 0)
1419 return r;
1420
1421 /* we cannot use the bind key before its created */
1422 r = tpm2_make_encryption_session(c.esys_context, primary, ESYS_TR_NONE, NULL, &session);
1423 if (r < 0)
1424 goto finish;
1425
1426 r = tpm2_make_policy_session(
1427 c.esys_context,
1428 primary,
1429 session,
1430 TPM2_SE_TRIAL,
1431 hash_pcr_mask,
1432 /* pcr_bank= */ UINT16_MAX,
1433 pubkey, pubkey_size,
1434 pubkey_pcr_mask,
1435 /* signature_json= */ NULL,
1436 !!pin,
1437 /* ret_session= */ NULL,
1438 &policy_digest,
1439 &pcr_bank);
1440 if (r < 0)
1441 goto finish;
1442
1443 /* We use a keyed hash object (i.e. HMAC) to store the secret key we want to use for unlocking the
1444 * LUKS2 volume with. We don't ever use for HMAC/keyed hash operations however, we just use it
1445 * because it's a key type that is universally supported and suitable for symmetric binary blobs. */
1446 hmac_template = (TPM2B_PUBLIC) {
1447 .size = sizeof(TPMT_PUBLIC),
1448 .publicArea = {
1449 .type = TPM2_ALG_KEYEDHASH,
1450 .nameAlg = TPM2_ALG_SHA256,
1451 .objectAttributes = TPMA_OBJECT_FIXEDTPM | TPMA_OBJECT_FIXEDPARENT,
1452 .parameters.keyedHashDetail.scheme.scheme = TPM2_ALG_NULL,
1453 .unique.keyedHash.size = 32,
1454 .authPolicy = *policy_digest,
1455 },
1456 };
1457
1458 hmac_sensitive = (TPM2B_SENSITIVE_CREATE) {
1459 .size = sizeof(hmac_sensitive.sensitive),
1460 .sensitive.data.size = 32,
1461 };
1462 if (pin)
1463 hash_pin(pin, strlen(pin), &hmac_sensitive.sensitive.userAuth);
1464
1465 assert(sizeof(hmac_sensitive.sensitive.data.buffer) >= hmac_sensitive.sensitive.data.size);
1466
1467 (void) tpm2_credit_random(c.esys_context);
1468
1469 log_debug("Generating secret key data.");
1470
1471 r = crypto_random_bytes(hmac_sensitive.sensitive.data.buffer, hmac_sensitive.sensitive.data.size);
1472 if (r < 0) {
1473 log_error_errno(r, "Failed to generate secret key: %m");
1474 goto finish;
1475 }
1476
1477 log_debug("Creating HMAC key.");
1478
1479 rc = sym_Esys_Create(
1480 c.esys_context,
1481 primary,
1482 session, /* use HMAC session to enable parameter encryption */
1483 ESYS_TR_NONE,
1484 ESYS_TR_NONE,
1485 &hmac_sensitive,
1486 &hmac_template,
1487 NULL,
1488 &creation_pcr,
1489 &private,
1490 &public,
1491 NULL,
1492 NULL,
1493 NULL);
1494 if (rc != TSS2_RC_SUCCESS) {
1495 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1496 "Failed to generate HMAC key in TPM: %s", sym_Tss2_RC_Decode(rc));
1497 goto finish;
1498 }
1499
1500 secret = memdup(hmac_sensitive.sensitive.data.buffer, hmac_sensitive.sensitive.data.size);
1501 explicit_bzero_safe(hmac_sensitive.sensitive.data.buffer, hmac_sensitive.sensitive.data.size);
1502 if (!secret) {
1503 r = log_oom();
1504 goto finish;
1505 }
1506
1507 log_debug("Marshalling private and public part of HMAC key.");
1508
1509 k = ALIGN8(sizeof(*private)) + ALIGN8(sizeof(*public)); /* Some roughly sensible start value */
1510 for (;;) {
1511 _cleanup_free_ void *buf = NULL;
1512 size_t offset = 0;
1513
1514 buf = malloc(k);
1515 if (!buf) {
1516 r = log_oom();
1517 goto finish;
1518 }
1519
1520 rc = sym_Tss2_MU_TPM2B_PRIVATE_Marshal(private, buf, k, &offset);
1521 if (rc == TSS2_RC_SUCCESS) {
1522 rc = sym_Tss2_MU_TPM2B_PUBLIC_Marshal(public, buf, k, &offset);
1523 if (rc == TSS2_RC_SUCCESS) {
1524 blob = TAKE_PTR(buf);
1525 blob_size = offset;
1526 break;
1527 }
1528 }
1529 if (rc != TSS2_MU_RC_INSUFFICIENT_BUFFER) {
1530 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1531 "Failed to marshal private/public key: %s", sym_Tss2_RC_Decode(rc));
1532 goto finish;
1533 }
1534
1535 if (k > SIZE_MAX / 2) {
1536 r = log_oom();
1537 goto finish;
1538 }
1539
1540 k *= 2;
1541 }
1542
1543 hash = memdup(policy_digest->buffer, policy_digest->size);
1544 if (!hash)
1545 return log_oom();
1546
1547 if (DEBUG_LOGGING)
1548 log_debug("Completed TPM2 key sealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - start, 1));
1549
1550 *ret_secret = TAKE_PTR(secret);
1551 *ret_secret_size = hmac_sensitive.sensitive.data.size;
1552 *ret_blob = TAKE_PTR(blob);
1553 *ret_blob_size = blob_size;
1554 *ret_pcr_hash = TAKE_PTR(hash);
1555 *ret_pcr_hash_size = policy_digest->size;
1556 *ret_pcr_bank = pcr_bank;
1557 *ret_primary_alg = primary_alg;
1558
1559 r = 0;
1560
1561 finish:
1562 explicit_bzero_safe(&hmac_sensitive, sizeof(hmac_sensitive));
1563 primary = tpm2_flush_context_verbose(c.esys_context, primary);
1564 session = tpm2_flush_context_verbose(c.esys_context, session);
1565 return r;
1566 }
1567
1568 #define RETRY_UNSEAL_MAX 30u
1569
1570 int tpm2_unseal(const char *device,
1571 uint32_t hash_pcr_mask,
1572 uint16_t pcr_bank,
1573 const void *pubkey,
1574 size_t pubkey_size,
1575 uint32_t pubkey_pcr_mask,
1576 JsonVariant *signature,
1577 const char *pin,
1578 uint16_t primary_alg,
1579 const void *blob,
1580 size_t blob_size,
1581 const void *known_policy_hash,
1582 size_t known_policy_hash_size,
1583 void **ret_secret,
1584 size_t *ret_secret_size) {
1585
1586 _cleanup_(tpm2_context_destroy) struct tpm2_context c = {};
1587 ESYS_TR primary = ESYS_TR_NONE, session = ESYS_TR_NONE, hmac_session = ESYS_TR_NONE,
1588 hmac_key = ESYS_TR_NONE;
1589 _cleanup_(Esys_Freep) TPM2B_SENSITIVE_DATA* unsealed = NULL;
1590 _cleanup_(Esys_Freep) TPM2B_DIGEST *policy_digest = NULL;
1591 _cleanup_(erase_and_freep) char *secret = NULL;
1592 TPM2B_PRIVATE private = {};
1593 TPM2B_PUBLIC public = {};
1594 size_t offset = 0;
1595 TSS2_RC rc;
1596 usec_t start;
1597 int r;
1598
1599 assert(blob);
1600 assert(blob_size > 0);
1601 assert(known_policy_hash_size == 0 || known_policy_hash);
1602 assert(pubkey_size == 0 || pubkey);
1603 assert(ret_secret);
1604 assert(ret_secret_size);
1605
1606 assert(TPM2_PCR_MASK_VALID(hash_pcr_mask));
1607 assert(TPM2_PCR_MASK_VALID(pubkey_pcr_mask));
1608
1609 r = dlopen_tpm2();
1610 if (r < 0)
1611 return log_error_errno(r, "TPM2 support is not installed.");
1612
1613 /* So here's what we do here: We connect to the TPM2 chip. As we do when sealing we generate a
1614 * "primary" key on the TPM2 chip, with the same parameters as well as a PCR-bound policy session.
1615 * Given we pass the same parameters, this will result in the same "primary" key, and same policy
1616 * hash (the latter of course, only if the PCR values didn't change in between). We unmarshal the
1617 * encrypted key we stored in the LUKS2 JSON token header and upload it into the TPM2, where it is
1618 * decrypted if the seed and the PCR policy were right ("unsealing"). We then download the result,
1619 * and use it to unlock the LUKS2 volume. */
1620
1621 start = now(CLOCK_MONOTONIC);
1622
1623 log_debug("Unmarshalling private part of HMAC key.");
1624
1625 rc = sym_Tss2_MU_TPM2B_PRIVATE_Unmarshal(blob, blob_size, &offset, &private);
1626 if (rc != TSS2_RC_SUCCESS)
1627 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1628 "Failed to unmarshal private key: %s", sym_Tss2_RC_Decode(rc));
1629
1630 log_debug("Unmarshalling public part of HMAC key.");
1631
1632 rc = sym_Tss2_MU_TPM2B_PUBLIC_Unmarshal(blob, blob_size, &offset, &public);
1633 if (rc != TSS2_RC_SUCCESS)
1634 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1635 "Failed to unmarshal public key: %s", sym_Tss2_RC_Decode(rc));
1636
1637 r = tpm2_context_init(device, &c);
1638 if (r < 0)
1639 return r;
1640
1641 r = tpm2_make_primary(c.esys_context, &primary, primary_alg, NULL);
1642 if (r < 0)
1643 return r;
1644
1645 log_debug("Loading HMAC key into TPM.");
1646
1647 /*
1648 * Nothing sensitive on the bus, no need for encryption. Even if an attacker
1649 * gives you back a different key, the session initiation will fail if a pin
1650 * is provided. If an attacker gives back a bad key, we already lost since
1651 * primary key is not verified and they could attack there as well.
1652 */
1653 rc = sym_Esys_Load(
1654 c.esys_context,
1655 primary,
1656 ESYS_TR_PASSWORD,
1657 ESYS_TR_NONE,
1658 ESYS_TR_NONE,
1659 &private,
1660 &public,
1661 &hmac_key);
1662 if (rc != TSS2_RC_SUCCESS) {
1663 /* If we're in dictionary attack lockout mode, we should see a lockout error here, which we
1664 * need to translate for the caller. */
1665 if (rc == TPM2_RC_LOCKOUT)
1666 r = log_error_errno(
1667 SYNTHETIC_ERRNO(ENOLCK),
1668 "TPM2 device is in dictionary attack lockout mode.");
1669 else
1670 r = log_error_errno(
1671 SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1672 "Failed to load HMAC key in TPM: %s",
1673 sym_Tss2_RC_Decode(rc));
1674 goto finish;
1675 }
1676
1677 r = tpm2_make_encryption_session(c.esys_context, primary, hmac_key, pin, &hmac_session);
1678 if (r < 0)
1679 goto finish;
1680
1681 for (unsigned i = RETRY_UNSEAL_MAX;; i--) {
1682 r = tpm2_make_policy_session(
1683 c.esys_context,
1684 primary,
1685 hmac_session,
1686 TPM2_SE_POLICY,
1687 hash_pcr_mask,
1688 pcr_bank,
1689 pubkey, pubkey_size,
1690 pubkey_pcr_mask,
1691 signature,
1692 !!pin,
1693 &session,
1694 &policy_digest,
1695 /* ret_pcr_bank= */ NULL);
1696 if (r < 0)
1697 goto finish;
1698
1699 /* If we know the policy hash to expect, and it doesn't match, we can shortcut things here, and not
1700 * wait until the TPM2 tells us to go away. */
1701 if (known_policy_hash_size > 0 &&
1702 memcmp_nn(policy_digest->buffer, policy_digest->size, known_policy_hash, known_policy_hash_size) != 0)
1703 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
1704 "Current policy digest does not match stored policy digest, cancelling "
1705 "TPM2 authentication attempt.");
1706
1707 log_debug("Unsealing HMAC key.");
1708
1709 rc = sym_Esys_Unseal(
1710 c.esys_context,
1711 hmac_key,
1712 session,
1713 hmac_session, /* use HMAC session to enable parameter encryption */
1714 ESYS_TR_NONE,
1715 &unsealed);
1716 if (rc == TPM2_RC_PCR_CHANGED && i > 0) {
1717 log_debug("A PCR value changed during the TPM2 policy session, restarting HMAC key unsealing (%u tries left).", i);
1718 session = tpm2_flush_context_verbose(c.esys_context, session);
1719 continue;
1720 }
1721 if (rc != TSS2_RC_SUCCESS) {
1722 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
1723 "Failed to unseal HMAC key in TPM: %s", sym_Tss2_RC_Decode(rc));
1724 goto finish;
1725 }
1726
1727 break;
1728 }
1729
1730 secret = memdup(unsealed->buffer, unsealed->size);
1731 explicit_bzero_safe(unsealed->buffer, unsealed->size);
1732 if (!secret) {
1733 r = log_oom();
1734 goto finish;
1735 }
1736
1737 if (DEBUG_LOGGING)
1738 log_debug("Completed TPM2 key unsealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - start, 1));
1739
1740 *ret_secret = TAKE_PTR(secret);
1741 *ret_secret_size = unsealed->size;
1742
1743 r = 0;
1744
1745 finish:
1746 primary = tpm2_flush_context_verbose(c.esys_context, primary);
1747 session = tpm2_flush_context_verbose(c.esys_context, session);
1748 hmac_key = tpm2_flush_context_verbose(c.esys_context, hmac_key);
1749 return r;
1750 }
1751
1752 #endif
1753
1754 int tpm2_list_devices(void) {
1755 #if HAVE_TPM2
1756 _cleanup_(table_unrefp) Table *t = NULL;
1757 _cleanup_(closedirp) DIR *d = NULL;
1758 int r;
1759
1760 r = dlopen_tpm2();
1761 if (r < 0)
1762 return log_error_errno(r, "TPM2 support is not installed.");
1763
1764 t = table_new("path", "device", "driver");
1765 if (!t)
1766 return log_oom();
1767
1768 d = opendir("/sys/class/tpmrm");
1769 if (!d) {
1770 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno, "Failed to open /sys/class/tpmrm: %m");
1771 if (errno != ENOENT)
1772 return -errno;
1773 } else {
1774 for (;;) {
1775 _cleanup_free_ char *device_path = NULL, *device = NULL, *driver_path = NULL, *driver = NULL, *node = NULL;
1776 struct dirent *de;
1777
1778 de = readdir_no_dot(d);
1779 if (!de)
1780 break;
1781
1782 device_path = path_join("/sys/class/tpmrm", de->d_name, "device");
1783 if (!device_path)
1784 return log_oom();
1785
1786 r = readlink_malloc(device_path, &device);
1787 if (r < 0)
1788 log_debug_errno(r, "Failed to read device symlink %s, ignoring: %m", device_path);
1789 else {
1790 driver_path = path_join(device_path, "driver");
1791 if (!driver_path)
1792 return log_oom();
1793
1794 r = readlink_malloc(driver_path, &driver);
1795 if (r < 0)
1796 log_debug_errno(r, "Failed to read driver symlink %s, ignoring: %m", driver_path);
1797 }
1798
1799 node = path_join("/dev", de->d_name);
1800 if (!node)
1801 return log_oom();
1802
1803 r = table_add_many(
1804 t,
1805 TABLE_PATH, node,
1806 TABLE_STRING, device ? last_path_component(device) : NULL,
1807 TABLE_STRING, driver ? last_path_component(driver) : NULL);
1808 if (r < 0)
1809 return table_log_add_error(r);
1810 }
1811 }
1812
1813 if (table_get_rows(t) <= 1) {
1814 log_info("No suitable TPM2 devices found.");
1815 return 0;
1816 }
1817
1818 r = table_print(t, stdout);
1819 if (r < 0)
1820 return log_error_errno(r, "Failed to show device table: %m");
1821
1822 return 0;
1823 #else
1824 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1825 "TPM2 not supported on this build.");
1826 #endif
1827 }
1828
1829 int tpm2_find_device_auto(
1830 int log_level, /* log level when no device is found */
1831 char **ret) {
1832 #if HAVE_TPM2
1833 _cleanup_(closedirp) DIR *d = NULL;
1834 int r;
1835
1836 r = dlopen_tpm2();
1837 if (r < 0)
1838 return log_error_errno(r, "TPM2 support is not installed.");
1839
1840 d = opendir("/sys/class/tpmrm");
1841 if (!d) {
1842 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
1843 "Failed to open /sys/class/tpmrm: %m");
1844 if (errno != ENOENT)
1845 return -errno;
1846 } else {
1847 _cleanup_free_ char *node = NULL;
1848
1849 for (;;) {
1850 struct dirent *de;
1851
1852 de = readdir_no_dot(d);
1853 if (!de)
1854 break;
1855
1856 if (node)
1857 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
1858 "More than one TPM2 (tpmrm) device found.");
1859
1860 node = path_join("/dev", de->d_name);
1861 if (!node)
1862 return log_oom();
1863 }
1864
1865 if (node) {
1866 *ret = TAKE_PTR(node);
1867 return 0;
1868 }
1869 }
1870
1871 return log_full_errno(log_level, SYNTHETIC_ERRNO(ENODEV), "No TPM2 (tpmrm) device found.");
1872 #else
1873 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1874 "TPM2 not supported on this build.");
1875 #endif
1876 }
1877
1878 int tpm2_parse_pcrs(const char *s, uint32_t *ret) {
1879 const char *p = ASSERT_PTR(s);
1880 uint32_t mask = 0;
1881 int r;
1882
1883 if (isempty(s)) {
1884 *ret = 0;
1885 return 0;
1886 }
1887
1888 /* Parses a "," or "+" separated list of PCR indexes. We support "," since this is a list after all,
1889 * and most other tools expect comma separated PCR specifications. We also support "+" since in
1890 * /etc/crypttab the "," is already used to separate options, hence a different separator is nice to
1891 * avoid escaping. */
1892
1893 for (;;) {
1894 _cleanup_free_ char *pcr = NULL;
1895 unsigned n;
1896
1897 r = extract_first_word(&p, &pcr, ",+", EXTRACT_DONT_COALESCE_SEPARATORS);
1898 if (r == 0)
1899 break;
1900 if (r < 0)
1901 return log_error_errno(r, "Failed to parse PCR list: %s", s);
1902
1903 r = safe_atou(pcr, &n);
1904 if (r < 0)
1905 return log_error_errno(r, "Failed to parse PCR number: %s", pcr);
1906 if (n >= TPM2_PCRS_MAX)
1907 return log_error_errno(SYNTHETIC_ERRNO(ERANGE),
1908 "PCR number out of range (valid range 0…23): %u", n);
1909
1910 mask |= UINT32_C(1) << n;
1911 }
1912
1913 *ret = mask;
1914 return 0;
1915 }
1916
1917 int tpm2_make_pcr_json_array(uint32_t pcr_mask, JsonVariant **ret) {
1918 _cleanup_(json_variant_unrefp) JsonVariant *a = NULL;
1919 JsonVariant* pcr_array[TPM2_PCRS_MAX];
1920 unsigned n_pcrs = 0;
1921 int r;
1922
1923 for (size_t i = 0; i < ELEMENTSOF(pcr_array); i++) {
1924 if ((pcr_mask & (UINT32_C(1) << i)) == 0)
1925 continue;
1926
1927 r = json_variant_new_integer(pcr_array + n_pcrs, i);
1928 if (r < 0)
1929 goto finish;
1930
1931 n_pcrs++;
1932 }
1933
1934 r = json_variant_new_array(&a, pcr_array, n_pcrs);
1935 if (r < 0)
1936 goto finish;
1937
1938 if (ret)
1939 *ret = TAKE_PTR(a);
1940 r = 0;
1941
1942 finish:
1943 json_variant_unref_many(pcr_array, n_pcrs);
1944 return r;
1945 }
1946
1947 int tpm2_parse_pcr_json_array(JsonVariant *v, uint32_t *ret) {
1948 JsonVariant *e;
1949 uint32_t mask = 0;
1950
1951 if (!json_variant_is_array(v))
1952 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR array is not a JSON array.");
1953
1954 JSON_VARIANT_ARRAY_FOREACH(e, v) {
1955 uint64_t u;
1956
1957 if (!json_variant_is_unsigned(e))
1958 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR is not an unsigned integer.");
1959
1960 u = json_variant_unsigned(e);
1961 if (u >= TPM2_PCRS_MAX)
1962 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR number out of range: %" PRIu64, u);
1963
1964 mask |= UINT32_C(1) << u;
1965 }
1966
1967 if (ret)
1968 *ret = mask;
1969
1970 return 0;
1971 }
1972
1973 int tpm2_make_luks2_json(
1974 int keyslot,
1975 uint32_t hash_pcr_mask,
1976 uint16_t pcr_bank,
1977 const void *pubkey,
1978 size_t pubkey_size,
1979 uint32_t pubkey_pcr_mask,
1980 uint16_t primary_alg,
1981 const void *blob,
1982 size_t blob_size,
1983 const void *policy_hash,
1984 size_t policy_hash_size,
1985 TPM2Flags flags,
1986 JsonVariant **ret) {
1987
1988 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL, *hmj = NULL, *pkmj = NULL;
1989 _cleanup_free_ char *keyslot_as_string = NULL;
1990 int r;
1991
1992 assert(blob || blob_size == 0);
1993 assert(policy_hash || policy_hash_size == 0);
1994 assert(pubkey || pubkey_size == 0);
1995
1996 if (asprintf(&keyslot_as_string, "%i", keyslot) < 0)
1997 return -ENOMEM;
1998
1999 r = tpm2_make_pcr_json_array(hash_pcr_mask, &hmj);
2000 if (r < 0)
2001 return r;
2002
2003 if (pubkey_pcr_mask != 0) {
2004 r = tpm2_make_pcr_json_array(pubkey_pcr_mask, &pkmj);
2005 if (r < 0)
2006 return r;
2007 }
2008
2009 /* Note: We made the mistake of using "-" in the field names, which isn't particular compatible with
2010 * other programming languages. Let's not make things worse though, i.e. future additions to the JSON
2011 * object should use "_" rather than "-" in field names. */
2012
2013 r = json_build(&v,
2014 JSON_BUILD_OBJECT(
2015 JSON_BUILD_PAIR("type", JSON_BUILD_CONST_STRING("systemd-tpm2")),
2016 JSON_BUILD_PAIR("keyslots", JSON_BUILD_ARRAY(JSON_BUILD_STRING(keyslot_as_string))),
2017 JSON_BUILD_PAIR("tpm2-blob", JSON_BUILD_BASE64(blob, blob_size)),
2018 JSON_BUILD_PAIR("tpm2-pcrs", JSON_BUILD_VARIANT(hmj)),
2019 JSON_BUILD_PAIR_CONDITION(!!tpm2_pcr_bank_to_string(pcr_bank), "tpm2-pcr-bank", JSON_BUILD_STRING(tpm2_pcr_bank_to_string(pcr_bank))),
2020 JSON_BUILD_PAIR_CONDITION(!!tpm2_primary_alg_to_string(primary_alg), "tpm2-primary-alg", JSON_BUILD_STRING(tpm2_primary_alg_to_string(primary_alg))),
2021 JSON_BUILD_PAIR("tpm2-policy-hash", JSON_BUILD_HEX(policy_hash, policy_hash_size)),
2022 JSON_BUILD_PAIR("tpm2-pin", JSON_BUILD_BOOLEAN(flags & TPM2_FLAGS_USE_PIN)),
2023 JSON_BUILD_PAIR_CONDITION(pubkey_pcr_mask != 0, "tpm2_pubkey_pcrs", JSON_BUILD_VARIANT(pkmj)),
2024 JSON_BUILD_PAIR_CONDITION(pubkey_pcr_mask != 0, "tpm2_pubkey", JSON_BUILD_BASE64(pubkey, pubkey_size))));
2025 if (r < 0)
2026 return r;
2027
2028 if (ret)
2029 *ret = TAKE_PTR(v);
2030
2031 return keyslot;
2032 }
2033
2034 int tpm2_parse_luks2_json(
2035 JsonVariant *v,
2036 int *ret_keyslot,
2037 uint32_t *ret_hash_pcr_mask,
2038 uint16_t *ret_pcr_bank,
2039 void **ret_pubkey,
2040 size_t *ret_pubkey_size,
2041 uint32_t *ret_pubkey_pcr_mask,
2042 uint16_t *ret_primary_alg,
2043 void **ret_blob,
2044 size_t *ret_blob_size,
2045 void **ret_policy_hash,
2046 size_t *ret_policy_hash_size,
2047 TPM2Flags *ret_flags) {
2048
2049 _cleanup_free_ void *blob = NULL, *policy_hash = NULL, *pubkey = NULL;
2050 size_t blob_size = 0, policy_hash_size = 0, pubkey_size = 0;
2051 uint32_t hash_pcr_mask = 0, pubkey_pcr_mask = 0;
2052 uint16_t primary_alg = TPM2_ALG_ECC; /* ECC was the only supported algorithm in systemd < 250, use that as implied default, for compatibility */
2053 uint16_t pcr_bank = UINT16_MAX; /* default: pick automatically */
2054 int r, keyslot = -1;
2055 TPM2Flags flags = 0;
2056 JsonVariant *w;
2057
2058 assert(v);
2059
2060 if (ret_keyslot) {
2061 keyslot = cryptsetup_get_keyslot_from_token(v);
2062 if (keyslot < 0) {
2063 /* Return a recognizable error when parsing this field, so that callers can handle parsing
2064 * errors of the keyslots field gracefully, since it's not 'owned' by us, but by the LUKS2
2065 * spec */
2066 log_debug_errno(keyslot, "Failed to extract keyslot index from TPM2 JSON data token, skipping: %m");
2067 return -EUCLEAN;
2068 }
2069 }
2070
2071 w = json_variant_by_key(v, "tpm2-pcrs");
2072 if (!w)
2073 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data lacks 'tpm2-pcrs' field.");
2074
2075 r = tpm2_parse_pcr_json_array(w, &hash_pcr_mask);
2076 if (r < 0)
2077 return log_debug_errno(r, "Failed to parse TPM2 PCR mask: %m");
2078
2079 /* The bank field is optional, since it was added in systemd 250 only. Before the bank was hardcoded
2080 * to SHA256. */
2081 w = json_variant_by_key(v, "tpm2-pcr-bank");
2082 if (w) {
2083 /* The PCR bank field is optional */
2084
2085 if (!json_variant_is_string(w))
2086 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR bank is not a string.");
2087
2088 r = tpm2_pcr_bank_from_string(json_variant_string(w));
2089 if (r < 0)
2090 return log_debug_errno(r, "TPM2 PCR bank invalid or not supported: %s", json_variant_string(w));
2091
2092 pcr_bank = r;
2093 }
2094
2095 /* The primary key algorithm field is optional, since it was also added in systemd 250 only. Before
2096 * the algorithm was hardcoded to ECC. */
2097 w = json_variant_by_key(v, "tpm2-primary-alg");
2098 if (w) {
2099 /* The primary key algorithm is optional */
2100
2101 if (!json_variant_is_string(w))
2102 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 primary key algorithm is not a string.");
2103
2104 r = tpm2_primary_alg_from_string(json_variant_string(w));
2105 if (r < 0)
2106 return log_debug_errno(r, "TPM2 primary key algorithm invalid or not supported: %s", json_variant_string(w));
2107
2108 primary_alg = r;
2109 }
2110
2111 w = json_variant_by_key(v, "tpm2-blob");
2112 if (!w)
2113 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data lacks 'tpm2-blob' field.");
2114
2115 r = json_variant_unbase64(w, &blob, &blob_size);
2116 if (r < 0)
2117 return log_debug_errno(r, "Invalid base64 data in 'tpm2-blob' field.");
2118
2119 w = json_variant_by_key(v, "tpm2-policy-hash");
2120 if (!w)
2121 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data lacks 'tpm2-policy-hash' field.");
2122
2123 r = json_variant_unhex(w, &policy_hash, &policy_hash_size);
2124 if (r < 0)
2125 return log_debug_errno(r, "Invalid base64 data in 'tpm2-policy-hash' field.");
2126
2127 w = json_variant_by_key(v, "tpm2-pin");
2128 if (w) {
2129 if (!json_variant_is_boolean(w))
2130 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PIN policy is not a boolean.");
2131
2132 SET_FLAG(flags, TPM2_FLAGS_USE_PIN, json_variant_boolean(w));
2133 }
2134
2135 w = json_variant_by_key(v, "tpm2_pubkey_pcrs");
2136 if (w) {
2137 r = tpm2_parse_pcr_json_array(w, &pubkey_pcr_mask);
2138 if (r < 0)
2139 return r;
2140 }
2141
2142 w = json_variant_by_key(v, "tpm2_pubkey");
2143 if (w) {
2144 r = json_variant_unbase64(w, &pubkey, &pubkey_size);
2145 if (r < 0)
2146 return log_debug_errno(r, "Failed to decode PCR public key.");
2147 } else if (pubkey_pcr_mask != 0)
2148 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Public key PCR mask set, but not public key included in JSON data, refusing.");
2149
2150 if (ret_keyslot)
2151 *ret_keyslot = keyslot;
2152 if (ret_hash_pcr_mask)
2153 *ret_hash_pcr_mask = hash_pcr_mask;
2154 if (ret_pcr_bank)
2155 *ret_pcr_bank = pcr_bank;
2156 if (ret_pubkey)
2157 *ret_pubkey = TAKE_PTR(pubkey);
2158 if (ret_pubkey_size)
2159 *ret_pubkey_size = pubkey_size;
2160 if (ret_pubkey_pcr_mask)
2161 *ret_pubkey_pcr_mask = pubkey_pcr_mask;
2162 if (ret_primary_alg)
2163 *ret_primary_alg = primary_alg;
2164 if (ret_blob)
2165 *ret_blob = TAKE_PTR(blob);
2166 if (ret_blob_size)
2167 *ret_blob_size = blob_size;
2168 if (ret_policy_hash)
2169 *ret_policy_hash = TAKE_PTR(policy_hash);
2170 if (ret_policy_hash_size)
2171 *ret_policy_hash_size = policy_hash_size;
2172 if (ret_flags)
2173 *ret_flags = flags;
2174
2175 return 0;
2176 }
2177
2178 const char *tpm2_pcr_bank_to_string(uint16_t bank) {
2179 if (bank == TPM2_ALG_SHA1)
2180 return "sha1";
2181 if (bank == TPM2_ALG_SHA256)
2182 return "sha256";
2183 if (bank == TPM2_ALG_SHA384)
2184 return "sha384";
2185 if (bank == TPM2_ALG_SHA512)
2186 return "sha512";
2187 return NULL;
2188 }
2189
2190 int tpm2_pcr_bank_from_string(const char *bank) {
2191 if (strcaseeq_ptr(bank, "sha1"))
2192 return TPM2_ALG_SHA1;
2193 if (strcaseeq_ptr(bank, "sha256"))
2194 return TPM2_ALG_SHA256;
2195 if (strcaseeq_ptr(bank, "sha384"))
2196 return TPM2_ALG_SHA384;
2197 if (strcaseeq_ptr(bank, "sha512"))
2198 return TPM2_ALG_SHA512;
2199 return -EINVAL;
2200 }
2201
2202 const char *tpm2_primary_alg_to_string(uint16_t alg) {
2203 if (alg == TPM2_ALG_ECC)
2204 return "ecc";
2205 if (alg == TPM2_ALG_RSA)
2206 return "rsa";
2207 return NULL;
2208 }
2209
2210 int tpm2_primary_alg_from_string(const char *alg) {
2211 if (strcaseeq_ptr(alg, "ecc"))
2212 return TPM2_ALG_ECC;
2213 if (strcaseeq_ptr(alg, "rsa"))
2214 return TPM2_ALG_RSA;
2215 return -EINVAL;
2216 }
2217
2218 Tpm2Support tpm2_support(void) {
2219 Tpm2Support support = TPM2_SUPPORT_NONE;
2220 int r;
2221
2222 if (detect_container() <= 0) {
2223 /* Check if there's a /dev/tpmrm* device via sysfs. If we run in a container we likely just
2224 * got the host sysfs mounted. Since devices are generally not virtualized for containers,
2225 * let's assume containers never have a TPM, at least for now. */
2226
2227 r = dir_is_empty("/sys/class/tpmrm", /* ignore_hidden_or_backup= */ false);
2228 if (r < 0) {
2229 if (r != -ENOENT)
2230 log_debug_errno(r, "Unable to test whether /sys/class/tpmrm/ exists and is populated, assuming it is not: %m");
2231 } else if (r == 0) /* populated! */
2232 support |= TPM2_SUPPORT_SUBSYSTEM|TPM2_SUPPORT_DRIVER;
2233 else
2234 /* If the directory exists but is empty, we know the subsystem is enabled but no
2235 * driver has been loaded yet. */
2236 support |= TPM2_SUPPORT_SUBSYSTEM;
2237 }
2238
2239 if (efi_has_tpm2())
2240 support |= TPM2_SUPPORT_FIRMWARE;
2241
2242 #if HAVE_TPM2
2243 support |= TPM2_SUPPORT_SYSTEM;
2244 #endif
2245
2246 return support;
2247 }
2248
2249 int tpm2_parse_pcr_argument(const char *arg, uint32_t *mask) {
2250 uint32_t m;
2251 int r;
2252
2253 assert(mask);
2254
2255 /* For use in getopt_long() command line parsers: merges masks specified on the command line */
2256
2257 if (isempty(arg)) {
2258 *mask = 0;
2259 return 0;
2260 }
2261
2262 r = tpm2_parse_pcrs(arg, &m);
2263 if (r < 0)
2264 return r;
2265
2266 if (*mask == UINT32_MAX)
2267 *mask = m;
2268 else
2269 *mask |= m;
2270
2271 return 0;
2272 }
2273
2274 int tpm2_load_pcr_signature(const char *path, JsonVariant **ret) {
2275 _cleanup_free_ char *discovered_path = NULL;
2276 _cleanup_fclose_ FILE *f = NULL;
2277 int r;
2278
2279 /* Tries to load a JSON PCR signature file. Takes an absolute path, a simple file name or NULL. In
2280 * the latter two cases searches in /etc/, /usr/lib/, /run/, as usual. */
2281
2282 if (!path)
2283 path = "tpm2-pcr-signature.json";
2284
2285 r = search_and_fopen(path, "re", NULL, (const char**) CONF_PATHS_STRV("systemd"), &f, &discovered_path);
2286 if (r < 0)
2287 return log_debug_errno(r, "Failed to find TPM PCR signature file '%s': %m", path);
2288
2289 r = json_parse_file(f, discovered_path, 0, ret, NULL, NULL);
2290 if (r < 0)
2291 return log_debug_errno(r, "Failed to parse TPM PCR signature JSON object '%s': %m", discovered_path);
2292
2293 return 0;
2294 }
2295
2296 int tpm2_load_pcr_public_key(const char *path, void **ret_pubkey, size_t *ret_pubkey_size) {
2297 _cleanup_free_ char *discovered_path = NULL;
2298 _cleanup_fclose_ FILE *f = NULL;
2299 int r;
2300
2301 /* Tries to load a PCR public key file. Takes an absolute path, a simple file name or NULL. In the
2302 * latter two cases searches in /etc/, /usr/lib/, /run/, as usual. */
2303
2304 if (!path)
2305 path = "tpm2-pcr-public-key.pem";
2306
2307 r = search_and_fopen(path, "re", NULL, (const char**) CONF_PATHS_STRV("systemd"), &f, &discovered_path);
2308 if (r < 0)
2309 return log_debug_errno(r, "Failed to find TPM PCR public key file '%s': %m", path);
2310
2311 r = read_full_stream(f, (char**) ret_pubkey, ret_pubkey_size);
2312 if (r < 0)
2313 return log_debug_errno(r, "Failed to load TPM PCR public key PEM file '%s': %m", discovered_path);
2314
2315 return 0;
2316 }
2317
2318 int pcr_mask_to_string(uint32_t mask, char **ret) {
2319 _cleanup_free_ char *buf = NULL;
2320 int r;
2321
2322 assert(ret);
2323
2324 for (unsigned i = 0; i < TPM2_PCRS_MAX; i++) {
2325 if (!(mask & (UINT32_C(1) << i)))
2326 continue;
2327
2328 r = strextendf_with_separator(&buf, "+", "%u", i);
2329 if (r < 0)
2330 return r;
2331 }
2332
2333 *ret = TAKE_PTR(buf);
2334 return 0;
2335 }