HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/tpm2-util.c

506,230 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 4aac8538339b20bce33c9a3fc2508a4679393682

Lines 5001–6000 of 12,273

                bool written_set,
                TPM2B_DIGEST **ret_policy_digest) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(session);
 
        log_debug("Submitting NvWritten policy.");
 
        rc = sym_Esys_PolicyNvWritten(
                        c->esys_context,
                        session->esys_handle,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        written_set ? TPM2_YES : TPM2_NO);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to add NvWritten policy to TPM: %s",
                                       sym_Tss2_RC_Decode(rc));
 
        return tpm2_get_policy_digest(c, session, ret_policy_digest);
}
 
/* Extend 'digest' with the PolicySigned calculated hash. */
int tpm2_calculate_policy_signed(TPM2B_DIGEST *digest, const TPM2B_NAME *name) {
        TPM2_CC command = TPM2_CC_PolicySigned;
        TSS2_RC rc;
        int r;
 
        assert(digest);
        assert(digest->size == SHA256_DIGEST_SIZE);
        assert(name);
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        uint8_t buf[sizeof(command)];
        size_t offset = 0;
 
        rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, sizeof(buf), &offset);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal PolicySigned command: %s", sym_Tss2_RC_Decode(rc));
 
        if (offset != sizeof(command))
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Offset 0x%zx wrong after marshalling PolicySigned command", offset);
 
        struct iovec data[] = {
                IOVEC_MAKE(buf, offset),
                IOVEC_MAKE(name->name, name->size),
        };
 
        r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, ELEMENTSOF(data), /* extend= */ true);
        if (r < 0)
                return r;
 
        const TPM2B_NONCE policyRef = {}; /* For now, we do not make use of the policyRef stuff */
 
        r = tpm2_digest_buffer(TPM2_ALG_SHA256, digest, policyRef.buffer, policyRef.size, /* extend= */ true);
        if (r < 0)
                return r;
 
        tpm2_log_debug_digest(digest, "PolicySigned calculated digest");
 
        return 0;
}
 
int tpm2_policy_signed_hmac_sha256(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const Tpm2Handle *hmac_key_handle,
                const struct iovec *hmac_key,
                TPM2B_DIGEST **ret_policy_digest) {
 
#if HAVE_OPENSSL
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(session);
        assert(hmac_key_handle);
        assert(iovec_is_set(hmac_key));
 
        /* This sends a TPM2_PolicySigned command to the tpm. As signature key we use an HMAC-SHA256 key
         * specified in the hmac_key parameter. The secret key must be loaded into the TPM already and
         * referenced in hmac_key_handle. */
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        log_debug("Submitting PolicySigned policy for HMAC-SHA256.");
 
        /* Acquire the nonce from the TPM that we shall sign */
        _cleanup_(Esys_Freep) TPM2B_NONCE *nonce = NULL;
        rc = sym_Esys_TRSess_GetNonceTPM(
                        c->esys_context,
                        session->esys_handle,
                        &nonce);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to determine NoneTPM of auth session: %s",
                                       sym_Tss2_RC_Decode(rc));
 
        be32_t expiration = htobe64(0);
        const TPM2B_DIGEST cpHashA = {};  /* For now, we do not make use of the cpHashA stuff */
        const TPM2B_NONCE policyRef = {}; /* ditto, we do not bother with policyRef */
 
        /* Put together the data to sign, as per TPM2 Spec Part 3, 23.3.1 */
        struct iovec data_to_sign[] = {
                IOVEC_MAKE(nonce->buffer, nonce->size),
                IOVEC_MAKE(&expiration, sizeof(expiration)),
                IOVEC_MAKE(cpHashA.buffer, cpHashA.size),
                IOVEC_MAKE(policyRef.buffer, policyRef.size),
        };
 
        /* Now calculate the digest of the data we put together */
        TPM2B_DIGEST digest_to_sign;
        r = tpm2_digest_many(TPM2_ALG_SHA256, &digest_to_sign, data_to_sign, ELEMENTSOF(data_to_sign), /* extend= */ false);
        if (r < 0)
                return r;
 
        unsigned char hmac_signature[SHA256_DIGEST_SIZE];
        unsigned hmac_signature_size = sizeof(hmac_signature);
 
        /* And sign this with our key */
        if (!sym_HMAC(sym_EVP_sha256(),
                  hmac_key->iov_base,
                  hmac_key->iov_len,
                  digest_to_sign.buffer,
                  digest_to_sign.size,
                  hmac_signature,
                  &hmac_signature_size))
                return -ENOTRECOVERABLE;
 
        /* Now bring the signature into a format that the TPM understands */
        TPMT_SIGNATURE sig = {
                .sigAlg = TPM2_ALG_HMAC,
                .signature.hmac.hashAlg = TPM2_ALG_SHA256,
        };
        assert(hmac_signature_size == sizeof(sig.signature.hmac.digest.sha256));
        memcpy(sig.signature.hmac.digest.sha256, hmac_signature, hmac_signature_size);
 
        /* And submit the whole shebang to the TPM */
        rc = sym_Esys_PolicySigned(
                        c->esys_context,
                        hmac_key_handle->esys_handle,
                        session->esys_handle,
                        /* shandle1= */ ESYS_TR_NONE,
                        /* shandle2= */ ESYS_TR_NONE,
                        /* shandle3= */ ESYS_TR_NONE,
                        nonce,
                        &cpHashA,
                        &policyRef,
                        expiration,
                        &sig,
                        /* timeout= */ NULL,
                        /* policyTicket= */ NULL);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to add PolicySigned policy to TPM: %s",
                                       sym_Tss2_RC_Decode(rc));
 
        return tpm2_get_policy_digest(c, session, ret_policy_digest);
#else /* HAVE_OPENSSL */
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
int tpm2_policy_secret(
                Tpm2Context *c,
                const Tpm2Handle *auth_session,
                const Tpm2Handle *session,
                const Tpm2Handle *handle,
                const TPM2B_NONCE *policy_ref,
                TPM2B_DIGEST **ret_policy_digest) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(session);
        assert(handle);
 
        log_debug("Submitting PolicySecret policy.");
 
        rc = sym_Esys_PolicySecret(
                        c->esys_context,
                        handle->esys_handle,
                        session->esys_handle,
                        auth_session ? auth_session->esys_handle : ESYS_TR_PASSWORD,
                        /* shandle2= */ ESYS_TR_NONE,
                        /* shandle3= */ ESYS_TR_NONE,
                        /* nonceTPM= */ NULL,
                        /* cpHashA= */ NULL,
                        policy_ref,
                        /* expiration= */ 0,
                        /* timeout= */ NULL,
                        /* policyTicket= */ NULL);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to add PolicySecret policy to TPM: %s",
                                       sym_Tss2_RC_Decode(rc));
 
        return tpm2_get_policy_digest(c, session, ret_policy_digest);
}
 
int tpm2_calculate_policy_authorize_nv(
                const TPM2B_NV_PUBLIC *public_info,
                TPM2B_DIGEST *digest) {
        TPM2_CC command = TPM2_CC_PolicyAuthorizeNV;
        TSS2_RC rc;
        int r;
 
        assert(public_info);
        assert(digest);
        assert(digest->size == SHA256_DIGEST_SIZE);
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        uint8_t buf[sizeof(command)];
        size_t offset = 0;
 
        rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, sizeof(buf), &offset);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal PolicyAuthorizeNV command: %s", sym_Tss2_RC_Decode(rc));
 
        if (offset != sizeof(command))
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Offset 0x%zx wrong after marshalling PolicyAuthorizeNV command", offset);
 
        TPM2B_NV_PUBLIC public_info_copy = *public_info; /* Make a copy, since we must set TPMA_NV_WRITTEN for the calculation */
        public_info_copy.nvPublic.attributes |= TPMA_NV_WRITTEN;
 
        TPM2B_NAME name = {};
        r = tpm2_calculate_nv_index_name(&public_info_copy.nvPublic, &name);
        if (r < 0)
                return r;
 
        struct iovec data[] = {
                IOVEC_MAKE(buf, offset),
                IOVEC_MAKE(name.name, name.size),
        };
 
        r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, ELEMENTSOF(data), /* extend= */ true);
        if (r < 0)
                return r;
 
        tpm2_log_debug_digest(digest, "PolicyAuthorizeNV calculated digest");
 
        return 0;
}
 
int tpm2_policy_authorize_nv(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const Tpm2Handle *nv_handle,
                TPM2B_DIGEST **ret_policy_digest) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(session);
 
        log_debug("Submitting AuthorizeNV policy.");
 
        rc = sym_Esys_PolicyAuthorizeNV(
                        c->esys_context,
                        ESYS_TR_RH_OWNER,
                        nv_handle->esys_handle,
                        session->esys_handle,
                        ESYS_TR_PASSWORD,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE);
        if ((rc & ~(TPM2_RC_N_MASK|TPM2_RC_P)) == TPM2_RC_VALUE) /* Return a recognizable error if the policy
                                                                  * in the NV index does not match what we
                                                                  * just put together */
                return log_debug_errno(SYNTHETIC_ERRNO(EREMCHG),
                                       "Submitted policy does not match policy stored in PolicyAuthorizeNV.");
        if ((rc & ~(TPM2_RC_N_MASK|TPM2_RC_P)) == TPM2_RC_HANDLE ||
            rc == TPM2_RC_NV_UNINITIALIZED) /* NV index is missing, unwritten, or otherwise unusable for this policy (or: wrong authHandle/policySession). */
                return log_debug_errno(SYNTHETIC_ERRNO(EADDRNOTAVAIL),
                                       "NV index referenced by token is missing, unwritten, or unusable, it could be for another system.");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to add AuthorizeNV policy to TPM: %s",
                                       sym_Tss2_RC_Decode(rc));
 
        return tpm2_get_policy_digest(c, session, ret_policy_digest);
}
 
int tpm2_policy_or(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const TPM2B_DIGEST *branches, size_t n_branches,
                TPM2B_DIGEST **ret_policy_digest) {
 
        TPML_DIGEST hash_list;
        TSS2_RC rc;
 
        assert(c);
        assert(session);
 
        if (n_branches > ELEMENTSOF(hash_list.digests))
                return -EOPNOTSUPP;
 
        log_debug("Submitting OR policy.");
 
        hash_list = (TPML_DIGEST) {
                .count = n_branches,
        };
 
        memcpy(hash_list.digests, branches, n_branches * sizeof(TPM2B_DIGEST));
 
        if (DEBUG_LOGGING)
                for (size_t i = 0; i < hash_list.count; i++) {
                        _cleanup_free_ char *h = hexmem(hash_list.digests[i].buffer, hash_list.digests[i].size);
                        log_debug("Submitting OR Branch #%zu: %s", i, h);
                }
 
        rc = sym_Esys_PolicyOR(
                        c->esys_context,
                        session->esys_handle,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        &hash_list);
        if ((rc & ~(TPM2_RC_N_MASK|TPM2_RC_P)) == TPM2_RC_VALUE) /* Return a recognizable error if none of the OR branches matched */
                return log_debug_errno(SYNTHETIC_ERRNO(ENOANO),
                                       "None of the PolicyOR branches matched the current policy state.");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to add OR policy to TPM: %s",
                                       sym_Tss2_RC_Decode(rc));
 
        return tpm2_get_policy_digest(c, session, ret_policy_digest);
}
 
/* Extend 'digest' with the PolicyOR calculated hash. */
int tpm2_calculate_policy_or(const TPM2B_DIGEST *branches, size_t n_branches, TPM2B_DIGEST *digest) {
        TPM2_CC command = TPM2_CC_PolicyOR;
        TSS2_RC rc;
        int r;
 
        assert(digest);
        assert(digest->size == SHA256_DIGEST_SIZE);
 
        if (n_branches == 0)
                return -EINVAL;
        if (n_branches == 1)
                log_warning("PolicyOR with a single branch submitted, this is weird.");
        if (n_branches > 8)
                return -E2BIG;
 
        r = dlopen_tpm2(LOG_ERR);
        if (r < 0)
                return r;
 
        uint8_t buf[sizeof(command)];
        size_t offset = 0;
 
        rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, sizeof(buf), &offset);
        if (rc != TSS2_RC_SUCCESS)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal PolicyOR command: %s", sym_Tss2_RC_Decode(rc));
 
        if (offset != sizeof(command))
                return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Offset 0x%zx wrong after marshalling PolicyOR command", offset);
        _cleanup_free_ struct iovec *data = new(struct iovec, 1 + n_branches);
        if (!data)
                return log_oom();
 
        data[0] = IOVEC_MAKE(buf, offset);
        for (size_t i = 0; i < n_branches; i++) {
                data[1 + i] = IOVEC_MAKE((void*) branches[i].buffer, branches[i].size);
 
                if (DEBUG_LOGGING) {
                        _cleanup_free_ char *h = hexmem(branches[i].buffer, branches[i].size);
                        log_debug("OR Branch #%zu: %s", i, h);
                }
        }
 
        /* PolicyOR does not use the previous hash value; we must zero and then extend it. */
        zero(digest->buffer);
 
        r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, 1 + n_branches, /* extend= */ true);
        if (r < 0)
                return r;
 
        tpm2_log_debug_digest(digest, "PolicyOR calculated digest");
 
        return 0;
}
 
/* Extend 'digest' with the PolicyPCR calculated hash. */
int tpm2_calculate_policy_pcr(
                const Tpm2PCRValue *pcr_values,
                size_t n_pcr_values,
                TPM2B_DIGEST *digest) {
 
        TPM2_CC command = TPM2_CC_PolicyPCR;
        TSS2_RC rc;
        int r;
 
        assert(pcr_values || n_pcr_values == 0);
        assert(digest);
        assert(digest->size == SHA256_DIGEST_SIZE);
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        TPML_PCR_SELECTION pcr_selection;
        _cleanup_free_ TPM2B_DIGEST *values = NULL;
        size_t n_values;
        r = tpm2_tpml_pcr_selection_from_pcr_values(pcr_values, n_pcr_values, &pcr_selection, &values, &n_values);
        if (r < 0)
                return log_debug_errno(r, "Could not convert PCR values to TPML_PCR_SELECTION: %m");
 
        TPM2B_DIGEST hash = {};
        r = tpm2_digest_many_digests(TPM2_ALG_SHA256, &hash, values, n_values, /* extend= */ false);
        if (r < 0)
                return r;
 
        _cleanup_free_ uint8_t *buf = NULL;
        size_t size = 0, maxsize = sizeof(command) + sizeof(pcr_selection);
 
        buf = malloc(maxsize);
        if (!buf)
                return log_oom_debug();
 
        rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, maxsize, &size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal PolicyPCR command: %s", sym_Tss2_RC_Decode(rc));
 
        rc = sym_Tss2_MU_TPML_PCR_SELECTION_Marshal(&pcr_selection, buf, maxsize, &size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal PCR selection: %s", sym_Tss2_RC_Decode(rc));
 
        struct iovec data[] = {
                IOVEC_MAKE(buf, size),
                IOVEC_MAKE(hash.buffer, hash.size),
        };
        r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, ELEMENTSOF(data), /* extend= */ true);
        if (r < 0)
                return r;
 
        tpm2_log_debug_digest(digest, "PolicyPCR calculated digest");
 
        return 0;
}
 
int tpm2_policy_pcr(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const TPML_PCR_SELECTION *pcr_selection,
                TPM2B_DIGEST **ret_policy_digest) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(session);
        assert(pcr_selection);
 
        log_debug("Submitting PCR hash policy.");
 
        rc = sym_Esys_PolicyPCR(
                        c->esys_context,
                        session->esys_handle,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        NULL,
                        pcr_selection);
        if (rc == TPM2_RC_PCR_CHANGED)
                return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
                                       "Failed to add PCR policy to TPM: %s", sym_Tss2_RC_Decode(rc));
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to add PCR policy to TPM: %s", sym_Tss2_RC_Decode(rc));
 
        return tpm2_get_policy_digest(c, session, ret_policy_digest);
}
 
/* Extend 'digest' with the PolicyAuthorize calculated hash. */
int tpm2_calculate_policy_authorize(
                const TPM2B_PUBLIC *public,
                const TPM2B_NONCE *policy_ref,
                TPM2B_DIGEST *digest) {
 
        TPM2_CC command = TPM2_CC_PolicyAuthorize;
        TSS2_RC rc;
        int r;
 
        assert(public);
        assert(digest);
        assert(digest->size == SHA256_DIGEST_SIZE);
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        uint8_t buf[sizeof(command)];
        size_t offset = 0;
 
        rc = sym_Tss2_MU_TPM2_CC_Marshal(command, buf, sizeof(buf), &offset);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal PolicyAuthorize command: %s", sym_Tss2_RC_Decode(rc));
 
        if (offset != sizeof(command))
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Offset 0x%zx wrong after marshalling PolicyAuthorize command", offset);
 
        TPM2B_NAME name = {};
        r = tpm2_calculate_pubkey_name(&public->publicArea, &name);
        if (r < 0)
                return r;
 
        /* PolicyAuthorize does not use the previous hash value; we must zero and then extend it. */
        zero(digest->buffer);
 
        struct iovec data[] = {
                IOVEC_MAKE(buf, offset),
                IOVEC_MAKE(name.name, name.size),
        };
        r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, ELEMENTSOF(data), /* extend= */ true);
        if (r < 0)
                return r;
 
        /* PolicyAuthorize requires hashing twice; this is either an extension or rehashing. */
        if (policy_ref)
                r = tpm2_digest_many_digests(TPM2_ALG_SHA256, digest, policy_ref, 1, /* extend= */ true);
        else
                r = tpm2_digest_rehash(TPM2_ALG_SHA256, digest);
        if (r < 0)
                return r;
 
        tpm2_log_debug_digest(digest, "PolicyAuthorize calculated digest");
 
        return 0;
}
 
static void tpm2_make_policy_ref(const char *policy_ref, TPM2B_NONCE *ret_policy_ref) {
        assert(ret_policy_ref);
        assert(SHA256_DIGEST_SIZE <= sizeof(ret_policy_ref->buffer));
 
        /* A policy reference is represented by the TPM2B_NONCE type, which has a maximum size equivalent
         * to the largest digest supported by the TPM. Because of this, digest the policy reference string.
         * As we don't know what the maximum digest size supported by the TPM is when publishing a
         * signed policy, we pick SHA256 which is universally supported on PC-Client devices. Ideally the
         * algorithm ID would be prepended to the digest, but we don't know if the TPM2B_NONCE type can
         * accommodate this. For this reason, the digest algorithm here should match the one used to create
         * the approved digest for the corresponding policy, which is always SHA256 at the moment.
         *
         * Note that we return a policy ref size of 0 if no string is supplied in order to maintain
         * backwards compatibility with previous systemd releases. */
        if (isempty(policy_ref)) {
                ret_policy_ref->size = 0;
                return;
        }
 
        sha256_direct(policy_ref, strlen(policy_ref), ret_policy_ref->buffer);
        ret_policy_ref->size = SHA256_DIGEST_SIZE;
}
 
static int tpm2_policy_authorize(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPML_PCR_SELECTION *pcr_selection,
                const TPM2B_PUBLIC *public,
                const char *policy_ref,
                const void *fp,
                size_t fp_size,
                sd_json_variant *signature_json,
                TPM2B_DIGEST **ret_policy_digest) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(session);
        assert(pcr_selection);
        assert(public);
        assert(fp && fp_size > 0);
 
        log_debug("Adding PCR signature policy.");
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *pubkey_handle = NULL;
        r = tpm2_load_external(c, NULL, public, NULL, &pubkey_handle);
        if (r < 0)
                return r;
 
        /* Acquire the "name" of what we just loaded */
        _cleanup_(Esys_Freep) TPM2B_NAME *pubkey_name = NULL;
        r = tpm2_get_name(c, pubkey_handle, &pubkey_name);
        if (r < 0)
                return r;
 
        /* If we have a signature, proceed with verifying the PCR digest */
        const TPMT_TK_VERIFIED *check_ticket;
        _cleanup_(Esys_Freep) TPMT_TK_VERIFIED *check_ticket_buffer = NULL;
        _cleanup_(Esys_Freep) TPM2B_DIGEST *approved_policy = NULL;
        if (signature_json) {
                r = tpm2_policy_pcr(
                                c,
                                session,
                                pcr_selection,
                                &approved_policy);
                if (r < 0)
                        return r;
 
                _cleanup_free_ void *signature_raw = NULL;
                size_t signature_size;
 
                r = find_signature(
                                signature_json,
                                pcr_selection,
                                fp, fp_size,
                                policy_ref,
                                approved_policy->buffer,
                                approved_policy->size,
                                &signature_raw,
                                &signature_size);
                if (r < 0)
                        return r;
 
                /* TPM2_VerifySignature() will only verify the RSA part of the RSA+SHA256 signature,
                 * hence we need to do the SHA256 part ourselves, first */
                _cleanup_(iovec_done) struct iovec tbs_data = {};
                r = tpm2_make_policy_authorize_tbs_data(approved_policy, policy_ref, &tbs_data);
                if (r < 0)
                        return r;
 
                TPM2B_DIGEST signature_hash;
                r = tpm2_digest_buffer(TPM2_ALG_SHA256, &signature_hash, tbs_data.iov_base, tbs_data.iov_len, /* extend= */ false);
                if (r < 0)
                        return r;
 
                r = TPM2B_PUBLIC_KEY_RSA_CHECK_SIZE(signature_size);
                if (r < 0)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Signature larger than buffer.");
 
                TPMT_SIGNATURE policy_signature = {
                        .sigAlg = TPM2_ALG_RSASSA,
                        .signature.rsassa = {
                                .hash = TPM2_ALG_SHA256,
                                .sig = TPM2B_PUBLIC_KEY_RSA_MAKE(signature_raw, signature_size),
                        },
                };
 
                rc = sym_Esys_VerifySignature(
                                c->esys_context,
                                pubkey_handle->esys_handle,
                                ESYS_TR_NONE,
                                ESYS_TR_NONE,
                                ESYS_TR_NONE,
                                &signature_hash,
                                &policy_signature,
                                &check_ticket_buffer);
                if (rc != TSS2_RC_SUCCESS)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to validate signature in TPM: %s", sym_Tss2_RC_Decode(rc));
 
                check_ticket = check_ticket_buffer;
        } else {
                /* When enrolling, we pass a NULL ticket */
                static const TPMT_TK_VERIFIED check_ticket_null = {
                        .tag = TPM2_ST_VERIFIED,
                        .hierarchy = TPM2_RH_OWNER,
                };
 
                check_ticket = &check_ticket_null;
        }
 
        TPM2B_NONCE policy_ref_tpm2b;
        tpm2_make_policy_ref(policy_ref, &policy_ref_tpm2b);
 
        rc = sym_Esys_PolicyAuthorize(
                        c->esys_context,
                        session->esys_handle,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        approved_policy,
                        &policy_ref_tpm2b,
                        pubkey_name,
                        check_ticket);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to push Authorize policy into TPM: %s", sym_Tss2_RC_Decode(rc));
 
        return tpm2_get_policy_digest(c, session, ret_policy_digest);
}
 
/* Extend 'digest' with the calculated policy hash. */
int tpm2_calculate_sealing_policy(
                const Tpm2PCRValue *pcr_values,
                size_t n_pcr_values,
                const TPM2B_PUBLIC *public,
                const char *pubkey_policy_ref,
                bool use_pin,
                const Tpm2PCRLockPolicy *pcrlock_policy,
                TPM2B_DIGEST *digest) {
 
        int r;
 
        assert(pcr_values || n_pcr_values == 0);
        assert(digest);
 
        /* The combination of signed PCR policies and pcrlock is not supported (because we cannot combine
         * PolicyAuthorize and PolicyAuthorizeNV in one policy). Callers need to use "sharding" of the
         * symmetric FDE unlock key to make policies like that work. */
        if (public && pcrlock_policy)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Policies that combined signed PCR and pcrlock are not supported.");
 
        if (public) {
                TPM2B_NONCE policy_ref;
                tpm2_make_policy_ref(pubkey_policy_ref, &policy_ref);
                r = tpm2_calculate_policy_authorize(public, &policy_ref, digest);
                if (r < 0)
                        return r;
        }
 
        if (pcrlock_policy) {
                TPM2B_NV_PUBLIC nv_public;
 
                r = tpm2_unmarshal_nv_public(
                                pcrlock_policy->nv_public.iov_base,
                                pcrlock_policy->nv_public.iov_len,
                                &nv_public);
                if (r < 0)
                        return r;
 
                r = tpm2_calculate_policy_authorize_nv(&nv_public, digest);
                if (r < 0)
                        return r;
        }
 
        if (n_pcr_values > 0) {
                r = tpm2_calculate_policy_pcr(pcr_values, n_pcr_values, digest);
                if (r < 0)
                        return r;
        }
 
        if (use_pin) {
                r = tpm2_calculate_policy_auth_value(digest);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static int tpm2_build_sealing_policy(
                Tpm2Context *c,
                const Tpm2Handle *session,
                uint32_t hash_pcr_mask,
                uint16_t pcr_bank,
                const TPM2B_PUBLIC *public,
                const char *pubkey_policy_ref,
                const void *fp,
                size_t fp_size,
                uint32_t pubkey_pcr_mask,
                sd_json_variant *signature_json,
                bool use_pin,
                const Tpm2PCRLockPolicy *pcrlock_policy,
                TPM2B_DIGEST **ret_policy_digest) {
 
        int r;
 
        assert(c);
        assert(session);
        assert(pubkey_pcr_mask == 0 || public);
        assert(!pubkey_policy_ref || public);
 
        log_debug("Building sealing policy.");
 
        if ((hash_pcr_mask | pubkey_pcr_mask) != 0) {
                r = tpm2_pcr_mask_good(c, pcr_bank, hash_pcr_mask|pubkey_pcr_mask);
                if (r < 0)
                        return r;
                if (r == 0)
                        log_debug("Selected TPM2 PCRs are not initialized on this system.");
        }
 
        if (pubkey_pcr_mask != 0 && pcrlock_policy)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Policies with both signed PCR and pcrlock are currently not supported.");
 
        if (pubkey_pcr_mask != 0) {
                TPML_PCR_SELECTION pcr_selection;
                tpm2_tpml_pcr_selection_from_mask(pubkey_pcr_mask, (TPMI_ALG_HASH)pcr_bank, &pcr_selection);
                r = tpm2_policy_authorize(c, session, &pcr_selection, public, pubkey_policy_ref, fp, fp_size, signature_json, NULL);
                if (r < 0)
                        return r;
        }
 
        if (pcrlock_policy) {
                _cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
 
                r = tpm2_policy_super_pcr(
                                c,
                                session,
                                &pcrlock_policy->prediction,
                                pcrlock_policy->algorithm);
                if (r < 0)
                        return r;
 
                r = tpm2_deserialize(
                                c,
                                &pcrlock_policy->nv_handle,
                                &nv_handle);
                if (r < 0)
                        return r;
 
                r = tpm2_policy_authorize_nv(
                                c,
                                session,
                                nv_handle,
                                NULL);
                if (r < 0)
                        return r;
        }
 
        if (hash_pcr_mask != 0) {
                TPML_PCR_SELECTION pcr_selection;
                tpm2_tpml_pcr_selection_from_mask(hash_pcr_mask, (TPMI_ALG_HASH)pcr_bank, &pcr_selection);
                r = tpm2_policy_pcr(c, session, &pcr_selection, NULL);
                if (r < 0)
                        return r;
        }
 
        if (use_pin) {
                r = tpm2_policy_auth_value(c, session, NULL);
                if (r < 0)
                        return r;
        }
 
        r = tpm2_get_policy_digest(c, session, ret_policy_digest);
        if (r < 0)
                return r;
 
        return 0;
}
 
#if HAVE_OPENSSL
static const struct {
        TPM2_ECC_CURVE tpm2_ecc_curve_id;
        int openssl_ecc_curve_id;
} tpm2_openssl_ecc_curve_table[] = {
        { TPM2_ECC_NIST_P192, NID_X9_62_prime192v1, },
        { TPM2_ECC_NIST_P224, NID_secp224r1,        },
        { TPM2_ECC_NIST_P256, NID_X9_62_prime256v1, },
        { TPM2_ECC_NIST_P384, NID_secp384r1,        },
        { TPM2_ECC_NIST_P521, NID_secp521r1,        },
        { TPM2_ECC_SM2_P256,  NID_sm2,              },
};
 
static int tpm2_ecc_curve_from_openssl_curve_id(int openssl_ecc_curve_id, TPM2_ECC_CURVE *ret) {
        assert(ret);
 
        FOREACH_ELEMENT(t, tpm2_openssl_ecc_curve_table)
                if (t->openssl_ecc_curve_id == openssl_ecc_curve_id) {
                        *ret = t->tpm2_ecc_curve_id;
                        return 0;
                }
 
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                               "OpenSSL ECC curve id %d not supported.", openssl_ecc_curve_id);
}
 
static int tpm2_ecc_curve_to_openssl_curve_id(TPM2_ECC_CURVE tpm2_ecc_curve_id, int *ret) {
        assert(ret);
 
        FOREACH_ELEMENT(t, tpm2_openssl_ecc_curve_table)
                if (t->tpm2_ecc_curve_id == tpm2_ecc_curve_id) {
                        *ret = t->openssl_ecc_curve_id;
                        return 0;
                }
 
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                               "TPM2 ECC curve %u not supported.", tpm2_ecc_curve_id);
}
 
#define TPM2_RSA_DEFAULT_EXPONENT UINT32_C(0x10001)
 
int tpm2_tpm2b_public_to_openssl_pkey(const TPM2B_PUBLIC *public, EVP_PKEY **ret) {
        int r;
 
        assert(public);
        assert(ret);
 
        const TPMT_PUBLIC *p = &public->publicArea;
        switch (p->type) {
        case TPM2_ALG_ECC: {
                int curve_id;
                r = tpm2_ecc_curve_to_openssl_curve_id(p->parameters.eccDetail.curveID, &curve_id);
                if (r < 0)
                        return r;
 
                const TPMS_ECC_POINT *point = &p->unique.ecc;
                return ecc_pkey_from_curve_x_y(
                                curve_id,
                                point->x.buffer,
                                point->x.size,
                                point->y.buffer,
                                point->y.size,
                                ret);
        }
        case TPM2_ALG_RSA: {
                /* TPM specification Part 2 ("Structures") section for TPMS_RSA_PARAMS states "An exponent of
                 * zero indicates that the exponent is the default of 2^16 + 1". */
                uint32_t exponent = htobe32(p->parameters.rsaDetail.exponent ?: TPM2_RSA_DEFAULT_EXPONENT);
                return rsa_pkey_from_n_e(
                                p->unique.rsa.buffer,
                                p->unique.rsa.size,
                                &exponent,
                                sizeof(exponent),
                                ret);
        }
        default:
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "TPM2 asymmetric algorithm 0x%" PRIx16 " not supported.", p->type);
        }
}
 
/* Be careful before changing anything in this function, as the TPM key "name" is calculated using the entire
 * TPMT_PUBLIC (after marshalling), and that "name" is used (for example) to calculate the policy hash for
 * the Authorize policy. So we must ensure this conversion of a PEM to TPM2B_PUBLIC does not change the
 * "name", because it would break unsealing of previously-sealed objects that used (for example)
 * tpm2_calculate_policy_authorize(). See bug #30546. */
int tpm2_tpm2b_public_from_openssl_pkey(const EVP_PKEY *pkey, TPM2B_PUBLIC *ret) {
        int r;
 
        assert(pkey);
        assert(ret);
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        TPMT_PUBLIC public = {
                .nameAlg = TPM2_ALG_SHA256,
                .objectAttributes = TPMA_OBJECT_DECRYPT | TPMA_OBJECT_SIGN_ENCRYPT | TPMA_OBJECT_USERWITHAUTH,
                .parameters.asymDetail = {
                        .symmetric.algorithm = TPM2_ALG_NULL,
                        .scheme.scheme = TPM2_ALG_NULL,
                },
        };
 
        int key_id = sym_EVP_PKEY_get_id(pkey);
        switch (key_id) {
        case EVP_PKEY_EC: {
                public.type = TPM2_ALG_ECC;
 
                int curve_id;
                _cleanup_free_ void *x = NULL, *y = NULL;
                size_t x_size, y_size;
                r = ecc_pkey_to_curve_x_y(pkey, &curve_id, &x, &x_size, &y, &y_size);
                if (r < 0)
                        return log_debug_errno(r, "Could not get ECC key curve/x/y: %m");
 
                TPM2_ECC_CURVE curve;
                r = tpm2_ecc_curve_from_openssl_curve_id(curve_id, &curve);
                if (r < 0)
                        return r;
 
                public.parameters.eccDetail.curveID = curve;
 
                public.parameters.eccDetail.kdf.scheme = TPM2_ALG_NULL;
 
                r = TPM2B_ECC_PARAMETER_CHECK_SIZE(x_size);
                if (r < 0)
                        return log_debug_errno(r, "ECC key x size %zu too large.", x_size);
 
                public.unique.ecc.x = TPM2B_ECC_PARAMETER_MAKE(x, x_size);
 
                r = TPM2B_ECC_PARAMETER_CHECK_SIZE(y_size);
                if (r < 0)
                        return log_debug_errno(r, "ECC key y size %zu too large.", y_size);
 
                public.unique.ecc.y = TPM2B_ECC_PARAMETER_MAKE(y, y_size);
 
                break;
        }
        case EVP_PKEY_RSA: {
                public.type = TPM2_ALG_RSA;
 
                _cleanup_free_ void *n = NULL, *e = NULL;
                size_t n_size, e_size;
                r = rsa_pkey_to_n_e(pkey, &n, &n_size, &e, &e_size);