From 05db351e119beb53ffc0046509a022ae9c471f15 Mon Sep 17 00:00:00 2001 From: Osmium Sorcerer Date: Wed, 23 Sep 2026 21:31:36 +0000 Subject: Introduce hardware auth keys backed by TPM Hardware keys are created and managed exclusively in the protected environment of the Trusted Platform Module (TPM 2.0), a separate, secure processor isolated from the rest of the system. Keyring provides them as an alternative to established software keys for challenge-response authentication. Software keys, while far more secure than naive passwords, have their limitations. They're stored in a keyring file in an encrypted form and can be extracted and copied. As a result, it's possible to perform unlimited attempts to decrypt them offline. To mitigate such attacks, a memory-hard key derivation function must be used to derive the decryption key, and the passhprase itself must still be sufficiently strong because a small search space will definitely be exhausted. A side effect of this is a massive latency spike and potentially disruptive peak memory usage. Hardware keys, by design, are non-exportable. Total system compromise won't lead to key exfiltration due to TPM having no such functionality, and TPM's tamper resistance makes extraction of secrets infeasible even with physical access to the machine (if the TPM is genuine). PIN that is used to protect hardware keys is validated by the TPM itself, which also locks itself out after too many failed attempts. This lockout cannot be overridden without either issuing a lockout clear command with authorization value or resetting the TPM outright, erasing all keys stored in it. Because of this, low-entropy secrets (such as six-digit PIN) can provide sufficient security. Their only limitation is the flipside of their strength: because they're non-exportable, you can't back them up and move them between devices. Once created, a hardware key is bound to the machine, unlike software keys which are usable everywhere as long as you have keyring.cbor. Hardware keys require TPM 2.0 and an API to communicate with it. Implementations are provided for: - Windows via Cryptography API: Next Generation (CNG) with Microsoft Platform Crypto Provider. - Unix systems with TPM2 Software Stack (TSS2). Windows scopes keys to a Windows user, so you likely won't be able to move them across users or installations within the same machine. The keys will remain on the system with "SoF_Auth_" prefix and a UUID so you can locate them in your key registry. They'll additionally have the name you set at key creation. Unix might require additoinal user permissions to access the TPM. For example, adding a user to the `tss` group on Linux. The platform input differs. Windows can take a user-friendly key name to display, which is a good feature considering weird requirement of Windows that key names (actual identifiers) must be unique strings, for which I use UUIDs. Unix has no concept of key names or identifiers, but it has to provide PIN to the TPM directly. Windows uses its own PIN prompt from Windows Security UI that's disconnected from the application. This is somewhat awkward because it's modeless. Also, a ridiciulous quirk of Windows CNG API makes it so key handle creation returns the same `NTE_INVALID_HANDLE` error no matter what kind of error it was. In particular, it's impossible to differentiate between the operation failing due to the TPM lockout, or the user voluntarily closing the dialog. The user will always see "hardware locked out" error message. Brilliant API design. The PIN is implemented as a direct authorization value for keys, so it might be vulnerable to the bus sniffing attack if the PIN is traveling in clear between CPU and TPM. Though, a hypothetical adversary who's sitting with a logic analyzer hooked up to your motherboard as you type the PIN will realistically have easier means to log your keystrokes. TPM is capable of remote attestation to prove its authenticity, but I chose to avoid it to protect users' privacy (there's anonymous attestation, but it's not always practical because it requires special CAs) and avoid significant implementation complexity on the server that the attestation entails, such as parsing and validating certificate chains. Because of the unfortunate reality, TPMs overwhelmingly have no support for X25519 (the key exchange algorithm used in software keys). It was added in a recent revision, but it's yet to be implemented, and only on the newest machines. You can't upgrade the TPM hardware, so we have to compromise. Instead, elliptic curve Diffie-Hellman over P-256 curve has been selected, which is also the default curve used in WebAuthn (passkey) protocol. It's ubiquitous, supported by every single TPM 2.0, and secure if reasonably implemented. Keys don't take up limited nonvolatile memory of the TPM. Every reference to TPM objects necessary to perform authentication is stored on disk, and keys and contexts are recreated on every operation and cleared from memory afterwards. For the client public key format, I *only* use compressed P-256 points (1-byte parity of y coordinate followed by a full 32-byte x coordinate) for robustness. Their designated identification byte is 0x33, and they start with the letter M when base64url-encoded. --- src/tpm/tpm_tss.c | 244 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 244 insertions(+) create mode 100644 src/tpm/tpm_tss.c (limited to 'src/tpm/tpm_tss.c') diff --git a/src/tpm/tpm_tss.c b/src/tpm/tpm_tss.c new file mode 100644 index 0000000..880fa32 --- /dev/null +++ b/src/tpm/tpm_tss.c @@ -0,0 +1,244 @@ +// Copyright 2026 Osmium Sorcerer +// SPDX-License-Identifier: MIT + +#include + +#include +#include + +#include "tpm.h" + +// Storage Key: asymmetric scheme is NULL, symmetric is defined and shall +// use CFB mode. The key is restricted. +static const TPM2B_PUBLIC primary_template = { + .publicArea = { + .type = TPM2_ALG_ECC, + .nameAlg = TPM2_ALG_SHA256, + .objectAttributes = + TPMA_OBJECT_FIXEDTPM | + TPMA_OBJECT_FIXEDPARENT | + TPMA_OBJECT_SENSITIVEDATAORIGIN | + TPMA_OBJECT_USERWITHAUTH | + TPMA_OBJECT_RESTRICTED | + TPMA_OBJECT_DECRYPT, + .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, + }, + }, +}; + +// Symmetric algorithm is NULL for a nonrestricted key. This is the template +// for actual key exchange keys under the primary storage key, accessed with a +// user authentication value. +// There is TPM2_ALG_ECDH scheme, but it requires KDF. +static const TPM2B_PUBLIC ecdh_key_template = { + .publicArea = { + .type = TPM2_ALG_ECC, + .nameAlg = TPM2_ALG_SHA256, + .objectAttributes = + TPMA_OBJECT_FIXEDTPM | + TPMA_OBJECT_FIXEDPARENT | + TPMA_OBJECT_SENSITIVEDATAORIGIN | + TPMA_OBJECT_USERWITHAUTH | + TPMA_OBJECT_DECRYPT, + .parameters.eccDetail = { + .symmetric.algorithm = TPM2_ALG_NULL, + .scheme.scheme = TPM2_ALG_NULL, + .curveID = TPM2_ECC_NIST_P256, + .kdf.scheme = TPM2_ALG_NULL, + }, + }, +}; + +static const TPM2B_SENSITIVE_CREATE empty_in_sensitive = { 0 }; +static const TPM2B_DATA empty_outside_info = { 0 }; +static const TPML_PCR_SELECTION empty_creation_pcr = { 0 }; + +// Make sure TPM 2.0 is present and working correctly before using it. +stkb_rc tpm2_init(void) +{ + int ret = 0; + ESYS_CONTEXT *ctx; + if (Esys_Initialize(&ctx, NULL, NULL) != TSS2_RC_SUCCESS) + return STKB_TPM_UNAVAILABLE; + // Simple self-test. Tests only what's necessary instead of all internal + // functions and operations, doesn't disrupt the system. + ret = Esys_SelfTest(ctx, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, TPM2_NO); + Esys_Finalize(&ctx); + if (ret != TSS2_RC_SUCCESS) + return STKB_TPM_UNAVAILABLE; + return STKB_SUCCESS; +} + +static TSS2_RC tpm2_setup_primary(ESYS_CONTEXT **ctx, ESYS_TR *primary_handle) +{ + TSS2_RC rc = Esys_Initialize(ctx, NULL, NULL); + if (rc != TSS2_RC_SUCCESS) + return rc; + rc = Esys_CreatePrimary(*ctx, ESYS_TR_RH_OWNER, ESYS_TR_PASSWORD, + ESYS_TR_NONE, ESYS_TR_NONE, &empty_in_sensitive, + &primary_template, &empty_outside_info, + &empty_creation_pcr, primary_handle, NULL, NULL, + NULL, NULL); + if (rc != TSS2_RC_SUCCESS) + Esys_Finalize(ctx); + return rc; +} + +static stkb_rc decode_tpm_rc(TSS2_RC tpm_rc) +{ + // Check that the code is from the TPM itself rather than ESAPI, otherwise + // return a generic error as we're not interested in details. + if ((tpm_rc & TSS2_RC_LAYER_MASK) != TSS2_TPM_RC_LAYER) + return STKB_ERROR; + + // Format-One return codes are composite and in particular have an added + // parameter value that is irrelevant to the nature of the error, clear it. + if (tpm_rc & TPM2_RC_FMT1) + tpm_rc &= ~TPM2_RC_N_MASK; + + switch (tpm_rc) { + case TPM2_RC_BAD_AUTH: + case TPM2_RC_AUTH_FAIL: + return STKB_AUTH_FAILURE; + case TPM2_RC_LOCKOUT: + return STKB_LOCKOUT; + default: + return STKB_ERROR; + } +} + +stkb_rc tpm2_keygen(uint8_t *out_pub, uint8_t *out_buffer, size_t buffer_size, + size_t *written, stkb_user_input input) +{ + if (input.pin_len > TPM2_SHA256_DIGEST_SIZE) + return STKB_BAD_PIN; + TPM2B_SENSITIVE_CREATE in_sensitive = { 0 }; + memcpy(in_sensitive.sensitive.userAuth.buffer, input.pin, input.pin_len); + in_sensitive.sensitive.userAuth.size = (UINT16)input.pin_len; + ESYS_CONTEXT *ctx; + ESYS_TR primary_handle; + stkb_rc ret = STKB_ERROR; + if (tpm2_setup_primary(&ctx, &primary_handle) != TSS2_RC_SUCCESS) + return ret; + TPM2B_PRIVATE *ecdh_priv = NULL; + TPM2B_PUBLIC *ecdh_pub = NULL; + TSS2_RC rc = Esys_Create(ctx, primary_handle, ESYS_TR_PASSWORD, + ESYS_TR_NONE, ESYS_TR_NONE, &in_sensitive, + &ecdh_key_template, &empty_outside_info, + &empty_creation_pcr, &ecdh_priv, &ecdh_pub, NULL, + NULL, NULL); + if (rc != TSS2_RC_SUCCESS) { + ret = decode_tpm_rc(rc); + goto exit; + } + + // TPM 2.0 Library, Part 1, 44.5.3 Padding: + // + // > In ECC points returned by the TPM, the x and y values, if non-empty, + // > are required to be the size of their associated curve (e.g., 32 bytes + // > for NIST P-256). + if (ecdh_pub->publicArea.unique.ecc.x.size != 32 || + ecdh_pub->publicArea.unique.ecc.y.size != 32) + goto exit; + + // Compress the public key: knowing x, it's enough to only encode parity of + // y to fully reconstruct the point. + if (ecdh_pub->publicArea.unique.ecc.y.buffer[31] & 1) + out_pub[0] = 0x03; + else + out_pub[0] = 0x02; + memcpy(out_pub + 1, ecdh_pub->publicArea.unique.ecc.x.buffer, 32); + + // Serialize both structures, we'll need them for Load. + size_t off = 0; + if (Tss2_MU_TPM2B_PRIVATE_Marshal(ecdh_priv, out_buffer, buffer_size, &off) != + TSS2_RC_SUCCESS) + goto exit; + if (Tss2_MU_TPM2B_PUBLIC_Marshal(ecdh_pub, out_buffer, buffer_size - off, + &off) != TSS2_RC_SUCCESS) + goto exit; + + *written = off; + ret = STKB_SUCCESS; + +exit: + Esys_Free(ecdh_priv); + Esys_Free(ecdh_pub); + Esys_FlushContext(ctx, primary_handle); + Esys_Finalize(&ctx); + return ret; +} + +// pk is an uncompressed 64-byte point (x || y) of the peer. +stkb_rc tpm2_compute_ss(uint8_t *ss, const uint8_t *blob, size_t blob_len, + const uint8_t *pk, stkb_user_input input) +{ + if (input.pin_len > TPM2_SHA256_DIGEST_SIZE) + return STKB_BAD_PIN; + TPM2B_AUTH auth_value = { 0 }; + memcpy(auth_value.buffer, input.pin, input.pin_len); + auth_value.size = (UINT16)input.pin_len; + + ESYS_CONTEXT *ctx; + ESYS_TR primary_handle; + stkb_rc ret = STKB_ERROR; + if (tpm2_setup_primary(&ctx, &primary_handle) != TSS2_RC_SUCCESS) + return ret; + + ESYS_TR ecdh_key_handle = ESYS_TR_NONE; + TPM2B_PRIVATE ecdh_priv; + TPM2B_PUBLIC ecdh_pub; + TPM2B_ECC_POINT *shared_point = NULL; + size_t off = 0; + if (Tss2_MU_TPM2B_PRIVATE_Unmarshal(blob, blob_len, &off, &ecdh_priv) != + TSS2_RC_SUCCESS) + goto exit; + if (Tss2_MU_TPM2B_PUBLIC_Unmarshal(blob, blob_len, &off, &ecdh_pub) != + TSS2_RC_SUCCESS) + goto exit; + + TSS2_RC rc = Esys_Load(ctx, primary_handle, ESYS_TR_PASSWORD, ESYS_TR_NONE, + ESYS_TR_NONE, &ecdh_priv, &ecdh_pub, + &ecdh_key_handle); + if (rc != TSS2_RC_SUCCESS) { + ret = decode_tpm_rc(rc); + goto exit; + } + + if (Esys_TR_SetAuth(ctx, ecdh_key_handle, &auth_value) != TSS2_RC_SUCCESS) + goto exit; + + TPM2B_ECC_POINT in_point; + in_point.point.x.size = 32; + in_point.point.y.size = 32; + memcpy(in_point.point.x.buffer, pk, 32); + memcpy(in_point.point.y.buffer, pk + 32, 32); + rc = Esys_ECDH_ZGen(ctx, ecdh_key_handle, ESYS_TR_PASSWORD, ESYS_TR_NONE, + ESYS_TR_NONE, &in_point, &shared_point); + if (rc != TSS2_RC_SUCCESS) { + ret = decode_tpm_rc(rc); + goto exit; + } + + // Deliver the x coordinate of the shared point. + memcpy(ss, shared_point->point.x.buffer, 32); + + ret = STKB_SUCCESS; + +exit: + Esys_Free(shared_point); + if (primary_handle != ESYS_TR_NONE) + Esys_FlushContext(ctx, primary_handle); + if (ecdh_key_handle != ESYS_TR_NONE) + Esys_FlushContext(ctx, ecdh_key_handle); + Esys_Finalize(&ctx); + return ret; +} -- cgit