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 4001–5000 of 12,273

                uint32_t pcr_mask,
                const uint16_t *banks,
                size_t n_banks,
                TPMI_ALG_HASH *ret) {
 
        TPMI_ALG_HASH supported_hash = 0, hash_with_valid_pcr = 0;
        int r;
 
        assert(c);
        assert(ret);
        assert(banks);
        assert(n_banks > 0);
 
        uint32_t efi_banks;
        r = efi_get_active_pcr_banks(&efi_banks);
        if (r < 0) {
                if (!IN_SET(r, -ENOENT, -EOPNOTSUPP))
                        return r;
 
                /* If variable is not set use guesswork below */
                log_debug("Boot loader didn't set the LoaderTpm2ActivePcrBanks EFI variable or EFI support is unavailable, we have to guess the used PCR banks.");
        } else if (efi_banks == UINT32_MAX)
                log_debug("Boot loader set the LoaderTpm2ActivePcrBanks EFI variable to indicate that the GetActivePcrBanks() API is not available in the firmware. We have to guess the used PCR banks.");
        else if (efi_banks == 0)
                log_debug("Boot loader set the LoaderTpm2ActivePcrBanks EFI variable to zero to indicate that TPM support is not available in the firmware. We'll have to guess the used PCR banks.");
        else {
                r = pcr_bank_from_efi_active(banks, n_banks, efi_banks, ret);
                if (r == -EOPNOTSUPP) {
                        _cleanup_free_ char *bank_list = pcr_bank_preference_to_string(banks, n_banks);
                        return log_debug_errno(r, "Firmware reports none of the PCR banks we can use (%s), cannot operate.", strna(bank_list));
                }
                if (r < 0)
                        return r;
 
                if (*ret == TPM2_ALG_SHA1)
                        log_notice("Firmware reports SHA1 as the best active PCR bank, binding policy to it. This reduces the security level substantially.");
                else
                        log_debug("Picked best PCR bank %s based on firmware reported banks.", tpm2_hash_alg_to_string(*ret));
                return 0;
        }
 
        if (pcr_mask == 0) {
                log_debug("Asked to pick best PCR bank but no PCRs selected we could derive this from. Defaulting to SHA256.");
                *ret = TPM2_ALG_SHA256; /* if no PCRs are selected this doesn't matter anyway... */
                return 0;
        }
 
        /* Walk our banks in order of preference. Because the list is already sorted best-first, the first
         * bank that qualifies is the most preferred one — no ranking needed. */
        FOREACH_ARRAY(bank, banks, n_banks) {
                int good;
 
                /* Skip banks the TPM doesn't expose with a full set of 24 PCRs. */
                if (!tpm2_tpml_pcr_selection_has_mask(&c->capability_pcrs, *bank, TPM2_PCRS_MASK))
                        continue;
 
                /* First supported bank we reach is the most preferred supported one. */
                if (supported_hash == 0)
                        supported_hash = *bank;
 
                good = tpm2_pcr_mask_good(c, *bank, pcr_mask);
                if (good < 0)
                        return good;
                if (good) {
                        /* First supported bank with initialized PCRs is the most preferred such bank; we
                         * cannot do any better, so we are done. */
                        hash_with_valid_pcr = *bank;
                        break;
                }
        }
 
        /* Prefer a bank whose selected PCRs are actually initialized. If none of the supported banks has
         * initialized PCRs we still proceed with the most preferred supported bank, but the resulting PCR
         * policy is then effectively unenforced. */
 
        if (hash_with_valid_pcr != 0) {
                if (hash_with_valid_pcr == TPM2_ALG_SHA1)
                        log_notice("Only the weak SHA1 PCR bank has initialized PCRs, binding policy to it. This reduces the security level substantially.");
                else if (hash_with_valid_pcr != supported_hash)
                        log_notice("Preferred %s PCR bank has uninitialized PCRs, binding policy to the %s bank instead.",
                                   tpm2_hash_alg_to_string(supported_hash), tpm2_hash_alg_to_string(hash_with_valid_pcr));
                else
                        log_debug("Binding policy to %s PCR bank with initialized PCRs.", tpm2_hash_alg_to_string(hash_with_valid_pcr));
 
                *ret = hash_with_valid_pcr;
        } else if (supported_hash != 0) {
                log_notice("TPM2 device supports the %s PCR bank but none of the selected PCRs are initialized! Firmware apparently did not measure into any of them. Proceeding anyway, but the PCR policy is effectively unenforced!",
                           tpm2_hash_alg_to_string(supported_hash));
                *ret = supported_hash;
        } else {
                _cleanup_free_ char *bank_list = pcr_bank_preference_to_string(banks, n_banks);
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "TPM2 module supports none of the PCR banks we can use (%s), cannot operate.", strna(bank_list));
        }
 
        return 0;
}
 
int tpm2_get_best_pcr_bank(Tpm2Context *c, uint32_t pcr_mask, TPMI_ALG_HASH *ret) {
        return get_best_pcr_bank(c, pcr_mask, tpm2_pcr_bank_preference, ELEMENTSOF(tpm2_pcr_bank_preference), ret);
}
 
int tpm2_get_best_pcr_bank_legacy(Tpm2Context *c, uint32_t pcr_mask, TPMI_ALG_HASH *ret) {
        return get_best_pcr_bank(c, pcr_mask, tpm2_pcr_bank_preference_legacy, ELEMENTSOF(tpm2_pcr_bank_preference_legacy), ret);
}
 
int tpm2_get_good_pcr_banks(
                Tpm2Context *c,
                uint32_t pcr_mask,
                TPMI_ALG_HASH **ret) {
 
        _cleanup_free_ TPMI_ALG_HASH *good_banks = NULL, *fallback_banks = NULL;
        size_t n_good_banks = 0, n_fallback_banks = 0;
        int r;
 
        assert(c);
        assert(ret);
 
        uint32_t efi_banks;
        r = efi_get_active_pcr_banks(&efi_banks);
        if (r < 0) {
                if (!IN_SET(r, -ENOENT, -EOPNOTSUPP))
                        return r;
 
                /* If the variable is not set we have to guess via the code below */
                log_debug("Boot loader didn't set the LoaderTpm2ActivePcrBanks EFI variable or EFI support is unavailable, we have to guess the used PCR banks.");
        } else if (efi_banks == UINT32_MAX)
                log_debug("Boot loader set the LoaderTpm2ActivePcrBanks EFI variable to indicate that the GetActivePcrBanks() API is not available in the firmware. We have to guess the used PCR banks.");
        else if (efi_banks == 0)
                log_debug("Boot loader set the LoaderTpm2ActivePcrBanks EFI variable to zero to indicate that TPM support is not available in the firmware. We'll have to guess the used PCR banks.");
        else {
                FOREACH_ARRAY(hash, tpm2_hash_algorithms, TPM2_N_HASH_ALGORITHMS) {
                        if (!BIT_SET(efi_banks, *hash))
                                continue;
 
                        if (!GREEDY_REALLOC(good_banks, n_good_banks+1))
                                return log_oom_debug();
 
                        good_banks[n_good_banks++] = *hash;
                }
 
                log_debug("Found %zu initialized TPM2 banks reported by firmware.", n_good_banks);
                *ret = TAKE_PTR(good_banks);
                return (int) n_good_banks;
        }
 
        FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(selection, &c->capability_pcrs) {
                TPMI_ALG_HASH hash = selection->hash;
 
                /* Let's see if this bank is superficially OK, i.e. has at least 24 enabled registers */
                r = tpm2_bank_has24(selection);
                if (r < 0)
                        return r;
                if (!r)
                        continue;
 
                /* Let's now see if this bank has any of the selected PCRs actually initialized */
                r = tpm2_pcr_mask_good(c, hash, pcr_mask);
                if (r < 0)
                        return r;
 
                if (n_good_banks + n_fallback_banks >= INT_MAX)
                        return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Too many good TPM2 banks?");
 
                if (r) {
                        if (!GREEDY_REALLOC(good_banks, n_good_banks+1))
                                return log_oom_debug();
 
                        good_banks[n_good_banks++] = hash;
                } else {
                        if (!GREEDY_REALLOC(fallback_banks, n_fallback_banks+1))
                                return log_oom_debug();
 
                        fallback_banks[n_fallback_banks++] = hash;
                }
        }
 
        /* Preferably, use the good banks (i.e. the ones the PCR values are actually initialized so
         * far). Otherwise use the fallback banks (i.e. which exist and are enabled, but so far not used. */
        if (n_good_banks > 0) {
                log_debug("Found %zu fully initialized TPM2 banks.", n_good_banks);
                *ret = TAKE_PTR(good_banks);
                return (int) n_good_banks;
        }
        if (n_fallback_banks > 0) {
                log_debug("Found %zu enabled but un-initialized TPM2 banks.", n_fallback_banks);
                *ret = TAKE_PTR(fallback_banks);
                return (int) n_fallback_banks;
        }
 
        /* No suitable banks found. */
        *ret = NULL;
        return 0;
}
 
int tpm2_get_good_pcr_banks_strv(
                Tpm2Context *c,
                uint32_t pcr_mask,
                char ***ret) {
 
#if HAVE_OPENSSL
        _cleanup_free_ TPMI_ALG_HASH *algs = NULL;
        _cleanup_strv_free_ char **l = NULL;
        int n_algs, r;
 
        assert(c);
        assert(ret);
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        n_algs = tpm2_get_good_pcr_banks(c, pcr_mask, &algs);
        if (n_algs < 0)
                return n_algs;
 
        FOREACH_ARRAY(a, algs, n_algs) {
                _cleanup_free_ char *n = NULL;
                const EVP_MD *implementation;
                const char *salg;
 
                salg = tpm2_hash_alg_to_string(*a);
                if (!salg)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "TPM2 operates with unknown PCR algorithm, can't measure.");
 
                implementation = sym_EVP_get_digestbyname(salg);
                if (!implementation)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "TPM2 operates with unsupported PCR algorithm, can't measure.");
 
                n = strdup(ASSERT_PTR(sym_EVP_MD_get0_name(implementation)));
                if (!n)
                        return log_oom_debug();
 
                ascii_strlower(n); /* OpenSSL uses uppercase digest names, we prefer them lower case. */
 
                if (strv_consume(&l, TAKE_PTR(n)) < 0)
                        return log_oom_debug();
        }
 
        *ret = TAKE_PTR(l);
        return 0;
#else /* HAVE_OPENSSL */
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
static int tpm2_tpmt_ha_to_data(TPMT_HA *ha, TPM2B_DATA *ret) {
        TSS2_RC rc;
        int r;
 
        assert(ha);
        assert(ret);
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        TPM2B_DATA data = {};
        size_t written = 0;
        rc = sym_Tss2_MU_TPMT_HA_Marshal(ha, data.buffer, sizeof(data.buffer), &written);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to marshal digest.");
        data.size = written;
 
        *ret = data;
        return 0;
}
 
int tpm2_digest_buf_to_data(TPMI_ALG_HASH alg, void *digest, size_t digest_sz, TPM2B_DATA *ret) {
        assert(digest);
        assert(ret);
 
        if (digest_sz != (size_t) tpm2_hash_alg_to_size(alg))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid digest size");
 
        TPMT_HA ha = {
                .hashAlg = alg,
        };
        assert(digest_sz <= sizeof_field(TPMT_HA, digest));
        memcpy_safe(&ha.digest, digest, digest_sz);
 
        return tpm2_tpmt_ha_to_data(&ha, ret);
}
 
int tpm2_digest_iovec_to_data(TPMI_ALG_HASH alg, const struct iovec *digest, TPM2B_DATA *ret) {
        assert(iovec_is_valid(digest));
        assert(ret);
 
        return tpm2_digest_buf_to_data(alg, digest->iov_base, digest->iov_len, ret);
}
 
/* Hash data into the digest.
 *
 * If 'extend' is true, the hashing operation starts with the existing digest hash (and the digest is
 * required to have a hash and its size must be correct). If 'extend' is false, the digest size is
 * initialized to the correct size for 'alg' and the hashing operation does not include any existing digest
 * hash. If 'extend' is false and no data is provided, the digest is initialized to a zero digest.
 *
 * On success, the digest hash will be updated with the hashing operation result and the digest size will be
 * correct for 'alg'.
 *
 * This currently only provides SHA256, so 'alg' must be TPM2_ALG_SHA256. */
int tpm2_digest_many(
                TPMI_ALG_HASH alg,
                TPM2B_DIGEST *digest,
                const struct iovec data[],
                size_t n_data,
                bool extend) {
 
        struct sha256_ctx ctx;
 
        assert(digest);
        assert(data || n_data == 0);
 
        if (alg != TPM2_ALG_SHA256)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "Hash algorithm not supported: 0x%x", alg);
 
        if (extend && digest->size != SHA256_DIGEST_SIZE)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "Digest size 0x%x, require 0x%x",
                                       digest->size, (unsigned)SHA256_DIGEST_SIZE);
 
        /* Since we're hardcoding SHA256 (for now), we can check this at compile time. */
        assert_cc(sizeof(digest->buffer) >= SHA256_DIGEST_SIZE);
 
        CLEANUP_ERASE(ctx);
 
        sha256_init_ctx(&ctx);
 
        if (extend)
                sha256_process_bytes(digest->buffer, digest->size, &ctx);
        else {
                *digest = (TPM2B_DIGEST) {
                        .size = SHA256_DIGEST_SIZE,
                };
                if (n_data == 0) /* If not extending and no data, return zero hash */
                        return 0;
        }
 
        FOREACH_ARRAY(d, data, n_data)
                sha256_process_bytes(d->iov_base, d->iov_len, &ctx);
 
        sha256_finish_ctx(&ctx, digest->buffer);
 
        return 0;
}
 
/* Same as tpm2_digest_many() but data is contained in TPM2B_DIGEST[]. The digests may be any size digests. */
int tpm2_digest_many_digests(
                TPMI_ALG_HASH alg,
                TPM2B_DIGEST *digest,
                const TPM2B_DIGEST data[],
                size_t n_data,
                bool extend) {
 
        _cleanup_free_ struct iovec *iovecs = NULL;
 
        assert(data || n_data == 0);
 
        iovecs = new(struct iovec, n_data);
        if (!iovecs)
                return log_oom_debug();
 
        for (size_t i = 0; i < n_data; i++)
                iovecs[i] = IOVEC_MAKE((void*) data[i].buffer, data[i].size);
 
        return tpm2_digest_many(alg, digest, iovecs, n_data, extend);
}
 
/* This hashes the provided pin into a digest value, but also verifies that the final byte is not 0, because
 * the TPM specification Part 1 ("Architecture") section Authorization Values (subsection "Authorization Size
 * Convention") states "Trailing octets of zero are to be removed from any string before it is used as an
 * authValue". Since the TPM doesn't know if the auth value is a "string" or just a hash digest, any hash
 * digest that randomly happens to end in 0 must have the final 0(s) trimmed.
 *
 * This is required at 2 points. First, when setting the authValue during creation of new sealed objects, in
 * tpm2_seal(). This only applies to newly created objects, of course.  Second, when using a previously
 * created sealed object that has an authValue set, we use the sealed objects as the session bind key. This
 * requires calling SetAuth so tpm2-tss can correctly calculate the HMAC to use for the encryption session.
 *
 * TPM implementations will perform the trimming for any authValue for existing sealed objects, so the
 * tpm2-tss library must also perform the trimming before HMAC calculation, but it does not yet; this bug is
 * open to add the trimming: https://github.com/tpm2-software/tpm2-tss/issues/2664
 *
 * Until our minimum tpm2-tss version contains a fix for that bug, we must perform the trimming
 * ourselves. Note that since we are trimming, which is exactly what a TPM implementation would do, this will
 * work for both existing objects with a authValue ending in 0(s) as well as new sealed objects we create,
 * which we will trim the 0(s) from before sending to the TPM.
 */
static void tpm2_trim_auth_value(TPM2B_AUTH *auth) {
        bool trimmed = false;
 
        assert(auth);
 
        while (auth->size > 0 && auth->buffer[auth->size - 1] == 0) {
                trimmed = true;
                auth->size--;
        }
 
        if (trimmed)
                log_debug("authValue ends in 0, trimming as required by the TPM2 specification Part 1 section 'HMAC Computation' authValue Note 2.");
}
 
int tpm2_auth_value_from_pin(TPMI_ALG_HASH hash, const char *pin, TPM2B_AUTH *ret_auth) {
        TPM2B_AUTH auth = {};
        int r;
 
        assert(pin);
        assert(ret_auth);
 
        r = tpm2_digest_buffer(hash, &auth, pin, strlen(pin), /* extend= */ false);
        if (r < 0)
                return r;
 
        tpm2_trim_auth_value(&auth);
 
        *ret_auth = TAKE_STRUCT(auth);
 
        return 0;
}
 
int tpm2_set_auth_binary(Tpm2Context *c, const Tpm2Handle *handle, const TPM2B_AUTH *auth) {
        TSS2_RC rc;
 
        assert(c);
        assert(handle);
 
        if (!auth)
                return 0;
 
        rc = sym_Esys_TR_SetAuth(c->esys_context, handle->esys_handle, auth);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to load PIN in TPM: %s", sym_Tss2_RC_Decode(rc));
 
        return 0;
}
 
int tpm2_set_auth(Tpm2Context *c, const Tpm2Handle *handle, const char *pin) {
        TPM2B_AUTH auth = {};
        int r;
 
        assert(c);
        assert(handle);
 
        if (!pin)
                return 0;
 
        CLEANUP_ERASE(auth);
 
        r = tpm2_auth_value_from_pin(TPM2_ALG_SHA256, pin, &auth);
        if (r < 0)
                return r;
 
        return tpm2_set_auth_binary(c, handle, &auth);
}
 
static bool tpm2_is_encryption_session(Tpm2Context *c, const Tpm2Handle *session) {
        TPMA_SESSION flags = 0;
        TSS2_RC rc;
 
        assert(c);
        assert(session);
 
        rc = sym_Esys_TRSess_GetAttributes(c->esys_context, session->esys_handle, &flags);
        if (rc != TSS2_RC_SUCCESS)
                return false;
 
        return (flags & TPMA_SESSION_DECRYPT) && (flags & TPMA_SESSION_ENCRYPT);
}
 
int tpm2_make_encryption_session(
                Tpm2Context *c,
                const Tpm2Handle *primary,
                const Tpm2Handle *bind_key,
                Tpm2Handle **ret_session) {
 
        const TPMA_SESSION sessionAttributes = TPMA_SESSION_DECRYPT | TPMA_SESSION_ENCRYPT |
                        TPMA_SESSION_CONTINUESESSION;
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(primary);
        assert(ret_session);
 
        log_debug("Starting HMAC encryption session.");
 
        /* Start a salted, unbound HMAC session with a well-known key (e.g. primary key) as tpmKey, which
         * means that the random salt will be encrypted with the well-known key. That way, only the TPM can
         * recover the salt, which is then used for key derivation. */
        _cleanup_(tpm2_handle_freep) Tpm2Handle *session = NULL;
        r = tpm2_handle_new(c, &session);
        if (r < 0)
                return r;
 
        rc = sym_Esys_StartAuthSession(
                        c->esys_context,
                        primary->esys_handle,
                        bind_key ? bind_key->esys_handle : ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        NULL,
                        TPM2_SE_HMAC,
                        &SESSION_TEMPLATE_SYM_AES_128_CFB,
                        TPM2_ALG_SHA256,
                        &session->esys_handle);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc));
 
        /* Enable parameter encryption/decryption with AES in CFB mode. Together with HMAC digests (which are
         * always used for sessions), this provides confidentiality, integrity and replay protection for
         * operations that use this session. */
        rc = sym_Esys_TRSess_SetAttributes(c->esys_context, session->esys_handle, sessionAttributes, 0xff);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to configure TPM session: %s", sym_Tss2_RC_Decode(rc));
 
        *ret_session = TAKE_PTR(session);
 
        return 0;
}
 
static bool tpm2_is_audit_session(Tpm2Context *c, const Tpm2Handle *session) {
        TPMA_SESSION flags = 0;
        TSS2_RC rc;
 
        assert(c);
        assert(session);
 
        rc = sym_Esys_TRSess_GetAttributes(c->esys_context, session->esys_handle, &flags);
        if (rc != TSS2_RC_SUCCESS)
                return false;
 
        return flags & TPMA_SESSION_AUDIT;
}
 
int tpm2_make_exclusive_audit_session(Tpm2Context *c, Tpm2Handle **ret_session) {
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(ret_session);
 
        log_debug("Starting HMAC exclusive audit session.");
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *session = NULL;
        r = tpm2_handle_new(c, &session);
        if (r < 0)
                return r;
 
        rc = sym_Esys_StartAuthSession(
                        c->esys_context,
                        /* tpmKey= */ ESYS_TR_NONE,
                        /* bind= */ ESYS_TR_NONE,
                        /* shandle1= */ ESYS_TR_NONE,
                        /* shandle2= */ ESYS_TR_NONE,
                        /* shandle3= */ ESYS_TR_NONE,
                        /* nonceCaller= */ NULL,
                        TPM2_SE_HMAC,
                        &SESSION_TEMPLATE_SYM_NULL,
                        TPM2_ALG_SHA256,
                        &session->esys_handle);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc));
 
        const TPMA_SESSION sessionAttributes = TPMA_SESSION_AUDIT | TPMA_SESSION_AUDITEXCLUSIVE | TPMA_SESSION_CONTINUESESSION;
        rc = sym_Esys_TRSess_SetAttributes(c->esys_context, session->esys_handle, sessionAttributes, 0xff);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to configure TPM session: %s", sym_Tss2_RC_Decode(rc));
 
        *ret_session = TAKE_PTR(session);
 
        return 0;
}
 
int tpm2_make_policy_session(
                Tpm2Context *c,
                const Tpm2Handle *primary,
                const Tpm2Handle *encryption_session,
                Tpm2Handle **ret_session) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(ret_session);
 
        if (encryption_session && !tpm2_is_encryption_session(c, encryption_session))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Invalid encryption session");
 
        log_debug("Starting policy session.");
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *session = NULL;
        r = tpm2_handle_new(c, &session);
        if (r < 0)
                return r;
 
        rc = sym_Esys_StartAuthSession(
                        c->esys_context,
                        primary ? primary->esys_handle : ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        encryption_session ? encryption_session->esys_handle : ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        NULL,
                        TPM2_SE_POLICY,
                        &SESSION_TEMPLATE_SYM_AES_128_CFB,
                        TPM2_ALG_SHA256,
                        &session->esys_handle);
        if ((rc & ~TPM2_RC_N_MASK) == TPM2_RC_AUTH_FAIL)
                return log_debug_errno(SYNTHETIC_ERRNO(EILSEQ),
                                       "Authorization failure from TPM: %s", sym_Tss2_RC_Decode(rc));
        if (rc == TPM2_RC_LOCKOUT)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOLCK),
                                       "TPM2 device is in dictionary attack lockout mode.");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc));
 
        *ret_session = TAKE_PTR(session);
 
        return 0;
}
 
static int find_signature(
                sd_json_variant *v,
                const TPML_PCR_SELECTION *pcr_selection,
                const void *fp,
                size_t fp_size,
                const char *policy_ref,
                const void *policy,
                size_t policy_size,
                void *ret_signature,
                size_t *ret_signature_size) {
 
#if HAVE_OPENSSL
        sd_json_variant *b, *i;
        const char *k;
        int r;
 
        assert(pcr_selection);
        assert(policy || !ret_signature);
        assert(!ret_signature || ret_signature_size);
 
        /* Searches for a signature blob in the specified JSON object. Search keys are PCR bank, PCR mask,
         * public key, policy reference and policy digest. If 'policy' is NULL, matches any policy digest.
         * If 'ret_signature' is NULL, only checks whether a matching entry exists. */
 
        if (!sd_json_variant_is_object(v))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature is not a JSON object.");
 
        uint16_t pcr_bank = pcr_selection->pcrSelections[0].hash;
        uint32_t pcr_mask = tpm2_tpml_pcr_selection_to_mask(pcr_selection, pcr_bank);
 
        k = tpm2_hash_alg_to_string(pcr_bank);
        if (!k)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Don't know PCR bank %" PRIu16, pcr_bank);
 
        /* First, find field by bank */
        b = sd_json_variant_by_key(v, k);
        if (!b)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOSTR), "Signature lacks data for PCR bank '%s'.", k);
 
        if (!sd_json_variant_is_array(b))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Bank data is not a JSON array.");
 
        /* Now iterate through all signatures known for this bank */
        JSON_VARIANT_ARRAY_FOREACH(i, b) {
                _cleanup_free_ void *fpj_data = NULL, *polj_data = NULL;
                const char *refj_data = NULL;
                sd_json_variant *maskj, *fpj, *sigj, *polj, *refj;
                size_t fpj_size, polj_size;
                uint32_t parsed_mask;
 
                if (!sd_json_variant_is_object(i))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Bank data element is not a JSON object");
 
                /* Check if the PCR mask matches our expectations */
                maskj = sd_json_variant_by_key(i, "pcrs");
                if (!maskj)
                        continue;
 
                r = tpm2_parse_pcr_json_array(maskj, &parsed_mask);
                if (r < 0)
                        return log_debug_errno(r, "Failed to parse JSON PCR mask");
 
                if (parsed_mask != pcr_mask)
                        continue; /* Not for this PCR mask */
 
                /* Then check if this is for the public key we operate with */
                fpj = sd_json_variant_by_key(i, "pkfp");
                if (!fpj)
                        continue;
 
                r = sd_json_variant_unhex(fpj, &fpj_data, &fpj_size);
                if (r < 0)
                        return log_debug_errno(r, "Failed to decode fingerprint in JSON data: %m");
 
                if (memcmp_nn(fp, fp_size, fpj_data, fpj_size) != 0)
                        continue; /* Not for this public key */
 
                refj = sd_json_variant_by_key(i, "ref");
                if (refj) {
                        refj_data = sd_json_variant_string(refj);
                        if (!refj_data)
                                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Policy reference is not a string.");
                }
 
                if (!streq_ptr(policy_ref, refj_data))
                        continue;
 
                /* Finally, check if this is for the PCR policy we expect this to be */
                polj = sd_json_variant_by_key(i, "pol");
                if (!polj)
                        continue;
 
                if (policy) {
                        r = sd_json_variant_unhex(polj, &polj_data, &polj_size);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to decode policy hash JSON data: %m");
 
                        if (memcmp_nn(policy, policy_size, polj_data, polj_size) != 0)
                                continue;
                }
 
                /* This entry matches all our expectations, now return the signature included in it */
                sigj = sd_json_variant_by_key(i, "sig");
                if (!sigj)
                        continue;
 
                if (!ret_signature)
                        return 0;
 
                return sd_json_variant_unbase64(sigj, ret_signature, ret_signature_size);
        }
 
        return log_debug_errno(SYNTHETIC_ERRNO(ENOSTR), "Couldn't find signature for this PCR bank, PCR index and public key.");
#else /* HAVE_OPENSSL */
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
/* Calculates the "name" of a public key.
 *
 * As specified in TPM2 spec "Part 1: Architecture", a key's "name" is its nameAlg value followed by a hash
 * of its TPM2 public area, all properly marshalled. This allows a key's "name" to be dependent not only on
 * the key fingerprint, but also on the TPM2-specific fields that associated with the key (i.e. all fields in
 * TPMT_PUBLIC). Note that this means an existing key may not change any of its TPMT_PUBLIC fields, since
 * that would also change the key name.
 *
 * Since we (currently) hardcode to always using SHA256 for hashing, this returns an error if the public key
 * nameAlg is not TPM2_ALG_SHA256. */
int tpm2_calculate_pubkey_name(const TPMT_PUBLIC *public, TPM2B_NAME *ret_name) {
        TSS2_RC rc;
        int r;
 
        assert(public);
        assert(ret_name);
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        if (public->nameAlg != TPM2_ALG_SHA256)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "Unsupported nameAlg: 0x%x",
                                       public->nameAlg);
 
        _cleanup_free_ uint8_t *buf = NULL;
        size_t size = 0;
 
        buf = (uint8_t*) new(TPMT_PUBLIC, 1);
        if (!buf)
                return log_oom_debug();
 
        rc = sym_Tss2_MU_TPMT_PUBLIC_Marshal(public, buf, sizeof(TPMT_PUBLIC), &size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal public key: %s", sym_Tss2_RC_Decode(rc));
 
        TPM2B_DIGEST digest = {};
        r = tpm2_digest_buffer(TPM2_ALG_SHA256, &digest, buf, size, /* extend= */ false);
        if (r < 0)
                return r;
 
        TPMT_HA ha = {
                .hashAlg = TPM2_ALG_SHA256,
        };
        assert(digest.size <= sizeof(ha.digest.sha256));
        memcpy_safe(ha.digest.sha256, digest.buffer, digest.size);
 
        TPM2B_NAME name;
        size = 0;
        rc = sym_Tss2_MU_TPMT_HA_Marshal(&ha, name.name, sizeof(name.name), &size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal key name: %s", sym_Tss2_RC_Decode(rc));
        name.size = size;
 
        tpm2_log_debug_name(&name, "Calculated public key name");
 
        *ret_name = name;
 
        return 0;
}
 
/* Get the "name" of a key from the TPM.
 *
 * The "name" of a key is explained above in tpm2_calculate_pubkey_name().
 *
 * The handle must reference a key already present in the TPM. It may be either a public key only, or a
 * public/private keypair. */
int tpm2_get_name(
                Tpm2Context *c,
                const Tpm2Handle *handle,
                TPM2B_NAME **ret_name) {
 
        _cleanup_(Esys_Freep) TPM2B_NAME *name = NULL;
        TSS2_RC rc;
 
        assert(c);
        assert(handle);
        assert(ret_name);
 
        rc = sym_Esys_TR_GetName(c->esys_context, handle->esys_handle, &name);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to get name of public key from TPM: %s", sym_Tss2_RC_Decode(rc));
 
        tpm2_log_debug_name(name, "Object name");
 
        *ret_name = TAKE_PTR(name);
 
        return 0;
}
 
int tpm2_calculate_nv_index_name(const TPMS_NV_PUBLIC *nvpublic, TPM2B_NAME *ret_name) {
        TSS2_RC rc;
        int r;
 
        assert(nvpublic);
        assert(ret_name);
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        if (nvpublic->nameAlg != TPM2_ALG_SHA256)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "Unsupported nameAlg: 0x%x",
                                       nvpublic->nameAlg);
 
        _cleanup_free_ uint8_t *buf = NULL;
        size_t size = 0;
 
        buf = (uint8_t*) new(TPMS_NV_PUBLIC, 1);
        if (!buf)
                return log_oom_debug();
 
        rc = sym_Tss2_MU_TPMS_NV_PUBLIC_Marshal(nvpublic, buf, sizeof(TPMS_NV_PUBLIC), &size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal NV index: %s", sym_Tss2_RC_Decode(rc));
 
        TPM2B_DIGEST digest = {};
        r = tpm2_digest_buffer(TPM2_ALG_SHA256, &digest, buf, size, /* extend= */ false);
        if (r < 0)
                return r;
 
        TPMT_HA ha = {
                .hashAlg = TPM2_ALG_SHA256,
        };
        assert(digest.size <= sizeof(ha.digest.sha256));
        memcpy_safe(ha.digest.sha256, digest.buffer, digest.size);
 
        TPM2B_NAME name;
        size = 0;
        rc = sym_Tss2_MU_TPMT_HA_Marshal(&ha, name.name, sizeof(name.name), &size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal NV index name: %s", sym_Tss2_RC_Decode(rc));
        name.size = size;
 
        tpm2_log_debug_name(&name, "Calculated NV index name");
 
        *ret_name = name;
 
        return 0;
}
 
/* Extend 'digest' with the PolicyAuthValue calculated hash. */
int tpm2_calculate_policy_auth_value(TPM2B_DIGEST *digest) {
        TPM2_CC command = TPM2_CC_PolicyAuthValue;
        TSS2_RC rc;
        int r;
 
        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 PolicyAuthValue command: %s", sym_Tss2_RC_Decode(rc));
 
        if (offset != sizeof(command))
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Offset 0x%zx wrong after marshalling PolicyAuthValue command", offset);
 
        r = tpm2_digest_buffer(TPM2_ALG_SHA256, digest, buf, offset, /* extend= */ true);
        if (r < 0)
                return r;
 
        tpm2_log_debug_digest(digest, "PolicyAuthValue calculated digest");
 
        return 0;
}
 
int tpm2_policy_auth_value(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPM2B_DIGEST **ret_policy_digest) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(session);
 
        log_debug("Submitting AuthValue policy.");
 
        rc = sym_Esys_PolicyAuthValue(
                        c->esys_context,
                        session->esys_handle,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to add authValue policy to TPM: %s",
                                       sym_Tss2_RC_Decode(rc));
 
        return tpm2_get_policy_digest(c, session, ret_policy_digest);
}
 
/* Extend 'digest' with the PolicyNvWritten calculated hash. */
int tpm2_calculate_policy_nv_written(bool written_set, TPM2B_DIGEST *digest) {
        TPM2_CC command = TPM2_CC_PolicyNvWritten;
        TSS2_RC rc;
        int r;
 
        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 PolicyNvWritten command: %s", sym_Tss2_RC_Decode(rc));
 
        if (offset != sizeof(command))
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Offset 0x%zx wrong after marshalling PolicyNvWritten command", offset);
 
        uint8_t written_byte = written_set ? TPM2_YES : TPM2_NO;
 
        struct iovec data[] = {
                IOVEC_MAKE(buf, offset),
                IOVEC_MAKE(&written_byte, sizeof(written_byte)),
        };
        r = tpm2_digest_many(TPM2_ALG_SHA256, digest, data, ELEMENTSOF(data), /* extend= */ true);
        if (r < 0)
                return r;
 
        tpm2_log_debug_digest(digest, "PolicyNvWritten calculated digest");
 
        return 0;
}
 
int tpm2_policy_nv_written(
                Tpm2Context *c,
                const Tpm2Handle *session,