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 2001–3000 of 12,273

                const Tpm2Handle *session,
                TPM2B_PUBLIC **ret_public,
                TPM2B_NAME **ret_name,
                TPM2B_NAME **ret_qname,
                Tpm2Handle **ret_handle) {
 
        return tpm2_object_index_to_handle(c, TPM2_SRK_HANDLE, session, ret_public, ret_name, ret_qname, ret_handle);
}
 
/* Get the SRK, creating one if needed. Returns 1 if a new SRK was created and persisted, 0 if an SRK already
 * exists, or < 0 on error. */
int tpm2_get_or_create_srk(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPM2B_PUBLIC **ret_public,
                TPM2B_NAME **ret_name,
                TPM2B_NAME **ret_qname,
                Tpm2Handle **ret_handle) {
 
        int r;
 
        r = tpm2_get_srk(c, session, ret_public, ret_name, ret_qname, ret_handle);
        if (r < 0)
                return r;
        if (r == 1)
                return 0; /* 0 → SRK already set up */
 
        /* No SRK, create and persist one */
        TPM2B_PUBLIC template = {
                .size = sizeof(TPMT_PUBLIC),
        };
        r = tpm2_get_best_srk_template(c, &template.publicArea);
        if (r < 0)
                return log_debug_errno(r, "Could not get best SRK template: %m");
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *transient_handle = NULL;
        r = tpm2_create_primary(
                        c,
                        session,
                        ESYS_TR_RH_OWNER,
                        &template,
                        /* sensitive= */ NULL,
                        /* ret_public= */ NULL,
                        &transient_handle);
        if (r < 0)
                return r;
 
        /* Try to persist the transient SRK we created. No locking needed; if multiple threads are trying to
         * persist SRKs concurrently, only one will succeed (r == 1) while the rest will fail (r == 0). In
         * either case, all threads will get the persistent SRK below. */
        r = tpm2_persist_handle(c, transient_handle, session, TPM2_SRK_HANDLE, /* ret_persistent_handle= */ NULL);
        if (r < 0)
                return r;
 
        /* The SRK should exist now. */
        r = tpm2_get_srk(c, session, ret_public, ret_name, ret_qname, ret_handle);
        if (r < 0)
                return r;
        if (r == 0)
                /* This should never happen. */
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "SRK we just persisted couldn't be found.");
 
        return 1; /* > 0 → SRK newly set up */
}
 
static bool has_expected_ek_cert_attributes(const TPM2B_NV_PUBLIC *nv_pub) {
        /* Determine whether the supplied NV index has the expected attributes for an EK certificate. These
         * attributes are defined in the "TCG PC Client Platform TPM Profile Specification for TPM 2.0" spec,
         * section 4.6.3.1 (Preprovisioned EK Certificates).
         *
         * TPMA_NV_OWNERREAD isn't required because some TPMs ship EK certs with only TPMA_NV_AUTHREAD.
         *
         * https://trustedcomputinggroup.org/resource/pc-client-platform-tpm-profile-ptp-specification/ */
        if ((nv_pub->nvPublic.attributes & TPMA_NV_TPM2_NT_MASK) != (TPM2_NT_ORDINARY << TPMA_NV_TPM2_NT_SHIFT))
                return false;
 
        static const TPMA_NV expected_clear_attrs =
                TPMA_NV_AUTHWRITE |
                TPMA_NV_OWNERWRITE |
                TPMA_NV_GLOBALLOCK |
                TPMA_NV_CLEAR_STCLEAR |
                TPMA_NV_ORDERLY |
                TPMA_NV_READ_STCLEAR;
        static const TPMA_NV expected_set_attrs =
                TPMA_NV_PLATFORMCREATE |
                TPMA_NV_AUTHREAD |
                TPMA_NV_NO_DA;
        return (((nv_pub->nvPublic.attributes & expected_set_attrs) == expected_set_attrs) &&
                ((nv_pub->nvPublic.attributes & expected_clear_attrs) == 0));
}
 
/* A mapping of each EK profile to the NV index handle where the corresponding EK certificate is expected to
 * be stored. Each EK profile has a dedicated NV index. See the "TCG EK Credential Profile for TPM Family
 * 2.0" spec, sections 2.2.2.4 (low range) and 2.2.2.5 (high range).
 *
 * https://trustedcomputinggroup.org/resource/http-trustedcomputinggroup-org-wp-content-uploads-tcg-ek-credential-profile/ */
static const TPM2_HANDLE ek_cert_nv_indexes[_TPM2_EK_TEMPLATE_MAX] = {
        [TPM2_EK_TEMPLATE_RSA_2048_LEGACY]      = 0x01C00002,
        [TPM2_EK_TEMPLATE_ECC_NIST_P256_LEGACY] = 0x01C0000A,
        [TPM2_EK_TEMPLATE_RSA_2048]             = 0x01C00012,
        [TPM2_EK_TEMPLATE_ECC_NIST_P256]        = 0x01C00014,
        [TPM2_EK_TEMPLATE_ECC_NIST_P384]        = 0x01C00016,
        [TPM2_EK_TEMPLATE_RSA_3072]             = 0x01C0001C,
};
 
#if HAVE_OPENSSL
 
static const char* const ek_template_names[_TPM2_EK_TEMPLATE_MAX] = {
        [TPM2_EK_TEMPLATE_RSA_2048_LEGACY]      = "RSA 2048 (L-1)",
        [TPM2_EK_TEMPLATE_ECC_NIST_P256_LEGACY] = "ECC NIST P256 (L-2)",
        [TPM2_EK_TEMPLATE_RSA_2048]             = "RSA 2048 (H-1)",
        [TPM2_EK_TEMPLATE_ECC_NIST_P256]        = "ECC NIST P256 (H-2)",
        [TPM2_EK_TEMPLATE_ECC_NIST_P384]        = "ECC NIST P384 (H-3)",
        [TPM2_EK_TEMPLATE_RSA_3072]             = "RSA 3072 (H-6)",
};
 
/* Read the EK certificate from its NV index for the specified EK profile. This returns 1 if there is a
 * valid certificate, 0 if no valid NV index exists, or < 0 if an error occurs. Note that this doesn't check
 * that the obtained certificate has the expected public key algorithm. */
static int tpm2_read_ek_cert(
                Tpm2Context *c,
                const Tpm2Handle *session,
                Tpm2EKTemplateProfile profile,
                X509 **ret_cert) {
 
        int r;
 
        assert(c);
        assert(profile >= 0);
        assert(profile < _TPM2_EK_TEMPLATE_MAX);
        assert(ret_cert);
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        TPM2_HANDLE cert_index = ek_cert_nv_indexes[profile];
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *cert_handle = NULL;
        _cleanup_(Esys_Freep) TPM2B_NV_PUBLIC *cert_nvpub = NULL;
        r = tpm2_nv_index_to_handle(c, cert_index, session, &cert_nvpub, /* ret_name= */ NULL, &cert_handle);
        if (r < 0)
                return r;
        if (r == 0) {
                *ret_cert = NULL;
                return r;
        }
 
        /* Ignore any NV index that doesn't have the expected attributes, to ensure that we don't generate
         * erroneous errors if we encounter some arbitrary owner-created index. */
        if (!has_expected_ek_cert_attributes(cert_nvpub)) {
                *ret_cert = NULL;
                return 0;
        }
 
        _cleanup_(iovec_done) struct iovec cert_data = {};
        r = tpm2_read_nv_index(c, session, cert_index, cert_handle, &cert_data);
        if (r < 0)
                return r;
 
        const unsigned char *p = cert_data.iov_base;
        _cleanup_(X509_freep) X509 *cert = sym_d2i_X509(NULL, &p, (long) cert_data.iov_len);
        if (!cert)
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                       "Failed to parse EK certificate for template '%s' from NV index 0x%08" PRIx32 ": %s",
                                       ek_template_names[profile], cert_index, sym_ERR_error_string(sym_ERR_get_error(), NULL));
 
        *ret_cert = TAKE_PTR(cert);
        return 1;
}
 
#endif
 
/* Obtain a custom EK template for the specified EK profile. The "TCG EK Credential Profile for TPM Family
 * 2.0" spec details how a TPM manufacturer can certify endorsement keys with templates that differ from the
 * default ones by storing a template in a NV index. Returns 1 if there is a custom template, 0 if there is
 * no custom template, or < 0 if an error occurred.
 *
 * https://trustedcomputinggroup.org/resource/http-trustedcomputinggroup-org-wp-content-uploads-tcg-ek-credential-profile/ */
static int tpm2_get_custom_ek_template(
                Tpm2Context *c,
                const Tpm2Handle *session,
                Tpm2EKTemplateProfile profile,
                TPMT_PUBLIC *ret_template) {
 
        int r;
 
        assert(c);
        assert(profile >= 0);
        assert(profile < _TPM2_EK_TEMPLATE_MAX);
        assert(ret_template);
 
        TPM2_HANDLE cert_index = ek_cert_nv_indexes[profile];
 
        /* Handle 0x01c00012 is the start of the "High Range" EK certs, with those lower than this being the
         * legacy "Low Range" ones. Low range certs can have an optional nonce as well as a custom template.
         * High range certs can only have a custom template, defined at the next subsequent (odd) NV index.
         * See sections 2.2.2.4 and 2.2.2.5 of the "TCG EK Credential Profile for TPM Family 2.0" spec. */
        TPM2_HANDLE template_index = cert_index >= 0x01C00012 ? cert_index + 1 : cert_index + 2;
        TPM2_HANDLE nonce_index = cert_index >= 0x01C00012 ? 0 : cert_index + 1;
 
        /* First check if there is a custom EK template NV index defined. */
        _cleanup_(tpm2_handle_freep) Tpm2Handle *template_handle = NULL;
        _cleanup_(Esys_Freep) TPM2B_NV_PUBLIC *template_nvpub = NULL;
        r = tpm2_nv_index_to_handle(c, template_index, session, &template_nvpub, /* ret_name= */ NULL, &template_handle);
        if (r < 0)
                return r;
        if (r > 0 && !has_expected_ek_cert_attributes(template_nvpub))
                /* Ignore this NV index because it doesn't have the expected attributes. */
                template_handle = tpm2_handle_free(template_handle);
 
        /* Now check if there is a nonce NV index defined. Table 1 of the "TCG EK Credential Profile for TPM
         * Family 2.0" spec suggests this combination (EKnonce without EKtemplate) must not appear, but
         * apparently this configuration did ship with Intel PTT. */
        _cleanup_(tpm2_handle_freep) Tpm2Handle *nonce_handle = NULL;
        _cleanup_(Esys_Freep) TPM2B_NV_PUBLIC *nonce_nvpub = NULL;
        if (nonce_index != 0) {
                r = tpm2_nv_index_to_handle(c, nonce_index, session, &nonce_nvpub, /* ret_name= */ NULL, &nonce_handle);
                if (r < 0)
                        return r;
                if (r > 0 && !has_expected_ek_cert_attributes(nonce_nvpub))
                        /* Ignore this NV index because it doesn't have the expected attributes. */
                        nonce_handle = tpm2_handle_free(nonce_handle);
        }
 
        if (!template_handle && !nonce_handle) {
                /* There is no custom template. */
                *ret_template = (TPMT_PUBLIC){};
                return 0;
        }
 
        TPMT_PUBLIC template = {};
        if (template_handle) {
                _cleanup_(iovec_done) struct iovec template_data = {};
                r = tpm2_read_nv_index(c, session, template_index, template_handle, &template_data);
                if (r < 0)
                        return r;
 
                size_t offset = 0;
                TSS2_RC rc = sym_Tss2_MU_TPMT_PUBLIC_Unmarshal(template_data.iov_base, template_data.iov_len, &offset, &template);
                if (rc != TSS2_RC_SUCCESS)
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed to unmarshal EK template from NV index 0x%08" PRIx32 ": %s",
                                               template_index, sym_Tss2_RC_Decode(rc));
                if (offset != template_data.iov_len)
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                               "Garbage at end of custom template data.");
        } else
                tpm2_get_default_ek_template(profile, &template);
 
        if (nonce_handle) {
                /* We have a nonce. Section 2.2.2.6 of the "TCG EK Credential Profile for TPM Family 2.0"
                 * spec explains how to construct the template from this. */
                _cleanup_(iovec_done) struct iovec nonce_data = {};
                r = tpm2_read_nv_index(c, session, nonce_index, nonce_handle, &nonce_data);
                if (r < 0)
                        return r;
 
                zero(template.unique);
 
                switch (profile) {
                case TPM2_EK_TEMPLATE_RSA_2048_LEGACY:
                        /* For the RSA-2048 (L-1) template, set unique.rsa to the nonce and append zero
                         * bytes to pad it to a size of 256-bytes. */
                        if (nonce_data.iov_len > 256)
                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                                       "Invalid RSA EK nonce length from NV index 0x%08" PRIx32, nonce_index);
 
                        template.unique.rsa.size = 256;
                        memcpy_safe(template.unique.rsa.buffer, nonce_data.iov_base, nonce_data.iov_len);
                        break;
                case TPM2_EK_TEMPLATE_ECC_NIST_P256_LEGACY:
                        /* For the ECC NIST P256 (L-2) template, set unique.ecc.x to the nonce and append
                         * zero bytes to pad it to a size of 32-bytes. Set unique.ecc.y to 32-bytes of
                         * zeroes. */
                        if (nonce_data.iov_len > 32)
                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                                       "Invalid ECC EK nonce length from NV index 0x%08" PRIx32, nonce_index);
 
                        template.unique.ecc.x.size = template.unique.ecc.y.size = 32;
                        memcpy_safe(template.unique.ecc.x.buffer, nonce_data.iov_base, nonce_data.iov_len);
                        break;
                default:
                        assert_not_reached();
                }
        }
 
        *ret_template = template;
        return 1;
}
 
/* This is the default authorization policy for low-range endorsement keys. It is:
 *
 * TPM2_PolicySecret(TPM_RH_ENDORSEMENT).
 *
 * See section 5.3 of the "TCG EK Credential Profile for TPM Family 2.0" spec. */
#define TPM2_EK_AUTH_POLICY_A                                   \
        { .size = TPM2_SHA256_DIGEST_SIZE,                      \
          .buffer = {                                           \
                0x83, 0x71, 0x97, 0x67, 0x44, 0x84, 0xB3, 0xF8, \
                0x1A, 0x90, 0xCC, 0x8D, 0x46, 0xA5, 0xD7, 0x24, \
                0xFD, 0x52, 0xD7, 0x6E, 0x06, 0x52, 0x0B, 0x64, \
                0xF2, 0xA1, 0xDA, 0x1B, 0x33, 0x14, 0x69, 0xAA, \
          },                                                    \
        }
 
/* This is the default SHA-256 authorization policy for high-range endorsement keys. High-range EKs
 * define a policy that permits the privacy administrator to delegate admin usage of the endorsement key via
 * TPM2_PolicyAuthorizeNV. There is one NV index defined per name algorithm. These and their public
 * attributes are specified in section A.1 of the "TCG EK Credential Profile for TPM Family 2.0" spec.
 *
 * This policy is:
 *
 * TPM2_PolicySecret(TPM_RH_ENDORSEMENT) OR TPM2_PolicyAuthorizeNV(0x01C07F01). */
#define TPM2_EK_AUTH_POLICY_B_SHA256                            \
        { .size = TPM2_SHA256_DIGEST_SIZE,                      \
          .buffer = {                                           \
                0xCA, 0x3D, 0x0A, 0x99, 0xA2, 0xB9, 0x39, 0x06, \
                0xF7, 0xA3, 0x34, 0x24, 0x14, 0xEF, 0xCF, 0xB3, \
                0xA3, 0x85, 0xD4, 0x4C, 0xD1, 0xFD, 0x45, 0x90, \
                0x89, 0xD1, 0x9B, 0x50, 0x71, 0xC0, 0xB7, 0xA0, \
          },                                                    \
        }
 
/* This is the default SHA-384 authorization policy for high-range endorsement keys. High-range EKs
 * define a policy that permits the privacy administrator to delegate admin usage of the endorsement key via
 * TPM2_PolicyAuthorizeNV. There is one NV index defined per name algorithm. These and their public
 * attributes are specified in section A.1 of the "TCG EK Credential Profile for TPM Family 2.0" spec.
 *
 * This policy is:
 *
 * TPM2_PolicySecret(TPM_RH_ENDORSEMENT) OR TPM2_PolicyAuthorizeNV(0x01C07F02). */
#define TPM2_EK_AUTH_POLICY_B_SHA384                            \
        { .size = TPM2_SHA384_DIGEST_SIZE,                      \
          .buffer = {                                           \
                0xB2, 0x6E, 0x7D, 0x28, 0xD1, 0x1A, 0x50, 0xBC, \
                0x53, 0xD8, 0x82, 0xBC, 0xF5, 0xFD, 0x3A, 0x1A, \
                0x07, 0x41, 0x48, 0xBB, 0x35, 0xD3, 0xB4, 0xE4, \
                0xCB, 0x1C, 0x0A, 0xD9, 0xBD, 0xE4, 0x19, 0xCA, \
                0xCB, 0x47, 0xBA, 0x09, 0x69, 0x96, 0x46, 0x15, \
                0x0F, 0x9F, 0xC0, 0x00, 0xF3, 0xF8, 0x0E, 0x12  \
          },                                                    \
        }
 
/* Get the default Endorsement Key (EK) template for the specified EK profile.
 *
 * EK template values are defined in the "TCG EK Credential Profile for TPM Family 2.0" spec in sections
 * 5.3 (low-range) and 5.4 (high-range). There are multiple templates for both RSA and ECC keys, with varying
 * key sizes or curves. The high-range also defines templates for storage and signing keys, although we only
 * support storage EKs. There are templates for PQC algorithms, although these aren't supported here yet. The
 * supported templates are the storage RSA and ECC templates required by the "TCG PC Client Platform TPM
 * Profile (PTP)" spec.
 *
 * https://trustedcomputinggroup.org/resource/http-trustedcomputinggroup-org-wp-content-uploads-tcg-ek-credential-profile
 * https://trustedcomputinggroup.org/resource/pc-client-platform-tpm-profile-ptp-specification/ */
void tpm2_get_default_ek_template(Tpm2EKTemplateProfile profile, TPMT_PUBLIC *ret_template) {
        assert(profile >= 0);
        assert(profile < _TPM2_EK_TEMPLATE_MAX);
        assert(ret_template);
 
        static const TPMA_OBJECT attributes_a =
                TPMA_OBJECT_FIXEDTPM |
                TPMA_OBJECT_FIXEDPARENT |
                TPMA_OBJECT_SENSITIVEDATAORIGIN |
                TPMA_OBJECT_ADMINWITHPOLICY |
                TPMA_OBJECT_RESTRICTED |
                TPMA_OBJECT_DECRYPT;
 
        static const TPMA_OBJECT attributes_b = attributes_a | TPMA_OBJECT_USERWITHAUTH;
 
        static const struct {
                TPMI_ALG_PUBLIC alg;
                TPMI_ALG_HASH name_alg;
                TPMA_OBJECT attrs;
                TPM2B_DIGEST auth_policy;
                union {
                        TPMI_RSA_KEY_BITS rsa_key_bits;
                        TPMI_ECC_CURVE ecc_curve_id;
                } asym;
                TPMU_PUBLIC_ID unique;
                TPMI_AES_KEY_BITS sym_key_bits;
        } template_params[_TPM2_EK_TEMPLATE_MAX] = {
                [TPM2_EK_TEMPLATE_RSA_2048_LEGACY] = {
                        .alg = TPM2_ALG_RSA,
                        .name_alg = TPM2_ALG_SHA256,
                        .attrs = attributes_a,
                        .auth_policy = TPM2_EK_AUTH_POLICY_A,
                        .asym.rsa_key_bits = 2048,
                        .unique.rsa.size = 256,
                        .sym_key_bits = 128,
                },
                [TPM2_EK_TEMPLATE_ECC_NIST_P256_LEGACY] = {
                        .alg = TPM2_ALG_ECC,
                        .name_alg = TPM2_ALG_SHA256,
                        .attrs = attributes_a,
                        .auth_policy = TPM2_EK_AUTH_POLICY_A,
                        .asym.ecc_curve_id = TPM2_ECC_NIST_P256,
                        .unique.ecc.x.size = 32,
                        .unique.ecc.y.size = 32,
                        .sym_key_bits = 128,
                },
                [TPM2_EK_TEMPLATE_RSA_2048] = {
                        .alg = TPM2_ALG_RSA,
                        .name_alg = TPM2_ALG_SHA256,
                        .attrs = attributes_b,
                        .auth_policy = TPM2_EK_AUTH_POLICY_B_SHA256,
                        .asym.rsa_key_bits = 2048,
                        .unique.rsa.size = 0,
                        .sym_key_bits = 128,
                },
                [TPM2_EK_TEMPLATE_ECC_NIST_P256] = {
                        .alg = TPM2_ALG_ECC,
                        .name_alg = TPM2_ALG_SHA256,
                        .attrs = attributes_b,
                        .auth_policy = TPM2_EK_AUTH_POLICY_B_SHA256,
                        .asym.ecc_curve_id = TPM2_ECC_NIST_P256,
                        .unique.ecc.x.size = 0,
                        .unique.ecc.y.size = 0,
                        .sym_key_bits = 128,
                },
                [TPM2_EK_TEMPLATE_ECC_NIST_P384] = {
                        .alg = TPM2_ALG_ECC,
                        .name_alg = TPM2_ALG_SHA384,
                        .attrs = attributes_b,
                        .auth_policy = TPM2_EK_AUTH_POLICY_B_SHA384,
                        .asym.ecc_curve_id = TPM2_ECC_NIST_P384,
                        .unique.ecc.x.size = 0,
                        .unique.ecc.y.size = 0,
                        .sym_key_bits = 256,
                },
                [TPM2_EK_TEMPLATE_RSA_3072] = {
                        .alg = TPM2_ALG_RSA,
                        .name_alg = TPM2_ALG_SHA384,
                        .attrs = attributes_b,
                        .auth_policy = TPM2_EK_AUTH_POLICY_B_SHA384,
                        .asym.rsa_key_bits = 3072,
                        .unique.rsa.size = 0,
                        .sym_key_bits = 256,
                },
        };
 
        const typeof(template_params[0]) *params = &template_params[profile];
 
        TPMT_PUBLIC template = {
                .type = params->alg,
                .nameAlg = params->name_alg,
                .objectAttributes = params->attrs,
                .authPolicy = params->auth_policy,
                .parameters.asymDetail = (TPMS_ASYM_PARMS){
                        .symmetric = (TPMT_SYM_DEF_OBJECT){
                                .algorithm = TPM2_ALG_AES,
                                .keyBits.aes = params->sym_key_bits,
                                .mode.aes = TPM2_ALG_CFB,
                        },
                        .scheme.scheme = TPM2_ALG_NULL,
                },
                .unique = params->unique,
        };
 
        switch (template.type) {
        case TPM2_ALG_RSA:
                template.parameters.rsaDetail.keyBits = params->asym.rsa_key_bits;
                break;
        case TPM2_ALG_ECC:
                template.parameters.eccDetail.curveID = params->asym.ecc_curve_id;
                template.parameters.eccDetail.kdf.scheme = TPM2_ALG_NULL;
                break;
        default:
                assert_not_reached();
        }
 
        *ret_template = template;
}
 
/* Get the Endorsement Key (EK) template for the specified EK profile.
 *
 * EK template values are defined in the "TCG EK Credential Profile for TPM Family 2.0" spec in sections
 * 5.3 (low-range) and 5.4 (high-range). There are multiple templates for both RSA and ECC keys, with varying
 * key sizes or curves. The high-range also defines templates for storage and signing keys, although we only
 * support storage EKs. There are templates for PQC algorithms, although these aren't supported here yet. The
 * supported templates are the storage RSA and ECC templates required by the "TCG PC Client Platform TPM
 * Profile (PTP)" spec.
 *
 * This will return a custom template for the specified profile if one is defined, else it will return the
 * default template. Returns 0 on success, or < 0 if an error occurred.
 *
 * https://trustedcomputinggroup.org/resource/http-trustedcomputinggroup-org-wp-content-uploads-tcg-ek-credential-profile
 * https://trustedcomputinggroup.org/resource/pc-client-platform-tpm-profile-ptp-specification/ */
int tpm2_get_ek_template(
                Tpm2Context *c,
                const Tpm2Handle *session,
                Tpm2EKTemplateProfile profile,
                TPMT_PUBLIC *ret_template) {
 
        int r;
 
        r = tpm2_get_custom_ek_template(c, session, profile, ret_template);
        if (r < 0)
                return r;
        if (r == 0)
                tpm2_get_default_ek_template(profile, ret_template);
 
        return 0;
}
 
/* Get the EK. Returns 1 if found, 0 if there is no EK, or < 0 on error. Also see
 * tpm2_get_or_create_ek() below. */
int tpm2_get_ek(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPM2B_PUBLIC **ret_public,
                TPM2B_NAME **ret_name,
                TPM2B_NAME **ret_qname,
                Tpm2Handle **ret_handle) {
 
        return tpm2_object_index_to_handle(c, TPM2_EK_HANDLE, session, ret_public, ret_name, ret_qname, ret_handle);
}
 
/* Get the EK, creating one if needed. This tries each of the supported templates in order of preference,
 * and will persist and return an EK created with the first template that has an EK certificate, and where
 * the created EK matches the certificate's public key.
 *
 * Returns 1 if a new EK was created and persisted, 0 if an EK already exists, or < 0 on error. */
int tpm2_get_or_create_ek(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPM2B_PUBLIC **ret_public,
                TPM2B_NAME **ret_name,
                TPM2B_NAME **ret_qname,
                Tpm2Handle **ret_handle) {
 
#if HAVE_OPENSSL
        int r;
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        r = tpm2_get_ek(c, session, ret_public, ret_name, ret_qname, ret_handle);
        if (r < 0)
                return r;
        if (r == 1)
                return 0; /* 0 → EK already set up */
 
        /* No EK, create and persist one */
        static const Tpm2EKTemplateProfile profile_preferences[] = {
                TPM2_EK_TEMPLATE_ECC_NIST_P384,
                TPM2_EK_TEMPLATE_ECC_NIST_P256,
                TPM2_EK_TEMPLATE_RSA_3072,
                TPM2_EK_TEMPLATE_RSA_2048,
                TPM2_EK_TEMPLATE_ECC_NIST_P256_LEGACY,
                TPM2_EK_TEMPLATE_RSA_2048_LEGACY,
        };
 
        FOREACH_ELEMENT(p, profile_preferences) {
                Tpm2EKTemplateProfile profile = *p;
 
                log_debug("Trying to create EK with template '%s'", ek_template_names[profile]);
 
                /* Check if there is a certificate for this profile. */
                _cleanup_(X509_freep) X509 *cert = NULL;
                r = tpm2_read_ek_cert(c, session, profile, &cert);
                if (r == -EBADMSG)
                        continue; /* Certificate populated but invalid. */
                if (r < 0)
                        return r;
                if (r == 0)
                        continue; /* No certificate populated. */
 
                EVP_PKEY *cert_pkey = sym_X509_get0_pubkey(cert);
                if (!cert_pkey) {
                        log_debug("Skipping EK creation with template '%s': cannot get EKcert public key", ek_template_names[profile]);
                        continue;
                }
 
                /* Obtain the template for this profile. */
                TPM2B_PUBLIC template = {
                        .size = sizeof(TPMT_PUBLIC),
                };
                r = tpm2_get_ek_template(c, session, profile, &template.publicArea);
                if (r == -EBADMSG)
                        continue; /* Custom template or nonce is invalid. */
                if (r < 0)
                        return r;
 
                /* Check that this profile is supported. */
                if (!tpm2_supports_alg(c, template.publicArea.type)) {
                        log_debug("Skipping EK creation with template '%s': unsupported object type", ek_template_names[profile]);
                        continue;
                }
                if (!tpm2_supports_tpmt_public(c, &template.publicArea)) {
                        log_debug("Skipping EK creation with template '%s': unsupported template", ek_template_names[profile]);
                        continue;
                }
                if (template.publicArea.type == TPM2_ALG_ECC && !tpm2_supports_ecc_curve(c, template.publicArea.parameters.eccDetail.curveID)) {
                        log_debug("Skipping EK creation with template '%s': unsupported curve", ek_template_names[profile]);
                        continue;
                }
 
                /* Create the transient EK now. */
                _cleanup_(tpm2_handle_freep) Tpm2Handle *transient_handle = NULL;
                r = tpm2_create_primary(
                                c,
                                session,
                                ESYS_TR_RH_ENDORSEMENT,
                                &template,
                                /* sensitive= */ NULL,
                                /* ret_public= */ NULL,
                                &transient_handle);
                if (r < 0)
                        return r;
 
                _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
                r = tpm2_read_public(c, session, transient_handle, &public, /* ret_name= */ NULL, /* ret_qname= */ NULL);
                if (r < 0)
                        return r;
 
                /* Check that the created EK has a public key that matches the one in the certificate. */
                _cleanup_(EVP_PKEY_freep) EVP_PKEY *tpm_pkey = NULL;
                r = tpm2_tpm2b_public_to_openssl_pkey(public, &tpm_pkey);
                if (r < 0)
                        return r;
 
                if (sym_EVP_PKEY_eq(tpm_pkey, cert_pkey) != 1) {
                        log_debug("EK created with template '%s' does not match EKcert public key", ek_template_names[profile]);
                        continue;
                }
 
                /* We've created a valid EK that is consistent with the supplied certificate, so persist this
                 * one and return it. */
                r = tpm2_persist_handle(c, transient_handle, session, TPM2_EK_HANDLE, /* ret_persistent_handle= */ NULL);
                if (r < 0)
                        return r;
 
                r = tpm2_get_ek(c, session, ret_public, ret_name, ret_qname, ret_handle);
                if (r < 0)
                        return r;
                if (r == 0)
                        /* This should never happen. */
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "EK we just persisted couldn't be found.");
 
                return 1; /* > 0 → EK newly set up */
        }
 
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                               "No usable EK certificate found for any supported template.");
#else
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
/* Opens a policy session for the EK associated with the supplied handle and executes the
 * TPM2_PolicySecret(TPM_RH_ENDORSEMENT) branch, leaving the session ready to use for the user auth role.
 *
 * This isn't very flexible - it doesn't support delegated policies and assumes that the endorsement
 * hierarchy auth is empty (or at least known by the caller). If the object has the userWithAuth attribute
 * set, it doesn't create a policy session, which assumes that the object's auth value is empty. The EK
 * template is designed in such a way that the use of the key can be locked down via a delegated policy by
 * setting the endorsement hierarchy auth and setting the persistent EKauth to a random value. In the future,
 * if we adopt the JSON policy language which will make it nicer to execute arbitrary policies, we might
 * want to support these use cases via systemd-tpm2-setup.
 *
 * Returns 1 if a policy session was opened, 0 if the object at the supplied handle doesn't need a policy for
 * the user auth role (in which case, no policy session is returned), or < 0 on error. */
int tpm2_open_ek_user_policy_session(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const Tpm2Handle *ek_handle,
                const Tpm2Handle *tpm_key,
                Tpm2Handle **ret_session) {
        int r;
 
        assert(c);
        assert(ek_handle);
 
        _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
        r = tpm2_read_public(c, /* session= */ NULL, ek_handle, &public, /* ret_name= */ NULL, /* ret_qname= */ NULL);
        if (r < 0)
                return r;
 
        if ((public->publicArea.objectAttributes & TPMA_OBJECT_USERWITHAUTH) != 0) {
                /* Prefer HMAC or passphrase auth for this object. This catches
                 * the case where ek_handle is actually the SRK, and also all
                 * high-range EKs. */
                if (ret_session)
                        *ret_session = NULL;
                return 0;
        }
 
        /* We need a policy session. The only EKs we require this for today are low-range ones. */
        if (public->publicArea.nameAlg != TPM2_ALG_SHA256)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to open EK user policy session: unsupported name algorithm");
 
        TPM2B_DIGEST expected_policy = TPM2_EK_AUTH_POLICY_A;
        if (memcmp_nn(expected_policy.buffer, expected_policy.size,
                      public->publicArea.authPolicy.buffer, public->publicArea.authPolicy.size) != 0)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to open EK user policy session: unrecognized policy digest");
 
        /* Note that tpm2_make_policy_session is currently hardcoded to SHA256. That's ok for now because
         * we only get this far if the supplied ek_handle has a name algorithm of SHA256. */
        _cleanup_(tpm2_handle_freep) Tpm2Handle *policy_session = NULL;
        r = tpm2_make_policy_session(c, tpm_key, /* encryption_session= */ NULL, &policy_session);
        if (r < 0)
                return r;
 
        r = tpm2_policy_secret(c, session, policy_session, &TPM2_HANDLE_RH_ENDORSEMENT, /* policy_ref= */ NULL, /* ret_policy_digest= */ NULL);
        if (r < 0)
                return r;
 
        if (ret_session)
                *ret_session = TAKE_PTR(policy_session);
 
        return 1;
}
 
/* Utility functions for TPMS_PCR_SELECTION. */
 
/* Convert a TPMS_PCR_SELECTION object to a mask. */
uint32_t tpm2_tpms_pcr_selection_to_mask(const TPMS_PCR_SELECTION *s) {
        assert(s);
        assert(s->sizeofSelect <= sizeof(s->pcrSelect));
 
        uint32_t mask = 0;
        for (unsigned i = 0; i < s->sizeofSelect; i++)
                SET_FLAG(mask, (uint32_t)s->pcrSelect[i] << (i * 8), true);
        return mask;
}
 
/* Convert a mask and hash alg to a TPMS_PCR_SELECTION object. */
void tpm2_tpms_pcr_selection_from_mask(uint32_t mask, TPMI_ALG_HASH hash_alg, TPMS_PCR_SELECTION *ret) {
        assert(ret);
 
        /* This is currently hardcoded at 24 PCRs, above. */
        if (!TPM2_PCR_MASK_VALID(mask))
                log_debug("PCR mask selections (%x) out of range, ignoring.",
                          mask & ~((uint32_t)TPM2_PCRS_MASK));
 
        *ret = (TPMS_PCR_SELECTION){
                .hash = hash_alg,
                .sizeofSelect = TPM2_PCRS_MAX / 8,
                .pcrSelect[0] = mask & 0xff,
                .pcrSelect[1] = (mask >> 8) & 0xff,
                .pcrSelect[2] = (mask >> 16) & 0xff,
        };
}
 
/* Test if all bits in the mask are set in the TPMS_PCR_SELECTION. */
bool tpm2_tpms_pcr_selection_has_mask(const TPMS_PCR_SELECTION *s, uint32_t mask) {
        assert(s);
 
        return FLAGS_SET(tpm2_tpms_pcr_selection_to_mask(s), mask);
}
 
static void tpm2_tpms_pcr_selection_update_mask(TPMS_PCR_SELECTION *s, uint32_t mask, bool b) {
        assert(s);
 
        tpm2_tpms_pcr_selection_from_mask(UPDATE_FLAG(tpm2_tpms_pcr_selection_to_mask(s), mask, b), s->hash, s);
}
 
/* Add all PCR selections in the mask. */
void tpm2_tpms_pcr_selection_add_mask(TPMS_PCR_SELECTION *s, uint32_t mask) {
        tpm2_tpms_pcr_selection_update_mask(s, mask, 1);
}
 
/* Remove all PCR selections in the mask. */
void tpm2_tpms_pcr_selection_sub_mask(TPMS_PCR_SELECTION *s, uint32_t mask) {
        tpm2_tpms_pcr_selection_update_mask(s, mask, 0);
}
 
/* Add all PCR selections in 'b' to 'a'. Both must have the same hash alg. */
void tpm2_tpms_pcr_selection_add(TPMS_PCR_SELECTION *a, const TPMS_PCR_SELECTION *b) {
        assert(a);
        assert(b);
        assert(a->hash == b->hash);
 
        tpm2_tpms_pcr_selection_add_mask(a, tpm2_tpms_pcr_selection_to_mask(b));
}
 
/* Remove all PCR selections in 'b' from 'a'. Both must have the same hash alg. */
void tpm2_tpms_pcr_selection_sub(TPMS_PCR_SELECTION *a, const TPMS_PCR_SELECTION *b) {
        assert(a);
        assert(b);
        assert(a->hash == b->hash);
 
        tpm2_tpms_pcr_selection_sub_mask(a, tpm2_tpms_pcr_selection_to_mask(b));
}
 
/* Move all PCR selections in 'b' to 'a'. Both must have the same hash alg. */
void tpm2_tpms_pcr_selection_move(TPMS_PCR_SELECTION *a, TPMS_PCR_SELECTION *b) {
        if (a == b)
                return;
 
        tpm2_tpms_pcr_selection_add(a, b);
        tpm2_tpms_pcr_selection_from_mask(0, b->hash, b);
}
 
#define FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(tpms, tpml)    \
        _FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(tpms, tpml, UNIQ_T(l, UNIQ))
#define _FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(tpms, tpml, l) \
        for (typeof(tpml) (l) = (tpml); (l); (l) = NULL)                \
                FOREACH_ARRAY(tpms, (l)->pcrSelections, (l)->count)
 
#define FOREACH_PCR_IN_TPMS_PCR_SELECTION(pcr, tpms)                    \
        FOREACH_PCR_IN_MASK(pcr, tpm2_tpms_pcr_selection_to_mask(tpms))
 
#define FOREACH_PCR_IN_TPML_PCR_SELECTION(pcr, tpms, tpml)              \
        FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(tpms, tpml)    \
                FOREACH_PCR_IN_TPMS_PCR_SELECTION(pcr, tpms)
 
char* tpm2_tpms_pcr_selection_to_string(const TPMS_PCR_SELECTION *s) {
        assert(s);
 
        const char *algstr = strna(tpm2_hash_alg_to_string(s->hash));
 
        _cleanup_free_ char *mask = tpm2_pcr_mask_to_string(tpm2_tpms_pcr_selection_to_mask(s));
        if (!mask)
                return NULL;
 
        return strjoin(algstr, "(", mask, ")");
}
 
size_t tpm2_tpms_pcr_selection_weight(const TPMS_PCR_SELECTION *s) {
        assert(s);
 
        return popcount(tpm2_tpms_pcr_selection_to_mask(s));
}
 
/* Utility functions for TPML_PCR_SELECTION. */
 
/* Remove the (0-based) index entry from 'l', shift all following entries, and update the count. */
static void tpm2_tpml_pcr_selection_remove_index(TPML_PCR_SELECTION *l, uint32_t index) {
        assert(l);
        assert(l->count <= ELEMENTSOF(l->pcrSelections));
        assert(index < l->count);
 
        size_t s = l->count - (index + 1);
        memmove(&l->pcrSelections[index], &l->pcrSelections[index + 1], s * sizeof(l->pcrSelections[0]));
        l->count--;
}
 
/* Get a TPMS_PCR_SELECTION from a TPML_PCR_SELECTION for the given hash alg. Returns NULL if there is no
 * entry for the hash alg. This guarantees the returned entry contains all the PCR selections for the given
 * hash alg, which may require modifying the TPML_PCR_SELECTION by removing duplicate entries. */
static TPMS_PCR_SELECTION *tpm2_tpml_pcr_selection_get_tpms_pcr_selection(
                TPML_PCR_SELECTION *l,
                TPMI_ALG_HASH hash_alg) {
 
        assert(l);
        assert(l->count <= ELEMENTSOF(l->pcrSelections));
 
        TPMS_PCR_SELECTION *selection = NULL;
        FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(s, l)
                if (s->hash == hash_alg) {
                        selection = s;
                        break;
                }
 
        if (!selection)
                return NULL;
 
        /* Iterate backwards through the entries, removing any other entries for the hash alg. */
        for (uint32_t i = l->count - 1; i > 0; i--) {
                TPMS_PCR_SELECTION *s = &l->pcrSelections[i];
 
                if (selection == s)
                        break;
 
                if (s->hash == hash_alg) {
                        tpm2_tpms_pcr_selection_move(selection, s);
                        tpm2_tpml_pcr_selection_remove_index(l, i);
                }
        }
 
        return selection;
}
 
/* Combine all duplicate (same hash alg) TPMS_PCR_SELECTION entries in 'l'. */
static void tpm2_tpml_pcr_selection_cleanup(TPML_PCR_SELECTION *l) {
        /* Can't use FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION() because we might modify l->count */
        for (uint32_t i = 0; i < l->count; i++)
                /* This removes all duplicate TPMS_PCR_SELECTION entries for this hash. */
                (void) tpm2_tpml_pcr_selection_get_tpms_pcr_selection(l, l->pcrSelections[i].hash);
}
 
/* Convert a TPML_PCR_SELECTION object to a mask. Returns empty mask (i.e. 0) if 'hash_alg' is not in the object. */
uint32_t tpm2_tpml_pcr_selection_to_mask(const TPML_PCR_SELECTION *l, TPMI_ALG_HASH hash_alg) {
        assert(l);
 
        /* Make a copy, as tpm2_tpml_pcr_selection_get_tpms_pcr_selection() will modify the object if there
         * are multiple entries with the requested hash alg. */
        TPML_PCR_SELECTION lcopy = *l;
 
        TPMS_PCR_SELECTION *s;
        s = tpm2_tpml_pcr_selection_get_tpms_pcr_selection(&lcopy, hash_alg);
        if (!s)
                return 0;
 
        return tpm2_tpms_pcr_selection_to_mask(s);
}
 
/* Convert a mask and hash alg to a TPML_PCR_SELECTION object. */
void tpm2_tpml_pcr_selection_from_mask(uint32_t mask, TPMI_ALG_HASH hash_alg, TPML_PCR_SELECTION *ret) {
        assert(ret);
 
        TPMS_PCR_SELECTION s;
        tpm2_tpms_pcr_selection_from_mask(mask, hash_alg, &s);
 
        *ret = (TPML_PCR_SELECTION){
                .count = 1,
                .pcrSelections[0] = s,
        };
}
 
/* Add the PCR selections in 's' to the corresponding hash alg TPMS_PCR_SELECTION entry in 'l'. Adds a new
 * TPMS_PCR_SELECTION entry for the hash alg if needed. This may modify the TPML_PCR_SELECTION by combining
 * entries with the same hash alg. */
void tpm2_tpml_pcr_selection_add_tpms_pcr_selection(TPML_PCR_SELECTION *l, const TPMS_PCR_SELECTION *s) {
        assert(l);
        assert(s);
 
        if (tpm2_tpms_pcr_selection_is_empty(s))
                return;
 
        TPMS_PCR_SELECTION *selection = tpm2_tpml_pcr_selection_get_tpms_pcr_selection(l, s->hash);
        if (selection) {
                tpm2_tpms_pcr_selection_add(selection, s);
                return;
        }
 
        /* It's already broken if the count is higher than the array has size for. */
        assert(l->count <= ELEMENTSOF(l->pcrSelections));
 
        /* If full, the cleanup should result in at least one available entry. */
        if (l->count == ELEMENTSOF(l->pcrSelections))
                tpm2_tpml_pcr_selection_cleanup(l);
 
        assert(l->count < ELEMENTSOF(l->pcrSelections));
        l->pcrSelections[l->count++] = *s;
}
 
/* Remove the PCR selections in 's' from the corresponding hash alg TPMS_PCR_SELECTION entry in 'l'. This
 * will combine all entries for 's->hash' in 'l'. */
void tpm2_tpml_pcr_selection_sub_tpms_pcr_selection(TPML_PCR_SELECTION *l, const TPMS_PCR_SELECTION *s) {
        assert(l);
        assert(s);
 
        if (tpm2_tpms_pcr_selection_is_empty(s))
                return;
 
        TPMS_PCR_SELECTION *selection = tpm2_tpml_pcr_selection_get_tpms_pcr_selection(l, s->hash);
        if (selection)
                tpm2_tpms_pcr_selection_sub(selection, s);
}
 
/* Test if all bits in the mask for the hash are set in the TPML_PCR_SELECTION. */
bool tpm2_tpml_pcr_selection_has_mask(const TPML_PCR_SELECTION *l, TPMI_ALG_HASH hash, uint32_t mask) {
        assert(l);
 
        return FLAGS_SET(tpm2_tpml_pcr_selection_to_mask(l, hash), mask);
}
 
/* Add the PCR selections in the mask, with the provided hash. */
void tpm2_tpml_pcr_selection_add_mask(TPML_PCR_SELECTION *l, TPMI_ALG_HASH hash, uint32_t mask) {
        TPMS_PCR_SELECTION tpms;
 
        assert(l);
 
        tpm2_tpms_pcr_selection_from_mask(mask, hash, &tpms);
        tpm2_tpml_pcr_selection_add_tpms_pcr_selection(l, &tpms);
}
 
/* Add all PCR selections in 'b' to 'a'. */
void tpm2_tpml_pcr_selection_add(TPML_PCR_SELECTION *a, const TPML_PCR_SELECTION *b) {
        assert(a);
        assert(b);
 
        FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(selection_b, b)
                tpm2_tpml_pcr_selection_add_tpms_pcr_selection(a, selection_b);
}
 
/* Remove all PCR selections in 'b' from 'a'. */
void tpm2_tpml_pcr_selection_sub(TPML_PCR_SELECTION *a, const TPML_PCR_SELECTION *b) {
        assert(a);
        assert(b);
 
        FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(selection_b, b)
                tpm2_tpml_pcr_selection_sub_tpms_pcr_selection(a, selection_b);
}
 
char* tpm2_tpml_pcr_selection_to_string(const TPML_PCR_SELECTION *l) {
        assert(l);
 
        _cleanup_free_ char *banks = NULL;
        FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(s, l) {
                if (tpm2_tpms_pcr_selection_is_empty(s))
                        continue;
 
                _cleanup_free_ char *str = tpm2_tpms_pcr_selection_to_string(s);
                if (!str || !strextend_with_separator(&banks, ",", str))