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 3001–4000 of 12,273

                        return NULL;
        }
 
        return strjoin("[", strempty(banks), "]");
}
 
size_t tpm2_tpml_pcr_selection_weight(const TPML_PCR_SELECTION *l) {
        assert(l);
        assert(l->count <= ELEMENTSOF(l->pcrSelections));
 
        size_t weight = 0;
        FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(s, l) {
                size_t w = tpm2_tpms_pcr_selection_weight(s);
                assert(weight <= SIZE_MAX - w);
                weight += w;
        }
 
        return weight;
}
 
bool tpm2_pcr_value_valid(const Tpm2PCRValue *pcr_value) {
        int r;
 
        if (!pcr_value)
                return false;
 
        if (!TPM2_PCR_INDEX_VALID(pcr_value->index)) {
                log_debug("PCR index %u invalid.", pcr_value->index);
                return false;
        }
 
        /* If it contains a value, the value size must match the hash size. */
        if (pcr_value->value.size > 0) {
                r = tpm2_hash_alg_to_size(pcr_value->hash);
                if (r < 0)
                        return false;
 
                if (pcr_value->value.size != (size_t) r) {
                        log_debug("PCR hash 0x%" PRIx16 " expected size %d does not match actual size %" PRIu16 ".",
                                  pcr_value->hash, r, pcr_value->value.size);
                        return false;
                }
        }
 
        return true;
}
 
/* Verify all entries are valid, and consistent with each other. The requirements for consistency are:
 *
 * 1) all entries must be sorted in ascending order (e.g. using tpm2_sort_pcr_values())
 * 2) all entries must be unique, i.e. there cannot be 2 entries with the same hash and index
 *
 * Returns true if all entries are valid (or if no entries are provided), false otherwise.
 */
bool tpm2_pcr_values_valid(const Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
        if (!pcr_values && n_pcr_values > 0)
                return false;
 
        const Tpm2PCRValue *previous = NULL;
        FOREACH_ARRAY(current, pcr_values, n_pcr_values) {
                if (!tpm2_pcr_value_valid(current))
                        return false;
 
                if (!previous) {
                        previous = current;
                        continue;
                }
 
                /* Hashes must be sorted in ascending order */
                if (current->hash < previous->hash) {
                        log_debug("PCR values not in ascending order, hash %" PRIu16 " is after %" PRIu16 ".",
                                  current->hash, previous->hash);
                        return false;
                }
 
                if (current->hash == previous->hash) {
                        /* Indexes (for the same hash) must be sorted in ascending order */
                        if (current->index < previous->index) {
                                log_debug("PCR values not in ascending order, hash %" PRIu16 " index %u is after %u.",
                                          current->hash, current->index, previous->index);
                                return false;
                        }
 
                        /* Indexes (for the same hash) must not be duplicates */
                        if (current->index == previous->index) {
                                log_debug("PCR values contain duplicates for hash %" PRIu16 " index %u.",
                                          current->hash, previous->index);
                                return false;
                        }
                }
        }
 
        return true;
}
 
/* Returns true if any of the provided PCR values has an actual hash value included, false otherwise. */
bool tpm2_pcr_values_has_any_values(const Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
        assert(pcr_values || n_pcr_values == 0);
 
        FOREACH_ARRAY(v, pcr_values, n_pcr_values)
                if (v->value.size > 0)
                        return true;
 
        return false;
}
 
/* Returns true if all of the provided PCR values has an actual hash value included, false otherwise. */
bool tpm2_pcr_values_has_all_values(const Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
        assert(pcr_values || n_pcr_values == 0);
 
        FOREACH_ARRAY(v, pcr_values, n_pcr_values)
                if (v->value.size == 0)
                        return false;
 
        return true;
}
 
static int cmp_pcr_values(const Tpm2PCRValue *a, const Tpm2PCRValue *b) {
        assert(a);
        assert(b);
 
        return CMP(a->hash, b->hash) ?: CMP(a->index, b->index);
}
 
/* Sort the array of Tpm2PCRValue entries in-place. This sorts first in ascending order of hash algorithm
 * (sorting simply by the TPM2 hash algorithm number), and then sorting by pcr index. */
void tpm2_sort_pcr_values(Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
        typesafe_qsort(pcr_values, n_pcr_values, cmp_pcr_values);
}
 
int tpm2_pcr_values_to_mask(
                const Tpm2PCRValue *pcr_values,
                size_t n_pcr_values,
                TPMI_ALG_HASH hash,
                uint32_t *ret_mask) {
 
        assert(pcr_values || n_pcr_values == 0);
        assert(ret_mask);
 
        if (!tpm2_pcr_values_valid(pcr_values, n_pcr_values))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PCR values.");
 
        uint32_t mask = 0;
        FOREACH_ARRAY(v, pcr_values, n_pcr_values)
                if (hash == 0 || v->hash == hash)
                        SET_BIT(mask, v->index);
 
        *ret_mask = mask;
        return 0;
}
 
int tpm2_tpml_pcr_selection_from_pcr_values(
                const Tpm2PCRValue *pcr_values,
                size_t n_pcr_values,
                TPML_PCR_SELECTION *ret_selection,
                TPM2B_DIGEST **ret_values,
                size_t *ret_n_values) {
 
        TPML_PCR_SELECTION selection = {};
        _cleanup_free_ TPM2B_DIGEST *values = NULL;
        size_t n_values = 0;
 
        assert(pcr_values || n_pcr_values == 0);
 
        if (!tpm2_pcr_values_valid(pcr_values, n_pcr_values))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "PCR values are not valid.");
 
        FOREACH_ARRAY(v, pcr_values, n_pcr_values) {
                tpm2_tpml_pcr_selection_add_mask(&selection, v->hash, INDEX_TO_MASK(uint32_t, v->index));
 
                if (!GREEDY_REALLOC_APPEND(values, n_values, &v->value, 1))
                        return log_oom_debug();
        }
 
        if (ret_selection)
                *ret_selection = selection;
        if (ret_values)
                *ret_values = TAKE_PTR(values);
        if (ret_n_values)
                *ret_n_values = n_values;
 
        return 0;
}
 
/* Count the number of different hash algorithms for all the entries. */
int tpm2_pcr_values_hash_count(const Tpm2PCRValue *pcr_values, size_t n_pcr_values, size_t *ret_count) {
        TPML_PCR_SELECTION selection;
        int r;
 
        assert(pcr_values);
        assert(ret_count);
 
        r = tpm2_tpml_pcr_selection_from_pcr_values(
                        pcr_values,
                        n_pcr_values,
                        &selection,
                        /* ret_values= */ NULL,
                        /* ret_n_values= */ NULL);
        if (r < 0)
                return r;
 
        *ret_count = selection.count;
 
        return 0;
}
 
/* Parse a string argument into a Tpm2PCRValue object.
 *
 * The format is <index>[:hash[=value]] where index is the index number (or name) of the PCR, e.g. 0 (or
 * platform-code), hash is the name of the hash algorithm (e.g. sha256) and value is the hex hash digest
 * value, optionally with a leading 0x. This does not check for validity of the fields. */
int tpm2_pcr_value_from_string(const char *arg, Tpm2PCRValue *ret_pcr_value) {
        Tpm2PCRValue pcr_value = {};
        const char *p = arg;
        int r;
 
        assert(arg);
        assert(ret_pcr_value);
 
        _cleanup_free_ char *index = NULL;
        r = extract_first_word(&p, &index, ":", /* flags= */ 0);
        if (r < 1)
                return log_debug_errno(r, "Could not parse pcr value '%s': %m", p);
 
        r = tpm2_pcr_index_from_string(index);
        if (r < 0)
                return log_debug_errno(r, "Invalid pcr index '%s': %m", index);
        pcr_value.index = (unsigned) r;
 
        if (!isempty(p)) {
                _cleanup_free_ char *hash = NULL;
                r = extract_first_word(&p, &hash, "=", /* flags= */ 0);
                if (r < 1)
                        return log_debug_errno(r, "Could not parse pcr hash algorithm '%s': %m", p);
 
                r = tpm2_hash_alg_from_string(hash);
                if (r < 0)
                        return log_debug_errno(r, "Invalid pcr hash algorithm '%s': %m", hash);
                pcr_value.hash = (TPMI_ALG_HASH) r;
 
                if (!isempty(p)) {
                        /* Remove leading 0x if present */
                        p = startswith_no_case(p, "0x") ?: p;
 
                        _cleanup_free_ void *buf = NULL;
                        size_t buf_size = 0;
                        r = unhexmem(p, &buf, &buf_size);
                        if (r < 0)
                                return log_debug_errno(r, "Invalid pcr hash value '%s': %m", p);
 
                        r = TPM2B_DIGEST_CHECK_SIZE(buf_size);
                        if (r < 0)
                                return log_debug_errno(r, "PCR hash value size %zu too large.", buf_size);
 
                        pcr_value.value = TPM2B_DIGEST_MAKE(buf, buf_size);
                }
        }
 
        *ret_pcr_value = pcr_value;
 
        return 0;
}
 
/* Return a string for the PCR value. The format is described in tpm2_pcr_value_from_string(). Note that if
 * the hash algorithm is not recognized, neither hash name nor hash digest value is included in the
 * string. This does not check for validity. */
char* tpm2_pcr_value_to_string(const Tpm2PCRValue *pcr_value) {
        _cleanup_free_ char *index = NULL, *value = NULL;
 
        if (asprintf(&index, "%u", pcr_value->index) < 0)
                return NULL;
 
        const char *hash = pcr_value->hash > 0 ? tpm2_hash_alg_to_string(pcr_value->hash) : NULL;
 
        if (hash && pcr_value->value.size > 0) {
                value = hexmem(pcr_value->value.buffer, pcr_value->value.size);
                if (!value)
                        return NULL;
        }
 
        return strjoin(index, hash ? ":" : "", strempty(hash), value ? "=" : "", strempty(value));
}
 
/* Parse a string argument into an array of Tpm2PCRValue objects.
 *
 * The format is zero or more entries separated by ',' or '+'. The format of each entry is described in
 * tpm2_pcr_value_from_string(). This does not check for validity of the entries. */
int tpm2_pcr_values_from_string(const char *arg, Tpm2PCRValue **ret_pcr_values, size_t *ret_n_pcr_values) {
        const char *p = arg;
        int r;
 
        assert(arg);
        assert(ret_pcr_values);
        assert(ret_n_pcr_values);
 
        _cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
        size_t n_pcr_values = 0;
 
        for (;;) {
                _cleanup_free_ char *pcr_arg = NULL;
                r = extract_first_word(&p, &pcr_arg, ",+", /* flags= */ 0);
                if (r < 0)
                        return log_debug_errno(r, "Could not parse pcr values '%s': %m", p);
                if (r == 0)
                        break;
 
                Tpm2PCRValue pcr_value;
                r = tpm2_pcr_value_from_string(pcr_arg, &pcr_value);
                if (r < 0)
                        return r;
 
                if (!GREEDY_REALLOC_APPEND(pcr_values, n_pcr_values, &pcr_value, 1))
                        return log_oom_debug();
        }
 
        *ret_pcr_values = TAKE_PTR(pcr_values);
        *ret_n_pcr_values = n_pcr_values;
 
        return 0;
}
 
void tpm2_log_debug_tpml_pcr_selection(const TPML_PCR_SELECTION *l, const char *msg) {
        if (!DEBUG_LOGGING || !l)
                return;
 
        _cleanup_free_ char *s = tpm2_tpml_pcr_selection_to_string(l);
        log_debug("%s: %s", msg ?: "PCR selection", strna(s));
}
 
void tpm2_log_debug_pcr_value(const Tpm2PCRValue *pcr_value, const char *msg) {
        if (!DEBUG_LOGGING || !pcr_value)
                return;
 
        _cleanup_free_ char *s = tpm2_pcr_value_to_string(pcr_value);
        log_debug("%s: %s", msg ?: "PCR value", strna(s));
}
 
void tpm2_log_debug_buffer(const void *buffer, size_t size, const char *msg) {
        if (!DEBUG_LOGGING || !buffer || size == 0)
                return;
 
        _cleanup_free_ char *h = hexmem(buffer, size);
        log_debug("%s: %s", msg ?: "Buffer", strna(h));
}
 
void tpm2_log_debug_digest(const TPM2B_DIGEST *digest, const char *msg) {
        if (digest)
                tpm2_log_debug_buffer(digest->buffer, digest->size, msg ?: "Digest");
}
 
void tpm2_log_debug_name(const TPM2B_NAME *name, const char *msg) {
        if (name)
                tpm2_log_debug_buffer(name->name, name->size, msg ?: "Name");
}
 
static int tpm2_get_policy_digest(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPM2B_DIGEST **ret_policy_digest) {
 
        TSS2_RC rc;
 
        if (!DEBUG_LOGGING && !ret_policy_digest)
                return 0;
 
        assert(c);
        assert(session);
 
        log_debug("Acquiring policy digest.");
 
        _cleanup_(Esys_Freep) TPM2B_DIGEST *policy_digest = NULL;
        rc = sym_Esys_PolicyGetDigest(
                        c->esys_context,
                        session->esys_handle,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        &policy_digest);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc));
 
        tpm2_log_debug_digest(policy_digest, "Session policy digest");
 
        if (ret_policy_digest)
                *ret_policy_digest = TAKE_PTR(policy_digest);
 
        return 0;
}
 
int tpm2_create_primary(
                Tpm2Context *c,
                const Tpm2Handle *session,
                ESYS_TR hierarchy,
                const TPM2B_PUBLIC *template,
                const TPM2B_SENSITIVE_CREATE *sensitive,
                TPM2B_PUBLIC **ret_public,
                Tpm2Handle **ret_handle) {
 
        usec_t ts;
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(template);
 
        log_debug("Creating primary key on TPM.");
 
        ts = now(CLOCK_MONOTONIC);
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
        r = tpm2_handle_new(c, &handle);
        if (r < 0)
                return r;
 
        _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
        rc = sym_Esys_CreatePrimary(
                        c->esys_context,
                        hierarchy,
                        session ? session->esys_handle : ESYS_TR_PASSWORD,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        sensitive ?: &(TPM2B_SENSITIVE_CREATE) {},
                        template,
                        /* outsideInfo= */ NULL,
                        &(TPML_PCR_SELECTION) {},
                        &handle->esys_handle,
                        &public,
                        /* creationData= */ NULL,
                        /* creationHash= */ NULL,
                        /* creationTicket= */ NULL);
        if ((rc & ~TPM2_RC_N_MASK) == TPM2_RC_BAD_AUTH)
                return log_debug_errno(SYNTHETIC_ERRNO(EDEADLK), "Authorization failure while attempting to create primary key.");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to generate primary key in TPM: %s",
                                       sym_Tss2_RC_Decode(rc));
 
        log_debug("Successfully created primary key on TPM in %s.",
                  FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - ts, USEC_PER_MSEC));
 
        if (ret_public)
                *ret_public = TAKE_PTR(public);
        if (ret_handle)
                *ret_handle = TAKE_PTR(handle);
 
        return 0;
}
 
/* Create a TPM object. Do not use this to create primary keys, because some HW TPMs refuse to allow that;
 * instead use tpm2_create_primary(). */
int tpm2_create(Tpm2Context *c,
                const Tpm2Handle *parent,
                const Tpm2Handle *session,
                const TPMT_PUBLIC *template,
                const TPMS_SENSITIVE_CREATE *sensitive,
                TPM2B_PUBLIC **ret_public,
                TPM2B_PRIVATE **ret_private) {
 
        usec_t ts;
        TSS2_RC rc;
 
        assert(c);
        assert(parent);
        assert(template);
 
        log_debug("Creating object on TPM.");
 
        ts = now(CLOCK_MONOTONIC);
 
        TPM2B_PUBLIC tpm2b_public = {
                .size = sizeof(*template) - sizeof(template->unique),
                .publicArea = *template,
        };
 
        /* Zero the unique area. */
        zero(tpm2b_public.publicArea.unique);
 
        TPM2B_SENSITIVE_CREATE tpm2b_sensitive;
        if (sensitive)
                tpm2b_sensitive = (TPM2B_SENSITIVE_CREATE) {
                        .size = sizeof(*sensitive),
                        .sensitive = *sensitive,
                };
        else
                tpm2b_sensitive = (TPM2B_SENSITIVE_CREATE) {};
 
        _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
        _cleanup_(Esys_Freep) TPM2B_PRIVATE *private = NULL;
        rc = sym_Esys_Create(
                        c->esys_context,
                        parent->esys_handle,
                        session ? session->esys_handle : ESYS_TR_PASSWORD,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        &tpm2b_sensitive,
                        &tpm2b_public,
                        /* outsideInfo= */ NULL,
                        &(TPML_PCR_SELECTION) {},
                        &private,
                        &public,
                        /* creationData= */ NULL,
                        /* creationHash= */ NULL,
                        /* creationTicket= */ NULL);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to generate object in TPM: %s",
                                       sym_Tss2_RC_Decode(rc));
 
        log_debug("Successfully created object on TPM in %s.",
                  FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - ts, USEC_PER_MSEC));
 
        if (ret_public)
                *ret_public = TAKE_PTR(public);
        if (ret_private)
                *ret_private = TAKE_PTR(private);
 
        return 0;
}
 
int tpm2_load(
                Tpm2Context *c,
                const Tpm2Handle *parent,
                const Tpm2Handle *session,
                const TPM2B_PUBLIC *public,
                const TPM2B_PRIVATE *private,
                Tpm2Handle **ret_handle) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(public);
        assert(private);
        assert(ret_handle);
 
        log_debug("Loading object into TPM.");
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
        r = tpm2_handle_new(c, &handle);
        if (r < 0)
                return r;
 
        rc = sym_Esys_Load(
                        c->esys_context,
                        parent ? parent->esys_handle : ESYS_TR_RH_OWNER,
                        session ? session->esys_handle : ESYS_TR_PASSWORD,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        private,
                        public,
                        &handle->esys_handle);
        if (rc == TPM2_RC_LOCKOUT)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOLCK),
                                       "TPM2 device is in dictionary attack lockout mode.");
        if (TPM2_RC_IS_FOREIGN_KEY(rc))
                return log_debug_errno(SYNTHETIC_ERRNO(EREMOTE),
                                       "Key invalid or does not belong to current TPM.");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to load key into TPM: %s", sym_Tss2_RC_Decode(rc));
 
        *ret_handle = TAKE_PTR(handle);
 
        return 0;
}
 
static int tpm2_load_external(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const TPM2B_PUBLIC *public,
                const TPM2B_SENSITIVE *private,
                Tpm2Handle **ret_handle) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(ret_handle);
 
        log_debug("Loading external key into TPM.");
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
        r = tpm2_handle_new(c, &handle);
        if (r < 0)
                return r;
 
        rc = sym_Esys_LoadExternal(
                        c->esys_context,
                        session ? session->esys_handle : ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        private,
                        public,
#if HAVE_TSS2_ESYS3
                        /* tpm2-tss >= 3.0.0 requires a ESYS_TR_RH_* constant specifying the requested
                         * hierarchy, older versions need TPM2_RH_* instead. */
                        private ? ESYS_TR_RH_NULL : ESYS_TR_RH_OWNER,
#else
                        private ? TPM2_RH_NULL : TPM2_RH_OWNER,
#endif
                        &handle->esys_handle);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to load public key into TPM: %s", sym_Tss2_RC_Decode(rc));
 
        *ret_handle = TAKE_PTR(handle);
 
        return 0;
}
 
int tpm2_marshal_private(const TPM2B_PRIVATE *private, void **ret, size_t *ret_size) {
        size_t max_size = SIZEOF(*private), blob_size = 0;
        _cleanup_free_ void *blob = NULL;
        TSS2_RC rc;
 
        assert(private);
        assert(ret);
        assert(ret_size);
 
        blob = malloc0(max_size);
        if (!blob)
                return log_oom_debug();
 
        rc = sym_Tss2_MU_TPM2B_PRIVATE_Marshal(private, blob, max_size, &blob_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal private key: %s", sym_Tss2_RC_Decode(rc));
 
        *ret = TAKE_PTR(blob);
        *ret_size = blob_size;
        return 0;
}
 
int tpm2_unmarshal_private(const void *data, size_t size, TPM2B_PRIVATE *ret_private) {
        TPM2B_PRIVATE private = {};
        size_t offset = 0;
        TSS2_RC rc;
 
        assert(data || size == 0);
        assert(ret_private);
 
        rc = sym_Tss2_MU_TPM2B_PRIVATE_Unmarshal(data, size, &offset, &private);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to unmarshal private key: %s", sym_Tss2_RC_Decode(rc));
        if (offset != size)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Garbage at end of private key marshal data.");
 
        *ret_private = private;
        return 0;
}
 
int tpm2_marshal_public(const TPM2B_PUBLIC *public, void **ret, size_t *ret_size) {
        size_t max_size = SIZEOF(*public), blob_size = 0;
        _cleanup_free_ void *blob = NULL;
        TSS2_RC rc;
 
        assert(public);
        assert(ret);
        assert(ret_size);
 
        blob = malloc0(max_size);
        if (!blob)
                return log_oom_debug();
 
        rc = sym_Tss2_MU_TPM2B_PUBLIC_Marshal(public, blob, max_size, &blob_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal public key: %s", sym_Tss2_RC_Decode(rc));
 
        *ret = TAKE_PTR(blob);
        *ret_size = blob_size;
        return 0;
}
 
int tpm2_unmarshal_public(const void *data, size_t size, TPM2B_PUBLIC *ret_public) {
        TPM2B_PUBLIC public = {};
        size_t offset = 0;
        TSS2_RC rc;
 
        assert(data || size == 0);
        assert(ret_public);
 
        rc = sym_Tss2_MU_TPM2B_PUBLIC_Unmarshal(data, size, &offset, &public);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to unmarshal public key: %s", sym_Tss2_RC_Decode(rc));
        if (offset != size)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Garbage at end of public key marshal data.");
 
        *ret_public = public;
        return 0;
}
 
int tpm2_marshal_nv_public(const TPM2B_NV_PUBLIC *nv_public, void **ret, size_t *ret_size) {
        size_t max_size = SIZEOF(*nv_public), blob_size = 0;
        _cleanup_free_ void *blob = NULL;
        TSS2_RC rc;
 
        assert(nv_public);
        assert(ret);
        assert(ret_size);
 
        blob = malloc0(max_size);
        if (!blob)
                return log_oom_debug();
 
        rc = sym_Tss2_MU_TPM2B_NV_PUBLIC_Marshal(nv_public, blob, max_size, &blob_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal NV public structure: %s", sym_Tss2_RC_Decode(rc));
 
        *ret = TAKE_PTR(blob);
        *ret_size = blob_size;
        return 0;
}
 
int tpm2_unmarshal_nv_public(const void *data, size_t size, TPM2B_NV_PUBLIC *ret_nv_public) {
        TPM2B_NV_PUBLIC nv_public = {};
        size_t offset = 0;
        TSS2_RC rc;
 
        assert(data || size == 0);
        assert(ret_nv_public);
 
        rc = sym_Tss2_MU_TPM2B_NV_PUBLIC_Unmarshal(data, size, &offset, &nv_public);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to unmarshal NV public structure: %s", sym_Tss2_RC_Decode(rc));
        if (offset != size)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Garbage at end of NV public structure marshal data.");
 
        *ret_nv_public = nv_public;
        return 0;
}
 
static int tpm2_import(
                Tpm2Context *c,
                const Tpm2Handle *parent,
                const Tpm2Handle *session,
                const TPM2B_PUBLIC *public,
                const TPM2B_PRIVATE *private,
                const TPM2B_ENCRYPTED_SECRET *seed,
                const TPM2B_DATA *encryption_key,
                const TPMT_SYM_DEF_OBJECT *symmetric,
                TPM2B_PRIVATE **ret_private) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(parent);
        assert(!!encryption_key == !!symmetric);
        assert(public);
        assert(private);
        assert(seed);
        assert(ret_private);
 
        log_debug("Importing key into TPM.");
 
        rc = sym_Esys_Import(
                        c->esys_context,
                        parent->esys_handle,
                        session ? session->esys_handle : ESYS_TR_PASSWORD,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        encryption_key,
                        public,
                        private,
                        seed,
                        symmetric ?: &(TPMT_SYM_DEF_OBJECT){ .algorithm = TPM2_ALG_NULL, },
                        ret_private);
        if (TPM2_RC_IS_FOREIGN_KEY(rc))
                return log_debug_errno(SYNTHETIC_ERRNO(EREMOTE),
                                       "Key invalid or does not belong to current TPM.");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to import key into TPM: %s", sym_Tss2_RC_Decode(rc));
 
        return 0;
}
 
/* Read hash values from the specified PCR selection. Provides a Tpm2PCRValue array that contains all
 * requested PCR values, in the order provided by the TPM. Normally, the provided pcr values will match
 * exactly what is in the provided selection, but the TPM may ignore some selected PCRs (for example, if an
 * unimplemented PCR index is requested), in which case those PCRs will be absent from the provided pcr
 * values. */
int tpm2_pcr_read(
                Tpm2Context *c,
                const TPML_PCR_SELECTION *pcr_selection,
                Tpm2PCRValue **ret_pcr_values,
                size_t *ret_n_pcr_values) {
 
        _cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
        size_t n_pcr_values = 0;
        TSS2_RC rc;
 
        assert(c);
        assert(pcr_selection);
        assert(ret_pcr_values);
        assert(ret_n_pcr_values);
 
        TPML_PCR_SELECTION remaining = *pcr_selection;
        while (!tpm2_tpml_pcr_selection_is_empty(&remaining)) {
                _cleanup_(Esys_Freep) TPML_PCR_SELECTION *current_read = NULL;
                _cleanup_(Esys_Freep) TPML_DIGEST *current_values = NULL;
 
                tpm2_log_debug_tpml_pcr_selection(&remaining, "Reading PCR selection");
 
                /* Unfortunately, PCR_Read will not return more than 8 values. */
                rc = sym_Esys_PCR_Read(
                                c->esys_context,
                                ESYS_TR_NONE,
                                ESYS_TR_NONE,
                                ESYS_TR_NONE,
                                &remaining,
                                NULL,
                                &current_read,
                                &current_values);
                if (rc != TSS2_RC_SUCCESS)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to read TPM2 PCRs: %s", sym_Tss2_RC_Decode(rc));
 
                tpm2_log_debug_tpml_pcr_selection(current_read, "Read PCR selection");
 
                if (tpm2_tpml_pcr_selection_is_empty(current_read)) {
                        log_debug("TPM2 refused to read possibly unimplemented PCRs, ignoring.");
                        break;
                }
 
                unsigned i = 0;
                FOREACH_PCR_IN_TPML_PCR_SELECTION(index, tpms, current_read) {
                        assert(i < current_values->count);
                        Tpm2PCRValue pcr_value = {
                                .index = index,
                                .hash = tpms->hash,
                                .value = current_values->digests[i++],
                        };
 
                        tpm2_log_debug_pcr_value(&pcr_value, /* msg= */ NULL);
 
                        if (!GREEDY_REALLOC_APPEND(pcr_values, n_pcr_values, &pcr_value, 1))
                                return log_oom_debug();
                }
                assert(i == current_values->count);
 
                tpm2_tpml_pcr_selection_sub(&remaining, current_read);
        }
 
        tpm2_sort_pcr_values(pcr_values, n_pcr_values);
 
        if (!tpm2_pcr_values_valid(pcr_values, n_pcr_values))
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "PCR values read from TPM are not valid.");
 
        *ret_pcr_values = TAKE_PTR(pcr_values);
        *ret_n_pcr_values = n_pcr_values;
 
        return 0;
}
 
/* Read the PCR value for each TPM2PCRValue entry in the array that does not have a value set. If all entries
 * have an unset hash (i.e. hash == 0), this first detects the "best" PCR bank to use; otherwise, all entries
 * must have a valid hash set. All entries must have a valid index. If this cannot read a PCR value for all
 * appropriate entries, this returns an error. This does not check the array for validity. */
int tpm2_pcr_read_missing_values(Tpm2Context *c, Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
        TPMI_ALG_HASH pcr_bank = 0;
        int r;
 
        assert(c);
        assert(pcr_values || n_pcr_values == 0);
 
        if (n_pcr_values > 0) {
                size_t hash_count;
                r = tpm2_pcr_values_hash_count(pcr_values, n_pcr_values, &hash_count);
                if (r < 0)
                        return log_debug_errno(r, "Could not get hash count from pcr values: %m");
 
                if (hash_count == 1 && pcr_values[0].hash == 0) {
                        uint32_t mask;
                        r = tpm2_pcr_values_to_mask(pcr_values, n_pcr_values, 0, &mask);
                        if (r < 0)
                                return r;
 
                        r = tpm2_get_best_pcr_bank(c, mask, &pcr_bank);
                        if (r < 0)
                                return r;
                }
        }
 
        FOREACH_ARRAY(v, pcr_values, n_pcr_values) {
                if (v->hash == 0)
                        v->hash = pcr_bank;
 
                if (v->value.size > 0)
                        continue;
 
                TPML_PCR_SELECTION selection;
                r = tpm2_tpml_pcr_selection_from_pcr_values(v, 1, &selection, NULL, NULL);
                if (r < 0)
                        return r;
 
                _cleanup_free_ Tpm2PCRValue *read_values = NULL;
                size_t n_read_values;
                r = tpm2_pcr_read(c, &selection, &read_values, &n_read_values);
                if (r < 0)
                        return r;
 
                if (n_read_values == 0)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Could not read PCR hash 0x%" PRIu16 " index %u",
                                               v->hash, v->index);
 
                assert(n_read_values == 1);
                assert(read_values[0].hash == v->hash);
                assert(read_values[0].index == v->index);
 
                v->value = read_values[0].value;
        }
 
        return 0;
}
 
static int tpm2_pcr_mask_good(
                Tpm2Context *c,
                TPMI_ALG_HASH bank,
                uint32_t mask) {
 
        TPML_PCR_SELECTION selection;
        int r;
 
        assert(c);
 
        /* So we have the problem that some systems might have working TPM2 chips, but the firmware doesn't
         * actually measure into them, or only into a suboptimal bank. If so, the PCRs should be all zero or
         * all 0xFF. Detect that, so that we can warn and maybe pick a better bank. */
 
        tpm2_tpml_pcr_selection_from_mask(mask, bank, &selection);
 
        _cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
        size_t n_pcr_values;
        r = tpm2_pcr_read(c, &selection, &pcr_values, &n_pcr_values);
        if (r < 0)
                return r;
 
        /* If at least one of the selected PCR values is something other than all 0x00 or all 0xFF we are happy. */
        FOREACH_ARRAY(v, pcr_values, n_pcr_values)
                if (!memeqbyte(0x00, v->value.buffer, v->value.size) &&
                    !memeqbyte(0xFF, v->value.buffer, v->value.size))
                        return true;
 
        return false;
}
 
static int tpm2_bank_has24(const TPMS_PCR_SELECTION *selection) {
 
        assert(selection);
 
        /* As per https://trustedcomputinggroup.org/wp-content/uploads/TCG_PCClient_PFP_r1p05_v23_pub.pdf a
         * TPM2 on a Client PC must have at least 24 PCRs. If this TPM has less, just skip over it. */
        if (selection->sizeofSelect < TPM2_PCRS_MAX/8) {
                log_debug("Skipping TPM2 PCR bank %s with fewer than 24 PCRs.",
                          strna(tpm2_hash_alg_to_string(selection->hash)));
                return false;
        }
 
        assert_cc(TPM2_PCRS_MAX % 8 == 0);
 
        /* It's not enough to check how many PCRs there are, we also need to check that the 24 are
         * enabled for this bank. Otherwise this TPM doesn't qualify. */
        bool valid = true;
        for (size_t j = 0; j < TPM2_PCRS_MAX/8; j++)
                if (selection->pcrSelect[j] != 0xFF) {
                        valid = false;
                        break;
                }
 
        if (!valid)
                log_debug("TPM2 PCR bank %s has fewer than 24 PCR bits enabled, ignoring.",
                          strna(tpm2_hash_alg_to_string(selection->hash)));
 
        return valid;
}
 
static char* pcr_bank_preference_to_string(const uint16_t *banks, size_t n_banks) {
        _cleanup_free_ char *s = NULL;
 
        assert(banks);
 
        FOREACH_ARRAY(bank, banks, n_banks)
                if (!strextend_with_separator(&s, ", ", tpm2_hash_alg_to_string(*bank)))
                        return NULL;
 
        return TAKE_PTR(s);
}
 
static int get_best_pcr_bank(
                Tpm2Context *c,