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 1–1000 of 12,273

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <sys/file.h>
#include <unistd.h>
 
#include "sd-device.h"
 
#include "alloc-util.h"
#include "ansi-color.h"
#include "bitfield.h"
#include "conf-files.h"
#include "constants.h"
#include "creds-util.h"
#include "crypto-util.h"
#include "cryptsetup-util.h"
#include "device-private.h"
#include "device-util.h"
#include "dirent-util.h"
#include "dlfcn-util.h"
#include "efi-api.h"
#include "errno-util.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-table.h"
#include "fs-util.h"
#include "hexdecoct.h"
#include "hmac.h"
#include "initrd-util.h"
#include "io-util.h"
#include "json-util.h"
#include "limits-util.h"
#include "log.h"
#include "logarithm.h"
#include "memory-util.h"
#include "memstream-util.h"
#include "mkdir.h"
#include "ordered-set.h"
#include "random-util.h"
#include "recurse-dir.h"
#include "siphash24.h"
#include "sort-util.h"
#include "sparse-endian.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "sync-util.h"
#include "time-util.h"
#include "tpm2-pcr.h"
#include "tpm2-util.h"
#include "unaligned.h"
#include "virt.h"
 
/* The PCR banks we are willing to bind policies to, in order of preference. We keep SHA256 as the top
 * preference for backwards compatibility (systems that already bind to it keep using the same bank, so
 * existing TPM2-sealed secrets remain valid), then prefer SHA384 over SHA512: SHA384 is computed in 64-bit
 * words like SHA512 but produces a shorter digest, so it takes up less room in the TPM event log, whose
 * memory is usually bounded. SHA512 comes next, and we only fall back to the weak SHA1 as a last resort. */
static const uint16_t tpm2_pcr_bank_preference[] = {
        TPM2_ALG_SHA256,
        TPM2_ALG_SHA384,
        TPM2_ALG_SHA512,
        TPM2_ALG_SHA1,
};
 
/* The reduced preference list used when re-deriving the bank for legacy enrollments that did not record one
 * (see tpm2_get_best_pcr_bank_legacy()). Such enrollments were sealed by code that only ever considered
 * SHA256 and SHA1, so they can only be bound to one of those two banks. We must restrict the choice to exactly this set. */
static const uint16_t tpm2_pcr_bank_preference_legacy[] = {
        TPM2_ALG_SHA256,
        TPM2_ALG_SHA1,
};
 
static int pcr_bank_from_efi_active(
                const uint16_t *banks,
                size_t n_banks,
                uint32_t active_banks,
                uint16_t *ret) {
 
        assert(banks);
        assert(ret);
 
        FOREACH_ARRAY(bank, banks, n_banks)
                if (BIT_SET(active_banks, *bank)) {
                        *ret = *bank;
                        return 0;
                }
 
        return -EOPNOTSUPP;
}
 
int tpm2_pcr_bank_from_efi_active(uint32_t active_banks, uint16_t *ret) {
        return pcr_bank_from_efi_active(tpm2_pcr_bank_preference, ELEMENTSOF(tpm2_pcr_bank_preference), active_banks, ret);
}
 
int tpm2_pcr_bank_from_efi_active_legacy(uint32_t active_banks, uint16_t *ret) {
        return pcr_bank_from_efi_active(tpm2_pcr_bank_preference_legacy, ELEMENTSOF(tpm2_pcr_bank_preference_legacy), active_banks, ret);
}
 
#if HAVE_TPM2
static DLSYM_PROTOTYPE(Esys_ContextLoad) = NULL;
static DLSYM_PROTOTYPE(Esys_ContextSave) = NULL;
static DLSYM_PROTOTYPE(Esys_Create) = NULL;
static DLSYM_PROTOTYPE(Esys_CreateLoaded) = NULL;
static DLSYM_PROTOTYPE(Esys_CreatePrimary) = NULL;
static DLSYM_PROTOTYPE(Esys_EvictControl) = NULL;
static DLSYM_PROTOTYPE(Esys_Finalize) = NULL;
static DLSYM_PROTOTYPE(Esys_FlushContext) = NULL;
DLSYM_PROTOTYPE(Esys_Free) = NULL;
static DLSYM_PROTOTYPE(Esys_GetCapability) = NULL;
static DLSYM_PROTOTYPE(Esys_GetRandom) = NULL;
static DLSYM_PROTOTYPE(Esys_GetSessionAuditDigest) = NULL;
static DLSYM_PROTOTYPE(Esys_Import) = NULL;
static DLSYM_PROTOTYPE(Esys_Initialize) = NULL;
static DLSYM_PROTOTYPE(Esys_Load) = NULL;
static DLSYM_PROTOTYPE(Esys_LoadExternal) = NULL;
static DLSYM_PROTOTYPE(Esys_NV_Certify) = NULL;
static DLSYM_PROTOTYPE(Esys_NV_DefineSpace) = NULL;
static DLSYM_PROTOTYPE(Esys_NV_Extend) = NULL;
static DLSYM_PROTOTYPE(Esys_NV_Read) = NULL;
static DLSYM_PROTOTYPE(Esys_NV_ReadPublic) = NULL;
static DLSYM_PROTOTYPE(Esys_NV_UndefineSpace) = NULL;
static DLSYM_PROTOTYPE(Esys_NV_Write) = NULL;
static DLSYM_PROTOTYPE(Esys_PCR_Extend) = NULL;
static DLSYM_PROTOTYPE(Esys_PCR_Read) = NULL;
static DLSYM_PROTOTYPE(Esys_PolicyAuthValue) = NULL;
static DLSYM_PROTOTYPE(Esys_PolicyAuthorize) = NULL;
static DLSYM_PROTOTYPE(Esys_PolicyAuthorizeNV) = NULL;
static DLSYM_PROTOTYPE(Esys_PolicyGetDigest) = NULL;
static DLSYM_PROTOTYPE(Esys_PolicyNvWritten) = NULL;
static DLSYM_PROTOTYPE(Esys_PolicyOR) = NULL;
static DLSYM_PROTOTYPE(Esys_PolicyPCR) = NULL;
static DLSYM_PROTOTYPE(Esys_PolicySecret) = NULL;
static DLSYM_PROTOTYPE(Esys_PolicySigned) = NULL;
static DLSYM_PROTOTYPE(Esys_Quote) = NULL;
static DLSYM_PROTOTYPE(Esys_ReadPublic) = NULL;
static DLSYM_PROTOTYPE(Esys_StartAuthSession) = NULL;
static DLSYM_PROTOTYPE(Esys_Startup) = NULL;
static DLSYM_PROTOTYPE(Esys_TestParms) = NULL;
static DLSYM_PROTOTYPE(Esys_TR_Close) = NULL;
static DLSYM_PROTOTYPE(Esys_TR_Deserialize) = NULL;
static DLSYM_PROTOTYPE(Esys_TR_FromTPMPublic) = NULL;
static DLSYM_PROTOTYPE(Esys_TR_GetName) = NULL;
static DLSYM_PROTOTYPE(Esys_TR_GetTpmHandle) = NULL;
static DLSYM_PROTOTYPE(Esys_TR_Serialize) = NULL;
static DLSYM_PROTOTYPE(Esys_TR_SetAuth) = NULL;
static DLSYM_PROTOTYPE(Esys_TRSess_GetAttributes) = NULL;
static DLSYM_PROTOTYPE(Esys_TRSess_GetNonceTPM) = NULL;
static DLSYM_PROTOTYPE(Esys_TRSess_SetAttributes) = NULL;
static DLSYM_PROTOTYPE(Esys_Unseal) = NULL;
static DLSYM_PROTOTYPE(Esys_VerifySignature) = NULL;
 
static DLSYM_PROTOTYPE(Tss2_MU_TPM2_CC_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2_HANDLE_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_DIGEST_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_ENCRYPTED_SECRET_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_ENCRYPTED_SECRET_Unmarshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_NAME_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_PRIVATE_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_PRIVATE_Unmarshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_PUBLIC_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_PUBLIC_Unmarshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_SENSITIVE_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPML_PCR_SELECTION_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPMS_ATTEST_Unmarshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPMS_CONTEXT_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPMS_CONTEXT_Unmarshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPMS_NV_PUBLIC_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_NV_PUBLIC_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPM2B_NV_PUBLIC_Unmarshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPMS_ECC_POINT_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPMT_HA_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPMT_PUBLIC_Marshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_TPMT_PUBLIC_Unmarshal) = NULL;
static DLSYM_PROTOTYPE(Tss2_MU_UINT32_Marshal) = NULL;
 
static DLSYM_PROTOTYPE(Tss2_RC_Decode) = NULL;
 
_dlopen_loader_
static int dlopen_tpm2_esys(int log_level) {
        static void *libtss2_esys_dl = NULL;
        int r;
 
        LIBTSS2_ESYS_NOTE(suggested);
 
        r = dlopen_many_sym_or_warn(
                        &libtss2_esys_dl, "libtss2-esys.so.0", log_level,
                        DLSYM_ARG(Esys_ContextLoad),
                        DLSYM_ARG(Esys_ContextSave),
                        DLSYM_ARG(Esys_Create),
                        DLSYM_ARG(Esys_CreateLoaded),
                        DLSYM_ARG(Esys_CreatePrimary),
                        DLSYM_ARG(Esys_EvictControl),
                        DLSYM_ARG(Esys_Finalize),
                        DLSYM_ARG(Esys_FlushContext),
                        DLSYM_ARG(Esys_Free),
                        DLSYM_ARG(Esys_GetCapability),
                        DLSYM_ARG(Esys_GetRandom),
                        DLSYM_ARG(Esys_GetSessionAuditDigest),
                        DLSYM_ARG(Esys_Import),
                        DLSYM_ARG(Esys_Initialize),
                        DLSYM_ARG(Esys_Load),
                        DLSYM_ARG(Esys_LoadExternal),
                        DLSYM_ARG(Esys_NV_Certify),
                        DLSYM_ARG(Esys_NV_DefineSpace),
                        DLSYM_ARG(Esys_NV_Extend),
                        DLSYM_ARG(Esys_NV_Read),
                        DLSYM_ARG(Esys_NV_ReadPublic),
                        DLSYM_ARG(Esys_NV_UndefineSpace),
                        DLSYM_ARG(Esys_NV_Write),
                        DLSYM_ARG(Esys_PCR_Extend),
                        DLSYM_ARG(Esys_PCR_Read),
                        DLSYM_ARG(Esys_PolicyAuthValue),
                        DLSYM_ARG(Esys_PolicyAuthorize),
                        DLSYM_ARG(Esys_PolicyAuthorizeNV),
                        DLSYM_ARG(Esys_PolicyGetDigest),
                        DLSYM_ARG(Esys_PolicyNvWritten),
                        DLSYM_ARG(Esys_PolicyOR),
                        DLSYM_ARG(Esys_PolicyPCR),
                        DLSYM_ARG(Esys_PolicySecret),
                        DLSYM_ARG(Esys_PolicySigned),
                        DLSYM_ARG(Esys_Quote),
                        DLSYM_ARG(Esys_ReadPublic),
                        DLSYM_ARG(Esys_StartAuthSession),
                        DLSYM_ARG(Esys_Startup),
                        DLSYM_ARG(Esys_TestParms),
                        DLSYM_ARG(Esys_TR_Close),
                        DLSYM_ARG(Esys_TR_Deserialize),
                        DLSYM_ARG(Esys_TR_FromTPMPublic),
                        DLSYM_ARG(Esys_TR_GetName),
                        DLSYM_ARG(Esys_TR_Serialize),
                        DLSYM_ARG(Esys_TR_SetAuth),
                        DLSYM_ARG(Esys_TRSess_GetAttributes),
                        DLSYM_ARG(Esys_TRSess_GetNonceTPM),
                        DLSYM_ARG(Esys_TRSess_SetAttributes),
                        DLSYM_ARG(Esys_Unseal),
                        DLSYM_ARG(Esys_VerifySignature));
        if (r < 0)
                return r;
 
        /* Esys_TR_GetTpmHandle was added to tpm2-tss in version 2.4.0. Once we can set a minimum tpm2-tss
         * version of 2.4.0 this sym can be moved up to the normal list above. */
        r = dlsym_many_or_warn(libtss2_esys_dl, LOG_DEBUG, DLSYM_ARG_FORCE(Esys_TR_GetTpmHandle));
        if (r < 0)
                log_debug("libtss2-esys too old, does not include Esys_TR_GetTpmHandle.");
 
        return 0;
}
 
_dlopen_loader_
static int dlopen_tpm2_rc(int log_level) {
        static void *libtss2_rc_dl = NULL;
 
        LIBTSS2_RC_NOTE(suggested);
 
        return dlopen_many_sym_or_warn(
                        &libtss2_rc_dl, "libtss2-rc.so.0", log_level,
                        DLSYM_ARG(Tss2_RC_Decode));
}
 
_dlopen_loader_
static int dlopen_tpm2_mu(int log_level) {
        static void *libtss2_mu_dl = NULL;
 
        LIBTSS2_MU_NOTE(suggested);
 
        return dlopen_many_sym_or_warn(
                        &libtss2_mu_dl, "libtss2-mu.so.0", log_level,
                        DLSYM_ARG(Tss2_MU_TPM2_CC_Marshal),
                        DLSYM_ARG(Tss2_MU_TPM2_HANDLE_Marshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_DIGEST_Marshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_ENCRYPTED_SECRET_Marshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_ENCRYPTED_SECRET_Unmarshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_NAME_Marshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_PRIVATE_Marshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_PRIVATE_Unmarshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_PUBLIC_Marshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_PUBLIC_Unmarshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_SENSITIVE_Marshal),
                        DLSYM_ARG(Tss2_MU_TPML_PCR_SELECTION_Marshal),
                        DLSYM_ARG(Tss2_MU_TPMS_ATTEST_Unmarshal),
                        DLSYM_ARG(Tss2_MU_TPMS_CONTEXT_Marshal),
                        DLSYM_ARG(Tss2_MU_TPMS_CONTEXT_Unmarshal),
                        DLSYM_ARG(Tss2_MU_TPMS_NV_PUBLIC_Marshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_NV_PUBLIC_Marshal),
                        DLSYM_ARG(Tss2_MU_TPM2B_NV_PUBLIC_Unmarshal),
                        DLSYM_ARG(Tss2_MU_TPMS_ECC_POINT_Marshal),
                        DLSYM_ARG(Tss2_MU_TPMT_HA_Marshal),
                        DLSYM_ARG(Tss2_MU_TPMT_PUBLIC_Marshal),
                        DLSYM_ARG(Tss2_MU_TPMT_PUBLIC_Unmarshal),
                        DLSYM_ARG(Tss2_MU_UINT32_Marshal));
}
 
_dlopen_loader_
static int dlopen_tpm2_tcti_device(int log_level) {
        static void *libtss2_tcti_device_dl = NULL;
 
        /* The "device" TCTI is the most relevant one, let's also load it explicitly on dlopen_tpm2(), even
         * if we don't resolve any symbols here. */
 
        LIBTSS2_TCTI_DEVICE_NOTE(suggested);
 
        return dlopen_verbose(
                        &libtss2_tcti_device_dl,
                        "libtss2-tcti-device.so.0",
                        log_level);
}
 
#endif
 
int dlopen_tpm2(int log_level) {
#if HAVE_TPM2
        int r;
 
        r = dlopen_tpm2_esys(log_level);
        if (r < 0)
                return r;
 
        r = dlopen_tpm2_rc(log_level);
        if (r < 0)
                return r;
 
        r = dlopen_tpm2_mu(log_level);
        if (r < 0)
                return r;
 
        r = dlopen_tpm2_tcti_device(log_level);
        if (r < 0)
                return r;
 
        return 0;
#else
        return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
                              "TPM2 support is not compiled in.");
#endif
}
 
#if HAVE_TPM2
 
void Esys_Freep(void *p) {
        assert(p);
 
        if (*(void**) p)
                sym_Esys_Free(*(void**) p);
}
 
static void tpm2b_sensitive_data_erase_and_esys_freep(TPM2B_SENSITIVE_DATA **p) {
        assert(p);
 
        if (!*p)
                return;
 
        explicit_bzero_safe((*p)->buffer, (*p)->size);
        sym_Esys_Free(*p);
}
 
/* Get a specific TPM capability (or capabilities).
 *
 * Returns 0 if there are no more capability properties of the requested type, or 1 if there are more, or < 0
 * on any error. Both 0 and 1 indicate this completed successfully, but do not indicate how many capability
 * properties were provided in 'ret_capability_data'. To find the number of provided properties, check the
 * specific type's 'count' field (e.g. for TPM2_CAP_ALGS, check ret_capability_data->algorithms.count).
 *
 * This calls TPM2_GetCapability() and does not alter the provided data, so it is important to understand how
 * that TPM function works. It is recommended to check the TCG TPM specification Part 3 ("Commands") section
 * on TPM2_GetCapability() for full details, but a short summary is: if this returns 0, all available
 * properties have been provided in ret_capability_data, or no properties were available. If this returns 1,
 * there are between 1 and "count" properties provided in ret_capability_data, and there are more available.
 * Note that this may provide less than "count" properties even if the TPM has more available. Also, each
 * capability category may have more specific requirements than described here; see the spec for exact
 * details. */
static int tpm2_get_capability(
                Tpm2Context *c,
                TPM2_CAP capability,
                uint32_t property,
                uint32_t count,
                TPMU_CAPABILITIES *ret_capability_data) {
 
        _cleanup_(Esys_Freep) TPMS_CAPABILITY_DATA *capabilities = NULL;
        TPMI_YES_NO more;
        TSS2_RC rc;
 
        assert(c);
 
        log_debug("Getting TPM2 capability 0x%04" PRIx32 " property 0x%04" PRIx32 " count %" PRIu32 ".",
                  capability, property, count);
 
        rc = sym_Esys_GetCapability(
                        c->esys_context,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        capability,
                        property,
                        count,
                        &more,
                        &capabilities);
        if (rc == TPM2_RC_VALUE)
                return log_debug_errno(SYNTHETIC_ERRNO(ENXIO),
                                       "Requested TPM2 capability 0x%04" PRIx32 " property 0x%04" PRIx32 " apparently doesn't exist: %s",
                                       capability, property, sym_Tss2_RC_Decode(rc));
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to get TPM2 capability 0x%04" PRIx32 " property 0x%04" PRIx32 ": %s",
                                       capability, property, sym_Tss2_RC_Decode(rc));
        if (capabilities->capability != capability)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "TPM provided wrong capability: 0x%04" PRIx32 " instead of 0x%04" PRIx32 ".",
                                       capabilities->capability, capability);
 
        if (ret_capability_data)
                *ret_capability_data = capabilities->data;
 
        return more == TPM2_YES;
}
 
static int tpm2_get_capability_property(Tpm2Context *c, uint32_t property, uint32_t *ret_value) {
        int r;
 
        assert(c);
        assert(ret_value);
 
        TPMU_CAPABILITIES capabilities = {};
        r = tpm2_get_capability(c, TPM2_CAP_TPM_PROPERTIES, property, 1, &capabilities);
        if (r < 0)
                return r;
 
        if (capabilities.tpmProperties.count == 0 ||
            capabilities.tpmProperties.tpmProperty[0].property != property)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "TPM property 0x%04" PRIx32 " does not exist", property);
 
        *ret_value = capabilities.tpmProperties.tpmProperty[0].value;
        return 0;
}
 
int tpm2_vendor_info_to_modalias(const Tpm2VendorInfo *info, char **ret) {
        _cleanup_free_ char *m = NULL;
 
        assert(info);
        assert(ret);
 
        /* Closely inspired by kernel modalias strings, this distills information from the TPM vendor data
         * into a string suitable for matching hwdb */
 
        if (asprintf(&m,
                     "fi%s:"
                     "lv%" PRIu32 ":"
                     "rv%" PRIu32 ".%" PRIu32 ":"
                     "sy%" PRIu32 ":"
                     "sd%" PRIu32 ":"
                     "mf%s:"
                     "vs%s:"
                     "ty%" PRIx32 ":"
                     "fw%" PRIu16 ".%" PRIu16 ".%" PRIu32 ":",
                     info->family_indicator,
                     info->level,
                     info->revision_major,
                     info->revision_minor,
                     info->year,
                     info->day_of_year,
                     info->manufacturer,
                     info->vendor_string,
                     info->vendor_tpm_type,
                     info->firmware_version_major,
                     info->firmware_version_minor,
                     info->firmware_version2) < 0)
                return -ENOMEM;
 
        *ret = TAKE_PTR(m);
        return 0;
}
 
static char *mangle_vendor_chars(char *c, size_t n) {
        char *end = c;
        assert(c || n == 0);
 
        /* Suppress all control characters, whitespace and non-ASCII bytes */
        for (char *x = c; x < c + n; x++) {
                if (!IN_SET(*x, ' ', 0))
                        end = x + 1;
 
                if ((unsigned char) *x <= (unsigned char) ' ' ||
                    (unsigned char) *x >= 127)
                        *x = '_';
        }
 
        /* Drop trailing spaces and NUL bytes */
        *end = 0;
        return c;
}
 
int tpm2_get_vendor_info(
                Tpm2Context *c,
                Tpm2VendorInfo *ret) {
 
        int r;
 
        assert(c);
        assert(ret);
 
        TPMU_CAPABILITIES capabilities = {};
        r = tpm2_get_capability(
                        c,
                        TPM2_CAP_TPM_PROPERTIES,
                        TPM2_PT_FAMILY_INDICATOR,
                        TPM2_PT_FIRMWARE_VERSION_2 - TPM2_PT_FAMILY_INDICATOR + 1, /* get all relevant fields at once */
                        &capabilities);
        if (r < 0)
                return r;
 
        Tpm2VendorInfo info = {};
 
        for (uint32_t i = 0; i < capabilities.tpmProperties.count; i++) {
                TPMS_TAGGED_PROPERTY *p = capabilities.tpmProperties.tpmProperty + i;
 
                switch (p->property) {
 
                case TPM2_PT_FAMILY_INDICATOR:
                        unaligned_write_be32(info.family_indicator, p->value);
                        mangle_vendor_chars(info.family_indicator, sizeof(info.family_indicator));
                        break;
 
                case TPM2_PT_LEVEL:
                        info.level = p->value;
                        break;
 
                case TPM2_PT_REVISION:
                        info.revision_major = p->value / 100;
                        info.revision_minor = p->value % 100;
                        break;
 
                case TPM2_PT_DAY_OF_YEAR:
                        info.day_of_year = p->value;
                        break;
 
                case TPM2_PT_YEAR:
                        info.year = p->value;
                        break;
 
                case TPM2_PT_MANUFACTURER:
                        unaligned_write_be32(info.manufacturer, p->value);
                        mangle_vendor_chars(info.manufacturer, sizeof(info.manufacturer));
                        break;
 
                case TPM2_PT_VENDOR_STRING_1:
                        unaligned_write_be32(info.vendor_string+0, p->value);
                        break;
 
                case TPM2_PT_VENDOR_STRING_2:
                        unaligned_write_be32(info.vendor_string+4, p->value);
                        break;
 
                case TPM2_PT_VENDOR_STRING_3:
                        unaligned_write_be32(info.vendor_string+8, p->value);
                        break;
 
                case TPM2_PT_VENDOR_STRING_4:
                        unaligned_write_be32(info.vendor_string+12, p->value);
                        break;
 
                case TPM2_PT_VENDOR_TPM_TYPE:
                        info.vendor_tpm_type = p->value;
                        break;
 
                case TPM2_PT_FIRMWARE_VERSION_1:
                        info.firmware_version_major = p->value >> 16;
                        info.firmware_version_minor = p->value & 0xFFFFU;
                        break;
 
                case TPM2_PT_FIRMWARE_VERSION_2:
                        info.firmware_version2 = p->value;
                        break;
                }
        }
 
        mangle_vendor_chars(info.vendor_string, sizeof(info.vendor_string));
        *ret = TAKE_STRUCT(info);
        return 0;
}
 
#define TPMA_CC_TO_TPM2_CC(cca) (((cca) & TPMA_CC_COMMANDINDEX_MASK) >> TPMA_CC_COMMANDINDEX_SHIFT)
 
/* The TCG reference library spec (part 2) doesn't guarantee a minimum size for the
 * TPM2B_MAX_NV_BUFFER type. However, the PC-Client PTP spec does set a minimum value of 512,
 * so we'll just assume this if the TPM didn't report a value or reports an implausible value. */
#define FALLBACK_MAX_NV_BUFFER_SIZE 512u
 
static int tpm2_cache_capabilities(Tpm2Context *c) {
        TPMU_CAPABILITIES capability;
        int r;
 
        assert(c);
 
        /* Cache the algorithms. The spec indicates supported algorithms can only be modified during runtime
         * by the SetAlgorithmSet() command. Unfortunately, the spec doesn't require a TPM reinitialization
         * after changing the algorithm set (unless the PCR algorithms are changed). However, the spec also
         * indicates the TPM behavior after SetAlgorithmSet() is "vendor-dependent", giving the example of
         * flushing sessions and objects, erasing policies, etc. So, if the algorithm set is programmatically
         * changed while we are performing some operation, it's reasonable to assume it will break us even if
         * we don't cache the algorithms, thus they should be "safe" to cache. */
        TPM2_ALG_ID current_alg = TPM2_ALG_FIRST;
        for (;;) {
                r = tpm2_get_capability(
                                c,
                                TPM2_CAP_ALGS,
                                (uint32_t) current_alg, /* The spec states to cast TPM2_ALG_ID to uint32_t. */
                                TPM2_MAX_CAP_ALGS,
                                &capability);
                if (r < 0)
                        return r;
 
                TPML_ALG_PROPERTY algorithms = capability.algorithms;
 
                /* We should never get 0; the TPM must support some algorithms, and it must not set 'more' if
                 * there are no more. */
                assert(algorithms.count > 0);
 
                if (!GREEDY_REALLOC_APPEND(
                                c->capability_algorithms,
                                c->n_capability_algorithms,
                                algorithms.algProperties,
                                algorithms.count))
                        return log_oom_debug();
 
                if (r == 0)
                        break;
 
                /* Set current_alg to alg id after last alg id the TPM provided */
                current_alg = algorithms.algProperties[algorithms.count - 1].alg + 1;
        }
 
        /* Cache the command capabilities. The spec isn't actually clear if commands can be added/removed
         * while running, but that would be crazy, so let's hope it is not possible. */
        TPM2_CC current_cc = TPM2_CC_FIRST;
        for (;;) {
                r = tpm2_get_capability(
                                c,
                                TPM2_CAP_COMMANDS,
                                current_cc,
                                TPM2_MAX_CAP_CC,
                                &capability);
                if (r < 0)
                        return r;
 
                TPML_CCA commands = capability.command;
 
                /* We should never get 0; the TPM must support some commands, and it must not set 'more' if
                 * there are no more. */
                assert(commands.count > 0);
 
                if (!GREEDY_REALLOC_APPEND(
                                c->capability_commands,
                                c->n_capability_commands,
                                commands.commandAttributes,
                                commands.count))
                        return log_oom_debug();
 
                if (r == 0)
                        break;
 
                /* Set current_cc to index after last cc the TPM provided */
                current_cc = TPMA_CC_TO_TPM2_CC(commands.commandAttributes[commands.count - 1]) + 1;
        }
 
        /* Cache the ECC curves. The spec isn't actually clear if ECC curves can be added/removed
         * while running, but that would be crazy, so let's hope it is not possible. */
        TPM2_ECC_CURVE current_ecc_curve = TPM2_ECC_NONE;
        for (;;) {
                r = tpm2_get_capability(
                                c,
                                TPM2_CAP_ECC_CURVES,
                                current_ecc_curve,
                                TPM2_MAX_ECC_CURVES,
                                &capability);
                if (r == -ENXIO) /* If the TPM doesn't support ECC, it might return TPM2_RC_VALUE rather than capability.eccCurves == 0 */
                        break;
                if (r < 0)
                        return r;
 
                TPML_ECC_CURVE ecc_curves = capability.eccCurves;
 
                /* ECC support isn't required */
                if (ecc_curves.count == 0)
                        break;
 
                if (!GREEDY_REALLOC_APPEND(
                                c->capability_ecc_curves,
                                c->n_capability_ecc_curves,
                                ecc_curves.eccCurves,
                                ecc_curves.count))
                        return log_oom_debug();
 
                if (r == 0)
                        break;
 
                /* Set current_ecc_curve to index after last ecc curve the TPM provided */
                current_ecc_curve = ecc_curves.eccCurves[ecc_curves.count - 1] + 1;
        }
 
        /* Cache the PCR capabilities, which are safe to cache, as the only way they can change is
         * TPM2_PCR_Allocate(), which changes the allocation after the next _TPM_Init(). If the TPM is
         * reinitialized while we are using it, all our context and sessions will be invalid, so we can
         * safely assume the TPM PCR allocation will not change while we are using it. */
        r = tpm2_get_capability(
                        c,
                        TPM2_CAP_PCRS,
                        /* property= */ 0,
                        /* count= */ 1,
                        &capability);
        if (r < 0)
                return r;
        if (r == 1)
                /* This should never happen. Part 3 ("Commands") of the TCG TPM2 spec in the section for
                 * TPM2_GetCapability states: "TPM_CAP_PCRS – Returns the current allocation of PCR in a
                 * TPML_PCR_SELECTION. The property parameter shall be zero. The TPM will always respond to
                 * this command with the full PCR allocation and moreData will be NO." */
                log_debug("TPM bug: reported multiple PCR sets; using only first set.");
        c->capability_pcrs = capability.assignedPCR;
 
        /* Cache the value of TPM_PT_NV_BUFFER_MAX, which defines the maximum size of TPM2B_MAX_NV_BUFFER and
         * which limits the amount of data that TPM2_NV_Read can return in a single command. This may be
         * smaller than the size of a NV index payload, particularly if that payload contains a X509
         * certificate with a RSA public key. */
        uint32_t max_nv_buffer_size = 0;
 
        r = tpm2_get_capability_property(c, TPM2_PT_NV_BUFFER_MAX, &max_nv_buffer_size);
        if (r == -ENOENT) {
                log_debug("TPM bug: didn't report a value for TPM_PT_NV_BUFFER_MAX; using %"PRIu32".", FALLBACK_MAX_NV_BUFFER_SIZE);
                max_nv_buffer_size = FALLBACK_MAX_NV_BUFFER_SIZE;
        } else if (r < 0)
                return r;
        if (max_nv_buffer_size == 0 || max_nv_buffer_size > UINT16_MAX) {
                /* TPM2B types have a uint16 size field. If the TPM reported a maximum size that is larger
                 * than this, or 0, then consider this as implausible and pick the default fallback. */
                log_debug("TPM bug: reported implausible value for TPM_PT_NV_BUFFER_MAX; using %"PRIu32".", FALLBACK_MAX_NV_BUFFER_SIZE);
                max_nv_buffer_size = FALLBACK_MAX_NV_BUFFER_SIZE;
        }
        c->max_nv_buffer_size = (uint16_t) max_nv_buffer_size;
 
        return 0;
}
 
/* Get the TPMA_ALGORITHM for a TPM2_ALG_ID. Returns true if the TPM supports the algorithm and the
 * TPMA_ALGORITHM is provided, otherwise false. */
static bool tpm2_get_capability_alg(Tpm2Context *c, TPM2_ALG_ID alg, TPMA_ALGORITHM *ret) {
        assert(c);
 
        FOREACH_ARRAY(alg_prop, c->capability_algorithms, c->n_capability_algorithms)
                if (alg_prop->alg == alg) {
                        if (ret)
                                *ret = alg_prop->algProperties;
                        return true;
                }
 
        log_debug("TPM does not support alg 0x%02" PRIx16 ".", alg);
        if (ret)
                *ret = 0;
 
        return false;
}
 
bool tpm2_supports_alg(Tpm2Context *c, TPM2_ALG_ID alg) {
        return tpm2_get_capability_alg(c, alg, NULL);
}
 
/* Get the TPMA_CC for a TPM2_CC. Returns true if the TPM supports the command and the TPMA_CC is provided,
 * otherwise false. */
static bool tpm2_get_capability_command(Tpm2Context *c, TPM2_CC command, TPMA_CC *ret) {
        assert(c);
 
        FOREACH_ARRAY(cca, c->capability_commands, c->n_capability_commands)
                if (TPMA_CC_TO_TPM2_CC(*cca) == command) {
                        if (ret)
                                *ret = *cca;
                        return true;
                }
 
        log_debug("TPM does not support command 0x%04" PRIx32 ".", command);
        if (ret)
                *ret = 0;
 
        return false;
}
 
bool tpm2_supports_command(Tpm2Context *c, TPM2_CC command) {
        return tpm2_get_capability_command(c, command, NULL);
}
 
/* Returns true if the TPM supports the ECC curve, otherwise false. */
bool tpm2_supports_ecc_curve(Tpm2Context *c, TPM2_ECC_CURVE ecc_curve) {
        assert(c);
 
        FOREACH_ARRAY(curve, c->capability_ecc_curves, c->n_capability_ecc_curves)
                if (*curve == ecc_curve)
                        return true;
 
        log_debug("TPM does not support ECC curve 0x%" PRIx16 ".", ecc_curve);
        return false;
}
 
/* Return the maximum size of a TPM2B_DATA structure. This structure is intended to be able to
 * store a TPMT_HA structure, so the maximum size is the value of TPM_PT_MAX_DIGEST (the maximum size
 * of a TPMU_HA structure) + the size of TPM_ALG_ID. */
int tpm2_max_data_size(Tpm2Context *c) {
        int r;
 
        assert(c);
 
        uint32_t max_digest_size = 0;
        r = tpm2_get_capability_property(c, TPM2_PT_MAX_DIGEST, &max_digest_size);
        if (r < 0)
                return r;
 
        if (max_digest_size > (UINT16_MAX - sizeof(TPM2_ALG_ID)))
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "TPM bug: reported implausible value for TPM_PT_MAX_DIGEST");
 
        return (int) max_digest_size + sizeof(TPM2_ALG_ID);
}
 
/* Query the TPM for populated handles.
 *
 * This provides an array of handle indexes populated in the TPM, starting at the requested handle. The array will
 * contain only populated handle addresses (which might not include the requested handle). The number of
 * handles will be no more than the 'max' number requested. This will not search past the end of the handle
 * range (i.e. handle & 0xff000000).
 *
 * Returns 0 if all populated handles in the range (starting at the requested handle) were provided (or no
 * handles were in the range), or 1 if there are more populated handles in the range, or < 0 on any error. */
static int tpm2_get_capability_handles(
                Tpm2Context *c,
                TPM2_HANDLE start,
                size_t max,
                TPM2_HANDLE **ret_handles,
                size_t *ret_n_handles) {
 
        _cleanup_free_ TPM2_HANDLE *handles = NULL;
        size_t n_handles = 0;
        TPM2_HANDLE current = start;
        int r = 0;
 
        assert(c);
        assert(ret_handles);
        assert(ret_n_handles);
 
        max = MIN(max, UINT32_MAX);
 
        while (max > 0) {
                TPMU_CAPABILITIES capability;
                r = tpm2_get_capability(c, TPM2_CAP_HANDLES, current, (uint32_t) max, &capability);
                if (r < 0)
                        return r;
 
                TPML_HANDLE handle_list = capability.handles;
                if (handle_list.count == 0)
                        break;
 
                assert(handle_list.count <= max);
 
                if (n_handles > SIZE_MAX - handle_list.count)
                        return log_oom_debug();
 
                if (!GREEDY_REALLOC_APPEND(handles, n_handles, handle_list.handle, handle_list.count))
                        return log_oom_debug();
 
                max -= handle_list.count;
 
                /* Update current to the handle index after the last handle in the list. */
                current = handles[n_handles - 1] + 1;
 
                if (r == 0)
                        /* No more handles in this range. */
                        break;
        }
 
        *ret_handles = TAKE_PTR(handles);
        *ret_n_handles = n_handles;
 
        return r;
}
 
#define TPM2_HANDLE_RANGE(h) ((TPM2_HANDLE)((h) & TPM2_HR_RANGE_MASK))
#define TPM2_HANDLE_TYPE(h) ((TPM2_HT)(TPM2_HANDLE_RANGE(h) >> TPM2_HR_SHIFT))
 
/* Returns 1 if the handle is populated in the TPM, 0 if not, and < 0 on any error. */
static int tpm2_get_capability_handle(Tpm2Context *c, TPM2_HANDLE handle) {
        _cleanup_free_ TPM2_HANDLE *handles = NULL;
        size_t n_handles = 0;
        int r;
 
        r = tpm2_get_capability_handles(c, handle, 1, &handles, &n_handles);
        if (r < 0)
                return r;
 
        return n_handles == 0 ? false : handles[0] == handle;
}
 
/* Returns 1 if the TPM supports the parms, or 0 if the TPM does not support the parms. */
bool tpm2_test_parms(Tpm2Context *c, TPMI_ALG_PUBLIC alg, const TPMU_PUBLIC_PARMS *parms) {
        TSS2_RC rc;
 
        assert(c);
        assert(parms);
 
        TPMT_PUBLIC_PARMS parameters = {
                .type = alg,
                .parameters = *parms,
        };
 
        rc = sym_Esys_TestParms(c->esys_context, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, &parameters);
        if (rc != TSS2_RC_SUCCESS)
                /* The spec says if the parms are not supported the TPM returns "...the appropriate
                 * unmarshaling error if a parameter is not valid". Since the spec (currently) defines 15
                 * unmarshaling errors, instead of checking for them all here, let's just assume any error
                 * indicates unsupported parms, and log the specific error text. */
                log_debug("TPM does not support tested parms: %s", sym_Tss2_RC_Decode(rc));
 
        return rc == TSS2_RC_SUCCESS;
}
 
static bool tpm2_supports_tpmt_public(Tpm2Context *c, const TPMT_PUBLIC *public) {
        assert(c);
        assert(public);
 
        return tpm2_test_parms(c, public->type, &public->parameters);
}
 
static bool tpm2_supports_tpmt_sym_def_object(Tpm2Context *c, const TPMT_SYM_DEF_OBJECT *parameters) {
        assert(c);
        assert(parameters);
 
        TPMU_PUBLIC_PARMS parms = {
                .symDetail.sym = *parameters,
        };
 
        return tpm2_test_parms(c, TPM2_ALG_SYMCIPHER, &parms);
}
 
static bool tpm2_supports_tpmt_sym_def(Tpm2Context *c, const TPMT_SYM_DEF *parameters) {
        assert(c);
        assert(parameters);
 
        /* Unfortunately, TPMT_SYM_DEF and TPMT_SYM_DEF_OBJECT are separately defined, even though they are
         * functionally identical. */
        TPMT_SYM_DEF_OBJECT object = {
                .algorithm = parameters->algorithm,
                .keyBits = parameters->keyBits,
                .mode = parameters->mode,
        };
 
        return tpm2_supports_tpmt_sym_def_object(c, &object);
}
 
static Tpm2Context *tpm2_context_free(Tpm2Context *c) {
        if (!c)
                return NULL;
 
        if (c->esys_context)
                sym_Esys_Finalize(&c->esys_context);
 
        c->tcti_context = mfree(c->tcti_context);
        c->tcti_dl = safe_dlclose(c->tcti_dl);
 
        c->capability_algorithms = mfree(c->capability_algorithms);
        c->capability_commands = mfree(c->capability_commands);
        c->capability_ecc_curves = mfree(c->capability_ecc_curves);
 
        c->tcti_driver = mfree(c->tcti_driver);
        c->tcti_param = mfree(c->tcti_param);
 
        return mfree(c);
}
 
DEFINE_TRIVIAL_REF_UNREF_FUNC(Tpm2Context, tpm2_context, tpm2_context_free);
 
static const TPMT_SYM_DEF SESSION_TEMPLATE_SYM_AES_128_CFB = {
        .algorithm = TPM2_ALG_AES,
        .keyBits.aes = 128,
        .mode.aes = TPM2_ALG_CFB, /* The spec requires sessions to use CFB. */
};
 
static const TPMT_SYM_DEF SESSION_TEMPLATE_SYM_NULL = {
        .algorithm = TPM2_ALG_NULL,
};
 
int tpm2_context_new(const char *device, Tpm2Context **ret_context) {
        _cleanup_(tpm2_context_unrefp) Tpm2Context *context = NULL;
        TSS2_RC rc;
        int r;
 
        assert(ret_context);
 
        context = new(Tpm2Context, 1);
        if (!context)
                return log_oom_debug();
 
        *context = (Tpm2Context) {
                .n_ref = 1,
        };