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 1001–2000 of 12,273

 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        if (!device) {
                device = secure_getenv("SYSTEMD_TPM2_DEVICE");
                if (device)
                        /* Setting the env var to an empty string forces tpm2-tss' own device picking
                         * logic to be used. */
                        device = empty_to_null(device);
                else
                        /* If nothing was specified explicitly, we'll use a hardcoded default: the "device" tcti
                         * driver and the "/dev/tpmrm0" device. We do this since on some distributions the tpm2-abrmd
                         * might be used and we really don't want that, since it is a system service and that creates
                         * various ordering issues/deadlocks during early boot. */
                        device = "device:/dev/tpmrm0";
        }
 
        if (device) {
                _cleanup_free_ char *_driver = NULL;
                const char *param, *driver;
                const TSS2_TCTI_INFO* info;
                TSS2_TCTI_INFO_FUNC func;
                size_t sz = 0;
 
                param = strchr(device, ':');
                if (param) {
                        /* Syntax #1: Pair of driver string and arbitrary parameter */
                        driver = _driver = strndup(device, param - device);
                        if (!driver)
                                return log_oom_debug();
                        if (isempty(driver))
                                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 driver name is empty, refusing.");
 
                        param++;
                } else if (path_is_absolute(device) && path_is_valid(device)) {
                        /* Syntax #2: TPM device node */
                        driver = "device";
                        param = device;
                } else
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid TPM2 driver string, refusing.");
 
                log_debug("Using TPM2 TCTI driver '%s' with device '%s'.", driver, param);
 
                _cleanup_free_ char *fn = strjoin("libtss2-tcti-", driver, ".so.0");
                if (!fn)
                        return log_oom_debug();
 
                /* Better safe than sorry, let's refuse strings that cannot possibly be valid driver early, before going to disk. */
                if (!filename_is_valid(fn))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 driver name '%s' not valid, refusing.", driver);
 
                const char *dle = NULL;
                r = dlopen_safe(fn, &context->tcti_dl, &dle);
                if (r < 0) {
                        log_debug_errno(r, "Failed to load %s: %s", fn, dle ?: STRERROR(r));
                        return -ENOPKG; /* Turn into recognizable error */
                }
 
                log_debug("Loaded '%s' via dlopen()", fn);
 
                func = dlsym(context->tcti_dl, TSS2_TCTI_INFO_SYMBOL);
                if (!func)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to find TCTI info symbol " TSS2_TCTI_INFO_SYMBOL ": %s",
                                               dlerror());
 
                info = func();
                if (!info)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Unable to get TCTI info data.");
 
                log_debug("Loaded TCTI module '%s' (%s) [Version %" PRIu32 "]", info->name, info->description, info->version);
 
                rc = info->init(/* context= */ NULL, &sz, /* param= */ NULL);
                if (rc != TPM2_RC_SUCCESS)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to initialize TCTI context: %s", sym_Tss2_RC_Decode(rc));
 
                context->tcti_context = malloc0(sz);
                if (!context->tcti_context)
                        return log_oom_debug();
 
                rc = info->init(context->tcti_context, &sz, param);
                if (rc != TPM2_RC_SUCCESS)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to initialize TCTI context: %s", sym_Tss2_RC_Decode(rc));
 
                context->tcti_driver = strdup(driver);
                if (!context->tcti_driver)
                        return log_oom_debug();
 
                context->tcti_param = strdup(param);
                if (!context->tcti_param)
                        return log_oom_debug();
        }
 
        rc = sym_Esys_Initialize(&context->esys_context, context->tcti_context, NULL);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to initialize TPM context: %s", sym_Tss2_RC_Decode(rc));
 
        rc = sym_Esys_Startup(context->esys_context, TPM2_SU_CLEAR);
        if (rc == TPM2_RC_INITIALIZE)
                log_debug("TPM already started up.");
        else if (rc == TSS2_RC_SUCCESS)
                log_debug("TPM successfully started up.");
        else
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to start up TPM: %s", sym_Tss2_RC_Decode(rc));
 
        r = tpm2_cache_capabilities(context);
        if (r < 0)
                return log_debug_errno(r, "Failed to cache TPM capabilities: %m");
 
        /* We require AES and CFB support for session encryption. */
        if (!tpm2_supports_alg(context, TPM2_ALG_AES))
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM does not support AES.");
 
        if (!tpm2_supports_alg(context, TPM2_ALG_CFB))
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM does not support CFB.");
 
        if (!tpm2_supports_tpmt_sym_def(context, &SESSION_TEMPLATE_SYM_AES_128_CFB))
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM does not support AES-128-CFB.");
 
        *ret_context = TAKE_PTR(context);
 
        return 0;
}
 
int tpm2_context_new_or_warn(const char *device, Tpm2Context **ret_context) {
        int r;
 
        assert(ret_context);
 
        r = tpm2_context_new(device, ret_context);
        if (r == -EOPNOTSUPP)
                return log_error_errno(r, "TPM device not usable as it does not support the required functionality (AES-128-CFB missing?).");
        if (r == -ENOPKG)
                return log_error_errno(r, "TPM TCTI driver not available.");
        if (r == -ENOENT)
                return log_error_errno(r, "TPM device not found.");
        if (r < 0)
                return log_error_errno(r, "Failed to create TPM2 context: %m");
 
        return 0;
}
 
static void tpm2_handle_cleanup(ESYS_CONTEXT *esys_context, ESYS_TR esys_handle, bool flush) {
        TSS2_RC rc;
 
        if (!esys_context || esys_handle == ESYS_TR_NONE)
                return;
 
        /* Closing the handle removes its reference from the esys_context, but leaves the corresponding
         * handle in the actual TPM. Flushing the handle removes its reference from the esys_context as well
         * as removing its corresponding handle from the actual TPM. */
        if (flush)
                rc = sym_Esys_FlushContext(esys_context, esys_handle);
        else
                /* We can't use Esys_TR_Close() because the tpm2-tss library does not use reference counting
                 * for handles, and a single Esys_TR_Close() will remove the handle (internal to the tpm2-tss
                 * library) that might be in use by other code that is using the same ESYS_CONTEXT. This
                 * directly affects us; for example the src/test/test-tpm2.c test function
                 * check_seal_unseal() will encounter this issue and will result in a failure when trying to
                 * cleanup (i.e. Esys_FlushContext) the transient primary key that the test function
                 * generates. However, not calling Esys_TR_Close() here should be ok, since any leaked handle
                 * references will be cleaned up when we free our ESYS_CONTEXT.
                 *
                 * An upstream bug is open here: https://github.com/tpm2-software/tpm2-tss/issues/2693 */
                rc = TSS2_RC_SUCCESS; // FIXME: restore sym_Esys_TR_Close() use once tpm2-tss is fixed and adopted widely enough
        if (rc != TSS2_RC_SUCCESS)
                /* We ignore failures here (besides debug logging), since this is called in error paths,
                 * where we cannot do anything about failures anymore. And when it is called in successful
                 * codepaths by this time we already did what we wanted to do, and got the results we wanted
                 * so there's no reason to make this fail more loudly than necessary. */
                log_debug("Failed to %s TPM handle, ignoring: %s", flush ? "flush" : "close", sym_Tss2_RC_Decode(rc));
}
 
Tpm2Handle *tpm2_handle_free(Tpm2Handle *handle) {
        if (!handle)
                return NULL;
 
        _cleanup_(tpm2_context_unrefp) Tpm2Context *context = handle->tpm2_context;
        if (context)
                tpm2_handle_cleanup(context->esys_context, handle->esys_handle, handle->flush);
 
        return mfree(handle);
}
 
int tpm2_handle_new(Tpm2Context *context, Tpm2Handle **ret_handle) {
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
 
        assert(ret_handle);
 
        handle = new(Tpm2Handle, 1);
        if (!handle)
                return log_oom_debug();
 
        *handle = (Tpm2Handle) {
                .tpm2_context = tpm2_context_ref(context),
                .esys_handle = ESYS_TR_NONE,
                .flush = true,
        };
 
        *ret_handle = TAKE_PTR(handle);
 
        return 0;
}
 
int tpm2_read_public(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const Tpm2Handle *handle,
                TPM2B_PUBLIC **ret_public,
                TPM2B_NAME **ret_name,
                TPM2B_NAME **ret_qname) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(handle);
 
        rc = sym_Esys_ReadPublic(
                        c->esys_context,
                        handle->esys_handle,
                        session ? session->esys_handle : ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ret_public,
                        ret_name,
                        ret_qname);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to read public info: %s", sym_Tss2_RC_Decode(rc));
 
        return 0;
}
 
static int tpm2_read_nv_public(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const Tpm2Handle *handle,
                TPM2B_NV_PUBLIC **ret_nv_public,
                TPM2B_NAME **ret_name) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(handle);
 
        rc = sym_Esys_NV_ReadPublic(
                        c->esys_context,
                        handle->esys_handle,
                        session ? session->esys_handle : ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ret_nv_public,
                        ret_name);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to read NV public info: %s", sym_Tss2_RC_Decode(rc));
 
        return 0;
}
 
/* Create a Tpm2Handle object that references a pre-existing handle in the TPM, at the handle index provided.
 * This should be used only for persistent, transient, or NV handles; and the handle must already exist in
 * the TPM at the specified handle index. The handle index should not be 0. Returns 1 if found, 0 if the
 * index is empty, or < 0 on error. Also see tpm2_get_srk() below; the SRK is a commonly used persistent
 * Tpm2Handle. */
int tpm2_index_to_handle(
                Tpm2Context *c,
                TPM2_HANDLE index,
                const Tpm2Handle *session,
                TPM2B_NAME **ret_name,
                Tpm2Handle **ret_handle) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
 
        /* Only allow persistent, transient, or NV index handle types. */
        switch (TPM2_HANDLE_TYPE(index)) {
        case TPM2_HT_PERSISTENT:
        case TPM2_HT_NV_INDEX:
        case TPM2_HT_TRANSIENT:
                break;
        case TPM2_HT_PCR:
                /* PCR handles are referenced by their actual index number and do not need a Tpm2Handle */
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Invalid handle 0x%08" PRIx32 " (in PCR range).", index);
        case TPM2_HT_HMAC_SESSION:
        case TPM2_HT_POLICY_SESSION:
                /* Session indexes are only used internally by tpm2-tss (or lower code) */
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Invalid handle 0x%08" PRIx32 " (in session range).", index);
        case TPM2_HT_PERMANENT:
                /* Permanent handles are defined, e.g. ESYS_TR_RH_OWNER. */
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Invalid handle 0x%08" PRIx32 " (in permanent range).", index);
        default:
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Invalid handle 0x%08" PRIx32 " (in unknown range).", index);
        }
 
        /* For transient handles, the kernel tpm "resource manager" (i.e. /dev/tpmrm0) performs mapping
         * which breaks GetCapability requests, so only check GetCapability if it's not a transient handle.
         * https://bugzilla.kernel.org/show_bug.cgi?id=218009 */
        if (TPM2_HANDLE_TYPE(index) != TPM2_HT_TRANSIENT) { // FIXME: once kernel bug is fixed, check transient handles too
                r = tpm2_get_capability_handle(c, index);
                if (r < 0)
                        return r;
                if (r == 0) {
                        log_debug("TPM handle 0x%08" PRIx32 " not populated.", index);
                        if (ret_name)
                                *ret_name = NULL;
                        if (ret_handle)
                                *ret_handle = NULL;
                        return 0;
                }
        }
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
        r = tpm2_handle_new(c, &handle);
        if (r < 0)
                return r;
 
        /* Since we didn't create this handle in the TPM (this is only creating an ESYS_TR handle for the
         * pre-existing TPM handle), we shouldn't flush (or evict) it on cleanup. */
        handle->flush = false;
 
        rc = sym_Esys_TR_FromTPMPublic(
                        c->esys_context,
                        index,
                        session ? session->esys_handle : ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        &handle->esys_handle);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to read public info: %s", sym_Tss2_RC_Decode(rc));
 
        if (ret_name) {
                r = tpm2_get_name(c, handle, ret_name);
                if (r < 0)
                        return r;
        }
 
        if (ret_handle)
                *ret_handle = TAKE_PTR(handle);
 
        return 1;
}
 
/* Create a Tpm2Handle object that references a pre-existing persistent or transient object in the TPM, at
 * the handle index provided. The handle index should not be 0. Returns 1 if found, 0 if the index is empty,
 * or < 0 on error. Also see tpm2_get_srk() below; the SRK is a commonly used persistent Tpm2Handle. */
int tpm2_object_index_to_handle(
                Tpm2Context *c,
                TPM2_HANDLE index,
                const Tpm2Handle *session,
                TPM2B_PUBLIC **ret_public,
                TPM2B_NAME **ret_name,
                TPM2B_NAME **ret_qname,
                Tpm2Handle **ret_handle) {
 
        int r;
 
        assert(c);
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
        _cleanup_(Esys_Freep) TPM2B_NAME *name = NULL;
        r = tpm2_index_to_handle(c, index, session, ret_name ? &name : NULL, &handle);
        if (r < 0)
                return r;
        if (r == 0) {
                if (ret_public)
                        *ret_public = NULL;
                if (ret_name)
                        *ret_name = NULL;
                if (ret_qname)
                        *ret_qname = NULL;
                if (ret_handle)
                        *ret_handle = NULL;
                return 0;
        }
 
        if (ret_public || ret_qname) {
                sym_Esys_Free(name);
                name = NULL;
 
                r = tpm2_read_public(c, session, handle, ret_public, &name, ret_qname);
                if (r < 0)
                        return r;
        }
 
        if (ret_name)
                *ret_name = TAKE_PTR(name);
        if (ret_handle)
                *ret_handle = TAKE_PTR(handle);
 
        return 1;
}
 
/* Create a Tpm2Handle object that references a pre-existing NV index in the TPM, at the handle index
 * provided. The handle index should not be 0. Returns 1 if found, 0 if the index is empty, or < 0 on
 * error. */
int tpm2_nv_index_to_handle(
                Tpm2Context *c,
                TPM2_HANDLE index,
                const Tpm2Handle *session,
                TPM2B_NV_PUBLIC **ret_nv_public,
                TPM2B_NAME **ret_name,
                Tpm2Handle **ret_handle) {
 
        int r;
 
        assert(c);
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
        _cleanup_(Esys_Freep) TPM2B_NAME *name = NULL;
        r = tpm2_index_to_handle(c, index, session, ret_name ? &name : NULL, &handle);
        if (r < 0)
                return r;
        if (r == 0) {
                if (ret_nv_public)
                        *ret_nv_public = NULL;
                if (ret_name)
                        *ret_name = NULL;
                if (ret_handle)
                        *ret_handle = NULL;
                return 0;
        }
 
        if (ret_nv_public) {
                sym_Esys_Free(name);
                name = NULL;
 
                r = tpm2_read_nv_public(c, session, handle, ret_nv_public, &name);
                if (r < 0)
                        return r;
        }
 
        if (ret_name)
                *ret_name = TAKE_PTR(name);
        if (ret_handle)
                *ret_handle = TAKE_PTR(handle);
 
        return 1;
}
 
/* Get the handle index for the provided Tpm2Handle. */
int tpm2_index_from_handle(Tpm2Context *c, const Tpm2Handle *handle, TPM2_HANDLE *ret_index) {
        TSS2_RC rc;
 
        assert(c);
        assert(handle);
        assert(ret_index);
 
        /* 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 check can be removed. */
        if (!sym_Esys_TR_GetTpmHandle)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "libtss2-esys too old, does not include Esys_TR_GetTpmHandle.");
 
        rc = sym_Esys_TR_GetTpmHandle(c->esys_context, handle->esys_handle, ret_index);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to get handle index: %s", sym_Tss2_RC_Decode(rc));
 
        return 0;
}
 
int tpm2_marshal_saved_handle_context(TPMS_CONTEXT *context, void **ret, size_t *ret_size) {
        size_t max_size = SIZEOF(*context), blob_size = 0;
        _cleanup_free_ void *blob = NULL;
        TSS2_RC rc;
 
        assert(context);
        assert(ret);
        assert(ret_size);
 
        blob = malloc0(max_size);
        if (!blob)
                return log_oom_debug();
 
        rc = sym_Tss2_MU_TPMS_CONTEXT_Marshal(context, blob, max_size, &blob_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal saved context structure: %s", sym_Tss2_RC_Decode(rc));
 
        *ret = TAKE_PTR(blob);
        *ret_size = blob_size;
        return 0;
}
 
int tpm2_unmarshal_saved_handle_context(const void *data, size_t size, TPMS_CONTEXT *ret) {
        size_t offset = 0;
        TPMS_CONTEXT context = {};
        TSS2_RC rc;
        int r;
 
        assert(data);
        assert(ret);
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        rc = sym_Tss2_MU_TPMS_CONTEXT_Unmarshal(data, size, &offset, &context);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to unmarshal saved context structure: %s", sym_Tss2_RC_Decode(rc));
        if (offset != size)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Garbage at end of saved context structure data.");
 
        *ret = context;
        return 0;
}
 
int tpm2_load_saved_handle_context(Tpm2Context *c, const TPMS_CONTEXT *context, TPM2B_NAME **ret_name, Tpm2Handle **ret_handle) {
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(context);
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
        r = tpm2_handle_new(c, &handle);
        if (r < 0)
                return r;
 
        rc = sym_Esys_ContextLoad(c->esys_context, context, &handle->esys_handle);
        if (rc != TPM2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to load handle context: %s", sym_Tss2_RC_Decode(rc));
 
        if (ret_name) {
                r = tpm2_get_name(c, handle, ret_name);
                if (r < 0)
                        return r;
        }
 
        if (ret_handle)
                *ret_handle = TAKE_PTR(handle);
 
        return 0;
}
 
int tpm2_save_handle_context(Tpm2Context *c, const Tpm2Handle *handle, TPMS_CONTEXT **ret_context) {
        TSS2_RC rc;
 
        assert(c);
        assert(handle);
        assert(ret_context);
 
        _cleanup_(Esys_Freep) TPMS_CONTEXT *context = NULL;
        rc = sym_Esys_ContextSave(c->esys_context, handle->esys_handle, &context);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to save handle context: %s", sym_Tss2_RC_Decode(rc));
 
        *ret_context = TAKE_PTR(context);
        return 0;
}
 
/* Copy an object in the TPM at a transient handle to a persistent handle.
 *
 * The provided transient handle must exist in the TPM in the transient range. The persistent handle may be 0
 * or any handle in the persistent range. If 0, this will try each handle in the persistent range, in
 * ascending order, until an available one is found. If non-zero, only the requested persistent handle will
 * be used.
 *
 * Note that the persistent handle parameter is an handle index (i.e. number), while the transient handle is
 * a Tpm2Handle object. The returned persistent handle will be a Tpm2Handle object that is located in the TPM
 * at the requested persistent handle index (or the first available if none was requested).
 *
 * Returns 1 if the object was successfully persisted, or 0 if there is already a key at the requested
 * handle, or < 0 on error. Theoretically, this would also return 0 if no specific persistent handle is
 * requested but all persistent handles are used, but it is extremely unlikely the TPM has enough internal
 * memory to store the entire persistent range, in which case an error will be returned if the TPM is out of
 * memory for persistent storage. The persistent handle is only provided when returning 1. */
static int tpm2_persist_handle(
                Tpm2Context *c,
                const Tpm2Handle *transient_handle,
                const Tpm2Handle *session,
                TPMI_DH_PERSISTENT persistent_handle_index,
                Tpm2Handle **ret_persistent_handle) {
 
        /* We don't use TPM2_PERSISTENT_FIRST and TPM2_PERSISTENT_LAST here due to:
         * https://github.com/systemd/systemd/pull/27713#issuecomment-1591864753 */
        TPMI_DH_PERSISTENT first = UINT32_C(0x81000000), last = UINT32_C(0x81ffffff);
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(transient_handle);
 
        /* If persistent handle index specified, only try that. */
        if (persistent_handle_index != 0) {
                if (TPM2_HANDLE_TYPE(persistent_handle_index) != TPM2_HT_PERSISTENT)
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Handle not in persistent range: 0x%x", persistent_handle_index);
 
                first = last = persistent_handle_index;
        }
 
        for (TPMI_DH_PERSISTENT requested = first; requested <= last; requested++) {
                _cleanup_(tpm2_handle_freep) Tpm2Handle *persistent_handle = NULL;
                r = tpm2_handle_new(c, &persistent_handle);
                if (r < 0)
                        return r;
 
                /* Since this is a persistent handle, don't flush it. */
                persistent_handle->flush = false;
 
                rc = sym_Esys_EvictControl(
                                c->esys_context,
                                ESYS_TR_RH_OWNER,
                                transient_handle->esys_handle,
                                session ? session->esys_handle : ESYS_TR_PASSWORD,
                                ESYS_TR_NONE,
                                ESYS_TR_NONE,
                                requested,
                                &persistent_handle->esys_handle);
                if (rc == TSS2_RC_SUCCESS) {
                        if (ret_persistent_handle)
                                *ret_persistent_handle = TAKE_PTR(persistent_handle);
 
                        return 1;
                }
                if ((rc & ~TPM2_RC_N_MASK) == TPM2_RC_BAD_AUTH)
                        return log_debug_errno(SYNTHETIC_ERRNO(EDEADLK), "Authorization failure while attempting to persist handle.");
                if (rc != TPM2_RC_NV_DEFINED)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to persist handle: %s", sym_Tss2_RC_Decode(rc));
        }
 
        if (ret_persistent_handle)
                *ret_persistent_handle = NULL;
 
        return 0;
}
 
#define TPM2_CREDIT_RANDOM_FLAG_PATH "/run/systemd/tpm-rng-credited"
 
static int tpm2_credit_random(Tpm2Context *c) {
        size_t rps, done = 0;
        TSS2_RC rc;
        usec_t t;
        int r;
 
        assert(c);
 
        /* Pulls some entropy from the TPM and adds it into the kernel RNG pool. That way we can say that the
         * key we will ultimately generate with the kernel random pool is at least as good as the TPM's RNG,
         * but likely better. Note that we don't trust the TPM RNG very much, hence do not actually credit
         * any entropy. */
 
        if (access(TPM2_CREDIT_RANDOM_FLAG_PATH, F_OK) < 0) {
                if (errno != ENOENT)
                        log_debug_errno(errno, "Failed to detect if '" TPM2_CREDIT_RANDOM_FLAG_PATH "' exists, ignoring: %m");
        } else {
                log_debug("Not adding TPM2 entropy to the kernel random pool again.");
                return 0; /* Already done */
        }
 
        t = now(CLOCK_MONOTONIC);
 
        for (rps = random_pool_size(); rps > 0;) {
                _cleanup_(Esys_Freep) TPM2B_DIGEST *buffer = NULL;
 
                rc = sym_Esys_GetRandom(
                                c->esys_context,
                                ESYS_TR_NONE,
                                ESYS_TR_NONE,
                                ESYS_TR_NONE,
                                MIN(rps, 32U), /* 32 is supposedly a safe choice, given that AES 256bit keys are this long, and TPM2 baseline requires support for those. */
                                &buffer);
                if (rc != TSS2_RC_SUCCESS)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to acquire entropy from TPM: %s", sym_Tss2_RC_Decode(rc));
 
                if (buffer->size == 0)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Zero-sized entropy returned from TPM.");
 
                r = random_write_entropy(-1, buffer->buffer, buffer->size, /* credit= */ false);
                if (r < 0)
                        return log_debug_errno(r, "Failed to write entropy to kernel: %m");
 
                done += buffer->size;
                rps = LESS_BY(rps, buffer->size);
        }
 
        log_debug("Added %zu bytes of TPM2 entropy to the kernel random pool in %s.", done, FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - t, 0));
 
        r = touch(TPM2_CREDIT_RANDOM_FLAG_PATH);
        if (r < 0)
                log_debug_errno(r, "Failed to touch '" TPM2_CREDIT_RANDOM_FLAG_PATH "', ignoring: %m");
 
        return 0;
}
 
/* Get one of the legacy primary key templates.
 *
 * The legacy templates should only be used for older sealed data that did not use the SRK. Instead of a
 * persistent SRK, a transient key was created to seal the data and then flushed; and the exact same template
 * must be used to recreate the same transient key to unseal the data. The alg parameter must be TPM2_ALG_RSA
 * or TPM2_ALG_ECC. This does not check if the alg is actually supported on this TPM. */
static int tpm2_get_legacy_template(TPMI_ALG_PUBLIC alg, TPMT_PUBLIC *ret_template) {
        /* Do not modify. */
        static const TPMT_PUBLIC legacy_ecc = {
                .type = TPM2_ALG_ECC,
                .nameAlg = TPM2_ALG_SHA256,
                .objectAttributes =
                        TPMA_OBJECT_RESTRICTED|
                        TPMA_OBJECT_DECRYPT|
                        TPMA_OBJECT_FIXEDTPM|
                        TPMA_OBJECT_FIXEDPARENT|
                        TPMA_OBJECT_SENSITIVEDATAORIGIN|
                        TPMA_OBJECT_USERWITHAUTH,
                .parameters.eccDetail = {
                        .symmetric = {
                                .algorithm = TPM2_ALG_AES,
                                .keyBits.aes = 128,
                                .mode.aes = TPM2_ALG_CFB,
                        },
                        .scheme.scheme = TPM2_ALG_NULL,
                        .curveID = TPM2_ECC_NIST_P256,
                        .kdf.scheme = TPM2_ALG_NULL,
                },
        };
 
        /* Do not modify. */
        static const TPMT_PUBLIC legacy_rsa = {
                .type = TPM2_ALG_RSA,
                .nameAlg = TPM2_ALG_SHA256,
                .objectAttributes = TPMA_OBJECT_RESTRICTED|TPMA_OBJECT_DECRYPT|TPMA_OBJECT_FIXEDTPM|TPMA_OBJECT_FIXEDPARENT|TPMA_OBJECT_SENSITIVEDATAORIGIN|TPMA_OBJECT_USERWITHAUTH,
                .parameters.rsaDetail = {
                        .symmetric = {
                                .algorithm = TPM2_ALG_AES,
                                .keyBits.aes = 128,
                                .mode.aes = TPM2_ALG_CFB,
                        },
                        .scheme.scheme = TPM2_ALG_NULL,
                        .keyBits = 2048,
                },
        };
 
        assert(ret_template);
 
        if (alg == TPM2_ALG_ECC)
                *ret_template = legacy_ecc;
        else if (alg == TPM2_ALG_RSA)
                *ret_template = legacy_rsa;
        else
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "Unsupported legacy SRK alg: 0x%x", alg);
 
        return 0;
}
 
int tpm2_get_best_attestation_key_template(Tpm2Context *c, TPMT_PUBLIC *ret) {
        assert(c);
        assert(ret);
 
        static const struct {
                TPMI_ALG_PUBLIC alg;
                TPMI_ALG_HASH name_alg;
                TPMT_ASYM_SCHEME asym_scheme;
                union {
                        TPMI_RSA_KEY_BITS rsa_key_bits;
                        TPMI_ECC_CURVE ecc_curve_id;
                } asym_params;
        } template_params[] = {
                {
                        .alg = TPM2_ALG_ECC,
                        .name_alg = TPM2_ALG_SHA384,
                        .asym_scheme = {
                                .scheme = TPM2_ALG_ECDSA,
                                .details.ecdsa.hashAlg = TPM2_ALG_SHA384,
                        },
                        .asym_params.ecc_curve_id = TPM2_ECC_NIST_P384,
                },
                {
                        .alg = TPM2_ALG_ECC,
                        .name_alg = TPM2_ALG_SHA256,
                        .asym_scheme = {
                                .scheme = TPM2_ALG_ECDSA,
                                .details.ecdsa.hashAlg = TPM2_ALG_SHA256,
                        },
                        .asym_params.ecc_curve_id = TPM2_ECC_NIST_P256,
                },
                {
                        .alg = TPM2_ALG_RSA,
                        .name_alg = TPM2_ALG_SHA384,
                        .asym_scheme = {
                                .scheme = TPM2_ALG_RSAPSS,
                                .details.rsapss.hashAlg = TPM2_ALG_SHA384,
                        },
                        .asym_params.rsa_key_bits = 3072,
                },
                {
                        .alg = TPM2_ALG_RSA,
                        .name_alg = TPM2_ALG_SHA384,
                        .asym_scheme = {
                                .scheme = TPM2_ALG_RSASSA,
                                .details.rsassa.hashAlg = TPM2_ALG_SHA384,
                        },
                        .asym_params.rsa_key_bits = 3072,
                },
                {
                        .alg = TPM2_ALG_RSA,
                        .name_alg = TPM2_ALG_SHA256,
                        .asym_scheme = {
                                .scheme = TPM2_ALG_RSAPSS,
                                .details.rsapss.hashAlg = TPM2_ALG_SHA256,
                        },
                        .asym_params.rsa_key_bits = 2048,
                },
                {
                        .alg = TPM2_ALG_RSA,
                        .name_alg = TPM2_ALG_SHA256,
                        .asym_scheme = {
                                .scheme = TPM2_ALG_RSASSA,
                                .details.rsassa.hashAlg = TPM2_ALG_SHA256,
                        },
                        .asym_params.rsa_key_bits = 2048,
                },
        };
 
        FOREACH_ELEMENT(p, template_params) {
                TPMT_PUBLIC template = {
                        .type = p->alg,
                        .nameAlg = p->name_alg,
                        .objectAttributes =
                                TPMA_OBJECT_FIXEDTPM |
                                TPMA_OBJECT_FIXEDPARENT |
                                TPMA_OBJECT_SENSITIVEDATAORIGIN |
                                TPMA_OBJECT_USERWITHAUTH |
                                TPMA_OBJECT_RESTRICTED |
                                TPMA_OBJECT_SIGN_ENCRYPT,
                        .parameters.asymDetail = {
                                .symmetric.algorithm = TPM2_ALG_NULL,
                                .scheme = p->asym_scheme,
                        },
                };
                switch (template.type) {
                case TPM2_ALG_RSA:
                        template.parameters.rsaDetail.keyBits = p->asym_params.rsa_key_bits;
                        break;
                case TPM2_ALG_ECC:
                        template.parameters.eccDetail.curveID = p->asym_params.ecc_curve_id;
                        template.parameters.eccDetail.kdf.scheme = TPM2_ALG_NULL;
                        break;
                default:
                        assert_not_reached();
                }
 
                if (!tpm2_supports_alg(c, template.type))
                        continue;
                if (!tpm2_supports_tpmt_public(c, &template))
                        continue;
                if (template.type == TPM2_ALG_ECC && !tpm2_supports_ecc_curve(c, template.parameters.eccDetail.curveID))
                        continue;
 
                *ret = template;
                return 0;
        }
 
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "No supported attestation key template");
}
 
/* Get a Storage Root Key (SRK) template.
 *
 * The SRK template values are recommended by the "TCG TPM v2.0 Provisioning Guidance" document in section
 * 7.5.1 "Storage Primary Key (SRK) Templates", referencing "TCG EK Credential Profile for TPM Family 2.0".
 * The EK Credential Profile version 2.0 provides only a single template each for RSA and ECC, while later EK
 * Credential Profile versions provide more templates, and keep the original templates as "L-1" (for RSA) and
 * "L-2" (for ECC).
 *
 * https://trustedcomputinggroup.org/resource/tcg-tpm-v2-0-provisioning-guidance
 * https://trustedcomputinggroup.org/resource/http-trustedcomputinggroup-org-wp-content-uploads-tcg-ek-credential-profile
 *
 * These templates are only needed to create a new persistent SRK (or a new transient key that is
 * SRK-compatible). Preferably, the TPM should contain a shared SRK located at the reserved shared SRK handle
 * (see TPM2_SRK_HANDLE in tpm2-util.h, and tpm2_get_srk() below).
 *
 * Returns 0 if the specified algorithm is ECC or RSA, otherwise -EOPNOTSUPP. */
int tpm2_get_srk_template(TPMI_ALG_PUBLIC alg, TPMT_PUBLIC *ret_template) {
        /* The attributes are the same between ECC and RSA templates. This has the changes specified in the
         * Provisioning Guidance document, specifically:
         * TPMA_OBJECT_USERWITHAUTH is added.
         * TPMA_OBJECT_ADMINWITHPOLICY is removed.
         * TPMA_OBJECT_NODA is added. */
        TPMA_OBJECT srk_attributes =
                        TPMA_OBJECT_DECRYPT |
                        TPMA_OBJECT_FIXEDPARENT |
                        TPMA_OBJECT_FIXEDTPM |
                        TPMA_OBJECT_NODA |
                        TPMA_OBJECT_RESTRICTED |
                        TPMA_OBJECT_SENSITIVEDATAORIGIN |
                        TPMA_OBJECT_USERWITHAUTH;
 
        /* The symmetric configuration is the same between ECC and RSA templates. */
        TPMT_SYM_DEF_OBJECT srk_symmetric = {
                .algorithm = TPM2_ALG_AES,
                .keyBits.aes = 128,
                .mode.aes = TPM2_ALG_CFB,
        };
 
        /* Both templates have an empty authPolicy as specified by the Provisioning Guidance document. */
 
        /* From the EK Credential Profile template "L-2". */
        TPMT_PUBLIC srk_ecc = {
                .type = TPM2_ALG_ECC,
                .nameAlg = TPM2_ALG_SHA256,
                .objectAttributes = srk_attributes,
                .parameters.eccDetail = {
                        .symmetric = srk_symmetric,
                        .scheme.scheme = TPM2_ALG_NULL,
                        .curveID = TPM2_ECC_NIST_P256,
                        .kdf.scheme = TPM2_ALG_NULL,
                },
        };
 
        /* From the EK Credential Profile template "L-1". */
        TPMT_PUBLIC srk_rsa = {
                .type = TPM2_ALG_RSA,
                .nameAlg = TPM2_ALG_SHA256,
                .objectAttributes = srk_attributes,
                .parameters.rsaDetail = {
                        .symmetric = srk_symmetric,
                        .scheme.scheme = TPM2_ALG_NULL,
                        .keyBits = 2048,
                },
        };
 
        assert(ret_template);
 
        switch (alg) {
        case TPM2_ALG_ECC:
                *ret_template = srk_ecc;
                return 0;
        case TPM2_ALG_RSA:
                *ret_template = srk_rsa;
                return 0;
        }
 
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "No SRK for algorithm 0x%" PRIx16, alg);
}
 
/* Get the best supported SRK template. ECC is preferred, then RSA. */
int tpm2_get_best_srk_template(Tpm2Context *c, TPMT_PUBLIC *ret_template) {
        TPMT_PUBLIC template;
        int r;
 
        assert(c);
        assert(ret_template);
 
        r = tpm2_get_srk_template(TPM2_ALG_ECC, &template);
        if (r < 0)
                return r;
 
        if (!tpm2_supports_alg(c, TPM2_ALG_ECC))
                log_debug("TPM does not support ECC.");
        else if (!tpm2_supports_ecc_curve(c, template.parameters.eccDetail.curveID))
                log_debug("TPM does not support ECC-NIST-P256 curve.");
        else if (!tpm2_supports_tpmt_public(c, &template))
                log_debug("TPM does not support SRK ECC template L-2.");
        else {
                *ret_template = template;
                return 0;
        }
 
        r = tpm2_get_srk_template(TPM2_ALG_RSA, &template);
        if (r < 0)
                return r;
 
        if (!tpm2_supports_alg(c, TPM2_ALG_RSA))
                log_debug("TPM does not support RSA.");
        else if (!tpm2_supports_tpmt_public(c, &template))
                log_debug("TPM does not support SRK RSA template L-1.");
        else {
                *ret_template = template;
                return 0;
        }
 
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                               "TPM does not support either SRK template L-1 (RSA) or L-2 (ECC).");
}
 
/* Get the SRK. Returns 1 if SRK is found, 0 if there is no SRK, or < 0 on error. Also see
 * tpm2_get_or_create_srk() below. */
int tpm2_get_srk(
                Tpm2Context *c,