1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include "alloc-util.h"
5 #include "cryptsetup-util.h"
6 #include "dirent-util.h"
7 #include "dlfcn-util.h"
9 #include "extract-word.h"
12 #include "format-table.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"
20 #include "stat-util.h"
21 #include "time-util.h"
22 #include "tpm2-util.h"
26 static void *libtss2_esys_dl
= NULL
;
27 static void *libtss2_rc_dl
= NULL
;
28 static void *libtss2_mu_dl
= NULL
;
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
);
54 const char* (*sym_Tss2_RC_Decode
)(TSS2_RC rc
) = NULL
;
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
;
61 int dlopen_tpm2(void) {
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
),
71 DLSYM_ARG(Esys_GetCapability
),
72 DLSYM_ARG(Esys_GetRandom
),
73 DLSYM_ARG(Esys_Initialize
),
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
));
92 r
= dlopen_many_sym_or_warn(
93 &libtss2_rc_dl
, "libtss2-rc.so.0", LOG_DEBUG
,
94 DLSYM_ARG(Tss2_RC_Decode
));
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
));
106 void tpm2_context_destroy(struct tpm2_context
*c
) {
110 sym_Esys_Finalize(&c
->esys_context
);
112 c
->tcti_context
= mfree(c
->tcti_context
);
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. */
124 sym_Esys_Finalize(c
);
127 ESYS_TR
tpm2_flush_context_verbose(ESYS_CONTEXT
*c
, ESYS_TR handle
) {
130 if (!c
|| handle
== ESYS_TR_NONE
)
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
));
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
;
153 return log_error_errno(r
, "TPM2 support not installed: %m");
156 device
= secure_getenv("SYSTEMD_TPM2_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
);
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";
170 const char *param
, *driver
, *fn
;
171 const TSS2_TCTI_INFO
* info
;
172 TSS2_TCTI_INFO_FUNC func
;
175 param
= strchr(device
, ':');
177 /* Syntax #1: Pair of driver string and arbitrary parameter */
178 driver
= strndupa_safe(device
, param
- device
);
180 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "TPM2 driver name is empty, refusing.");
183 } else if (path_is_absolute(device
) && path_is_valid(device
)) {
184 /* Syntax #2: TPM device node */
188 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid TPM2 driver string, refusing.");
190 log_debug("Using TPM2 TCTI driver '%s' with device '%s'.", driver
, param
);
192 fn
= strjoina("libtss2-tcti-", driver
, ".so.0");
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
);
198 dl
= dlopen(fn
, RTLD_NOW
);
200 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "Failed to load %s: %s", fn
, dlerror());
202 func
= dlsym(dl
, TSS2_TCTI_INFO_SYMBOL
);
204 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
205 "Failed to find TCTI info symbol " TSS2_TCTI_INFO_SYMBOL
": %s",
210 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "Unable to get TCTI info data.");
213 log_debug("Loaded TCTI module '%s' (%s) [Version %" PRIu32
"]", info
->name
, info
->description
, info
->version
);
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
));
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
));
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
));
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.");
241 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
242 "Failed to start up TPM: %s", sym_Tss2_RC_Decode(rc
));
244 *ret
= (struct tpm2_context
) {
245 .esys_context
= TAKE_PTR(c
),
246 .tcti_context
= TAKE_PTR(tcti
),
247 .tcti_dl
= TAKE_PTR(dl
),
253 #define TPM2_CREDIT_RANDOM_FLAG_PATH "/run/systemd/tpm-rng-credited"
255 static int tpm2_credit_random(ESYS_CONTEXT
*c
) {
256 size_t rps
, done
= 0;
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
268 if (access(TPM2_CREDIT_RANDOM_FLAG_PATH
, F_OK
) < 0) {
270 log_debug_errno(errno
, "Failed to detect if '" TPM2_CREDIT_RANDOM_FLAG_PATH
"' exists, ignoring: %m");
272 log_debug("Not adding TPM2 entropy to the kernel random pool again.");
273 return 0; /* Already done */
276 t
= now(CLOCK_MONOTONIC
);
278 for (rps
= random_pool_size(); rps
> 0;) {
279 _cleanup_(Esys_Freep
) TPM2B_DIGEST
*buffer
= NULL
;
281 rc
= sym_Esys_GetRandom(
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. */
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
));
292 if (buffer
->size
== 0)
293 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
294 "Zero-sized entropy returned from TPM.");
296 r
= random_write_entropy(-1, buffer
->buffer
, buffer
->size
, /* credit= */ false);
298 return log_error_errno(r
, "Failed wo write entropy to kernel: %m");
300 done
+= buffer
->size
;
301 rps
= LESS_BY(rps
, buffer
->size
);
304 log_debug("Added %zu bytes of TPM2 entropy to the kernel random pool in %s.", done
, FORMAT_TIMESPAN(now(CLOCK_MONOTONIC
) - t
, 0));
306 r
= touch(TPM2_CREDIT_RANDOM_FLAG_PATH
);
308 log_debug_errno(r
, "Failed to touch '" TPM2_CREDIT_RANDOM_FLAG_PATH
"', ignoring: %m");
313 static int tpm2_make_primary(
315 ESYS_TR
*ret_primary
,
317 TPMI_ALG_PUBLIC
*ret_alg
) {
319 static const TPM2B_SENSITIVE_CREATE primary_sensitive
= {};
320 static const TPM2B_PUBLIC primary_template_ecc
= {
321 .size
= sizeof(TPMT_PUBLIC
),
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
= {
328 .algorithm
= TPM2_ALG_AES
,
330 .mode
.aes
= TPM2_ALG_CFB
,
332 .scheme
.scheme
= TPM2_ALG_NULL
,
333 .curveID
= TPM2_ECC_NIST_P256
,
334 .kdf
.scheme
= TPM2_ALG_NULL
,
338 static const TPM2B_PUBLIC primary_template_rsa
= {
339 .size
= sizeof(TPMT_PUBLIC
),
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
= {
346 .algorithm
= TPM2_ALG_AES
,
348 .mode
.aes
= TPM2_ALG_CFB
,
350 .scheme
.scheme
= TPM2_ALG_NULL
,
356 static const TPML_PCR_SELECTION creation_pcr
= {};
357 ESYS_TR primary
= ESYS_TR_NONE
;
361 log_debug("Creating primary key on TPM.");
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. */
367 ts
= now(CLOCK_MONOTONIC
);
369 if (IN_SET(alg
, 0, TPM2_ALG_ECC
)) {
370 rc
= sym_Esys_CreatePrimary(
377 &primary_template_ecc
,
386 if (rc
!= TSS2_RC_SUCCESS
) {
388 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
389 "Failed to generate ECC primary key in TPM: %s", sym_Tss2_RC_Decode(rc
));
391 log_debug("Failed to generate ECC primary key in TPM, trying RSA: %s", sym_Tss2_RC_Decode(rc
));
393 log_debug("Successfully created ECC primary key on TPM.");
398 if (IN_SET(alg
, 0, TPM2_ALG_RSA
)) {
399 rc
= sym_Esys_CreatePrimary(
406 &primary_template_rsa
,
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
));
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.");
423 log_debug("Successfully created RSA primary key on TPM.");
426 log_debug("Generating primary key on TPM2 took %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC
) - ts
, USEC_PER_MSEC
));
428 *ret_primary
= primary
;
435 void tpm2_pcr_mask_to_selection(uint32_t mask
, uint16_t bank
, TPML_PCR_SELECTION
*ret
) {
438 /* We only do 24bit here, as that's what PC TPMs are supposed to support */
439 assert(mask
<= 0xFFFFFFU
);
441 *ret
= (TPML_PCR_SELECTION
) {
443 .pcrSelections
[0] = {
446 .pcrSelect
[0] = mask
& 0xFF,
447 .pcrSelect
[1] = (mask
>> 8) & 0xFF,
448 .pcrSelect
[2] = (mask
>> 16) & 0xFF,
453 static unsigned find_nth_bit(uint32_t mask
, unsigned n
) {
458 /* Returns the bit index of the nth set bit, e.g. mask=0b101001, n=3 → 5 */
460 for (unsigned i
= 0; i
< sizeof(mask
)*8; i
++) {
475 static int tpm2_pcr_mask_good(
480 _cleanup_(Esys_Freep
) TPML_DIGEST
*pcr_values
= NULL
;
481 TPML_PCR_SELECTION selection
;
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. */
491 tpm2_pcr_mask_to_selection(mask
, bank
, &selection
);
493 rc
= sym_Esys_PCR_Read(
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
));
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
++) {
509 _cleanup_free_
char *h
= NULL
;
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
);
516 log_debug("PCR %u value: %s", j
, strna(h
));
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
))
527 static int tpm2_bank_has24(const TPMS_PCR_SELECTION
*selection
) {
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
)));
539 assert_cc(TPM2_PCRS_MAX
% 8 == 0);
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. */
544 for (size_t j
= 0; j
< TPM2_PCRS_MAX
/8; j
++)
545 if (selection
->pcrSelect
[j
] != 0xFF) {
551 log_debug("TPM2 PCR bank %s has fewer than 24 PCR bits enabled, ignoring.",
552 strna(tpm2_pcr_bank_to_string(selection
->hash
)));
557 static int tpm2_get_best_pcr_bank(
560 TPMI_ALG_HASH
*ret
) {
562 _cleanup_(Esys_Freep
) TPMS_CAPABILITY_DATA
*pcap
= NULL
;
563 TPMI_ALG_HASH supported_hash
= 0, hash_with_valid_pcr
= 0;
570 rc
= sym_Esys_GetCapability(
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
));
584 assert(pcap
->capability
== TPM2_CAP_PCRS
);
586 for (size_t i
= 0; i
< pcap
->data
.assignedPCR
.count
; i
++) {
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
))
593 r
= tpm2_bank_has24(pcap
->data
.assignedPCR
.pcrSelections
+ i
);
599 good
= tpm2_pcr_mask_good(c
, pcap
->data
.assignedPCR
.pcrSelections
[i
].hash
, pcr_mask
);
603 if (pcap
->data
.assignedPCR
.pcrSelections
[i
].hash
== TPM2_ALG_SHA256
) {
604 supported_hash
= TPM2_ALG_SHA256
;
606 /* Great, SHA256 is supported and has initialized PCR values, we are done. */
607 hash_with_valid_pcr
= TPM2_ALG_SHA256
;
611 assert(pcap
->data
.assignedPCR
.pcrSelections
[i
].hash
== TPM2_ALG_SHA1
);
613 if (supported_hash
== 0)
614 supported_hash
= TPM2_ALG_SHA1
;
616 if (good
&& hash_with_valid_pcr
== 0)
617 hash_with_valid_pcr
= TPM2_ALG_SHA1
;
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
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. */
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.");
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.");
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
;
648 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
649 "TPM2 module supports neither SHA1 nor SHA256 PCR banks, cannot operate.");
654 int tpm2_get_good_pcr_banks(
657 TPMI_ALG_HASH
**ret
) {
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;
669 rc
= sym_Esys_GetCapability(
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
));
683 assert(pcap
->capability
== TPM2_CAP_PCRS
);
685 for (size_t i
= 0; i
< pcap
->data
.assignedPCR
.count
; i
++) {
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
);
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
);
699 if (n_good_banks
+ n_fallback_banks
>= INT_MAX
)
700 return log_error_errno(SYNTHETIC_ERRNO(E2BIG
), "Too many good TPM2 banks?");
703 if (!GREEDY_REALLOC(good_banks
, n_good_banks
+1))
706 good_banks
[n_good_banks
++] = pcap
->data
.assignedPCR
.pcrSelections
[i
].hash
;
708 if (!GREEDY_REALLOC(fallback_banks
, n_fallback_banks
+1))
711 fallback_banks
[n_fallback_banks
++] = pcap
->data
.assignedPCR
.pcrSelections
[i
].hash
;
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
;
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
;
728 /* No suitable banks found. */
733 static void hash_pin(const char *pin
, size_t len
, TPM2B_AUTH
*auth
) {
734 struct sha256_ctx hash
;
739 auth
->size
= SHA256_DIGEST_SIZE
;
743 sha256_init_ctx(&hash
);
744 sha256_process_bytes(pin
, len
, &hash
);
745 sha256_finish_ctx(&hash
, auth
->buffer
);
748 static int tpm2_make_encryption_session(
753 ESYS_TR
*ret_session
) {
755 static const TPMT_SYM_DEF symmetric
= {
756 .algorithm
= TPM2_ALG_AES
,
758 .mode
.aes
= TPM2_ALG_CFB
,
760 const TPMA_SESSION sessionAttributes
= TPMA_SESSION_DECRYPT
| TPMA_SESSION_ENCRYPT
|
761 TPMA_SESSION_CONTINUESESSION
;
762 ESYS_TR session
= ESYS_TR_NONE
;
768 * if a pin is set for the seal object, use it to bind the session
769 * key to that object. This prevents active bus interposers from
770 * faking a TPM and seeing the unsealed value. An active interposer
771 * could fake a TPM, satisfying the encrypted session, and just
772 * forward everything to the *real* TPM.
775 TPM2B_AUTH auth
= {};
779 hash_pin(pin
, strlen(pin
), &auth
);
781 rc
= sym_Esys_TR_SetAuth(c
, bind_key
, &auth
);
782 if (rc
!= TSS2_RC_SUCCESS
)
783 return log_error_errno(
784 SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
785 "Failed to load PIN in TPM: %s",
786 sym_Tss2_RC_Decode(rc
));
789 log_debug("Starting HMAC encryption session.");
791 /* Start a salted, unbound HMAC session with a well-known key (e.g. primary key) as tpmKey, which
792 * means that the random salt will be encrypted with the well-known key. That way, only the TPM can
793 * recover the salt, which is then used for key derivation. */
794 rc
= sym_Esys_StartAuthSession(
806 if (rc
!= TSS2_RC_SUCCESS
)
807 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
808 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc
));
810 /* Enable parameter encryption/decryption with AES in CFB mode. Together with HMAC digests (which are
811 * always used for sessions), this provides confidentiality, integrity and replay protection for
812 * operations that use this session. */
813 rc
= sym_Esys_TRSess_SetAttributes(c
, session
, sessionAttributes
, 0xff);
814 if (rc
!= TSS2_RC_SUCCESS
)
815 return log_error_errno(
816 SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
817 "Failed to configure TPM session: %s",
818 sym_Tss2_RC_Decode(rc
));
821 *ret_session
= session
;
822 session
= ESYS_TR_NONE
;
825 session
= tpm2_flush_context_verbose(c
, session
);
830 static int openssl_pubkey_to_tpm2_pubkey(EVP_PKEY
*input
, TPM2B_PUBLIC
*output
) {
831 #if OPENSSL_VERSION_MAJOR >= 3
832 _cleanup_(BN_freep
) BIGNUM
*n
= NULL
, *e
= NULL
;
834 const BIGNUM
*n
= NULL
, *e
= NULL
;
835 const RSA
*rsa
= NULL
;
837 int n_bytes
, e_bytes
;
842 /* Converts an OpenSSL public key to a structure that the TPM chip can process. */
844 if (EVP_PKEY_base_id(input
) != EVP_PKEY_RSA
)
845 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Provided public key is not an RSA key.");
847 #if OPENSSL_VERSION_MAJOR >= 3
848 if (!EVP_PKEY_get_bn_param(input
, OSSL_PKEY_PARAM_RSA_N
, &n
))
849 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to get RSA modulus from public key.");
851 rsa
= EVP_PKEY_get0_RSA(input
);
853 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to extract RSA key from public key.");
857 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to get RSA modulus from public key.");
860 n_bytes
= BN_num_bytes(n
);
861 assert_se(n_bytes
> 0);
862 if ((size_t) n_bytes
> sizeof_field(TPM2B_PUBLIC
, publicArea
.unique
.rsa
.buffer
))
863 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "RSA modulus too large for TPM2 public key object.");
865 #if OPENSSL_VERSION_MAJOR >= 3
866 if (!EVP_PKEY_get_bn_param(input
, OSSL_PKEY_PARAM_RSA_E
, &e
))
867 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to get RSA exponent from public key.");
871 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to get RSA exponent from public key.");
874 e_bytes
= BN_num_bytes(e
);
875 assert_se(e_bytes
> 0);
876 if ((size_t) e_bytes
> sizeof_field(TPM2B_PUBLIC
, publicArea
.parameters
.rsaDetail
.exponent
))
877 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "RSA exponent too large for TPM2 public key object.");
879 *output
= (TPM2B_PUBLIC
) {
880 .size
= sizeof(TPMT_PUBLIC
),
882 .type
= TPM2_ALG_RSA
,
883 .nameAlg
= TPM2_ALG_SHA256
,
884 .objectAttributes
= TPMA_OBJECT_DECRYPT
| TPMA_OBJECT_SIGN_ENCRYPT
| TPMA_OBJECT_USERWITHAUTH
,
885 .parameters
.rsaDetail
= {
887 .scheme
= TPM2_ALG_NULL
,
888 .details
.anySig
.hashAlg
= TPM2_ALG_NULL
,
891 .algorithm
= TPM2_ALG_NULL
,
892 .mode
.sym
= TPM2_ALG_NULL
,
894 .keyBits
= n_bytes
* 8,
895 /* .exponent will be filled in below. */
899 /* .rsa.buffer will be filled in below. */
904 if (BN_bn2bin(n
, output
->publicArea
.unique
.rsa
.buffer
) <= 0)
905 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to convert RSA modulus.");
907 if (BN_bn2bin(e
, (unsigned char*) &output
->publicArea
.parameters
.rsaDetail
.exponent
) <= 0)
908 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to convert RSA exponent.");
913 static int find_signature(
921 size_t *ret_signature_size
) {
923 _cleanup_free_
void *fp
= NULL
;
929 /* Searches for a signature blob in the specified JSON object. Search keys are PCR bank, PCR mask,
930 * public key, and policy digest. */
932 if (!json_variant_is_object(v
))
933 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature is not a JSON object.");
935 k
= tpm2_pcr_bank_to_string(pcr_bank
);
937 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Don't know PCR bank %" PRIu16
, pcr_bank
);
939 /* First, find field by bank */
940 b
= json_variant_by_key(v
, k
);
942 return log_error_errno(SYNTHETIC_ERRNO(ENXIO
), "Signature lacks data for PCR bank '%s'.", k
);
944 if (!json_variant_is_array(b
))
945 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Bank data is not a JSON array.");
947 /* Now iterate through all signatures known for this bank */
948 JSON_VARIANT_ARRAY_FOREACH(i
, b
) {
949 _cleanup_free_
void *fpj_data
= NULL
, *polj_data
= NULL
;
950 JsonVariant
*maskj
, *fpj
, *sigj
, *polj
;
951 size_t fpj_size
, polj_size
;
952 uint32_t parsed_mask
;
954 if (!json_variant_is_object(i
))
955 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Bank data element is not a JSON object");
957 /* Check if the PCR mask matches our expectations */
958 maskj
= json_variant_by_key(i
, "pcrs");
962 r
= tpm2_parse_pcr_json_array(maskj
, &parsed_mask
);
964 return log_error_errno(r
, "Failed to parse JSON PCR mask");
966 if (parsed_mask
!= pcr_mask
)
967 continue; /* Not for this PCR mask */
969 /* Then check if this is for the public key we operate with */
970 fpj
= json_variant_by_key(i
, "pkfp");
974 r
= json_variant_unhex(fpj
, &fpj_data
, &fpj_size
);
976 return log_error_errno(r
, "Failed to decode fingerprint in JSON data: %m");
979 r
= pubkey_fingerprint(pk
, EVP_sha256(), &fp
, &fp_size
);
981 return log_error_errno(r
, "Failed to calculate public key fingerprint: %m");
984 if (memcmp_nn(fp
, fp_size
, fpj_data
, fpj_size
) != 0)
985 continue; /* Not for this public key */
987 /* Finally, check if this is for the PCR policy we expect this to be */
988 polj
= json_variant_by_key(i
, "pol");
992 r
= json_variant_unhex(polj
, &polj_data
, &polj_size
);
994 return log_error_errno(r
, "Failed to decode policy hash JSON data: %m");
996 if (memcmp_nn(policy
, policy_size
, polj_data
, polj_size
) != 0)
999 /* This entry matches all our expectations, now return the signature included in it */
1000 sigj
= json_variant_by_key(i
, "sig");
1004 return json_variant_unbase64(sigj
, ret_signature
, ret_signature_size
);
1007 return log_error_errno(SYNTHETIC_ERRNO(ENXIO
), "Couldn't find signature for this PCR bank, PCR index and public key.");
1011 static int tpm2_make_policy_session(
1014 ESYS_TR parent_session
,
1015 TPM2_SE session_type
,
1016 uint32_t hash_pcr_mask
,
1017 uint16_t pcr_bank
, /* If UINT16_MAX, pick best bank automatically, otherwise specify bank explicitly. */
1020 uint32_t pubkey_pcr_mask
,
1021 JsonVariant
*signature_json
,
1023 ESYS_TR
*ret_session
,
1024 TPM2B_DIGEST
**ret_policy_digest
,
1025 TPMI_ALG_HASH
*ret_pcr_bank
) {
1027 static const TPMT_SYM_DEF symmetric
= {
1028 .algorithm
= TPM2_ALG_AES
,
1030 .mode
.aes
= TPM2_ALG_CFB
,
1032 _cleanup_(Esys_Freep
) TPM2B_DIGEST
*policy_digest
= NULL
;
1033 ESYS_TR session
= ESYS_TR_NONE
, pubkey_handle
= ESYS_TR_NONE
;
1038 assert(pubkey
|| pubkey_size
== 0);
1039 assert(pubkey_pcr_mask
== 0 || pubkey_size
> 0);
1041 log_debug("Starting authentication session.");
1043 /* So apparently some TPM implementations don't implement trial mode correctly. To avoid issues let's
1044 * avoid it when it is easy to. At the moment we only really need trial mode for the signed PCR
1045 * policies (since only then we need to shove PCR values into the policy that don't match current
1046 * state anyway), hence if we have none of those we don't need to bother. Hence, let's patch in
1047 * TPM2_SE_POLICY even if trial mode is requested unless a pubkey PCR mask is specified that is
1048 * non-zero, i.e. signed PCR policy is requested.
1050 * One day we should switch to calculating policy hashes client side when trial mode is requested, to
1051 * avoid this mess. */
1052 if (session_type
== TPM2_SE_TRIAL
&& pubkey_pcr_mask
== 0)
1053 session_type
= TPM2_SE_POLICY
;
1055 if ((hash_pcr_mask
| pubkey_pcr_mask
) != 0) {
1056 /* We are told to configure a PCR policy of some form, let's determine/validate the PCR bank to use. */
1058 if (pcr_bank
!= UINT16_MAX
) {
1059 r
= tpm2_pcr_mask_good(c
, pcr_bank
, hash_pcr_mask
|pubkey_pcr_mask
);
1063 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.");
1065 /* No bank configured, pick automatically. Some TPM2 devices only can do SHA1. If we
1066 * detect that use that, but preferably use SHA256 */
1067 r
= tpm2_get_best_pcr_bank(c
, hash_pcr_mask
|pubkey_pcr_mask
, &pcr_bank
);
1074 _cleanup_(EVP_PKEY_freep
) EVP_PKEY
*pk
= NULL
;
1075 if (pubkey_size
> 0) {
1076 /* If a pubkey is specified, load it to validate it, even if the PCR mask for this is
1077 * actually zero, and we are thus not going to use it. */
1078 _cleanup_fclose_
FILE *f
= fmemopen((void*) pubkey
, pubkey_size
, "r");
1082 pk
= PEM_read_PUBKEY(f
, NULL
, NULL
, NULL
);
1084 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse PEM public key.");
1088 rc
= sym_Esys_StartAuthSession(
1100 if (rc
!= TSS2_RC_SUCCESS
)
1101 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1102 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc
));
1104 if (pubkey_pcr_mask
!= 0) {
1106 log_debug("Configuring public key based PCR policy.");
1108 /* First: load public key into the TPM */
1109 TPM2B_PUBLIC pubkey_tpm2
;
1110 r
= openssl_pubkey_to_tpm2_pubkey(pk
, &pubkey_tpm2
);
1114 rc
= sym_Esys_LoadExternal(
1122 /* tpm2-tss >= 3.0.0 requires a ESYS_TR_RH_* constant specifying the requested
1123 * hierarchy, older versions need TPM2_RH_* instead. */
1129 if (rc
!= TSS2_RC_SUCCESS
) {
1130 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1131 "Failed to load public key into TPM: %s", sym_Tss2_RC_Decode(rc
));
1135 /* Acquire the "name" of what we just loaded */
1136 _cleanup_(Esys_Freep
) TPM2B_NAME
*pubkey_name
= NULL
;
1137 rc
= sym_Esys_TR_GetName(
1141 if (rc
!= TSS2_RC_SUCCESS
) {
1142 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1143 "Failed to get name of public key from TPM: %s", sym_Tss2_RC_Decode(rc
));
1147 /* Put together the PCR policy we want to use */
1148 TPML_PCR_SELECTION pcr_selection
;
1149 tpm2_pcr_mask_to_selection(pubkey_pcr_mask
, pcr_bank
, &pcr_selection
);
1150 rc
= sym_Esys_PolicyPCR(
1158 if (rc
!= TSS2_RC_SUCCESS
) {
1159 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1160 "Failed to add PCR policy to TPM: %s", sym_Tss2_RC_Decode(rc
));
1164 /* Get the policy hash of the PCR policy */
1165 _cleanup_(Esys_Freep
) TPM2B_DIGEST
*approved_policy
= NULL
;
1166 rc
= sym_Esys_PolicyGetDigest(
1173 if (rc
!= TSS2_RC_SUCCESS
) {
1174 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1175 "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc
));
1179 /* When we are unlocking and have a signature, let's pass it to the TPM */
1180 _cleanup_(Esys_Freep
) TPMT_TK_VERIFIED
*check_ticket_buffer
= NULL
;
1181 const TPMT_TK_VERIFIED
*check_ticket
;
1182 if (signature_json
) {
1183 _cleanup_free_
void *signature_raw
= NULL
;
1184 size_t signature_size
;
1191 approved_policy
->buffer
,
1192 approved_policy
->size
,
1198 /* TPM2_VerifySignature() will only verify the RSA part of the RSA+SHA256 signature,
1199 * hence we need to do the SHA256 part ourselves, first */
1200 TPM2B_DIGEST signature_hash
= {
1201 .size
= SHA256_DIGEST_SIZE
,
1203 assert(sizeof(signature_hash
.buffer
) >= SHA256_DIGEST_SIZE
);
1204 sha256_direct(approved_policy
->buffer
, approved_policy
->size
, signature_hash
.buffer
);
1206 TPMT_SIGNATURE policy_signature
= {
1207 .sigAlg
= TPM2_ALG_RSASSA
,
1208 .signature
.rsassa
= {
1209 .hash
= TPM2_ALG_SHA256
,
1210 .sig
.size
= signature_size
,
1213 if (signature_size
> sizeof(policy_signature
.signature
.rsassa
.sig
.buffer
)) {
1214 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "Signature larger than buffer.");
1217 memcpy(policy_signature
.signature
.rsassa
.sig
.buffer
, signature_raw
, signature_size
);
1219 rc
= sym_Esys_VerifySignature(
1227 &check_ticket_buffer
);
1228 if (rc
!= TSS2_RC_SUCCESS
) {
1229 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1230 "Failed to validate signature in TPM: %s", sym_Tss2_RC_Decode(rc
));
1234 check_ticket
= check_ticket_buffer
;
1236 /* When enrolling, we pass a NULL ticket */
1237 static const TPMT_TK_VERIFIED check_ticket_null
= {
1238 .tag
= TPM2_ST_VERIFIED
,
1239 .hierarchy
= TPM2_RH_OWNER
,
1242 check_ticket
= &check_ticket_null
;
1245 rc
= sym_Esys_PolicyAuthorize(
1252 /* policyRef= */ &(const TPM2B_NONCE
) {},
1255 if (rc
!= TSS2_RC_SUCCESS
) {
1256 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1257 "Failed to push Authorize policy into TPM: %s", sym_Tss2_RC_Decode(rc
));
1261 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "OpenSSL support is disabled.");
1265 if (hash_pcr_mask
!= 0) {
1266 log_debug("Configuring hash-based PCR policy.");
1268 TPML_PCR_SELECTION pcr_selection
;
1269 tpm2_pcr_mask_to_selection(hash_pcr_mask
, pcr_bank
, &pcr_selection
);
1270 rc
= sym_Esys_PolicyPCR(
1278 if (rc
!= TSS2_RC_SUCCESS
) {
1279 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1280 "Failed to add PCR policy to TPM: %s", sym_Tss2_RC_Decode(rc
));
1286 log_debug("Configuring PIN policy.");
1288 rc
= sym_Esys_PolicyAuthValue(
1294 if (rc
!= TSS2_RC_SUCCESS
) {
1295 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1296 "Failed to add authValue policy to TPM: %s",
1297 sym_Tss2_RC_Decode(rc
));
1302 if (DEBUG_LOGGING
|| ret_policy_digest
) {
1303 log_debug("Acquiring policy digest.");
1305 rc
= sym_Esys_PolicyGetDigest(
1313 if (rc
!= TSS2_RC_SUCCESS
) {
1314 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1315 "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc
));
1319 if (DEBUG_LOGGING
) {
1320 _cleanup_free_
char *h
= NULL
;
1322 h
= hexmem(policy_digest
->buffer
, policy_digest
->size
);
1328 log_debug("Session policy digest: %s", h
);
1333 *ret_session
= session
;
1334 session
= ESYS_TR_NONE
;
1337 if (ret_policy_digest
)
1338 *ret_policy_digest
= TAKE_PTR(policy_digest
);
1341 *ret_pcr_bank
= pcr_bank
;
1346 session
= tpm2_flush_context_verbose(c
, session
);
1347 pubkey_handle
= tpm2_flush_context_verbose(c
, pubkey_handle
);
1351 int tpm2_seal(const char *device
,
1352 uint32_t hash_pcr_mask
,
1354 const size_t pubkey_size
,
1355 uint32_t pubkey_pcr_mask
,
1358 size_t *ret_secret_size
,
1360 size_t *ret_blob_size
,
1361 void **ret_pcr_hash
,
1362 size_t *ret_pcr_hash_size
,
1363 uint16_t *ret_pcr_bank
,
1364 uint16_t *ret_primary_alg
) {
1366 _cleanup_(tpm2_context_destroy
) struct tpm2_context c
= {};
1367 _cleanup_(Esys_Freep
) TPM2B_DIGEST
*policy_digest
= NULL
;
1368 _cleanup_(Esys_Freep
) TPM2B_PRIVATE
*private = NULL
;
1369 _cleanup_(Esys_Freep
) TPM2B_PUBLIC
*public = NULL
;
1370 static const TPML_PCR_SELECTION creation_pcr
= {};
1371 _cleanup_(erase_and_freep
) void *secret
= NULL
;
1372 _cleanup_free_
void *blob
= NULL
, *hash
= NULL
;
1373 ESYS_TR primary
= ESYS_TR_NONE
, session
= ESYS_TR_NONE
;
1374 TPM2B_SENSITIVE_CREATE hmac_sensitive
;
1375 TPMI_ALG_PUBLIC primary_alg
;
1376 TPM2B_PUBLIC hmac_template
;
1377 TPMI_ALG_HASH pcr_bank
;
1378 size_t k
, blob_size
;
1383 assert(pubkey
|| pubkey_size
== 0);
1386 assert(ret_secret_size
);
1388 assert(ret_blob_size
);
1389 assert(ret_pcr_hash
);
1390 assert(ret_pcr_hash_size
);
1391 assert(ret_pcr_bank
);
1393 assert(TPM2_PCR_MASK_VALID(hash_pcr_mask
));
1394 assert(TPM2_PCR_MASK_VALID(pubkey_pcr_mask
));
1396 /* So here's what we do here: we connect to the TPM2 chip. It persistently contains a "seed" key that
1397 * is randomized when the TPM2 is first initialized or reset and remains stable across boots. We
1398 * generate a "primary" key pair derived from that (ECC if possible, RSA as fallback). Given the seed
1399 * remains fixed this will result in the same key pair whenever we specify the exact same parameters
1400 * for it. We then create a PCR-bound policy session, which calculates a hash on the current PCR
1401 * values of the indexes we specify. We then generate a randomized key on the host (which is the key
1402 * we actually enroll in the LUKS2 keyslots), which we upload into the TPM2, where it is encrypted
1403 * with the "primary" key, taking the PCR policy session into account. We then download the encrypted
1404 * key from the TPM2 ("sealing") and marshall it into binary form, which is ultimately placed in the
1405 * LUKS2 JSON header.
1407 * The TPM2 "seed" key and "primary" keys never leave the TPM2 chip (and cannot be extracted at
1408 * all). The random key we enroll in LUKS2 we generate on the host using the Linux random device. It
1409 * is stored in the LUKS2 JSON only in encrypted form with the "primary" key of the TPM2 chip, thus
1410 * binding the unlocking to the TPM2 chip. */
1412 start
= now(CLOCK_MONOTONIC
);
1414 CLEANUP_ERASE(hmac_sensitive
);
1416 r
= tpm2_context_init(device
, &c
);
1420 r
= tpm2_make_primary(c
.esys_context
, &primary
, 0, &primary_alg
);
1424 /* we cannot use the bind key before its created */
1425 r
= tpm2_make_encryption_session(c
.esys_context
, primary
, ESYS_TR_NONE
, NULL
, &session
);
1429 r
= tpm2_make_policy_session(
1435 /* pcr_bank= */ UINT16_MAX
,
1436 pubkey
, pubkey_size
,
1438 /* signature_json= */ NULL
,
1440 /* ret_session= */ NULL
,
1446 /* We use a keyed hash object (i.e. HMAC) to store the secret key we want to use for unlocking the
1447 * LUKS2 volume with. We don't ever use for HMAC/keyed hash operations however, we just use it
1448 * because it's a key type that is universally supported and suitable for symmetric binary blobs. */
1449 hmac_template
= (TPM2B_PUBLIC
) {
1450 .size
= sizeof(TPMT_PUBLIC
),
1452 .type
= TPM2_ALG_KEYEDHASH
,
1453 .nameAlg
= TPM2_ALG_SHA256
,
1454 .objectAttributes
= TPMA_OBJECT_FIXEDTPM
| TPMA_OBJECT_FIXEDPARENT
,
1455 .parameters
.keyedHashDetail
.scheme
.scheme
= TPM2_ALG_NULL
,
1456 .unique
.keyedHash
.size
= 32,
1457 .authPolicy
= *policy_digest
,
1461 hmac_sensitive
= (TPM2B_SENSITIVE_CREATE
) {
1462 .size
= sizeof(hmac_sensitive
.sensitive
),
1463 .sensitive
.data
.size
= 32,
1466 hash_pin(pin
, strlen(pin
), &hmac_sensitive
.sensitive
.userAuth
);
1468 assert(sizeof(hmac_sensitive
.sensitive
.data
.buffer
) >= hmac_sensitive
.sensitive
.data
.size
);
1470 (void) tpm2_credit_random(c
.esys_context
);
1472 log_debug("Generating secret key data.");
1474 r
= crypto_random_bytes(hmac_sensitive
.sensitive
.data
.buffer
, hmac_sensitive
.sensitive
.data
.size
);
1476 log_error_errno(r
, "Failed to generate secret key: %m");
1480 log_debug("Creating HMAC key.");
1482 rc
= sym_Esys_Create(
1485 session
, /* use HMAC session to enable parameter encryption */
1497 if (rc
!= TSS2_RC_SUCCESS
) {
1498 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1499 "Failed to generate HMAC key in TPM: %s", sym_Tss2_RC_Decode(rc
));
1503 secret
= memdup(hmac_sensitive
.sensitive
.data
.buffer
, hmac_sensitive
.sensitive
.data
.size
);
1509 log_debug("Marshalling private and public part of HMAC key.");
1511 k
= ALIGN8(sizeof(*private)) + ALIGN8(sizeof(*public)); /* Some roughly sensible start value */
1513 _cleanup_free_
void *buf
= NULL
;
1522 rc
= sym_Tss2_MU_TPM2B_PRIVATE_Marshal(private, buf
, k
, &offset
);
1523 if (rc
== TSS2_RC_SUCCESS
) {
1524 rc
= sym_Tss2_MU_TPM2B_PUBLIC_Marshal(public, buf
, k
, &offset
);
1525 if (rc
== TSS2_RC_SUCCESS
) {
1526 blob
= TAKE_PTR(buf
);
1531 if (rc
!= TSS2_MU_RC_INSUFFICIENT_BUFFER
) {
1532 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1533 "Failed to marshal private/public key: %s", sym_Tss2_RC_Decode(rc
));
1537 if (k
> SIZE_MAX
/ 2) {
1545 hash
= memdup(policy_digest
->buffer
, policy_digest
->size
);
1550 log_debug("Completed TPM2 key sealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC
) - start
, 1));
1552 *ret_secret
= TAKE_PTR(secret
);
1553 *ret_secret_size
= hmac_sensitive
.sensitive
.data
.size
;
1554 *ret_blob
= TAKE_PTR(blob
);
1555 *ret_blob_size
= blob_size
;
1556 *ret_pcr_hash
= TAKE_PTR(hash
);
1557 *ret_pcr_hash_size
= policy_digest
->size
;
1558 *ret_pcr_bank
= pcr_bank
;
1559 *ret_primary_alg
= primary_alg
;
1564 primary
= tpm2_flush_context_verbose(c
.esys_context
, primary
);
1565 session
= tpm2_flush_context_verbose(c
.esys_context
, session
);
1569 #define RETRY_UNSEAL_MAX 30u
1571 int tpm2_unseal(const char *device
,
1572 uint32_t hash_pcr_mask
,
1576 uint32_t pubkey_pcr_mask
,
1577 JsonVariant
*signature
,
1579 uint16_t primary_alg
,
1582 const void *known_policy_hash
,
1583 size_t known_policy_hash_size
,
1585 size_t *ret_secret_size
) {
1587 _cleanup_(tpm2_context_destroy
) struct tpm2_context c
= {};
1588 ESYS_TR primary
= ESYS_TR_NONE
, session
= ESYS_TR_NONE
, hmac_session
= ESYS_TR_NONE
,
1589 hmac_key
= ESYS_TR_NONE
;
1590 _cleanup_(Esys_Freep
) TPM2B_SENSITIVE_DATA
* unsealed
= NULL
;
1591 _cleanup_(Esys_Freep
) TPM2B_DIGEST
*policy_digest
= NULL
;
1592 _cleanup_(erase_and_freep
) char *secret
= NULL
;
1593 TPM2B_PRIVATE
private = {};
1594 TPM2B_PUBLIC
public = {};
1601 assert(blob_size
> 0);
1602 assert(known_policy_hash_size
== 0 || known_policy_hash
);
1603 assert(pubkey_size
== 0 || pubkey
);
1605 assert(ret_secret_size
);
1607 assert(TPM2_PCR_MASK_VALID(hash_pcr_mask
));
1608 assert(TPM2_PCR_MASK_VALID(pubkey_pcr_mask
));
1612 return log_error_errno(r
, "TPM2 support is not installed.");
1614 /* So here's what we do here: We connect to the TPM2 chip. As we do when sealing we generate a
1615 * "primary" key on the TPM2 chip, with the same parameters as well as a PCR-bound policy session.
1616 * Given we pass the same parameters, this will result in the same "primary" key, and same policy
1617 * hash (the latter of course, only if the PCR values didn't change in between). We unmarshal the
1618 * encrypted key we stored in the LUKS2 JSON token header and upload it into the TPM2, where it is
1619 * decrypted if the seed and the PCR policy were right ("unsealing"). We then download the result,
1620 * and use it to unlock the LUKS2 volume. */
1622 start
= now(CLOCK_MONOTONIC
);
1624 log_debug("Unmarshalling private part of HMAC key.");
1626 rc
= sym_Tss2_MU_TPM2B_PRIVATE_Unmarshal(blob
, blob_size
, &offset
, &private);
1627 if (rc
!= TSS2_RC_SUCCESS
)
1628 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1629 "Failed to unmarshal private key: %s", sym_Tss2_RC_Decode(rc
));
1631 log_debug("Unmarshalling public part of HMAC key.");
1633 rc
= sym_Tss2_MU_TPM2B_PUBLIC_Unmarshal(blob
, blob_size
, &offset
, &public);
1634 if (rc
!= TSS2_RC_SUCCESS
)
1635 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1636 "Failed to unmarshal public key: %s", sym_Tss2_RC_Decode(rc
));
1638 r
= tpm2_context_init(device
, &c
);
1642 r
= tpm2_make_primary(c
.esys_context
, &primary
, primary_alg
, NULL
);
1646 log_debug("Loading HMAC key into TPM.");
1649 * Nothing sensitive on the bus, no need for encryption. Even if an attacker
1650 * gives you back a different key, the session initiation will fail if a pin
1651 * is provided. If an attacker gives back a bad key, we already lost since
1652 * primary key is not verified and they could attack there as well.
1663 if (rc
!= TSS2_RC_SUCCESS
) {
1664 /* If we're in dictionary attack lockout mode, we should see a lockout error here, which we
1665 * need to translate for the caller. */
1666 if (rc
== TPM2_RC_LOCKOUT
)
1667 r
= log_error_errno(
1668 SYNTHETIC_ERRNO(ENOLCK
),
1669 "TPM2 device is in dictionary attack lockout mode.");
1671 r
= log_error_errno(
1672 SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1673 "Failed to load HMAC key in TPM: %s",
1674 sym_Tss2_RC_Decode(rc
));
1678 r
= tpm2_make_encryption_session(c
.esys_context
, primary
, hmac_key
, pin
, &hmac_session
);
1682 for (unsigned i
= RETRY_UNSEAL_MAX
;; i
--) {
1683 r
= tpm2_make_policy_session(
1690 pubkey
, pubkey_size
,
1696 /* ret_pcr_bank= */ NULL
);
1700 /* If we know the policy hash to expect, and it doesn't match, we can shortcut things here, and not
1701 * wait until the TPM2 tells us to go away. */
1702 if (known_policy_hash_size
> 0 &&
1703 memcmp_nn(policy_digest
->buffer
, policy_digest
->size
, known_policy_hash
, known_policy_hash_size
) != 0)
1704 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
1705 "Current policy digest does not match stored policy digest, cancelling "
1706 "TPM2 authentication attempt.");
1708 log_debug("Unsealing HMAC key.");
1710 rc
= sym_Esys_Unseal(
1714 hmac_session
, /* use HMAC session to enable parameter encryption */
1717 if (rc
== TPM2_RC_PCR_CHANGED
&& i
> 0) {
1718 log_debug("A PCR value changed during the TPM2 policy session, restarting HMAC key unsealing (%u tries left).", i
);
1719 session
= tpm2_flush_context_verbose(c
.esys_context
, session
);
1722 if (rc
!= TSS2_RC_SUCCESS
) {
1723 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
1724 "Failed to unseal HMAC key in TPM: %s", sym_Tss2_RC_Decode(rc
));
1731 secret
= memdup(unsealed
->buffer
, unsealed
->size
);
1732 explicit_bzero_safe(unsealed
->buffer
, unsealed
->size
);
1739 log_debug("Completed TPM2 key unsealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC
) - start
, 1));
1741 *ret_secret
= TAKE_PTR(secret
);
1742 *ret_secret_size
= unsealed
->size
;
1747 primary
= tpm2_flush_context_verbose(c
.esys_context
, primary
);
1748 session
= tpm2_flush_context_verbose(c
.esys_context
, session
);
1749 hmac_key
= tpm2_flush_context_verbose(c
.esys_context
, hmac_key
);
1755 int tpm2_list_devices(void) {
1757 _cleanup_(table_unrefp
) Table
*t
= NULL
;
1758 _cleanup_(closedirp
) DIR *d
= NULL
;
1763 return log_error_errno(r
, "TPM2 support is not installed.");
1765 t
= table_new("path", "device", "driver");
1769 d
= opendir("/sys/class/tpmrm");
1771 log_full_errno(errno
== ENOENT
? LOG_DEBUG
: LOG_ERR
, errno
, "Failed to open /sys/class/tpmrm: %m");
1772 if (errno
!= ENOENT
)
1776 _cleanup_free_
char *device_path
= NULL
, *device
= NULL
, *driver_path
= NULL
, *driver
= NULL
, *node
= NULL
;
1779 de
= readdir_no_dot(d
);
1783 device_path
= path_join("/sys/class/tpmrm", de
->d_name
, "device");
1787 r
= readlink_malloc(device_path
, &device
);
1789 log_debug_errno(r
, "Failed to read device symlink %s, ignoring: %m", device_path
);
1791 driver_path
= path_join(device_path
, "driver");
1795 r
= readlink_malloc(driver_path
, &driver
);
1797 log_debug_errno(r
, "Failed to read driver symlink %s, ignoring: %m", driver_path
);
1800 node
= path_join("/dev", de
->d_name
);
1807 TABLE_STRING
, device
? last_path_component(device
) : NULL
,
1808 TABLE_STRING
, driver
? last_path_component(driver
) : NULL
);
1810 return table_log_add_error(r
);
1814 if (table_get_rows(t
) <= 1) {
1815 log_info("No suitable TPM2 devices found.");
1819 r
= table_print(t
, stdout
);
1821 return log_error_errno(r
, "Failed to show device table: %m");
1825 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1826 "TPM2 not supported on this build.");
1830 int tpm2_find_device_auto(
1831 int log_level
, /* log level when no device is found */
1834 _cleanup_(closedirp
) DIR *d
= NULL
;
1839 return log_error_errno(r
, "TPM2 support is not installed.");
1841 d
= opendir("/sys/class/tpmrm");
1843 log_full_errno(errno
== ENOENT
? LOG_DEBUG
: LOG_ERR
, errno
,
1844 "Failed to open /sys/class/tpmrm: %m");
1845 if (errno
!= ENOENT
)
1848 _cleanup_free_
char *node
= NULL
;
1853 de
= readdir_no_dot(d
);
1858 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
1859 "More than one TPM2 (tpmrm) device found.");
1861 node
= path_join("/dev", de
->d_name
);
1867 *ret
= TAKE_PTR(node
);
1872 return log_full_errno(log_level
, SYNTHETIC_ERRNO(ENODEV
), "No TPM2 (tpmrm) device found.");
1874 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1875 "TPM2 not supported on this build.");
1879 int tpm2_parse_pcrs(const char *s
, uint32_t *ret
) {
1880 const char *p
= ASSERT_PTR(s
);
1889 /* Parses a "," or "+" separated list of PCR indexes. We support "," since this is a list after all,
1890 * and most other tools expect comma separated PCR specifications. We also support "+" since in
1891 * /etc/crypttab the "," is already used to separate options, hence a different separator is nice to
1892 * avoid escaping. */
1895 _cleanup_free_
char *pcr
= NULL
;
1898 r
= extract_first_word(&p
, &pcr
, ",+", EXTRACT_DONT_COALESCE_SEPARATORS
);
1902 return log_error_errno(r
, "Failed to parse PCR list: %s", s
);
1904 r
= safe_atou(pcr
, &n
);
1906 return log_error_errno(r
, "Failed to parse PCR number: %s", pcr
);
1907 if (n
>= TPM2_PCRS_MAX
)
1908 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
),
1909 "PCR number out of range (valid range 0…23): %u", n
);
1911 mask
|= UINT32_C(1) << n
;
1918 int tpm2_make_pcr_json_array(uint32_t pcr_mask
, JsonVariant
**ret
) {
1919 _cleanup_(json_variant_unrefp
) JsonVariant
*a
= NULL
;
1920 JsonVariant
* pcr_array
[TPM2_PCRS_MAX
];
1921 unsigned n_pcrs
= 0;
1924 for (size_t i
= 0; i
< ELEMENTSOF(pcr_array
); i
++) {
1925 if ((pcr_mask
& (UINT32_C(1) << i
)) == 0)
1928 r
= json_variant_new_integer(pcr_array
+ n_pcrs
, i
);
1935 r
= json_variant_new_array(&a
, pcr_array
, n_pcrs
);
1944 json_variant_unref_many(pcr_array
, n_pcrs
);
1948 int tpm2_parse_pcr_json_array(JsonVariant
*v
, uint32_t *ret
) {
1952 if (!json_variant_is_array(v
))
1953 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "TPM2 PCR array is not a JSON array.");
1955 JSON_VARIANT_ARRAY_FOREACH(e
, v
) {
1958 if (!json_variant_is_unsigned(e
))
1959 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "TPM2 PCR is not an unsigned integer.");
1961 u
= json_variant_unsigned(e
);
1962 if (u
>= TPM2_PCRS_MAX
)
1963 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "TPM2 PCR number out of range: %" PRIu64
, u
);
1965 mask
|= UINT32_C(1) << u
;
1974 int tpm2_make_luks2_json(
1976 uint32_t hash_pcr_mask
,
1980 uint32_t pubkey_pcr_mask
,
1981 uint16_t primary_alg
,
1984 const void *policy_hash
,
1985 size_t policy_hash_size
,
1987 JsonVariant
**ret
) {
1989 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
, *hmj
= NULL
, *pkmj
= NULL
;
1990 _cleanup_free_
char *keyslot_as_string
= NULL
;
1993 assert(blob
|| blob_size
== 0);
1994 assert(policy_hash
|| policy_hash_size
== 0);
1995 assert(pubkey
|| pubkey_size
== 0);
1997 if (asprintf(&keyslot_as_string
, "%i", keyslot
) < 0)
2000 r
= tpm2_make_pcr_json_array(hash_pcr_mask
, &hmj
);
2004 if (pubkey_pcr_mask
!= 0) {
2005 r
= tpm2_make_pcr_json_array(pubkey_pcr_mask
, &pkmj
);
2010 /* Note: We made the mistake of using "-" in the field names, which isn't particular compatible with
2011 * other programming languages. Let's not make things worse though, i.e. future additions to the JSON
2012 * object should use "_" rather than "-" in field names. */
2016 JSON_BUILD_PAIR("type", JSON_BUILD_CONST_STRING("systemd-tpm2")),
2017 JSON_BUILD_PAIR("keyslots", JSON_BUILD_ARRAY(JSON_BUILD_STRING(keyslot_as_string
))),
2018 JSON_BUILD_PAIR("tpm2-blob", JSON_BUILD_BASE64(blob
, blob_size
)),
2019 JSON_BUILD_PAIR("tpm2-pcrs", JSON_BUILD_VARIANT(hmj
)),
2020 JSON_BUILD_PAIR_CONDITION(!!tpm2_pcr_bank_to_string(pcr_bank
), "tpm2-pcr-bank", JSON_BUILD_STRING(tpm2_pcr_bank_to_string(pcr_bank
))),
2021 JSON_BUILD_PAIR_CONDITION(!!tpm2_primary_alg_to_string(primary_alg
), "tpm2-primary-alg", JSON_BUILD_STRING(tpm2_primary_alg_to_string(primary_alg
))),
2022 JSON_BUILD_PAIR("tpm2-policy-hash", JSON_BUILD_HEX(policy_hash
, policy_hash_size
)),
2023 JSON_BUILD_PAIR("tpm2-pin", JSON_BUILD_BOOLEAN(flags
& TPM2_FLAGS_USE_PIN
)),
2024 JSON_BUILD_PAIR_CONDITION(pubkey_pcr_mask
!= 0, "tpm2_pubkey_pcrs", JSON_BUILD_VARIANT(pkmj
)),
2025 JSON_BUILD_PAIR_CONDITION(pubkey_pcr_mask
!= 0, "tpm2_pubkey", JSON_BUILD_BASE64(pubkey
, pubkey_size
))));
2035 int tpm2_parse_luks2_json(
2038 uint32_t *ret_hash_pcr_mask
,
2039 uint16_t *ret_pcr_bank
,
2041 size_t *ret_pubkey_size
,
2042 uint32_t *ret_pubkey_pcr_mask
,
2043 uint16_t *ret_primary_alg
,
2045 size_t *ret_blob_size
,
2046 void **ret_policy_hash
,
2047 size_t *ret_policy_hash_size
,
2048 TPM2Flags
*ret_flags
) {
2050 _cleanup_free_
void *blob
= NULL
, *policy_hash
= NULL
, *pubkey
= NULL
;
2051 size_t blob_size
= 0, policy_hash_size
= 0, pubkey_size
= 0;
2052 uint32_t hash_pcr_mask
= 0, pubkey_pcr_mask
= 0;
2053 uint16_t primary_alg
= TPM2_ALG_ECC
; /* ECC was the only supported algorithm in systemd < 250, use that as implied default, for compatibility */
2054 uint16_t pcr_bank
= UINT16_MAX
; /* default: pick automatically */
2055 int r
, keyslot
= -1;
2056 TPM2Flags flags
= 0;
2062 keyslot
= cryptsetup_get_keyslot_from_token(v
);
2064 /* Return a recognizable error when parsing this field, so that callers can handle parsing
2065 * errors of the keyslots field gracefully, since it's not 'owned' by us, but by the LUKS2
2067 log_debug_errno(keyslot
, "Failed to extract keyslot index from TPM2 JSON data token, skipping: %m");
2072 w
= json_variant_by_key(v
, "tpm2-pcrs");
2074 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "TPM2 token data lacks 'tpm2-pcrs' field.");
2076 r
= tpm2_parse_pcr_json_array(w
, &hash_pcr_mask
);
2078 return log_debug_errno(r
, "Failed to parse TPM2 PCR mask: %m");
2080 /* The bank field is optional, since it was added in systemd 250 only. Before the bank was hardcoded
2082 w
= json_variant_by_key(v
, "tpm2-pcr-bank");
2084 /* The PCR bank field is optional */
2086 if (!json_variant_is_string(w
))
2087 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "TPM2 PCR bank is not a string.");
2089 r
= tpm2_pcr_bank_from_string(json_variant_string(w
));
2091 return log_debug_errno(r
, "TPM2 PCR bank invalid or not supported: %s", json_variant_string(w
));
2096 /* The primary key algorithm field is optional, since it was also added in systemd 250 only. Before
2097 * the algorithm was hardcoded to ECC. */
2098 w
= json_variant_by_key(v
, "tpm2-primary-alg");
2100 /* The primary key algorithm is optional */
2102 if (!json_variant_is_string(w
))
2103 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "TPM2 primary key algorithm is not a string.");
2105 r
= tpm2_primary_alg_from_string(json_variant_string(w
));
2107 return log_debug_errno(r
, "TPM2 primary key algorithm invalid or not supported: %s", json_variant_string(w
));
2112 w
= json_variant_by_key(v
, "tpm2-blob");
2114 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "TPM2 token data lacks 'tpm2-blob' field.");
2116 r
= json_variant_unbase64(w
, &blob
, &blob_size
);
2118 return log_debug_errno(r
, "Invalid base64 data in 'tpm2-blob' field.");
2120 w
= json_variant_by_key(v
, "tpm2-policy-hash");
2122 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "TPM2 token data lacks 'tpm2-policy-hash' field.");
2124 r
= json_variant_unhex(w
, &policy_hash
, &policy_hash_size
);
2126 return log_debug_errno(r
, "Invalid base64 data in 'tpm2-policy-hash' field.");
2128 w
= json_variant_by_key(v
, "tpm2-pin");
2130 if (!json_variant_is_boolean(w
))
2131 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "TPM2 PIN policy is not a boolean.");
2133 SET_FLAG(flags
, TPM2_FLAGS_USE_PIN
, json_variant_boolean(w
));
2136 w
= json_variant_by_key(v
, "tpm2_pubkey_pcrs");
2138 r
= tpm2_parse_pcr_json_array(w
, &pubkey_pcr_mask
);
2143 w
= json_variant_by_key(v
, "tpm2_pubkey");
2145 r
= json_variant_unbase64(w
, &pubkey
, &pubkey_size
);
2147 return log_debug_errno(r
, "Failed to decode PCR public key.");
2148 } else if (pubkey_pcr_mask
!= 0)
2149 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Public key PCR mask set, but not public key included in JSON data, refusing.");
2152 *ret_keyslot
= keyslot
;
2153 if (ret_hash_pcr_mask
)
2154 *ret_hash_pcr_mask
= hash_pcr_mask
;
2156 *ret_pcr_bank
= pcr_bank
;
2158 *ret_pubkey
= TAKE_PTR(pubkey
);
2159 if (ret_pubkey_size
)
2160 *ret_pubkey_size
= pubkey_size
;
2161 if (ret_pubkey_pcr_mask
)
2162 *ret_pubkey_pcr_mask
= pubkey_pcr_mask
;
2163 if (ret_primary_alg
)
2164 *ret_primary_alg
= primary_alg
;
2166 *ret_blob
= TAKE_PTR(blob
);
2168 *ret_blob_size
= blob_size
;
2169 if (ret_policy_hash
)
2170 *ret_policy_hash
= TAKE_PTR(policy_hash
);
2171 if (ret_policy_hash_size
)
2172 *ret_policy_hash_size
= policy_hash_size
;
2179 const char *tpm2_pcr_bank_to_string(uint16_t bank
) {
2180 if (bank
== TPM2_ALG_SHA1
)
2182 if (bank
== TPM2_ALG_SHA256
)
2184 if (bank
== TPM2_ALG_SHA384
)
2186 if (bank
== TPM2_ALG_SHA512
)
2191 int tpm2_pcr_bank_from_string(const char *bank
) {
2192 if (strcaseeq_ptr(bank
, "sha1"))
2193 return TPM2_ALG_SHA1
;
2194 if (strcaseeq_ptr(bank
, "sha256"))
2195 return TPM2_ALG_SHA256
;
2196 if (strcaseeq_ptr(bank
, "sha384"))
2197 return TPM2_ALG_SHA384
;
2198 if (strcaseeq_ptr(bank
, "sha512"))
2199 return TPM2_ALG_SHA512
;
2203 const char *tpm2_primary_alg_to_string(uint16_t alg
) {
2204 if (alg
== TPM2_ALG_ECC
)
2206 if (alg
== TPM2_ALG_RSA
)
2211 int tpm2_primary_alg_from_string(const char *alg
) {
2212 if (strcaseeq_ptr(alg
, "ecc"))
2213 return TPM2_ALG_ECC
;
2214 if (strcaseeq_ptr(alg
, "rsa"))
2215 return TPM2_ALG_RSA
;
2219 Tpm2Support
tpm2_support(void) {
2220 Tpm2Support support
= TPM2_SUPPORT_NONE
;
2223 if (detect_container() <= 0) {
2224 /* Check if there's a /dev/tpmrm* device via sysfs. If we run in a container we likely just
2225 * got the host sysfs mounted. Since devices are generally not virtualized for containers,
2226 * let's assume containers never have a TPM, at least for now. */
2228 r
= dir_is_empty("/sys/class/tpmrm", /* ignore_hidden_or_backup= */ false);
2231 log_debug_errno(r
, "Unable to test whether /sys/class/tpmrm/ exists and is populated, assuming it is not: %m");
2232 } else if (r
== 0) /* populated! */
2233 support
|= TPM2_SUPPORT_SUBSYSTEM
|TPM2_SUPPORT_DRIVER
;
2235 /* If the directory exists but is empty, we know the subsystem is enabled but no
2236 * driver has been loaded yet. */
2237 support
|= TPM2_SUPPORT_SUBSYSTEM
;
2241 support
|= TPM2_SUPPORT_FIRMWARE
;
2244 support
|= TPM2_SUPPORT_SYSTEM
;
2250 int tpm2_parse_pcr_argument(const char *arg
, uint32_t *mask
) {
2256 /* For use in getopt_long() command line parsers: merges masks specified on the command line */
2263 r
= tpm2_parse_pcrs(arg
, &m
);
2267 if (*mask
== UINT32_MAX
)
2275 int tpm2_load_pcr_signature(const char *path
, JsonVariant
**ret
) {
2276 _cleanup_free_
char *discovered_path
= NULL
;
2277 _cleanup_fclose_
FILE *f
= NULL
;
2280 /* Tries to load a JSON PCR signature file. Takes an absolute path, a simple file name or NULL. In
2281 * the latter two cases searches in /etc/, /usr/lib/, /run/, as usual. */
2284 path
= "tpm2-pcr-signature.json";
2286 r
= search_and_fopen(path
, "re", NULL
, (const char**) CONF_PATHS_STRV("systemd"), &f
, &discovered_path
);
2288 return log_debug_errno(r
, "Failed to find TPM PCR signature file '%s': %m", path
);
2290 r
= json_parse_file(f
, discovered_path
, 0, ret
, NULL
, NULL
);
2292 return log_debug_errno(r
, "Failed to parse TPM PCR signature JSON object '%s': %m", discovered_path
);
2297 int tpm2_load_pcr_public_key(const char *path
, void **ret_pubkey
, size_t *ret_pubkey_size
) {
2298 _cleanup_free_
char *discovered_path
= NULL
;
2299 _cleanup_fclose_
FILE *f
= NULL
;
2302 /* Tries to load a PCR public key file. Takes an absolute path, a simple file name or NULL. In the
2303 * latter two cases searches in /etc/, /usr/lib/, /run/, as usual. */
2306 path
= "tpm2-pcr-public-key.pem";
2308 r
= search_and_fopen(path
, "re", NULL
, (const char**) CONF_PATHS_STRV("systemd"), &f
, &discovered_path
);
2310 return log_debug_errno(r
, "Failed to find TPM PCR public key file '%s': %m", path
);
2312 r
= read_full_stream(f
, (char**) ret_pubkey
, ret_pubkey_size
);
2314 return log_debug_errno(r
, "Failed to load TPM PCR public key PEM file '%s': %m", discovered_path
);
2319 int pcr_mask_to_string(uint32_t mask
, char **ret
) {
2320 _cleanup_free_
char *buf
= NULL
;
2325 for (unsigned i
= 0; i
< TPM2_PCRS_MAX
; i
++) {
2326 if (!(mask
& (UINT32_C(1) << i
)))
2329 r
= strextendf_with_separator(&buf
, "+", "%u", i
);
2334 *ret
= TAKE_PTR(buf
);