From 47cf7db1cc2883628b8b2ea24e24f31811bdaf36 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 16:12:37 -0800 Subject: [PATCH 001/124] F-16225 - Use only the IDENTITY label for the fwTPM RSA credential seed --- src/fwtpm/fwtpm_command.c | 38 +--------------- src/fwtpm/fwtpm_crypto.c | 2 +- tests/fwtpm_unit_tests.c | 92 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 37 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 09adb2795..a5a6d5dde 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -19208,8 +19208,6 @@ static TPM_RC FwCmd_MakeCredential(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_DECLARE_BUF(encCred, FWTPM_MAX_NV_DATA + 2); word32 encCredSz = 0; byte outerHmac[TPM_MAX_DIGEST_SIZE]; - byte oaepLabel[64]; - int oaepLabelSz = 0; FWTPM_ALLOC_BUF(encSeed, FWTPM_MAX_PUB_BUF); FWTPM_ALLOC_BUF(encCred, FWTPM_MAX_NV_DATA + 2); @@ -19297,25 +19295,10 @@ static TPM_RC FwCmd_MakeCredential(FWTPM_CTX* ctx, TPM2_Packet* cmd, } #endif - /* Build OAEP label: "IDENTITY\0" + objectName */ - if (rc == 0) { - XMEMCPY(oaepLabel, "IDENTITY", 8); - oaepLabelSz = 8; - oaepLabel[oaepLabelSz++] = 0x00; - if (objectName.size + oaepLabelSz > (int)sizeof(oaepLabel)) { - rc = TPM_RC_SIZE; - } - else { - XMEMCPY(oaepLabel + oaepLabelSz, objectName.name, - objectName.size); - oaepLabelSz += objectName.size; - } - } - /* Generate seed and encrypt to key's public key */ if (rc == 0) { rc = FwEncryptSeed(ctx, keyObj, - oaepLabel, oaepLabelSz, "IDENTITY", + (const byte*)"IDENTITY", 9, "IDENTITY", seed, (int)sizeof(seed), &seedSz, encSeed, FWTPM_MAX_PUB_BUF, &encSeedSz); } @@ -19407,8 +19390,6 @@ static TPM_RC FwCmd_ActivateCredential(FWTPM_CTX* ctx, TPM2_Packet* cmd, byte hmacKey[TPM_MAX_DIGEST_SIZE]; int symKeySz = 0; int hmacKeySz = 0; - byte oaepLabel[64]; - int oaepLabelSz = 0; byte credOut[sizeof(TPMU_HA)]; UINT16 credSz = 0; TPM2B_NAME* objName; @@ -19519,26 +19500,11 @@ static TPM_RC FwCmd_ActivateCredential(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } - /* Build OAEP label: "IDENTITY\0" + activateObj->name */ - if (rc == 0) { - objName = &activateObj->name; - XMEMCPY(oaepLabel, "IDENTITY", 8); - oaepLabelSz = 8; - oaepLabel[oaepLabelSz++] = 0x00; - if (objName->size + oaepLabelSz > (int)sizeof(oaepLabel)) { - rc = TPM_RC_SIZE; - } - else { - XMEMCPY(oaepLabel + oaepLabelSz, objName->name, objName->size); - oaepLabelSz += objName->size; - } - } - /* Decrypt seed using keyHandle's private key */ if (rc == 0) { rc = FwDecryptSeed(ctx, keyObj, secretBuf, secretSz, - oaepLabel, oaepLabelSz, "IDENTITY", + (const byte*)"IDENTITY", 9, "IDENTITY", seed, (int)sizeof(seed), &seedSzInt); } diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index d7256de51..cb7d9737c 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -2776,7 +2776,7 @@ int FwUnwrapContextBlob(FWTPM_CTX* ctx, UINT64 seq, byte ctxType, /* --- Shared helper: decrypt encrypted seed with RSA OAEP or ECC ECDH+KDFe --- * Used by Import ("DUPLICATE"), StartAuthSession ("SECRET"), - * and ActivateCredential ("IDENTITY\0" + objectName). */ + * and ActivateCredential ("IDENTITY"). */ TPM_RC FwDecryptSeed(FWTPM_CTX* ctx, const FWTPM_Object* keyObj, const byte* encSeedBuf, UINT16 encSeedSz, diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 31fc2bc66..730098579 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -16967,6 +16967,94 @@ static void test_fwtpm_rewrap_null_newparent_rejected(void) } #endif /* !FWTPM_NO_KEY_MIGRATION */ +#if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) && \ + !defined(FWTPM_NO_CREDENTIAL) +/* The RSA credential seed is OAEP-wrapped with the label "IDENTITY" and its + * terminating zero only (Part 1 Sec.24); the object Name enters through the + * KDFa "STORAGE" derivation, not the label. */ +static void test_fwtpm_rsa_credential_oaep_label(void) +{ + FWTPM_CTX ctx; + FWTPM_Object* ek = NULL; + UINT32 ekH; + byte credential[16]; + byte blob[sizeof(TPM2B_ID_OBJECT)]; + byte secret[sizeof(TPM2B_ENCRYPTED_SECRET)]; + byte seed[TPM_MAX_DIGEST_SIZE]; + UINT16 blobSz, secretSz, outSz; + int i, pos, cmdSz, rspSize = 0, seedSz = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + memset(credential, 0xC7, sizeof(credential)); + + cmdSz = BuildCreatePrimaryCmdEx(gCmd, TPM_ALG_RSA, 0x00030472); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + ekH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + for (i = 0; i < FWTPM_MAX_OBJECTS; i++) { + if (ctx.objects[i].used && ctx.objects[i].handle == ekH) { + ek = &ctx.objects[i]; + } + } + AssertNotNull(ek); + if (ek->name.size == 0) { + FwComputeObjectName(ek); + } + + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_MakeCredential); + PutU32BE(gCmd + pos, ekH); pos += 4; + PutU16BE(gCmd + pos, (UINT16)sizeof(credential)); pos += 2; + memcpy(gCmd + pos, credential, sizeof(credential)); + pos += (int)sizeof(credential); + PutU16BE(gCmd + pos, ek->name.size); pos += 2; + memcpy(gCmd + pos, ek->name.name, ek->name.size); pos += ek->name.size; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pos = TPM2_HEADER_SIZE; + blobSz = GetU16BE(gRsp + pos); pos += 2; + AssertIntEQ(blobSz <= sizeof(blob), 1); + memcpy(blob, gRsp + pos, blobSz); pos += blobSz; + secretSz = GetU16BE(gRsp + pos); pos += 2; + AssertIntEQ(secretSz <= sizeof(secret), 1); + memcpy(secret, gRsp + pos, secretSz); + + AssertIntEQ(FwDecryptSeed(&ctx, ek, secret, secretSz, + (const byte*)"IDENTITY", 9, "IDENTITY", + seed, (int)sizeof(seed), &seedSz), TPM_RC_SUCCESS); + AssertIntGT(seedSz, 0); + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ActivateCredential); + PutU32BE(gCmd + pos, ekH); pos += 4; /* activateHandle */ + PutU32BE(gCmd + pos, ekH); pos += 4; /* keyHandle */ + PutU32BE(gCmd + pos, 18); pos += 4; + for (i = 0; i < 2; i++) { + PutU32BE(gCmd + pos, TPM_RS_PW); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; + gCmd[pos++] = 0; + PutU16BE(gCmd + pos, 0); pos += 2; + } + PutU16BE(gCmd + pos, blobSz); pos += 2; + memcpy(gCmd + pos, blob, blobSz); pos += blobSz; + PutU16BE(gCmd + pos, secretSz); pos += 2; + memcpy(gCmd + pos, secret, secretSz); pos += secretSz; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pos = TPM2_HEADER_SIZE + 4; + outSz = GetU16BE(gRsp + pos); pos += 2; + AssertIntEQ((int)outSz, (int)sizeof(credential)); + AssertIntEQ(XMEMCMP(gRsp + pos, credential, sizeof(credential)), 0); + + FlushHandle(&ctx, ekH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("RSA credential OAEP label:", 0); +} +#endif /* !NO_RSA && WOLFSSL_KEY_GEN && !FWTPM_NO_CREDENTIAL */ + #if !defined(FWTPM_NO_KEY_MIGRATION) && !defined(FWTPM_NO_POLICY) static TPM_RC SendDuplicateToNullCmd(FWTPM_CTX* ctx, UINT32 objH, UINT32 sessH, UINT16 symAlg) @@ -25338,6 +25426,10 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif test_fwtpm_read_public(); test_fwtpm_loadexternal_symcipher_bad_keysize_rejected(); +#if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) && \ + !defined(FWTPM_NO_CREDENTIAL) + test_fwtpm_rsa_credential_oaep_label(); +#endif #ifndef FWTPM_NO_KEY_MIGRATION test_fwtpm_rewrap_null_newparent_rejected(); #ifndef FWTPM_NO_POLICY From 50208904976c9c41d5648c104b5823deb2dbcdee Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 16:16:16 -0800 Subject: [PATCH 002/124] F-16241 - Reject non-boolean TPMI_YES_NO in fwTPM ClearControl and SelfTest --- src/fwtpm/fwtpm_command.c | 6 ++++++ tests/fwtpm_unit_tests.c | 31 +++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index a5a6d5dde..80e9998b6 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -1510,6 +1510,9 @@ static TPM_RC FwCmd_SelfTest(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, if (rc == 0) { TPM2_Packet_ParseU8(cmd, &fullTest); + if (fullTest > 1) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_1; + } #ifdef DEBUG_WOLFTPM printf("fwTPM: SelfTest(fullTest=%d)\n", fullTest); @@ -7064,6 +7067,9 @@ static TPM_RC FwCmd_ClearControl(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { TPM2_Packet_ParseU8(cmd, &disable); + if (disable > 1) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_1; + } } if (rc == 0 && authHandle != TPM_RH_PLATFORM && diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 730098579..72399de2a 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -15727,6 +15727,36 @@ static void test_fwtpm_clear_control_nv_failure(void) fwtpm_pass("ClearControl NV failure rollback:", 0); } +/* A TPMI_YES_NO other than 0 or 1 is TPM_RC_VALUE; lockout authorization + * must not be able to disable Clear by sending 2. */ +static void test_fwtpm_yes_no_range(void) +{ + FWTPM_CTX ctx; + int rspSize, pos; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ClearControl); + PutU32BE(gCmd + pos, TPM_RH_LOCKOUT); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + gCmd[pos++] = 2; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_VALUE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(ctx.disableClear, 0); + + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 11, TPM_CC_SelfTest); + gCmd[pos++] = 2; + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_VALUE | TPM_RC_P | TPM_RC_1); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("TPMI_YES_NO range:", 0); +} + /* State-changing handlers that persist to NV must report failure, not * success, when the journal write fails. Representative commands from the * clock, NV-index and hierarchy-auth families run on one context; @@ -25636,6 +25666,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_nv_setbits_truncated(); test_fwtpm_nv_define_type_sizes(); test_fwtpm_clear_control_nv_failure(); + test_fwtpm_yes_no_range(); test_fwtpm_state_change_nv_failure(); test_fwtpm_nv_append_atomic(); test_fwtpm_nv_compaction_commit(); From 8524fb8015ac0b30208ccf7456791f3d718c25f6 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 16:27:10 -0800 Subject: [PATCH 003/124] F-18067 - Allow ownerAuth on platform-created fwTPM NV indexes with OWNERREAD or OWNERWRITE --- src/fwtpm/fwtpm_command.c | 4 --- tests/fwtpm_unit_tests.c | 71 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 4 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 80e9998b6..b24d9652f 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -16651,8 +16651,6 @@ static TPM_RC FwNvCheckAccess(TPM_HANDLE authHandle, else if (authHandle == TPM_RH_OWNER) { if (!(attributes & TPMA_NV_OWNERWRITE)) return TPM_RC_NV_AUTHORIZATION; - if (attributes & TPMA_NV_PLATFORMCREATE) - return TPM_RC_NV_AUTHORIZATION; } else if (authHandle == (TPM_HANDLE)nvHandle) { UINT32 requiredAttr = authIsPolicy ? @@ -16672,8 +16670,6 @@ static TPM_RC FwNvCheckAccess(TPM_HANDLE authHandle, else if (authHandle == TPM_RH_OWNER) { if (!(attributes & TPMA_NV_OWNERREAD)) return TPM_RC_NV_AUTHORIZATION; - if (attributes & TPMA_NV_PLATFORMCREATE) - return TPM_RC_NV_AUTHORIZATION; } else if (authHandle == (TPM_HANDLE)nvHandle) { UINT32 requiredAttr = authIsPolicy ? diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 72399de2a..9ac2ae47f 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -15757,6 +15757,76 @@ static void test_fwtpm_yes_no_range(void) fwtpm_pass("TPMI_YES_NO range:", 0); } +static TPM_RC SendNvOwnerAccessCmd(FWTPM_CTX* ctx, UINT32 nvIndex, + int isWrite) +{ + int rspSize = 0; + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + isWrite ? TPM_CC_NV_Write : TPM_CC_NV_Read); + + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; /* authHandle */ + PutU32BE(gCmd + pos, nvIndex); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 1); pos += 2; + if (isWrite) { + gCmd[pos++] = 0x5A; + } + PutU16BE(gCmd + pos, 0); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* OWNERREAD and OWNERWRITE alone decide whether ownerAuth may access an + * index; TPMA_NV_PLATFORMCREATE only governs who defines and undefines it. */ +static void test_fwtpm_nv_owner_access_platform_index(void) +{ + FWTPM_CTX ctx; + UINT32 ownerIdx = 0x01400081; + UINT32 ppIdx = 0x01400082; + int i, pos, cmdSz, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmdSz = BuildNvDefineCmdEx(gCmd, ownerIdx, 1, TPMA_NV_PLATFORMCREATE | + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA, + NULL, 0, NULL, 0); + PutU32BE(gCmd + TPM2_HEADER_SIZE, TPM_RH_PLATFORM); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerAccessCmd(&ctx, ownerIdx, 1), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerAccessCmd(&ctx, ownerIdx, 0), TPM_RC_SUCCESS); + + cmdSz = BuildNvDefineCmdEx(gCmd, ppIdx, 1, TPMA_NV_PLATFORMCREATE | + TPMA_NV_PPWRITE | TPMA_NV_PPREAD | TPMA_NV_NO_DA, + NULL, 0, NULL, 0); + PutU32BE(gCmd + TPM2_HEADER_SIZE, TPM_RH_PLATFORM); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerAccessCmd(&ctx, ppIdx, 1), + TPM_RC_NV_AUTHORIZATION); + AssertIntEQ(SendNvOwnerAccessCmd(&ctx, ppIdx, 0), + TPM_RC_NV_AUTHORIZATION); + + for (i = 0; i < 2; i++) { + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + TPM_CC_NV_UndefineSpace); + PutU32BE(gCmd + pos, TPM_RH_PLATFORM); pos += 4; + PutU32BE(gCmd + pos, (i == 0) ? ownerIdx : ppIdx); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + } + + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV owner access to platform index:", 0); +} + /* State-changing handlers that persist to NV must report failure, not * success, when the journal write fails. Representative commands from the * clock, NV-index and hierarchy-auth families run on one context; @@ -25667,6 +25737,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_nv_define_type_sizes(); test_fwtpm_clear_control_nv_failure(); test_fwtpm_yes_no_range(); + test_fwtpm_nv_owner_access_platform_index(); test_fwtpm_state_change_nv_failure(); test_fwtpm_nv_append_atomic(); test_fwtpm_nv_compaction_commit(); From d913b354f91b6858b95e7e910796f753ca872471 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 16:30:07 -0800 Subject: [PATCH 004/124] F-16219 - Require the fwTPM Duplicate policy session to be bound to TPM_CC_Duplicate --- src/fwtpm/fwtpm_command.c | 12 ++++++++++ tests/fwtpm_unit_tests.c | 47 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index b24d9652f..35096456f 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -23568,6 +23568,18 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); return TPM_RC_SUCCESS; } + if ((entry->encDecFlags & FW_CMD_FLAG_AUTH_DUP) && cmdAuthCnt > 0 && + cmdAuths[0].sess != NULL && + cmdAuths[0].sess->commandCode != cmdCode) { + #ifdef DEBUG_WOLFTPM + printf("fwTPM: DUP role requires PolicyCommandCode (CC=0x%x)\n", + cmdCode); + #endif + *rspSize = FwBuildErrorResponse(rspBuf, rspCap, + TPM_ST_NO_SESSIONS, TPM_RC_POLICY_CC); + TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); + return TPM_RC_SUCCESS; + } /* ADMIN-role authorization requires a policy session when the object * sets adminWithPolicy, and always for an NV index. A policy used for diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 9ac2ae47f..573386971 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -17238,6 +17238,52 @@ static void test_fwtpm_duplicate_encrypted_needs_new_parent(void) FWTPM_Cleanup(&ctx); fwtpm_pass("Duplicate encryptedDuplication needs new parent:", 0); } +/* The DUP role needs a policy bound to TPM_CC_Duplicate; a policy written + * for ordinary use of the object must not also authorize exporting it. */ +static void test_fwtpm_duplicate_needs_command_code(void) +{ + FWTPM_CTX ctx; + FWTPM_Object* obj = NULL; + FWTPM_Session* sess = NULL; + UINT32 keyH, sessH; + int i; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); +#ifdef HAVE_ECC + keyH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); +#else + keyH = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); +#endif + AssertIntNE(keyH, 0); + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(sessH, 0); + + for (i = 0; i < FWTPM_MAX_OBJECTS; i++) { + if (ctx.objects[i].used && ctx.objects[i].handle == keyH) { + obj = &ctx.objects[i]; + } + } + for (i = 0; i < FWTPM_MAX_SESSIONS; i++) { + if (ctx.sessions[i].used && ctx.sessions[i].handle == sessH) { + sess = &ctx.sessions[i]; + } + } + AssertNotNull(obj); + AssertNotNull(sess); + obj->pub.objectAttributes &= + ~(TPMA_OBJECT_fixedTPM | TPMA_OBJECT_fixedParent); + XMEMCPY(&obj->pub.authPolicy, &sess->policyDigest, + sizeof(obj->pub.authPolicy)); + + AssertIntEQ(SendDuplicateToNullCmd(&ctx, keyH, sessH, TPM_ALG_NULL), + TPM_RC_POLICY_CC); + + FlushHandle(&ctx, sessH); + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Duplicate needs PolicyCommandCode:", 0); +} #endif /* !FWTPM_NO_KEY_MIGRATION && !FWTPM_NO_POLICY */ /* ================================================================== */ @@ -25534,6 +25580,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_rewrap_null_newparent_rejected(); #ifndef FWTPM_NO_POLICY test_fwtpm_duplicate_encrypted_needs_new_parent(); + test_fwtpm_duplicate_needs_command_code(); #endif #endif /* !FWTPM_NO_KEY_MIGRATION */ test_fwtpm_evict_control(); From 82cc0798e0005638ef5163c38cd32b4fa3169f02 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 17:54:51 -0800 Subject: [PATCH 005/124] Return TPM_RC_POLICY_FAIL when an fwTPM ADMIN or DUP policy session has no command code --- src/fwtpm/fwtpm_command.c | 10 ++++++---- tests/fwtpm_unit_tests.c | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 35096456f..5a4ad2a9e 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -23575,8 +23575,9 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, printf("fwTPM: DUP role requires PolicyCommandCode (CC=0x%x)\n", cmdCode); #endif - *rspSize = FwBuildErrorResponse(rspBuf, rspCap, - TPM_ST_NO_SESSIONS, TPM_RC_POLICY_CC); + *rspSize = FwBuildErrorResponse(rspBuf, rspCap, TPM_ST_NO_SESSIONS, + (cmdAuths[0].sess->commandCode == 0) ? + TPM_RC_POLICY_FAIL : TPM_RC_POLICY_CC); TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); return TPM_RC_SUCCESS; } @@ -23631,8 +23632,9 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, printf("fwTPM: ADMIN role requires PolicyCommandCode (CC=0x%x)\n", cmdCode); #endif - *rspSize = FwBuildErrorResponse(rspBuf, rspCap, - TPM_ST_NO_SESSIONS, TPM_RC_POLICY_CC); + *rspSize = FwBuildErrorResponse(rspBuf, rspCap, TPM_ST_NO_SESSIONS, + (adminSess->commandCode == 0) ? + TPM_RC_POLICY_FAIL : TPM_RC_POLICY_CC); TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); return TPM_RC_SUCCESS; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 573386971..61b457d36 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -13245,7 +13245,7 @@ static void test_fwtpm_admin_authorization_requires_policy(void) PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_POLICY_CC); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_POLICY_FAIL); pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_PolicyCommandCode); @@ -17277,7 +17277,7 @@ static void test_fwtpm_duplicate_needs_command_code(void) sizeof(obj->pub.authPolicy)); AssertIntEQ(SendDuplicateToNullCmd(&ctx, keyH, sessH, TPM_ALG_NULL), - TPM_RC_POLICY_CC); + TPM_RC_POLICY_FAIL); FlushHandle(&ctx, sessH); FlushHandle(&ctx, keyH); From 5ebe7138b56c2cf13d2db62cbbb5f3d3234f2865 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 17:56:33 -0800 Subject: [PATCH 006/124] F-17157 - Drop the command-parameter decrypt flag from fwTPM EncryptDecrypt --- src/fwtpm/fwtpm_command.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 5a4ad2a9e..2d5cce31e 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -22242,7 +22242,7 @@ static const FWTPM_CMD_ENTRY fwCmdTable[] = { /* --- Symmetric --- */ #ifndef NO_AES #ifndef FWTPM_NO_SYM_ENCRYPT - { TPM_CC_EncryptDecrypt, FwCmd_EncryptDecrypt, 1, 1, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, + { TPM_CC_EncryptDecrypt, FwCmd_EncryptDecrypt, 1, 1, 0, FW_CMD_FLAG_DEC }, { TPM_CC_EncryptDecrypt2, FwCmd_EncryptDecrypt2, 1, 1, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, #endif /* !FWTPM_NO_SYM_ENCRYPT */ #endif From 4afe4d34d47382e74a9e0b45d9621bba38706934 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 17:57:26 -0800 Subject: [PATCH 007/124] F-16132 - Mark every fwTPM command whose first parameter is a TPM2B for parameter encryption --- src/fwtpm/fwtpm_command.c | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 2d5cce31e..38e5c7cb3 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -22105,7 +22105,7 @@ static const FWTPM_CMD_ENTRY fwCmdTable[] = { { TPM_CC_Shutdown, FwCmd_Shutdown, 0, 0, 0, FW_CMD_MOD_NV }, { TPM_CC_SelfTest, FwCmd_SelfTest, 0, 0, 0, FW_CMD_MOD_NV }, { TPM_CC_IncrementalSelfTest, FwCmd_IncrementalSelfTest, 0, 0, 0, FW_CMD_MOD_NV }, - { TPM_CC_GetTestResult, FwCmd_GetTestResult, 0, 0, 0, 0 }, + { TPM_CC_GetTestResult, FwCmd_GetTestResult, 0, 0, 0, FW_CMD_FLAG_DEC }, { TPM_CC_GetRandom, FwCmd_GetRandom, 0, 0, 0, FW_CMD_FLAG_DEC }, { TPM_CC_StirRandom, FwCmd_StirRandom, 0, 0, 0, FW_CMD_FLAG_ENC | FW_CMD_MOD_NV }, { TPM_CC_GetCapability, FwCmd_GetCapability, 0, 0, 0, 0 }, @@ -22152,7 +22152,7 @@ static const FWTPM_CMD_ENTRY fwCmdTable[] = { { TPM_CC_ObjectChangeAuth, FwCmd_ObjectChangeAuth, 2, 1, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC | FW_CMD_FLAG_AUTH_ADMIN | FW_CMD_RO_DENY }, { TPM_CC_Load, FwCmd_Load, 1, 1, 1, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, { TPM_CC_Sign, FwCmd_Sign, 1, 1, 0, FW_CMD_FLAG_ENC }, - { TPM_CC_VerifySignature, FwCmd_VerifySignature, 1, 0, 0, 0 }, + { TPM_CC_VerifySignature, FwCmd_VerifySignature, 1, 0, 0, FW_CMD_FLAG_ENC }, #ifndef NO_RSA { TPM_CC_RSA_Encrypt, FwCmd_RSA_Encrypt, 1, 0, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, { TPM_CC_RSA_Decrypt, FwCmd_RSA_Decrypt, 1, 1, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, @@ -22194,7 +22194,7 @@ static const FWTPM_CMD_ENTRY fwCmdTable[] = { #endif #endif /* --- Sessions --- */ - { TPM_CC_StartAuthSession, FwCmd_StartAuthSession, 2, 0, 1, 0 }, + { TPM_CC_StartAuthSession, FwCmd_StartAuthSession, 2, 0, 1, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, { TPM_CC_Unseal, FwCmd_Unseal, 1, 1, 0, FW_CMD_FLAG_DEC }, /* --- Policy --- */ #ifndef FWTPM_NO_POLICY @@ -22205,13 +22205,13 @@ static const FWTPM_CMD_ENTRY fwCmdTable[] = { { TPM_CC_PolicyAuthValue, FwCmd_PolicyAuthValue, 1, 0, 0, 0 }, { TPM_CC_PolicyCommandCode, FwCmd_PolicyCommandCode, 1, 0, 0, 0 }, { TPM_CC_PolicyOR, FwCmd_PolicyOR, 1, 0, 0, 0 }, - { TPM_CC_PolicySecret, FwCmd_PolicySecret, 2, 1, 0, FW_CMD_FLAG_ENC }, + { TPM_CC_PolicySecret, FwCmd_PolicySecret, 2, 1, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, { TPM_CC_PolicyAuthorize, FwCmd_PolicyAuthorize, 1, 0, 0, FW_CMD_FLAG_ENC }, { TPM_CC_PolicyLocality, FwCmd_PolicyLocality, 1, 0, 0, 0 }, #ifdef WOLFTPM_SPDM { TPM_CC_PolicyTransportSPDM, FwCmd_PolicyTransportSPDM, 1, 0, 0, FW_CMD_FLAG_ENC }, #endif - { TPM_CC_PolicySigned, FwCmd_PolicySigned, 2, 0, 0, FW_CMD_FLAG_ENC }, + { TPM_CC_PolicySigned, FwCmd_PolicySigned, 2, 0, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, #ifndef FWTPM_NO_NV { TPM_CC_PolicyNV, FwCmd_PolicyNV, 3, 1, 0, FW_CMD_FLAG_ENC }, #endif @@ -22235,8 +22235,8 @@ static const FWTPM_CMD_ENTRY fwCmdTable[] = { { TPM_CC_LoadExternal, FwCmd_LoadExternal, 0, 0, 1, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, #ifndef FWTPM_NO_KEY_MIGRATION { TPM_CC_Import, FwCmd_Import, 1, 1, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, - { TPM_CC_Duplicate, FwCmd_Duplicate, 2, 1, 0, FW_CMD_FLAG_DEC | FW_CMD_FLAG_AUTH_DUP }, - { TPM_CC_Rewrap, FwCmd_Rewrap, 2, 1, 0, 0 }, + { TPM_CC_Duplicate, FwCmd_Duplicate, 2, 1, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC | FW_CMD_FLAG_AUTH_DUP }, + { TPM_CC_Rewrap, FwCmd_Rewrap, 2, 1, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, #endif /* !FWTPM_NO_KEY_MIGRATION */ { TPM_CC_CreateLoaded, FwCmd_CreateLoaded, 1, 1, 1, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC | FW_CMD_RO_DENY }, /* --- Symmetric --- */ @@ -22272,18 +22272,18 @@ static const FWTPM_CMD_ENTRY fwCmdTable[] = { #endif /* --- Attestation --- */ #ifndef FWTPM_NO_ATTESTATION - { TPM_CC_Quote, FwCmd_Quote, 1, 1, 0, FW_CMD_FLAG_DEC }, - { TPM_CC_Certify, FwCmd_Certify, 2, 2, 0, FW_CMD_FLAG_DEC | FW_CMD_FLAG_AUTH_ADMIN }, - { TPM_CC_CertifyCreation, FwCmd_CertifyCreation, 2, 1, 0, FW_CMD_FLAG_DEC }, - { TPM_CC_GetTime, FwCmd_GetTime, 2, 2, 0, FW_CMD_FLAG_DEC }, + { TPM_CC_Quote, FwCmd_Quote, 1, 1, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, + { TPM_CC_Certify, FwCmd_Certify, 2, 2, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC | FW_CMD_FLAG_AUTH_ADMIN }, + { TPM_CC_CertifyCreation, FwCmd_CertifyCreation, 2, 1, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, + { TPM_CC_GetTime, FwCmd_GetTime, 2, 2, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, #ifndef FWTPM_NO_NV - { TPM_CC_NV_Certify, FwCmd_NV_Certify, 3, 2, 0, FW_CMD_FLAG_DEC }, + { TPM_CC_NV_Certify, FwCmd_NV_Certify, 3, 2, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, #endif #endif /* !FWTPM_NO_ATTESTATION */ /* --- Credentials --- */ #ifndef FWTPM_NO_CREDENTIAL - { TPM_CC_MakeCredential, FwCmd_MakeCredential, 1, 0, 0, FW_CMD_FLAG_DEC }, - { TPM_CC_ActivateCredential, FwCmd_ActivateCredential, 2, 2, 0, FW_CMD_FLAG_DEC | FW_CMD_FLAG_AUTH_ADMIN }, + { TPM_CC_MakeCredential, FwCmd_MakeCredential, 1, 0, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC }, + { TPM_CC_ActivateCredential, FwCmd_ActivateCredential, 2, 2, 0, FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC | FW_CMD_FLAG_AUTH_ADMIN }, #endif /* !FWTPM_NO_CREDENTIAL */ /* --- Dictionary Attack --- */ #ifndef FWTPM_NO_DA From 7c7f855b48f555388ae55d21ad36d2285c0ce536 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:16:44 -0800 Subject: [PATCH 008/124] F-16236 - Enforce TPMA_SESSION attribute rules in the fwTPM dispatcher --- src/fwtpm/fwtpm_command.c | 54 ++++++++++++++++++++++++ tests/fwtpm_unit_tests.c | 89 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 137 insertions(+), 6 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 38e5c7cb3..bb489a277 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -22800,6 +22800,53 @@ static int FwAllowPreStartupSpdmProbe(FWTPM_CTX* ctx, TPM_CC cmdCode) #endif } +/* TPMA_SESSION consistency rules for one session (Part 3 Sec.5.5): a + * password session carries no use attribute, auditExclusive and auditReset + * need audit, only one session audits, decrypt and encrypt need a sized + * first command or response parameter, and a session that authorizes no + * handle must be there to decrypt, encrypt or audit. An extra password + * session holds no state and is tolerated. */ +static TPM_RC FwCheckSessionAttributes(const FWTPM_CMD_ENTRY* entry, + UINT32 sessHandle, UINT8 attribs, int sessIdx, int* auditCnt) +{ + UINT8 use = attribs & (TPMA_SESSION_decrypt | TPMA_SESSION_encrypt | + TPMA_SESSION_audit); + UINT16 flags = entry->encDecFlags; + +#ifdef FWTPM_NO_PARAM_ENC + flags &= (UINT16)~(FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC); +#endif + if (sessHandle == TPM_RS_PW) { + if (use != 0 || (attribs & (TPMA_SESSION_auditExclusive | + TPMA_SESSION_auditReset)) != 0) { + return TPM_RC_ATTRIBUTES; + } + } + else { + if ((attribs & (TPMA_SESSION_auditExclusive | + TPMA_SESSION_auditReset)) != 0 && + (attribs & TPMA_SESSION_audit) == 0) { + return TPM_RC_ATTRIBUTES; + } + if ((attribs & TPMA_SESSION_decrypt) != 0 && + (flags & FW_CMD_FLAG_ENC) == 0) { + return TPM_RC_ATTRIBUTES; + } + if ((attribs & TPMA_SESSION_encrypt) != 0 && + (flags & FW_CMD_FLAG_DEC) == 0) { + return TPM_RC_ATTRIBUTES; + } + if ((attribs & TPMA_SESSION_audit) != 0 && ++(*auditCnt) > 1) { + return TPM_RC_ATTRIBUTES; + } + } + if (sessHandle != TPM_RS_PW && sessIdx >= (int)entry->authHandleCnt && + use == 0) { + return TPM_RC_ATTRIBUTES; + } + return TPM_RC_SUCCESS; +} + int FWTPM_ProcessCommand(FWTPM_CTX* ctx, const byte* cmdBuf, int cmdSize, byte* rspBuf, int* rspSize, int locality) @@ -22818,6 +22865,7 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, int doEncCmd = 0; /* Decrypt incoming encrypted param */ int doEncRsp = 0; /* Encrypt outgoing response param */ #endif + int auditCnt = 0; int pj, hj; /* Loop indices for auth validation */ int transientIdx; TPM_HANDLE transientHandle; @@ -23117,6 +23165,12 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, break; } + rc = FwCheckSessionAttributes(entry, sessHandle, attribs, + cmdAuthCnt, &auditCnt); + if (rc != 0) { + break; + } + if (sessHandle != TPM_RS_PW) { FWTPM_Session* sess = FwFindSession(ctx, sessHandle); if (sess != NULL) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 61b457d36..929e4735c 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -17854,7 +17854,7 @@ static int BuildHmacSessionCmd(UINT32 cc, int nHandles, UINT32 handle, if (withPw) { PutU32BE(gCmd + pos, TPM_RS_PW); pos += 4; PutU16BE(gCmd + pos, 0); pos += 2; - gCmd[pos++] = attrs; + gCmd[pos++] = (UINT8)(attrs & TPMA_SESSION_continueSession); PutU16BE(gCmd + pos, 0); pos += 2; } PutU32BE(gCmd + pos, sessionH); pos += 4; @@ -17883,7 +17883,7 @@ static void SweepSessionHmac(FWTPM_CTX* ctx, FWTPM_Session* sess, UINT32 cc, byte pHash[TPM_SHA256_DIGEST_SIZE]; byte authHmac[TPM_SHA256_DIGEST_SIZE]; UINT16 nonceSz = sess->nonceTPM.size; - UINT8 attrs = TPMA_SESSION_continueSession; + UINT8 attrs = TPMA_SESSION_continueSession | TPMA_SESSION_audit; int pos, rspSize, h, bad, rejected, cpSz = 0; TPM_RC rc; @@ -18071,7 +18071,7 @@ static void test_fwtpm_session_params_after_auth(void) byte pHash[TPM_SHA256_DIGEST_SIZE]; byte authHmac[TPM_SHA256_DIGEST_SIZE]; UINT16 nonceSz; - UINT8 attrs = TPMA_SESSION_continueSession; + UINT8 attrs = TPMA_SESSION_continueSession | TPMA_SESSION_audit; UINT32 sessionH; int i, pos, rspSize; @@ -18429,14 +18429,14 @@ static void test_fwtpm_param_enc_session_no_handle(void) for (withNonce = 0; withNonce <= 1; withNonce++) { ComputeAuthHmac(noKey, 0, pHash, nonceCaller, (UINT16)sizeof(nonceCaller), nonceH, nonceHSz, nonceE, - withNonce ? nonceESz : 0, attrs, authHmac); + withNonce ? nonceESz : 0, attrs | TPMA_SESSION_audit, authHmac); pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_GetRandom); authStart = pos; pos += 4; PutU32BE(gCmd + pos, hmacSess); pos += 4; PutU16BE(gCmd + pos, (UINT16)sizeof(nonceCaller)); pos += 2; XMEMCPY(gCmd + pos, nonceCaller, sizeof(nonceCaller)); pos += sizeof(nonceCaller); - gCmd[pos++] = attrs; + gCmd[pos++] = attrs | TPMA_SESSION_audit; PutU16BE(gCmd + pos, (UINT16)sizeof(authHmac)); pos += 2; XMEMCPY(gCmd + pos, authHmac, sizeof(authHmac)); pos += sizeof(authHmac); @@ -18461,6 +18461,82 @@ static void test_fwtpm_param_enc_session_no_handle(void) fwtpm_pass("No-handle HMAC covers encrypt session nonce:", 0); } +/* Session attribute rules of Part 3 Sec.5.5 on GetRandom, which authorizes + * nothing and has a sized response but no sized command parameter. */ +static void test_fwtpm_session_attribute_rules(void) +{ + static const struct { + UINT8 attrs; + TPM_RC rc; + } cases[] = { + { TPMA_SESSION_continueSession, TPM_RC_ATTRIBUTES }, + { TPMA_SESSION_continueSession | TPMA_SESSION_audit, TPM_RC_SUCCESS }, + { TPMA_SESSION_continueSession | TPMA_SESSION_encrypt, + TPM_RC_SUCCESS }, + { TPMA_SESSION_continueSession | TPMA_SESSION_decrypt, + TPM_RC_ATTRIBUTES }, + { TPMA_SESSION_continueSession | TPMA_SESSION_encrypt | + TPMA_SESSION_decrypt, TPM_RC_ATTRIBUTES }, + { TPMA_SESSION_continueSession | TPMA_SESSION_encrypt | + TPMA_SESSION_auditExclusive, TPM_RC_ATTRIBUTES }, + { TPMA_SESSION_continueSession | TPMA_SESSION_encrypt | + TPMA_SESSION_auditReset, TPM_RC_ATTRIBUTES } + }; + FWTPM_CTX ctx; + FWTPM_Session* sess = NULL; + UINT32 sessH; + byte nonceTPM[TPM_MAX_DIGEST_SIZE]; + UINT16 nonceSz = 0; + byte nonceCaller[16]; + byte noKey[1] = {0}; + byte cpBuf[6]; + byte pHash[WC_SHA256_DIGEST_SIZE]; + byte authHmac[WC_SHA256_DIGEST_SIZE]; + int pos, rspSize; + size_t i; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + sessH = StartParamEncSessionHelper(&ctx, TPM_SE_HMAC, TPM_ALG_XOR, + nonceTPM, &nonceSz); + AssertIntNE(sessH, 0); + for (i = 0; i < FWTPM_MAX_SESSIONS; i++) { + if (ctx.sessions[i].used && ctx.sessions[i].handle == sessH) { + sess = &ctx.sessions[i]; + } + } + AssertNotNull(sess); + + memset(nonceCaller, 0x5C, sizeof(nonceCaller)); + PutU32BE(cpBuf, TPM_CC_GetRandom); + PutU16BE(cpBuf + 4, 16); + AssertIntEQ(wc_Sha256Hash(cpBuf, sizeof(cpBuf), pHash), 0); + for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + ComputeAuthHmac(noKey, 0, pHash, nonceCaller, + (UINT16)sizeof(nonceCaller), sess->nonceTPM.buffer, + sess->nonceTPM.size, NULL, 0, cases[i].attrs, authHmac); + pos = BuildHmacSessionCmd(TPM_CC_GetRandom, 0, 0, 0, sessH, + nonceCaller, sizeof(nonceCaller), cases[i].attrs, authHmac, + sizeof(authHmac)); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), cases[i].rc); + } + + /* a password session cannot decrypt, encrypt or audit */ + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_GetRandom); + pos = AppendAuth(gCmd, pos, TPM_RS_PW, TPMA_SESSION_encrypt, NULL, 0); + PutU16BE(gCmd + pos, 16); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES); + + FlushHandle(&ctx, sessH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Session attribute rules:", 0); +} + /* With an HMAC authorization first, its HMAC must also cover the nonceTPM * of a separate encrypt or decrypt session (Part 1 Sec.19.6.5). */ static void test_fwtpm_param_enc_session_bound_to_auth(void) @@ -18812,7 +18888,7 @@ static void test_fwtpm_command_crypto_allocation_failure(void) PutU32BE(gCmd + pos, sessH); pos += 4; PutU16BE(gCmd + pos, (UINT16)sizeof(data)); pos += 2; XMEMCPY(gCmd + pos, data, sizeof(data)); pos += sizeof(data); - gCmd[pos++] = TPMA_SESSION_continueSession; + gCmd[pos++] = TPMA_SESSION_continueSession | TPMA_SESSION_audit; PutU16BE(gCmd + pos, 0); pos += 2; PutU32BE(gCmd + authStart, (UINT32)(pos - authStart - 4)); PutU32BE(gCmd + 2, (UINT32)pos); @@ -25615,6 +25691,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_session_params_after_auth(); test_fwtpm_param_enc_session_bound_to_auth(); test_fwtpm_param_enc_session_no_handle(); + test_fwtpm_session_attribute_rules(); test_fwtpm_bound_auth_change_response_hmac(); test_fwtpm_sequence_complete_response_hmac(); #endif From 52d0ea356936ff676793a9e0e6c4f33c9edab969 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:27:10 -0800 Subject: [PATCH 009/124] F-16834 - Extend the fwTPM PolicyPassword digest with TPM_CC_PolicyAuthValue --- src/fwtpm/fwtpm_command.c | 5 +++-- tests/fwtpm_unit_tests.c | 31 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index bb489a277..6b45b36df 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -13617,7 +13617,8 @@ static FWTPM_Session* FwPolicyParseSession(FWTPM_CTX* ctx, } /* --- TPM2_PolicyPassword (CC 0x018C) --- */ -/* policyDigest = H(policyDigest || TPM_CC_PolicyPassword) */ +/* policyDigest = H(policyDigest || TPM_CC_PolicyAuthValue), the same digest + * as PolicyAuthValue (Part 3 Sec.23.18) */ static TPM_RC FwCmd_PolicyPassword(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, TPM2_Packet* rsp, UINT16 cmdTag) { @@ -13638,7 +13639,7 @@ static TPM_RC FwCmd_PolicyPassword(FWTPM_CTX* ctx, TPM2_Packet* cmd, #ifdef DEBUG_WOLFTPM printf("fwTPM: PolicyPassword(session=0x%x)\n", sess->handle); #endif - if (FwPolicyExtend(sess, TPM_CC_PolicyPassword, NULL, 0, + if (FwPolicyExtend(sess, TPM_CC_PolicyAuthValue, NULL, 0, NULL, 0, 0) != 0) { rc = TPM_RC_FAILURE; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 929e4735c..68a115bc7 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -12242,6 +12242,36 @@ static void test_fwtpm_policyauthorize_null_ticket_rejected(void) fwtpm_pass("PolicyAuthorize zero-ticket (TICKET):", 0); } +/* PolicyPassword extends policyDigest with TPM_CC_PolicyAuthValue, so one + * authPolicy is satisfied by either command (Part 3 Sec.23.18). */ +static void test_fwtpm_policy_password_digest(void) +{ + FWTPM_CTX ctx; + UINT32 sessH; + byte digest[2][WC_SHA256_DIGEST_SIZE]; + int i; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + for (i = 0; i < 2; i++) { + sessH = StartSessionHelper(&ctx, TPM_SE_TRIAL); + AssertIntNE(sessH, 0); + AssertIntEQ(SendPolicyCmd(&ctx, (i == 0) ? TPM_CC_PolicyPassword : + TPM_CC_PolicyAuthValue, sessH), TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyGetDigest, sessH), + TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4), + WC_SHA256_DIGEST_SIZE); + memcpy(digest[i], gRsp + TPM2_HEADER_SIZE + 6, WC_SHA256_DIGEST_SIZE); + FlushHandle(&ctx, sessH); + } + AssertIntEQ(memcmp(digest[0], digest[1], WC_SHA256_DIGEST_SIZE), 0); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("PolicyPassword digest:", 0); +} + #ifndef FWTPM_NO_NV /* PolicyNV and PolicyAuthorizeNV must verify the caller is authorized to * read the NV index. An OWNER authHandle against an index without @@ -25777,6 +25807,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif test_fwtpm_policy_ticket_zero_digest_rejected(); test_fwtpm_policyauthorize_null_ticket_rejected(); + test_fwtpm_policy_password_digest(); #ifndef FWTPM_NO_NV test_fwtpm_policynv_owner_read_denied(); test_fwtpm_policyauthorizenv_owner_read_denied(); From 91af2de7e5614764828d4df644e78b6b15edfab2 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:29:06 -0800 Subject: [PATCH 010/124] F-16230 - Return TPM_RC_SIZE for an out-of-range fwTPM PolicyOR digest count --- src/fwtpm/fwtpm_command.c | 2 +- tests/fwtpm_unit_tests.c | 46 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 6b45b36df..9590d4e55 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -13770,7 +13770,7 @@ static TPM_RC FwCmd_PolicyOR(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_COMMAND_SIZE; } else if (digestCount < 2 || digestCount > 8) { - rc = TPM_RC_VALUE; + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; } } if (rc == 0) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 68a115bc7..6900353c1 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -12272,6 +12272,51 @@ static void test_fwtpm_policy_password_digest(void) fwtpm_pass("PolicyPassword digest:", 0); } +static TPM_RC SendPolicyOR(FWTPM_CTX* ctx, UINT32 sessH, UINT32 count, + const byte* list, int listSz) +{ + int rspSize = 0; + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_PolicyOR); + + PutU32BE(gCmd + pos, sessH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + pos, count); pos += 4; + memcpy(gCmd + pos, list, listSz); pos += listSz; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* A TPML_DIGEST count outside 2..8 is TPM_RC_SIZE (Part 2 Table 125). */ +static void test_fwtpm_policy_or_count(void) +{ + FWTPM_CTX ctx; + UINT32 sessH; + byte list[9 * (2 + WC_SHA256_DIGEST_SIZE)]; + int i; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + sessH = StartSessionHelper(&ctx, TPM_SE_TRIAL); + AssertIntNE(sessH, 0); + + memset(list, 0, sizeof(list)); + for (i = 0; i < 9; i++) { + PutU16BE(list + i * (2 + WC_SHA256_DIGEST_SIZE), + WC_SHA256_DIGEST_SIZE); + } + AssertIntEQ(SendPolicyOR(&ctx, sessH, 1, list, + 2 + WC_SHA256_DIGEST_SIZE), TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendPolicyOR(&ctx, sessH, 9, list, (int)sizeof(list)), + TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendPolicyOR(&ctx, sessH, 2, list, + 2 * (2 + WC_SHA256_DIGEST_SIZE)), TPM_RC_SUCCESS); + + FlushHandle(&ctx, sessH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("PolicyOR digest count:", 0); +} + #ifndef FWTPM_NO_NV /* PolicyNV and PolicyAuthorizeNV must verify the caller is authorized to * read the NV index. An OWNER authHandle against an index without @@ -25808,6 +25853,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_policy_ticket_zero_digest_rejected(); test_fwtpm_policyauthorize_null_ticket_rejected(); test_fwtpm_policy_password_digest(); + test_fwtpm_policy_or_count(); #ifndef FWTPM_NO_NV test_fwtpm_policynv_owner_read_denied(); test_fwtpm_policyauthorizenv_owner_read_denied(); From dd1d786d3ccecf10ade4dfda5b5fdeaacdf01b51 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:31:03 -0800 Subject: [PATCH 011/124] F-16229 - Accept fwTPM PolicyOR list entries of any digest size --- src/fwtpm/fwtpm_command.c | 9 +++---- tests/fwtpm_unit_tests.c | 57 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 9590d4e55..777ed0378 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -13785,15 +13785,14 @@ static TPM_RC FwCmd_PolicyOR(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_AUTH_TYPE; } } - /* Per TPM 2.0 Part 3 Section 23.5: each digest must be the size of - * the session's hash algorithm digest */ + /* Per TPM 2.0 Part 3 Section 23.6: a digest of another size is not an + * error, it only cannot match policyDigest */ if (rc == 0) { - dSz = TPM2_GetHashDigestSize(sess->authHash); for (i = 0; i < (int)digestCount; i++) { rc = FwPolicyParseTpm2b(cmd, cmdSize, digests[i], (UINT16)sizeof(digests[i]), &digestSizes[i]); - if (rc == 0 && digestSizes[i] != (UINT16)dSz) { - rc = TPM_RC_SIZE; + if (rc == TPM_RC_SIZE) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; } if (rc != 0) { break; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 6900353c1..85e706b44 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -12317,6 +12317,62 @@ static void test_fwtpm_policy_or_count(void) fwtpm_pass("PolicyOR digest count:", 0); } +/* A pHashList entry of another digest size is not an error; it only cannot + * match policyDigest, and is still hashed as supplied (Part 3 Sec.23.6). */ +static void test_fwtpm_policy_or_mixed_sizes(void) +{ + FWTPM_CTX ctx; + UINT32 sessH; + byte list[(2 + TPM_SHA_DIGEST_SIZE) + (2 + WC_SHA256_DIGEST_SIZE)]; + byte hashSrc[WC_SHA256_DIGEST_SIZE + 4 + TPM_SHA_DIGEST_SIZE + + WC_SHA256_DIGEST_SIZE]; + byte expect[WC_SHA256_DIGEST_SIZE]; + byte big[(2 + TPM_MAX_DIGEST_SIZE + 1) + (2 + WC_SHA256_DIGEST_SIZE)]; + int i; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + /* SHA-1 sized entry, then the all-zero SHA-256 start digest */ + memset(list, 0, sizeof(list)); + PutU16BE(list, TPM_SHA_DIGEST_SIZE); + memset(list + 2, 0x5A, TPM_SHA_DIGEST_SIZE); + PutU16BE(list + 2 + TPM_SHA_DIGEST_SIZE, WC_SHA256_DIGEST_SIZE); + + memset(hashSrc, 0, sizeof(hashSrc)); + PutU32BE(hashSrc + WC_SHA256_DIGEST_SIZE, TPM_CC_PolicyOR); + memset(hashSrc + WC_SHA256_DIGEST_SIZE + 4, 0x5A, TPM_SHA_DIGEST_SIZE); + AssertIntEQ(wc_Sha256Hash(hashSrc, (word32)sizeof(hashSrc), expect), 0); + + for (i = 0; i < 2; i++) { + sessH = StartSessionHelper(&ctx, (i == 0) ? TPM_SE_TRIAL : + TPM_SE_POLICY); + AssertIntNE(sessH, 0); + AssertIntEQ(SendPolicyOR(&ctx, sessH, 2, list, (int)sizeof(list)), + TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyGetDigest, sessH), + TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4), + WC_SHA256_DIGEST_SIZE); + AssertIntEQ(memcmp(gRsp + TPM2_HEADER_SIZE + 6, expect, + WC_SHA256_DIGEST_SIZE), 0); + FlushHandle(&ctx, sessH); + } + + /* An entry larger than any digest is not a TPM2B_DIGEST */ + memset(big, 0, sizeof(big)); + PutU16BE(big, TPM_MAX_DIGEST_SIZE + 1); + PutU16BE(big + 2 + TPM_MAX_DIGEST_SIZE + 1, WC_SHA256_DIGEST_SIZE); + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(sessH, 0); + AssertIntEQ(SendPolicyOR(&ctx, sessH, 2, big, (int)sizeof(big)), + TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + FlushHandle(&ctx, sessH); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("PolicyOR mixed digest sizes:", 0); +} + #ifndef FWTPM_NO_NV /* PolicyNV and PolicyAuthorizeNV must verify the caller is authorized to * read the NV index. An OWNER authHandle against an index without @@ -25854,6 +25910,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_policyauthorize_null_ticket_rejected(); test_fwtpm_policy_password_digest(); test_fwtpm_policy_or_count(); + test_fwtpm_policy_or_mixed_sizes(); #ifndef FWTPM_NO_NV test_fwtpm_policynv_owner_read_denied(); test_fwtpm_policyauthorizenv_owner_read_denied(); From b3381d1467066581d32e98d7e4a7f8580398e04f Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:32:55 -0800 Subject: [PATCH 012/124] F-16233 - Reject a repeated fwTPM PolicyNameHash with TPM_RC_CPHASH --- src/fwtpm/fwtpm_command.c | 23 +++++------------------ tests/fwtpm_unit_tests.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 18 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 777ed0378..37eda9749 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -15448,9 +15448,6 @@ static TPM_RC FwCmd_PolicyNameHash(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_Session* sess; UINT16 nameHashSz = 0; byte nameHashBuf[TPM_MAX_DIGEST_SIZE]; - int sizeMismatch; - int nameDiff; - word32 cmpSz; sess = FwPolicyParseSession(ctx, cmd, cmdSize, cmdTag); if (sess == NULL) { @@ -15471,23 +15468,13 @@ static TPM_RC FwCmd_PolicyNameHash(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } if (rc == 0) { - /* cpHash, nameHash, templateHash and paramHash share one slot */ - if (sess->cpHashA.size > 0 || sess->templateHash.size > 0 || - sess->paramHash.size > 0) { + /* cpHash, nameHash, templateHash and paramHash share one slot. + * Unlike PolicyCpHash, a repeat of the same nameHash is refused + * (Part 3 Sec.23.14). */ + if (sess->cpHashA.size > 0 || sess->nameHash.size > 0 || + sess->templateHash.size > 0 || sess->paramHash.size > 0) { rc = TPM_RC_CPHASH; } - /* If nameHash already set, must be identical — always run - * TPM2_ConstantCompare so timing doesn't leak size match */ - else if (sess->nameHash.size > 0) { - sizeMismatch = (sess->nameHash.size != nameHashSz); - cmpSz = (sess->nameHash.size < nameHashSz) ? - sess->nameHash.size : nameHashSz; - nameDiff = TPM2_ConstantCompare(sess->nameHash.buffer, nameHashBuf, - cmpSz); - if (sizeMismatch | nameDiff) { - rc = TPM_RC_CPHASH; - } - } } if (rc == 0) { #ifdef DEBUG_WOLFTPM diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 85e706b44..c9ee02b28 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -12373,6 +12373,38 @@ static void test_fwtpm_policy_or_mixed_sizes(void) fwtpm_pass("PolicyOR mixed digest sizes:", 0); } +/* PolicyNameHash has no same-value exception: once the session's + * cpHash/nameHash slot is occupied it is TPM_RC_CPHASH (Part 3 Sec.23.14). */ +static void test_fwtpm_policy_name_hash_repeat(void) +{ + FWTPM_CTX ctx; + UINT32 sessH; + int i, pos, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(sessH, 0); + + for (i = 0; i < 2; i++) { + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_PolicyNameHash); + PutU32BE(gCmd + pos, sessH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, WC_SHA256_DIGEST_SIZE); pos += 2; + memset(gCmd + pos, 0x33, WC_SHA256_DIGEST_SIZE); + pos += WC_SHA256_DIGEST_SIZE; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), (i == 0) ? TPM_RC_SUCCESS : + TPM_RC_CPHASH); + } + + FlushHandle(&ctx, sessH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("PolicyNameHash repeat:", 0); +} + #ifndef FWTPM_NO_NV /* PolicyNV and PolicyAuthorizeNV must verify the caller is authorized to * read the NV index. An OWNER authHandle against an index without @@ -25911,6 +25943,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_policy_password_digest(); test_fwtpm_policy_or_count(); test_fwtpm_policy_or_mixed_sizes(); + test_fwtpm_policy_name_hash_repeat(); #ifndef FWTPM_NO_NV test_fwtpm_policynv_owner_read_denied(); test_fwtpm_policyauthorizenv_owner_read_denied(); From 3c09a9e17f53b76ccf127e7a7c88ea3f1fb43605 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:34:49 -0800 Subject: [PATCH 013/124] F-16231 - Return TPM_RC_VALUE for an fwTPM PolicyCounterTimer offset past TPMS_TIME_INFO --- src/fwtpm/fwtpm_command.c | 5 ++++- tests/fwtpm_unit_tests.c | 41 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 37eda9749..b68516c58 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -15703,7 +15703,10 @@ static TPM_RC FwCmd_PolicyCounterTimer(FWTPM_CTX* ctx, TPM2_Packet* cmd, FwStoreU32BE(timeInfo + p, ctx->restartCount); p += 4; timeInfo[p++] = (byte)ctx->clockSafe; - if ((UINT32)offset + operandBSz > (UINT32)p) { + if ((UINT32)offset > (UINT32)p) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; + } + else if ((UINT32)offset + operandBSz > (UINT32)p) { rc = TPM_RC_RANGE; } } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index c9ee02b28..a1886770e 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -12405,6 +12405,46 @@ static void test_fwtpm_policy_name_hash_repeat(void) fwtpm_pass("PolicyNameHash repeat:", 0); } +static TPM_RC SendPolicyCounterTimer(FWTPM_CTX* ctx, UINT32 sessH, + UINT16 operandSz, UINT16 offset) +{ + int rspSize = 0; + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + TPM_CC_PolicyCounterTimer); + + PutU32BE(gCmd + pos, sessH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, operandSz); pos += 2; + memset(gCmd + pos, 0, operandSz); pos += operandSz; + PutU16BE(gCmd + pos, offset); pos += 2; + PutU16BE(gCmd + pos, TPM_EO_EQ); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* An offset past the marshaled TPMS_TIME_INFO is TPM_RC_VALUE; an operand + * that runs off its end is TPM_RC_RANGE (Part 3 Sec.23.10). */ +static void test_fwtpm_policy_counter_timer_offset(void) +{ + FWTPM_CTX ctx; + UINT32 sessH; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + sessH = StartSessionHelper(&ctx, TPM_SE_TRIAL); + AssertIntNE(sessH, 0); + + AssertIntEQ(SendPolicyCounterTimer(&ctx, sessH, 0, 26), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendPolicyCounterTimer(&ctx, sessH, 8, 20), TPM_RC_RANGE); + AssertIntEQ(SendPolicyCounterTimer(&ctx, sessH, 0, 25), TPM_RC_SUCCESS); + + FlushHandle(&ctx, sessH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("PolicyCounterTimer offset:", 0); +} + #ifndef FWTPM_NO_NV /* PolicyNV and PolicyAuthorizeNV must verify the caller is authorized to * read the NV index. An OWNER authHandle against an index without @@ -25944,6 +25984,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_policy_or_count(); test_fwtpm_policy_or_mixed_sizes(); test_fwtpm_policy_name_hash_repeat(); + test_fwtpm_policy_counter_timer_offset(); #ifndef FWTPM_NO_NV test_fwtpm_policynv_owner_read_denied(); test_fwtpm_policyauthorizenv_owner_read_denied(); From 4037a194dae9a303a32748769394565a03dc2abf Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:39:09 -0800 Subject: [PATCH 014/124] F-16188 - Return an empty buffer for a zero-size fwTPM NV_Read --- src/fwtpm/fwtpm_command.c | 3 -- tests/fwtpm_unit_tests.c | 64 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 3 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index b68516c58..4e88e7e3e 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -17288,9 +17288,6 @@ static TPM_RC FwCmd_NV_Read(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseU16(cmd, &readSize); TPM2_Packet_ParseU16(cmd, &offset); - if (readSize == 0) { - readSize = nv->nvPublic.dataSize; - } if ((UINT32)offset + readSize > nv->nvPublic.dataSize) { rc = TPM_RC_NV_RANGE; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index a1886770e..5f20bba73 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -11497,6 +11497,35 @@ static TPM_RC SendNvLockCmd(FWTPM_CTX* ctx, UINT32 commandCode, return GetRspRC(gRsp); } +/* Owner-authorized NV_Read (size, offset), NV_Write (data, offset) or + * NV_Extend (data). A NULL data pointer sends size octets of 0xA5. */ +static TPM_RC SendNvOwnerCmd(FWTPM_CTX* ctx, UINT32 commandCode, + UINT32 nvIndex, const byte* data, UINT16 size, UINT16 offset) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, commandCode); + int rspSize = 0; + + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, nvIndex); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, size); pos += 2; + if (commandCode != TPM_CC_NV_Read) { + if (data != NULL) { + memcpy(gCmd + pos, data, size); + } + else { + memset(gCmd + pos, 0xA5, size); + } + pos += size; + } + if (commandCode != TPM_CC_NV_Extend) { + PutU16BE(gCmd + pos, offset); pos += 2; + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + #ifndef FWTPM_NO_POLICY static TPM_RC SendNvAccessCmd(FWTPM_CTX* ctx, UINT32 nvIndex, UINT32 sessionHandle, const byte* auth, int authSz, int isWrite) @@ -16030,6 +16059,40 @@ static void test_fwtpm_nv_owner_access_platform_index(void) fwtpm_pass("NV owner access to platform index:", 0); } +/* NV_Read size is the number of octets to return, so zero reads nothing. */ +static void test_fwtpm_nv_read_zero_size(void) +{ + FWTPM_CTX ctx; + UINT32 nvIdx = 0x01500A01; + int cmdSz, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, 8, + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Read, nvIdx, NULL, 0, 0), + TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4), 0); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Read, nvIdx, NULL, 0, 4), + TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4), 0); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Read, nvIdx, NULL, 4, 4), + TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4), 4); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV_Read zero size:", 0); +} + /* State-changing handlers that persist to NV must report failure, not * success, when the journal write fails. Representative commands from the * clock, NV-index and hierarchy-auth families run on one context; @@ -26070,6 +26133,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_clear_control_nv_failure(); test_fwtpm_yes_no_range(); test_fwtpm_nv_owner_access_platform_index(); + test_fwtpm_nv_read_zero_size(); test_fwtpm_state_change_nv_failure(); test_fwtpm_nv_append_atomic(); test_fwtpm_nv_compaction_commit(); From 7e98c11ed62851efb0120c560f94acd42732c565 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:41:03 -0800 Subject: [PATCH 015/124] F-18077 - Bound fwTPM NV_Write, NV_Read and NV_Certify by MAX_NV_BUFFER_SIZE --- src/fwtpm/fwtpm_command.c | 21 +++++++--- tests/fwtpm_unit_tests.c | 88 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 6 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 4e88e7e3e..e39e38b06 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -17191,8 +17191,8 @@ static TPM_RC FwCmd_NV_Write(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Parse: TPM2B data + offset */ if (rc == 0) { TPM2_Packet_ParseU16(cmd, &dataSize); - if (dataSize > FWTPM_MAX_NV_DATA) { - rc = TPM_RC_SIZE; + if (dataSize > MAX_NV_BUFFER_SIZE || dataSize > FWTPM_MAX_NV_DATA) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; } else if (cmd->pos + dataSize > cmdSize) { rc = TPM_RC_COMMAND_SIZE; @@ -17202,7 +17202,10 @@ static TPM_RC FwCmd_NV_Write(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseBytes(cmd, dataBuf, dataSize); TPM2_Packet_ParseU16(cmd, &offset); - if ((UINT32)offset + dataSize > nv->nvPublic.dataSize) { + if (offset > nv->nvPublic.dataSize) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; + } + else if ((UINT32)offset + dataSize > nv->nvPublic.dataSize) { rc = TPM_RC_NV_RANGE; } } @@ -17288,7 +17291,13 @@ static TPM_RC FwCmd_NV_Read(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseU16(cmd, &readSize); TPM2_Packet_ParseU16(cmd, &offset); - if ((UINT32)offset + readSize > nv->nvPublic.dataSize) { + if (readSize > MAX_NV_BUFFER_SIZE) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_1; + } + else if (offset > nv->nvPublic.dataSize) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; + } + else if ((UINT32)offset + readSize > nv->nvPublic.dataSize) { rc = TPM_RC_NV_RANGE; } } @@ -19026,8 +19035,8 @@ static TPM_RC FwCmd_NV_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, if ((UINT32)(readOffset + readSize) > nv->nvPublic.dataSize) { rc = TPM_RC_NV_RANGE; } - if (rc == 0 && !digestMode && readSize > FWTPM_MAX_NV_DATA) { - rc = TPM_RC_SIZE; + if (rc == 0 && !digestMode && readSize > MAX_NV_BUFFER_SIZE) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_3; } } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 5f20bba73..29c3842a3 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -14804,6 +14804,36 @@ static void test_fwtpm_nv_certify_digest_mode(void) printf("Test fwTPM:\tNV_Certify (digest mode):\tPassed\n"); } +#ifdef HAVE_ECC +/* NV_Certify with password authorization for signHandle and ownerAuth */ +static TPM_RC SendNvCertifyCmd(FWTPM_CTX* ctx, UINT32 keyH, UINT32 nvIndex, + UINT16 size, UINT16 offset) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_NV_Certify); + int rspSize = 0; + int i; + + PutU32BE(gCmd + pos, keyH); pos += 4; + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, nvIndex); pos += 4; + PutU32BE(gCmd + pos, 18); pos += 4; /* two password sessions */ + for (i = 0; i < 2; i++) { + PutU32BE(gCmd + pos, TPM_RS_PW); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; /* nonce */ + gCmd[pos++] = 0; /* attributes */ + PutU16BE(gCmd + pos, 0); pos += 2; /* hmac */ + } + PutU16BE(gCmd + pos, 0); pos += 2; /* qualifyingData */ + PutU16BE(gCmd + pos, TPM_ALG_ECDSA); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU16BE(gCmd + pos, size); pos += 2; + PutU16BE(gCmd + pos, offset); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} +#endif /* HAVE_ECC */ + #if defined(WOLFTPM_MLDSA_SIGN) && defined(WOLFTPM_MLDSA_VERIFY) /* TPM2_NV_Certify signed by a Pure ML-DSA key, verified with the wolfCrypt * ML-DSA verifier. Exercises the same FwSignAttest path as Quote/Certify. */ @@ -16093,6 +16123,63 @@ static void test_fwtpm_nv_read_zero_size(void) fwtpm_pass("NV_Read zero size:", 0); } +/* One NV_Write, NV_Read or NV_Certify moves at most MAX_NV_BUFFER_SIZE + * octets, the advertised TPM_PT_NV_BUFFER_MAX. */ +static void test_fwtpm_nv_buffer_max(void) +{ + FWTPM_CTX ctx; + UINT32 nvIdx = 0x01500A02; + int cmdSz, rspSize; +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) + UINT32 keyH; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, MAX_NV_BUFFER_SIZE + 8, + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, NULL, + MAX_NV_BUFFER_SIZE + 1, 0), TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, NULL, + MAX_NV_BUFFER_SIZE, 0), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, NULL, 8, + MAX_NV_BUFFER_SIZE), TPM_RC_SUCCESS); + + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Read, nvIdx, NULL, + MAX_NV_BUFFER_SIZE + 1, 0), TPM_RC_VALUE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Read, nvIdx, NULL, + MAX_NV_BUFFER_SIZE, 8), TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4), MAX_NV_BUFFER_SIZE); + + /* An offset past the index is a bad offset, not a bad range */ + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, NULL, 1, + MAX_NV_BUFFER_SIZE + 8), TPM_RC_NV_RANGE); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, NULL, 1, + MAX_NV_BUFFER_SIZE + 9), TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Read, nvIdx, NULL, 1, + MAX_NV_BUFFER_SIZE + 8), TPM_RC_NV_RANGE); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Read, nvIdx, NULL, 1, + MAX_NV_BUFFER_SIZE + 9), TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) + keyH = CreatePrimaryEccSignHelper(&ctx); + AssertIntNE(keyH, 0); + AssertIntEQ(SendNvCertifyCmd(&ctx, keyH, nvIdx, MAX_NV_BUFFER_SIZE + 1, + 0), TPM_RC_VALUE | TPM_RC_P | TPM_RC_3); + FlushHandle(&ctx, keyH); +#endif + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV buffer maximum:", 0); +} + /* State-changing handlers that persist to NV must report failure, not * success, when the journal write fails. Representative commands from the * clock, NV-index and hierarchy-auth families run on one context; @@ -26134,6 +26221,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_yes_no_range(); test_fwtpm_nv_owner_access_platform_index(); test_fwtpm_nv_read_zero_size(); + test_fwtpm_nv_buffer_max(); test_fwtpm_state_change_nv_failure(); test_fwtpm_nv_append_atomic(); test_fwtpm_nv_compaction_commit(); From 81b939e6e18696a77d59d63a290804ec7bd53564 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:42:59 -0800 Subject: [PATCH 016/124] F-16840 - Certify zero octets for a zero-size fwTPM NV_Certify at a non-zero offset --- src/fwtpm/fwtpm_command.c | 3 --- tests/fwtpm_unit_tests.c | 46 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index e39e38b06..96c0273c9 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -19029,9 +19029,6 @@ static TPM_RC FwCmd_NV_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, digestMode = 1; readSize = nv->nvPublic.dataSize; } - else if (readSize == 0) { - readSize = nv->nvPublic.dataSize - readOffset; - } if ((UINT32)(readOffset + readSize) > nv->nvPublic.dataSize) { rc = TPM_RC_NV_RANGE; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 29c3842a3..d476e7f91 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -16180,6 +16180,49 @@ static void test_fwtpm_nv_buffer_max(void) fwtpm_pass("NV buffer maximum:", 0); } +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) +/* Only size 0 with offset 0 selects the digest form; size 0 at any other + * offset certifies zero octets (Part 3 Sec.31.16). */ +static void test_fwtpm_nv_certify_zero_size_offset(void) +{ + FWTPM_CTX ctx; + UINT32 nvIdx = 0x01500A03; + UINT32 keyH; + int cmdSz, rspSize, pos; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + keyH = CreatePrimaryEccSignHelper(&ctx); + AssertIntNE(keyH, 0); + + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, 32, + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, NULL, 32, 0), + TPM_RC_SUCCESS); + + AssertIntEQ(SendNvCertifyCmd(&ctx, keyH, nvIdx, 0, 4), TPM_RC_SUCCESS); + /* header, parameterSize, TPM2B_ATTEST size, magic */ + pos = TPM2_HEADER_SIZE + 4 + 2 + 4; + AssertIntEQ(GetU16BE(gRsp + pos), TPM_ST_ATTEST_NV); + pos += 2; + pos += 2 + GetU16BE(gRsp + pos); /* qualifiedSigner */ + pos += 2 + GetU16BE(gRsp + pos); /* extraData */ + pos += 17 + 8; /* clockInfo, firmwareVersion */ + pos += 2 + GetU16BE(gRsp + pos); /* indexName */ + AssertIntEQ(GetU16BE(gRsp + pos), 4); /* offset */ + AssertIntEQ(GetU16BE(gRsp + pos + 2), 0); /* nvContents size */ + + FlushHandle(&ctx, keyH); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV_Certify zero size at offset:", 0); +} +#endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION */ + /* State-changing handlers that persist to NV must report failure, not * success, when the journal write fails. Representative commands from the * clock, NV-index and hierarchy-auth families run on one context; @@ -26222,6 +26265,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_nv_owner_access_platform_index(); test_fwtpm_nv_read_zero_size(); test_fwtpm_nv_buffer_max(); +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) + test_fwtpm_nv_certify_zero_size_offset(); +#endif test_fwtpm_state_change_nv_failure(); test_fwtpm_nv_append_atomic(); test_fwtpm_nv_compaction_commit(); From 7b1c3d0eee13c58118318d7fde6e3a988f72f805 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:46:29 -0800 Subject: [PATCH 017/124] F-18068 - Accept fwTPM NV_Extend data up to MAX_NV_BUFFER_SIZE --- src/fwtpm/fwtpm_command.c | 11 ++++++----- tests/fwtpm_unit_tests.c | 40 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 96c0273c9..22874d958 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -17321,7 +17321,7 @@ static TPM_RC FwCmd_NV_Extend(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPMI_RH_NV_INDEX nvHandle; FWTPM_NvIndex* nv; UINT16 dataSize = 0; - byte dataBuf[TPM_MAX_DIGEST_SIZE * 2]; /* input data */ + const byte* data = NULL; int hSz = 0; FWTPM_DECLARE_VAR(hashCtx, wc_HashAlg); enum wc_HashType wcHash; @@ -17366,15 +17366,16 @@ static TPM_RC FwCmd_NV_Extend(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { TPM2_Packet_ParseU16(cmd, &dataSize); - if (dataSize > sizeof(dataBuf)) { - rc = TPM_RC_SIZE; + if (dataSize > MAX_NV_BUFFER_SIZE) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; } else if (cmd->pos + dataSize > cmdSize) { rc = TPM_RC_COMMAND_SIZE; } } if (rc == 0) { - TPM2_Packet_ParseBytes(cmd, dataBuf, dataSize); + data = cmd->buf + cmd->pos; + cmd->pos += dataSize; hSz = TPM2_GetHashDigestSize(nv->nvPublic.nameAlg); if (hSz <= 0 || hSz > FWTPM_MAX_NV_DATA) { @@ -17400,7 +17401,7 @@ static TPM_RC FwCmd_NV_Extend(FWTPM_CTX* ctx, TPM2_Packet* cmd, XMEMCPY(oldData, nv->data, hSz); hashRc = wc_HashUpdate(hashCtx, wcHash, nv->data, hSz); if (hashRc == 0) { - hashRc = wc_HashUpdate(hashCtx, wcHash, dataBuf, dataSize); + hashRc = wc_HashUpdate(hashCtx, wcHash, data, dataSize); } if (hashRc == 0) { hashRc = wc_HashFinal(hashCtx, wcHash, newVal); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index d476e7f91..bd8d819c8 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -16180,6 +16180,45 @@ static void test_fwtpm_nv_buffer_max(void) fwtpm_pass("NV buffer maximum:", 0); } +/* NV_Extend data is a TPM2B_MAX_NV_BUFFER, not bounded by the digest size + * of the index (Part 3 Sec.31.9). */ +static void test_fwtpm_nv_extend_buffer_max(void) +{ + FWTPM_CTX ctx; + UINT32 nvIdx = 0x01500A04; + byte hashSrc[WC_SHA256_DIGEST_SIZE + MAX_NV_BUFFER_SIZE]; + byte expect[WC_SHA256_DIGEST_SIZE]; + int cmdSz, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, WC_SHA256_DIGEST_SIZE, + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA | + ((UINT32)TPM_NT_EXTEND << 4)); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Extend, nvIdx, NULL, + MAX_NV_BUFFER_SIZE, 0), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Extend, nvIdx, NULL, + MAX_NV_BUFFER_SIZE + 1, 0), TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + + memset(hashSrc, 0, WC_SHA256_DIGEST_SIZE); + memset(hashSrc + WC_SHA256_DIGEST_SIZE, 0xA5, MAX_NV_BUFFER_SIZE); + AssertIntEQ(wc_Sha256Hash(hashSrc, (word32)sizeof(hashSrc), expect), 0); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Read, nvIdx, NULL, + WC_SHA256_DIGEST_SIZE, 0), TPM_RC_SUCCESS); + AssertIntEQ(memcmp(gRsp + TPM2_HEADER_SIZE + 6, expect, + WC_SHA256_DIGEST_SIZE), 0); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV_Extend buffer maximum:", 0); +} + #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) /* Only size 0 with offset 0 selects the digest form; size 0 at any other * offset certifies zero octets (Part 3 Sec.31.16). */ @@ -26265,6 +26304,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_nv_owner_access_platform_index(); test_fwtpm_nv_read_zero_size(); test_fwtpm_nv_buffer_max(); + test_fwtpm_nv_extend_buffer_max(); #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) test_fwtpm_nv_certify_zero_size_offset(); #endif From 657cea3d349f3fb5b08fe45aa138cd1e0570aa84 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 18:48:47 -0800 Subject: [PATCH 018/124] F-18069 - Leave fwTPM bits and extend NV indexes unwritten at definition --- src/fwtpm/fwtpm_command.c | 5 ++-- tests/fwtpm_unit_tests.c | 63 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 22874d958..a78cf2bb0 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -16887,21 +16887,20 @@ static TPM_RC FwNvDefineSpaceEx(FWTPM_CTX* ctx, TPM2_Packet* cmd, } slot->written = 0; - /* Counter is not written until its first increment. */ + /* A counter, bits or extend index starts from zero but is not + * written until its first Increment, SetBits or Extend. */ nt = (int)((slot->nvPublic.attributes & TPMA_NV_TPM_NT) >> 4); if (nt == TPM_NT_COUNTER) { XMEMSET(slot->data, 0, 8); } else if (nt == TPM_NT_BITS) { XMEMSET(slot->data, 0, 8); - slot->written = 1; } else if (nt == TPM_NT_EXTEND) { int hSz = TPM2_GetHashDigestSize(slot->nvPublic.nameAlg); if (hSz > 0) { XMEMSET(slot->data, 0, hSz); } - slot->written = 1; } rc = FWTPM_NV_SaveNvIndex(ctx, diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index bd8d819c8..70aacc843 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -16219,6 +16219,68 @@ static void test_fwtpm_nv_extend_buffer_max(void) fwtpm_pass("NV_Extend buffer maximum:", 0); } +/* A bits or extend index is unwritten until its first SetBits or Extend: + * TPMA_NV_WRITTEN is CLEAR and a read is TPM_RC_NV_UNINITIALIZED. */ +static void test_fwtpm_nv_bits_extend_unwritten(void) +{ + FWTPM_CTX ctx; + UINT32 nvIdx = 0x01500A05; + UINT16 size; + int i, pos, cmdSz, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + for (i = 0; i < 2; i++) { + size = (i == 0) ? 8 : WC_SHA256_DIGEST_SIZE; + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, size, TPMA_NV_OWNERWRITE | + TPMA_NV_OWNERREAD | TPMA_NV_NO_DA | + ((UINT32)((i == 0) ? TPM_NT_BITS : TPM_NT_EXTEND) << 4)); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + /* TPM2B_NV_PUBLIC: size(2) | nvIndex(4) | nameAlg(2) | attributes */ + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_NV_ReadPublic); + PutU32BE(gCmd + pos, nvIdx); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(GetU32BE(gRsp + TPM2_HEADER_SIZE + 2 + 4 + 2) & + TPMA_NV_WRITTEN, 0); + + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Read, nvIdx, NULL, size, + 0), TPM_RC_NV_UNINITIALIZED); + + if (i == 0) { + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_NV_SetBits); + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, nvIdx); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + pos, 0); pos += 4; + PutU32BE(gCmd + pos, 1); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + } + else { + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Extend, nvIdx, NULL, + 4, 0), TPM_RC_SUCCESS); + } + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Read, nvIdx, NULL, size, + 0), TPM_RC_SUCCESS); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + } + + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV bits and extend unwritten:", 0); +} + #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) /* Only size 0 with offset 0 selects the digest form; size 0 at any other * offset certifies zero octets (Part 3 Sec.31.16). */ @@ -26305,6 +26367,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_nv_read_zero_size(); test_fwtpm_nv_buffer_max(); test_fwtpm_nv_extend_buffer_max(); + test_fwtpm_nv_bits_extend_unwritten(); #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) test_fwtpm_nv_certify_zero_size_offset(); #endif From 2a833feb9a40e1aeaf2dd3726d964ceb5380e0f4 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 19:00:44 -0800 Subject: [PATCH 019/124] F-17152 - Add the NV_DefineSpace attribute, size and auth consistency checks to fwTPM --- src/fwtpm/fwtpm_command.c | 49 ++++++++++++-- tests/fwtpm_unit_tests.c | 131 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 171 insertions(+), 9 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index a78cf2bb0..01f660403 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -16768,6 +16768,19 @@ static TPM_RC FwNvDefineSpaceEx(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + /* nvIndex and nameAlg are checked as the public area unmarshals, ahead + * of every check on what was unmarshaled */ + if (rc == 0) { + UINT32 nvIdx = publicInfo.nvPublic.nvIndex; + if (nvIdx < NV_INDEX_FIRST || nvIdx > NV_INDEX_LAST) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; + } + /* nameAlg is a TPMI_ALG_HASH, so TPM_ALG_NULL is not allowed */ + else if (TPM2_GetHashDigestSize(publicInfo.nvPublic.nameAlg) <= 0) { + rc = TPM_RC_HASH | TPM_RC_P | TPM_RC_2; + } + } + /* A platform NV index cannot be created while phEnableNV is clear, even * though the new index handle is not yet in the handle area for the * generic disabled-hierarchy gate (TPM 2.0 Part 3 Sec.31.3). */ @@ -16811,11 +16824,14 @@ static TPM_RC FwNvDefineSpaceEx(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } - /* Validate NV index handle range */ + /* auth, less trailing zeros, must fit the nameAlg digest size */ if (rc == 0) { - UINT32 nvIdx = publicInfo.nvPublic.nvIndex; - if (nvIdx < NV_INDEX_FIRST || nvIdx > NV_INDEX_LAST) { - rc = TPM_RC_NV_RANGE; + while (auth.size > 0 && auth.buffer[auth.size - 1] == 0) { + auth.size--; + } + if ((int)auth.size > + TPM2_GetHashDigestSize(publicInfo.nvPublic.nameAlg)) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; } } @@ -16838,6 +16854,24 @@ static TPM_RC FwNvDefineSpaceEx(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + /* TPM 2.0 Part 3 Sec.31.3: an index is defined unwritten and unlocked, + * with some way to read it and some way to write it. CLEAR_STCLEAR + * cannot be combined with a counter or with WRITEDEFINE. */ + if (rc == 0) { + UINT32 attrs = publicInfo.nvPublic.attributes; + if ((attrs & (TPMA_NV_WRITTEN | TPMA_NV_WRITELOCKED | + TPMA_NV_READLOCKED)) != 0 || + (attrs & (TPMA_NV_PPREAD | TPMA_NV_OWNERREAD | + TPMA_NV_AUTHREAD | TPMA_NV_POLICYREAD)) == 0 || + (attrs & (TPMA_NV_PPWRITE | TPMA_NV_OWNERWRITE | + TPMA_NV_AUTHWRITE | TPMA_NV_POLICYWRITE)) == 0 || + ((attrs & TPMA_NV_CLEAR_STCLEAR) != 0 && + ((attrs & TPMA_NV_WRITEDEFINE) != 0 || + ((attrs & TPMA_NV_TPM_NT) >> 4) == TPM_NT_COUNTER))) { + rc = TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_2; + } + } + /* TPMA_NV_PLATFORMCREATE must be set under platform auth and clear under * any other hierarchy (TPM 2.0 Part 3, NV_DefineSpace). */ if (rc == 0 && authHandle == TPM_RH_PLATFORM && @@ -16856,6 +16890,13 @@ static TPM_RC FwNvDefineSpaceEx(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_ATTRIBUTES; } + /* A WRITEALL index has to fit one NV_Write */ + if (rc == 0 && + (publicInfo.nvPublic.attributes & TPMA_NV_WRITEALL) != 0 && + publicInfo.nvPublic.dataSize > MAX_NV_BUFFER_SIZE) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_2; + } + /* Check for duplicate */ if (rc == 0 && FwFindNvIndex(ctx, publicInfo.nvPublic.nvIndex) != NULL) { rc = TPM_RC_NV_DEFINED; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 70aacc843..f9c61841a 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -16281,6 +16281,118 @@ static void test_fwtpm_nv_bits_extend_unwritten(void) fwtpm_pass("NV bits and extend unwritten:", 0); } +/* NV_DefineSpace consistency checks of Part 3 Sec.31.3 */ +static void test_fwtpm_nv_define_consistency(void) +{ + FWTPM_CTX ctx; + UINT32 nvIdx = 0x01500A06; + const UINT32 base = TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | + TPMA_NV_NO_DA; + static const struct { + UINT32 attrs; + UINT16 dataSize; + UINT16 authSz; + TPM_RC expect; + } cases[] = { + { TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_WRITTEN, 8, 0, + TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_2 }, + { TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_READLOCKED, 8, 0, + TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_2 }, + { TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_WRITELOCKED, 8, 0, + TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_2 }, + { TPMA_NV_OWNERWRITE, 8, 0, + TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_2 }, + { TPMA_NV_OWNERREAD, 8, 0, + TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_2 }, + { TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_CLEAR_STCLEAR | + ((UINT32)TPM_NT_COUNTER << 4), 8, 0, + TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_2 }, + { TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_CLEAR_STCLEAR | + TPMA_NV_WRITEDEFINE, 8, 0, + TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_2 }, + { TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_WRITEALL, + MAX_NV_BUFFER_SIZE + 1, 0, TPM_RC_SIZE | TPM_RC_P | TPM_RC_2 }, + { TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD, 8, + WC_SHA256_DIGEST_SIZE + 1, TPM_RC_SIZE | TPM_RC_P | TPM_RC_1 }, + { TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_WRITEALL, + MAX_NV_BUFFER_SIZE, WC_SHA256_DIGEST_SIZE, TPM_RC_SUCCESS } + }; + byte auth[WC_SHA256_DIGEST_SIZE + 1]; + int i, cmdSz, rspSize; + const int authEnd = TPM2_HEADER_SIZE + 4 + 13 + 2 + (int)sizeof(auth); + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + memset(auth, 0x11, sizeof(auth)); + + for (i = 0; i < (int)(sizeof(cases) / sizeof(cases[0])); i++) { + cmdSz = BuildNvDefineCmdEx(gCmd, nvIdx, cases[i].dataSize, + cases[i].attrs | TPMA_NV_NO_DA, auth, cases[i].authSz, NULL, 0); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), cases[i].expect); + } + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + + /* nvIndex and nameAlg are range-checked as the public area unmarshals; + * nameAlg follows authHandle, the auth area, auth, the TPM2B size and + * nvIndex. */ + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, 8, base); + PutU16BE(gCmd + TPM2_HEADER_SIZE + 4 + 13 + 2 + 2 + 4, TPM_ALG_NULL); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_HASH | TPM_RC_P | TPM_RC_2); + + cmdSz = BuildNvDefineCmd(gCmd, HMAC_SESSION_FIRST, 8, base); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + + /* Both are reported ahead of an auth that is too large, nvIndex first */ + cmdSz = BuildNvDefineCmdEx(gCmd, HMAC_SESSION_FIRST, 8, base, auth, + (UINT16)sizeof(auth), NULL, 0); + PutU16BE(gCmd + authEnd + 2 + 4, TPM_ALG_NULL); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + cmdSz = BuildNvDefineCmdEx(gCmd, nvIdx, 8, base, auth, + (UINT16)sizeof(auth), NULL, 0); + PutU16BE(gCmd + authEnd + 2 + 4, TPM_ALG_NULL); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_HASH | TPM_RC_P | TPM_RC_2); + + /* The WRITEALL size is the last check: here the owner asking for a + * platform index comes first */ + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, MAX_NV_BUFFER_SIZE + 1, base | + TPMA_NV_WRITEALL | TPMA_NV_PLATFORMCREATE); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES); + + /* The auth is stored without its trailing zeros */ + auth[2] = 0; + auth[3] = 0; + cmdSz = BuildNvDefineCmdEx(gCmd, nvIdx, 8, base, auth, 4, NULL, 0); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + for (i = 0; i < FWTPM_MAX_NV_INDICES; i++) { + if (ctx.nvIndices[i].inUse && + ctx.nvIndices[i].nvPublic.nvIndex == nvIdx) { + break; + } + } + AssertIntNE(i, FWTPM_MAX_NV_INDICES); + AssertIntEQ(ctx.nvIndices[i].authValue.size, 2); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV_DefineSpace consistency:", 0); +} + #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) /* Only size 0 with offset 0 selects the digest form; size 0 at any other * offset certifies zero octets (Part 3 Sec.31.16). */ @@ -22869,8 +22981,7 @@ static void test_fwtpm_orderly_counter_recovery(void) FWTPM_CTX ctx, probe; UINT32 index = 0x01500003; UINT32 attrs = TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA | - TPMA_NV_ORDERLY | TPMA_NV_CLEAR_STCLEAR | - ((UINT32)TPM_NT_COUNTER << 4); + TPMA_NV_ORDERLY | ((UINT32)TPM_NT_COUNTER << 4); int pos, rspSize = 0; int (*savedWrite)(void*, word32, const byte*, word32); @@ -23627,8 +23738,9 @@ static void test_fwtpm_read_only_nv_conditional(void) } /* A counter carrying the same two attributes, plus WRITEDEFINE, and left - * written. Part 2 forbids CLEAR_STCLEAR on a counter, but NV_DefineSpace - * accepts it, so the gate cannot rely on the pair being impossible. */ + * written. NV_DefineSpace refuses CLEAR_STCLEAR on a counter, so it is + * set on the stored index, as one persisted by an earlier build may + * have it; the gate cannot rely on the pair being impossible. */ cmdSz = 0; PutU16BE(gCmd + cmdSz, TPM_ST_SESSIONS); cmdSz += 2; PutU32BE(gCmd + cmdSz, 0); cmdSz += 4; @@ -23644,7 +23756,7 @@ static void test_fwtpm_read_only_nv_conditional(void) PutU32BE(gCmd + cmdSz, cntIdx); cmdSz += 4; PutU16BE(gCmd + cmdSz, TPM_ALG_SHA256); cmdSz += 2; PutU32BE(gCmd + cmdSz, TPMA_NV_AUTHWRITE | TPMA_NV_AUTHREAD | - TPMA_NV_ORDERLY | TPMA_NV_CLEAR_STCLEAR | TPMA_NV_WRITEDEFINE | + TPMA_NV_ORDERLY | TPMA_NV_WRITEDEFINE | ((UINT32)TPM_NT_COUNTER << 4)); cmdSz += 4; PutU16BE(gCmd + cmdSz, 0); cmdSz += 2; /* authPolicy size */ PutU16BE(gCmd + cmdSz, 8); cmdSz += 2; /* dataSize */ @@ -23653,6 +23765,14 @@ static void test_fwtpm_read_only_nv_conditional(void) rc = FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); AssertIntEQ(rc, TPM_RC_SUCCESS); AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + for (i = 0; i < FWTPM_MAX_NV_INDICES; i++) { + if (ctx.nvIndices[i].inUse && + ctx.nvIndices[i].nvPublic.nvIndex == cntIdx) { + ctx.nvIndices[i].nvPublic.attributes |= TPMA_NV_CLEAR_STCLEAR; + break; + } + } + AssertIntNE(i, FWTPM_MAX_NV_INDICES); cmdSz = 0; PutU16BE(gCmd + cmdSz, TPM_ST_SESSIONS); cmdSz += 2; @@ -26368,6 +26488,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_nv_buffer_max(); test_fwtpm_nv_extend_buffer_max(); test_fwtpm_nv_bits_extend_unwritten(); + test_fwtpm_nv_define_consistency(); #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) test_fwtpm_nv_certify_zero_size_offset(); #endif From f364f8256f9b4f36e702f35fd44273b66e3562b6 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 19:03:49 -0800 Subject: [PATCH 020/124] F-16228 - Skip NV state validation for trial sessions in fwTPM PolicyNV and PolicyAuthorizeNV --- src/fwtpm/fwtpm_command.c | 62 +++++++------- tests/fwtpm_unit_tests.c | 176 ++++++++++++++++++++++++++++++-------- 2 files changed, 173 insertions(+), 65 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 01f660403..f025e125a 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -14925,15 +14925,6 @@ static TPM_RC FwCmd_PolicyNV(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } - /* Verify caller is authorized to read the NV index */ - if (rc == 0) { - rc = FwNvCheckAccess(authHandle, nvIndex, - nv->nvPublic.attributes, 0, ctx->activeCmdAuthIsPolicy[0]); - } - if (rc == 0 && (nv->nvPublic.attributes & TPMA_NV_READLOCKED)) { - rc = TPM_RC_NV_LOCKED; - } - /* Find policy session */ if (rc == 0) { sess = FwFindSession(ctx, sessHandle); @@ -14955,18 +14946,25 @@ static TPM_RC FwCmd_PolicyNV(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } - /* Validate range */ - if (rc == 0) { - if ((UINT32)offset + operandBSz > nv->nvPublic.dataSize) { - rc = TPM_RC_NV_RANGE; - } + /* A trial session only updates policyDigest, so read access, the index + * state and the range are not validated for it (Part 3 Sec.23.9) */ + if (rc == 0 && sess->sessionType == TPM_SE_POLICY) { + rc = FwNvCheckAccess(authHandle, nvIndex, + nv->nvPublic.attributes, 0, ctx->activeCmdAuthIsPolicy[0]); } - - /* NV must have been written */ - if (rc == 0) { - if (!nv->written) { + if (rc == 0 && sess->sessionType == TPM_SE_POLICY) { + if (nv->nvPublic.attributes & TPMA_NV_READLOCKED) { + rc = TPM_RC_NV_LOCKED; + } + else if (!nv->written) { rc = TPM_RC_NV_UNINITIALIZED; } + else if (offset > nv->nvPublic.dataSize) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; + } + else if (operandBSz > nv->nvPublic.dataSize - offset) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; + } } /* For policy sessions (not trial), compare NV data with operandB. @@ -16478,19 +16476,6 @@ static TPM_RC FwCmd_PolicyAuthorizeNV(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = FW_NV_HANDLE_ERR_2; } - /* Verify caller is authorized to read the NV index */ - if (rc == 0) { - rc = FwNvCheckAccess(authHandle, nvHandle, - nv->nvPublic.attributes, 0, ctx->activeCmdAuthIsPolicy[0]); - } - if (rc == 0 && (nv->nvPublic.attributes & TPMA_NV_READLOCKED)) { - rc = TPM_RC_NV_LOCKED; - } - - if (rc == 0 && !nv->written) { - rc = TPM_RC_NV_UNINITIALIZED; - } - sess = FwFindSession(ctx, sessHandle); if (sess == NULL) { rc = TPM_RC_VALUE; @@ -16506,6 +16491,21 @@ static TPM_RC FwCmd_PolicyAuthorizeNV(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_HASH; } + /* A trial session only updates policyDigest, so read access and the + * index state are not validated for it (Part 3 Sec.23.22) */ + if (rc == 0 && sess->sessionType == TPM_SE_POLICY) { + rc = FwNvCheckAccess(authHandle, nvHandle, + nv->nvPublic.attributes, 0, ctx->activeCmdAuthIsPolicy[0]); + } + if (rc == 0 && sess->sessionType == TPM_SE_POLICY) { + if (nv->nvPublic.attributes & TPMA_NV_READLOCKED) { + rc = TPM_RC_NV_LOCKED; + } + else if (!nv->written) { + rc = TPM_RC_NV_UNINITIALIZED; + } + } + /* For policy sessions (not trial): verify policyDigest == NV data. * Always run TPM2_ConstantCompare over min(sizes) so timing doesn't * leak size match. */ diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index f9c61841a..88ba79e51 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -12477,14 +12477,18 @@ static void test_fwtpm_policy_counter_timer_offset(void) #ifndef FWTPM_NO_NV /* PolicyNV and PolicyAuthorizeNV must verify the caller is authorized to * read the NV index. An OWNER authHandle against an index without - * TPMA_NV_OWNERREAD must be rejected with TPM_RC_NV_AUTHORIZATION. */ + * TPMA_NV_OWNERREAD must be rejected with TPM_RC_NV_AUTHORIZATION by a + * policy session. A trial session skips the read access checks. */ static void test_fwtpm_policynv_owner_read_denied(void) { FWTPM_CTX ctx; int pos, cmdSz, rspSize = 0; + int i; UINT32 sessH; UINT32 nvIdx = 0x01500051; UINT32 attrs = TPMA_NV_OWNERWRITE | TPMA_NV_AUTHREAD | TPMA_NV_NO_DA; + UINT8 sessTypes[2] = { TPM_SE_POLICY, TPM_SE_TRIAL }; + TPM_RC expected[2] = { TPM_RC_NV_AUTHORIZATION, TPM_RC_SUCCESS }; memset(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), 0); @@ -12493,26 +12497,31 @@ static void test_fwtpm_policynv_owner_read_denied(void) FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); - sessH = StartSessionHelper(&ctx, TPM_SE_TRIAL); - AssertIntNE(sessH, 0); + for (i = 0; i < 2; i++) { + sessH = StartSessionHelper(&ctx, sessTypes[i]); + AssertIntNE(sessH, 0); - pos = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; - PutU32BE(gCmd + pos, 0); pos += 4; - PutU32BE(gCmd + pos, TPM_CC_PolicyNV); pos += 4; - PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; /* authHandle */ - PutU32BE(gCmd + pos, nvIdx); pos += 4; - PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); - PutU16BE(gCmd + pos, 0); pos += 2; /* operandB */ - PutU16BE(gCmd + pos, 0); pos += 2; /* offset */ - PutU16BE(gCmd + pos, 0); pos += 2; /* operation */ - PutU32BE(gCmd + 2, (UINT32)pos); - rspSize = 0; - FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_NV_AUTHORIZATION); + pos = 0; + PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU32BE(gCmd + pos, 0); pos += 4; + PutU32BE(gCmd + pos, TPM_CC_PolicyNV); pos += 4; + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; /* authHandle */ + PutU32BE(gCmd + pos, nvIdx); pos += 4; + PutU32BE(gCmd + pos, sessH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 0); pos += 2; /* operandB */ + PutU16BE(gCmd + pos, 0); pos += 2; /* offset */ + PutU16BE(gCmd + pos, 0); pos += 2; /* operation */ + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), expected[i]); - FlushHandle(&ctx, sessH); + FlushHandle(&ctx, sessH); + } + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); FWTPM_Cleanup(&ctx); printf("Test fwTPM:\tPolicyNV OWNER read denied:\tPassed\n"); } @@ -12521,9 +12530,12 @@ static void test_fwtpm_policyauthorizenv_owner_read_denied(void) { FWTPM_CTX ctx; int pos, cmdSz, rspSize = 0; + int i; UINT32 sessH; UINT32 nvIdx = 0x01500052; UINT32 attrs = TPMA_NV_OWNERWRITE | TPMA_NV_AUTHREAD | TPMA_NV_NO_DA; + UINT8 sessTypes[2] = { TPM_SE_POLICY, TPM_SE_TRIAL }; + TPM_RC expected[2] = { TPM_RC_NV_AUTHORIZATION, TPM_RC_SUCCESS }; memset(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), 0); @@ -12532,23 +12544,28 @@ static void test_fwtpm_policyauthorizenv_owner_read_denied(void) FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); - sessH = StartSessionHelper(&ctx, TPM_SE_TRIAL); - AssertIntNE(sessH, 0); + for (i = 0; i < 2; i++) { + sessH = StartSessionHelper(&ctx, sessTypes[i]); + AssertIntNE(sessH, 0); - pos = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; - PutU32BE(gCmd + pos, 0); pos += 4; - PutU32BE(gCmd + pos, TPM_CC_PolicyAuthorizeNV); pos += 4; - PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; /* authHandle */ - PutU32BE(gCmd + pos, nvIdx); pos += 4; - PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); - PutU32BE(gCmd + 2, (UINT32)pos); - rspSize = 0; - FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_NV_AUTHORIZATION); + pos = 0; + PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU32BE(gCmd + pos, 0); pos += 4; + PutU32BE(gCmd + pos, TPM_CC_PolicyAuthorizeNV); pos += 4; + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; /* authHandle */ + PutU32BE(gCmd + pos, nvIdx); pos += 4; + PutU32BE(gCmd + pos, sessH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), expected[i]); - FlushHandle(&ctx, sessH); + FlushHandle(&ctx, sessH); + } + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); FWTPM_Cleanup(&ctx); printf("Test fwTPM:\tPolicyAuthorizeNV OWNER read denied:\tPassed\n"); } @@ -12619,6 +12636,96 @@ static void test_fwtpm_policy_nv_read_locked(void) fwtpm_pass("Policy NV read lock:", 0); } +/* Owner-authorized PolicyNV (zero operandB, TPM_EO_EQ) or + * PolicyAuthorizeNV */ +static TPM_RC SendPolicyNvCmd(FWTPM_CTX* ctx, UINT32 commandCode, + UINT32 nvIndex, UINT32 sessH, UINT16 operandSz, UINT16 offset) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, commandCode); + int rspSize = 0; + + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, nvIndex); pos += 4; + PutU32BE(gCmd + pos, sessH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + if (commandCode == TPM_CC_PolicyNV) { + PutU16BE(gCmd + pos, operandSz); pos += 2; + memset(gCmd + pos, 0, operandSz); pos += operandSz; + PutU16BE(gCmd + pos, offset); pos += 2; + PutU16BE(gCmd + pos, TPM_EO_EQ); pos += 2; + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* A trial session only updates policyDigest: PolicyNV and PolicyAuthorizeNV + * do not validate the index state or range (Part 3 Sec.23.9, Sec.23.22). */ +static void test_fwtpm_policy_nv_trial_no_validation(void) +{ + FWTPM_CTX ctx; + UINT32 nvIdx = 0x01500A07; + UINT32 sessH, polH; + int cmdSz, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, 8, TPMA_NV_OWNERWRITE | + TPMA_NV_OWNERREAD | TPMA_NV_READ_STCLEAR | TPMA_NV_NO_DA); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + /* Unwritten index, then an operand past its end, then read locked */ + sessH = StartSessionHelper(&ctx, TPM_SE_TRIAL); + AssertIntNE(sessH, 0); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyNV, nvIdx, sessH, 2, 0), + TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyAuthorizeNV, nvIdx, sessH, + 0, 0), TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyNV, nvIdx, sessH, 2, 8), + TPM_RC_SUCCESS); + + /* A policy session checks the index state, then the offset and the + * operand against the index size */ + polH = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(polH, 0); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyNV, nvIdx, polH, 2, 8), + TPM_RC_NV_UNINITIALIZED); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyNV, nvIdx, polH, 2, 9), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyNV, nvIdx, polH, 2, 7), + TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyNV, nvIdx, polH, 0, 8), + TPM_RC_SUCCESS); + FlushHandle(&ctx, polH); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_ReadLock, nvIdx), + TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyNV, nvIdx, sessH, 2, 0), + TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyAuthorizeNV, nvIdx, sessH, + 0, 0), TPM_RC_SUCCESS); + FlushHandle(&ctx, sessH); + + /* A policy session still validates */ + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(sessH, 0); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyNV, nvIdx, sessH, 2, 0), + TPM_RC_NV_LOCKED); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyAuthorizeNV, nvIdx, sessH, + 0, 0), TPM_RC_NV_LOCKED); + FlushHandle(&ctx, sessH); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Policy NV trial session:", 0); +} + /* PolicyLocality must bind a locality constraint that is enforced when the * policy session authorizes an entity. A session satisfying a locality-4 * policy must not authorize a command issued at locality 0. */ @@ -26403,6 +26510,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_policynv_owner_read_denied(); test_fwtpm_policyauthorizenv_owner_read_denied(); test_fwtpm_policy_nv_read_locked(); + test_fwtpm_policy_nv_trial_no_validation(); test_fwtpm_policy_locality_enforced(); test_fwtpm_policy_cphash_enforced(); #ifdef WOLFTPM_SPDM From b4901901970021b5797e1da108b61eed7e394b68 Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 19:07:21 -0800 Subject: [PATCH 021/124] F-16227 - Read a TPMT_HA from the NV index in fwTPM PolicyAuthorizeNV --- src/fwtpm/fwtpm_command.c | 42 +++++++++++++--------- tests/fwtpm_unit_tests.c | 74 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 17 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index f025e125a..436313aef 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -16456,10 +16456,8 @@ static TPM_RC FwCmd_PolicyAuthorizeNV(FWTPM_CTX* ctx, TPM2_Packet* cmd, byte ccBuf[4]; UINT32 cc = TPM_CC_PolicyAuthorizeNV; int hashInit = 0; - int nvSizeMismatch; - int sessSizeMismatch; - int policyDiff; - word32 policyCmpSz; + UINT16 nvHashAlg; + int nvHashSz; (void)cmdSize; @@ -16506,20 +16504,30 @@ static TPM_RC FwCmd_PolicyAuthorizeNV(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } - /* For policy sessions (not trial): verify policyDigest == NV data. - * Always run TPM2_ConstantCompare over min(sizes) so timing doesn't - * leak size match. */ + /* For policy sessions (not trial): the index holds a TPMT_HA, the + * session hash algorithm then the approved policyDigest. Octets after + * it are ignored (Part 3 Sec.23.22). */ if (rc == 0 && sess->sessionType == TPM_SE_POLICY) { - nvSizeMismatch = ((int)nv->nvPublic.dataSize != dSz); - sessSizeMismatch = ((int)sess->policyDigest.size != dSz); - policyCmpSz = (sess->policyDigest.size < nv->nvPublic.dataSize) ? - sess->policyDigest.size : nv->nvPublic.dataSize; - if (policyCmpSz > (word32)dSz) - policyCmpSz = (word32)dSz; - policyDiff = TPM2_ConstantCompare(sess->policyDigest.buffer, - nv->data, policyCmpSz); - if (nvSizeMismatch | sessSizeMismatch | policyDiff) { - rc = TPM_RC_POLICY_FAIL; + if (nv->nvPublic.dataSize < sizeof(UINT16)) { + rc = TPM_RC_INSUFFICIENT; + } + } + if (rc == 0 && sess->sessionType == TPM_SE_POLICY) { + nvHashAlg = FwLoadU16BE(nv->data); + nvHashSz = TPM2_GetHashDigestSize(nvHashAlg); + if (nvHashSz <= 0) { + rc = TPM_RC_HASH; + } + else if ((int)nv->nvPublic.dataSize < (int)sizeof(UINT16) + nvHashSz) { + rc = TPM_RC_INSUFFICIENT; + } + else if (nvHashAlg != sess->authHash) { + rc = TPM_RC_HASH; + } + else if ((int)sess->policyDigest.size != dSz || + TPM2_ConstantCompare(sess->policyDigest.buffer, + nv->data + sizeof(UINT16), (word32)dSz) != 0) { + rc = TPM_RC_VALUE; } } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 88ba79e51..5b42fc068 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -12726,6 +12726,79 @@ static void test_fwtpm_policy_nv_trial_no_validation(void) fwtpm_pass("Policy NV trial session:", 0); } +/* PolicyAuthorizeNV reads a TPMT_HA from the index: a hash algorithm that + * must be the session's, then the approved digest, with any trailing octets + * ignored (Part 3 Sec.23.22). */ +static void test_fwtpm_policy_authorize_nv_tpmt_ha(void) +{ + FWTPM_CTX ctx; + UINT32 nvIdx = 0x01500A08; + UINT32 shortIdx = 0x01500A09; + UINT32 sessH; + byte data[2 + TPM_SHA384_DIGEST_SIZE]; + int i, cmdSz, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + for (i = 0; i < 2; i++) { + cmdSz = BuildNvDefineCmd(gCmd, (i == 0) ? nvIdx : shortIdx, + (UINT16)((i == 0) ? sizeof(data) : 2 + WC_SHA256_DIGEST_SIZE - 1), + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + } + + /* A new policy session has an all-zero policyDigest */ + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(sessH, 0); + + memset(data, 0, sizeof(data)); + PutU16BE(data, TPM_ALG_SHA256); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, shortIdx, data, + 2 + WC_SHA256_DIGEST_SIZE - 1, 0), TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyAuthorizeNV, shortIdx, + sessH, 0, 0), TPM_RC_INSUFFICIENT); + + /* A bare digest starts with what parses as an unknown algorithm */ + PutU16BE(data, 0); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, data, + (UINT16)sizeof(data), 0), TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyAuthorizeNV, nvIdx, sessH, + 0, 0), TPM_RC_HASH); + + PutU16BE(data, TPM_ALG_SHA384); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, data, + (UINT16)sizeof(data), 0), TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyAuthorizeNV, nvIdx, sessH, + 0, 0), TPM_RC_HASH); + + PutU16BE(data, TPM_ALG_SHA256); + data[2] = 1; + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, data, + (UINT16)sizeof(data), 0), TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyAuthorizeNV, nvIdx, sessH, + 0, 0), TPM_RC_VALUE); + + /* Matching digest, followed by octets that are not part of the TPMT_HA */ + data[2] = 0; + memset(data + 2 + WC_SHA256_DIGEST_SIZE, 0xEE, + sizeof(data) - 2 - WC_SHA256_DIGEST_SIZE); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, data, + (UINT16)sizeof(data), 0), TPM_RC_SUCCESS); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyAuthorizeNV, nvIdx, sessH, + 0, 0), TPM_RC_SUCCESS); + FlushHandle(&ctx, sessH); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, shortIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("PolicyAuthorizeNV TPMT_HA:", 0); +} + /* PolicyLocality must bind a locality constraint that is enforced when the * policy session authorizes an entity. A session satisfying a locality-4 * policy must not authorize a command issued at locality 0. */ @@ -26511,6 +26584,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_policyauthorizenv_owner_read_denied(); test_fwtpm_policy_nv_read_locked(); test_fwtpm_policy_nv_trial_no_validation(); + test_fwtpm_policy_authorize_nv_tpmt_ha(); test_fwtpm_policy_locality_enforced(); test_fwtpm_policy_cphash_enforced(); #ifdef WOLFTPM_SPDM From aa6e5aaadb227eb30f32920734b8c7e2effff402 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 06:42:58 -0800 Subject: [PATCH 022/124] Reject a fwTPM password authorization that has no handle to authorize --- src/fwtpm/fwtpm_command.c | 10 ++- tests/fwtpm_unit_tests.c | 152 +++++++++++++++++++++++--------------- 2 files changed, 97 insertions(+), 65 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 436313aef..556135537 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -22846,8 +22846,8 @@ static int FwAllowPreStartupSpdmProbe(FWTPM_CTX* ctx, TPM_CC cmdCode) * password session carries no use attribute, auditExclusive and auditReset * need audit, only one session audits, decrypt and encrypt need a sized * first command or response parameter, and a session that authorizes no - * handle must be there to decrypt, encrypt or audit. An extra password - * session holds no state and is tolerated. */ + * handle must be there to decrypt, encrypt or audit. A password session + * always authorizes a handle (Part 1 Sec.19.4). */ static TPM_RC FwCheckSessionAttributes(const FWTPM_CMD_ENTRY* entry, UINT32 sessHandle, UINT8 attribs, int sessIdx, int* auditCnt) { @@ -22859,6 +22859,9 @@ static TPM_RC FwCheckSessionAttributes(const FWTPM_CMD_ENTRY* entry, flags &= (UINT16)~(FW_CMD_FLAG_ENC | FW_CMD_FLAG_DEC); #endif if (sessHandle == TPM_RS_PW) { + if (sessIdx >= (int)entry->authHandleCnt) { + return TPM_RC_HANDLE; + } if (use != 0 || (attribs & (TPMA_SESSION_auditExclusive | TPMA_SESSION_auditReset)) != 0) { return TPM_RC_ATTRIBUTES; @@ -22882,8 +22885,7 @@ static TPM_RC FwCheckSessionAttributes(const FWTPM_CMD_ENTRY* entry, return TPM_RC_ATTRIBUTES; } } - if (sessHandle != TPM_RS_PW && sessIdx >= (int)entry->authHandleCnt && - use == 0) { + if (sessIdx >= (int)entry->authHandleCnt && use == 0) { return TPM_RC_ATTRIBUTES; } return TPM_RC_SUCCESS; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 5b42fc068..a67bd3c86 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -11430,11 +11430,10 @@ static void test_fwtpm_bound_session_auth_change(void) static TPM_RC SendPolicyCmd(FWTPM_CTX* ctx, UINT32 cc, UINT32 sessHandle) { int pos = 0, rspSize = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; PutU32BE(gCmd + pos, 0); pos += 4; PutU32BE(gCmd + pos, cc); pos += 4; PutU32BE(gCmd + pos, sessHandle); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU32BE(gCmd + 2, (UINT32)pos); FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); return GetRspRC(gRsp); @@ -11842,11 +11841,10 @@ static void test_fwtpm_verifysignature_policyauthorize_roundtrip(void) AssertIntNE(sessH, 0); pos = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; PutU32BE(gCmd + pos, 0); pos += 4; PutU32BE(gCmd + pos, TPM_CC_PolicyAuthorize); pos += 4; PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, sizeof(approvedPolicy)); pos += 2; memcpy(gCmd + pos, approvedPolicy, sizeof(approvedPolicy)); pos += sizeof(approvedPolicy); @@ -11982,11 +11980,10 @@ static void test_fwtpm_policy_command_code(void) AssertIntNE(sessH, 0); /* PolicyCommandCode(sessHandle, CC_GetRandom) */ pos = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; PutU32BE(gCmd + pos, 0); pos += 4; PutU32BE(gCmd + pos, TPM_CC_PolicyCommandCode); pos += 4; PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU32BE(gCmd + pos, TPM_CC_GetRandom); pos += 4; PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; @@ -12008,11 +12005,10 @@ static void test_fwtpm_policy_locality(void) AssertIntNE(sessH, 0); /* PolicyLocality(sessHandle, locality=1) */ pos = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; PutU32BE(gCmd + pos, 0); pos += 4; PutU32BE(gCmd + pos, TPM_CC_PolicyLocality); pos += 4; PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); gCmd[pos++] = 1; /* locality = 1 */ PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; @@ -12029,9 +12025,8 @@ static TPM_RC SendPolicyTemplate(FWTPM_CTX* ctx, UINT32 sessH, const byte* templateHash) { int pos = 0, rspSize = 0; - pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_PolicyTemplate); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_PolicyTemplate); PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, WC_SHA256_DIGEST_SIZE); pos += 2; memcpy(gCmd + pos, templateHash, WC_SHA256_DIGEST_SIZE); pos += WC_SHA256_DIGEST_SIZE; @@ -12068,9 +12063,9 @@ static void test_fwtpm_policy_template_create_only(void) TPM_RC_SUCCESS); AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyGetDigest, sessH), TPM_RC_SUCCESS); - dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE + 4); + dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE); AssertIntEQ(dSz, 32); - memcpy(digest, gRsp + TPM2_HEADER_SIZE + 6, dSz); + memcpy(digest, gRsp + TPM2_HEADER_SIZE + 2, dSz); FlushHandle(&ctx, sessH); /* ownerPolicy = PolicyTemplate(templateHash) */ @@ -12132,11 +12127,10 @@ static void test_fwtpm_policy_pcr(void) AssertIntNE(sessH, 0); /* PolicyPCR(sessHandle, pcrDigest=empty, pcrSelect=count 0) */ pos = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; PutU32BE(gCmd + pos, 0); pos += 4; PutU32BE(gCmd + pos, TPM_CC_PolicyPCR); pos += 4; PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, 0); pos += 2; /* pcrDigest size = 0 */ PutU32BE(gCmd + pos, 0); pos += 4; /* pcrSelect count = 0 */ PutU32BE(gCmd + 2, (UINT32)pos); @@ -12173,11 +12167,10 @@ static void test_fwtpm_policy_ticket_zero_digest_rejected(void) memset(fakeAuthName + 2, 0xAB, 32); pos = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; PutU32BE(gCmd + pos, 0); pos += 4; PutU32BE(gCmd + pos, TPM_CC_PolicyTicket); pos += 4; PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, 8); pos += 2; /* timeout TPM2B */ memset(gCmd + pos, 0, 8); pos += 8; PutU16BE(gCmd + pos, 0); pos += 2; /* cpHashA TPM2B size = 0 */ @@ -12211,11 +12204,10 @@ static int BuildPolicyAuthorizeNullTicketCmd(UINT32 sessH) PutU16BE(fakeKeyName, TPM_ALG_SHA256); memset(fakeKeyName + 2, 0xAB, 32); - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; PutU32BE(gCmd + pos, 0); pos += 4; PutU32BE(gCmd + pos, TPM_CC_PolicyAuthorize); pos += 4; PutU32BE(gCmd + pos, sessH); pos += 4; /* policySession handle */ - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, 32); pos += 2; /* approvedPolicy size */ memset(gCmd + pos, 0x00, 32); pos += 32; /* approvedPolicy = zeros */ PutU16BE(gCmd + pos, 0); pos += 2; /* policyRef size = 0 */ @@ -12290,9 +12282,9 @@ static void test_fwtpm_policy_password_digest(void) TPM_CC_PolicyAuthValue, sessH), TPM_RC_SUCCESS); AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyGetDigest, sessH), TPM_RC_SUCCESS); - AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4), + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE), WC_SHA256_DIGEST_SIZE); - memcpy(digest[i], gRsp + TPM2_HEADER_SIZE + 6, WC_SHA256_DIGEST_SIZE); + memcpy(digest[i], gRsp + TPM2_HEADER_SIZE + 2, WC_SHA256_DIGEST_SIZE); FlushHandle(&ctx, sessH); } AssertIntEQ(memcmp(digest[0], digest[1], WC_SHA256_DIGEST_SIZE), 0); @@ -12305,10 +12297,9 @@ static TPM_RC SendPolicyOR(FWTPM_CTX* ctx, UINT32 sessH, UINT32 count, const byte* list, int listSz) { int rspSize = 0; - int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_PolicyOR); + int pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_PolicyOR); PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU32BE(gCmd + pos, count); pos += 4; memcpy(gCmd + pos, list, listSz); pos += listSz; PutU32BE(gCmd + 2, (UINT32)pos); @@ -12381,9 +12372,9 @@ static void test_fwtpm_policy_or_mixed_sizes(void) TPM_RC_SUCCESS); AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyGetDigest, sessH), TPM_RC_SUCCESS); - AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4), + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE), WC_SHA256_DIGEST_SIZE); - AssertIntEQ(memcmp(gRsp + TPM2_HEADER_SIZE + 6, expect, + AssertIntEQ(memcmp(gRsp + TPM2_HEADER_SIZE + 2, expect, WC_SHA256_DIGEST_SIZE), 0); FlushHandle(&ctx, sessH); } @@ -12416,9 +12407,9 @@ static void test_fwtpm_policy_name_hash_repeat(void) AssertIntNE(sessH, 0); for (i = 0; i < 2; i++) { - pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_PolicyNameHash); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_PolicyNameHash); PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, WC_SHA256_DIGEST_SIZE); pos += 2; memset(gCmd + pos, 0x33, WC_SHA256_DIGEST_SIZE); pos += WC_SHA256_DIGEST_SIZE; @@ -12438,11 +12429,10 @@ static TPM_RC SendPolicyCounterTimer(FWTPM_CTX* ctx, UINT32 sessH, UINT16 operandSz, UINT16 offset) { int rspSize = 0; - int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + int pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_PolicyCounterTimer); PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, operandSz); pos += 2; memset(gCmd + pos, 0, operandSz); pos += operandSz; PutU16BE(gCmd + pos, offset); pos += 2; @@ -12820,11 +12810,10 @@ static void test_fwtpm_policy_locality_enforced(void) /* PolicyLocality(bit 4 = locality 4 only) */ pos = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; PutU32BE(gCmd + pos, 0); pos += 4; PutU32BE(gCmd + pos, TPM_CC_PolicyLocality); pos += 4; PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); gCmd[pos++] = 0x10; PutU32BE(gCmd + 2, (UINT32)pos); FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); @@ -12833,9 +12822,9 @@ static void test_fwtpm_policy_locality_enforced(void) /* Read back the resulting policyDigest */ AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyGetDigest, sessH), TPM_RC_SUCCESS); - dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE + 4); + dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE); AssertIntEQ(dSz, 32); - memcpy(digest, gRsp + TPM2_HEADER_SIZE + 6, dSz); + memcpy(digest, gRsp + TPM2_HEADER_SIZE + 2, dSz); /* Bind that policy to the owner hierarchy */ pos = 0; @@ -12871,11 +12860,10 @@ static TPM_RC SendPolicyTransportSPDM(FWTPM_CTX* ctx, UINT32 sessH, const byte* req, UINT16 reqSz, const byte* tpm, UINT16 tpmSz) { int pos = 0, rspSize = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; PutU32BE(gCmd + pos, 0); pos += 4; PutU32BE(gCmd + pos, TPM_CC_PolicyTransportSPDM); pos += 4; PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, reqSz); pos += 2; if (reqSz > 0) { memcpy(gCmd + pos, req, reqSz); pos += reqSz; } PutU16BE(gCmd + pos, tpmSz); pos += 2; @@ -12890,9 +12878,9 @@ static void ReadPolicyDigest(FWTPM_CTX* ctx, UINT32 sessH, byte* digest, { AssertIntEQ(SendPolicyCmd(ctx, TPM_CC_PolicyGetDigest, sessH), TPM_RC_SUCCESS); - *dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE + 4); + *dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE); AssertIntEQ(*dSz, 32); - memcpy(digest, gRsp + TPM2_HEADER_SIZE + 6, *dSz); + memcpy(digest, gRsp + TPM2_HEADER_SIZE + 2, *dSz); } /* Vectors: SHA-256 of (zeros[32] || 0x000001A1 || scKeyNameHash) where @@ -12975,11 +12963,10 @@ static void test_fwtpm_policy_transport_spdm(void) /* Truncated command with no name fields is rejected, not read as empty */ tpos = 0; trspSize = 0; - PutU16BE(gCmd + tpos, TPM_ST_SESSIONS); tpos += 2; + PutU16BE(gCmd + tpos, TPM_ST_NO_SESSIONS); tpos += 2; PutU32BE(gCmd + tpos, 0); tpos += 4; PutU32BE(gCmd + tpos, TPM_CC_PolicyTransportSPDM); tpos += 4; PutU32BE(gCmd + tpos, sessH); tpos += 4; - tpos = AppendPwAuth(gCmd, tpos, NULL, 0); PutU32BE(gCmd + 2, (UINT32)tpos); FWTPM_ProcessCommand(&ctx, gCmd, tpos, gRsp, &trspSize, 0); AssertIntEQ(GetRspRC(gRsp), TPM_RC_COMMAND_SIZE); @@ -13184,9 +13171,9 @@ static void test_fwtpm_policy_cphash_enforced(void) AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyGetDigest, sessH), TPM_RC_SUCCESS); - dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE + 4); + dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE); AssertIntEQ(dSz, 32); - memcpy(digest, gRsp + TPM2_HEADER_SIZE + 6, dSz); + memcpy(digest, gRsp + TPM2_HEADER_SIZE + 2, dSz); pos = 0; PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; @@ -13461,11 +13448,10 @@ static TPM_RC SendPolicyPcrCmd(FWTPM_CTX* ctx, UINT32 sessH, const byte* digest, UINT16 digestSz) { int pos = 0, rspSize = 0; - PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; + PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; PutU32BE(gCmd + pos, 0); pos += 4; PutU32BE(gCmd + pos, TPM_CC_PolicyPCR); pos += 4; PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, digestSz); pos += 2; if (digestSz > 0) { memcpy(gCmd + pos, digest, digestSz); pos += digestSz; @@ -13541,9 +13527,9 @@ static void test_fwtpm_policy_pcr_change_invalidates(void) AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyGetDigest, sessH), TPM_RC_SUCCESS); - dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE + 4); + dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE); AssertIntEQ(dSz, 32); - memcpy(digest, gRsp + TPM2_HEADER_SIZE + 6, dSz); + memcpy(digest, gRsp + TPM2_HEADER_SIZE + 2, dSz); pos = 0; PutU16BE(gCmd + pos, TPM_ST_SESSIONS); pos += 2; @@ -13659,10 +13645,9 @@ static void test_fwtpm_admin_authorization_requires_policy(void) FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); AssertIntEQ(GetRspRC(gRsp), TPM_RC_POLICY_FAIL); - pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_PolicyCommandCode); PutU32BE(gCmd + pos, policySessHandle); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU32BE(gCmd + pos, TPM_CC_ObjectChangeAuth); pos += 4; PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; @@ -17986,9 +17971,8 @@ static void test_fwtpm_duplicate_encrypted_needs_new_parent(void) sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); AssertIntNE(sessH, 0); - pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_PolicyCommandCode); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_PolicyCommandCode); PutU32BE(gCmd + pos, sessH); pos += 4; - pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU32BE(gCmd + pos, TPM_CC_Duplicate); pos += 4; PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; @@ -18725,7 +18709,9 @@ static void SweepSessionHmac(FWTPM_CTX* ctx, FWTPM_Session* sess, UINT32 cc, * in its authorization area (Part 1 Sec.19.6), whether the session is the * only one or follows a password authorization. A wrong HMAC fails with * TPM_RC_BAD_AUTH and leaves the session nonce unchanged, and the correct - * HMAC passes. The listed commands reject the owner-handle authorization + * HMAC passes. A password authorization on a command with no handle to + * authorize fails with TPM_RC_HANDLE (Part 1 Sec.19.4). The listed commands + * reject the owner-handle authorization * area before any HMAC is checked: the context commands take no sessions, * two authorized handles need two sessions, and a hierarchy in the ADMIN or * DUP role needs a policy session. The ADMIN-role commands are swept again @@ -18763,6 +18749,28 @@ static void test_fwtpm_session_hmac_sweep(void) { TPM_CC_Certify, TPM_RC_AUTH_MISSING }, { TPM_CC_ActivateCredential, TPM_RC_AUTH_MISSING }, }; + /* commands whose handles need no authorization */ + static const UINT32 noAuth[] = { + TPM_CC_ReadPublic, TPM_CC_VerifySignature, TPM_CC_RSA_Encrypt, + TPM_CC_ECDH_KeyGen, TPM_CC_ECC_Encrypt, TPM_CC_StartAuthSession, + TPM_CC_PolicyGetDigest, TPM_CC_PolicyRestart, TPM_CC_PolicyPCR, + TPM_CC_PolicyPassword, TPM_CC_PolicyAuthValue, + TPM_CC_PolicyCommandCode, TPM_CC_PolicyOR, TPM_CC_PolicyAuthorize, + TPM_CC_PolicyLocality, TPM_CC_PolicySigned, + TPM_CC_PolicyPhysicalPresence, TPM_CC_PolicyCpHash, + TPM_CC_PolicyParameters, TPM_CC_PolicyCapability, + TPM_CC_PolicyNameHash, TPM_CC_PolicyDuplicationSelect, + TPM_CC_PolicyNvWritten, TPM_CC_PolicyTemplate, + TPM_CC_PolicyCounterTimer, TPM_CC_PolicyTicket, TPM_CC_NV_ReadPublic, + TPM_CC_NV_ReadPublic2, TPM_CC_MakeCredential, + #ifdef WOLFTPM_SPDM + TPM_CC_PolicyTransportSPDM, + #endif + #ifdef WOLFTPM_PQC + TPM_CC_Encapsulate, TPM_CC_SignSequenceStart, + TPM_CC_VerifySequenceStart, TPM_CC_VerifyDigestSignature, + #endif + }; FWTPM_CTX ctx; FWTPM_Session* sess; FWTPM_Object* key = NULL; @@ -18819,6 +18827,15 @@ static void test_fwtpm_session_hmac_sweep(void) nHandles = (int)TpmaCcHandles(tpmaList[i]); for (withPw = 0; withPw <= 1; withPw++) { expectRc = TPM_RC_BAD_AUTH; + if (withPw && nHandles == 0) { + expectRc = TPM_RC_HANDLE; + } + for (j = 0; withPw && j < sizeof(noAuth) / sizeof(noAuth[0]); + j++) { + if (noAuth[j] == cc) { + expectRc = TPM_RC_HANDLE; + } + } for (j = 0; j < sizeof(early) / sizeof(early[0]); j++) { if (early[j].cc == cc) { expectRc = withPw ? early[j].rcPw : early[j].rc; @@ -19312,13 +19329,22 @@ static void test_fwtpm_session_attribute_rules(void) AssertIntEQ(GetRspRC(gRsp), cases[i].rc); } - /* a password session cannot decrypt, encrypt or audit */ + /* a password session needs a handle to authorize (Part 1 Sec.19.4) */ pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_GetRandom); - pos = AppendAuth(gCmd, pos, TPM_RS_PW, TPMA_SESSION_encrypt, NULL, 0); + pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, 16); pos += 2; PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_HANDLE); + + /* and cannot decrypt, encrypt or audit */ + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Clear); + PutU32BE(gCmd + pos, TPM_RH_LOCKOUT); pos += 4; + pos = AppendAuth(gCmd, pos, TPM_RS_PW, TPMA_SESSION_audit, NULL, 0); + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES); FlushHandle(&ctx, sessH); @@ -24346,15 +24372,19 @@ static int fwtpm_build_ecc_crypt(UINT32 cc, UINT32 keyHandle, { int cmdSz = 0; - PutU16BE(gCmd + cmdSz, TPM_ST_SESSIONS); cmdSz += 2; + /* ECC_Encrypt has no authorization handle, so it carries no session. */ + PutU16BE(gCmd + cmdSz, (cc == TPM_CC_ECC_Encrypt) ? + TPM_ST_NO_SESSIONS : TPM_ST_SESSIONS); cmdSz += 2; PutU32BE(gCmd + cmdSz, 0); cmdSz += 4; PutU32BE(gCmd + cmdSz, cc); cmdSz += 4; PutU32BE(gCmd + cmdSz, keyHandle); cmdSz += 4; - PutU32BE(gCmd + cmdSz, 9); cmdSz += 4; - PutU32BE(gCmd + cmdSz, TPM_RS_PW); cmdSz += 4; - PutU16BE(gCmd + cmdSz, 0); cmdSz += 2; - gCmd[cmdSz++] = 0; - PutU16BE(gCmd + cmdSz, 0); cmdSz += 2; + if (cc != TPM_CC_ECC_Encrypt) { + PutU32BE(gCmd + cmdSz, 9); cmdSz += 4; + PutU32BE(gCmd + cmdSz, TPM_RS_PW); cmdSz += 4; + PutU16BE(gCmd + cmdSz, 0); cmdSz += 2; + gCmd[cmdSz++] = 0; + PutU16BE(gCmd + cmdSz, 0); cmdSz += 2; + } if (bodyIsTpm2b) { PutU16BE(gCmd + cmdSz, (UINT16)bodySz); cmdSz += 2; } @@ -24444,8 +24474,8 @@ static void test_fwtpm_ecc_encrypt(void) AssertIntEQ(rc, TPM_RC_SUCCESS); AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); - /* Response: parameterSize(4) then C1 || C2 || C3 */ - pos = TPM2_HEADER_SIZE + 4; + /* Response: C1 || C2 || C3 */ + pos = TPM2_HEADER_SIZE; c1Outer = GetU16BE(gRsp + pos); cipherSz = 2 + c1Outer; /* C1 with its outer size */ c2Sz = GetU16BE(gRsp + pos + cipherSz); @@ -25849,9 +25879,9 @@ static void test_fwtpm_policy_parameters_enforced(void) AssertIntNE(sessH, 0); AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyGetDigest, sessH), TPM_RC_SUCCESS); - dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE + 4); + dSz = GetU16BE(gRsp + TPM2_HEADER_SIZE); AssertIntEQ(dSz, WC_SHA256_DIGEST_SIZE); - memcpy(digest, gRsp + TPM2_HEADER_SIZE + 6, dSz); + memcpy(digest, gRsp + TPM2_HEADER_SIZE + 2, dSz); FlushHandle(&ctx, sessH); pos = 0; From 58c960874dd1335d2cfa5a7b4614bf3bf3860380 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 06:50:30 -0800 Subject: [PATCH 023/124] F-18071 - Reset the fwTPM PCR authValues on Startup(CLEAR) --- src/fwtpm/fwtpm_command.c | 24 +++++++++++++++++ tests/fwtpm_unit_tests.c | 54 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 556135537..ca3fe1bb3 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -1164,6 +1164,7 @@ static TPM_RC FwCmd_Startup(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, FWTPM_DECLARE_BUF(oldNvData, FWTPM_MAX_NV_DATA); int oldNvDataAllocated = 0; #endif + FWTPM_DECLARE_BUF(oldPcrAuth, sizeof(ctx->pcrAuth)); int wasOrderly = ctx->nvOrderly; @@ -1420,6 +1421,29 @@ static TPM_RC FwCmd_Startup(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, TPM2_ForceZero(&oldPlatformPolicy, sizeof(oldPlatformPolicy)); } + /* PCR authValues are state-clear data (Part 3 Sec.22.7): kept by + * Startup(STATE), reset to the Empty Auth by Startup(CLEAR). */ + if (rc == 0 && startupType == TPM_SU_CLEAR) { + for (i = 0; i < IMPLEMENTATION_PCR; i++) { + if (ctx->pcrAuth[i].size > 0) + break; + } + if (i < IMPLEMENTATION_PCR) { + FWTPM_ALLOC_BUF(oldPcrAuth, sizeof(ctx->pcrAuth)); + if (rc == 0) { + XMEMCPY(oldPcrAuth, ctx->pcrAuth, sizeof(ctx->pcrAuth)); + TPM2_ForceZero(ctx->pcrAuth, sizeof(ctx->pcrAuth)); + rc = FWTPM_NV_SavePcrAuth(ctx); + if (rc != 0) { + XMEMCPY(ctx->pcrAuth, oldPcrAuth, + sizeof(ctx->pcrAuth)); + } + TPM2_ForceZero(oldPcrAuth, sizeof(ctx->pcrAuth)); + } + FWTPM_FREE_BUF(oldPcrAuth); + } + } + /* phEnable is SET on every _TPM_Init/Startup (TPM 2.0 Part 2 * TPMS_STARTUP_CLEAR), regardless of CLEAR vs STATE. */ ctx->phDisabled = 0; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index a67bd3c86..e079e7b1d 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -25925,6 +25925,59 @@ static void test_fwtpm_policy_parameters_enforced(void) #endif /* !FWTPM_NO_NV */ #endif /* !FWTPM_NO_POLICY */ +static TPM_RC SendPcrSetAuthValue(FWTPM_CTX* ctx, UINT32 pcrHandle, + const byte* oldAuth, int oldAuthSz, const byte* newAuth, int newAuthSz) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + TPM_CC_PCR_SetAuthValue); + int rspSize = 0; + + PutU32BE(gCmd + pos, pcrHandle); pos += 4; + pos = AppendPwAuth(gCmd, pos, oldAuth, oldAuthSz); + PutU16BE(gCmd + pos, (UINT16)newAuthSz); pos += 2; + if (newAuthSz > 0) { + memcpy(gCmd + pos, newAuth, newAuthSz); + pos += newAuthSz; + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* PCR authValues are state-clear data: kept by Startup(STATE), reset to the + * Empty Auth by Startup(CLEAR). */ +static void test_fwtpm_pcr_auth_startup_clear(void) +{ + FWTPM_CTX ctx; + static const byte pcrAuth[] = "pcr-auth"; + const int pcrAuthSz = (int)sizeof(pcrAuth) - 1; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(SendPcrSetAuthValue(&ctx, FW_TEST_PCR, NULL, 0, pcrAuth, + pcrAuthSz), TPM_RC_SUCCESS); + AssertIntEQ(SendPcrExtendLoc(&ctx, FW_TEST_PCR, 0), TPM_RC_BAD_AUTH); + +#ifndef FWTPM_NO_NV + AssertIntEQ(fwtpm_test_cycle(&ctx, TPM_SU_STATE, TPM_SU_STATE), 0); + AssertIntEQ(SendPcrExtendLoc(&ctx, FW_TEST_PCR, 0), TPM_RC_BAD_AUTH); + + AssertIntEQ(fwtpm_test_cycle(&ctx, TPM_SU_STATE, TPM_SU_CLEAR), 0); + AssertIntEQ(SendPcrExtendLoc(&ctx, FW_TEST_PCR, 0), TPM_RC_SUCCESS); + AssertIntEQ(SendPcrSetAuthValue(&ctx, FW_TEST_PCR, NULL, 0, pcrAuth, + pcrAuthSz), TPM_RC_SUCCESS); +#endif + + /* A power cycle without Shutdown */ + FWTPM_Cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(SendPcrExtendLoc(&ctx, FW_TEST_PCR, 0), TPM_RC_SUCCESS); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("PCR authValue reset by Startup(CLEAR):", 0); +} + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -26678,6 +26731,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_incremental_selftest(); test_fwtpm_incremental_selftest_truncated_returns_cmd_size(); test_fwtpm_gettestresult_needs_test_then_success(); + test_fwtpm_pcr_auth_startup_clear(); /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 19a92c1b30db80a0d4d44e4c44ab4e124ee6029a Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 06:53:53 -0800 Subject: [PATCH 024/124] F-18076 - Reject fwTPM Shutdown(STATE) while a PCR_Allocate is staged --- src/fwtpm/fwtpm_command.c | 6 +++++ tests/fwtpm_unit_tests.c | 46 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index ca3fe1bb3..96c9fcf46 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -1486,6 +1486,12 @@ static TPM_RC FwCmd_Shutdown(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, } } + /* A staged PCR_Allocate needs a TPM Reset, so the state cannot be saved + * for a Resume (Part 3 Sec.22.5). */ + if (rc == 0 && shutdownType == TPM_SU_STATE && ctx->pcrAllocPending) { + rc = TPM_RC_TYPE | TPM_RC_P | TPM_RC_1; + } + if (rc == 0) { #ifdef DEBUG_WOLFTPM printf("fwTPM: Shutdown(%s)\n", diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index e079e7b1d..421eb19d5 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -25978,6 +25978,51 @@ static void test_fwtpm_pcr_auth_startup_clear(void) fwtpm_pass("PCR authValue reset by Startup(CLEAR):", 0); } +static TPM_RC SendShutdown(FWTPM_CTX* ctx, UINT16 shutdownType) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_Shutdown); + int rspSize = 0; + + PutU16BE(gCmd + pos, shutdownType); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* A staged PCR_Allocate only takes effect on a TPM Reset, so the state may + * not be saved for a Resume until then. */ +static void test_fwtpm_shutdown_state_after_pcr_allocate(void) +{ + FWTPM_CTX ctx; + int rspSize = 0, cmdSz; + UINT16 algs[2]; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + algs[0] = TPM_ALG_SHA256; + algs[1] = TPM_ALG_SHA384; + cmdSz = BuildPcrAllocateCmd(gCmd, TPM_RH_PLATFORM, algs, 2, 1); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(gRsp[TPM2_HEADER_SIZE + 4], 1); + + AssertIntEQ(SendShutdown(&ctx, TPM_SU_STATE), + TPM_RC_TYPE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(ctx.shutdownStateSaved, 0); + AssertIntEQ(SendShutdown(&ctx, TPM_SU_CLEAR), TPM_RC_SUCCESS); + + /* Startup(CLEAR) applies the allocation and lifts the restriction */ + FWTPM_Cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(SendShutdown(&ctx, TPM_SU_STATE), TPM_RC_SUCCESS); + AssertIntEQ(SendShutdown(&ctx, TPM_SU_CLEAR), TPM_RC_SUCCESS); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("Shutdown(STATE) after PCR_Allocate:", 0); +} + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -26732,6 +26777,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_incremental_selftest_truncated_returns_cmd_size(); test_fwtpm_gettestresult_needs_test_then_success(); test_fwtpm_pcr_auth_startup_clear(); + test_fwtpm_shutdown_state_after_pcr_allocate(); /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 2dff65e1916d9e3627f324317de2514f573a6dd0 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 06:56:23 -0800 Subject: [PATCH 025/124] F-16182 - Skip unallocated PCR banks in fwTPM PCR_Extend --- src/fwtpm/fwtpm_command.c | 2 +- tests/fwtpm_unit_tests.c | 52 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 96c9fcf46..0e17d3d40 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -3692,7 +3692,7 @@ static TPM_RC FwCmd_PCR_Extend(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, rc = TPM_RC_COMMAND_SIZE; break; } - if (bank < 0) { + if (bank < 0 || (ctx->pcrAllocatedBanks & (1u << bank)) == 0) { /* Known algorithm but unsupported bank — skip the digest bytes */ cmd->pos += dSize; continue; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 421eb19d5..9a880cced 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -26023,6 +26023,55 @@ static void test_fwtpm_shutdown_state_after_pcr_allocate(void) fwtpm_pass("Shutdown(STATE) after PCR_Allocate:", 0); } +#ifndef NO_SHA +/* PCR_Extend for FW_TEST_PCR with one digest per algs[] entry */ +static TPM_RC SendPcrExtendAlgs(FWTPM_CTX* ctx, const UINT16* algs, int count) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_PCR_Extend); + int rspSize = 0; + int i, dSz; + + PutU32BE(gCmd + pos, FW_TEST_PCR); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + pos, (UINT32)count); pos += 4; + for (i = 0; i < count; i++) { + dSz = TPM2_GetHashDigestSize(algs[i]); + PutU16BE(gCmd + pos, algs[i]); pos += 2; + memset(gCmd + pos, 0x5A, dSz); pos += dSz; + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* The SHA-1 bank is implemented but not allocated by default, so a digest + * for it is skipped while the allocated banks are extended. */ +static void test_fwtpm_pcr_extend_unallocated_bank(void) +{ + FWTPM_CTX ctx; + UINT16 algs[2]; + byte zero[TPM_MAX_DIGEST_SIZE]; + int pcr = FW_TEST_PCR - PCR_FIRST; + + memset(&ctx, 0, sizeof(ctx)); + memset(zero, 0, sizeof(zero)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA1), 0); + AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA256), 1); + + algs[0] = TPM_ALG_SHA1; + algs[1] = TPM_ALG_SHA256; + AssertIntEQ(SendPcrExtendAlgs(&ctx, algs, 2), TPM_RC_SUCCESS); + AssertIntEQ(memcmp(ctx.pcrDigest[pcr][FWTPM_PCR_BANK_SHA1], zero, + sizeof(zero)), 0); + AssertIntNE(memcmp(ctx.pcrDigest[pcr][FWTPM_PCR_BANK_SHA256], zero, + sizeof(zero)), 0); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("PCR_Extend skips unallocated bank:", 0); +} +#endif /* !NO_SHA */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -26778,6 +26827,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_gettestresult_needs_test_then_success(); test_fwtpm_pcr_auth_startup_clear(); test_fwtpm_shutdown_state_after_pcr_allocate(); +#ifndef NO_SHA + test_fwtpm_pcr_extend_unallocated_bank(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 6162986f857451f073db6a821180e5dd86047a02 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 06:58:33 -0800 Subject: [PATCH 026/124] F-16183 - Clear unallocated PCR banks from the fwTPM PCR_Read selection --- src/fwtpm/fwtpm_command.c | 1 + tests/fwtpm_unit_tests.c | 44 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 0e17d3d40..1aa07a6e9 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -3486,6 +3486,7 @@ static TPM_RC FwCmd_PCR_Read(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, if (selections[s].pcrSelect[j] & (1 << pcr)) { int pcrIndex = j * 8 + pcr; if (bank < 0 || pcrIndex >= IMPLEMENTATION_PCR || + (ctx->pcrAllocatedBanks & (1u << bank)) == 0 || totalDigests >= 8) { selections[s].pcrSelect[j] &= (byte)~(1 << pcr); } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 9a880cced..bb6c55c26 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -26072,6 +26072,47 @@ static void test_fwtpm_pcr_extend_unallocated_bank(void) } #endif /* !NO_SHA */ +#ifndef NO_SHA +/* PCR_Read reports only what TPM_CAP_PCRS reports as allocated: a selection + * in the unallocated SHA-1 bank comes back empty with no digest. */ +static void test_fwtpm_pcr_read_unallocated_bank(void) +{ + FWTPM_CTX ctx; + int rspSize = 0, cmdSz, pos, i; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA1), 0); + + cmdSz = BuildPcrReadCmd(gCmd, FW_TEST_PCR); + PutU16BE(gCmd + TPM2_HEADER_SIZE + 4, TPM_ALG_SHA1); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + /* pcrUpdateCounter(4) | count(4) | hash(2) | sizeofSelect(1) | select */ + pos = TPM2_HEADER_SIZE + 4; + AssertIntEQ(GetU32BE(gRsp + pos), 1); pos += 4; + AssertIntEQ(GetU16BE(gRsp + pos), TPM_ALG_SHA1); pos += 2; + AssertIntEQ(gRsp[pos], PCR_SELECT_MAX); pos++; + for (i = 0; i < PCR_SELECT_MAX; i++) { + AssertIntEQ(gRsp[pos + i], 0); + } + pos += PCR_SELECT_MAX; + AssertIntEQ(GetU32BE(gRsp + pos), 0); pos += 4; + AssertIntEQ(rspSize, pos); + + /* The allocated bank is unaffected */ + cmdSz = BuildPcrReadCmd(gCmd, FW_TEST_PCR); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pos = TPM2_HEADER_SIZE + 4 + 4 + 2 + 1 + PCR_SELECT_MAX; + AssertIntEQ(GetU32BE(gRsp + pos), 1); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("PCR_Read skips unallocated bank:", 0); +} +#endif /* !NO_SHA */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -26830,6 +26871,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifndef NO_SHA test_fwtpm_pcr_extend_unallocated_bank(); #endif +#ifndef NO_SHA + test_fwtpm_pcr_read_unallocated_bank(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 8efefed18145c0c3ecbe9f88f01e85151cecdba4 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:01:34 -0800 Subject: [PATCH 027/124] F-18070 - Keep unlisted PCR banks allocated in fwTPM PCR_Allocate --- src/fwtpm/fwtpm_command.c | 20 ++++++++-- tests/fwtpm_unit_tests.c | 81 +++++++++++++++++++++++++++++++++++---- 2 files changed, 90 insertions(+), 11 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 1aa07a6e9..a59297d92 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -3934,6 +3934,9 @@ static TPM_RC FwCmd_PCR_Allocate(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = FwValidatePcrSelection(cmd, cmdSize); } if (rc == 0) { + /* Only the listed banks change; the others keep their current + * allocation (Part 3 Sec.22.5). */ + newBanks = ctx->pcrAllocatedBanks; TPM2_Packet_ParseU32(cmd, &count); if (count > FWTPM_PCR_BANKS * 4) { rc = TPM_RC_SIZE; @@ -3960,10 +3963,13 @@ static TPM_RC FwCmd_PCR_Allocate(FWTPM_CTX* ctx, TPM2_Packet* cmd, } bank = FwGetPcrBankIndex(hashAlg); - if (bank >= 0 && anySelected) { - newBanks |= (UINT8)(1 << bank); - sizeNeeded += (UINT32)(IMPLEMENTATION_PCR * - TPM2_GetHashDigestSize(hashAlg)); + if (bank >= 0) { + if (anySelected) { + newBanks |= (UINT8)(1 << bank); + } + else { + newBanks &= (UINT8)~(1 << bank); + } } /* Unsupported hash algorithms are silently ignored per spec */ } @@ -3975,6 +3981,12 @@ static TPM_RC FwCmd_PCR_Allocate(FWTPM_CTX* ctx, TPM2_Packet* cmd, #endif sizeAvailable = (UINT32)(IMPLEMENTATION_PCR * FWTPM_PCR_BANKS * TPM_MAX_DIGEST_SIZE); + for (b = 0; b < FWTPM_PCR_BANKS; b++) { + if (newBanks & (1u << b)) { + sizeNeeded += (UINT32)(IMPLEMENTATION_PCR * + TPM2_GetHashDigestSize(FwGetPcrBankAlg(b))); + } + } /* Storing an empty result would persist "no banks at all" to NV */ if (newBanks == 0) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index bb6c55c26..4cc8028c5 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -2530,21 +2530,19 @@ static void test_fwtpm_pcr_allocate(void) AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA384), 1); /* The restart performs the _TPM_Init and Startup(CLEAR) that apply it. - * Replace, not add: the bank left out of the selection is now gone. - * Without NV nothing survives the restart - the TPM comes back with the - * default banks - so the applied state is only observable with NV. */ + * A bank left out of the selection keeps its allocation. */ #ifndef FWTPM_NO_NV FWTPM_Cleanup(&ctx); memset(&ctx, 0, sizeof(ctx)); rc = fwtpm_test_startup(&ctx); AssertIntEQ(rc, 0); AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA256), 1); - AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA384), 0); + AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA384), 1); #endif /* An all-zero bitmap deallocates, but must not leave zero banks */ algs[0] = TPM_ALG_SHA256; - cmdSz = BuildPcrAllocateCmd(gCmd, TPM_RH_PLATFORM, algs, 1, 0); + cmdSz = BuildPcrAllocateCmd(gCmd, TPM_RH_PLATFORM, algs, 2, 0); rspSize = 0; rc = FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); AssertIntEQ(rc, TPM_RC_SUCCESS); @@ -2552,15 +2550,23 @@ static void test_fwtpm_pcr_allocate(void) AssertIntEQ(gRsp[TPM2_HEADER_SIZE + 4], 0); /* allocationSuccess = NO */ AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA256), 1); /* unchanged */ - /* Same trap: an unimplemented bank must not store "no banks" */ + /* Same trap: an unimplemented bank must not store "no banks". With no + * implemented bank listed the allocation is kept as it is. */ algs[0] = (UINT16)0x7FFF; cmdSz = BuildPcrAllocateCmd(gCmd, TPM_RH_PLATFORM, algs, 1, 1); rspSize = 0; rc = FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); AssertIntEQ(rc, TPM_RC_SUCCESS); AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); - AssertIntEQ(gRsp[TPM2_HEADER_SIZE + 4], 0); + AssertIntEQ(gRsp[TPM2_HEADER_SIZE + 4], 1); AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA256), 1); + cmdSz = BuildPcrAllocateCmd(gCmd, TPM_RH_PLATFORM, algs, 0, 1); + rspSize = 0; + rc = FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(rc, TPM_RC_SUCCESS); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(gRsp[TPM2_HEADER_SIZE + 4], 1); + AssertIntEQ(ctx.pcrAllocatedBanksPending, ctx.pcrAllocatedBanks); /* Restore both banks, applied by the restart below */ algs[0] = TPM_ALG_SHA256; @@ -26113,6 +26119,64 @@ static void test_fwtpm_pcr_read_unallocated_bank(void) } #endif /* !NO_SHA */ +#ifdef WOLFSSL_SHA384 +static int SendPcrAllocateOne(FWTPM_CTX* ctx, UINT16 hashAlg, int selectAll) +{ + int rspSize = 0; + int cmdSz = BuildPcrAllocateCmd(gCmd, TPM_RH_PLATFORM, &hashAlg, 1, + selectAll); + + FWTPM_ProcessCommand(ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + if (GetRspRC(gRsp) != TPM_RC_SUCCESS) { + return -1; + } + return gRsp[TPM2_HEADER_SIZE + 4]; /* allocationSuccess */ +} + +/* PCR_Allocate changes only the banks it lists: an unlisted bank keeps its + * allocation, and a bank goes away only when listed with an empty select. */ +static void test_fwtpm_pcr_allocate_unlisted_bank(void) +{ + FWTPM_CTX ctx; + byte both = (byte)((1 << FWTPM_PCR_BANK_SHA256) | + (1 << FWTPM_PCR_BANK_SHA384)); + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(ctx.pcrAllocatedBanks, both); + + AssertIntEQ(SendPcrAllocateOne(&ctx, TPM_ALG_SHA256, 1), 1); + AssertIntEQ(ctx.pcrAllocatedBanksPending, both); + + AssertIntEQ(SendPcrAllocateOne(&ctx, TPM_ALG_SHA384, 0), 1); + AssertIntEQ(ctx.pcrAllocatedBanksPending, 1 << FWTPM_PCR_BANK_SHA256); + AssertIntEQ(ctx.pcrAllocatedBanks, both); + +#ifndef FWTPM_NO_NV + FWTPM_Cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA256), 1); + AssertIntEQ(fwtpm_bank_allocated(&ctx, TPM_ALG_SHA384), 0); + + /* Unlisted and deallocated stays deallocated */ + AssertIntEQ(SendPcrAllocateOne(&ctx, TPM_ALG_SHA256, 1), 1); + AssertIntEQ(ctx.pcrAllocatedBanksPending, 1 << FWTPM_PCR_BANK_SHA256); +#endif + + /* Restore the default banks for the tests that follow */ + AssertIntEQ(SendPcrAllocateOne(&ctx, TPM_ALG_SHA384, 1), 1); + AssertIntEQ(ctx.pcrAllocatedBanksPending, both); + FWTPM_Cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(ctx.pcrAllocatedBanks, both); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("PCR_Allocate keeps unlisted banks:", 0); +} +#endif /* WOLFSSL_SHA384 */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -26874,6 +26938,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifndef NO_SHA test_fwtpm_pcr_read_unallocated_bank(); #endif +#ifdef WOLFSSL_SHA384 + test_fwtpm_pcr_allocate_unlisted_bank(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 6f7d3e980586ee384da81723466dab3a3a4aac13 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:05:05 -0800 Subject: [PATCH 028/124] F-18073 - Flush persistent objects of the changed hierarchy in fwTPM ChangeEPS and ChangePPS --- src/fwtpm/fwtpm_command.c | 22 ++++++++++ tests/fwtpm_unit_tests.c | 92 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 114 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index a59297d92..e95fb3b85 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -7022,6 +7022,17 @@ static TPM_RC FwCmd_ChangeEPS(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + /* Persistent endorsement objects are flushed with the seed + * (Part 3 Sec.24.5). The compacting FWTPM_NV_Save in the + * pendingClear path drops the freed slots. */ + for (i = 0; i < FWTPM_MAX_PERSISTENT; i++) { + if (ctx->persistent[i].used && + ctx->persistent[i].hierarchy == TPM_RH_ENDORSEMENT) { + TPM2_ForceZero(&ctx->persistent[i], + sizeof(ctx->persistent[i])); + } + } + /* A new endorsement seed re-enables the hierarchy (Part 3 * Sec.24.5). */ ctx->ehDisabled = 0; @@ -7082,6 +7093,17 @@ static TPM_RC FwCmd_ChangePPS(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + /* Persistent platform objects are flushed with the seed + * (Part 3 Sec.24.4). The compacting FWTPM_NV_Save in the + * pendingClear path drops the freed slots. */ + for (i = 0; i < FWTPM_MAX_PERSISTENT; i++) { + if (ctx->persistent[i].used && + ctx->persistent[i].hierarchy == TPM_RH_PLATFORM) { + TPM2_ForceZero(&ctx->persistent[i], + sizeof(ctx->persistent[i])); + } + } + /* Defer object flush until after response auth */ ctx->pendingClear = 1; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 4cc8028c5..df32b12ca 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -26177,6 +26177,95 @@ static void test_fwtpm_pcr_allocate_unlisted_bank(void) } #endif /* WOLFSSL_SHA384 */ +#if !defined(FWTPM_NO_NV) && defined(HAVE_ECC) +static UINT32 CreatePrimaryInHierarchy(FWTPM_CTX* ctx, UINT32 hierarchy) +{ + int cmdSz = BuildCreatePrimaryCmd(gCmd, TPM_ALG_ECC); + int rspSize = 0; + + PutU32BE(gCmd + TPM2_HEADER_SIZE, hierarchy); + FWTPM_ProcessCommand(ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + return GetU32BE(gRsp + TPM2_HEADER_SIZE); +} + +static TPM_RC SendEvictControl(FWTPM_CTX* ctx, UINT32 authHandle, + UINT32 objectHandle, UINT32 persistentHandle) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_EvictControl); + int rspSize = 0; + + PutU32BE(gCmd + pos, authHandle); pos += 4; + PutU32BE(gCmd + pos, objectHandle); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + pos, persistentHandle); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +static TPM_RC SendReadPublic(FWTPM_CTX* ctx, UINT32 handle) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ReadPublic); + int rspSize = 0; + + PutU32BE(gCmd + pos, handle); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* ChangeEPS and ChangePPS flush the persistent objects of the hierarchy + * whose seed they replace and leave the other hierarchies alone. */ +static void test_fwtpm_change_seed_evicts_persistent(void) +{ + FWTPM_CTX ctx; + UINT32 h; + const UINT32 ownerP = PERSISTENT_FIRST + 0x10; + const UINT32 endorseP = PERSISTENT_FIRST + 0x11; + const UINT32 platformP = PLATFORM_PERSISTENT + 0x10; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + h = CreatePrimaryInHierarchy(&ctx, TPM_RH_OWNER); + AssertIntEQ(SendEvictControl(&ctx, TPM_RH_OWNER, h, ownerP), + TPM_RC_SUCCESS); + FlushHandle(&ctx, h); + h = CreatePrimaryInHierarchy(&ctx, TPM_RH_ENDORSEMENT); + AssertIntEQ(SendEvictControl(&ctx, TPM_RH_OWNER, h, endorseP), + TPM_RC_SUCCESS); + FlushHandle(&ctx, h); + h = CreatePrimaryInHierarchy(&ctx, TPM_RH_PLATFORM); + AssertIntEQ(SendEvictControl(&ctx, TPM_RH_PLATFORM, h, platformP), + TPM_RC_SUCCESS); + FlushHandle(&ctx, h); + + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_ChangeEPS, TPM_RH_PLATFORM), + TPM_RC_SUCCESS); + AssertIntEQ(SendReadPublic(&ctx, endorseP), TPM_RC_HANDLE); + AssertIntEQ(SendReadPublic(&ctx, ownerP), TPM_RC_SUCCESS); + AssertIntEQ(SendReadPublic(&ctx, platformP), TPM_RC_SUCCESS); + + /* The eviction is persistent */ + FWTPM_Cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(SendReadPublic(&ctx, endorseP), TPM_RC_HANDLE); + AssertIntEQ(SendReadPublic(&ctx, platformP), TPM_RC_SUCCESS); + + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_ChangePPS, TPM_RH_PLATFORM), + TPM_RC_SUCCESS); + AssertIntEQ(SendReadPublic(&ctx, platformP), TPM_RC_HANDLE); + AssertIntEQ(SendReadPublic(&ctx, ownerP), TPM_RC_SUCCESS); + + AssertIntEQ(SendEvictControl(&ctx, TPM_RH_OWNER, ownerP, ownerP), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("ChangeEPS/ChangePPS evict persistent:", 0); +} +#endif /* !FWTPM_NO_NV && HAVE_ECC */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -26941,6 +27030,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifdef WOLFSSL_SHA384 test_fwtpm_pcr_allocate_unlisted_bank(); #endif +#if !defined(FWTPM_NO_NV) && defined(HAVE_ECC) + test_fwtpm_change_seed_evicts_persistent(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From f12f71f625a20340b02bf9d6984c2b2f4162c818 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:08:05 -0800 Subject: [PATCH 029/124] F-18072 - Reset platformPolicy and the PCR policies in fwTPM ChangePPS --- src/fwtpm/fwtpm_command.c | 9 +++++++ tests/fwtpm_unit_tests.c | 56 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index e95fb3b85..37e9fb94a 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -7093,6 +7093,15 @@ static TPM_RC FwCmd_ChangePPS(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + /* platformPolicy and the PCR policies return to their defaults + * (Part 3 Sec.24.4) */ + XMEMSET(&ctx->platformPolicy, 0, sizeof(ctx->platformPolicy)); + ctx->platformPolicyAlg = TPM_ALG_NULL; + XMEMSET(ctx->pcrPolicy, 0, sizeof(ctx->pcrPolicy)); + for (i = 0; i < IMPLEMENTATION_PCR; i++) { + ctx->pcrPolicyAlg[i] = TPM_ALG_NULL; + } + /* Persistent platform objects are flushed with the seed * (Part 3 Sec.24.4). The compacting FWTPM_NV_Save in the * pendingClear path drops the freed slots. */ diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index df32b12ca..e85aaf137 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -26266,6 +26266,61 @@ static void test_fwtpm_change_seed_evicts_persistent(void) } #endif /* !FWTPM_NO_NV && HAVE_ECC */ +/* SetPrimaryPolicy (pcrHandle 0) or PCR_SetAuthPolicy with a SHA-256 policy + * of policySz octets, platform authorized */ +static TPM_RC SendPlatformSetPolicy(FWTPM_CTX* ctx, UINT32 pcrHandle, + int policySz) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, (pcrHandle == 0) ? + TPM_CC_SetPrimaryPolicy : TPM_CC_PCR_SetAuthPolicy); + int rspSize = 0; + + PutU32BE(gCmd + pos, TPM_RH_PLATFORM); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, (UINT16)policySz); pos += 2; + memset(gCmd + pos, 0x3C, policySz); pos += policySz; + PutU16BE(gCmd + pos, (policySz > 0) ? TPM_ALG_SHA256 : TPM_ALG_NULL); + pos += 2; + if (pcrHandle != 0) { + PutU32BE(gCmd + pos, pcrHandle); pos += 4; + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* ChangePPS returns platformPolicy and the PCR policies to their defaults */ +static void test_fwtpm_change_pps_resets_policies(void) +{ + FWTPM_CTX ctx; + int pcr = FW_TEST_PCR - PCR_FIRST; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + AssertIntEQ(SendPlatformSetPolicy(&ctx, FW_TEST_PCR, 32), + TPM_RC_SUCCESS); + AssertIntEQ(SendPlatformSetPolicy(&ctx, 0, 32), TPM_RC_SUCCESS); + AssertIntEQ(ctx.platformPolicy.size, 32); + AssertIntEQ(ctx.pcrPolicy[pcr].size, 32); + + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_ChangePPS, TPM_RH_PLATFORM), + TPM_RC_SUCCESS); + AssertIntEQ(ctx.platformPolicy.size, 0); + AssertIntEQ(ctx.platformPolicyAlg, TPM_ALG_NULL); + AssertIntEQ(ctx.pcrPolicy[pcr].size, 0); + AssertIntEQ(ctx.pcrPolicyAlg[pcr], TPM_ALG_NULL); + + /* The PCR policy reset is persistent */ + FWTPM_Cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(ctx.pcrPolicy[pcr].size, 0); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("ChangePPS resets platform and PCR policy:", 0); +} + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -27033,6 +27088,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if !defined(FWTPM_NO_NV) && defined(HAVE_ECC) test_fwtpm_change_seed_evicts_persistent(); #endif + test_fwtpm_change_pps_resets_policies(); /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From b0f126924c9af73dd23b81a1711ad91acfa5f1f6 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:11:42 -0800 Subject: [PATCH 030/124] F-16222 - Reset lockoutAuth in fwTPM Clear when built with FWTPM_NO_DA --- src/fwtpm/fwtpm_command.c | 6 ++--- tests/fwtpm_unit_tests.c | 56 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 37e9fb94a..d1c9635a6 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -6940,12 +6940,12 @@ static TPM_RC FwCmd_Clear(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, ctx->shDisabled = 0; ctx->ehDisabled = 0; - #ifndef FWTPM_NO_DA - /* Clear resets lockoutAuth and DA state to defaults - * (Part 3 Sec.24.6) */ + /* Clear resets lockoutAuth (Part 3 Sec.24.6) */ TPM2_ForceZero(ctx->lockoutAuth.buffer, sizeof(ctx->lockoutAuth.buffer)); ctx->lockoutAuth.size = 0; + #ifndef FWTPM_NO_DA + /* Clear resets the DA state to defaults (Part 3 Sec.24.6) */ ctx->daFailedTries = 0; ctx->daMaxTries = FWTPM_DA_DEFAULT_MAX_TRIES; ctx->daRecoveryTime = FWTPM_DA_DEFAULT_RECOVERY; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index e85aaf137..96bcdfd31 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -26321,6 +26321,61 @@ static void test_fwtpm_change_pps_resets_policies(void) fwtpm_pass("ChangePPS resets platform and PCR policy:", 0); } +static TPM_RC SendHierarchyChangeAuth(FWTPM_CTX* ctx, UINT32 authHandle, + const byte* oldAuth, int oldAuthSz, const byte* newAuth, int newAuthSz) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + TPM_CC_HierarchyChangeAuth); + int rspSize = 0; + + PutU32BE(gCmd + pos, authHandle); pos += 4; + pos = AppendPwAuth(gCmd, pos, oldAuth, oldAuthSz); + PutU16BE(gCmd + pos, (UINT16)newAuthSz); pos += 2; + if (newAuthSz > 0) { + memcpy(gCmd + pos, newAuth, newAuthSz); + pos += newAuthSz; + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* Clear returns lockoutAuth to the Empty Auth, with or without DA support */ +static void test_fwtpm_clear_resets_lockout_auth(void) +{ + FWTPM_CTX ctx; + static const byte lockoutAuth[] = "lockout"; + const int lockoutAuthSz = (int)sizeof(lockoutAuth) - 1; + int pos, rspSize = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(SendHierarchyChangeAuth(&ctx, TPM_RH_LOCKOUT, NULL, 0, + lockoutAuth, lockoutAuthSz), TPM_RC_SUCCESS); + AssertIntEQ(ctx.lockoutAuth.size, lockoutAuthSz); + + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_Clear, TPM_RH_PLATFORM), + TPM_RC_SUCCESS); + AssertIntEQ(ctx.lockoutAuth.size, 0); + + FWTPM_Cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(ctx.lockoutAuth.size, 0); + + /* ClearControl(TPM_RH_LOCKOUT, NO) with the Empty Auth */ + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ClearControl); + PutU32BE(gCmd + pos, TPM_RH_LOCKOUT); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + gCmd[pos++] = 0; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("Clear resets lockoutAuth:", 0); +} + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -27089,6 +27144,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_change_seed_evicts_persistent(); #endif test_fwtpm_change_pps_resets_policies(); + test_fwtpm_clear_resets_lockout_auth(); /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From a5b4edc6c1db1ecd5be0a50348a0a57be3a217f3 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:15:43 -0800 Subject: [PATCH 031/124] F-18066 - Set TPMA_NV_WRITELOCKED on GLOBALLOCK indexes in fwTPM NV_GlobalWriteLock --- src/fwtpm/fwtpm_command.c | 39 +++--- src/fwtpm/fwtpm_nv.c | 56 +++++++++ tests/fwtpm_unit_tests.c | 259 +++++++++++++++++++++++++++++++++++++- wolftpm/fwtpm/fwtpm.h | 2 +- wolftpm/fwtpm/fwtpm_nv.h | 17 +++ 5 files changed, 346 insertions(+), 27 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index d1c9635a6..0a67ff576 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -17305,10 +17305,6 @@ static TPM_RC FwCmd_NV_Write(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0 && (nv->nvPublic.attributes & TPMA_NV_WRITELOCKED)) { rc = TPM_RC_NV_LOCKED; } - if (rc == 0 && ctx->globalNvWriteLock && - (nv->nvPublic.attributes & TPMA_NV_GLOBALLOCK)) { - rc = TPM_RC_NV_LOCKED; - } /* Parse: TPM2B data + offset */ if (rc == 0) { @@ -17477,10 +17473,6 @@ static TPM_RC FwCmd_NV_Extend(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0 && (nv->nvPublic.attributes & TPMA_NV_WRITELOCKED)) { rc = TPM_RC_NV_LOCKED; } - if (rc == 0 && ctx->globalNvWriteLock && - (nv->nvPublic.attributes & TPMA_NV_GLOBALLOCK)) { - rc = TPM_RC_NV_LOCKED; - } if (rc == 0 && ((nv->nvPublic.attributes & TPMA_NV_TPM_NT) >> 4) != TPM_NT_EXTEND) { rc = TPM_RC_ATTRIBUTES; @@ -17586,10 +17578,6 @@ static TPM_RC FwCmd_NV_Increment(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0 && (nv->nvPublic.attributes & TPMA_NV_WRITELOCKED)) { rc = TPM_RC_NV_LOCKED; } - if (rc == 0 && ctx->globalNvWriteLock && - (nv->nvPublic.attributes & TPMA_NV_GLOBALLOCK)) { - rc = TPM_RC_NV_LOCKED; - } if (rc == 0 && ((nv->nvPublic.attributes & TPMA_NV_TPM_NT) >> 4) != TPM_NT_COUNTER) { rc = TPM_RC_ATTRIBUTES; @@ -17793,10 +17781,6 @@ static TPM_RC FwCmd_NV_SetBits(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0 && (nv->nvPublic.attributes & TPMA_NV_WRITELOCKED)) { rc = TPM_RC_NV_LOCKED; } - if (rc == 0 && ctx->globalNvWriteLock && - (nv->nvPublic.attributes & TPMA_NV_GLOBALLOCK)) { - rc = TPM_RC_NV_LOCKED; - } if (rc == 0 && ((nv->nvPublic.attributes & TPMA_NV_TPM_NT) >> 4) != TPM_NT_BITS) { rc = TPM_RC_ATTRIBUTES; @@ -17912,13 +17896,14 @@ static TPM_RC FwCmd_NV_ChangeAuth(FWTPM_CTX* ctx, TPM2_Packet* cmd, } /* --- TPM2_NV_GlobalWriteLock (CC 0x0132) --- */ -/* Set the global NV write lock. All NV indices with TPMA_NV_GLOBALLOCK - * become write-locked until the next Startup(CLEAR). */ +/* Set TPMA_NV_WRITELOCKED on every NV index that has TPMA_NV_GLOBALLOCK. + * An index defined afterwards is not locked until the command runs again. */ static TPM_RC FwCmd_NV_GlobalWriteLock(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, TPM2_Packet* rsp, UINT16 cmdTag) { TPM_RC rc = TPM_RC_SUCCESS; UINT32 authHandle = 0; + int i; (void)cmdSize; @@ -17932,17 +17917,23 @@ static TPM_RC FwCmd_NV_GlobalWriteLock(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { - int oldGlobalNvWriteLock = ctx->globalNvWriteLock; #ifdef DEBUG_WOLFTPM printf("fwTPM: NV_GlobalWriteLock(auth=0x%x)\n", authHandle); #endif - ctx->globalNvWriteLock = 1; - /* Persist so the lock survives a daemon restart (Resume) */ - rc = FWTPM_NV_SaveFlags(ctx); + for (i = 0; i < FWTPM_MAX_NV_INDICES; i++) { + const FWTPM_NvIndex* nv = &ctx->nvIndices[i]; + + if (nv->inUse && + (nv->nvPublic.attributes & TPMA_NV_GLOBALLOCK) != 0 && + (nv->nvPublic.attributes & TPMA_NV_WRITELOCKED) == 0) { + /* One journal record locks every index, or none of them + * when it cannot be saved */ + rc = FWTPM_NV_GlobalWriteLock(ctx); + break; + } + } if (rc == 0) FwRspNoParams(rsp, cmdTag); - else - ctx->globalNvWriteLock = oldGlobalNvWriteLock; } return rc; diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index adc5c9663..d38e51ba0 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -1350,6 +1350,22 @@ static int FwNvFindOrAllocCacheSlot(FWTPM_CTX* ctx, UINT32 hierarchy, return freeSlot; } +#ifndef FWTPM_NO_NV +/* Write-lock every NV index that has TPMA_NV_GLOBALLOCK */ +static void FwNvApplyGlobalLock(FWTPM_CTX* ctx) +{ + int i; + + for (i = 0; i < FWTPM_MAX_NV_INDICES; i++) { + if (ctx->nvIndices[i].inUse && + (ctx->nvIndices[i].nvPublic.attributes & + TPMA_NV_GLOBALLOCK) != 0) { + ctx->nvIndices[i].nvPublic.attributes |= TPMA_NV_WRITELOCKED; + } + } +} +#endif /* !FWTPM_NO_NV */ + /* Process a single TLV entry during journal scan */ static int FwNvProcessEntry(FWTPM_CTX* ctx, UINT16 tag, const byte* value, UINT16 valueLen) @@ -1833,6 +1849,15 @@ static int FwNvProcessEntry(FWTPM_CTX* ctx, UINT16 tag, } break; } + + case FWTPM_NV_TAG_NV_GLOBAL_LOCK: + if (valueLen != 0) { + rc = TPM_RC_FAILURE; + } + else { + FwNvApplyGlobalLock(ctx); + } + break; #endif /* !FWTPM_NO_NV */ case FWTPM_NV_TAG_PERSISTENT: { @@ -3252,6 +3277,37 @@ int FWTPM_NV_DeleteNvIndex(FWTPM_CTX* ctx, UINT32 nvHandle) #endif /* FWTPM_NO_NV */ } +int FWTPM_NV_GlobalWriteLock(FWTPM_CTX* ctx) +{ +#ifdef FWTPM_NO_NV + (void)ctx; + return NOT_COMPILED_IN; +#else + int rc; + int compacted = 0; + + if (ctx == NULL) { + return BAD_FUNC_ARG; + } + + rc = FwNvAppendEntryEx(ctx, FWTPM_NV_TAG_NV_GLOBAL_LOCK, NULL, 0, + &compacted); + /* A compaction rewrote the indexes as they are and left the record out, + * so the lock is still to be committed. */ + if (rc == TPM_RC_SUCCESS && compacted) { + rc = FwNvAppendEntryEx(ctx, FWTPM_NV_TAG_NV_GLOBAL_LOCK, NULL, 0, + &compacted); + if (rc == TPM_RC_SUCCESS && compacted) { + rc = TPM_RC_NV_SPACE; + } + } + if (rc == TPM_RC_SUCCESS) { + FwNvApplyGlobalLock(ctx); + } + return rc; +#endif /* FWTPM_NO_NV */ +} + int FWTPM_NV_SavePersistent(FWTPM_CTX* ctx, int slot) { int rc; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 96bcdfd31..7f6b605e7 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -15984,10 +15984,15 @@ static void test_fwtpm_global_write_lock_nv_failure(void) { FWTPM_CTX ctx; FWTPM_NV_HAL oldHal, failHal; + const UINT32 nvIdx = 0x01500A18; + int cmdSz, rspSize = 0; XMEMSET(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), TPM_RC_SUCCESS); - AssertIntEQ(ctx.globalNvWriteLock, 0); + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, 8, TPMA_NV_OWNERWRITE | + TPMA_NV_OWNERREAD | TPMA_NV_GLOBALLOCK); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); oldHal = ctx.nvHal; failHal = oldHal; @@ -15996,9 +16001,12 @@ static void test_fwtpm_global_write_lock_nv_failure(void) AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_NV_GlobalWriteLock, TPM_RH_OWNER), TPM_RC_FAILURE); - AssertIntEQ(ctx.globalNvWriteLock, 0); AssertIntEQ(FWTPM_NV_SetHAL(&ctx, &oldHal), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, nvIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); FWTPM_Cleanup(&ctx); fwtpm_pass("GlobalWriteLock NV failure rollback:", 0); } @@ -26376,6 +26384,246 @@ static void test_fwtpm_clear_resets_lockout_auth(void) fwtpm_pass("Clear resets lockoutAuth:", 0); } +#ifndef FWTPM_NO_NV +static UINT32 NvReadPublicAttributes(FWTPM_CTX* ctx, UINT32 nvIndex) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_NV_ReadPublic); + int rspSize = 0; + + PutU32BE(gCmd + pos, nvIndex); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + /* TPM2B_NV_PUBLIC: size(2) | nvIndex(4) | nameAlg(2) | attributes(4) */ + return GetU32BE(gRsp + TPM2_HEADER_SIZE + 2 + 4 + 2); +} + +/* NV_GlobalWriteLock sets TPMA_NV_WRITELOCKED on the GLOBALLOCK indexes that + * exist when it runs. Startup(CLEAR) then clears the lock unless the index + * is WRITEDEFINE and written. */ +static void test_fwtpm_nv_global_write_lock_attribute(void) +{ + FWTPM_CTX ctx; + const UINT32 lockIdx = 0x01500A10; + const UINT32 defineIdx = 0x01500A11; + const UINT32 plainIdx = 0x01500A12; + const UINT32 lateIdx = 0x01500A13; + const UINT32 attrs = TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD; + int cmdSz, rspSize = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmdSz = BuildNvDefineCmd(gCmd, lockIdx, 8, attrs | TPMA_NV_GLOBALLOCK); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + cmdSz = BuildNvDefineCmd(gCmd, defineIdx, 8, attrs | TPMA_NV_GLOBALLOCK | + TPMA_NV_WRITEDEFINE); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + cmdSz = BuildNvDefineCmd(gCmd, plainIdx, 8, attrs); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, defineIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_NV_GlobalWriteLock, + TPM_RH_OWNER), TPM_RC_SUCCESS); + AssertIntNE(NvReadPublicAttributes(&ctx, lockIdx) & + TPMA_NV_WRITELOCKED, 0); + AssertIntNE(NvReadPublicAttributes(&ctx, defineIdx) & + TPMA_NV_WRITELOCKED, 0); + AssertIntEQ(NvReadPublicAttributes(&ctx, plainIdx) & + TPMA_NV_WRITELOCKED, 0); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, lockIdx, NULL, 8, 0), + TPM_RC_NV_LOCKED); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, plainIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + + /* An index defined after the command is not locked by it */ + cmdSz = BuildNvDefineCmd(gCmd, lateIdx, 8, attrs | TPMA_NV_GLOBALLOCK); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, lateIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + + FWTPM_Cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, lockIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, defineIdx, NULL, 8, 0), + TPM_RC_NV_LOCKED); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, lockIdx), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, defineIdx), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, plainIdx), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, lateIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV_GlobalWriteLock sets WRITELOCKED:", 0); +} + +static FWTPM_NV_HAL gNvFailAfterHal; +static int gNvFailAfterWrites; + +/* Pass gNvFailAfterWrites writes on to gNvFailAfterHal, then fail */ +static int fail_after_nv_write(void* ctx, word32 offset, const byte* buf, + word32 size) +{ + if (gNvFailAfterWrites <= 0) { + return TPM_RC_FAILURE; + } + gNvFailAfterWrites--; + return gNvFailAfterHal.write(ctx, offset, buf, size); +} + +/* NV_GlobalWriteLock locks every GLOBALLOCK index or none. Whichever NV + * write fails, no index is locked, neither in the context nor in the journal + * a restart loads; the indexes are written WRITEDEFINE ones, which stay + * locked across Startup(CLEAR). */ +static void test_fwtpm_nv_global_write_lock_all_or_none(void) +{ + static FWTPM_CTX reload; + FWTPM_CTX ctx; + FWTPM_NV_HAL failHal; + const UINT32 idx[2] = { 0x01500A14, 0x01500A15 }; + const UINT32 attrs = TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | + TPMA_NV_GLOBALLOCK | TPMA_NV_WRITEDEFINE; + TPM_RC rc = TPM_RC_FAILURE; + int n, i, locked, found, cmdSz, rspSize = 0; + + for (n = 0; rc != TPM_RC_SUCCESS; n++) { + AssertIntLE(n, 16); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + for (i = 0; i < 2; i++) { + cmdSz = BuildNvDefineCmd(gCmd, idx[i], 8, attrs); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, idx[i], NULL, + 8, 0), TPM_RC_SUCCESS); + } + + gNvFailAfterHal = ctx.nvHal; + gNvFailAfterWrites = n; + failHal = ctx.nvHal; + failHal.write = fail_after_nv_write; + AssertIntEQ(FWTPM_NV_SetHAL(&ctx, &failHal), TPM_RC_SUCCESS); + rc = SendSimpleSessionCmd(&ctx, TPM_CC_NV_GlobalWriteLock, + TPM_RH_OWNER); + AssertIntEQ(FWTPM_NV_SetHAL(&ctx, &gNvFailAfterHal), TPM_RC_SUCCESS); + + locked = (rc == TPM_RC_SUCCESS); + for (i = 0; i < 2; i++) { + AssertIntEQ((NvReadPublicAttributes(&ctx, idx[i]) & + TPMA_NV_WRITELOCKED) != 0, locked); + } + + /* A later save commits whatever the failed command left in the + * journal. Replay it before FWTPM_Cleanup rewrites it from ctx. */ + AssertIntEQ(FWTPM_NV_SaveFlags(&ctx), TPM_RC_SUCCESS); + memset(&reload, 0, sizeof(reload)); + AssertIntEQ(FWTPM_Init(&reload), TPM_RC_SUCCESS); + found = 0; + for (i = 0; i < FWTPM_MAX_NV_INDICES; i++) { + if (reload.nvIndices[i].inUse && + (reload.nvIndices[i].nvPublic.nvIndex == idx[0] || + reload.nvIndices[i].nvPublic.nvIndex == idx[1])) { + AssertIntEQ((reload.nvIndices[i].nvPublic.attributes & + TPMA_NV_WRITELOCKED) != 0, locked); + found++; + } + } + AssertIntEQ(found, 2); + FWTPM_Cleanup(&reload); + + for (i = 0; i < 2; i++) { + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, idx[i]), + TPM_RC_SUCCESS); + } + FWTPM_Cleanup(&ctx); + } + /* at least one failed save was exercised */ + AssertIntGT(n, 1); + fwtpm_pass("NV_GlobalWriteLock all or none:", 0); +} + +/* A full journal is compacted and the lock record appended after it. With no + * room for the record even then, no index is locked. */ +static void test_fwtpm_nv_global_write_lock_at_capacity(void) +{ + FWTPM_CTX ctx; + FWTPM_NV_HAL hal; + const UINT32 nvIdx = 0x01500A16; + word32 maxSize; + int i, found, baseErases, cmdSz, rspSize = 0; + + memset(gMockNvStore, 0xFF, sizeof(gMockNvStore)); + gMockNvFailHeader = 0; + gMockNvFailAfterCompact = 0; + gMockNvCompactSeen = 0; + gMockNvCtx = NULL; + memset(&ctx, 0, sizeof(ctx)); + memset(&hal, 0, sizeof(hal)); + hal.read = mock_nv_read; + hal.write = mock_nv_write; + hal.erase = mock_nv_erase; + hal.maxSize = MOCK_NV_SIZE; + AssertIntEQ(FWTPM_NV_SetHAL(&ctx, &hal), 0); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, 8, TPMA_NV_OWNERWRITE | + TPMA_NV_OWNERREAD | TPMA_NV_GLOBALLOCK); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + /* One octet short of the record and the journal seal */ + AssertIntEQ(FWTPM_NV_Save(&ctx), 0); + ctx.nvHal.maxSize = ctx.nvWritePos + WC_SHA256_DIGEST_SIZE + 3; + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_NV_GlobalWriteLock, + TPM_RH_OWNER), TPM_RC_NV_SPACE); + AssertIntEQ(NvReadPublicAttributes(&ctx, nvIdx) & TPMA_NV_WRITELOCKED, + 0); + + /* The same once the superseded flags records are compacted away */ + ctx.nvHal.maxSize = MOCK_NV_SIZE; + AssertIntEQ(FWTPM_NV_SaveFlags(&ctx), 0); + AssertIntEQ(FWTPM_NV_SaveFlags(&ctx), 0); + maxSize = ctx.nvWritePos + WC_SHA256_DIGEST_SIZE + 3; + ctx.nvHal.maxSize = maxSize; + baseErases = gMockNvErases; + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_NV_GlobalWriteLock, + TPM_RH_OWNER), TPM_RC_SUCCESS); + AssertIntGT(gMockNvErases, baseErases); + AssertIntNE(NvReadPublicAttributes(&ctx, nvIdx) & TPMA_NV_WRITELOCKED, + 0); + + /* Unclean restart on the same store: the index is locked. */ + wc_FreeRng(&ctx.rng); + memset(&ctx, 0, sizeof(ctx)); + hal.maxSize = maxSize; + AssertIntEQ(FWTPM_NV_SetHAL(&ctx, &hal), 0); + AssertIntEQ(FWTPM_Init(&ctx), 0); + found = 0; + for (i = 0; i < FWTPM_MAX_NV_INDICES; i++) { + if (ctx.nvIndices[i].inUse && + ctx.nvIndices[i].nvPublic.nvIndex == nvIdx) { + AssertIntNE(ctx.nvIndices[i].nvPublic.attributes & + TPMA_NV_WRITELOCKED, 0); + found = 1; + } + } + AssertIntEQ(found, 1); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV_GlobalWriteLock at capacity:", 0); +} +#endif /* !FWTPM_NO_NV */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -26600,6 +26848,8 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifndef FWTPM_NO_NV if (argc == 2 && XSTRCMP(argv[1], "global-write-lock-failure") == 0) { test_fwtpm_global_write_lock_nv_failure(); + test_fwtpm_nv_global_write_lock_all_or_none(); + test_fwtpm_nv_global_write_lock_at_capacity(); return 0; } if (argc == 2 && XSTRCMP(argv[1], "nv-setbits-truncated") == 0) { @@ -27145,6 +27395,11 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif test_fwtpm_change_pps_resets_policies(); test_fwtpm_clear_resets_lockout_auth(); +#ifndef FWTPM_NO_NV + test_fwtpm_nv_global_write_lock_attribute(); + test_fwtpm_nv_global_write_lock_all_or_none(); + test_fwtpm_nv_global_write_lock_at_capacity(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); diff --git a/wolftpm/fwtpm/fwtpm.h b/wolftpm/fwtpm/fwtpm.h index a55a40f91..1bc63a156 100644 --- a/wolftpm/fwtpm/fwtpm.h +++ b/wolftpm/fwtpm/fwtpm.h @@ -860,7 +860,7 @@ typedef struct FWTPM_CTX { int shutdownStateSaved; /* Previous Shutdown(STATE), persisted */ int pendingClear; /* Deferred clear (after response auth) */ int disableClear; /* ClearControl: 1 = Clear is disabled */ - int globalNvWriteLock; /* NV_GlobalWriteLock (reset on Startup CLEAR) */ + int globalNvWriteLock; /* Persisted in the NV flags; not enforced */ /* HierarchyControl enable state (0 = enabled). Re-enabled on Startup * CLEAR per TPM 2.0 Part 1 (TPMS_STARTUP_CLEAR). */ int shDisabled; /* !shEnable: owner hierarchy */ diff --git a/wolftpm/fwtpm/fwtpm_nv.h b/wolftpm/fwtpm/fwtpm_nv.h index 3a60d4b09..0302812da 100644 --- a/wolftpm/fwtpm/fwtpm_nv.h +++ b/wolftpm/fwtpm/fwtpm_nv.h @@ -129,6 +129,10 @@ typedef struct FWTPM_NV_HEADER { /* NV indices (value starts with UINT32 nvHandle) */ #define FWTPM_NV_TAG_NV_INDEX 0x0040 #define FWTPM_NV_TAG_NV_INDEX_DEL 0x0041 +/* TPM2_NV_GlobalWriteLock (no value): sets TPMA_NV_WRITELOCKED on every + * TPMA_NV_GLOBALLOCK index replayed before it. One record, so the lock is + * committed for all of them or for none. */ +#define FWTPM_NV_TAG_NV_GLOBAL_LOCK 0x0042 /* Persistent objects (value starts with UINT32 handle) */ #define FWTPM_NV_TAG_PERSISTENT 0x0050 @@ -314,6 +318,19 @@ WOLFTPM_API int FWTPM_NV_SaveNvIndex(FWTPM_CTX* ctx, int slot); */ WOLFTPM_API int FWTPM_NV_DeleteNvIndex(FWTPM_CTX* ctx, UINT32 nvHandle); +/*! + \ingroup wolfTPM_fwTPM_NV + \brief Set TPMA_NV_WRITELOCKED on every NV index that has + TPMA_NV_GLOBALLOCK. The change is appended to the NV journal as one + record and applied to ctx->nvIndices only once that record is committed, + so on error no index is locked. + + \return 0 on success; a nonzero error code on I/O error + + \param ctx pointer to an initialized FWTPM_CTX +*/ +WOLFTPM_API int FWTPM_NV_GlobalWriteLock(FWTPM_CTX* ctx); + /*! \ingroup wolfTPM_fwTPM_NV \brief Append a persistent object slot to the NV journal. From 06d7df25fa0b775126302ace3ccacc6dfb4fe3a9 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:20:09 -0800 Subject: [PATCH 032/124] F-17151 - Treat a zero recovery time as DA disabled in fwTPM --- examples/management/da_check.c | 2 +- src/fwtpm/fwtpm_command.c | 9 +++++- tests/fwtpm_unit_tests.c | 53 ++++++++++++++++++++++++++++++---- 3 files changed, 57 insertions(+), 7 deletions(-) diff --git a/examples/management/da_check.c b/examples/management/da_check.c index ee58dd0ce..96fe91a52 100644 --- a/examples/management/da_check.c +++ b/examples/management/da_check.c @@ -169,7 +169,7 @@ int TPM2_DA_Check_Example(void* userCtx, int argc, char *argv[]) daSaved = 1; wolfTPM2_SetAuthPassword(&dev, 0, NULL); - rc = wolfTPM2_DictionaryAttackParameters(&dev, 3, 0, 0); + rc = wolfTPM2_DictionaryAttackParameters(&dev, 3, 1000, 0); if (rc != 0) goto exit; /* Bad auth until lockout. */ diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 0a67ff576..16f5b32ab 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -22623,6 +22623,12 @@ static void FwDaSelfHeal(FWTPM_CTX* ctx) UINT64 now; UINT64 elapsedSec, heals; + /* A daRecoveryTime of zero disables DA protection (Part 3 Sec.25.3): + * failures are not counted and those already counted are forgotten. */ + if (ctx->daRecoveryTime == 0) { + ctx->daFailedTries = 0; + } + /* Only after Startup, which seeds the baselines: running before then would * measure elapsed time from an unseeded (zero) baseline and wrongly heal. * No clock HAL means reboot/LockReset-only recovery. */ @@ -22686,7 +22692,8 @@ static int FwDaRegisterFailure(FWTPM_CTX* ctx, TPM_HANDLE entityH) * noDA primary handle with a DA-protected secondary auth) cannot grow * the counter or append NV entries without bound while already * locked. */ - if (ctx->daFailedTries < ctx->daMaxTries) { + if (ctx->daRecoveryTime != 0 && + ctx->daFailedTries < ctx->daMaxTries) { ctx->daFailedTries++; ctx->orderly = 0; (void)FWTPM_NV_SaveFlags(ctx); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 7f6b605e7..186bf07aa 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -17196,7 +17196,7 @@ static void test_fwtpm_da_lockout_and_reset(void) int rspSize = 0, cmdSz; memset(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), 0); - AssertIntEQ(DaSetParams(&ctx, 2, 0, 0), TPM_RC_SUCCESS); + AssertIntEQ(DaSetParams(&ctx, 2, 1000, 0), TPM_RC_SUCCESS); key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); @@ -17237,7 +17237,7 @@ static void test_fwtpm_da_noda_usable_during_lockout(void) UINT32 daKey, noDaKey; memset(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), 0); - AssertIntEQ(DaSetParams(&ctx, 2, 0, 0), TPM_RC_SUCCESS); + AssertIntEQ(DaSetParams(&ctx, 2, 1000, 0), TPM_RC_SUCCESS); noDaKey = DaMakeEccSignKey(&ctx, 0x00040472); /* noDA set */ daKey = DaMakeEccSignKey(&ctx, 0x00040072); /* noDA clear */ @@ -17308,7 +17308,7 @@ static void test_fwtpm_da_persist_failedtries(void) /* Boot 1: two failures, then a clean Shutdown (orderly). */ memset(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), 0); - AssertIntEQ(DaSetParams(&ctx, 100, 0, 0), TPM_RC_SUCCESS); + AssertIntEQ(DaSetParams(&ctx, 100, 1000, 0), TPM_RC_SUCCESS); key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); @@ -17364,7 +17364,7 @@ static void test_fwtpm_da_nonorderly_penalty(void) PutU32BE(gCmd + 2, (UINT32)cmdSz); FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); - AssertIntEQ(DaSetParams(&ctx, 100, 0, 0), TPM_RC_SUCCESS); + AssertIntEQ(DaSetParams(&ctx, 100, 1000, 0), TPM_RC_SUCCESS); key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); @@ -17399,7 +17399,7 @@ static void test_fwtpm_da_reboot_in_lockout_recovers(void) /* Boot 1: drive into lockout (maxTries=2), then drop power (non-orderly). */ memset(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), 0); - AssertIntEQ(DaSetParams(&ctx, 2, 0, 0), TPM_RC_SUCCESS); + AssertIntEQ(DaSetParams(&ctx, 2, 1000, 0), TPM_RC_SUCCESS); key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); @@ -26624,6 +26624,46 @@ static void test_fwtpm_nv_global_write_lock_at_capacity(void) } #endif /* !FWTPM_NO_NV */ +#if !defined(FWTPM_NO_DA) && defined(HAVE_ECC) +/* A newRecoveryTime of zero disables DA protection: an authorization failure + * is still reported, but it is not counted and never causes lockout. */ +static void test_fwtpm_da_recovery_zero_disables(void) +{ + FWTPM_CTX ctx; + UINT32 key; + int i; + + (void)remove(FWTPM_NV_FILE); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(DaSetParams(&ctx, 2, 0, 0), TPM_RC_SUCCESS); + key = DaMakeEccSignKey(&ctx, 0x00040072); + AssertIntNE(key, 0); + + for (i = 0; i < 4; i++) { + AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ((int)DaGetCapProp(&ctx, TPM_PT_LOCKOUT_COUNTER), 0); + } + AssertIntEQ(DaGetCapProp(&ctx, TPM_PT_PERMANENT) & + TPMA_PERMANENT_inLockout, 0); + + /* Failures counted earlier are forgotten at once */ + ctx.daFailedTries = 2; + AssertIntEQ((int)DaGetCapProp(&ctx, TPM_PT_LOCKOUT_COUNTER), 0); + AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + + /* A non-zero recovery time counts failures again */ + AssertIntEQ(DaSetParams(&ctx, 2, 1000, 0), TPM_RC_SUCCESS); + AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_LOCKOUT); + AssertIntEQ((int)DaGetCapProp(&ctx, TPM_PT_LOCKOUT_COUNTER), 2); + + FWTPM_Cleanup(&ctx); + (void)remove(FWTPM_NV_FILE); + fwtpm_pass("DA disabled by recoveryTime 0:", 0); +} +#endif /* !FWTPM_NO_DA && HAVE_ECC */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -27400,6 +27440,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_nv_global_write_lock_all_or_none(); test_fwtpm_nv_global_write_lock_at_capacity(); #endif +#if !defined(FWTPM_NO_DA) && defined(HAVE_ECC) + test_fwtpm_da_recovery_zero_disables(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 390250dca65147f2fdb5e75f65b51f4f82f0acd6 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:23:40 -0800 Subject: [PATCH 033/124] F-16835 - Accept an unrestricted signing key in fwTPM Quote --- src/fwtpm/fwtpm_command.c | 6 +----- tests/fwtpm_unit_tests.c | 36 ++++++++++++++++++++++++++---------- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 16f5b32ab..5dc0bb3d7 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -18601,15 +18601,11 @@ static TPM_RC FwCmd_Quote(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_HANDLE; } } - /* Quote requires a restricted signing key (Part 3 Sec.18.4) */ + /* Quote requires a signing key (Part 3 Sec.18.4) */ if (rc == 0) { if (!(sigObj->pub.objectAttributes & TPMA_OBJECT_sign)) rc = TPM_RC_KEY; } - if (rc == 0) { - if (!(sigObj->pub.objectAttributes & TPMA_OBJECT_restricted)) - rc = TPM_RC_ATTRIBUTES; - } if (rc == 0) { rc = FwParseAttestParams(cmd, cmdSize, cmdTag, diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 186bf07aa..8cc797628 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -14657,8 +14657,8 @@ static void test_fwtpm_zgen_2phase_signkey_returns_attributes(void) } #endif /* !FWTPM_NO_ECDH && !FWTPM_NO_ZGEN_2PHASE */ -/* Quote requires a restricted signing key per Part 3 Sec.18.4. Build the - * command once and run it against keys that violate each requirement. */ +/* Quote requires a signing key per Part 3 Sec.18.4. Build the command with + * no inScheme and an empty PCR selection. */ static int BuildQuoteCmd(byte* buf, UINT32 signHandle) { int pos = 0; @@ -14699,26 +14699,42 @@ static void test_fwtpm_quote_decrypt_key_returns_key(void) printf("Test fwTPM:\tQuote(decrypt key) rejected:\tPassed\n"); } -static void test_fwtpm_quote_unrestricted_sign_returns_attributes(void) +/* An unrestricted signing key may quote. With no scheme of its own it signs + * with the one in inScheme. */ +static void test_fwtpm_quote_unrestricted_sign(void) { FWTPM_CTX ctx; - int cmdSz, rspSize = 0; + int pos, rspSize = 0; UINT32 keyH; memset(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), 0); - /* Non-restricted signing key must not be usable for attestation */ keyH = CreatePrimaryEccSignHelper(&ctx); AssertIntNE(keyH, 0); - cmdSz = BuildQuoteCmd(gCmd, keyH); - FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES); + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Quote); + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 0); pos += 2; /* qualifyingData */ + PutU16BE(gCmd + pos, TPM_ALG_ECDSA); pos += 2; /* inScheme */ + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + pos, 1); pos += 4; /* PCRselect count */ + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + gCmd[pos++] = (byte)PCR_SELECT_MAX; + XMEMSET(gCmd + pos, 0, PCR_SELECT_MAX); pos += PCR_SELECT_MAX; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + /* paramSize(4) | TPM2B_ATTEST | sigAlg(2) | hashAlg(2) */ + pos = TPM2_HEADER_SIZE + 4; + pos += 2 + GetU16BE(gRsp + pos); + AssertIntEQ(GetU16BE(gRsp + pos), TPM_ALG_ECDSA); + AssertIntEQ(GetU16BE(gRsp + pos + 2), TPM_ALG_SHA256); FlushHandle(&ctx, keyH); FWTPM_Cleanup(&ctx); - printf("Test fwTPM:\tQuote(unrestricted sign) rejected:\tPassed\n"); + fwtpm_pass("Quote(unrestricted sign):", 0); } /* A key that declares a signing scheme must not be downgraded by a wire @@ -27402,7 +27418,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif /* !FWTPM_NO_ZGEN_2PHASE */ #endif /* !FWTPM_NO_ECDH */ test_fwtpm_quote_decrypt_key_returns_key(); - test_fwtpm_quote_unrestricted_sign_returns_attributes(); + test_fwtpm_quote_unrestricted_sign(); test_fwtpm_sign_scheme_downgrade_rejected(); test_fwtpm_quote_clockinfo_resetcount_nonzero(); test_fwtpm_certify_decrypt_key_returns_key(); From 4335991d0c27b2de2be22eca0391ddef66c3dc06 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:28:34 -0800 Subject: [PATCH 034/124] F-16836 - Hash the fwTPM Quote pcrDigest with the selected signing scheme hash --- src/fwtpm/fwtpm_command.c | 19 +++++- tests/fwtpm_unit_tests.c | 126 +++++++++++++++++++++++++++++++++++++- 2 files changed, 140 insertions(+), 5 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 5dc0bb3d7..f29eb6a44 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -18611,6 +18611,17 @@ static TPM_RC FwCmd_Quote(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = FwParseAttestParams(cmd, cmdSize, cmdTag, &qualifyingData, &sigScheme, &sigHashAlg); } + /* A key with no scheme of its own needs one from inScheme + * (Part 3 Sec.18.4) */ + if (rc == 0 && sigScheme == TPM_ALG_NULL && + ((sigObj->pub.type == TPM_ALG_RSA && + sigObj->pub.parameters.rsaDetail.scheme.scheme == + TPM_ALG_NULL) || + (sigObj->pub.type == TPM_ALG_ECC && + sigObj->pub.parameters.eccDetail.scheme.scheme == + TPM_ALG_NULL))) { + rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; + } /* PCRselect */ if (rc == 0) { @@ -18656,11 +18667,13 @@ static TPM_RC FwCmd_Quote(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* pcrDigest = hash of the selected PCR values under the signature's * hash so a verifier agrees. ML-DSA keys resolve to nameAlg (no scheme - * hash on the wire); classical keys honor the wire hash then PCR bank. */ + * hash on the wire); classical keys use the hash of the selected + * signing scheme (Part 3 Sec.18.4). */ pcrHashAlg = FwAttestMldsaHashAlg(sigObj); if (pcrHashAlg == TPM_ALG_NULL) { - pcrHashAlg = (sigHashAlg != TPM_ALG_NULL) ? sigHashAlg : - (numSel > 0 ? selections[0].hashAlg : (UINT16)TPM_ALG_SHA256); + UINT16 keyScheme = sigScheme; + pcrHashAlg = sigHashAlg; + FwResolveSignScheme(sigObj, &keyScheme, &pcrHashAlg); } wcH = FwGetWcHashType(pcrHashAlg); dSz = TPM2_GetHashDigestSize(pcrHashAlg); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 8cc797628..43f02834a 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -14658,7 +14658,7 @@ static void test_fwtpm_zgen_2phase_signkey_returns_attributes(void) #endif /* !FWTPM_NO_ECDH && !FWTPM_NO_ZGEN_2PHASE */ /* Quote requires a signing key per Part 3 Sec.18.4. Build the command with - * no inScheme and an empty PCR selection. */ + * an ECDSA SHA-256 inScheme and an empty PCR selection. */ static int BuildQuoteCmd(byte* buf, UINT32 signHandle) { int pos = 0; @@ -14668,7 +14668,8 @@ static int BuildQuoteCmd(byte* buf, UINT32 signHandle) PutU32BE(buf + pos, signHandle); pos += 4; pos = AppendPwAuth(buf, pos, NULL, 0); PutU16BE(buf + pos, 0); pos += 2; /* qualifyingData */ - PutU16BE(buf + pos, TPM_ALG_NULL); pos += 2; /* inScheme */ + PutU16BE(buf + pos, TPM_ALG_ECDSA); pos += 2; /* inScheme */ + PutU16BE(buf + pos, TPM_ALG_SHA256); pos += 2; PutU32BE(buf + pos, 1); pos += 4; /* PCRselect count */ PutU16BE(buf + pos, TPM_ALG_SHA256); pos += 2; buf[pos++] = (byte)PCR_SELECT_MAX; @@ -26680,6 +26681,124 @@ static void test_fwtpm_da_recovery_zero_disables(void) } #endif /* !FWTPM_NO_DA && HAVE_ECC */ +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) +/* ECC P-256 signing primary; sigScheme TPM_ALG_NULL leaves the scheme open */ +static UINT32 CreateEccSignPrimaryScheme(FWTPM_CTX* ctx, UINT32 attributes, + UINT16 sigScheme, UINT16 sigHashAlg) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_CreatePrimary); + int pubStart, rspSize = 0; + + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 4); pos += 2; /* inSensitive */ + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, 0); pos += 2; + pubStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_ECC); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + pos, attributes); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; /* authPolicy */ + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* symmetric */ + PutU16BE(gCmd + pos, sigScheme); pos += 2; + if (sigScheme != TPM_ALG_NULL) { + PutU16BE(gCmd + pos, sigHashAlg); pos += 2; + } + PutU16BE(gCmd + pos, TPM_ECC_NIST_P256); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* kdf */ + PutU16BE(gCmd + pos, 0); pos += 2; /* x */ + PutU16BE(gCmd + pos, 0); pos += 2; /* y */ + PutU16BE(gCmd + pubStart, (UINT16)(pos - pubStart - 2)); + PutU16BE(gCmd + pos, 0); pos += 2; /* outsideInfo */ + PutU32BE(gCmd + pos, 0); pos += 4; /* creationPCR */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + return GetU32BE(gRsp + TPM2_HEADER_SIZE); +} + +/* Quote FW_TEST_PCR of one bank. On success *pcrDigestSz is the size of the + * pcrDigest inside the returned TPMS_ATTEST. */ +static TPM_RC SendQuoteScheme(FWTPM_CTX* ctx, UINT32 keyH, UINT16 sigScheme, + UINT16 sigHashAlg, UINT16 bankAlg, int* pcrDigestSz) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Quote); + int rspSize = 0; + int pcr = FW_TEST_PCR - PCR_FIRST; + + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 0); pos += 2; /* qualifyingData */ + PutU16BE(gCmd + pos, sigScheme); pos += 2; + if (sigScheme != TPM_ALG_NULL) { + PutU16BE(gCmd + pos, sigHashAlg); pos += 2; + } + PutU32BE(gCmd + pos, 1); pos += 4; + PutU16BE(gCmd + pos, bankAlg); pos += 2; + gCmd[pos++] = (byte)PCR_SELECT_MAX; + memset(gCmd + pos, 0, PCR_SELECT_MAX); + gCmd[pos + pcr / 8] = (byte)(1 << (pcr % 8)); + pos += PCR_SELECT_MAX; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + if (GetRspRC(gRsp) == TPM_RC_SUCCESS) { + /* paramSize(4) | attest size(2) | magic(4) | type(2) | + * qualifiedSigner | extraData | clockInfo(17) | firmware(8) | + * count(4) | hash(2) | sizeofSelect(1) | select | pcrDigest */ + pos = TPM2_HEADER_SIZE + 4 + 2 + 4 + 2; + pos += 2 + GetU16BE(gRsp + pos); + pos += 2 + GetU16BE(gRsp + pos); + pos += 17 + 8 + 4 + 2 + 1 + PCR_SELECT_MAX; + *pcrDigestSz = GetU16BE(gRsp + pos); + } + return GetRspRC(gRsp); +} + +/* pcrDigest is computed with the hash of the selected signing scheme, taken + * from the key or else from inScheme, not with the hash of the PCR bank. */ +static void test_fwtpm_quote_scheme_hash(void) +{ + FWTPM_CTX ctx; + UINT32 keyH; + int dSz = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + /* restricted sign key with a fixed ECDSA SHA-256 scheme */ + keyH = CreateEccSignPrimaryScheme(&ctx, 0x00050472, TPM_ALG_ECDSA, + TPM_ALG_SHA256); + AssertIntEQ(SendQuoteScheme(&ctx, keyH, TPM_ALG_NULL, TPM_ALG_NULL, + TPM_ALG_SHA256, &dSz), TPM_RC_SUCCESS); + AssertIntEQ(dSz, 32); +#ifdef WOLFSSL_SHA384 + AssertIntEQ(SendQuoteScheme(&ctx, keyH, TPM_ALG_NULL, TPM_ALG_NULL, + TPM_ALG_SHA384, &dSz), TPM_RC_SUCCESS); + AssertIntEQ(dSz, 32); +#endif + FlushHandle(&ctx, keyH); + + /* sign key with no scheme: inScheme has to supply one */ + keyH = CreateEccSignPrimaryScheme(&ctx, 0x00040472, TPM_ALG_NULL, + TPM_ALG_NULL); + AssertIntEQ(SendQuoteScheme(&ctx, keyH, TPM_ALG_NULL, TPM_ALG_NULL, + TPM_ALG_SHA256, &dSz), TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendQuoteScheme(&ctx, keyH, TPM_ALG_ECDSA, TPM_ALG_SHA256, + TPM_ALG_SHA256, &dSz), TPM_RC_SUCCESS); + AssertIntEQ(dSz, 32); +#ifdef WOLFSSL_SHA384 + AssertIntEQ(SendQuoteScheme(&ctx, keyH, TPM_ALG_ECDSA, TPM_ALG_SHA384, + TPM_ALG_SHA256, &dSz), TPM_RC_SUCCESS); + AssertIntEQ(dSz, 48); +#endif + FlushHandle(&ctx, keyH); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("Quote pcrDigest uses scheme hash:", 0); +} +#endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -27459,6 +27578,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if !defined(FWTPM_NO_DA) && defined(HAVE_ECC) test_fwtpm_da_recovery_zero_disables(); #endif +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) + test_fwtpm_quote_scheme_hash(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 573a6c59e511aec1f8ff113151d3d82f5e14bd44 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:33:38 -0800 Subject: [PATCH 035/124] F-16224 - Refuse a fwTPM policy session for an entity that has no authPolicy --- src/fwtpm/fwtpm_command.c | 81 +++++++++++++++++------------ tests/fwtpm_unit_tests.c | 105 ++++++++++++++++++++++++++++++++++---- 2 files changed, 143 insertions(+), 43 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index f29eb6a44..660ddba72 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -23435,24 +23435,6 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, int policyDiff; word32 cmpSz; - /* PCR values changed since PolicyPCR: the session no longer - * reflects the PCR state it was evaluated against. */ - if (pSess->hasPcrUpdateCounter && - pSess->pcrUpdateCounter != ctx->pcrUpdateCounter) { - *rspSize = FwBuildErrorResponse(rspBuf, rspCap, - TPM_ST_NO_SESSIONS, TPM_RC_PCR_CHANGED); - TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); - return TPM_RC_SUCCESS; - } - - if (pSess->timeout != 0 && - pSess->timeout < FWTPM_Clock_GetMs(ctx)) { - *rspSize = FwBuildErrorResponse(rspBuf, rspCap, - TPM_ST_NO_SESSIONS, TPM_RC_EXPIRED); - TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); - return TPM_RC_SUCCESS; - } - /* Find entity's authPolicy by handle type */ #ifndef FWTPM_NO_NV if ((entityH & 0xFF000000) == (NV_INDEX_FIRST & 0xFF000000)) { @@ -23496,6 +23478,53 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, authPolicyAlg = ctx->pcrPolicyAlg[entityH - PCR_FIRST]; } + if (authPolicy != NULL && authPolicy->size == 0) { + /* A policy session cannot authorize an entity that has no + * authPolicy (Part 1 Sec.19.7.1). The empty authPolicy of an + * object or a PCR never equals a policyDigest; any other + * entity has no policy authorization available, which is + * reported ahead of the session checks. */ + TPM_RC noPolicyRc = TPM_RC_AUTH_UNAVAILABLE; + if ((entityH & 0xFF000000) == + (TRANSIENT_FIRST & 0xFF000000) || + (entityH & 0xFF000000) == + (PERSISTENT_FIRST & 0xFF000000) || + entityH <= PCR_LAST) { + noPolicyRc = TPM_RC_POLICY_FAIL; + if (pSess->hasPcrUpdateCounter && + pSess->pcrUpdateCounter != ctx->pcrUpdateCounter) { + noPolicyRc = TPM_RC_PCR_CHANGED; + } + } + #ifdef DEBUG_WOLFTPM + printf("fwTPM: Policy session rejected for " + "handle 0x%x without authPolicy (CC=0x%x)\n", + entityH, cmdCode); + #endif + *rspSize = FwBuildErrorResponse(rspBuf, rspCap, + TPM_ST_NO_SESSIONS, noPolicyRc); + TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); + return TPM_RC_SUCCESS; + } + + /* PCR values changed since PolicyPCR: the session no longer + * reflects the PCR state it was evaluated against. */ + if (pSess->hasPcrUpdateCounter && + pSess->pcrUpdateCounter != ctx->pcrUpdateCounter) { + *rspSize = FwBuildErrorResponse(rspBuf, rspCap, + TPM_ST_NO_SESSIONS, TPM_RC_PCR_CHANGED); + TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); + return TPM_RC_SUCCESS; + } + + if (pSess->timeout != 0 && + pSess->timeout < FWTPM_Clock_GetMs(ctx)) { + *rspSize = FwBuildErrorResponse(rspBuf, rspCap, + TPM_ST_NO_SESSIONS, TPM_RC_EXPIRED); + TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); + return TPM_RC_SUCCESS; + } + /* If entity has a non-empty authPolicy, it must match */ if (authPolicy != NULL && authPolicy->size > 0) { /* Always run TPM2_ConstantCompare so timing doesn't leak size */ @@ -23568,22 +23597,6 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, } #endif /* !FWTPM_NO_PP */ } - else if (authPolicy != NULL && authPolicy->size == 0 && - (cmdAuths[pj].cmdHmacSize == 0 || - (!pSess->isPasswordPolicy && !pSess->isAuthValuePolicy))) { - /* A policy session authorizes an empty-authPolicy entity only - * via PolicyPassword or PolicyAuthValue; otherwise the entity - * auth is excluded and an unbound/empty HMAC would authorize. */ - #ifdef DEBUG_WOLFTPM - printf("fwTPM: Policy session empty-HMAC rejected for " - "handle 0x%x without authPolicy (CC=0x%x)\n", - entityH, cmdCode); - #endif - *rspSize = FwBuildErrorResponse(rspBuf, rspCap, - TPM_ST_NO_SESSIONS, TPM_RC_POLICY_FAIL); - TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); - return TPM_RC_SUCCESS; - } else if (authPolicy == NULL) { /* A policy session cannot authorize a handle whose authPolicy * cannot be resolved (for example hash/sign sequence handles); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 43f02834a..95c4f72ab 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -25806,10 +25806,9 @@ static int fwtpm_nv_define_sess(byte* buf, UINT32 nvIndex, UINT16 dataSize, return pos; } -/* The parameter binding must also hold for an entity whose authPolicy is - * empty. Such an entity is authorized by its auth value through - * PolicyPassword, never by comparing the session digest against a policy, so - * a binding enforced only alongside that comparison would not apply here. */ +/* An entity whose authPolicy is empty has no policy authorization, so a + * policy session is refused for it whether or not the command matches the + * PolicyParameters binding, even with PolicyPassword and the auth value. */ static void test_fwtpm_policy_parameters_empty_policy(void) { FWTPM_CTX ctx; @@ -25858,8 +25857,7 @@ static void test_fwtpm_policy_parameters_empty_policy(void) pHash, &pHashSz), 0); AssertIntEQ(pHashSz, WC_SHA256_DIGEST_SIZE); - /* Bound to okIdx, so a different index is a different parameter area and - * must be refused even though the password authorizes the owner. */ + /* Bound to okIdx, so a different index is a different parameter area */ sessH = fwtpm_policy_parameters_session(&ctx, pHash); AssertIntNE(sessH, 0); AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyPassword, sessH), @@ -25868,10 +25866,10 @@ static void test_fwtpm_policy_parameters_empty_policy(void) pw, (int)sizeof(pw)); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_POLICY_FAIL); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_AUTH_UNAVAILABLE); FlushHandle(&ctx, sessH); - /* The command the pHash was computed over is still authorized */ + /* The command the pHash was computed over is refused as well */ sessH = fwtpm_policy_parameters_session(&ctx, pHash); AssertIntNE(sessH, 0); AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyPassword, sessH), @@ -25880,7 +25878,7 @@ static void test_fwtpm_policy_parameters_empty_policy(void) pw, (int)sizeof(pw)); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_AUTH_UNAVAILABLE); FlushHandle(&ctx, sessH); FWTPM_Cleanup(&ctx); @@ -26799,6 +26797,92 @@ static void test_fwtpm_quote_scheme_hash(void) } #endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION */ +#if !defined(FWTPM_NO_POLICY) && !defined(FWTPM_NO_NV) +/* A policy session cannot authorize an entity that has no authPolicy, even + * after PolicyPassword with the right authValue: an NV index or a hierarchy + * has no policy authorization available, and an object's empty authPolicy + * never equals a policyDigest. */ +static void test_fwtpm_policy_session_needs_auth_policy(void) +{ + FWTPM_CTX ctx; + static const byte pw[] = { 'p', 'w' }; + const UINT32 nvIdx = 0x01500A20; + UINT32 sessH; +#ifdef HAVE_ECC + UINT32 objH; +#endif + int cmdSz, pos, rspSize = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmdSz = BuildNvDefineCmdEx(gCmd, nvIdx, 8, TPMA_NV_AUTHREAD | + TPMA_NV_AUTHWRITE, pw, (UINT16)sizeof(pw), NULL, 0); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + AssertIntEQ(SendHierarchyChangeAuth(&ctx, TPM_RH_OWNER, NULL, 0, pw, + (int)sizeof(pw)), TPM_RC_SUCCESS); + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(sessH, 0); + AssertIntEQ(SendPolicyCmd(&ctx, TPM_CC_PolicyPassword, sessH), + TPM_RC_SUCCESS); + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + TPM_CC_HierarchyChangeAuth); + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + pos = AppendAuth(gCmd, pos, sessH, TPMA_SESSION_continueSession, pw, + (int)sizeof(pw)); + PutU16BE(gCmd + pos, 0); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_AUTH_UNAVAILABLE); + AssertIntEQ(SendHierarchyChangeAuth(&ctx, TPM_RH_OWNER, pw, + (int)sizeof(pw), NULL, 0), TPM_RC_SUCCESS); + + AssertIntEQ(SendNvAccessCmd(&ctx, nvIdx, sessH, pw, (int)sizeof(pw), 1), + TPM_RC_AUTH_UNAVAILABLE); + AssertIntEQ(SendNvAccessCmd(&ctx, nvIdx, TPM_RS_PW, pw, (int)sizeof(pw), + 1), TPM_RC_SUCCESS); + +#ifdef HAVE_ECC + /* An object: the session's digest cannot match the empty authPolicy */ + objH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); + AssertIntNE(objH, 0); + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Create); + PutU32BE(gCmd + pos, objH); pos += 4; + pos = AppendAuth(gCmd, pos, sessH, TPMA_SESSION_continueSession, NULL, 0); + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_POLICY_FAIL); + FlushHandle(&ctx, objH); +#endif + + /* A PCR: its empty authPolicy cannot match the session's digest either */ + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_PCR_Extend); + PutU32BE(gCmd + pos, 16); pos += 4; + pos = AppendAuth(gCmd, pos, sessH, TPMA_SESSION_continueSession, NULL, 0); + PutU32BE(gCmd + pos, 1); pos += 4; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + memset(gCmd + pos, 0, WC_SHA256_DIGEST_SIZE); + pos += WC_SHA256_DIGEST_SIZE; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_POLICY_FAIL); + + /* The missing authPolicy is reported ahead of a stale PolicyPCR */ + AssertIntEQ(SendPolicyPcrCmd(&ctx, sessH, NULL, 0), TPM_RC_SUCCESS); + AssertIntEQ(SendPcrExtendLoc(&ctx, 0, 0), TPM_RC_SUCCESS); + AssertIntEQ(SendNvAccessCmd(&ctx, nvIdx, sessH, pw, (int)sizeof(pw), 1), + TPM_RC_AUTH_UNAVAILABLE); + FlushHandle(&ctx, sessH); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Policy session needs an authPolicy:", 0); +} +#endif /* !FWTPM_NO_POLICY && !FWTPM_NO_NV */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -27581,6 +27665,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) test_fwtpm_quote_scheme_hash(); #endif +#if !defined(FWTPM_NO_POLICY) && !defined(FWTPM_NO_NV) + test_fwtpm_policy_session_needs_auth_policy(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 88cfac7fa8f380e43f289413533eb1360e9592d0 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:37:26 -0800 Subject: [PATCH 036/124] F-17156 - Return TPM_RC_AUTH_UNAVAILABLE for fwTPM authorization of a public-only object --- src/fwtpm/fwtpm_command.c | 39 ++++- src/fwtpm/fwtpm_nv.c | 17 ++- tests/fwtpm_unit_tests.c | 301 +++++++++++++++++++++++++++++++++++++- wolftpm/fwtpm/fwtpm.h | 1 + 4 files changed, 344 insertions(+), 14 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 660ddba72..c15954c4f 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -6165,6 +6165,7 @@ static TPM_RC FwSerializeObjectContext(FWTPM_CTX* ctx, FWTPM_Object* obj, TPM2_Packet_AppendBytes(&packet, obj->authValue.buffer, obj->authValue.size); TPM2_Packet_AppendU16(&packet, (UINT16)obj->privKeySize); TPM2_Packet_AppendBytes(&packet, obj->privKey, obj->privKeySize); + TPM2_Packet_AppendU8(&packet, (UINT8)(obj->publicOnly != 0)); if (packet.overflow) { rc = TPM_RC_SIZE; } @@ -6185,6 +6186,7 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, byte proof[WC_SHA256_DIGEST_SIZE]; UINT16 pubSz, authSz = 0, privateSz = 0; int authPos = 0, privatePos = 0, publicEnd; + int flagPos = 0; UINT32 expectedMarker; /* hierarchy + proof + public/auth/private size fields */ @@ -6243,7 +6245,15 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, TPM2_Packet_ParseU16(&packet, &privateSz); privatePos = packet.pos; if (privateSz > FWTPM_MAX_PRIVKEY_DER || - privatePos + privateSz != plainSz) { + privatePos + privateSz > plainSz) { + rc = TPM_RC_INTEGRITY; + } + } + /* The public-only flag trails the private data; a blob saved without it + * ends there */ + if (rc == 0 && privatePos + privateSz != plainSz) { + flagPos = privatePos + privateSz; + if (flagPos + 1 != plainSz) { rc = TPM_RC_INTEGRITY; } } @@ -6260,6 +6270,10 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, XMEMCPY(obj->authValue.buffer, plain + authPos, authSz); obj->privKeySize = privateSz; XMEMCPY(obj->privKey, plain + privatePos, privateSz); + /* Without the flag only an object that has no private data is taken + * to be public-only */ + obj->publicOnly = (flagPos != 0) ? (plain[flagPos] != 0) : + (privateSz == 0); rc = FwComputePublicName(&obj->pub, &obj->name); if (rc != 0) { wc_ForceZero(obj, sizeof(*obj)); @@ -7790,7 +7804,7 @@ static TPM_RC FwCmd_EvictControl(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } if (rc == 0 && (obj->hierarchy == TPM_RH_NULL || - obj->privKeySize == 0 || + obj->publicOnly || (obj->pub.objectAttributes & TPMA_OBJECT_stClear) != 0)) { rc = TPM_RC_ATTRIBUTES; } @@ -8778,6 +8792,7 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, XMEMCPY(obj->privKey, privKeyDer, (size_t)privKeyDerSz); } obj->privKeySize = privKeyDerSz; + obj->publicOnly = (inPrivSize == 0); /* Per Part 3 Sec.12.3.1, the supplied hierarchy field controls which * proofValue (if any) signs tickets produced by this key; default * to TPM_RH_NULL when caller passed 0 so the resulting object @@ -23435,6 +23450,18 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, int policyDiff; word32 cmpSz; + /* An object loaded without its sensitive area has no authPolicy + * to authorize with (Part 3 Sec.18.2). */ + if ((entityH & 0xFF000000) == (TRANSIENT_FIRST & 0xFF000000)) { + FWTPM_Object* pubObj = FwFindObject(ctx, entityH); + if (pubObj != NULL && pubObj->publicOnly) { + *rspSize = FwBuildErrorResponse(rspBuf, rspCap, + TPM_ST_NO_SESSIONS, TPM_RC_AUTH_UNAVAILABLE); + TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); + return TPM_RC_SUCCESS; + } + } + /* Find entity's authPolicy by handle type */ #ifndef FWTPM_NO_NV if ((entityH & 0xFF000000) == (NV_INDEX_FIRST & 0xFF000000)) { @@ -23835,7 +23862,8 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, /* userWithAuth enforcement: per TPM 2.0 spec Part 1, Section 19.7.1, * if an object has authPolicy set and userWithAuth is CLEAR, only a * policy session can authorize the object. Reject password and HMAC - * sessions for such objects. */ + * sessions for such objects. An object loaded without its sensitive area + * has no authValue to authorize with either (Part 3 Sec.18.2). */ for (pj = 0; pj < cmdAuthCnt && pj < (int)entry->authHandleCnt; pj++) { if (cmdAuths[pj].handle == TPM_RS_PW || (cmdAuths[pj].sess != NULL && @@ -23846,8 +23874,9 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, (entityH & 0xFF000000) == (PERSISTENT_FIRST & 0xFF000000)) { uwObj = FwFindObject(ctx, entityH); } - if (uwObj != NULL && uwObj->pub.authPolicy.size > 0 && - !(uwObj->pub.objectAttributes & TPMA_OBJECT_userWithAuth)) { + if (uwObj != NULL && (uwObj->publicOnly || + (uwObj->pub.authPolicy.size > 0 && + !(uwObj->pub.objectAttributes & TPMA_OBJECT_userWithAuth)))) { #ifdef DEBUG_WOLFTPM printf("fwTPM: Password/HMAC auth rejected for handle " "0x%x — policy required (userWithAuth clear)\n", entityH); diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index d38e51ba0..a76029c92 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -671,6 +671,9 @@ static int FwNvMarshalObject(byte* buf, word32* pos, word32 maxSz, if (rc == 0) { rc = FwNvMarshalU32(buf, pos, maxSz, obj->hierarchy); } + if (rc == 0) { + rc = FwNvMarshalU8(buf, pos, maxSz, (UINT8)(obj->publicOnly != 0)); + } return rc; } @@ -680,6 +683,7 @@ static int FwNvUnmarshalObject(const byte* buf, word32* pos, word32 maxSz, int rc; int skipEntry = 0; UINT16 privSz; + UINT8 publicOnly = 0; XMEMSET(obj, 0, sizeof(FWTPM_Object)); @@ -722,6 +726,15 @@ static int FwNvUnmarshalObject(const byte* buf, word32* pos, word32 maxSz, else if (rc == 0 && obj->handle >= PLATFORM_PERSISTENT) { obj->hierarchy = TPM_RH_PLATFORM; } + /* Optional trailing public-only flag. A record written without it holds + * a public-only object when it has no private data. */ + if (rc == 0 && *pos + 1 <= maxSz) { + rc = FwNvUnmarshalU8(buf, pos, maxSz, &publicOnly); + obj->publicOnly = (publicOnly != 0); + } + else if (rc == 0) { + obj->publicOnly = (obj->privKeySize == 0); + } if (rc == 0) { /* Validate the handle after consuming the complete record so a * truncated entry cannot be mistaken for a legacy semantic reject. */ @@ -2809,7 +2822,7 @@ int FWTPM_NV_Save(FWTPM_CTX* ctx) word32 needed; pos = 0; needed = 4 + FWTPM_NV_PUBAREA_EST + FWTPM_NV_NAME_EST + 2 + - ctx->persistent[i].privKeySize + FWTPM_NV_AUTH_EST; + ctx->persistent[i].privKeySize + FWTPM_NV_AUTH_EST + 1; if (needed > bufSz) { byte* newBuf; newBuf = (byte*)XMALLOC(needed, NULL, @@ -3326,7 +3339,7 @@ int FWTPM_NV_SavePersistent(FWTPM_CTX* ctx, int slot) } bufSz = 4 + FWTPM_NV_PUBAREA_EST + 2 + FWTPM_NV_NAME_EST + 2 + - obj->privKeySize + 2 + FWTPM_NV_AUTH_EST; + obj->privKeySize + 2 + FWTPM_NV_AUTH_EST + 1; buf = (byte*)XMALLOC(bufSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (buf == NULL) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 95c4f72ab..0bb74195c 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -6544,8 +6544,8 @@ static void test_fwtpm_mldsa_loadexternal_verify(void) !defined(FWTPM_NO_ATTESTATION) /* A public-only ML-DSA key (loaded via TPM2_LoadExternal, no private seed) * must not be usable for attestation: signing from its all-zero seed would - * derive a universally reproducible key unrelated to the public key. Quote - * must return TPM_RC_KEY. */ + * derive a universally reproducible key unrelated to the public key. It has + * no authValue to authorize with, so Quote returns TPM_RC_AUTH_UNAVAILABLE. */ static void test_fwtpm_mldsa_quote_public_only_returns_key(void) { FWTPM_CTX ctx; @@ -6602,7 +6602,7 @@ static void test_fwtpm_mldsa_quote_public_only_returns_key(void) rspSize = 0; AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0), TPM_RC_SUCCESS); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_KEY); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_AUTH_UNAVAILABLE); FlushHandle(&ctx, handle); FWTPM_Cleanup(&ctx); @@ -6645,8 +6645,9 @@ static UINT32 LoadPublicOnlyMldsa(FWTPM_CTX* ctx, UINT16 algType) return GetU32BE(gRsp + TPM2_HEADER_SIZE); } -/* A public-only ML-DSA key has no private seed. SignSequenceComplete and - * SignDigest must return TPM_RC_KEY rather than sign from an all-zero seed. */ +/* A public-only ML-DSA key has no private seed and no authValue. + * SignSequenceComplete and SignDigest must return TPM_RC_AUTH_UNAVAILABLE + * rather than sign from an all-zero seed. */ static void test_fwtpm_mldsa_sign_public_only_returns_key(void) { FWTPM_CTX ctx; @@ -6693,7 +6694,7 @@ static void test_fwtpm_mldsa_sign_public_only_returns_key(void) rspSize = 0; AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0), TPM_RC_SUCCESS); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_KEY); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_AUTH_UNAVAILABLE); FlushHandle(&ctx, seqHandle); FlushHandle(&ctx, handle); @@ -6721,7 +6722,7 @@ static void test_fwtpm_mldsa_sign_public_only_returns_key(void) rspSize = 0; AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0), TPM_RC_SUCCESS); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_KEY); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_AUTH_UNAVAILABLE); FlushHandle(&ctx, handle); #endif /* WOLFTPM_HASH_MLDSA */ @@ -26883,6 +26884,286 @@ static void test_fwtpm_policy_session_needs_auth_policy(void) } #endif /* !FWTPM_NO_POLICY && !FWTPM_NO_NV */ +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) +/* Certify objectHandle with signHandle. A zero sessH authorizes the object + * with the Empty Auth password, otherwise with that session. */ +static TPM_RC SendCertify(FWTPM_CTX* ctx, UINT32 objectHandle, + UINT32 signHandle, UINT32 sessH) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Certify); + int rspSize = 0; + int authStart; + + PutU32BE(gCmd + pos, objectHandle); pos += 4; + PutU32BE(gCmd + pos, signHandle); pos += 4; + authStart = pos; + pos = AppendAuth(gCmd, pos, (sessH != 0) ? sessH : (TPM_HANDLE)TPM_RS_PW, + (sessH != 0) ? TPMA_SESSION_continueSession : 0, NULL, 0); + /* second entry in the same authorization area */ + PutU32BE(gCmd + pos, TPM_RS_PW); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; + gCmd[pos++] = 0; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU32BE(gCmd + authStart, (UINT32)(pos - authStart - 4)); + PutU16BE(gCmd + pos, 0); pos += 2; /* qualifyingData */ + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* inScheme */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +#ifndef FWTPM_NO_CONTEXT +/* Save the context of objH to saved and take the trailing public-only flag, + * which has the value flag, off its protected area. Returns the size. */ +static int SaveContextWithoutFlag(FWTPM_CTX* ctx, UINT32 objH, byte* saved, + int savedMax, byte flag) +{ + const int wrapOff = 8 + 4 + 4 + 2 + 4 + 4; + byte plain[MAX_CONTEXT_SIZE]; + int rspSize = 0, ctxSz, plainSz = 0, wrappedSz = 0; + UINT64 seq; + + BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 14, TPM_CC_ContextSave); + PutU32BE(gCmd + 10, objH); + FWTPM_ProcessCommand(ctx, gCmd, 14, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + ctxSz = rspSize - TPM2_HEADER_SIZE; + AssertIntGT(ctxSz, wrapOff); + AssertIntLE(ctxSz, savedMax); + memcpy(saved, gRsp + TPM2_HEADER_SIZE, (size_t)ctxSz); + + seq = ((UINT64)GetU32BE(saved) << 32) | GetU32BE(saved + 4); + AssertIntEQ(FwUnwrapContextBlob(ctx, seq, FWTPM_CTX_TYPE_OBJECT, + saved + wrapOff, ctxSz - wrapOff, plain, (int)sizeof(plain), + &plainSz), 0); + AssertIntGT(plainSz, 1); + plainSz--; + AssertIntEQ(plain[plainSz], flag); + AssertIntEQ(FwWrapContextBlob(ctx, seq, FWTPM_CTX_TYPE_OBJECT, plain, + plainSz, saved + wrapOff, savedMax - wrapOff, &wrappedSz), 0); + PutU16BE(saved + 16, (UINT16)(8 + wrappedSz)); + wc_ForceZero(plain, sizeof(plain)); + return wrapOff + wrappedSz; +} +#endif /* !FWTPM_NO_CONTEXT */ + +/* An object loaded without its sensitive area has no authValue or authPolicy + * to authorize with, so it cannot be the certified object. */ +static void test_fwtpm_public_only_object_auth_unavailable(void) +{ + FWTPM_CTX ctx; + UINT32 signH, pubOnlyH; +#ifndef FWTPM_NO_POLICY + UINT32 sessH; +#endif + byte pub[sizeof(TPM2B_PUBLIC)]; +#ifndef FWTPM_NO_CONTEXT + UINT32 loadedH; + byte saved[sizeof(TPMS_CONTEXT)]; + int ctxSz; +#endif + int pubSz, pos, rspSize = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + signH = CreateEccSignPrimaryScheme(&ctx, 0x00050472, TPM_ALG_ECDSA, + TPM_ALG_SHA256); + AssertIntEQ(SendCertify(&ctx, signH, signH, 0), TPM_RC_SUCCESS); + + /* Reload the same public area on its own */ + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ReadPublic); + PutU32BE(gCmd + pos, signH); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pubSz = 2 + GetU16BE(gRsp + TPM2_HEADER_SIZE); + AssertIntLE(pubSz, (int)sizeof(pub)); + memcpy(pub, gRsp + TPM2_HEADER_SIZE, pubSz); + + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_LoadExternal); + PutU16BE(gCmd + pos, 0); pos += 2; /* inPrivate */ + memcpy(gCmd + pos, pub, pubSz); pos += pubSz; + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pubOnlyH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + + AssertIntEQ(SendCertify(&ctx, pubOnlyH, signH, 0), + TPM_RC_AUTH_UNAVAILABLE); +#ifndef FWTPM_NO_POLICY + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(sessH, 0); + AssertIntEQ(SendCertify(&ctx, pubOnlyH, signH, sessH), + TPM_RC_AUTH_UNAVAILABLE); + FlushHandle(&ctx, sessH); +#endif + +#ifndef FWTPM_NO_CONTEXT + /* A saved context does not gain a sensitive area */ + BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 14, TPM_CC_ContextSave); + PutU32BE(gCmd + 10, pubOnlyH); + FWTPM_ProcessCommand(&ctx, gCmd, 14, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + ctxSz = rspSize - TPM2_HEADER_SIZE; + AssertIntLE(ctxSz, (int)sizeof(saved)); + memcpy(saved, gRsp + TPM2_HEADER_SIZE, (size_t)ctxSz); + FlushHandle(&ctx, pubOnlyH); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ContextLoad); + memcpy(gCmd + pos, saved, (size_t)ctxSz); pos += ctxSz; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pubOnlyH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + AssertIntEQ(SendCertify(&ctx, pubOnlyH, signH, 0), + TPM_RC_AUTH_UNAVAILABLE); + + /* A context saved without the flag is public-only when it holds no + * private data */ + ctxSz = SaveContextWithoutFlag(&ctx, pubOnlyH, saved, (int)sizeof(saved), + 1); + FlushHandle(&ctx, pubOnlyH); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ContextLoad); + memcpy(gCmd + pos, saved, (size_t)ctxSz); pos += ctxSz; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pubOnlyH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + AssertIntEQ(SendCertify(&ctx, pubOnlyH, signH, 0), + TPM_RC_AUTH_UNAVAILABLE); + ctxSz = SaveContextWithoutFlag(&ctx, signH, saved, (int)sizeof(saved), + 0); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ContextLoad); + memcpy(gCmd + pos, saved, (size_t)ctxSz); pos += ctxSz; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + loadedH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + AssertIntEQ(SendCertify(&ctx, loadedH, signH, 0), TPM_RC_SUCCESS); + FlushHandle(&ctx, loadedH); +#endif + + FlushHandle(&ctx, pubOnlyH); + FlushHandle(&ctx, signH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Public-only object cannot authorize:", 0); +} +#endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION */ + +#ifndef FWTPM_NO_NV +/* Take the trailing public-only flag off the last journal record, a + * persistent object appended at recPos, and restart on that journal. Returns + * the object. */ +static FWTPM_Object* NvReloadPersistentWithoutFlag(FWTPM_CTX* ctx, + word32 recPos, UINT32 persH) +{ + FWTPM_NV_HAL hal = ctx->nvHal; + word32 writePos = ctx->nvWritePos; + word32 len = (word32)gMockNvStore[recPos + 2] | + ((word32)gMockNvStore[recPos + 3] << 8); + int i; + + AssertIntEQ(gMockNvStore[recPos], FWTPM_NV_TAG_PERSISTENT & 0xFF); + AssertIntEQ(gMockNvStore[recPos + 1], FWTPM_NV_TAG_PERSISTENT >> 8); + AssertIntEQ(recPos + 4 + len, writePos); + AssertIntEQ(gMockNvStore[writePos - 1], 0); + len--; + writePos--; + gMockNvStore[recPos + 2] = (byte)len; + gMockNvStore[recPos + 3] = (byte)(len >> 8); + gMockNvStore[8] = (byte)writePos; + gMockNvStore[9] = (byte)(writePos >> 8); + gMockNvStore[10] = (byte)(writePos >> 16); + gMockNvStore[11] = (byte)(writePos >> 24); + + wc_FreeRng(&ctx->rng); + memset(ctx, 0, sizeof(*ctx)); + AssertIntEQ(FWTPM_NV_SetHAL(ctx, &hal), 0); + AssertIntEQ(FWTPM_Init(ctx), 0); + for (i = 0; i < FWTPM_MAX_PERSISTENT; i++) { + if (ctx->persistent[i].used && ctx->persistent[i].handle == persH) { + return &ctx->persistent[i]; + } + } + return NULL; +} + +/* A persistent object record written before the public-only flag was kept + * holds a public-only object when it has no private data. */ +static void test_fwtpm_nv_persistent_without_public_only_flag(void) +{ + FWTPM_CTX ctx; + FWTPM_NV_HAL hal; + FWTPM_Object* obj; + const UINT32 persH = 0x81000A21; + UINT32 keyH; + word32 recPos; + int i, slot = -1, pos, rspSize = 0; + + memset(gMockNvStore, 0xFF, sizeof(gMockNvStore)); + gMockNvFailHeader = 0; + gMockNvFailAfterCompact = 0; + gMockNvCompactSeen = 0; + gMockNvCtx = NULL; + memset(&ctx, 0, sizeof(ctx)); + memset(&hal, 0, sizeof(hal)); + hal.read = mock_nv_read; + hal.write = mock_nv_write; + hal.erase = mock_nv_erase; + hal.maxSize = MOCK_NV_SIZE; + AssertIntEQ(FWTPM_NV_SetHAL(&ctx, &hal), 0); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); +#ifdef HAVE_ECC + keyH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); +#else + keyH = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); +#endif + AssertIntNE(keyH, 0); + + recPos = ctx.nvWritePos; + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_EvictControl); + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + pos, persH); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + obj = NvReloadPersistentWithoutFlag(&ctx, recPos, persH); + AssertNotNull(obj); + AssertIntGT(obj->privKeySize, 0); + AssertIntEQ(obj->publicOnly, 0); + + /* The same object as an earlier EvictControl stored it from a + * LoadExternal with no private area */ + for (i = 0; i < FWTPM_MAX_PERSISTENT; i++) { + if (&ctx.persistent[i] == obj) { + slot = i; + } + } + obj->privKeySize = 0; + recPos = ctx.nvWritePos; + AssertIntEQ(FWTPM_NV_SavePersistent(&ctx, slot), 0); + obj = NvReloadPersistentWithoutFlag(&ctx, recPos, persH); + AssertNotNull(obj); + AssertIntEQ(obj->privKeySize, 0); + AssertIntEQ(obj->publicOnly, 1); + + /* Saved again with the flag it stays public-only */ + AssertIntEQ(FWTPM_NV_Save(&ctx), 0); + wc_FreeRng(&ctx.rng); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(FWTPM_NV_SetHAL(&ctx, &hal), 0); + AssertIntEQ(FWTPM_Init(&ctx), 0); + AssertIntEQ(ctx.persistent[slot].handle, persH); + AssertIntEQ(ctx.persistent[slot].publicOnly, 1); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV persistent object without flag:", 0); +} +#endif /* !FWTPM_NO_NV */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -27668,6 +27949,12 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if !defined(FWTPM_NO_POLICY) && !defined(FWTPM_NO_NV) test_fwtpm_policy_session_needs_auth_policy(); #endif +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) + test_fwtpm_public_only_object_auth_unavailable(); +#endif +#ifndef FWTPM_NO_NV + test_fwtpm_nv_persistent_without_public_only_flag(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); diff --git a/wolftpm/fwtpm/fwtpm.h b/wolftpm/fwtpm/fwtpm.h index 1bc63a156..9fc7a8738 100644 --- a/wolftpm/fwtpm/fwtpm.h +++ b/wolftpm/fwtpm/fwtpm.h @@ -598,6 +598,7 @@ typedef struct FWTPM_Object { byte privKey[FWTPM_MAX_PRIVKEY_DER]; /* DER-encoded private key */ int privKeySize; TPM2B_NAME name; /* Object name = nameAlg || H(publicArea) */ + int publicOnly; /* Loaded without a sensitive area */ } FWTPM_Object; /* Hash sequence slot (for HashSequenceStart/SequenceUpdate/SequenceComplete) */ From 53d3121d4dc87d41ea363c4ccfbdf7de138a5515 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:40:15 -0800 Subject: [PATCH 037/124] F-16838 - Require TPM_RH_ENDORSEMENT as the fwTPM GetTime privacyAdminHandle --- src/fwtpm/fwtpm_command.c | 8 ++++-- tests/fwtpm_unit_tests.c | 54 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index c15954c4f..00491db9a 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -19048,8 +19048,12 @@ static TPM_RC FwCmd_GetTime(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { TPM2_Packet_ParseU32(cmd, &privHandle); TPM2_Packet_ParseU32(cmd, &signHandle); - (void)privHandle; - + /* privacyAdminHandle is a TPMI_RH_ENDORSEMENT (Part 3 Sec.18.7) */ + if (privHandle != TPM_RH_ENDORSEMENT) { + rc = TPM_RC_VALUE | TPM_RC_1; + } + } + if (rc == 0) { sigObj = FwFindObject(ctx, signHandle); if (sigObj == NULL) { rc = TPM_RC_HANDLE; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 0bb74195c..f831a8e51 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -27164,6 +27164,57 @@ static void test_fwtpm_nv_persistent_without_public_only_flag(void) } #endif /* !FWTPM_NO_NV */ +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) +static TPM_RC SendGetTime(FWTPM_CTX* ctx, UINT32 privacyAdminHandle, + UINT32 signHandle) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_GetTime); + int rspSize = 0; + int authStart; + + PutU32BE(gCmd + pos, privacyAdminHandle); pos += 4; + PutU32BE(gCmd + pos, signHandle); pos += 4; + authStart = pos; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + /* second entry in the same authorization area */ + PutU32BE(gCmd + pos, TPM_RS_PW); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; + gCmd[pos++] = 0; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU32BE(gCmd + authStart, (UINT32)(pos - authStart - 4)); + PutU16BE(gCmd + pos, 0); pos += 2; /* qualifyingData */ + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* inScheme */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* privacyAdminHandle is a TPMI_RH_ENDORSEMENT: only Endorsement + * Authorization releases the time attestation. */ +static void test_fwtpm_gettime_privacy_admin_handle(void) +{ + FWTPM_CTX ctx; + UINT32 signH; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + signH = CreateEccSignPrimaryScheme(&ctx, 0x00050472, TPM_ALG_ECDSA, + TPM_ALG_SHA256); + + AssertIntEQ(SendGetTime(&ctx, TPM_RH_OWNER, signH), + TPM_RC_VALUE | TPM_RC_1); + AssertIntEQ(SendGetTime(&ctx, TPM_RH_PLATFORM, signH), + TPM_RC_VALUE | TPM_RC_1); + AssertIntEQ(SendGetTime(&ctx, signH, signH), TPM_RC_VALUE | TPM_RC_1); + AssertIntEQ(SendGetTime(&ctx, TPM_RH_ENDORSEMENT, signH), + TPM_RC_SUCCESS); + + FlushHandle(&ctx, signH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("GetTime privacyAdminHandle:", 0); +} +#endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -27955,6 +28006,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifndef FWTPM_NO_NV test_fwtpm_nv_persistent_without_public_only_flag(); #endif +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) + test_fwtpm_gettime_privacy_admin_handle(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 132de1bc48aad589534f66099637ac895042dd4a Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:43:22 -0800 Subject: [PATCH 038/124] F-16134 - Return TPM_RC_TYPE for a non-storage fwTPM ActivateCredential keyHandle --- src/fwtpm/fwtpm_command.c | 4 +-- tests/fwtpm_unit_tests.c | 71 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 00491db9a..59ce80786 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -19599,7 +19599,7 @@ static TPM_RC FwCmd_ActivateCredential(FWTPM_CTX* ctx, TPM2_Packet* cmd, keyObj->pub.type != TPM_ALG_MLKEM && #endif keyObj->pub.type != TPM_ALG_ECC) { - rc = TPM_RC_KEY; + rc = TPM_RC_TYPE | TPM_RC_2; } } /* Part 3 Sec.24: keyHandle MUST be restricted decryption (Storage). An @@ -19608,7 +19608,7 @@ static TPM_RC FwCmd_ActivateCredential(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0 && (((keyObj->pub.objectAttributes & TPMA_OBJECT_restricted) == 0) || ((keyObj->pub.objectAttributes & TPMA_OBJECT_decrypt) == 0))) { - rc = TPM_RC_ATTRIBUTES; + rc = TPM_RC_TYPE | TPM_RC_2; } /* Credential protection derives the HMAC under the key's nameAlg and the * symmetric key at its declared AES-CFB size (Part 1 Sec.24). Reject a key diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index f831a8e51..f26a5d9b9 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -4313,7 +4313,7 @@ static void test_fwtpm_mlkem_activatecredential_unrestricted_rejected(void) secret, sizeof(secret)); AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0), TPM_RC_SUCCESS); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_TYPE | TPM_RC_2); FlushHandle(&ctx, ekHandle); FWTPM_Cleanup(&ctx); @@ -27215,6 +27215,71 @@ static void test_fwtpm_gettime_privacy_admin_handle(void) } #endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION */ +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) && \ + !defined(FWTPM_NO_CREDENTIAL) +/* keyHandle has to be a Storage Key: anything else is TPM_RC_TYPE for the + * second handle. */ +static void test_fwtpm_activate_credential_key_type(void) +{ + FWTPM_CTX ctx; + UINT32 signH, hmacH; + int i, pos, authStart, rspSize = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + signH = CreateEccSignPrimaryScheme(&ctx, 0x00050472, TPM_ALG_ECDSA, + TPM_ALG_SHA256); + + /* An HMAC key: fixedTPM|fixedParent|sensitiveDataOrigin|userWithAuth| + * noDA|sign */ + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_CreatePrimary); + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 4); pos += 2; /* inSensitive */ + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, 16); pos += 2; /* inPublic */ + PutU16BE(gCmd + pos, TPM_ALG_KEYEDHASH); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + pos, 0x00040472); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; /* authPolicy */ + PutU16BE(gCmd + pos, TPM_ALG_HMAC); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU16BE(gCmd + pos, 0); pos += 2; /* unique */ + PutU16BE(gCmd + pos, 0); pos += 2; /* outsideInfo */ + PutU32BE(gCmd + pos, 0); pos += 4; /* creationPCR */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + hmacH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + + /* A signing key is not a Storage Key, an HMAC key is not asymmetric */ + for (i = 0; i < 2; i++) { + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + TPM_CC_ActivateCredential); + PutU32BE(gCmd + pos, signH); pos += 4; /* activateHandle */ + PutU32BE(gCmd + pos, (i == 0) ? signH : hmacH); pos += 4; + authStart = pos; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + pos, TPM_RS_PW); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; + gCmd[pos++] = 0; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU32BE(gCmd + authStart, (UINT32)(pos - authStart - 4)); + PutU16BE(gCmd + pos, 0); pos += 2; /* credentialBlob */ + PutU16BE(gCmd + pos, 0); pos += 2; /* secret */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_TYPE | TPM_RC_2); + } + + FlushHandle(&ctx, hmacH); + FlushHandle(&ctx, signH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("ActivateCredential keyHandle type:", 0); +} +#endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION && !FWTPM_NO_CREDENTIAL */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -28009,6 +28074,10 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) test_fwtpm_gettime_privacy_admin_handle(); #endif +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) && \ + !defined(FWTPM_NO_CREDENTIAL) + test_fwtpm_activate_credential_key_type(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 4bb1928251560fec69113762e416fcfafbdf9701 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:43:54 -0800 Subject: [PATCH 039/124] F-16126 - Wipe the fwTPM command authorizations on the SPDM channel rejection paths --- src/fwtpm/fwtpm_command.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 59ce80786..8cfbe4113 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -23600,6 +23600,7 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, if (!FwSpdmSessionNames(ctx, &scReq, &scTpm)) { *rspSize = FwBuildErrorResponse(rspBuf, rspCap, TPM_ST_NO_SESSIONS, TPM_RC_CHANNEL); + TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); return TPM_RC_SUCCESS; } if ((pSess->checkReqKey || pSess->checkTpmKey) && @@ -23612,6 +23613,7 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, scHash, (word32)scHashSz) != 0)) { *rspSize = FwBuildErrorResponse(rspBuf, rspCap, TPM_ST_NO_SESSIONS, TPM_RC_CHANNEL_KEY); + TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); return TPM_RC_SUCCESS; } } From b4068b897fc1ade0a469a8533e172987099a466b Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:47:01 -0800 Subject: [PATCH 040/124] F-16125 - Wipe the fwTPM socket command buffer after dispatch --- src/fwtpm/fwtpm_io.c | 8 ++++ tests/fwtpm_unit_tests.c | 95 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) diff --git a/src/fwtpm/fwtpm_io.c b/src/fwtpm/fwtpm_io.c index c3d45e207..0334deedb 100644 --- a/src/fwtpm/fwtpm_io.c +++ b/src/fwtpm/fwtpm_io.c @@ -549,6 +549,7 @@ static int DispatchAndRespond(FWTPM_CTX* ctx, UINT32 cmdSize, int locality, /* Per wolfSPDM_RespHandleMessage's contract, an E_FRAMING * return MUST drop the connection - it indicates a plaintext * bypass attempt or other malformed inbound frame. */ + TPM2_ForceZero(ctx->cmdBuf, cmdSize); return -1; } if (procRc != WOLFSPDM_SUCCESS) { @@ -593,6 +594,10 @@ static int DispatchAndRespond(FWTPM_CTX* ctx, UINT32 cmdSize, int locality, } } + /* The command carries password authorizations in the clear, and the + * dispatcher decrypts session-encrypted parameters in place. */ + TPM2_ForceZero(ctx->cmdBuf, cmdSize); + if (isSwtpm) { /* swtpm protocol: raw TPM response only (no framing) */ rc = TransportSend(ctx, FWTPM_IO_TYPE_COMMAND, clientFd, @@ -664,6 +669,7 @@ static int HandleCommandConnection(FWTPM_CTX* ctx, SOCKET_T clientFd) rc = TransportRecv(ctx, FWTPM_IO_TYPE_COMMAND, clientFd, ctx->cmdBuf + 4, 6); if (rc != TPM_RC_SUCCESS) { + TPM2_ForceZero(ctx->cmdBuf, TPM2_HEADER_SIZE); return rc; } cmdSize = FwLoadU32BE(ctx->cmdBuf + 2); @@ -681,6 +687,7 @@ static int HandleCommandConnection(FWTPM_CTX* ctx, SOCKET_T clientFd) rc = TransportRecv(ctx, FWTPM_IO_TYPE_COMMAND, clientFd, ctx->cmdBuf + TPM2_HEADER_SIZE, (int)remaining); if (rc != TPM_RC_SUCCESS) { + TPM2_ForceZero(ctx->cmdBuf, cmdSize); return rc; } } @@ -744,6 +751,7 @@ static int HandleCommandConnection(FWTPM_CTX* ctx, SOCKET_T clientFd) rc = TransportRecv(ctx, FWTPM_IO_TYPE_COMMAND, clientFd, ctx->cmdBuf, (int)cmdSize); if (rc != TPM_RC_SUCCESS) { + TPM2_ForceZero(ctx->cmdBuf, cmdSize); return rc; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index f26a5d9b9..4be7cad72 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -27280,6 +27280,98 @@ static void test_fwtpm_activate_credential_key_type(void) } #endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION && !FWTPM_NO_CREDENTIAL */ +#if defined(WOLFTPM_FWTPM_UNIT_TEST) && !defined(WOLFTPM_FWTPM_TIS) +typedef struct CmdWipeIoCtx { + FWTPM_CTX* fwtpm; + byte input[16]; + int inputSz; + int inputPos; + int waitCount; +} CmdWipeIoCtx; + +static int cmd_wipe_io_send(void* userCtx, int type, const void* buf, int sz) +{ + (void)userCtx; + (void)type; + (void)buf; + (void)sz; + return TPM_RC_SUCCESS; +} + +static int cmd_wipe_io_recv(void* userCtx, int type, void* buf, int sz) +{ + CmdWipeIoCtx* io = (CmdWipeIoCtx*)userCtx; + + (void)type; + if (sz < 0) + return TPM_RC_FAILURE; + if (io->inputPos + sz > io->inputSz) { + /* a connection that drops part way through a read */ + XMEMCPY(buf, io->input + io->inputPos, + (size_t)(io->inputSz - io->inputPos)); + io->inputPos = io->inputSz; + return TPM_RC_FAILURE; + } + XMEMCPY(buf, io->input + io->inputPos, (size_t)sz); + io->inputPos += sz; + return TPM_RC_SUCCESS; +} + +static int cmd_wipe_io_wait(void* userCtx, int timeoutMs) +{ + CmdWipeIoCtx* io = (CmdWipeIoCtx*)userCtx; + + (void)timeoutMs; + if (++io->waitCount == 2) { + io->fwtpm->running = 0; + return 0; + } + return FWTPM_IO_READY_COMMAND; +} + +/* The socket transport dispatches from ctx->cmdBuf, where password + * authorizations and decrypted parameters would otherwise outlive the + * command. */ +static void test_fwtpm_io_command_buffer_wiped(void) +{ + FWTPM_CTX ctx; + FWTPM_IO_HAL hal; + CmdWipeIoCtx io; + int i, truncated; + + for (truncated = 0; truncated < 2; truncated++) { + XMEMSET(&ctx, 0, sizeof(ctx)); + XMEMSET(&hal, 0, sizeof(hal)); + XMEMSET(&io, 0, sizeof(io)); + io.fwtpm = &ctx; + /* raw TPM2_GetRandom: refused before Startup, but still dispatched */ + io.inputSz = BuildCmdHeader(io.input, TPM_ST_NO_SESSIONS, 12, + TPM_CC_GetRandom); + PutU16BE(io.input + io.inputSz, 8); io.inputSz += 2; + if (truncated) { + /* the connection drops before the last octet arrives */ + io.inputSz--; + } + hal.send = cmd_wipe_io_send; + hal.recv = cmd_wipe_io_recv; + hal.wait = cmd_wipe_io_wait; + hal.ctx = &io; + + AssertIntEQ(FWTPM_IO_SetHAL(&ctx, &hal), TPM_RC_SUCCESS); + AssertIntEQ(FWTPM_Init(&ctx), TPM_RC_SUCCESS); + AssertIntEQ(FWTPM_IO_Init(&ctx), TPM_RC_SUCCESS); + AssertIntEQ(FWTPM_IO_ServerLoop(&ctx), TPM_RC_SUCCESS); + AssertIntEQ(io.inputPos, io.inputSz); + for (i = 0; i < io.inputSz; i++) { + AssertIntEQ(ctx.cmdBuf[i], 0); + } + FWTPM_IO_Cleanup(&ctx); + AssertIntEQ(FWTPM_Cleanup(&ctx), TPM_RC_SUCCESS); + } + fwtpm_pass("Socket command buffer wiped:", 0); +} +#endif /* WOLFTPM_FWTPM_UNIT_TEST && !WOLFTPM_FWTPM_TIS */ + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -28078,6 +28170,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) !defined(FWTPM_NO_CREDENTIAL) test_fwtpm_activate_credential_key_type(); #endif +#if defined(WOLFTPM_FWTPM_UNIT_TEST) && !defined(WOLFTPM_FWTPM_TIS) + test_fwtpm_io_command_buffer_wiped(); +#endif /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 23ff7af5d437fcd8d511624fdbebe3273863d699 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:53:47 -0800 Subject: [PATCH 041/124] F-17150 - Report hierarchy policies and the PCR policy and auth properties in fwTPM GetCapability --- src/fwtpm/fwtpm_command.c | 64 +++++++++++++++++++++++- tests/fwtpm_unit_tests.c | 101 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 164 insertions(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 8cfbe4113..870289aad 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -1772,6 +1772,7 @@ static int FwPcrLocalityAllowed(int pcrIndex, int locality, int isReset); #define FW_PCR_KIND_RESET 1 /* reset allowed at loc */ #define FW_PCR_KIND_SAVE 2 /* saved across power cycles (PCR 0-15) */ #define FW_PCR_KIND_DRTM_RESET 3 /* reset allowed at locality 4 */ +#define FW_PCR_KIND_AUTH 4 /* takes a policy or authValue (every PCR) */ /* Overwrite a big-endian UINT32 already appended at buf[pos]. Used to * back-patch a TPML count with the number of entries actually emitted, so a @@ -1998,6 +1999,10 @@ static TPM_RC FwCmd_GetCapability(FWTPM_CTX* ctx, TPM2_Packet* cmd, return TPM_RC_VALUE; } #endif + if (capability == TPM_CAP_AUTH_POLICIES && + (property & HR_RANGE_MASK) != HR_PERMANENT) { + return TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; + } paramStart = FwRspParamsBegin(rsp, cmdTag, ¶mSzPos); @@ -2572,7 +2577,9 @@ static TPM_RC FwCmd_GetCapability(FWTPM_CTX* ctx, TPM2_Packet* cmd, { TPM_PT_PCR_RESET_L3, FW_PCR_KIND_RESET, 3 }, { TPM_PT_PCR_EXTEND_L4, FW_PCR_KIND_EXTEND, 4 }, { TPM_PT_PCR_RESET_L4, FW_PCR_KIND_RESET, 4 }, - { TPM_PT_PCR_DRTM_RESET, FW_PCR_KIND_DRTM_RESET, 4 } + { TPM_PT_PCR_DRTM_RESET, FW_PCR_KIND_DRTM_RESET, 4 }, + { TPM_PT_PCR_POLICY, FW_PCR_KIND_AUTH, 0 }, + { TPM_PT_PCR_AUTH, FW_PCR_KIND_AUTH, 0 } }; int totalProps = (int)(sizeof(pcrProps) / sizeof(pcrProps[0])); int startIdx = 0; @@ -2607,6 +2614,8 @@ static TPM_RC FwCmd_GetCapability(FWTPM_CTX* ctx, TPM2_Packet* cmd, set = (p < FWTPM_PCR_SAVE_COUNT); else if (kind == FW_PCR_KIND_DRTM_RESET) set = FwPcrLocalityAllowed(p, WOLFTPM_LOCALITY_MAX, 1); + else if (kind == FW_PCR_KIND_AUTH) + set = 1; else set = FwPcrLocalityAllowed(p, (int)loc, (int)kind); if (set) @@ -2719,6 +2728,59 @@ static TPM_RC FwCmd_GetCapability(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_AppendU32(rsp, 0); break; + /* TPML_TAGGED_POLICY: the hierarchy policies in handle order. One + * that is not set is reported as TPM_ALG_NULL with no digest. */ + case TPM_CAP_AUTH_POLICIES: { + static const UINT32 policyHandles[] = { + TPM_RH_OWNER, TPM_RH_LOCKOUT, TPM_RH_ENDORSEMENT, + TPM_RH_PLATFORM + }; + TPM2B_DIGEST* pol; + TPMI_ALG_HASH polAlg; + int countPos = rsp->pos; + UINT32 emitted = 0; + int h; + + TPM2_Packet_AppendU32(rsp, 0); /* back-patched below */ + for (h = 0; h < (int)(sizeof(policyHandles) / + sizeof(policyHandles[0])); h++) { + if (policyHandles[h] < property) { + continue; + } + if (emitted >= propertyCount) { + FwPatchMoreData(rsp, moreDataPos, 1); + break; + } + if (policyHandles[h] == TPM_RH_OWNER) { + pol = &ctx->ownerPolicy; + polAlg = ctx->ownerPolicyAlg; + } + else if (policyHandles[h] == TPM_RH_LOCKOUT) { + pol = &ctx->lockoutPolicy; + polAlg = ctx->lockoutPolicyAlg; + } + else if (policyHandles[h] == TPM_RH_ENDORSEMENT) { + pol = &ctx->endorsementPolicy; + polAlg = ctx->endorsementPolicyAlg; + } + else { + pol = &ctx->platformPolicy; + polAlg = ctx->platformPolicyAlg; + } + TPM2_Packet_AppendU32(rsp, policyHandles[h]); + if (pol->size == 0) { + TPM2_Packet_AppendU16(rsp, TPM_ALG_NULL); + } + else { + TPM2_Packet_AppendU16(rsp, polAlg); + TPM2_Packet_AppendBytes(rsp, pol->buffer, pol->size); + } + emitted++; + } + FwPatchU32BE(rsp, countPos, emitted); + break; + } + /* Settable feature configuration written by TPM2_SetCapability. * TPML_TAGGED_CONFIG: count then configuration/enable/lock triples, * starting at the requested TPM_PT_CONFIG and capped by diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 4be7cad72..7a20ac2c7 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -27372,6 +27372,106 @@ static void test_fwtpm_io_command_buffer_wiped(void) } #endif /* WOLFTPM_FWTPM_UNIT_TEST && !WOLFTPM_FWTPM_TIS */ +/* GetCapability(capability, property, count); returns the response code and + * leaves the reply in gRsp: moreData(1) | capability(4) | count(4) | data */ +static TPM_RC SendGetCapability(FWTPM_CTX* ctx, UINT32 capability, + UINT32 property, UINT32 count) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_GetCapability); + int rspSize = 0; + + PutU32BE(gCmd + pos, capability); pos += 4; + PutU32BE(gCmd + pos, property); pos += 4; + PutU32BE(gCmd + pos, count); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* TPM_CAP_AUTH_POLICIES lists the hierarchy policies in handle order, with + * TPM_ALG_NULL and no digest for one that is not set. TPM_PT_PCR_POLICY and + * TPM_PT_PCR_AUTH report the PCRs that take a policy or an authValue. */ +static void test_fwtpm_getcap_auth_policies(void) +{ + FWTPM_CTX ctx; + static const UINT32 handles[] = { + TPM_RH_OWNER, TPM_RH_LOCKOUT, TPM_RH_ENDORSEMENT, TPM_RH_PLATFORM + }; + const TPM2B_DIGEST* pol[4]; + const int dataPos = TPM2_HEADER_SIZE + 1 + 4 + 4; + int pos, i, p; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(SendPlatformSetPolicy(&ctx, 0, 32), TPM_RC_SUCCESS); + pol[0] = &ctx.ownerPolicy; + pol[1] = &ctx.lockoutPolicy; + pol[2] = &ctx.endorsementPolicy; + pol[3] = &ctx.platformPolicy; + + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_AUTH_POLICIES, + PERMANENT_FIRST, 8), TPM_RC_SUCCESS); + AssertIntEQ(gRsp[TPM2_HEADER_SIZE], 0); + AssertIntEQ(GetU32BE(gRsp + TPM2_HEADER_SIZE + 1), + TPM_CAP_AUTH_POLICIES); + AssertIntEQ(GetU32BE(gRsp + TPM2_HEADER_SIZE + 5), 4); + pos = dataPos; + for (i = 0; i < 4; i++) { + AssertIntEQ(GetU32BE(gRsp + pos), handles[i]); pos += 4; + if (pol[i]->size == 0) { + AssertIntEQ(GetU16BE(gRsp + pos), TPM_ALG_NULL); pos += 2; + } + else { + AssertIntEQ(TPM2_GetHashDigestSize(GetU16BE(gRsp + pos)), + pol[i]->size); + pos += 2; + AssertIntEQ(memcmp(gRsp + pos, pol[i]->buffer, pol[i]->size), 0); + pos += pol[i]->size; + } + } + AssertIntEQ(GetU32BE(gRsp + 2), pos); + AssertIntEQ(ctx.platformPolicy.size, 32); + + /* Paging starts at the first handle at or after property */ + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_AUTH_POLICIES, + TPM_RH_LOCKOUT, 1), TPM_RC_SUCCESS); + AssertIntEQ(gRsp[TPM2_HEADER_SIZE], 1); + AssertIntEQ(GetU32BE(gRsp + TPM2_HEADER_SIZE + 5), 1); + AssertIntEQ(GetU32BE(gRsp + dataPos), TPM_RH_LOCKOUT); + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_AUTH_POLICIES, + TPM_RH_PLATFORM, 4), TPM_RC_SUCCESS); + AssertIntEQ(gRsp[TPM2_HEADER_SIZE], 0); + AssertIntEQ(GetU32BE(gRsp + TPM2_HEADER_SIZE + 5), 1); + AssertIntEQ(GetU32BE(gRsp + dataPos), TPM_RH_PLATFORM); + AssertIntEQ(GetU16BE(gRsp + dataPos + 4), TPM_ALG_SHA256); + + /* property has to be a permanent handle */ + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_AUTH_POLICIES, + TRANSIENT_FIRST, 4), TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendPlatformSetPolicy(&ctx, 0, 0), TPM_RC_SUCCESS); + + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_PCR_PROPERTIES, + TPM_PT_PCR_POLICY, 4), TPM_RC_SUCCESS); + AssertIntEQ(gRsp[TPM2_HEADER_SIZE], 0); + AssertIntEQ(GetU32BE(gRsp + TPM2_HEADER_SIZE + 5), 2); + pos = dataPos; + for (i = 0; i < 2; i++) { + AssertIntEQ(GetU32BE(gRsp + pos), (i == 0) ? TPM_PT_PCR_POLICY : + TPM_PT_PCR_AUTH); + pos += 4; + AssertIntEQ(gRsp[pos], PCR_SELECT_MAX); pos++; + for (p = 0; p < PCR_SELECT_MAX * 8; p++) { + AssertIntEQ((gRsp[pos + p / 8] >> (p % 8)) & 1, + p < IMPLEMENTATION_PCR); + } + pos += PCR_SELECT_MAX; + } + + FWTPM_Cleanup(&ctx); + fwtpm_pass("GetCapability auth policies:", 0); +} + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -28173,6 +28273,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if defined(WOLFTPM_FWTPM_UNIT_TEST) && !defined(WOLFTPM_FWTPM_TIS) test_fwtpm_io_command_buffer_wiped(); #endif + test_fwtpm_getcap_auth_policies(); /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From e58b2c472b70148d149a994404e86669ae4a3b07 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 07:57:03 -0800 Subject: [PATCH 042/124] F-18075 - Validate the fwTPM GetCapability capability and the TPM_CAP_PCRS property --- src/fwtpm/fwtpm_command.c | 11 +++++++++++ tests/fwtpm_unit_tests.c | 30 ++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 870289aad..39626dcd0 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -2003,6 +2003,11 @@ static TPM_RC FwCmd_GetCapability(FWTPM_CTX* ctx, TPM2_Packet* cmd, (property & HR_RANGE_MASK) != HR_PERMANENT) { return TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; } + /* TPM_CAP_PCRS always reports every bank, so property has to be zero + * (Part 3 Sec.30.2) */ + if (capability == TPM_CAP_PCRS && property != 0) { + return TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; + } paramStart = FwRspParamsBegin(rsp, cmdTag, ¶mSzPos); @@ -2832,6 +2837,12 @@ static TPM_RC FwCmd_GetCapability(FWTPM_CTX* ctx, TPM2_Packet* cmd, #endif /* WOLFTPM_SPDM */ default: + /* A TPM_CAP with nothing to report here is an empty list; a + * value outside TPM_CAP does not unmarshal (Part 2 Sec.6.12) + * and there are no vendor properties. */ + if (capability > TPM_CAP_LAST) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_1; + } TPM2_Packet_AppendU32(rsp, 0); break; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 7a20ac2c7..80bbc0b7a 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -27472,6 +27472,35 @@ static void test_fwtpm_getcap_auth_policies(void) fwtpm_pass("GetCapability auth policies:", 0); } +/* TPM_CAP_PCRS takes no property, and a capability outside TPM_CAP does not + * unmarshal. */ +static void test_fwtpm_getcap_input_validation(void) +{ + FWTPM_CTX ctx; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_PCRS, 0, HASH_COUNT), + TPM_RC_SUCCESS); + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_PCRS, 1, HASH_COUNT), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_PCRS, TPM_ALG_SHA256, + HASH_COUNT), TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_LAST + 1, 0, 1), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_VENDOR_PROPERTY - 1, 0, 1), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendGetCapability(&ctx, TPM_CAP_VENDOR_PROPERTY, 0, 1), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendGetCapability(&ctx, 0xFFFFFFFFu, 0, 1), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_1); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("GetCapability input validation:", 0); +} + #ifndef NO_MAIN_DRIVER int main(int argc, char *argv[]) #else @@ -28274,6 +28303,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_io_command_buffer_wiped(); #endif test_fwtpm_getcap_auth_policies(); + test_fwtpm_getcap_input_validation(); /* Destructive tests last (Clear changes state) */ test_fwtpm_change_eps(); From 2fc4fe46407cbb642ab8de7a31a9c55ae0cfc599 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 08:15:09 -0800 Subject: [PATCH 043/124] F-16184 - Keep the allocation failure in fwTPM Duplicate and Rewrap before skipping the auth area --- src/fwtpm/fwtpm_command.c | 4 +- tests/fwtpm_unit_tests.c | 90 +++++++++++++++++++++++++++++++++++++++ wolftpm/fwtpm/fwtpm.h | 27 +++++++++--- 3 files changed, 113 insertions(+), 8 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 39626dcd0..72ecbe48d 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -9366,7 +9366,7 @@ static TPM_RC FwCmd_Duplicate(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseU32(cmd, &objectHandle); TPM2_Packet_ParseU32(cmd, &newParentHandle); - if (cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); + if (rc == 0 && cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); /* Parse encryptionKeyIn (TPM2B) - save for inner wrapping */ TPM2_Packet_ParseU16(cmd, &encKeyInSz); @@ -9830,7 +9830,7 @@ static TPM_RC FwCmd_Rewrap(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Parse handles */ TPM2_Packet_ParseU32(cmd, &oldParentH); TPM2_Packet_ParseU32(cmd, &newParentH); - if (cmdTag == TPM_ST_SESSIONS) + if (rc == 0 && cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); /* Parse inDuplicate (TPM2B) */ diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 80bbc0b7a..c68d58613 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -657,6 +657,11 @@ static void fwtpm_test_fail_next_alloc(void) gFwTpmAllocFailCount = 1; } +static void fwtpm_test_fail_alloc_at(int n) +{ + gFwTpmAllocFailCount = n; +} + static void test_fwtpm_crypto_alloc_failure(void) { byte hash[WC_SHA256_DIGEST_SIZE]; @@ -18089,6 +18094,88 @@ static void test_fwtpm_duplicate_needs_command_code(void) FWTPM_Cleanup(&ctx); fwtpm_pass("Duplicate needs PolicyCommandCode:", 0); } + +#if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) +/* A failed small-stack allocation in Duplicate or Rewrap is reported as + * TPM_RC_MEMORY and the unallocated buffers are not used. */ +static void test_fwtpm_duplicate_rewrap_alloc_failure(void) +{ + FWTPM_CTX ctx; + FWTPM_Object* obj = NULL; + FWTPM_Session* sess = NULL; + UINT32 keyH, sessH; + int i, n, pos, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); +#ifdef HAVE_ECC + keyH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); +#else + keyH = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); +#endif + AssertIntNE(keyH, 0); + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(sessH, 0); + + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_PolicyCommandCode); + PutU32BE(gCmd + pos, sessH); pos += 4; + PutU32BE(gCmd + pos, TPM_CC_Duplicate); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + for (i = 0; i < FWTPM_MAX_OBJECTS; i++) { + if (ctx.objects[i].used && ctx.objects[i].handle == keyH) { + obj = &ctx.objects[i]; + } + } + for (i = 0; i < FWTPM_MAX_SESSIONS; i++) { + if (ctx.sessions[i].used && ctx.sessions[i].handle == sessH) { + sess = &ctx.sessions[i]; + } + } + AssertNotNull(obj); + AssertNotNull(sess); + obj->pub.objectAttributes &= + ~(TPMA_OBJECT_fixedTPM | TPMA_OBJECT_fixedParent); + XMEMCPY(&obj->pub.authPolicy, &sess->policyDigest, + sizeof(obj->pub.authPolicy)); + + /* encSeedBuf, then outPrivate */ + for (n = 1; n <= 2; n++) { + fwtpm_test_fail_alloc_at(n); + AssertIntEQ(SendDuplicateToNullCmd(&ctx, keyH, sessH, TPM_ALG_NULL), + TPM_RC_MEMORY); + AssertIntEQ(gFwTpmAllocFailCount, 0); + } + AssertIntEQ(SendDuplicateToNullCmd(&ctx, keyH, sessH, TPM_ALG_NULL), + TPM_RC_SUCCESS); + + /* dupBuf, symSeedBuf, plainSens, encSeedBuf */ + for (n = 1; n <= 4; n++) { + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Rewrap); + PutU32BE(gCmd + pos, keyH); pos += 4; /* oldParent */ + PutU32BE(gCmd + pos, keyH); pos += 4; /* newParent */ + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 8); pos += 2; /* inDuplicate */ + memset(gCmd + pos, 0x5A, 8); pos += 8; + PutU16BE(gCmd + pos, 0); pos += 2; /* name */ + PutU16BE(gCmd + pos, 0); pos += 2; /* inSymSeed */ + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + fwtpm_test_fail_alloc_at(n); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_MEMORY); + AssertIntEQ(gFwTpmAllocFailCount, 0); + } + + FlushHandle(&ctx, sessH); + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Duplicate/Rewrap allocation failure:", 0); +} +#endif /* WOLFTPM_FWTPM_UNIT_TEST && WOLFTPM_SMALL_STACK */ #endif /* !FWTPM_NO_KEY_MIGRATION && !FWTPM_NO_POLICY */ /* ================================================================== */ @@ -28062,6 +28149,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifndef FWTPM_NO_POLICY test_fwtpm_duplicate_encrypted_needs_new_parent(); test_fwtpm_duplicate_needs_command_code(); +#if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) + test_fwtpm_duplicate_rewrap_alloc_failure(); +#endif #endif #endif /* !FWTPM_NO_KEY_MIGRATION */ test_fwtpm_evict_control(); diff --git a/wolftpm/fwtpm/fwtpm.h b/wolftpm/fwtpm/fwtpm.h index 9fc7a8738..570202387 100644 --- a/wolftpm/fwtpm/fwtpm.h +++ b/wolftpm/fwtpm/fwtpm.h @@ -531,8 +531,13 @@ * the memset and leaking stack data into the output. */ #define FWTPM_CALLOC_VAR(name, type) \ do { \ - (name) = (type*)XMALLOC(sizeof(type), NULL, \ - DYNAMIC_TYPE_TMP_BUFFER); \ + if (FWTPM_TEST_ALLOC_FAIL()) { \ + (name) = NULL; \ + } \ + else { \ + (name) = (type*)XMALLOC(sizeof(type), NULL, \ + DYNAMIC_TYPE_TMP_BUFFER); \ + } \ if ((name) == NULL) { rc = TPM_RC_MEMORY; } \ else { XMEMSET((name), 0, sizeof(type)); } \ } while (0) @@ -547,8 +552,13 @@ do { \ typedef char _fwtpm_bufchk_##name[((sz) > 8) ? 1 : -1]; \ (void)sizeof(_fwtpm_bufchk_##name); \ - (name) = (byte*)XMALLOC((sz), NULL, \ - DYNAMIC_TYPE_TMP_BUFFER); \ + if (FWTPM_TEST_ALLOC_FAIL()) { \ + (name) = NULL; \ + } \ + else { \ + (name) = (byte*)XMALLOC((sz), NULL, \ + DYNAMIC_TYPE_TMP_BUFFER); \ + } \ if ((name) == NULL) { rc = TPM_RC_MEMORY; } \ } while (0) /* Allocate AND zero-initialize byte buffer. */ @@ -556,8 +566,13 @@ do { \ typedef char _fwtpm_bufchk_##name[((sz) > 8) ? 1 : -1]; \ (void)sizeof(_fwtpm_bufchk_##name); \ - (name) = (byte*)XMALLOC((sz), NULL, \ - DYNAMIC_TYPE_TMP_BUFFER); \ + if (FWTPM_TEST_ALLOC_FAIL()) { \ + (name) = NULL; \ + } \ + else { \ + (name) = (byte*)XMALLOC((sz), NULL, \ + DYNAMIC_TYPE_TMP_BUFFER); \ + } \ if ((name) == NULL) { rc = TPM_RC_MEMORY; } \ else { XMEMSET((name), 0, (sz)); } \ } while (0) From 62cd64e73141085170646a8e437d88cd1a570ffb Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 08:11:07 -0800 Subject: [PATCH 044/124] F-16185 - Keep the allocation failure in fwTPM policy, NV_Extend and ZGen_2Phase handlers before skipping the auth area --- src/fwtpm/fwtpm_command.c | 22 +++++++------- tests/fwtpm_unit_tests.c | 64 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 11 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 72ecbe48d..fa79184ff 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -13059,7 +13059,7 @@ static TPM_RC FwCmd_StartAuthSession(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* A session-tagged command with no auth handles still carries an auth * area between the handles and parameters; skip it before parsing */ - if (cmdTag == TPM_ST_SESSIONS) { + if (rc == 0 && cmdTag == TPM_ST_SESSIONS) { rc = FwSkipAuthArea(cmd, cmdSize); } @@ -13477,7 +13477,7 @@ static TPM_RC FwCmd_PolicyPCR(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseU32(cmd, &sessHandle); /* Skip auth area if present */ - if (cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); + if (rc == 0 && cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); /* Parse pcrDigest (TPM2B) */ if (rc == 0) { @@ -13924,7 +13924,7 @@ static TPM_RC FwCmd_PolicyOR(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_ALLOC_VAR(hashCtx, wc_HashAlg); TPM2_Packet_ParseU32(cmd, &sessHandle); - if (cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); + if (rc == 0 && cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); if (rc == 0) { TPM2_Packet_ParseU32(cmd, &digestCount); @@ -15054,7 +15054,7 @@ static TPM_RC FwCmd_PolicyNV(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseU32(cmd, &sessHandle); /* Skip auth area */ - if (cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); + if (rc == 0 && cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); /* Parse operandB (TPM2B) */ TPM2_Packet_ParseU16(cmd, &operandBSz); @@ -16628,7 +16628,7 @@ static TPM_RC FwCmd_PolicyAuthorizeNV(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseU32(cmd, &authHandle); TPM2_Packet_ParseU32(cmd, &nvHandle); TPM2_Packet_ParseU32(cmd, &sessHandle); - if (cmdTag == TPM_ST_SESSIONS) + if (rc == 0 && cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); nv = FwFindNvIndex(ctx, nvHandle); @@ -16698,10 +16698,6 @@ static TPM_RC FwCmd_PolicyAuthorizeNV(FWTPM_CTX* ctx, TPM2_Packet* cmd, printf("fwTPM: PolicyAuthorizeNV(auth=0x%x, nv=0x%x, sess=0x%x)\n", authHandle, nvHandle, sessHandle); #endif - /* Step 1: Reset policyDigest to zero */ - XMEMSET(sess->policyDigest.buffer, 0, dSz); - sess->policyDigest.size = (UINT16)dSz; - /* Compute nvIndexName */ FwComputeNvName(nv, nvName, &nvNameSz); @@ -16714,6 +16710,10 @@ static TPM_RC FwCmd_PolicyAuthorizeNV(FWTPM_CTX* ctx, TPM2_Packet* cmd, hashInit = 1; } if (rc == 0) { + /* Step 1: Reset policyDigest to zero */ + XMEMSET(sess->policyDigest.buffer, 0, dSz); + sess->policyDigest.size = (UINT16)dSz; + wc_HashUpdate(hashCtx, wcHash, sess->policyDigest.buffer, sess->policyDigest.size); FwStoreU32BE(ccBuf, cc); @@ -17540,7 +17540,7 @@ static TPM_RC FwCmd_NV_Extend(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseU32(cmd, &authHandle); TPM2_Packet_ParseU32(cmd, &nvHandle); - if (cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); + if (rc == 0 && cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); nv = FwFindNvIndex(ctx, nvHandle); if (nv == NULL) { @@ -20042,7 +20042,7 @@ static TPM_RC FwCmd_ZGen_2Phase(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Parse keyA handle */ TPM2_Packet_ParseU32(cmd, &keyAHandle); - if (cmdTag == TPM_ST_SESSIONS) + if (rc == 0 && cmdTag == TPM_ST_SESSIONS) rc = FwSkipAuthArea(cmd, cmdSize); keyA = FwFindObject(ctx, keyAHandle); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index c68d58613..25d9889da 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -12728,6 +12728,67 @@ static void test_fwtpm_policy_nv_trial_no_validation(void) fwtpm_pass("Policy NV trial session:", 0); } +#if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) +/* A failed small-stack allocation is reported as TPM_RC_MEMORY and leaves + * the session policyDigest as it was. */ +static void test_fwtpm_policy_nv_alloc_failure(void) +{ + FWTPM_CTX ctx; + FWTPM_Session* sess = NULL; + UINT32 nvIdx = 0x01500A0A; + UINT32 sessH; + byte before[WC_SHA256_DIGEST_SIZE]; + int i, cmdSz, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, WC_SHA256_DIGEST_SIZE, + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA | + ((UINT32)TPM_NT_EXTEND << 4)); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + fwtpm_test_fail_next_alloc(); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Extend, nvIdx, NULL, 8, 0), + TPM_RC_MEMORY); + AssertIntEQ(gFwTpmAllocFailCount, 0); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Extend, nvIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + + sessH = StartSessionHelper(&ctx, TPM_SE_TRIAL); + AssertIntNE(sessH, 0); + for (i = 0; i < FWTPM_MAX_SESSIONS; i++) { + if (ctx.sessions[i].used && ctx.sessions[i].handle == sessH) { + sess = &ctx.sessions[i]; + } + } + AssertNotNull(sess); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyNV, nvIdx, sessH, 2, 0), + TPM_RC_SUCCESS); + AssertIntEQ(sess->policyDigest.size, WC_SHA256_DIGEST_SIZE); + memcpy(before, sess->policyDigest.buffer, sizeof(before)); + + fwtpm_test_fail_next_alloc(); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyNV, nvIdx, sessH, 2, 0), + TPM_RC_MEMORY); + AssertIntEQ(gFwTpmAllocFailCount, 0); + fwtpm_test_fail_next_alloc(); + AssertIntEQ(SendPolicyNvCmd(&ctx, TPM_CC_PolicyAuthorizeNV, nvIdx, sessH, + 0, 0), TPM_RC_MEMORY); + AssertIntEQ(gFwTpmAllocFailCount, 0); + AssertIntEQ(memcmp(before, sess->policyDigest.buffer, sizeof(before)), + 0); + FlushHandle(&ctx, sessH); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Policy NV allocation failure:", 0); +} +#endif /* WOLFTPM_FWTPM_UNIT_TEST && WOLFTPM_SMALL_STACK */ + /* PolicyAuthorizeNV reads a TPMT_HA from the index: a hash algorithm that * must be the session's, then the approved digest, with any trailing octets * ignored (Part 3 Sec.23.22). */ @@ -28282,6 +28343,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_policyauthorizenv_owner_read_denied(); test_fwtpm_policy_nv_read_locked(); test_fwtpm_policy_nv_trial_no_validation(); +#if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) + test_fwtpm_policy_nv_alloc_failure(); +#endif test_fwtpm_policy_authorize_nv_tpmt_ha(); test_fwtpm_policy_locality_enforced(); test_fwtpm_policy_cphash_enforced(); From c5ba2f610d9bc8b4e37455288b18cb149ad5dee6 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 08:31:33 -0800 Subject: [PATCH 045/124] F-17155 - Reject a fwTPM StartAuthSession salt without a tpmKey and an oversized RSA salt --- src/fwtpm/fwtpm_command.c | 16 +++++++- tests/fwtpm_unit_tests.c | 83 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+), 2 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index fa79184ff..cefba1739 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -13174,6 +13174,12 @@ static TPM_RC FwCmd_StartAuthSession(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + /* encryptedSalt is an Empty Buffer without a tpmKey (Part 3 + * Sec.11.1.1) */ + if (rc == 0 && tpmKey == TPM_RH_NULL && encSaltSize != 0) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; + } + /* If tpmKey is specified, decrypt the encrypted salt */ if (rc == 0 && tpmKey != TPM_RH_NULL) { FWTPM_Object* keyObj = FwFindObject(ctx, tpmKey); @@ -13189,7 +13195,7 @@ static TPM_RC FwCmd_StartAuthSession(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_ATTRIBUTES; } else if (encSaltSize == 0) { - rc = TPM_RC_VALUE; + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; } if (rc == 0) { rc = FwDecryptSeed(ctx, keyObj, @@ -13197,9 +13203,15 @@ static TPM_RC FwCmd_StartAuthSession(FWTPM_CTX* ctx, TPM2_Packet* cmd, (const byte*)"SECRET", 7, "SECRET", salt, (int)sizeof(salt), &saltSize); if (rc != 0 && rc != TPM_RC_KEY) { - rc = TPM_RC_VALUE; + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; } } + /* An RSA salt is no larger than the digest of the tpmKey nameAlg + * (Part 3 Sec.11.1.1) */ + if (rc == 0 && keyObj->pub.type == TPM_ALG_RSA && + saltSize > TPM2_GetHashDigestSize(keyObj->pub.nameAlg)) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; + } } /* sessionKey = KDFa(authHash, bindAuth || salt, "ATH", ...) per TPM 2.0 diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 25d9889da..5f2b209fc 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -22854,6 +22854,88 @@ static void test_fwtpm_rsa_seed_hashes(void) fwtpm_pass("RSA seed encryption for each nameAlg:", 0); } +static TPM_RC SendSaltedStartAuthSession(FWTPM_CTX* ctx, UINT32 tpmKey, + const byte* encSalt, UINT16 encSaltSz) +{ + int pos, rspSize = 0; + TPM_RC rc; + + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_StartAuthSession); + PutU32BE(gCmd + pos, tpmKey); pos += 4; + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; /* bind */ + PutU16BE(gCmd + pos, 16); pos += 2; + memset(gCmd + pos, 0xAA, 16); pos += 16; /* nonceCaller */ + PutU16BE(gCmd + pos, encSaltSz); pos += 2; + memcpy(gCmd + pos, encSalt, encSaltSz); pos += encSaltSz; + gCmd[pos++] = TPM_SE_HMAC; + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* symmetric */ + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; /* authHash */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + rc = GetRspRC(gRsp); + if (rc == TPM_RC_SUCCESS) { + FlushHandle(ctx, GetU32BE(gRsp + TPM2_HEADER_SIZE)); + } + return rc; +} + +/* encryptedSalt must be empty when tpmKey is TPM_RH_NULL, and an RSA salt + * is at most the digest size of the tpmKey nameAlg (Part 3 Sec.11.1.1). */ +static void test_fwtpm_start_auth_session_salt_rules(void) +{ + FWTPM_CTX ctx; + FWTPM_Object* obj; + RsaKey key; + UINT32 keyH; + byte salt[WC_SHA256_DIGEST_SIZE + 16]; + byte encSalt[MAX_RSA_KEY_BYTES]; + int encSaltSz; + + XMEMSET(&ctx, 0, sizeof(ctx)); + XMEMSET(&key, 0, sizeof(key)); + XMEMSET(salt, 0x3C, sizeof(salt)); + AssertIntEQ(fwtpm_test_startup(&ctx), TPM_RC_SUCCESS); + + AssertIntEQ(SendSaltedStartAuthSession(&ctx, TPM_RH_NULL, salt, 8), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendSaltedStartAuthSession(&ctx, TPM_RH_NULL, salt, 0), + TPM_RC_SUCCESS); + + keyH = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); + AssertIntNE(keyH, 0); + obj = &ctx.objects[keyH - TRANSIENT_FIRST]; + AssertIntEQ(obj->pub.nameAlg, TPM_ALG_SHA256); + AssertIntEQ(FwImportRsaKey(obj, &key), TPM_RC_SUCCESS); + AssertIntEQ(wc_RsaSetRNG(&key, &ctx.rng), 0); + + /* With a tpmKey the salt is not empty and has to decrypt */ + AssertIntEQ(SendSaltedStartAuthSession(&ctx, keyH, salt, 0), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + XMEMSET(encSalt, 0x3C, sizeof(encSalt)); + AssertIntEQ(SendSaltedStartAuthSession(&ctx, keyH, encSalt, 256), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + + encSaltSz = wc_RsaPublicEncrypt_ex(salt, WC_SHA256_DIGEST_SIZE, + encSalt, sizeof(encSalt), &key, &ctx.rng, WC_RSA_OAEP_PAD, + WC_HASH_TYPE_SHA256, WC_MGF1SHA256, (byte*)"SECRET", 7); + AssertIntEQ(encSaltSz, 256); + AssertIntEQ(SendSaltedStartAuthSession(&ctx, keyH, encSalt, + (UINT16)encSaltSz), TPM_RC_SUCCESS); + + encSaltSz = wc_RsaPublicEncrypt_ex(salt, sizeof(salt), + encSalt, sizeof(encSalt), &key, &ctx.rng, WC_RSA_OAEP_PAD, + WC_HASH_TYPE_SHA256, WC_MGF1SHA256, (byte*)"SECRET", 7); + AssertIntEQ(encSaltSz, 256); + AssertIntEQ(SendSaltedStartAuthSession(&ctx, keyH, encSalt, + (UINT16)encSaltSz), TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + + wc_FreeRsaKey(&key); + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("StartAuthSession salt rules:", 0); +} + static void test_fwtpm_rsa_hash_matrix(void) { test_fwtpm_rsa_seed_hashes(); @@ -27683,6 +27765,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_hash_capabilities(); #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) test_fwtpm_rsa_hash_matrix(); + test_fwtpm_start_auth_session_salt_rules(); #endif } From 483808980b97a1a3c04c733cc19724ed2e3a302d Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 08:32:55 -0800 Subject: [PATCH 046/124] F-16846 - Wipe the fwTPM TIS command and response FIFOs after use --- src/fwtpm/fwtpm_tis.c | 15 ++++++ src/fwtpm/fwtpm_tis_shm.c | 2 + tests/fwtpm_hal_unit_tests.c | 100 ++++++++++++++++++++++++++++++++++- 3 files changed, 115 insertions(+), 2 deletions(-) diff --git a/src/fwtpm/fwtpm_tis.c b/src/fwtpm/fwtpm_tis.c index 00f607f31..e19765ed3 100644 --- a/src/fwtpm/fwtpm_tis.c +++ b/src/fwtpm/fwtpm_tis.c @@ -73,6 +73,14 @@ static UINT32 TisBuildSts(BYTE stsFlags, UINT16 burstCount) return ((UINT32)burstCount << 8) | (UINT32)stsFlags; } +/* The FIFOs hold whole commands and responses in what may be shared memory, + * so they are wiped once consumed. */ +static void TisWipeFifos(FWTPM_TIS_REGS* regs) +{ + TPM2_ForceZero(regs->cmd_buf, sizeof(regs->cmd_buf)); + TPM2_ForceZero(regs->rsp_buf, sizeof(regs->rsp_buf)); +} + /* Handle a single TIS register access */ static void TisHandleRegAccess(FWTPM_CTX* ctx, FWTPM_TIS_REGS* regs) { @@ -111,6 +119,7 @@ static void TisHandleRegAccess(FWTPM_CTX* ctx, FWTPM_TIS_REGS* regs) * owner cannot drain the previous locality's bytes * without first writing COMMAND_READY. */ if (ctx->tisLocality < 0) { + TisWipeFifos(regs); regs->cmd_len = 0; regs->fifo_write_pos = 0; regs->fifo_read_pos = 0; @@ -125,6 +134,7 @@ static void TisHandleRegAccess(FWTPM_CTX* ctx, FWTPM_TIS_REGS* regs) if (val & FWTPM_ACCESS_ACTIVE_LOCALITY) { /* Release only if it is the current owner */ if (ctx->tisLocality == loc) { + TisWipeFifos(regs); ctx->tisLocality = -1; regs->sts = TisBuildSts(0, 0); } @@ -143,6 +153,7 @@ static void TisHandleRegAccess(FWTPM_CTX* ctx, FWTPM_TIS_REGS* regs) } if (val & FWTPM_STS_COMMAND_READY) { /* Reset FIFO for new command */ + TisWipeFifos(regs); regs->cmd_len = 0; regs->fifo_write_pos = 0; regs->fifo_read_pos = 0; @@ -160,6 +171,7 @@ static void TisHandleRegAccess(FWTPM_CTX* ctx, FWTPM_TIS_REGS* regs) int procRc = TPM_RC_FAILURE; TPM_RC rc = TPM_RC_SUCCESS; /* FWTPM_ALLOC_BUF sets on OOM */ + TPM2_ForceZero(regs->rsp_buf, sizeof(regs->rsp_buf)); FWTPM_ALLOC_BUF(localCmd, FWTPM_TIS_FIFO_SIZE); if (rc == TPM_RC_SUCCESS) { FWTPM_ALLOC_BUF(localRsp, FWTPM_TIS_FIFO_SIZE); @@ -195,6 +207,7 @@ static void TisHandleRegAccess(FWTPM_CTX* ctx, FWTPM_TIS_REGS* regs) FWTPM_SIZEOF_BUF(localCmd, FWTPM_TIS_FIFO_SIZE)); FWTPM_FREE_BUF(localRsp); FWTPM_FREE_BUF(localCmd); + TPM2_ForceZero(regs->cmd_buf, sizeof(regs->cmd_buf)); if (procRc != TPM_RC_SUCCESS || rspSize == 0) { /* Build minimal error response * TPM_ST_NO_SESSIONS = 0x8001 (big-endian) */ @@ -239,6 +252,7 @@ static void TisHandleRegAccess(FWTPM_CTX* ctx, FWTPM_TIS_REGS* regs) break; } if (wpos >= FWTPM_TIS_FIFO_SIZE) { + TPM2_ForceZero(regs->cmd_buf, sizeof(regs->cmd_buf)); regs->fifo_write_pos = 0; break; } @@ -270,6 +284,7 @@ static void TisHandleRegAccess(FWTPM_CTX* ctx, FWTPM_TIS_REGS* regs) if (cmdTotalSz < TPM2_HEADER_SIZE || cmdTotalSz > FWTPM_TIS_FIFO_SIZE) { /* Invalid command size, reset FIFO */ + TPM2_ForceZero(regs->cmd_buf, sizeof(regs->cmd_buf)); regs->cmd_len = 0; regs->fifo_write_pos = 0; regs->sts = TisBuildSts( diff --git a/src/fwtpm/fwtpm_tis_shm.c b/src/fwtpm/fwtpm_tis_shm.c index 4fe17903e..2fb268e5f 100644 --- a/src/fwtpm/fwtpm_tis_shm.c +++ b/src/fwtpm/fwtpm_tis_shm.c @@ -230,6 +230,8 @@ static void TisShmCleanup(void* ctx) FWTPM_TIS_ATOMIC_STORE(shm->regs->magic, 0U); TPM2_ForceZero(shm->regs->reg_data, sizeof(shm->regs->reg_data)); + TPM2_ForceZero(shm->regs->cmd_buf, sizeof(shm->regs->cmd_buf)); + TPM2_ForceZero(shm->regs->rsp_buf, sizeof(shm->regs->rsp_buf)); if (shm->semRsp != NULL && shm->semRsp != SEM_FAILED) { (void)sem_post(shm->semRsp); } diff --git a/tests/fwtpm_hal_unit_tests.c b/tests/fwtpm_hal_unit_tests.c index 43c21a78e..83acd0847 100644 --- a/tests/fwtpm_hal_unit_tests.c +++ b/tests/fwtpm_hal_unit_tests.c @@ -591,7 +591,7 @@ static int TestTisGoSuccess(void) if (!gGoPrivateBufs || regs.rsp_len != (UINT32)rspSize || regs.fifo_read_pos != 0 || (regs.sts & FWTPM_STS_DATA_AVAIL) == 0 || - regs.rsp_buf[rspSize] != 0xEE) { + regs.rsp_buf[rspSize] != 0) { failed = 1; } if (TisDrainFifo(&ctx, ®s, out, sizeof(out)) != (UINT32)rspSize) { @@ -631,7 +631,7 @@ static int TestTisGoFailure(int rc, int rspSize, const char* name) failed = 1; } for (i = (int)sizeof(expected); i < (int)sizeof(regs.rsp_buf); i++) { - if (regs.rsp_buf[i] != 0xEE) { + if (regs.rsp_buf[i] != 0) { failed = 1; break; } @@ -646,6 +646,101 @@ static int TestTisGoFailure(int rc, int rspSize, const char* name) return failed; } +static int TisBufIsZero(const byte* buf, UINT32 sz) +{ + UINT32 i; + + for (i = 0; i < sz; i++) { + if (buf[i] != 0) { + return 0; + } + } + return 1; +} + +/* A consumed command and a finished response do not stay in the FIFOs */ +static int TestTisFifoWiped(void) +{ + static const int rspSize = 100; + FWTPM_CTX ctx; + FWTPM_TIS_REGS regs; + byte out[100]; + int failed = 0; + + TisGoSetup(&ctx, ®s); + XMEMSET(regs.cmd_buf, 0xC3, sizeof(regs.cmd_buf)); + gGoRc = TPM_RC_SUCCESS; + gGoRspSize = rspSize; + TisHandleRegAccess(&ctx, ®s); + if (!TisBufIsZero(regs.cmd_buf, sizeof(regs.cmd_buf)) || + !TisBufIsZero(regs.rsp_buf + rspSize, + sizeof(regs.rsp_buf) - rspSize)) { + failed = 1; + } + if (TisDrainFifo(&ctx, ®s, out, sizeof(out)) != (UINT32)rspSize) { + failed = 1; + } + gGoRegs = NULL; + + regs.reg_addr = FWTPM_TIS_STS; + regs.reg_len = 1; + regs.reg_is_write = 1; + regs.reg_data[0] = FWTPM_STS_COMMAND_READY; + TisHandleRegAccess(&ctx, ®s); + if (!TisBufIsZero(regs.rsp_buf, sizeof(regs.rsp_buf))) { + failed = 1; + } + + /* A command that is abandoned before GO goes at the next COMMAND_READY */ + regs.reg_addr = FWTPM_TIS_DATA_FIFO; + regs.reg_len = TPM2_HEADER_SIZE - 2; + XMEMSET(regs.reg_data, 0xC3, TPM2_HEADER_SIZE - 2); + TisHandleRegAccess(&ctx, ®s); + if (regs.cmd_len != TPM2_HEADER_SIZE - 2 || + TisBufIsZero(regs.cmd_buf, TPM2_HEADER_SIZE - 2)) { + failed = 1; + } + regs.reg_addr = FWTPM_TIS_STS; + regs.reg_len = 1; + regs.reg_data[0] = FWTPM_STS_COMMAND_READY; + TisHandleRegAccess(&ctx, ®s); + if (!TisBufIsZero(regs.cmd_buf, sizeof(regs.cmd_buf))) { + failed = 1; + } + + /* A command with an impossible size, or one past the end of the FIFO, + * is dropped along with its bytes */ + regs.reg_addr = FWTPM_TIS_DATA_FIFO; + regs.reg_len = TPM2_HEADER_SIZE + 2; + XMEMSET(regs.reg_data, 0xC3, TPM2_HEADER_SIZE + 2); + TisHandleRegAccess(&ctx, ®s); + if (regs.cmd_len != 0 || + !TisBufIsZero(regs.cmd_buf, sizeof(regs.cmd_buf))) { + failed = 1; + } + XMEMSET(regs.cmd_buf, 0xC3, sizeof(regs.cmd_buf)); + regs.fifo_write_pos = FWTPM_TIS_FIFO_SIZE; + TisHandleRegAccess(&ctx, ®s); + if (regs.fifo_write_pos != 0 || + !TisBufIsZero(regs.cmd_buf, sizeof(regs.cmd_buf))) { + failed = 1; + } + + XMEMSET(regs.cmd_buf, 0xC3, sizeof(regs.cmd_buf)); + XMEMSET(regs.rsp_buf, 0xEE, sizeof(regs.rsp_buf)); + regs.reg_addr = FWTPM_TIS_ACCESS; + regs.reg_data[0] = FWTPM_ACCESS_ACTIVE_LOCALITY; + TisHandleRegAccess(&ctx, ®s); + if (ctx.tisLocality != -1 || + !TisBufIsZero(regs.cmd_buf, sizeof(regs.cmd_buf)) || + !TisBufIsZero(regs.rsp_buf, sizeof(regs.rsp_buf))) { + failed = 1; + } + + printf("%s: TIS FIFOs are wiped after use\n", failed ? "FAIL" : "PASS"); + return failed; +} + int main(void) { int failures = 0; @@ -686,6 +781,7 @@ int main(void) failures += TestTisGoFailure(TPM_RC_SUCCESS, 0, "an empty response"); failures += TestTisGoFailure(TPM_RC_SUCCESS, FWTPM_TIS_FIFO_SIZE + 1, "an oversized response"); + failures += TestTisFifoWiped(); CleanupEndpoint(); printf("fwTPM HAL endpoint tests: %s\n", From 19c6ce899d98d9e5151f4ee2d0ffaceff7101a89 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 08:43:00 -0800 Subject: [PATCH 047/124] F-16235 - Return TPM_RC_SEQUENCE from fwTPM ReadPublic for a sequence handle --- src/fwtpm/fwtpm_command.c | 34 ++++++++++++++++++---------------- tests/fwtpm_unit_tests.c | 29 +++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 16 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index cefba1739..f6e757703 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -5379,21 +5379,6 @@ static int FwCopyHmacContext(Hmac* src, Hmac* dst) #endif #endif -#ifndef FWTPM_NO_CONTEXT -#define FWTPM_CTX_MAGIC 0x4657544Du /* 'FWTM' */ -#define FWTPM_CTX_VER 1u -#define FWTPM_CTX_SAVED_STCLEAR (TRANSIENT_FIRST + 2u) -#define FWTPM_OBJ_CTX_WRAPPED_MAX \ - ((MAX_CONTEXT_SIZE - 8 < FWTPM_MAX_COMMAND_SIZE - TPM2_HEADER_SIZE - 26) ? \ - MAX_CONTEXT_SIZE - 8 : FWTPM_MAX_COMMAND_SIZE - TPM2_HEADER_SIZE - 26) -#define FWTPM_OBJ_CTX_PLAIN_MAX \ - (FWTPM_OBJ_CTX_WRAPPED_MAX - AES_BLOCK_SIZE - WC_SHA256_DIGEST_SIZE) - -#define FWTPM_CTX_SAVED_SEQUENCE (TRANSIENT_FIRST + 1u) -#define FWTPM_SEQ_CTX_PLAIN_MAX \ - (MAX_CONTEXT_SIZE - 8 - AES_BLOCK_SIZE - WC_SHA256_DIGEST_SIZE) -#define FWTPM_SEQ_CTX_WRAPPED_MAX (MAX_CONTEXT_SIZE - 8) - static int FwIsSequenceHandle(FWTPM_CTX* ctx, TPM_HANDLE handle) { (void)ctx; @@ -5411,6 +5396,21 @@ static int FwIsSequenceHandle(FWTPM_CTX* ctx, TPM_HANDLE handle) return 0; } +#ifndef FWTPM_NO_CONTEXT +#define FWTPM_CTX_MAGIC 0x4657544Du /* 'FWTM' */ +#define FWTPM_CTX_VER 1u +#define FWTPM_CTX_SAVED_STCLEAR (TRANSIENT_FIRST + 2u) +#define FWTPM_OBJ_CTX_WRAPPED_MAX \ + ((MAX_CONTEXT_SIZE - 8 < FWTPM_MAX_COMMAND_SIZE - TPM2_HEADER_SIZE - 26) ? \ + MAX_CONTEXT_SIZE - 8 : FWTPM_MAX_COMMAND_SIZE - TPM2_HEADER_SIZE - 26) +#define FWTPM_OBJ_CTX_PLAIN_MAX \ + (FWTPM_OBJ_CTX_WRAPPED_MAX - AES_BLOCK_SIZE - WC_SHA256_DIGEST_SIZE) + +#define FWTPM_CTX_SAVED_SEQUENCE (TRANSIENT_FIRST + 1u) +#define FWTPM_SEQ_CTX_PLAIN_MAX \ + (MAX_CONTEXT_SIZE - 8 - AES_BLOCK_SIZE - WC_SHA256_DIGEST_SIZE) +#define FWTPM_SEQ_CTX_WRAPPED_MAX (MAX_CONTEXT_SIZE - 8) + #define FWTPM_SEQ_CTX_HASH 1u #define FWTPM_SEQ_CTX_SIGN 2u #define FWTPM_SEQ_CTX_HASH_INIT 0x01u @@ -6840,7 +6840,9 @@ static TPM_RC FwCmd_ReadPublic(FWTPM_CTX* ctx, TPM2_Packet* cmd, obj = FwFindObject(ctx, objectHandle); if (obj == NULL) { - rc = TPM_RC_HANDLE; + /* Part 3 Sec.12.4.1: a sequence object has no public area */ + rc = FwIsSequenceHandle(ctx, objectHandle) ? + TPM_RC_SEQUENCE : TPM_RC_HANDLE; } } if (rc == 0 && cmdTag == TPM_ST_SESSIONS) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 5f2b209fc..7a154c1da 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -19648,6 +19648,34 @@ static UINT32 StartHashSeqHelper(FWTPM_CTX* ctx) return GetU32BE(gRsp + TPM2_HEADER_SIZE); } +/* A sequence object has no public area to read (Part 3 Sec.12.4.1). */ +static void test_fwtpm_read_public_sequence(void) +{ + FWTPM_CTX ctx; + UINT32 seqH; + int pos, rspSize = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + seqH = StartHashSeqHelper(&ctx); + AssertIntNE(seqH, 0); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ReadPublic); + PutU32BE(gCmd + pos, seqH); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SEQUENCE); + + FlushHandle(&ctx, seqH); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntNE(GetRspRC(gRsp), TPM_RC_SEQUENCE); + AssertIntNE(GetRspRC(gRsp), TPM_RC_SUCCESS); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("ReadPublic on a sequence handle:", 0); +} + /* SequenceUpdate, or SequenceComplete asking for an owner ticket */ static TPM_RC SendSeqDataCmd(FWTPM_CTX* ctx, UINT32 cc, UINT32 seqH, const byte* data, UINT16 dataSz) @@ -28321,6 +28349,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifndef FWTPM_NO_HASH_CMDS test_fwtpm_hash(); test_fwtpm_hash_sequence(); + test_fwtpm_read_public_sequence(); test_fwtpm_hashcheck_ticket_generated_prefix(); #if !defined(FWTPM_NO_PARAM_ENC) && FWTPM_MAX_SESSIONS >= 2 test_fwtpm_param_enc_session_selection(); From ad54e9dc78e4210624d99db1cc0a0f818ed4f718 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 08:51:14 -0800 Subject: [PATCH 048/124] F-16097 - Honor the TPM2B sizes of ECC coordinates and scalars in fwTPM key imports --- src/fwtpm/fwtpm_command.c | 42 +++++--- src/fwtpm/fwtpm_crypto.c | 71 ++++++++++-- tests/fwtpm_unit_tests.c | 204 +++++++++++++++++++++++++++++++++++ wolftpm/fwtpm/fwtpm_crypto.h | 2 + 4 files changed, 296 insertions(+), 23 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index f6e757703..7601328dc 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -8725,6 +8725,19 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { rc = FwValidatePublicTemplate(&inPublic.publicArea, 1); } +#ifdef HAVE_ECC + /* The coordinates of a public-only ECC key are curve sized */ + if (rc == 0 && inPrivSize == 0 && + inPublic.publicArea.type == TPM_ALG_ECC) { + int keySz = wc_ecc_get_curve_size_from_id(FwGetWcCurveId( + inPublic.publicArea.parameters.eccDetail.curveID)); + if (keySz > 0 && + ((int)inPublic.publicArea.unique.ecc.x.size != keySz || + (int)inPublic.publicArea.unique.ecc.y.size != keySz)) { + rc = TPM_RC_KEY | TPM_RC_P | TPM_RC_2; + } + } +#endif #ifdef DEBUG_WOLFTPM if (rc == 0) { @@ -8770,10 +8783,12 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } if (rc == 0) { - rc = wc_ecc_import_unsigned(eccKey, + rc = FwEccImportUnsigned(eccKey, inPublic.publicArea.unique.ecc.x.buffer, + inPublic.publicArea.unique.ecc.x.size, inPublic.publicArea.unique.ecc.y.buffer, - qBuf, wcCurveExt); + inPublic.publicArea.unique.ecc.y.size, + qBuf, qSz, wcCurveExt); if (rc == 0) { privKeyDerSz = wc_EccKeyToDer(eccKey, privKeyDer, FWTPM_MAX_PRIVKEY_DER); @@ -8781,9 +8796,6 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_FAILURE; } } - else { - rc = TPM_RC_FAILURE; - } wc_ecc_free(eccKey); } FWTPM_FREE_VAR(eccKey); @@ -12432,12 +12444,10 @@ static TPM_RC FwCmd_ECDH_ZGen(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } if (rc == 0) { - rc = wc_ecc_import_unsigned(peerPub, - inPoint->point.x.buffer, inPoint->point.y.buffer, - NULL, wcCurve); - if (rc != 0) { - rc = TPM_RC_FAILURE; - } + rc = FwEccImportUnsigned(peerPub, + inPoint->point.x.buffer, inPoint->point.x.size, + inPoint->point.y.buffer, inPoint->point.y.size, + NULL, 0, wcCurve); } /* Validate peer point is on the expected curve (invalid curve attack) */ if (rc == 0) { @@ -20160,8 +20170,9 @@ static TPM_RC FwCmd_ZGen_2Phase(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) peerInit = 1; } if (rc == 0) { - rc = wc_ecc_import_unsigned(peerPub, - inQsB.point.x.buffer, inQsB.point.y.buffer, NULL, wcCurve); + rc = FwEccImportUnsigned(peerPub, + inQsB.point.x.buffer, inQsB.point.x.size, + inQsB.point.y.buffer, inQsB.point.y.size, NULL, 0, wcCurve); } if (rc == 0) { rc = wc_ecc_check_key(peerPub); @@ -20196,8 +20207,9 @@ static TPM_RC FwCmd_ZGen_2Phase(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) peerInit = 1; } if (rc == 0) { - rc = wc_ecc_import_unsigned(peerPub, - inQeB.point.x.buffer, inQeB.point.y.buffer, NULL, wcCurve); + rc = FwEccImportUnsigned(peerPub, + inQeB.point.x.buffer, inQeB.point.x.size, + inQeB.point.y.buffer, inQeB.point.y.size, NULL, 0, wcCurve); } if (rc == 0) { rc = wc_ecc_check_key(peerPub); diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index cb7d9737c..65603450d 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -2889,8 +2889,8 @@ TPM_RC FwDecryptSeed(FWTPM_CTX* ctx, rc = wc_ecc_init(ephemPub); if (rc == 0) { ephemPubInit = 1; - rc = wc_ecc_import_unsigned(ephemPub, xBuf, yBuf, - NULL, wcCurve); + rc = (int)FwEccImportUnsigned(ephemPub, xBuf, xSz, yBuf, ySz, + NULL, 0, wcCurve); } if (rc != 0) { rc = TPM_RC_FAILURE; @@ -3500,10 +3500,12 @@ TPM_RC FwImportReconstructKey( rc = wc_ecc_init(eccKey); if (rc == 0) { eccKeyInit = 1; - rc = wc_ecc_import_unsigned(eccKey, + rc = FwEccImportUnsigned(eccKey, objectPublic->publicArea.unique.ecc.x.buffer, + objectPublic->publicArea.unique.ecc.x.size, objectPublic->publicArea.unique.ecc.y.buffer, - primeBuf, wcCurve); + objectPublic->publicArea.unique.ecc.y.size, + primeBuf, primeSz, wcCurve); } if (rc == 0) { *privKeyDerSzOut = wc_EccKeyToDer(eccKey, privKeyDer, @@ -3621,6 +3623,59 @@ int FwImportEccKeyFromDer(const FWTPM_Object* obj, ecc_key* key) } #endif /* HAVE_ECC */ +#ifdef HAVE_ECC +/* Import TPM2B coordinates and an optional private scalar into an + * initialized key. wc_ecc_import_unsigned reads curve-width values and takes + * no lengths, so each value is right-aligned into the full width. */ +TPM_RC FwEccImportUnsigned(ecc_key* key, const byte* x, word32 xSz, + const byte* y, word32 ySz, const byte* d, word32 dSz, int wcCurve) +{ + TPM_RC rc = TPM_RC_SUCCESS; + byte xBuf[MAX_ECC_BYTES]; + byte yBuf[MAX_ECC_BYTES]; + byte dBuf[MAX_ECC_BYTES]; + int keySz = wc_ecc_get_curve_size_from_id(wcCurve); + + if (keySz <= 0 || keySz > MAX_ECC_BYTES) { + return TPM_RC_CURVE; + } + while (xSz > (word32)keySz && *x == 0) { + x++; + xSz--; + } + while (ySz > (word32)keySz && *y == 0) { + y++; + ySz--; + } + while (d != NULL && dSz > (word32)keySz && *d == 0) { + d++; + dSz--; + } + if (xSz > (word32)keySz || ySz > (word32)keySz) { + rc = TPM_RC_ECC_POINT; + } + else if (d != NULL && dSz > (word32)keySz) { + rc = TPM_RC_KEY_SIZE; + } + if (rc == 0) { + XMEMSET(xBuf, 0, sizeof(xBuf)); + XMEMSET(yBuf, 0, sizeof(yBuf)); + XMEMSET(dBuf, 0, sizeof(dBuf)); + XMEMCPY(xBuf + keySz - xSz, x, xSz); + XMEMCPY(yBuf + keySz - ySz, y, ySz); + if (d != NULL) { + XMEMCPY(dBuf + keySz - dSz, d, dSz); + } + if (wc_ecc_import_unsigned(key, xBuf, yBuf, + (d != NULL) ? dBuf : NULL, wcCurve) != 0) { + rc = TPM_RC_FAILURE; + } + } + TPM2_ForceZero(dBuf, sizeof(dBuf)); + return rc; +} +#endif /* HAVE_ECC */ + #ifndef NO_RSA /* Import public-only RSA key from TPMT_PUBLIC */ int FwImportRsaPubFromPublic(const TPMT_PUBLIC* pub, RsaKey* key) @@ -3664,10 +3719,10 @@ int FwImportEccPubFromPublic(const TPMT_PUBLIC* pub, ecc_key* key) rc = wc_ecc_init(key); if (rc != 0) return rc; - rc = wc_ecc_import_unsigned(key, - (byte*)pub->unique.ecc.x.buffer, - (byte*)pub->unique.ecc.y.buffer, - NULL, wcCurve); + rc = (int)FwEccImportUnsigned(key, + pub->unique.ecc.x.buffer, pub->unique.ecc.x.size, + pub->unique.ecc.y.buffer, pub->unique.ecc.y.size, + NULL, 0, wcCurve); if (rc != 0) { wc_ecc_free(key); return rc; } return 0; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 7a154c1da..ac5250d30 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -17939,6 +17939,207 @@ static void test_fwtpm_rewrap_null_newparent_rejected(void) } #endif /* !FWTPM_NO_KEY_MIGRATION */ +#ifdef HAVE_ECC +/* LoadExternal of a P-256 key, public only when d is NULL. */ +static TPM_RC SendLoadExternalEcc(FWTPM_CTX* ctx, UINT32 attributes, + const byte* x, UINT16 xSz, const byte* y, UINT16 ySz, + const byte* d, UINT16 dSz, UINT32* handle) +{ + int pos, privStart, pubStart, rspSize = 0; + + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_LoadExternal); + privStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + if (d != NULL) { + PutU16BE(gCmd + pos, TPM_ALG_ECC); pos += 2; /* sensitiveType */ + PutU16BE(gCmd + pos, 0); pos += 2; /* authValue */ + PutU16BE(gCmd + pos, 0); pos += 2; /* seedValue */ + PutU16BE(gCmd + pos, dSz); pos += 2; + memcpy(gCmd + pos, d, dSz); pos += dSz; + PutU16BE(gCmd + privStart, (UINT16)(pos - privStart - 2)); + } + pubStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_ECC); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; /* nameAlg */ + PutU32BE(gCmd + pos, attributes); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; /* authPolicy */ + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* symmetric */ + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* scheme */ + PutU16BE(gCmd + pos, TPM_ECC_NIST_P256); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* kdf */ + PutU16BE(gCmd + pos, xSz); pos += 2; + memcpy(gCmd + pos, x, xSz); pos += xSz; + PutU16BE(gCmd + pos, ySz); pos += 2; + memcpy(gCmd + pos, y, ySz); pos += ySz; + PutU16BE(gCmd + pubStart, (UINT16)(pos - pubStart - 2)); + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; /* hierarchy */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + if (GetRspRC(gRsp) == TPM_RC_SUCCESS && handle != NULL) { + *handle = GetU32BE(gRsp + TPM2_HEADER_SIZE); + } + return GetRspRC(gRsp); +} + +/* Make a P-256 key whose x coordinate (wantX) or private scalar starts with + * a zero octet, and export its fixed-width values. */ +static void MakeEccKeyLeadingZero(WC_RNG* rng, ecc_key* key, int wantX, + byte* x, byte* y, byte* d) +{ + word32 xSz, ySz, dSz; + int i, found = 0; + + for (i = 0; i < 20000 && !found; i++) { + AssertIntEQ(wc_ecc_init(key), 0); + AssertIntEQ(wc_ecc_make_key_ex(rng, 32, key, ECC_SECP256R1), 0); + xSz = ySz = dSz = 32; + AssertIntEQ(wc_ecc_export_private_raw(key, x, &xSz, y, &ySz, d, + &dSz), 0); + AssertIntEQ(xSz, 32); + AssertIntEQ(ySz, 32); + AssertIntEQ(dSz, 32); + found = wantX ? (x[0] == 0) : (d[0] == 0); + if (!found) { + wc_ecc_free(key); + } + } + AssertIntEQ(found, 1); +} + +#ifndef FWTPM_NO_ECDH +static TPM_RC SendEcdhZGen(FWTPM_CTX* ctx, UINT32 keyH, const byte* x, + UINT16 xSz, const byte* y, UINT16 ySz) +{ + int pos, rspSize = 0; + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ECDH_ZGen); + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, (UINT16)(4 + xSz + ySz)); pos += 2; + PutU16BE(gCmd + pos, xSz); pos += 2; + memcpy(gCmd + pos, x, xSz); pos += xSz; + PutU16BE(gCmd + pos, ySz); pos += 2; + memcpy(gCmd + pos, y, ySz); pos += ySz; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* A TPM2B coordinate or scalar is a number: one sent without its leading + * zero octet, or with an extra one, is the same value. */ +static void test_fwtpm_ecc_unpadded_values(void) +{ + FWTPM_CTX ctx; + FWTPM_Object* obj; + ecc_key ours, peer, loaded; + UINT32 keyH = 0; + byte x[32], y[32], d[32]; + byte px[33], py[32], pd[32]; + byte z[32], gotD[32]; + word32 zSz = sizeof(z), gotSz = sizeof(gotD); + TPM2B_PUBLIC pub; + byte der[FWTPM_MAX_PRIVKEY_DER]; + int derSz = 0; +#ifndef FWTPM_NO_ZGEN_2PHASE + int pos, rspSize = 0; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + MakeEccKeyLeadingZero(&ctx.rng, &ours, 0, x, y, d); + px[0] = 0; + MakeEccKeyLeadingZero(&ctx.rng, &peer, 1, px + 1, py, pd); + AssertIntEQ(wc_ecc_set_rng(&ours, &ctx.rng), 0); + AssertIntEQ(wc_ecc_shared_secret(&ours, &peer, z, &zSz), 0); + AssertIntEQ(zSz, 32); + + /* userWithAuth | decrypt, private scalar without its leading zero */ + AssertIntEQ(SendLoadExternalEcc(&ctx, 0x00020040, x, 32, y, 32, + d + 1, 31, &keyH), TPM_RC_SUCCESS); + obj = &ctx.objects[keyH - TRANSIENT_FIRST]; + AssertIntEQ(FwImportEccKeyFromDer(obj, &loaded), 0); + AssertIntEQ(wc_ecc_export_private_only(&loaded, gotD, &gotSz), 0); + AssertIntEQ(gotSz, 32); + AssertIntEQ(memcmp(gotD, d, 32), 0); + wc_ecc_free(&loaded); + + /* peer x without its leading zero, then with a second one */ + AssertIntEQ(SendEcdhZGen(&ctx, keyH, px + 2, 31, py, 32), + TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 6), 32); + AssertIntEQ(memcmp(gRsp + TPM2_HEADER_SIZE + 8, z, 32), 0); + AssertIntEQ(SendEcdhZGen(&ctx, keyH, px, 33, py, 32), TPM_RC_SUCCESS); + AssertIntEQ(memcmp(gRsp + TPM2_HEADER_SIZE + 8, z, 32), 0); + +#ifndef FWTPM_NO_ZGEN_2PHASE + /* both ZGen_2Phase points, one short and one long */ + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_EC_Ephemeral); + PutU16BE(gCmd + pos, TPM_ECC_NIST_P256); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ZGen_2Phase); + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 4 + 31 + 32); pos += 2; /* inQsB */ + PutU16BE(gCmd + pos, 31); pos += 2; + memcpy(gCmd + pos, px + 2, 31); pos += 31; + PutU16BE(gCmd + pos, 32); pos += 2; + memcpy(gCmd + pos, py, 32); pos += 32; + PutU16BE(gCmd + pos, 4 + 33 + 32); pos += 2; /* inQeB */ + PutU16BE(gCmd + pos, 33); pos += 2; + memcpy(gCmd + pos, px, 33); pos += 33; + PutU16BE(gCmd + pos, 32); pos += 2; + memcpy(gCmd + pos, py, 32); pos += 32; + PutU16BE(gCmd + pos, TPM_ALG_ECDH); pos += 2; + PutU16BE(gCmd + pos, ctx.ecEphemeralCounter); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 6), 32); + AssertIntEQ(memcmp(gRsp + TPM2_HEADER_SIZE + 8, z, 32), 0); +#endif + + /* an imported key: x, then the private scalar, without the leading + * zero */ + memset(&pub, 0, sizeof(pub)); + pub.publicArea.type = TPM_ALG_ECC; + pub.publicArea.nameAlg = TPM_ALG_SHA256; + pub.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256; + pub.publicArea.unique.ecc.x.size = 31; + memcpy(pub.publicArea.unique.ecc.x.buffer, px + 2, 31); + pub.publicArea.unique.ecc.y.size = 32; + memcpy(pub.publicArea.unique.ecc.y.buffer, py, 32); + AssertIntEQ(FwImportReconstructKey(&pub, TPM_ALG_ECC, pd, 32, der, + (int)sizeof(der), &derSz, &ctx.rng), TPM_RC_SUCCESS); + pub.publicArea.unique.ecc.x.size = 32; + memcpy(pub.publicArea.unique.ecc.x.buffer, x, 32); + memcpy(pub.publicArea.unique.ecc.y.buffer, y, 32); + AssertIntEQ(FwImportReconstructKey(&pub, TPM_ALG_ECC, d + 1, 31, der, + (int)sizeof(der), &derSz, &ctx.rng), TPM_RC_SUCCESS); + AssertIntEQ(derSz, obj->privKeySize); + AssertIntEQ(memcmp(der, obj->privKey, (size_t)derSz), 0); + FlushHandle(&ctx, keyH); + + /* a public-only key is loaded with curve-sized coordinates only */ + AssertIntEQ(SendLoadExternalEcc(&ctx, 0x00020040, px + 2, 31, py, 32, + NULL, 0, &keyH), TPM_RC_KEY | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendLoadExternalEcc(&ctx, 0x00020040, px, 33, py, 32, + NULL, 0, &keyH), TPM_RC_KEY | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendLoadExternalEcc(&ctx, 0x00020040, px + 1, 32, py, 32, + NULL, 0, &keyH), TPM_RC_SUCCESS); + + wc_ecc_free(&ours); + wc_ecc_free(&peer); + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("ECC unpadded coordinates and scalar:", 0); +} +#endif /* !FWTPM_NO_ECDH */ +#endif /* HAVE_ECC */ + #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) && \ !defined(FWTPM_NO_CREDENTIAL) /* The RSA credential seed is OAEP-wrapped with the label "IDENTITY" and its @@ -28312,6 +28513,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif test_fwtpm_read_public(); test_fwtpm_loadexternal_symcipher_bad_keysize_rejected(); +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ECDH) + test_fwtpm_ecc_unpadded_values(); +#endif #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) && \ !defined(FWTPM_NO_CREDENTIAL) test_fwtpm_rsa_credential_oaep_label(); diff --git a/wolftpm/fwtpm/fwtpm_crypto.h b/wolftpm/fwtpm/fwtpm_crypto.h index f3f653462..80b6bb3a0 100644 --- a/wolftpm/fwtpm/fwtpm_crypto.h +++ b/wolftpm/fwtpm/fwtpm_crypto.h @@ -340,6 +340,8 @@ int FwGetRsaHashOid(UINT16 hashAlg); #ifdef HAVE_ECC int FwImportEccKeyFromDer(const FWTPM_Object* obj, ecc_key* key); +TPM_RC FwEccImportUnsigned(ecc_key* key, const byte* x, word32 xSz, + const byte* y, word32 ySz, const byte* d, word32 dSz, int wcCurve); int FwImportEccPubFromPublic(const TPMT_PUBLIC* pub, ecc_key* key); int FwImportEccKey(const FWTPM_Object* obj, ecc_key* key); #if !defined(FWTPM_NO_ZGEN_2PHASE) || !defined(FWTPM_NO_ECC_ENCRYPT) From 352d81d15c8a78c2d8fb61551d3675d154a61cb0 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 08:56:30 -0800 Subject: [PATCH 049/124] F-16124 - Check that a fwTPM ECC private scalar matches its public point in LoadExternal and Import --- src/fwtpm/fwtpm_command.c | 3 + src/fwtpm/fwtpm_crypto.c | 59 ++++++++++++++++- tests/fwtpm_unit_tests.c | 121 +++++++++++++++++++++++++++++++++++ wolftpm/fwtpm/fwtpm_crypto.h | 1 + 4 files changed, 181 insertions(+), 3 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 7601328dc..15037ac0d 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -8789,6 +8789,9 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, inPublic.publicArea.unique.ecc.y.buffer, inPublic.publicArea.unique.ecc.y.size, qBuf, qSz, wcCurveExt); + if (rc == 0) { + rc = FwEccCheckBinding(eccKey, &ctx->rng); + } if (rc == 0) { privKeyDerSz = wc_EccKeyToDer(eccKey, privKeyDer, FWTPM_MAX_PRIVKEY_DER); diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 65603450d..87af4f578 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -3507,6 +3507,9 @@ TPM_RC FwImportReconstructKey( objectPublic->publicArea.unique.ecc.y.size, primeBuf, primeSz, wcCurve); } + if (rc == 0) { + rc = FwEccCheckBinding(eccKey, rng); + } if (rc == 0) { *privKeyDerSzOut = wc_EccKeyToDer(eccKey, privKeyDer, privKeyDerBufSz); @@ -3517,7 +3520,8 @@ TPM_RC FwImportReconstructKey( if (eccKeyInit) { wc_ecc_free(eccKey); } - if (rc != 0) { + if (rc != 0 && rc != TPM_RC_BINDING && rc != TPM_RC_KEY_SIZE && + rc != TPM_RC_ECC_POINT && rc != TPM_RC_MEMORY) { rc = TPM_RC_FAILURE; } } @@ -3634,6 +3638,11 @@ TPM_RC FwEccImportUnsigned(ecc_key* key, const byte* x, word32 xSz, byte xBuf[MAX_ECC_BYTES]; byte yBuf[MAX_ECC_BYTES]; byte dBuf[MAX_ECC_BYTES]; + byte order[MAX_ECC_BYTES]; + byte nonZero = 0; + int orderBits = 0; + int i; + int wcRc; int keySz = wc_ecc_get_curve_size_from_id(wcCurve); if (keySz <= 0 || keySz > MAX_ECC_BYTES) { @@ -3665,9 +3674,27 @@ TPM_RC FwEccImportUnsigned(ecc_key* key, const byte* x, word32 xSz, XMEMCPY(yBuf + keySz - ySz, y, ySz); if (d != NULL) { XMEMCPY(dBuf + keySz - dSz, d, dSz); + rc = FwEccGetCurveOrder(wcCurve, order, keySz, &orderBits); } - if (wc_ecc_import_unsigned(key, xBuf, yBuf, - (d != NULL) ? dBuf : NULL, wcCurve) != 0) { + } + /* A private scalar is in [1, n-1] */ + if (rc == 0 && d != NULL) { + for (i = 0; i < keySz; i++) { + nonZero |= dBuf[i]; + } + if (nonZero == 0 || !FwCtLessBE(dBuf, order, keySz)) { + rc = TPM_RC_KEY_SIZE; + } + } + if (rc == 0) { + wcRc = wc_ecc_import_unsigned(key, xBuf, yBuf, + (d != NULL) ? dBuf : NULL, wcCurve); + /* wolfCrypt checks the scalar against the point itself when built + * with WOLFSSL_VALIDATE_ECC_IMPORT */ + if (wcRc == ECC_PRIV_KEY_E) { + rc = TPM_RC_BINDING; + } + else if (wcRc != 0) { rc = TPM_RC_FAILURE; } } @@ -3676,6 +3703,32 @@ TPM_RC FwEccImportUnsigned(ecc_key* key, const byte* x, word32 xSz, } #endif /* HAVE_ECC */ +#ifdef HAVE_ECC +/* The private scalar of a loaded key has to generate its public point, else + * the Name would describe a key the TPM does not hold (Part 3 Sec.12.3.1). */ +TPM_RC FwEccCheckBinding(ecc_key* key, WC_RNG* rng) +{ + TPM_RC rc = TPM_RC_SUCCESS; + int wcRc; + ecc_point* pub = wc_ecc_new_point(); + + if (pub == NULL) { + return TPM_RC_MEMORY; + } +#ifdef ECC_TIMING_RESISTANT + wcRc = wc_ecc_make_pub_ex(key, pub, rng); +#else + (void)rng; + wcRc = wc_ecc_make_pub(key, pub); +#endif + if (wcRc != 0 || wc_ecc_cmp_point(pub, &key->pubkey) != MP_EQ) { + rc = TPM_RC_BINDING; + } + wc_ecc_del_point(pub); + return rc; +} +#endif /* HAVE_ECC */ + #ifndef NO_RSA /* Import public-only RSA key from TPMT_PUBLIC */ int FwImportRsaPubFromPublic(const TPMT_PUBLIC* pub, RsaKey* key) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index ac5250d30..2f12f1968 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -18007,6 +18007,62 @@ static void MakeEccKeyLeadingZero(WC_RNG* rng, ecc_key* key, int wantX, AssertIntEQ(found, 1); } +/* A private scalar is loaded or imported only with the public point it + * generates (Part 3 Sec.12.3.1). */ +static void test_fwtpm_ecc_private_binding(void) +{ + FWTPM_CTX ctx; + ecc_key a, b; + TPM2B_PUBLIC pub; + UINT32 keyH = 0; + byte ax[32], ay[32], ad[32]; + byte bx[32], by[32], bd[32]; + byte zero[32]; + byte der[FWTPM_MAX_PRIVKEY_DER]; + int derSz = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + MakeEccKeyLeadingZero(&ctx.rng, &a, 0, ax, ay, ad); + MakeEccKeyLeadingZero(&ctx.rng, &b, 0, bx, by, bd); + wc_ecc_free(&a); + wc_ecc_free(&b); + memset(zero, 0, sizeof(zero)); + + /* userWithAuth | sign */ + AssertIntEQ(SendLoadExternalEcc(&ctx, 0x00040040, ax, 32, ay, 32, + bd, 32, &keyH), TPM_RC_BINDING); + AssertIntEQ(SendLoadExternalEcc(&ctx, 0x00040040, ax, 32, ay, 32, + zero, 32, &keyH), TPM_RC_KEY_SIZE); + AssertIntEQ(SendLoadExternalEcc(&ctx, 0x00040040, ax, 32, ay, 32, + ad, 32, &keyH), TPM_RC_SUCCESS); + FlushHandle(&ctx, keyH); + + memset(&pub, 0, sizeof(pub)); + pub.publicArea.type = TPM_ALG_ECC; + pub.publicArea.nameAlg = TPM_ALG_SHA256; + pub.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256; + pub.publicArea.unique.ecc.x.size = 32; + memcpy(pub.publicArea.unique.ecc.x.buffer, ax, 32); + pub.publicArea.unique.ecc.y.size = 32; + memcpy(pub.publicArea.unique.ecc.y.buffer, ay, 32); + AssertIntEQ(FwImportReconstructKey(&pub, TPM_ALG_ECC, bd, 32, der, + (int)sizeof(der), &derSz, &ctx.rng), TPM_RC_BINDING); + AssertIntEQ(FwImportReconstructKey(&pub, TPM_ALG_ECC, ad, 32, der, + (int)sizeof(der), &derSz, &ctx.rng), TPM_RC_SUCCESS); + AssertIntGT(derSz, 0); + + /* A coordinate wider than the curve is not a point on it */ + pub.publicArea.unique.ecc.x.size = 33; + pub.publicArea.unique.ecc.x.buffer[0] = 1; + memcpy(pub.publicArea.unique.ecc.x.buffer + 1, ax, 32); + AssertIntEQ(FwImportReconstructKey(&pub, TPM_ALG_ECC, ad, 32, der, + (int)sizeof(der), &derSz, &ctx.rng), TPM_RC_ECC_POINT); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("ECC private scalar bound to public point:", 0); +} + #ifndef FWTPM_NO_ECDH static TPM_RC SendEcdhZGen(FWTPM_CTX* ctx, UINT32 keyH, const byte* x, UINT16 xSz, const byte* y, UINT16 ySz) @@ -20023,6 +20079,7 @@ static void test_fwtpm_hashcheck_ticket_generated_prefix(void) static wolfSSL_Malloc_cb gFwtpmTestMalloc; static int gFwtpmTestAllocCount; static int gFwtpmTestFailAllocAt; +static size_t gFwtpmTestFailAllocSize; static void* test_fwtpm_fail_malloc(size_t size #ifdef WOLFSSL_STATIC_MEMORY @@ -20038,6 +20095,12 @@ static void* test_fwtpm_fail_malloc(size_t size gFwtpmTestAllocCount >= gFwtpmTestFailAllocAt) { return NULL; } + if (gFwtpmTestFailAllocSize != 0 && size == gFwtpmTestFailAllocSize) { + return NULL; + } + if (gFwtpmTestMalloc == NULL) { + return malloc(size); + } #ifdef WOLFSSL_STATIC_MEMORY #ifdef WOLFSSL_DEBUG_MEMORY return gFwtpmTestMalloc(size, heap, type, func, line); @@ -20140,6 +20203,58 @@ static void test_fwtpm_command_crypto_allocation_failure(void) fwtpm_pass("Command crypto allocation failures:", 0); } + +#ifdef HAVE_ECC +/* An ECC import that cannot allocate the point of its binding check reports + * the allocation failure. */ +static void test_fwtpm_import_ecc_binding_alloc_failure(void) +{ + wolfSSL_Malloc_cb oldMalloc; + wolfSSL_Free_cb oldFree; + wolfSSL_Realloc_cb oldRealloc; + FWTPM_CTX ctx; + ecc_key key; + TPM2B_PUBLIC pub; + byte x[32], y[32], d[32]; + word32 xSz = sizeof(x), ySz = sizeof(y), dSz = sizeof(d); + byte der[FWTPM_MAX_PRIVKEY_DER]; + int derSz = 0; + TPM_RC rc; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(wc_ecc_init(&key), 0); + AssertIntEQ(wc_ecc_make_key_ex(&ctx.rng, 32, &key, ECC_SECP256R1), 0); + AssertIntEQ(wc_ecc_export_private_raw(&key, x, &xSz, y, &ySz, d, &dSz), + 0); + wc_ecc_free(&key); + + memset(&pub, 0, sizeof(pub)); + pub.publicArea.type = TPM_ALG_ECC; + pub.publicArea.nameAlg = TPM_ALG_SHA256; + pub.publicArea.parameters.eccDetail.curveID = TPM_ECC_NIST_P256; + pub.publicArea.unique.ecc.x.size = (UINT16)xSz; + memcpy(pub.publicArea.unique.ecc.x.buffer, x, xSz); + pub.publicArea.unique.ecc.y.size = (UINT16)ySz; + memcpy(pub.publicArea.unique.ecc.y.buffer, y, ySz); + + AssertIntEQ(wolfSSL_GetAllocators(&oldMalloc, &oldFree, &oldRealloc), 0); + gFwtpmTestMalloc = oldMalloc; + gFwtpmTestAllocCount = 0; + gFwtpmTestFailAllocAt = 0; + gFwtpmTestFailAllocSize = sizeof(ecc_point); + AssertIntEQ(wolfSSL_SetAllocators(test_fwtpm_fail_malloc, oldFree, + oldRealloc), 0); + rc = FwImportReconstructKey(&pub, TPM_ALG_ECC, d, (UINT16)dSz, der, + (int)sizeof(der), &derSz, &ctx.rng); + gFwtpmTestFailAllocSize = 0; + AssertIntEQ(wolfSSL_SetAllocators(oldMalloc, oldFree, oldRealloc), 0); + AssertIntEQ(rc, TPM_RC_MEMORY); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("ECC import binding allocation failure:", 0); +} +#endif /* HAVE_ECC */ #endif /* WOLFTPM_FWTPM_UNIT_TEST && WOLFTPM_SMALL_STACK */ #if defined(HAVE_ECC) && !defined(FWTPM_NO_ECDH) @@ -28516,6 +28631,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if defined(HAVE_ECC) && !defined(FWTPM_NO_ECDH) test_fwtpm_ecc_unpadded_values(); #endif +#ifdef HAVE_ECC + test_fwtpm_ecc_private_binding(); +#endif #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) && \ !defined(FWTPM_NO_CREDENTIAL) test_fwtpm_rsa_credential_oaep_label(); @@ -28570,6 +28688,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif /* !FWTPM_NO_HASH_CMDS */ #if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) test_fwtpm_command_crypto_allocation_failure(); +#ifdef HAVE_ECC + test_fwtpm_import_ecc_binding_alloc_failure(); +#endif #endif #if defined(HAVE_ECC) && !defined(FWTPM_NO_ECDH) test_fwtpm_ecc_parameters(); diff --git a/wolftpm/fwtpm/fwtpm_crypto.h b/wolftpm/fwtpm/fwtpm_crypto.h index 80b6bb3a0..319d1a9c2 100644 --- a/wolftpm/fwtpm/fwtpm_crypto.h +++ b/wolftpm/fwtpm/fwtpm_crypto.h @@ -342,6 +342,7 @@ int FwGetRsaHashOid(UINT16 hashAlg); int FwImportEccKeyFromDer(const FWTPM_Object* obj, ecc_key* key); TPM_RC FwEccImportUnsigned(ecc_key* key, const byte* x, word32 xSz, const byte* y, word32 ySz, const byte* d, word32 dSz, int wcCurve); +TPM_RC FwEccCheckBinding(ecc_key* key, WC_RNG* rng); int FwImportEccPubFromPublic(const TPMT_PUBLIC* pub, ecc_key* key); int FwImportEccKey(const FWTPM_Object* obj, ecc_key* key); #if !defined(FWTPM_NO_ZGEN_2PHASE) || !defined(FWTPM_NO_ECC_ENCRYPT) From 5a6e34fc9b1be69b855fc685e4094a181a78060b Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:01:52 -0800 Subject: [PATCH 050/124] F-16137 - Reject a scheme on a fwTPM KEYEDHASH object that is both or neither sign and decrypt --- src/fwtpm/fwtpm_command.c | 26 ++++++- tests/fwtpm_unit_tests.c | 142 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+), 2 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 15037ac0d..248df6376 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -3221,6 +3221,22 @@ static TPM_RC FwValidatePublicTemplate(const TPMT_PUBLIC* pub, return rc; } +/* Usage checks that hold however the object arrives: created, loaded or + * imported. */ +static TPM_RC FwValidateKeyUsage(const TPMT_PUBLIC* pub) +{ + int sign = (pub->objectAttributes & TPMA_OBJECT_sign) != 0; + int decrypt = (pub->objectAttributes & TPMA_OBJECT_decrypt) != 0; + + /* Part 3 Sec.12.1.1: a keyedHash object with sign and decrypt both SET + * or both CLEAR has no scheme */ + if (pub->type == TPM_ALG_KEYEDHASH && sign == decrypt && + pub->parameters.keyedHashDetail.scheme.scheme != TPM_ALG_NULL) { + return TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; + } + return TPM_RC_SUCCESS; +} + static TPM_RC FwValidateCreateAttributes(const TPMT_PUBLIC* pub, const FWTPM_Object* parent, UINT16 sensitiveDataSz) { @@ -3306,8 +3322,7 @@ static TPM_RC FwValidateCreateAttributes(const TPMT_PUBLIC* pub, return TPM_RC_ATTRIBUTES; } #endif - - return TPM_RC_SUCCESS; + return FwValidateKeyUsage(pub); } #ifdef WOLFTPM_V185 @@ -8720,6 +8735,10 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + if (rc == 0) { + rc = FwValidateKeyUsage(&inPublic.publicArea); + } + /* Validate ML public parameters and the supplied public key size before * the object is created (Part 3 Sec.18.4). */ if (rc == 0) { @@ -9026,6 +9045,9 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { rc = FwValidatePublicTemplate(&objectPublic->publicArea, 0); } + if (rc == 0) { + rc = FwValidateKeyUsage(&objectPublic->publicArea); + } if (rc == 0 && (objectPublic->publicArea.objectAttributes & (TPMA_OBJECT_fixedTPM | TPMA_OBJECT_fixedParent)) != 0) { rc = TPM_RC_ATTRIBUTES; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 2f12f1968..bf7a0725e 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -3390,6 +3390,147 @@ static void test_fwtpm_rsassa_sha512_sign_verify(void) #endif /* WOLFSSL_SHA512 */ #endif /* !NO_RSA && WOLFSSL_KEY_GEN */ +/* CreatePrimary of a KEYEDHASH object holding caller-supplied data */ +static TPM_RC SendCreatePrimaryKeyedHash(FWTPM_CTX* ctx, UINT32 attributes, + UINT16 scheme) +{ + int pos, rspSize = 0, sensStart, pubStart; + TPM_RC rc; + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_CreatePrimary); + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, 9); pos += 4; /* authAreaSize */ + PutU32BE(gCmd + pos, TPM_RS_PW); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; + gCmd[pos++] = 0; + PutU16BE(gCmd + pos, 0); pos += 2; + sensStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, 0); pos += 2; /* userAuth */ + PutU16BE(gCmd + pos, 16); pos += 2; /* data */ + memset(gCmd + pos, 0x6B, 16); pos += 16; + PutU16BE(gCmd + sensStart, (UINT16)(pos - sensStart - 2)); + pubStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_KEYEDHASH); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + pos, attributes); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; /* authPolicy */ + PutU16BE(gCmd + pos, scheme); pos += 2; + if (scheme != TPM_ALG_NULL) { + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + } + PutU16BE(gCmd + pos, 0); pos += 2; /* unique */ + PutU16BE(gCmd + pubStart, (UINT16)(pos - pubStart - 2)); + PutU16BE(gCmd + pos, 0); pos += 2; /* outsideInfo */ + PutU32BE(gCmd + pos, 0); pos += 4; /* creationPCR */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + rc = GetRspRC(gRsp); + if (rc == TPM_RC_SUCCESS) { + UINT32 handle = GetU32BE(gRsp + TPM2_HEADER_SIZE); + rspSize = 0; + BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 14, TPM_CC_FlushContext); + PutU32BE(gCmd + 10, handle); + FWTPM_ProcessCommand(ctx, gCmd, 14, gRsp, &rspSize, 0); + } + return rc; +} + +/* The KEYEDHASH public area of SendCreatePrimaryKeyedHash with no unique, + * as the public-only inPublic of LoadExternal or, with a parent, as the + * objectPublic of Import */ +static TPM_RC SendKeyedHashPublic(FWTPM_CTX* ctx, UINT32 parentH, + UINT32 attributes, UINT16 scheme) +{ + int pos, rspSize = 0, pubStart; + + if (parentH == 0) { + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_LoadExternal); + PutU16BE(gCmd + pos, 0); pos += 2; /* inPrivate */ + } + else { + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Import); + PutU32BE(gCmd + pos, parentH); pos += 4; + PutU32BE(gCmd + pos, 9); pos += 4; /* authAreaSize */ + PutU32BE(gCmd + pos, TPM_RS_PW); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; + gCmd[pos++] = 0; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, 0); pos += 2; /* encryptionKey */ + } + pubStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_KEYEDHASH); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + pos, attributes); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; /* authPolicy */ + PutU16BE(gCmd + pos, scheme); pos += 2; + if (scheme != TPM_ALG_NULL) { + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + } + PutU16BE(gCmd + pos, 0); pos += 2; /* unique */ + PutU16BE(gCmd + pubStart, (UINT16)(pos - pubStart - 2)); + if (parentH == 0) { + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; /* hierarchy */ + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* A KEYEDHASH object with sign and decrypt both SET or both CLEAR has no + * scheme (Part 3 Sec.12.1.1). */ +static void test_fwtpm_create_keyedhash_scheme(void) +{ + FWTPM_CTX ctx; + /* fixedTPM | fixedParent | userWithAuth | noDA */ + UINT32 attrs = 0x00000452; +#if defined(HAVE_ECC) && !defined(FWTPM_NO_KEY_MIGRATION) + UINT32 parentH; + int cmdSz, rspSize = 0; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + AssertIntEQ(SendCreatePrimaryKeyedHash(&ctx, attrs | TPMA_OBJECT_sign | + TPMA_OBJECT_decrypt, TPM_ALG_HMAC), TPM_RC_SCHEME | TPM_RC_P | + TPM_RC_2); + AssertIntEQ(SendCreatePrimaryKeyedHash(&ctx, attrs, TPM_ALG_HMAC), + TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendCreatePrimaryKeyedHash(&ctx, attrs, TPM_ALG_NULL), + TPM_RC_SUCCESS); + AssertIntEQ(SendCreatePrimaryKeyedHash(&ctx, attrs | TPMA_OBJECT_sign, + TPM_ALG_HMAC), TPM_RC_SUCCESS); + + /* A loaded or an imported object is held to the same rule */ + AssertIntEQ(SendKeyedHashPublic(&ctx, 0, TPMA_OBJECT_userWithAuth, + TPM_ALG_HMAC), TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendKeyedHashPublic(&ctx, 0, TPMA_OBJECT_userWithAuth | + TPMA_OBJECT_sign | TPMA_OBJECT_decrypt, TPM_ALG_HMAC), + TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); +#if defined(HAVE_ECC) && !defined(FWTPM_NO_KEY_MIGRATION) + cmdSz = BuildCreatePrimaryCmd(gCmd, TPM_ALG_ECC); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + parentH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + AssertIntEQ(SendKeyedHashPublic(&ctx, parentH, TPMA_OBJECT_userWithAuth, + TPM_ALG_HMAC), TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendKeyedHashPublic(&ctx, parentH, TPMA_OBJECT_userWithAuth | + TPMA_OBJECT_sign | TPMA_OBJECT_decrypt, TPM_ALG_HMAC), + TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + rspSize = 0; + BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 14, TPM_CC_FlushContext); + PutU32BE(gCmd + 10, parentH); + FWTPM_ProcessCommand(&ctx, gCmd, 14, gRsp, &rspSize, 0); +#endif + + FWTPM_Cleanup(&ctx); + fwtpm_pass("CreatePrimary KEYEDHASH scheme:", 0); +} + #if defined(WOLFTPM_V185) && !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) static void test_fwtpm_create_primary_limited_attrs(void) { @@ -28448,6 +28589,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_rsassa_sha512_sign_verify(); #endif #endif + test_fwtpm_create_keyedhash_scheme(); #if defined(WOLFTPM_V185) && !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) test_fwtpm_create_primary_limited_attrs(); test_fwtpm_limited_attrs_rejected_all_paths(); From 6938bde80fc5f6982eefabd44f0ef0544b11f20a Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:01:52 -0800 Subject: [PATCH 051/124] F-16239 - Enforce the sign-only and decrypt-only usage of fwTPM ML-DSA and ML-KEM keys --- src/fwtpm/fwtpm_command.c | 13 ++++++++ tests/fwtpm_unit_tests.c | 65 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 248df6376..8c7cb211b 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -3228,6 +3228,19 @@ static TPM_RC FwValidateKeyUsage(const TPMT_PUBLIC* pub) int sign = (pub->objectAttributes & TPMA_OBJECT_sign) != 0; int decrypt = (pub->objectAttributes & TPMA_OBJECT_decrypt) != 0; +#ifdef WOLFTPM_MLDSA + /* Part 2 Sec.12.2.3.7: an ML-DSA key is a signing key only */ + if ((pub->type == TPM_ALG_MLDSA || pub->type == TPM_ALG_HASH_MLDSA) && + decrypt) { + return TPM_RC_ATTRIBUTES; + } +#endif +#ifdef WOLFTPM_MLKEM + /* Part 2 Sec.12.2.3.7: an ML-KEM key is a decryption key only */ + if (pub->type == TPM_ALG_MLKEM && sign) { + return TPM_RC_ATTRIBUTES; + } +#endif /* Part 3 Sec.12.1.1: a keyedHash object with sign and decrypt both SET * or both CLEAR has no scheme */ if (pub->type == TPM_ALG_KEYEDHASH && sign == decrypt && diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index bf7a0725e..43d6f964c 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -3562,6 +3562,67 @@ static void test_fwtpm_create_primary_limited_attrs(void) } #endif /* WOLFTPM_V185 && !NO_RSA && WOLFSSL_KEY_GEN */ +#if defined(WOLFTPM_V185) && defined(WOLFTPM_MLDSA) && \ + defined(WOLFTPM_HASH_MLDSA) && defined(WOLFTPM_MLKEM) +/* An ML-DSA key may only be a signing key and an ML-KEM key only a + * decryption key (Part 2 Sec.12.2.3.7). */ +static void test_fwtpm_create_primary_pqc_usage_attrs(void) +{ + static const struct { + TPM_ALG_ID alg; + UINT32 attrs; + } bad[] = { + { TPM_ALG_MLDSA, 0x00020072 }, /* decrypt */ + { TPM_ALG_MLDSA, 0x00060072 }, /* sign and decrypt */ + { TPM_ALG_HASH_MLDSA, 0x00020072 }, + { TPM_ALG_HASH_MLDSA, 0x00060072 }, + { TPM_ALG_MLKEM, 0x00040072 }, /* sign */ + { TPM_ALG_MLKEM, 0x00060072 } + }; + FWTPM_CTX ctx; + int i, rspSize, cmdSz, pos, pubSz; + /* inPublic follows the header, the handle, the auth area and an empty + * inSensitive */ + const int pubPos = TPM2_HEADER_SIZE + 4 + 13 + 6; + byte ext[TPM2_HEADER_SIZE + 2 + 64 + 4]; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + for (i = 0; i < (int)(sizeof(bad) / sizeof(bad[0])); i++) { + cmdSz = BuildCreatePrimaryCmdEx(gCmd, bad[i].alg, bad[i].attrs); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES); + + /* The same public area as a public-only LoadExternal */ + cmdSz = BuildCreatePrimaryCmdEx(gCmd, bad[i].alg, bad[i].attrs); + pubSz = 2 + GetU16BE(gCmd + pubPos); + AssertIntLE(pubSz, 2 + 64); + pos = BuildCmdHeader(ext, TPM_ST_NO_SESSIONS, 0, + TPM_CC_LoadExternal); + PutU16BE(ext + pos, 0); pos += 2; /* inPrivate */ + memcpy(ext + pos, gCmd + pubPos, (size_t)pubSz); pos += pubSz; + PutU32BE(ext + pos, TPM_RH_NULL); pos += 4; + PutU32BE(ext + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, ext, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES); + } + cmdSz = BuildCreatePrimaryCmd(gCmd, TPM_ALG_MLDSA); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + cmdSz = BuildCreatePrimaryCmd(gCmd, TPM_ALG_MLKEM); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("CreatePrimary ML-DSA/ML-KEM usage attributes:", 0); +} +#endif + #ifdef HAVE_ECC static void test_fwtpm_create_primary_ecc(void) { @@ -28594,6 +28655,10 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_create_primary_limited_attrs(); test_fwtpm_limited_attrs_rejected_all_paths(); #endif +#if defined(WOLFTPM_V185) && defined(WOLFTPM_MLDSA) && \ + defined(WOLFTPM_HASH_MLDSA) && defined(WOLFTPM_MLKEM) + test_fwtpm_create_primary_pqc_usage_attrs(); +#endif #ifdef HAVE_ECC test_fwtpm_create_primary_ecc(); #endif From 22e1ad56e389b1a3d1d34055656bfe85f09ceee2 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:06:26 -0800 Subject: [PATCH 052/124] F-16186 - Use the TCG inner wrap format in fwTPM Duplicate, Import and Rewrap --- src/fwtpm/fwtpm_command.c | 901 +++++++++++++++++---------------- src/fwtpm/fwtpm_crypto.c | 35 +- tests/fwtpm_unit_tests.c | 945 ++++++++++++++++++++++++++++++++++- wolftpm/fwtpm/fwtpm_crypto.h | 1 + 4 files changed, 1444 insertions(+), 438 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 8c7cb211b..0dd465cac 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -8954,8 +8954,332 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, #ifndef FWTPM_NO_KEY_MIGRATION +/* Add a parameter or handle number to a format-one response code that has + * none. */ +static TPM_RC FwRcAddIndex(TPM_RC rc, TPM_RC index) +{ + if ((rc & RC_FMT1) != 0 && (rc & (TPM_RC_P | 0xF00)) == 0) { + rc |= index; + } + return rc; +} + +/* Marshal the TPM2B_SENSITIVE of an object for duplication: one prime for + * RSA, the private scalar for ECC and the stored key octets for the other + * types. The authValue is zero padded to the nameAlg digest size. This TPM + * keeps no seedValue. */ +static TPM_RC FwDupMarshalSensitive(const FWTPM_Object* obj, byte* buf, + int bufSz, int* outSz) +{ + TPM_RC rc = TPM_RC_SUCCESS; + TPM2B_AUTH auth; + const byte* sens = obj->privKey; + int sensSz = obj->privKeySize; + int digestSz = TPM2_GetHashDigestSize(obj->pub.nameAlg); + int sz; + FWTPM_DECLARE_BUF(comp, FWTPM_MAX_DER_SIG_BUF); + + FWTPM_CALLOC_BUF(comp, FWTPM_MAX_DER_SIG_BUF); + + XMEMSET(&auth, 0, sizeof(auth)); + if (rc == 0 && obj->authValue.size > sizeof(auth.buffer)) { + rc = TPM_RC_FAILURE; + } + if (rc == 0) { + auth.size = obj->authValue.size; + XMEMCPY(auth.buffer, obj->authValue.buffer, auth.size); + if (digestSz > (int)auth.size && digestSz <= (int)sizeof(auth.buffer)) { + auth.size = (UINT16)digestSz; + } + } + +#ifndef NO_RSA + if (rc == 0 && obj->pub.type == TPM_ALG_RSA) { + FWTPM_DECLARE_VAR(rsaKey, RsaKey); + FWTPM_ALLOC_VAR(rsaKey, RsaKey); + if (rc == 0) { + if (FwImportRsaKeyFromDer(obj, rsaKey) != 0) { + rc = TPM_RC_KEY; + } + else { + sensSz = mp_unsigned_bin_size(&rsaKey->p); + if (sensSz <= 0 || sensSz > (int)FWTPM_MAX_DER_SIG_BUF) { + rc = TPM_RC_KEY; + } + else if (mp_to_unsigned_bin(&rsaKey->p, comp) != 0) { + rc = TPM_RC_FAILURE; + } + wc_FreeRsaKey(rsaKey); + } + } + FWTPM_FREE_VAR(rsaKey); + sens = comp; + } +#endif +#ifdef HAVE_ECC + if (rc == 0 && obj->pub.type == TPM_ALG_ECC) { + word32 dSz = (word32)FWTPM_MAX_DER_SIG_BUF; + FWTPM_DECLARE_VAR(eccKey, ecc_key); + FWTPM_ALLOC_VAR(eccKey, ecc_key); + if (rc == 0) { + if (FwImportEccKeyFromDer(obj, eccKey) != 0) { + rc = TPM_RC_KEY; + } + else { + if (wc_ecc_export_private_only(eccKey, comp, &dSz) != 0) { + rc = TPM_RC_FAILURE; + } + sensSz = (int)dSz; + wc_ecc_free(eccKey); + } + } + FWTPM_FREE_VAR(eccKey); + sens = comp; + } +#endif + + if (rc == 0) { + sz = FwMarshalSensitiveStd(buf, bufSz, obj->pub.type, &auth, + sens, sensSz); + if (sz < 0) { + rc = TPM_RC_SIZE; + } + else { + *outSz = sz; + } + } + + TPM2_ForceZero(&auth, sizeof(auth)); + TPM2_ForceZero(comp, FWTPM_MAX_DER_SIG_BUF); + FWTPM_FREE_BUF(comp); + return rc; +} + +/* Inner wrap of a duplication blob (Part 1 Sec.23.3.2.2). buf holds dataSz + * octets of sensitive after room for a TPM2B_DIGEST of the object nameAlg. + * The digest of sensitive || Name is stored there and both are encrypted + * with AES-CFB under a zero IV. */ +static TPM_RC FwDupInnerWrap(TPMI_ALG_HASH nameAlg, const byte* name, + int nameSz, const byte* key, int keySz, byte* buf, int dataSz) +{ + TPM_RC rc = TPM_RC_SUCCESS; + int digestSz = TPM2_GetHashDigestSize(nameAlg); + int hRc; + + if (digestSz <= 0) { + rc = TPM_RC_HASH; + } + if (rc == 0) { + hRc = FwComputeHashUnique(nameAlg, buf + 2 + digestSz, dataSz, + name, nameSz, buf + 2); + if (hRc != digestSz) { + rc = (hRc == (int)TPM_RC_MEMORY) ? TPM_RC_MEMORY : TPM_RC_FAILURE; + } + } + if (rc == 0) { + FwStoreU16BE(buf, (UINT16)digestSz); + if (TPM2_AesCfbEncrypt(key, keySz, NULL, buf, + (word32)(2 + digestSz + dataSz)) != 0) { + rc = TPM_RC_FAILURE; + } + } + return rc; +} + +/* Remove the inner wrap of a duplication blob in place: decrypt, then check + * the leading TPM2B_DIGEST against the digest of sensitive || Name. sensOff + * receives the offset of the sensitive. */ +static TPM_RC FwDupInnerUnwrap(TPMI_ALG_HASH nameAlg, const byte* name, + int nameSz, const byte* key, int keySz, byte* buf, int bufSz, + int* sensOff) +{ + TPM_RC rc = TPM_RC_SUCCESS; + int digestSz = TPM2_GetHashDigestSize(nameAlg); + int integSz = 0; + int hRc; + int cmpSz; + int sizeMismatch; + int digestDiff; + byte digest[TPM_MAX_DIGEST_SIZE]; + + if (digestSz <= 0) { + rc = TPM_RC_HASH; + } + if (rc == 0 && TPM2_AesCfbDecrypt(key, keySz, NULL, buf, + (word32)bufSz) != 0) { + rc = TPM_RC_FAILURE; + } + if (rc == 0 && bufSz < 2) { + rc = TPM_RC_INSUFFICIENT; + } + if (rc == 0) { + integSz = (int)FwLoadU16BE(buf); + if (integSz > (int)sizeof(digest)) { + rc = TPM_RC_SIZE; + } + else if (2 + integSz > bufSz) { + rc = TPM_RC_INSUFFICIENT; + } + } + if (rc == 0) { + hRc = FwComputeHashUnique(nameAlg, buf + 2 + integSz, + bufSz - 2 - integSz, name, nameSz, digest); + if (hRc != digestSz) { + rc = (hRc == (int)TPM_RC_MEMORY) ? TPM_RC_MEMORY : TPM_RC_FAILURE; + } + } + if (rc == 0) { + cmpSz = (integSz < digestSz) ? integSz : digestSz; + sizeMismatch = (integSz != digestSz); + digestDiff = TPM2_ConstantCompare(buf + 2, digest, (word32)cmpSz); + if (sizeMismatch | digestDiff) { + rc = TPM_RC_INTEGRITY; + } + } + if (rc == 0) { + *sensOff = 2 + integSz; + } + TPM2_ForceZero(digest, sizeof(digest)); + return rc; +} + +/* Outer wrap of a duplication blob (Part 1 Sec.23.3.2.3). buf holds dataSz + * octets after room for a TPM2B_DIGEST of the new parent nameAlg. The data + * is encrypted with AES-CFB under a zero IV and the HMAC of the encrypted + * data || Name is stored in front of it. */ +static TPM_RC FwDupOuterWrap(const FWTPM_Object* newParent, const byte* seed, + int seedSz, const byte* name, int nameSz, byte* buf, int dataSz) +{ + TPM_RC rc = TPM_RC_SUCCESS; + TPMI_ALG_HASH parentNameAlg = newParent->pub.nameAlg; + int digestSz = TPM2_GetHashDigestSize(parentNameAlg); + int symKeySz = 0; + byte aesKey[FWTPM_MAX_SYM_KEY_SIZE]; + byte hmacKey[FWTPM_MAX_HMAC_KEY_SIZE]; + + if (digestSz <= 0) { + rc = TPM_RC_HASH; + } + if (rc == 0) { + if (newParent->pub.type == TPM_ALG_RSA) { + symKeySz = (int)(newParent->pub.parameters.rsaDetail + .symmetric.keyBits.sym / 8); + } + else { + symKeySz = (int)(newParent->pub.parameters.eccDetail + .symmetric.keyBits.sym / 8); + } + if (symKeySz <= 0) { + symKeySz = 16; /* default AES-128 */ + } + if (symKeySz > FWTPM_MAX_SYM_KEY_SIZE) { + rc = TPM_RC_SYMMETRIC; + } + } + if (rc == 0) { + if (TPM2_KDFa_ex(parentNameAlg, seed, seedSz, "STORAGE", name, + (UINT32)nameSz, NULL, 0, aesKey, symKeySz) != symKeySz) { + rc = TPM_RC_FAILURE; + } + } + if (rc == 0) { + if (TPM2_KDFa_ex(parentNameAlg, seed, seedSz, "INTEGRITY", NULL, 0, + NULL, 0, hmacKey, digestSz) != digestSz) { + rc = TPM_RC_FAILURE; + } + } + if (rc == 0) { + if (TPM2_AesCfbEncrypt(aesKey, symKeySz, NULL, buf + 2 + digestSz, + (word32)dataSz) != 0) { + rc = TPM_RC_FAILURE; + } + } + if (rc == 0) { + FwStoreU16BE(buf, (UINT16)digestSz); + if (TPM2_HmacCompute(parentNameAlg, hmacKey, (word32)digestSz, + buf + 2 + digestSz, (word32)dataSz, name, (word32)nameSz, + buf + 2, NULL) != 0) { + rc = TPM_RC_FAILURE; + } + } + TPM2_ForceZero(aesKey, sizeof(aesKey)); + TPM2_ForceZero(hmacKey, sizeof(hmacKey)); + return rc; +} + +/* Check an imported KEYEDHASH or SYMCIPHER sensitive area and return its + * key: the key fits the public parameters and unique is the nameAlg digest + * of seedValue || key. Objects created by this TPM have an empty + * seedValue. */ +static TPM_RC FwImportSymSensitive(const TPMT_PUBLIC* pub, UINT16 sensType, + const byte* seed, UINT16 seedSz, const byte* key, UINT16 keySz, + byte* privKey, int privKeyBufSz, int* privKeySz) +{ + TPM_RC rc = TPM_RC_SUCCESS; + int digestSz = TPM2_GetHashDigestSize(pub->nameAlg); + int maxSz = 128; + int hRc; + UINT16 scheme; + byte unique[TPM_MAX_DIGEST_SIZE]; + + if (sensType != pub->type) { + rc = TPM_RC_TYPE | TPM_RC_P | TPM_RC_3; + } + else if (pub->type == TPM_ALG_SYMCIPHER) { + if ((int)keySz * 8 != (int)pub->parameters.symDetail.sym.keyBits.sym) { + rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_3; + } + } + else { + scheme = pub->parameters.keyedHashDetail.scheme.scheme; + if (scheme == TPM_ALG_HMAC) { + maxSz = wc_HashGetBlockSize(FwGetWcHashType( + pub->parameters.keyedHashDetail.scheme.details.hmac.hashAlg)); + } + else if (scheme == TPM_ALG_XOR) { + maxSz = wc_HashGetBlockSize(FwGetWcHashType( + pub->parameters.keyedHashDetail.scheme.details.xorr.hashAlg)); + } + else if (scheme != TPM_ALG_NULL) { + rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; + } + if (rc == 0 && (maxSz <= 0 || (int)keySz > maxSz)) { + rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_3; + } + } + if (rc == 0 && (int)keySz > privKeyBufSz) { + rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_3; + } + if (rc == 0) { + if (digestSz <= 0 || (seedSz != 0 && (int)seedSz != digestSz)) { + rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_3; + } + } + if (rc == 0) { + hRc = FwComputeHashUnique(pub->nameAlg, seed, seedSz, key, keySz, + unique); + if (hRc != digestSz) { + rc = (hRc == (int)TPM_RC_MEMORY) ? TPM_RC_MEMORY : TPM_RC_FAILURE; + } + else if ((int)pub->unique.keyedHash.size != digestSz || + TPM2_ConstantCompare(pub->unique.keyedHash.buffer, unique, + (word32)digestSz) != 0) { + rc = TPM_RC_BINDING; + } + } + if (rc == 0) { + if (keySz > 0) { + XMEMCPY(privKey, key, keySz); + } + *privKeySz = (int)keySz; + } + TPM2_ForceZero(unique, sizeof(unique)); + return rc; +} + /* --- TPM2_Import (CC 0x156) --- - * Import an externally created key (outer-wrapped) under a parent key. + * Import a duplicate, with or without its inner and outer wrap, under a + * parent key. * Response: [paramSz] | outPrivate */ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, TPM2_Packet* rsp, UINT16 cmdTag) @@ -8994,7 +9318,9 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, int plainSensSz = 0; UINT16 sensType = 0; UINT16 primeSz = 0; - FWTPM_DECLARE_VAR(innerHashCtx, wc_HashAlg); + const byte* sensSeed = NULL; + UINT16 sensSeedSz = 0; + int innerOff = 0; FWTPM_DECLARE_BUF(primeBuf, FWTPM_MAX_DER_SIG_BUF); TPM2B_AUTH importedAuth; TPM_RC rc = TPM_RC_SUCCESS; @@ -9005,7 +9331,6 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_ALLOC_BUF(pubAreaBuf, FWTPM_MAX_PUB_BUF); FWTPM_ALLOC_BUF(plainSens, FWTPM_MAX_SENSITIVE_SIZE); FWTPM_ALLOC_BUF(primeBuf, FWTPM_MAX_DER_SIG_BUF); - FWTPM_ALLOC_VAR(innerHashCtx, wc_HashAlg); FWTPM_CALLOC_VAR(objectPublic, TPM2B_PUBLIC); FWTPM_CALLOC_VAR(outPrivate, TPM2B_PRIVATE); @@ -9047,7 +9372,6 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseBytes(cmd, encKeyBuf, encKeySz); } } - /* encKeyBuf used later for inner decryption if symmetricAlg != NULL */ /* Parse objectPublic */ if (rc == 0) { @@ -9135,10 +9459,33 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, } (void)symMode; - if (rc == 0 && (objectPublic->publicArea.objectAttributes & - TPMA_OBJECT_encryptedDuplication) != 0 && - (encKeySz == 0 || symSeedSz == 0 || symAlg == TPM_ALG_NULL)) { - rc = TPM_RC_ATTRIBUTES; + /* The inner wrap key matches symmetricAlg, and an encryptedDuplication + * object arrives under both wraps (Part 3 Sec.13.3). */ + if (rc == 0 && symAlg != TPM_ALG_NULL) { + if (symAlg != TPM_ALG_AES) { + rc = TPM_RC_SYMMETRIC | TPM_RC_P | TPM_RC_5; + } + else if (symKeyBits != 128 && symKeyBits != 192 && + symKeyBits != 256) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_5; + } + else if (encKeySz != symKeyBits / 8) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; + } + } + else if (rc == 0) { + if (encKeySz != 0) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; + } + else if ((objectPublic->publicArea.objectAttributes & + TPMA_OBJECT_encryptedDuplication) != 0) { + rc = TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_1; + } + } + if (rc == 0 && symSeedSz == 0 && + (objectPublic->publicArea.objectAttributes & + TPMA_OBJECT_encryptedDuplication) != 0) { + rc = TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_4; } #ifdef DEBUG_WOLFTPM @@ -9175,12 +9522,14 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_KEY; } - /* Decrypt inSymSeed with parent key */ - if (rc == 0) { + /* Decrypt inSymSeed with parent key. An empty inSymSeed means the + * duplicate has no outer wrap. */ + if (rc == 0 && symSeedSz != 0) { rc = FwDecryptSeed(ctx, parent, symSeedBuf, symSeedSz, (const byte*)"DUPLICATE", 10, "DUPLICATE", seedBuf, (int)sizeof(seedBuf), &seedSz); + rc = FwRcAddIndex(rc, TPM_RC_P | TPM_RC_4); } /* Compute name of objectPublic: nameAlg(2) || Hash(publicArea) */ @@ -9213,7 +9562,7 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, } /* KDFa for storage key (AES wrap key) */ - if (rc == 0) { + if (rc == 0 && symSeedSz != 0) { rc = TPM2_KDFa_ex(parentNameAlg, seedBuf, seedSz, "STORAGE", nameBuf, nameSz, NULL, 0, aesKey, symKeySz); if (rc != symKeySz) { @@ -9225,7 +9574,7 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, } /* KDFa for integrity key (HMAC key) */ - if (rc == 0) { + if (rc == 0 && symSeedSz != 0) { rc = TPM2_KDFa_ex(parentNameAlg, seedBuf, seedSz, "INTEGRITY", NULL, 0, NULL, 0, hmacKeyBuf, digestSz); if (rc != digestSz) { @@ -9238,117 +9587,60 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Verify integrity and decrypt duplicate */ - if (rc == 0) { + if (rc == 0 && symSeedSz != 0) { rc = FwImportVerifyAndDecrypt(parentNameAlg, hmacKeyBuf, digestSz, aesKey, symKeySz, nameBuf, nameSz, dupBuf, dupSz, plainSens, (int)(FWTPM_MAX_SENSITIVE_SIZE), &plainSensSz); + rc = FwRcAddIndex(rc, TPM_RC_P | TPM_RC_3); } - - - /* Inner decryption: if symmetricAlg != NULL and encryptionKey provided, - * the plainSens contains inner wrapping that must be removed. - * Per TPM spec Part 1 Section 23.4: - * innerWrapped = innerIntegrity(TPM2B) || AES-CFB(encryptionKey, sens) - * innerIntegrity = HMAC(nameAlg, sensitive || objectName) */ - if (rc == 0 && symAlg != TPM_ALG_NULL && encKeySz > 0 && - plainSensSz > 2) { - UINT16 innerIntegSz; - int innerStart; - byte* encInner; - int encInnerSz; - byte innerHash[TPM_MAX_DIGEST_SIZE]; - int ihRc; - - /* Parse inner integrity size */ - innerIntegSz = FwLoadU16BE(plainSens); - innerStart = 2 + innerIntegSz; - - if (innerStart >= plainSensSz) { - #ifdef DEBUG_WOLFTPM - printf("fwTPM: Import inner integrity fail: " - "innerIntegSz=%d, innerStart=%d, plainSensSz=%d\n", - innerIntegSz, innerStart, plainSensSz); - #endif - rc = TPM_RC_INTEGRITY; - } - - /* AES-CFB decrypt inner sensitive using encryptionKey */ - if (rc == 0) { - encInner = plainSens + innerStart; - encInnerSz = plainSensSz - innerStart; - rc = TPM2_AesCfbDecrypt(encKeyBuf, encKeySz, - NULL, encInner, (word32)encInnerSz); - if (rc != 0) { - rc = TPM_RC_FAILURE; - } - } - - /* Verify inner integrity: Hash(decryptedSensitive || objectName) - * Per TPM 2.0 Part 1 Section 23.4 */ - if (rc == 0 && objDigestSz > 0 && - (UINT16)objDigestSz != innerIntegSz) { - rc = TPM_RC_INTEGRITY; - } - if (rc == 0) { - ihRc = wc_HashInit(innerHashCtx, objWcHash); - if (ihRc == 0) { - ihRc = wc_HashUpdate(innerHashCtx, objWcHash, - encInner, (word32)encInnerSz); - } - if (ihRc == 0) { - ihRc = wc_HashUpdate(innerHashCtx, objWcHash, - nameBuf, (word32)nameSz); - } - if (ihRc == 0) { - ihRc = wc_HashFinal(innerHashCtx, objWcHash, innerHash); - } - wc_HashFree(innerHashCtx, objWcHash); - if (ihRc != 0) { - rc = TPM_RC_FAILURE; - } - if (rc == 0) { - if (TPM2_ConstantCompare(innerHash, plainSens + 2, - innerIntegSz) != 0) { - rc = TPM_RC_INTEGRITY; - } - } - TPM2_ForceZero(innerHash, sizeof(innerHash)); + else if (rc == 0) { + if (dupSz > (UINT16)FWTPM_MAX_SENSITIVE_SIZE) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_3; } - - /* Shift decrypted sensitive to beginning of plainSens buffer */ - if (rc == 0) { - XMEMMOVE(plainSens, plainSens + innerStart, encInnerSz); - plainSensSz = encInnerSz; + else { + XMEMCPY(plainSens, dupBuf, dupSz); + plainSensSz = dupSz; } + } - #ifdef DEBUG_WOLFTPM - printf("fwTPM: Import inner decrypt: rc=0x%x, innerIntegSz=%d, " - "plainSensSz=%d, first4=0x%02x%02x%02x%02x\n", - rc, innerIntegSz, plainSensSz, - (rc == 0 && plainSensSz >= 4) ? plainSens[0] : 0, - (rc == 0 && plainSensSz >= 4) ? plainSens[1] : 0, - (rc == 0 && plainSensSz >= 4) ? plainSens[2] : 0, - (rc == 0 && plainSensSz >= 4) ? plainSens[3] : 0); - #endif + /* Remove the inner wrap: innerIntegrity || sensitive encrypted with + * encryptionKey, innerIntegrity = H_nameAlg(sensitive || Name) + * (Part 1 Sec.23.3.2.2) */ + if (rc == 0 && symAlg != TPM_ALG_NULL) { + rc = FwDupInnerUnwrap(objNameAlg, nameBuf, nameSz, encKeyBuf, + encKeySz, plainSens, plainSensSz, &innerOff); + rc = FwRcAddIndex(rc, TPM_RC_P | TPM_RC_3); } - (void)encKeyBuf; /* Parse decrypted sensitive area */ if (rc == 0) { - rc = FwImportParseSensitive(plainSens, plainSensSz, - &sensType, &importedAuth, + rc = FwImportParseSensitive(plainSens + innerOff, + plainSensSz - innerOff, &sensType, &importedAuth, + &sensSeed, &sensSeedSz, &primeSz, primeBuf, (int)FWTPM_MAX_DER_SIG_BUF); + rc = FwRcAddIndex(rc, TPM_RC_P | TPM_RC_3); } - /* Reconstruct private key from sensitive data */ - if (rc == 0 && primeSz > 0) { + if (rc == 0 && (objectPublic->publicArea.type == TPM_ALG_KEYEDHASH || + objectPublic->publicArea.type == TPM_ALG_SYMCIPHER)) { + rc = FwImportSymSensitive(&objectPublic->publicArea, sensType, + sensSeed, sensSeedSz, primeBuf, primeSz, + privKeyDer, (int)FWTPM_MAX_PRIVKEY_DER, &privKeyDerSz); + } + else if (rc == 0 && primeSz > 0) { rc = FwImportReconstructKey(objectPublic, sensType, primeBuf, primeSz, privKeyDer, (int)FWTPM_MAX_PRIVKEY_DER, &privKeyDerSz, &ctx->rng); } + /* Trailing zeros of an authValue are not significant; a duplicate + * carries it padded to the nameAlg digest size. */ + while (rc == 0 && importedAuth.size > 0 && + importedAuth.buffer[importedAuth.size - 1] == 0) { + importedAuth.size--; + } /* Wrap private for output, bound to the imported object's Name */ if (rc == 0) { @@ -9383,7 +9675,6 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_FREE_BUF(plainSens); TPM2_ForceZero(primeBuf, FWTPM_MAX_DER_SIG_BUF); FWTPM_FREE_BUF(primeBuf); - FWTPM_FREE_VAR(innerHashCtx); FWTPM_FREE_VAR(objectPublic); FWTPM_FREE_VAR(outPrivate); return rc; @@ -9412,6 +9703,12 @@ static TPM_RC FwCmd_Duplicate(FWTPM_CTX* ctx, TPM2_Packet* cmd, int seedSz = 0; FWTPM_DECLARE_BUF(encSeedBuf, FWTPM_MAX_PUB_BUF); int encSeedSz = 0; + byte innerKey[32]; + int innerKeySz = 0; + int innerDigestSz = 0; + int innerOff = 0; + int sensOff = 0; + int dataSz = 0; FWTPM_ALLOC_BUF(encSeedBuf, FWTPM_MAX_PUB_BUF); FWTPM_CALLOC_VAR(outPrivate, TPM2B_PRIVATE); @@ -9423,7 +9720,7 @@ static TPM_RC FwCmd_Duplicate(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Parse encryptionKeyIn (TPM2B) - save for inner wrapping */ TPM2_Packet_ParseU16(cmd, &encKeyInSz); if (encKeyInSz > sizeof(encKeyIn)) { - rc = TPM_RC_SIZE; + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; } else if (cmd->pos + encKeyInSz > cmdSize) { rc = TPM_RC_COMMAND_SIZE; @@ -9461,19 +9758,40 @@ static TPM_RC FwCmd_Duplicate(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPMA_OBJECT_fixedParent)) { rc = TPM_RC_ATTRIBUTES; } + if (rc == 0) { + innerDigestSz = TPM2_GetHashDigestSize(obj->pub.nameAlg); + if (innerDigestSz <= 0) { + rc = TPM_RC_TYPE | TPM_RC_1; + } + } /* Per TPM 2.0 Part 3 Section 13.1: encryptedDuplication needs both an - * inner wrap and an outer wrap to a new parent. The outer-wrap path below - * does not also apply the inner wrap, so no new parent is accepted yet. */ + * inner wrap and an outer wrap to a new parent. */ if (rc == 0 && (obj->pub.objectAttributes & TPMA_OBJECT_encryptedDuplication)) { if (symAlg == TPM_ALG_NULL) { - rc = TPM_RC_SYMMETRIC; + rc = TPM_RC_SYMMETRIC | TPM_RC_P | TPM_RC_2; } else if (newParentHandle == TPM_RH_NULL) { rc = TPM_RC_HIERARCHY | TPM_RC_2; } - else { - rc = TPM_RC_SYMMETRIC; + } + /* encryptionKeyIn is empty or the size of the inner wrap key */ + if (rc == 0 && symAlg == TPM_ALG_NULL) { + if (encKeyInSz != 0) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; + } + } + else if (rc == 0) { + innerKeySz = symKeyBits / 8; + if (symAlg != TPM_ALG_AES) { + rc = TPM_RC_SYMMETRIC | TPM_RC_P | TPM_RC_2; + } + else if (symKeyBits != 128 && symKeyBits != 192 && + symKeyBits != 256) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_2; + } + else if (encKeyInSz != 0 && (int)encKeyInSz != innerKeySz) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; } } @@ -9485,318 +9803,66 @@ static TPM_RC FwCmd_Duplicate(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } - /* Wrap the object's private data for export */ + /* Ensure object name is computed */ + if (rc == 0 && obj->name.size == 0) { + FwComputeObjectName(obj); + } + + /* The duplicate is built in place per TPM 2.0 Part 1 Section 23.3: + * [outer integrity] [inner integrity] TPM2B_SENSITIVE, each integrity + * a TPM2B_DIGEST present only when that wrap is applied. */ if (rc == 0) { if (newParent != NULL) { - /* Outer wrapping under new parent per TPM 2.0 Part 1 Section 24: - * 1. Encrypt seed to newParent's public key → outSymSeed - * 2. KDFa(seed, "STORAGE") → AES key - * 3. KDFa(seed, "INTEGRITY") → HMAC key - * 4. AES-CFB encrypt sensitive, HMAC for integrity */ - TPMI_ALG_HASH parentNameAlg = newParent->pub.nameAlg; - int digestSz = TPM2_GetHashDigestSize(parentNameAlg); - int symKeySz; - byte aesKey[FWTPM_MAX_SYM_KEY_SIZE]; - byte hmacKey[FWTPM_MAX_HMAC_KEY_SIZE]; - FWTPM_DECLARE_BUF(sensBuf, FWTPM_MAX_SENSITIVE_SIZE); - int sensSz = 0; - byte hmacDigest[FWTPM_MAX_HMAC_DIGEST_SIZE]; - int outPos = 0; - - FWTPM_ALLOC_BUF(sensBuf, FWTPM_MAX_SENSITIVE_SIZE); - - if (digestSz <= 0) { + innerOff = TPM2_GetHashDigestSize(newParent->pub.nameAlg); + if (innerOff <= 0) { rc = TPM_RC_HASH; } + innerOff += 2; + } + sensOff = innerOff; + if (symAlg != TPM_ALG_NULL) { + sensOff += 2 + innerDigestSz; + } + } + if (rc == 0) { + rc = FwDupMarshalSensitive(obj, outPrivate->buffer + sensOff, + (int)sizeof(outPrivate->buffer) - sensOff, &dataSz); + } - /* Get parent's symmetric key size from its public template */ - if (rc == 0) { - if (newParent->pub.type == TPM_ALG_RSA) { - symKeySz = (int)(newParent->pub.parameters.rsaDetail - .symmetric.keyBits.sym / 8); - } - else { - symKeySz = (int)(newParent->pub.parameters.eccDetail - .symmetric.keyBits.sym / 8); - } - if (symKeySz <= 0) { - symKeySz = 16; /* default AES-128 */ - } - if (symKeySz > FWTPM_MAX_SYM_KEY_SIZE) { - rc = TPM_RC_SYMMETRIC; - } - } - - /* Ensure object name is computed */ - if (rc == 0 && obj->name.size == 0) { - FwComputeObjectName(obj); - } - - /* Encrypt seed to newParent's public key */ - if (rc == 0) { - rc = FwEncryptSeed(ctx, newParent, - (const byte*)"DUPLICATE", 10, "DUPLICATE", - seedBuf, (int)sizeof(seedBuf), &seedSz, - encSeedBuf, FWTPM_MAX_PUB_BUF, &encSeedSz); - } - - /* KDFa for AES wrap key */ - if (rc == 0) { - rc = TPM2_KDFa_ex(parentNameAlg, seedBuf, seedSz, - "STORAGE", - (const byte*)obj->name.name, obj->name.size, - NULL, 0, aesKey, symKeySz); - if (rc != symKeySz) { - rc = TPM_RC_FAILURE; - } - else { - rc = 0; - } - } - - /* KDFa for HMAC integrity key */ - if (rc == 0) { - rc = TPM2_KDFa_ex(parentNameAlg, seedBuf, seedSz, - "INTEGRITY", NULL, 0, NULL, 0, - hmacKey, digestSz); - if (rc != digestSz) { - rc = TPM_RC_FAILURE; - } - else { - rc = 0; - } - } - - /* Extract raw sensitive component from DER key: - * RSA: prime p, ECC: private scalar d */ - if (rc == 0) { - byte sensComp[FWTPM_MAX_DER_SIG_BUF]; - int sensCompSz = 0; - #ifndef NO_RSA - if (obj->pub.type == TPM_ALG_RSA) { - FWTPM_DECLARE_VAR(tmpRsa, RsaKey); - FWTPM_ALLOC_VAR(tmpRsa, RsaKey); - rc = FwImportRsaKeyFromDer(obj, tmpRsa); - if (rc == 0) { - word32 pSz = (word32)sizeof(sensComp); - rc = mp_to_unsigned_bin(&tmpRsa->p, sensComp); - if (rc == 0) { - pSz = (word32)mp_unsigned_bin_size(&tmpRsa->p); - sensCompSz = (int)pSz; - } - else { - rc = TPM_RC_FAILURE; - } - wc_FreeRsaKey(tmpRsa); - } - else { - rc = TPM_RC_KEY; - } - FWTPM_FREE_VAR(tmpRsa); - } - else - #endif - #ifdef HAVE_ECC - if (obj->pub.type == TPM_ALG_ECC) { - FWTPM_DECLARE_VAR(tmpEcc, ecc_key); - FWTPM_ALLOC_VAR(tmpEcc, ecc_key); - if (rc == 0) { - rc = FwImportEccKeyFromDer(obj, tmpEcc); - } - if (rc == 0) { - word32 dSz = (word32)sizeof(sensComp); - rc = wc_ecc_export_private_only(tmpEcc, - sensComp, &dSz); - if (rc == 0) { - sensCompSz = (int)dSz; - } - else { - rc = TPM_RC_FAILURE; - } - wc_ecc_free(tmpEcc); - } - else { - rc = TPM_RC_KEY; - } - FWTPM_FREE_VAR(tmpEcc); - } - else - #endif - { - rc = TPM_RC_KEY; - } - - /* Marshal in standard TPM 2.0 format */ - if (rc == 0) { - sensSz = FwMarshalSensitiveStd(sensBuf, - FWTPM_MAX_SENSITIVE_SIZE, - obj->pub.type, &obj->authValue, - sensComp, sensCompSz); - if (sensSz < 0) { - rc = TPM_RC_SIZE; - } - } - TPM2_ForceZero(sensComp, sizeof(sensComp)); - } - - /* AES-CFB encrypt (zero IV) */ - if (rc == 0) { - rc = TPM2_AesCfbEncrypt(aesKey, symKeySz, - NULL, sensBuf, (word32)sensSz); - if (rc != 0) - rc = TPM_RC_FAILURE; - } - - /* HMAC(hmacKey, encSens || objectName) */ - if (rc == 0) { - rc = TPM2_HmacCompute(parentNameAlg, - hmacKey, (word32)digestSz, - sensBuf, (word32)sensSz, - (byte*)obj->name.name, obj->name.size, - hmacDigest, NULL); - if (rc != 0) - rc = TPM_RC_FAILURE; - } - - /* Pack outPrivate: integritySize(2) + integrity + encSens */ - if (rc == 0) { - FwStoreU16BE(outPrivate->buffer + outPos, (UINT16)digestSz); - outPos += 2; - XMEMCPY(outPrivate->buffer + outPos, hmacDigest, digestSz); - outPos += digestSz; - if (outPos + sensSz > (int)sizeof(outPrivate->buffer)) { - rc = TPM_RC_SIZE; - } - } - if (rc == 0) { - XMEMCPY(outPrivate->buffer + outPos, sensBuf, sensSz); - outPos += sensSz; - outPrivate->size = (UINT16)outPos; - } - - TPM2_ForceZero(seedBuf, sizeof(seedBuf)); - TPM2_ForceZero(aesKey, sizeof(aesKey)); - TPM2_ForceZero(hmacKey, sizeof(hmacKey)); - TPM2_ForceZero(sensBuf, FWTPM_MAX_SENSITIVE_SIZE); - FWTPM_FREE_BUF(sensBuf); - } - else if (symAlg != TPM_ALG_NULL) { - /* Inner wrapping with AES-CFB + HMAC integrity per - * TPM 2.0 Part 3 Section 12.5 */ - byte innerKey[32]; - int innerKeySz = symKeyBits / 8; - FWTPM_DECLARE_BUF(sensBuf, FWTPM_MAX_PRIVKEY_DER + 64); - int sensSz; - byte innerHmac[TPM_SHA256_DIGEST_SIZE]; - int innerHmacSz = TPM_SHA256_DIGEST_SIZE; - int outPos = 0; - - FWTPM_ALLOC_BUF(sensBuf, FWTPM_MAX_PRIVKEY_DER + 64); - - if (innerKeySz <= 0 || innerKeySz > (int)sizeof(innerKey)) { - rc = TPM_RC_KEY_SIZE; - } - - /* Get or generate inner key */ - if (rc == 0) { - if (encKeyInSz > 0) { - XMEMCPY(innerKey, encKeyIn, encKeyInSz); - innerKeySz = encKeyInSz; - } - else { - rc = wc_RNG_GenerateBlock(&ctx->rng, innerKey, - (word32)innerKeySz); - /* Save generated key for response encryptionKeyOut */ - if (rc == 0) { - XMEMCPY(encKeyIn, innerKey, innerKeySz); - } - } - } - - /* Marshal sensitive */ - if (rc == 0) { - sensSz = FwMarshalSensitive(sensBuf, - FWTPM_MAX_PRIVKEY_DER + 64, - obj->pub.type, &obj->authValue, - obj->privKey, obj->privKeySize); - if (sensSz < 0) { - rc = TPM_RC_SIZE; - } - } - - /* AES-CFB encrypt (zero IV) */ - if (rc == 0) { - rc = TPM2_AesCfbEncrypt(innerKey, innerKeySz, - NULL, sensBuf, (word32)sensSz); - if (rc != 0) - rc = TPM_RC_FAILURE; - } - - /* HMAC(innerKey, encSens || objectName) */ - if (rc == 0) { - if (obj->name.size == 0) { - FwComputeObjectName(obj); - } - rc = TPM2_HmacCompute(TPM_ALG_SHA256, - innerKey, (word32)innerKeySz, - sensBuf, (word32)sensSz, - (byte*)obj->name.name, obj->name.size, - innerHmac, NULL); - if (rc != 0) - rc = TPM_RC_FAILURE; - } - - /* Pack: integritySize(2) || integrity || encSens */ - if (rc == 0) { - FwStoreU16BE(outPrivate->buffer + outPos, (UINT16)innerHmacSz); - outPos += 2; - XMEMCPY(outPrivate->buffer + outPos, innerHmac, innerHmacSz); - outPos += innerHmacSz; - if (outPos + sensSz > (int)sizeof(outPrivate->buffer)) { - rc = TPM_RC_SIZE; - } - } - if (rc == 0) { - XMEMCPY(outPrivate->buffer + outPos, sensBuf, sensSz); - outPos += sensSz; - outPrivate->size = (UINT16)outPos; - } - - TPM2_ForceZero(innerKey, sizeof(innerKey)); - TPM2_ForceZero(sensBuf, FWTPM_MAX_PRIVKEY_DER + 64); - FWTPM_FREE_BUF(sensBuf); + /* Inner wrap with the caller's key or one generated here */ + if (rc == 0 && symAlg != TPM_ALG_NULL) { + if (encKeyInSz > 0) { + XMEMCPY(innerKey, encKeyIn, encKeyInSz); } - else { - /* symAlg == NULL and newParent == NULL: output plaintext - * sensitive (no wrapping) */ - int pos = 0; - if (obj->privKeySize + 6 + (int)obj->authValue.size > - (int)sizeof(outPrivate->buffer)) { - rc = TPM_RC_SIZE; - } - if (rc == 0) { - FwStoreU16BE(outPrivate->buffer + pos, obj->pub.type); - pos += 2; - FwStoreU16BE(outPrivate->buffer + pos, obj->authValue.size); - pos += 2; - if (obj->authValue.size > 0) { - XMEMCPY(outPrivate->buffer + pos, - obj->authValue.buffer, obj->authValue.size); - pos += obj->authValue.size; - } - FwStoreU16BE(outPrivate->buffer + pos, - (UINT16)obj->privKeySize); - pos += 2; - if (obj->privKeySize > 0) { - XMEMCPY(outPrivate->buffer + pos, obj->privKey, - obj->privKeySize); - pos += obj->privKeySize; - } - outPrivate->size = (UINT16)pos; - } + else if (wc_RNG_GenerateBlock(&ctx->rng, innerKey, + (word32)innerKeySz) != 0) { + rc = TPM_RC_FAILURE; + } + if (rc == 0) { + rc = FwDupInnerWrap(obj->pub.nameAlg, + (const byte*)obj->name.name, obj->name.size, + innerKey, innerKeySz, outPrivate->buffer + innerOff, dataSz); + dataSz += 2 + innerDigestSz; } } + /* Outer wrap: the seed is encrypted to newParent's public key */ + if (rc == 0 && newParent != NULL) { + rc = FwEncryptSeed(ctx, newParent, + (const byte*)"DUPLICATE", 10, "DUPLICATE", + seedBuf, (int)sizeof(seedBuf), &seedSz, + encSeedBuf, FWTPM_MAX_PUB_BUF, &encSeedSz); + if (rc == 0) { + rc = FwDupOuterWrap(newParent, seedBuf, seedSz, + (const byte*)obj->name.name, obj->name.size, + outPrivate->buffer, dataSz); + dataSz += innerOff; + } + } + if (rc == 0) { + outPrivate->size = (UINT16)dataSz; + } + if (rc == 0) { #ifdef DEBUG_WOLFTPM printf("fwTPM: Duplicate(obj=0x%x, newParent=0x%x)\n", @@ -9807,11 +9873,9 @@ static TPM_RC FwCmd_Duplicate(FWTPM_CTX* ctx, TPM2_Packet* cmd, paramStart = FwRspParamsBegin(rsp, cmdTag, ¶mSzPos); /* encryptionKeyOut (TPM2B) - return generated key if we made one */ - if (newParentHandle == TPM_RH_NULL && symAlg != TPM_ALG_NULL && - encKeyInSz == 0) { - int innerKeySz2 = symKeyBits / 8; - TPM2_Packet_AppendU16(rsp, (UINT16)innerKeySz2); - TPM2_Packet_AppendBytes(rsp, encKeyIn, innerKeySz2); + if (symAlg != TPM_ALG_NULL && encKeyInSz == 0) { + TPM2_Packet_AppendU16(rsp, (UINT16)innerKeySz); + TPM2_Packet_AppendBytes(rsp, innerKey, innerKeySz); } else { TPM2_Packet_AppendU16(rsp, 0); @@ -9836,9 +9900,10 @@ static TPM_RC FwCmd_Duplicate(FWTPM_CTX* ctx, TPM2_Packet* cmd, } TPM2_ForceZero(encKeyIn, sizeof(encKeyIn)); - /* outPrivate is the encrypted/HMAC-protected blob — no zero needed. */ + TPM2_ForceZero(innerKey, sizeof(innerKey)); TPM2_ForceZero(seedBuf, sizeof(seedBuf)); FWTPM_FREE_BUF(encSeedBuf); + TPM2_ForceZero(outPrivate, sizeof(*outPrivate)); FWTPM_FREE_VAR(outPrivate); return rc; } diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 87af4f578..93124d928 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -3276,7 +3276,7 @@ TPM_RC FwImportVerifyAndDecrypt( /* Parse duplicate structure */ if (dupSz < 4) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; } if (rc == 0) { integritySize = FwLoadU16BE(dupBuf); @@ -3286,7 +3286,7 @@ TPM_RC FwImportVerifyAndDecrypt( } } if (rc == 0 && dupPos + integritySize > (int)dupSz) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; } if (rc == 0) { integrity = dupBuf + dupPos; @@ -3294,7 +3294,7 @@ TPM_RC FwImportVerifyAndDecrypt( encSens = dupBuf + dupPos; encSensSz = (int)dupSz - dupPos; if (encSensSz <= 0) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; } } @@ -3379,6 +3379,7 @@ TPM_RC FwImportVerifyAndDecrypt( TPM_RC FwImportParseSensitive( const byte* plainSens, int plainSensSz, UINT16* sensType, TPM2B_AUTH* importedAuth, + const byte** seedOut, UINT16* seedSzOut, UINT16* primeSzOut, byte* primeBuf, int primeBufSz) { TPM_RC rc = TPM_RC_SUCCESS; @@ -3386,23 +3387,23 @@ TPM_RC FwImportParseSensitive( UINT16 totalSensSize, avSz, svSz, primeSz; if (sp + 2 > plainSensSz) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; } if (rc == 0) { totalSensSize = FwLoadU16BE(plainSens + sp); sp += 2; - if (totalSensSize + 2 > (UINT16)plainSensSz) { + if ((int)totalSensSize + 2 != plainSensSz) { return TPM_RC_SIZE; } if (sp + 2 > plainSensSz) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; } } if (rc == 0) { *sensType = FwLoadU16BE(plainSens + sp); sp += 2; if (sp + 2 > plainSensSz) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; } } @@ -3419,7 +3420,7 @@ TPM_RC FwImportParseSensitive( importedAuth->size = avSz; if (avSz > 0) { if (sp + avSz > plainSensSz) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; } if (rc == 0) { XMEMCPY(importedAuth->buffer, plainSens + sp, avSz); @@ -3428,27 +3429,30 @@ TPM_RC FwImportParseSensitive( } } - /* seedValue (skip) */ + /* seedValue */ if (rc == 0) { if (sp + 2 > plainSensSz) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; } } if (rc == 0) { svSz = FwLoadU16BE(plainSens + sp); sp += 2; if (sp + svSz > plainSensSz) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; } } if (rc == 0) { + *seedOut = plainSens + sp; + *seedSzOut = svSz; sp += svSz; if (sp + 2 > plainSensSz) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; } } - /* sensitive (prime q for RSA, private scalar d for ECC) */ + /* sensitive (a prime for RSA, private scalar d for ECC, the key for + * KEYEDHASH and SYMCIPHER) */ if (rc == 0) { primeSz = FwLoadU16BE(plainSens + sp); sp += 2; @@ -3457,7 +3461,10 @@ TPM_RC FwImportParseSensitive( } } if (rc == 0 && sp + primeSz > plainSensSz) { - rc = TPM_RC_FAILURE; + rc = TPM_RC_INSUFFICIENT; + } + if (rc == 0 && sp + primeSz != plainSensSz) { + rc = TPM_RC_SIZE; } if (rc == 0) { XMEMCPY(primeBuf, plainSens + sp, primeSz); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 43d6f964c..689b2bff5 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -18487,13 +18487,13 @@ static void test_fwtpm_rsa_credential_oaep_label(void) #endif /* !NO_RSA && WOLFSSL_KEY_GEN && !FWTPM_NO_CREDENTIAL */ #if !defined(FWTPM_NO_KEY_MIGRATION) && !defined(FWTPM_NO_POLICY) -static TPM_RC SendDuplicateToNullCmd(FWTPM_CTX* ctx, UINT32 objH, - UINT32 sessH, UINT16 symAlg) +static TPM_RC SendDuplicateCmd(FWTPM_CTX* ctx, UINT32 objH, + UINT32 newParentH, UINT32 sessH, UINT16 symAlg) { int pos, rspSize = 0; pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Duplicate); PutU32BE(gCmd + pos, objH); pos += 4; - PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; /* newParentHandle */ + PutU32BE(gCmd + pos, newParentH); pos += 4; pos = AppendAuth(gCmd, pos, sessH, TPMA_SESSION_continueSession, NULL, 0); PutU16BE(gCmd + pos, 0); pos += 2; /* encryptionKeyIn */ @@ -18507,6 +18507,12 @@ static TPM_RC SendDuplicateToNullCmd(FWTPM_CTX* ctx, UINT32 objH, return GetRspRC(gRsp); } +static TPM_RC SendDuplicateToNullCmd(FWTPM_CTX* ctx, UINT32 objH, + UINT32 sessH, UINT16 symAlg) +{ + return SendDuplicateCmd(ctx, objH, TPM_RH_NULL, sessH, symAlg); +} + /* An encryptedDuplication object may leave the TPM only under both an inner * symmetric wrap and an outer wrap to a new parent (Part 3 Sec.13.1). */ static void test_fwtpm_duplicate_encrypted_needs_new_parent(void) @@ -18555,7 +18561,7 @@ static void test_fwtpm_duplicate_encrypted_needs_new_parent(void) sizeof(obj->pub.authPolicy)); AssertIntEQ(SendDuplicateToNullCmd(&ctx, keyH, sessH, TPM_ALG_NULL), - TPM_RC_SYMMETRIC); + TPM_RC_SYMMETRIC | TPM_RC_P | TPM_RC_2); AssertIntEQ(SendDuplicateToNullCmd(&ctx, keyH, sessH, TPM_ALG_AES), TPM_RC_HIERARCHY | TPM_RC_2); @@ -18615,6 +18621,927 @@ static void test_fwtpm_duplicate_needs_command_code(void) fwtpm_pass("Duplicate needs PolicyCommandCode:", 0); } +#define DUP_INNER_CALLER 0x1 +#define DUP_INNER_TPM 0x2 +#define DUP_OUTER 0x4 + +/* userWithAuth | noDA | sign, plus sensitiveDataOrigin for generated keys + * and decrypt for a symmetric cipher key */ +#define DUP_ATTR_HMAC 0x00040440 +#define DUP_ATTR_SIGN 0x00040460 +#define DUP_ATTR_SYM 0x00060460 + +static const byte gDupAuth[] = "dupauth"; +static const byte gDupHmacKey[20] = { + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b +}; +static const byte gDupInnerKey[32] = { + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f +}; + +/* objectPublic with its size prefix and the Duplicate / Import outputs */ +typedef struct DupBlob { + byte pub[640]; + UINT16 pubSz; + byte encKey[32]; + UINT16 encKeySz; + byte dup[1024]; + UINT16 dupSz; + byte seed[640]; + UINT16 seedSz; + byte priv[sizeof(TPM2B_PRIVATE)]; + UINT16 privSz; +} DupBlob; +static DupBlob gDup; + +/* A primary that may be duplicated: fixedTPM and fixedParent clear, + * authValue gDupAuth and authPolicy PolicyCommandCode(TPM_CC_Duplicate). + * KEYEDHASH is an HMAC-SHA256 key holding gDupHmacKey, SYMCIPHER an AES-128 + * key; ECC and RSA are signing keys. Its TPM2B_PUBLIC is copied to blob. */ +static UINT32 DupCreateObject(FWTPM_CTX* ctx, TPM_ALG_ID type, + UINT32 attributes, DupBlob* blob) +{ + byte policyIn[WC_SHA256_DIGEST_SIZE + 8]; + byte policy[WC_SHA256_DIGEST_SIZE]; + int pos, rspSize = 0, sensStart, pubStart; + + memset(policyIn, 0, sizeof(policyIn)); + PutU32BE(policyIn + WC_SHA256_DIGEST_SIZE, TPM_CC_PolicyCommandCode); + PutU32BE(policyIn + WC_SHA256_DIGEST_SIZE + 4, TPM_CC_Duplicate); + AssertIntEQ(wc_Sha256Hash(policyIn, sizeof(policyIn), policy), 0); + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_CreatePrimary); + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + sensStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, sizeof(gDupAuth) - 1); pos += 2; + memcpy(gCmd + pos, gDupAuth, sizeof(gDupAuth) - 1); + pos += sizeof(gDupAuth) - 1; + if (type == TPM_ALG_KEYEDHASH) { + PutU16BE(gCmd + pos, sizeof(gDupHmacKey)); pos += 2; + memcpy(gCmd + pos, gDupHmacKey, sizeof(gDupHmacKey)); + pos += sizeof(gDupHmacKey); + } + else { + PutU16BE(gCmd + pos, 0); pos += 2; + } + PutU16BE(gCmd + sensStart, (UINT16)(pos - sensStart - 2)); + pubStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, type); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + pos, attributes); pos += 4; + PutU16BE(gCmd + pos, WC_SHA256_DIGEST_SIZE); pos += 2; + memcpy(gCmd + pos, policy, WC_SHA256_DIGEST_SIZE); + pos += WC_SHA256_DIGEST_SIZE; + if (type == TPM_ALG_KEYEDHASH) { + PutU16BE(gCmd + pos, TPM_ALG_HMAC); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU16BE(gCmd + pos, 0); pos += 2; /* unique */ + } + else if (type == TPM_ALG_SYMCIPHER) { + PutU16BE(gCmd + pos, TPM_ALG_AES); pos += 2; + PutU16BE(gCmd + pos, 128); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_CFB); pos += 2; + PutU16BE(gCmd + pos, 0); pos += 2; /* unique */ + } + else if (type == TPM_ALG_ECC) { + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* symmetric */ + PutU16BE(gCmd + pos, TPM_ALG_ECDSA); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU16BE(gCmd + pos, TPM_ECC_NIST_P256); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* kdf */ + PutU16BE(gCmd + pos, 0); pos += 2; /* unique.x */ + PutU16BE(gCmd + pos, 0); pos += 2; /* unique.y */ + } + else { + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* symmetric */ + PutU16BE(gCmd + pos, TPM_ALG_RSASSA); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU16BE(gCmd + pos, 2048); pos += 2; + PutU32BE(gCmd + pos, 0); pos += 4; /* exponent */ + PutU16BE(gCmd + pos, 0); pos += 2; /* unique */ + } + PutU16BE(gCmd + pubStart, (UINT16)(pos - pubStart - 2)); + PutU16BE(gCmd + pos, 0); pos += 2; /* outsideInfo */ + PutU32BE(gCmd + pos, 0); pos += 4; /* creationPCR */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + pos = TPM2_HEADER_SIZE + 4 + 4; + blob->pubSz = (UINT16)(2 + GetU16BE(gRsp + pos)); + AssertIntLE(blob->pubSz, sizeof(blob->pub)); + memcpy(blob->pub, gRsp + pos, blob->pubSz); + return GetU32BE(gRsp + TPM2_HEADER_SIZE); +} + +/* Duplicate objH on a new policy session bound to TPM_CC_Duplicate and copy + * encryptionKeyOut, duplicate and outSymSeed to blob */ +static TPM_RC DupSend(FWTPM_CTX* ctx, UINT32 objH, UINT32 newParentH, + const byte* key, UINT16 keySz, UINT16 symAlg, UINT16 keyBits, + DupBlob* blob) +{ + UINT32 sessH = StartSessionHelper(ctx, TPM_SE_POLICY); + int pos, rspSize = 0; + TPM_RC rc; + + AssertIntNE(sessH, 0); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_PolicyCommandCode); + PutU32BE(gCmd + pos, sessH); pos += 4; + PutU32BE(gCmd + pos, TPM_CC_Duplicate); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Duplicate); + PutU32BE(gCmd + pos, objH); pos += 4; + PutU32BE(gCmd + pos, newParentH); pos += 4; + pos = AppendAuth(gCmd, pos, sessH, TPMA_SESSION_continueSession, + NULL, 0); + PutU16BE(gCmd + pos, keySz); pos += 2; + if (keySz > 0) { + memcpy(gCmd + pos, key, keySz); pos += keySz; + } + PutU16BE(gCmd + pos, symAlg); pos += 2; + if (symAlg != TPM_ALG_NULL) { + PutU16BE(gCmd + pos, keyBits); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_CFB); pos += 2; + } + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + rc = GetRspRC(gRsp); + if (rc == TPM_RC_SUCCESS) { + pos = TPM2_HEADER_SIZE + 4; + blob->encKeySz = GetU16BE(gRsp + pos); pos += 2; + AssertIntLE(blob->encKeySz, sizeof(blob->encKey)); + memcpy(blob->encKey, gRsp + pos, blob->encKeySz); + pos += blob->encKeySz; + blob->dupSz = GetU16BE(gRsp + pos); pos += 2; + AssertIntLE(blob->dupSz, sizeof(blob->dup)); + memcpy(blob->dup, gRsp + pos, blob->dupSz); pos += blob->dupSz; + blob->seedSz = GetU16BE(gRsp + pos); pos += 2; + AssertIntLE(blob->seedSz, sizeof(blob->seed)); + memcpy(blob->seed, gRsp + pos, blob->seedSz); + } + FlushHandle(ctx, sessH); + return rc; +} + +/* Import the duplicate in blob under parentH; outPrivate is kept in blob */ +static TPM_RC DupImport(FWTPM_CTX* ctx, UINT32 parentH, const byte* key, + UINT16 keySz, UINT16 symAlg, UINT16 keyBits, DupBlob* blob) +{ + int pos, rspSize = 0; + TPM_RC rc; + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Import); + PutU32BE(gCmd + pos, parentH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, keySz); pos += 2; + if (keySz > 0) { + memcpy(gCmd + pos, key, keySz); pos += keySz; + } + memcpy(gCmd + pos, blob->pub, blob->pubSz); pos += blob->pubSz; + PutU16BE(gCmd + pos, blob->dupSz); pos += 2; + memcpy(gCmd + pos, blob->dup, blob->dupSz); pos += blob->dupSz; + PutU16BE(gCmd + pos, blob->seedSz); pos += 2; + memcpy(gCmd + pos, blob->seed, blob->seedSz); pos += blob->seedSz; + PutU16BE(gCmd + pos, symAlg); pos += 2; + if (symAlg != TPM_ALG_NULL) { + PutU16BE(gCmd + pos, keyBits); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_CFB); pos += 2; + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + rc = GetRspRC(gRsp); + if (rc == TPM_RC_SUCCESS) { + pos = TPM2_HEADER_SIZE + 4; + blob->privSz = GetU16BE(gRsp + pos); pos += 2; + AssertIntLE(blob->privSz, sizeof(blob->priv)); + memcpy(blob->priv, gRsp + pos, blob->privSz); + } + return rc; +} + +/* Load the imported object under parentH and return its handle */ +static UINT32 DupLoad(FWTPM_CTX* ctx, UINT32 parentH, const DupBlob* blob) +{ + int pos, rspSize = 0; + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Load); + PutU32BE(gCmd + pos, parentH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, blob->privSz); pos += 2; + memcpy(gCmd + pos, blob->priv, blob->privSz); pos += blob->privSz; + memcpy(gCmd + pos, blob->pub, blob->pubSz); pos += blob->pubSz; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + return GetU32BE(gRsp + TPM2_HEADER_SIZE); +} + +/* The imported object still holds the sensitive area: an HMAC key matches + * wolfCrypt under gDupHmacKey, a symmetric cipher key equals the one in the + * original object origH, and a signature made with an asymmetric key + * verifies under origH. The commands authorize with gDupAuth. */ +static void DupCheckUse(FWTPM_CTX* ctx, TPM_ALG_ID type, UINT32 keyH, + UINT32 origH) +{ + FWTPM_Object* key = NULL; + FWTPM_Object* orig = NULL; + byte digest[WC_SHA256_DIGEST_SIZE]; + byte sig[600]; + int i, pos, rspSize = 0; + UINT32 sigSz; + + memset(digest, 0x5C, sizeof(digest)); + if (type == TPM_ALG_KEYEDHASH) { +#ifndef FWTPM_NO_HASH_CMDS + Hmac hmac; + + AssertIntEQ(wc_HmacInit(&hmac, NULL, INVALID_DEVID), 0); + AssertIntEQ(wc_HmacSetKey(&hmac, WC_SHA256, gDupHmacKey, + sizeof(gDupHmacKey)), 0); + AssertIntEQ(wc_HmacUpdate(&hmac, (const byte*)"abc", 3), 0); + AssertIntEQ(wc_HmacFinal(&hmac, digest), 0); + wc_HmacFree(&hmac); + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_HMAC); + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, gDupAuth, sizeof(gDupAuth) - 1); + PutU16BE(gCmd + pos, 3); pos += 2; + memcpy(gCmd + pos, "abc", 3); pos += 3; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4), sizeof(digest)); + AssertIntEQ(memcmp(gRsp + TPM2_HEADER_SIZE + 6, digest, + sizeof(digest)), 0); +#endif + } + else if (type == TPM_ALG_SYMCIPHER) { + for (i = 0; i < FWTPM_MAX_OBJECTS; i++) { + if (ctx->objects[i].used && ctx->objects[i].handle == keyH) { + key = &ctx->objects[i]; + } + if (ctx->objects[i].used && ctx->objects[i].handle == origH) { + orig = &ctx->objects[i]; + } + } + AssertNotNull(key); + AssertNotNull(orig); + AssertIntEQ(key->privKeySize, AES_128_KEY_SIZE); + AssertIntEQ(orig->privKeySize, AES_128_KEY_SIZE); + AssertIntEQ(memcmp(key->privKey, orig->privKey, AES_128_KEY_SIZE), + 0); + } + else { + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Sign); + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, gDupAuth, sizeof(gDupAuth) - 1); + PutU16BE(gCmd + pos, sizeof(digest)); pos += 2; + memcpy(gCmd + pos, digest, sizeof(digest)); pos += sizeof(digest); + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* use key scheme */ + PutU16BE(gCmd + pos, TPM_ST_HASHCHECK); pos += 2; + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + sigSz = GetU32BE(gRsp + TPM2_HEADER_SIZE); + AssertIntLE(sigSz, sizeof(sig)); + memcpy(sig, gRsp + TPM2_HEADER_SIZE + 4, sigSz); + + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_VerifySignature); + PutU32BE(gCmd + pos, origH); pos += 4; + PutU16BE(gCmd + pos, sizeof(digest)); pos += 2; + memcpy(gCmd + pos, digest, sizeof(digest)); pos += sizeof(digest); + memcpy(gCmd + pos, sig, sigSz); pos += (int)sigSz; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + } +} + +/* Duplicate an object of objType with the wraps in mode, Import it under + * the parent again, Load it and use it. */ +static void DupRoundTrip(FWTPM_CTX* ctx, TPM_ALG_ID objType, + TPM_ALG_ID parentAlg, int mode, UINT16 keyBits) +{ + UINT32 parentH, objH, newH; + UINT16 symAlg = (mode & (DUP_INNER_CALLER | DUP_INNER_TPM)) ? + TPM_ALG_AES : TPM_ALG_NULL; + UINT16 keySz = (mode & DUP_INNER_CALLER) ? (UINT16)(keyBits / 8) : 0; + const byte* importKey = gDupInnerKey; + + parentH = CreatePrimaryHelper(ctx, parentAlg); + AssertIntNE(parentH, 0); + objH = DupCreateObject(ctx, objType, + (objType == TPM_ALG_KEYEDHASH) ? DUP_ATTR_HMAC : + (objType == TPM_ALG_SYMCIPHER) ? DUP_ATTR_SYM : DUP_ATTR_SIGN, + &gDup); + + AssertIntEQ(DupSend(ctx, objH, + (mode & DUP_OUTER) ? parentH : (TPM_HANDLE)TPM_RH_NULL, + gDupInnerKey, keySz, + symAlg, keyBits, &gDup), TPM_RC_SUCCESS); + AssertIntGT(gDup.dupSz, 0); + if (mode & DUP_OUTER) { + AssertIntGT(gDup.seedSz, 0); + } + else { + AssertIntEQ(gDup.seedSz, 0); + } + if (mode & DUP_INNER_TPM) { + AssertIntEQ(gDup.encKeySz, keyBits / 8); + importKey = gDup.encKey; + keySz = gDup.encKeySz; + } + else { + AssertIntEQ(gDup.encKeySz, 0); + } + + AssertIntEQ(DupImport(ctx, parentH, importKey, keySz, symAlg, keyBits, + &gDup), TPM_RC_SUCCESS); + newH = DupLoad(ctx, parentH, &gDup); + DupCheckUse(ctx, objType, newH, objH); + + FlushHandle(ctx, newH); + FlushHandle(ctx, objH); + FlushHandle(ctx, parentH); +} + +/* Duplicate and Import agree on the Part 1 Sec.23.3 blob for no wrap, the + * inner wrap alone, the outer wrap alone and both, with a caller-supplied + * and a TPM-generated inner key. */ +static void test_fwtpm_duplicate_import_roundtrip(void) +{ + FWTPM_CTX ctx; + static const int modes[] = { + 0, DUP_INNER_CALLER, DUP_INNER_TPM, DUP_OUTER, + DUP_INNER_CALLER | DUP_OUTER, DUP_INNER_TPM | DUP_OUTER + }; + int i; +#ifdef HAVE_ECC + TPM_ALG_ID parentAlg = TPM_ALG_ECC; +#else + TPM_ALG_ID parentAlg = TPM_ALG_RSA; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + for (i = 0; i < (int)(sizeof(modes) / sizeof(modes[0])); i++) { + DupRoundTrip(&ctx, TPM_ALG_KEYEDHASH, parentAlg, modes[i], 128); + } + DupRoundTrip(&ctx, TPM_ALG_KEYEDHASH, parentAlg, + DUP_INNER_CALLER | DUP_OUTER, 256); + DupRoundTrip(&ctx, TPM_ALG_SYMCIPHER, parentAlg, DUP_OUTER, 128); + DupRoundTrip(&ctx, TPM_ALG_SYMCIPHER, parentAlg, + DUP_INNER_TPM | DUP_OUTER, 128); +#ifdef HAVE_ECC + DupRoundTrip(&ctx, TPM_ALG_ECC, TPM_ALG_ECC, DUP_INNER_CALLER, 128); + DupRoundTrip(&ctx, TPM_ALG_ECC, TPM_ALG_ECC, DUP_INNER_TPM | DUP_OUTER, + 128); +#endif +#if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) + DupRoundTrip(&ctx, TPM_ALG_KEYEDHASH, TPM_ALG_RSA, + DUP_INNER_TPM | DUP_OUTER, 128); + DupRoundTrip(&ctx, TPM_ALG_RSA, TPM_ALG_RSA, + DUP_INNER_CALLER | DUP_OUTER, 128); +#endif + + FWTPM_Cleanup(&ctx); + fwtpm_pass("Duplicate/Import round trip:", 0); +} + +/* Rewrap replaces the outer wrap only: an inner and outer wrapped duplicate + * moved to a second parent imports there with the inner key. */ +static void test_fwtpm_duplicate_rewrap_import(void) +{ + FWTPM_CTX ctx; + FWTPM_Object* obj = NULL; + UINT32 oldH, newH, objH, keyH; + byte name[sizeof(TPM2B_NAME)]; + UINT16 nameSz; + int i, pos, rspSize = 0; +#ifdef HAVE_ECC + TPM_ALG_ID parentAlg = TPM_ALG_ECC; +#else + TPM_ALG_ID parentAlg = TPM_ALG_RSA; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + oldH = CreatePrimaryHelper(&ctx, parentAlg); + AssertIntNE(oldH, 0); + objH = DupCreateObject(&ctx, TPM_ALG_KEYEDHASH, DUP_ATTR_HMAC, &gDup); + for (i = 0; i < FWTPM_MAX_OBJECTS; i++) { + if (ctx.objects[i].used && ctx.objects[i].handle == objH) { + obj = &ctx.objects[i]; + } + } + AssertNotNull(obj); + nameSz = obj->name.size; + AssertIntGT(nameSz, 0); + memcpy(name, obj->name.name, nameSz); + + AssertIntEQ(DupSend(&ctx, objH, oldH, gDupInnerKey, 16, TPM_ALG_AES, 128, + &gDup), TPM_RC_SUCCESS); + FlushHandle(&ctx, objH); +#if defined(HAVE_ECC) && !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) + newH = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); +#else + newH = CreatePrimaryHelper(&ctx, parentAlg); +#endif + AssertIntNE(newH, 0); + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Rewrap); + PutU32BE(gCmd + pos, oldH); pos += 4; + PutU32BE(gCmd + pos, newH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, gDup.dupSz); pos += 2; + memcpy(gCmd + pos, gDup.dup, gDup.dupSz); pos += gDup.dupSz; + PutU16BE(gCmd + pos, nameSz); pos += 2; + memcpy(gCmd + pos, name, nameSz); pos += nameSz; + PutU16BE(gCmd + pos, gDup.seedSz); pos += 2; + memcpy(gCmd + pos, gDup.seed, gDup.seedSz); pos += gDup.seedSz; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pos = TPM2_HEADER_SIZE + 4; + gDup.dupSz = GetU16BE(gRsp + pos); pos += 2; + AssertIntLE(gDup.dupSz, sizeof(gDup.dup)); + memcpy(gDup.dup, gRsp + pos, gDup.dupSz); pos += gDup.dupSz; + gDup.seedSz = GetU16BE(gRsp + pos); pos += 2; + AssertIntLE(gDup.seedSz, sizeof(gDup.seed)); + memcpy(gDup.seed, gRsp + pos, gDup.seedSz); + FlushHandle(&ctx, oldH); + + AssertIntEQ(DupImport(&ctx, newH, gDupInnerKey, 16, TPM_ALG_AES, 128, + &gDup), TPM_RC_SUCCESS); + keyH = DupLoad(&ctx, newH, &gDup); + DupCheckUse(&ctx, TPM_ALG_KEYEDHASH, keyH, 0); + + FlushHandle(&ctx, keyH); + FlushHandle(&ctx, newH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Duplicate/Rewrap/Import inner wrap:", 0); +} + +/* The size and attribute rules of Part 3 Sec.13.1 and Sec.13.3 for the + * inner wrap key, and the integrity checks of both wraps. */ +static void test_fwtpm_duplicate_import_rejections(void) +{ + FWTPM_CTX ctx; + UINT32 parentH, objH; + TPM_RC rc; + byte wrongKey[16]; +#ifdef HAVE_ECC + TPM_ALG_ID parentAlg = TPM_ALG_ECC; +#else + TPM_ALG_ID parentAlg = TPM_ALG_RSA; +#endif + + memset(&ctx, 0, sizeof(ctx)); + memset(wrongKey, 0xEE, sizeof(wrongKey)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + parentH = CreatePrimaryHelper(&ctx, parentAlg); + AssertIntNE(parentH, 0); + objH = DupCreateObject(&ctx, TPM_ALG_KEYEDHASH, DUP_ATTR_HMAC, &gDup); + + /* encryptionKeyIn without an inner wrap, of the wrong size, and a key + * size that is not an AES key size */ + AssertIntEQ(DupSend(&ctx, objH, parentH, gDupInnerKey, 16, TPM_ALG_NULL, + 0, &gDup), TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(DupSend(&ctx, objH, parentH, gDupInnerKey, 24, TPM_ALG_AES, + 128, &gDup), TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(DupSend(&ctx, objH, TPM_RH_NULL, gDupInnerKey, 32, + TPM_ALG_AES, 128, &gDup), TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(DupSend(&ctx, objH, parentH, NULL, 0, TPM_ALG_AES, 100, + &gDup), TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + + /* Inner wrap alone: a changed octet fails the inner integrity */ + AssertIntEQ(DupSend(&ctx, objH, TPM_RH_NULL, gDupInnerKey, 16, + TPM_ALG_AES, 128, &gDup), TPM_RC_SUCCESS); + gDup.dup[gDup.dupSz - 1] ^= 0x01; + AssertIntEQ(DupImport(&ctx, parentH, gDupInnerKey, 16, TPM_ALG_AES, 128, + &gDup), TPM_RC_INTEGRITY | TPM_RC_P | TPM_RC_3); + gDup.dup[gDup.dupSz - 1] ^= 0x01; + + /* The wrong inner key leaves no valid integrity value */ + rc = DupImport(&ctx, parentH, wrongKey, 16, TPM_ALG_AES, 128, &gDup); + AssertTrue(rc == (TPM_RC_INTEGRITY | TPM_RC_P | TPM_RC_3) || + rc == (TPM_RC_SIZE | TPM_RC_P | TPM_RC_3) || + rc == (TPM_RC_INSUFFICIENT | TPM_RC_P | TPM_RC_3)); + + /* encryptionKey of the wrong size, and without an inner wrap */ + AssertIntEQ(DupImport(&ctx, parentH, gDupInnerKey, 24, TPM_ALG_AES, 128, + &gDup), TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_AES, 128, + &gDup), TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(DupImport(&ctx, parentH, gDupInnerKey, 16, TPM_ALG_NULL, 0, + &gDup), TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(DupImport(&ctx, parentH, gDupInnerKey, 16, TPM_ALG_AES, 128, + &gDup), TPM_RC_SUCCESS); + + /* Both wraps: a changed octet fails the outer integrity */ + AssertIntEQ(DupSend(&ctx, objH, parentH, gDupInnerKey, 16, TPM_ALG_AES, + 128, &gDup), TPM_RC_SUCCESS); + gDup.dup[gDup.dupSz - 1] ^= 0x01; + AssertIntEQ(DupImport(&ctx, parentH, gDupInnerKey, 16, TPM_ALG_AES, 128, + &gDup), TPM_RC_INTEGRITY | TPM_RC_P | TPM_RC_3); + gDup.dup[gDup.dupSz - 1] ^= 0x01; + rc = DupImport(&ctx, parentH, wrongKey, 16, TPM_ALG_AES, 128, &gDup); + AssertTrue(rc == (TPM_RC_INTEGRITY | TPM_RC_P | TPM_RC_3) || + rc == (TPM_RC_SIZE | TPM_RC_P | TPM_RC_3) || + rc == (TPM_RC_INSUFFICIENT | TPM_RC_P | TPM_RC_3)); + AssertIntEQ(DupImport(&ctx, parentH, gDupInnerKey, 16, TPM_ALG_AES, 128, + &gDup), TPM_RC_SUCCESS); + FlushHandle(&ctx, objH); + + /* An encryptedDuplication object leaves and arrives under both wraps */ + objH = DupCreateObject(&ctx, TPM_ALG_KEYEDHASH, + DUP_ATTR_HMAC | TPMA_OBJECT_encryptedDuplication, &gDup); + AssertIntEQ(DupSend(&ctx, objH, parentH, NULL, 0, TPM_ALG_NULL, 0, + &gDup), TPM_RC_SYMMETRIC | TPM_RC_P | TPM_RC_2); + AssertIntEQ(DupSend(&ctx, objH, TPM_RH_NULL, NULL, 0, TPM_ALG_AES, 128, + &gDup), TPM_RC_HIERARCHY | TPM_RC_2); + AssertIntEQ(DupSend(&ctx, objH, parentH, NULL, 0, TPM_ALG_AES, 128, + &gDup), TPM_RC_SUCCESS); + AssertIntEQ(gDup.encKeySz, 16); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_1); + AssertIntEQ(DupImport(&ctx, parentH, gDup.encKey, 16, TPM_ALG_AES, 128, + &gDup), TPM_RC_SUCCESS); + gDup.seedSz = 0; + AssertIntEQ(DupImport(&ctx, parentH, gDup.encKey, 16, TPM_ALG_AES, 128, + &gDup), TPM_RC_ATTRIBUTES | TPM_RC_P | TPM_RC_4); + + FlushHandle(&ctx, objH); + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Duplicate/Import wrap rejections:", 0); +} + +/* A duplicate built here from fixed inputs per Part 1 Sec.23.3, with a + * seedValue and a padded authValue as another TPM produces them, imports + * and works: sensitive = TPM2B_SENSITIVE, inner = AES-CFB(innerKey, + * H(sensitive || Name) || sensitive), outer = HMAC(KDFa(seed, "INTEGRITY"), + * enc || Name) || enc with enc = AES-CFB(KDFa(seed, "STORAGE", Name), + * inner). */ +static void test_fwtpm_import_known_duplicate(void) +{ + FWTPM_CTX ctx; + FWTPM_Object* parent = NULL; + UINT32 parentH, keyH; + Aes aes; + Hmac hmac; + wc_HashAlg hash; + byte iv[AES_BLOCK_SIZE]; + byte seedValue[WC_SHA256_DIGEST_SIZE]; + byte name[2 + WC_SHA256_DIGEST_SIZE]; + byte seed[FWTPM_MAX_HMAC_DIGEST_SIZE]; + byte symKey[AES_128_KEY_SIZE]; + byte hmacKey[WC_SHA256_DIGEST_SIZE]; + byte innerDigest[WC_SHA256_DIGEST_SIZE]; + byte plain[128]; + /* SHA-256 of the inner wrapped blob, computed outside wolfCrypt */ + static const byte innerExpect[WC_SHA256_DIGEST_SIZE] = { + 0xf8, 0xcc, 0x57, 0xc4, 0x3c, 0xf6, 0x47, 0x85, + 0xef, 0x3d, 0x58, 0x1a, 0xe6, 0x39, 0x61, 0xd0, + 0x0e, 0x6e, 0xaa, 0x63, 0x7c, 0xb3, 0xd3, 0x22, + 0xd4, 0xf3, 0x2d, 0x22, 0xc0, 0xa7, 0x11, 0x20 + }; + byte* p; + byte* sens; + byte* inner; + int i, seedSz = 0, encSeedSz = 0, sensSz, innerSz; +#ifdef HAVE_ECC + TPM_ALG_ID parentAlg = TPM_ALG_ECC; +#else + TPM_ALG_ID parentAlg = TPM_ALG_RSA; +#endif + + memset(&ctx, 0, sizeof(ctx)); + memset(iv, 0, sizeof(iv)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + parentH = CreatePrimaryHelper(&ctx, parentAlg); + AssertIntNE(parentH, 0); + for (i = 0; i < FWTPM_MAX_OBJECTS; i++) { + if (ctx.objects[i].used && ctx.objects[i].handle == parentH) { + parent = &ctx.objects[i]; + } + } + AssertNotNull(parent); + for (i = 0; i < (int)sizeof(seedValue); i++) { + seedValue[i] = (byte)(0x40 + i); + } + + /* TPM2B_PUBLIC: HMAC-SHA256 key, unique = H(seedValue || key) */ + p = gDup.pub + 2; + PutU16BE(p, TPM_ALG_KEYEDHASH); p += 2; + PutU16BE(p, TPM_ALG_SHA256); p += 2; + PutU32BE(p, DUP_ATTR_HMAC); p += 4; + PutU16BE(p, 0); p += 2; /* authPolicy */ + PutU16BE(p, TPM_ALG_HMAC); p += 2; + PutU16BE(p, TPM_ALG_SHA256); p += 2; + PutU16BE(p, WC_SHA256_DIGEST_SIZE); p += 2; + AssertIntEQ(wc_HashInit(&hash, WC_HASH_TYPE_SHA256), 0); + AssertIntEQ(wc_HashUpdate(&hash, WC_HASH_TYPE_SHA256, seedValue, + sizeof(seedValue)), 0); + AssertIntEQ(wc_HashUpdate(&hash, WC_HASH_TYPE_SHA256, gDupHmacKey, + sizeof(gDupHmacKey)), 0); + AssertIntEQ(wc_HashFinal(&hash, WC_HASH_TYPE_SHA256, p), 0); + wc_HashFree(&hash, WC_HASH_TYPE_SHA256); + p += WC_SHA256_DIGEST_SIZE; + gDup.pubSz = (UINT16)(p - gDup.pub); + PutU16BE(gDup.pub, (UINT16)(gDup.pubSz - 2)); + PutU16BE(name, TPM_ALG_SHA256); + AssertIntEQ(wc_Sha256Hash(gDup.pub + 2, (word32)(gDup.pubSz - 2), + name + 2), 0); + + /* inner = TPM2B_DIGEST || TPM2B_SENSITIVE behind room for the outer + * TPM2B_DIGEST */ + inner = gDup.dup + 2 + WC_SHA256_DIGEST_SIZE; + sens = inner + 2 + WC_SHA256_DIGEST_SIZE; + p = sens + 2; + PutU16BE(p, TPM_ALG_KEYEDHASH); p += 2; + PutU16BE(p, WC_SHA256_DIGEST_SIZE); p += 2; + memset(p, 0, WC_SHA256_DIGEST_SIZE); + memcpy(p, gDupAuth, sizeof(gDupAuth) - 1); p += WC_SHA256_DIGEST_SIZE; + PutU16BE(p, sizeof(seedValue)); p += 2; + memcpy(p, seedValue, sizeof(seedValue)); p += sizeof(seedValue); + PutU16BE(p, sizeof(gDupHmacKey)); p += 2; + memcpy(p, gDupHmacKey, sizeof(gDupHmacKey)); p += sizeof(gDupHmacKey); + sensSz = (int)(p - sens); + PutU16BE(sens, (UINT16)(sensSz - 2)); + AssertIntLE(sensSz, (int)sizeof(plain)); + memcpy(plain, sens, (size_t)sensSz); + + PutU16BE(inner, WC_SHA256_DIGEST_SIZE); + AssertIntEQ(wc_HashInit(&hash, WC_HASH_TYPE_SHA256), 0); + AssertIntEQ(wc_HashUpdate(&hash, WC_HASH_TYPE_SHA256, sens, + (word32)sensSz), 0); + AssertIntEQ(wc_HashUpdate(&hash, WC_HASH_TYPE_SHA256, name, + sizeof(name)), 0); + AssertIntEQ(wc_HashFinal(&hash, WC_HASH_TYPE_SHA256, inner + 2), 0); + wc_HashFree(&hash, WC_HASH_TYPE_SHA256); + innerSz = 2 + WC_SHA256_DIGEST_SIZE + sensSz; + AssertIntEQ(wc_AesInit(&aes, NULL, INVALID_DEVID), 0); + AssertIntEQ(wc_AesSetKey(&aes, gDupInnerKey, AES_128_KEY_SIZE, iv, + AES_ENCRYPTION), 0); + AssertIntEQ(wc_AesCfbEncrypt(&aes, inner, inner, (word32)innerSz), 0); + wc_AesFree(&aes); + AssertIntEQ(wc_Sha256Hash(inner, (word32)innerSz, innerDigest), 0); + AssertIntEQ(memcmp(innerDigest, innerExpect, sizeof(innerExpect)), 0); + + /* The seed is protected to the parent as for any duplicate */ + AssertIntEQ(FwEncryptSeed(&ctx, parent, (const byte*)"DUPLICATE", 10, + "DUPLICATE", seed, (int)sizeof(seed), &seedSz, gDup.seed, + (int)sizeof(gDup.seed), &encSeedSz), TPM_RC_SUCCESS); + gDup.seedSz = (UINT16)encSeedSz; + AssertIntEQ(TPM2_KDFa_ex(TPM_ALG_SHA256, seed, (UINT32)seedSz, "STORAGE", + name, sizeof(name), NULL, 0, symKey, sizeof(symKey)), + (int)sizeof(symKey)); + AssertIntEQ(TPM2_KDFa_ex(TPM_ALG_SHA256, seed, (UINT32)seedSz, + "INTEGRITY", NULL, 0, NULL, 0, hmacKey, sizeof(hmacKey)), + (int)sizeof(hmacKey)); + AssertIntEQ(wc_AesInit(&aes, NULL, INVALID_DEVID), 0); + AssertIntEQ(wc_AesSetKey(&aes, symKey, sizeof(symKey), iv, + AES_ENCRYPTION), 0); + AssertIntEQ(wc_AesCfbEncrypt(&aes, inner, inner, (word32)innerSz), 0); + wc_AesFree(&aes); + PutU16BE(gDup.dup, WC_SHA256_DIGEST_SIZE); + AssertIntEQ(wc_HmacInit(&hmac, NULL, INVALID_DEVID), 0); + AssertIntEQ(wc_HmacSetKey(&hmac, WC_SHA256, hmacKey, sizeof(hmacKey)), + 0); + AssertIntEQ(wc_HmacUpdate(&hmac, inner, (word32)innerSz), 0); + AssertIntEQ(wc_HmacUpdate(&hmac, name, sizeof(name)), 0); + AssertIntEQ(wc_HmacFinal(&hmac, gDup.dup + 2), 0); + wc_HmacFree(&hmac); + gDup.dupSz = (UINT16)(2 + WC_SHA256_DIGEST_SIZE + innerSz); + + AssertIntEQ(DupImport(&ctx, parentH, gDupInnerKey, 16, TPM_ALG_AES, 128, + &gDup), TPM_RC_SUCCESS); + keyH = DupLoad(&ctx, parentH, &gDup); + DupCheckUse(&ctx, TPM_ALG_KEYEDHASH, keyH, 0); + FlushHandle(&ctx, keyH); + + /* The same sensitive with no wrap, then with a key that unique does + * not cover */ + memcpy(gDup.dup, plain, (size_t)sensSz); + gDup.dupSz = (UINT16)sensSz; + gDup.seedSz = 0; + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_SUCCESS); + gDup.dup[sensSz - 1] ^= 0x01; + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_BINDING); + + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Import known inner and outer wrap:", 0); +} + +/* Unseal itemH with the password pw, or with the session sessH when it is + * not zero, and return the size of outData in dataSz */ +static TPM_RC SendUnseal(FWTPM_CTX* ctx, UINT32 itemH, UINT32 sessH, + const byte* pw, int pwSz, int* dataSz) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Unseal); + int rspSize = 0; + TPM_RC rc; + + PutU32BE(gCmd + pos, itemH); pos += 4; + if (sessH != 0) { + pos = AppendAuth(gCmd, pos, sessH, TPMA_SESSION_continueSession, + NULL, 0); + } + else { + pos = AppendPwAuth(gCmd, pos, pw, pwSz); + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + rc = GetRspRC(gRsp); + if (rc == TPM_RC_SUCCESS) { + *dataSz = GetU16BE(gRsp + TPM2_HEADER_SIZE + 4); + } + return rc; +} + +/* An unwrapped duplicate of a sealed data object whose data is the Empty + * Buffer: authValue gDupAuth and the given attributes and authPolicy */ +static void DupBuildEmptySealed(DupBlob* blob, UINT32 attributes, + const byte* policy, UINT16 policySz) +{ + byte seedValue[WC_SHA256_DIGEST_SIZE]; + byte* p; + + memset(seedValue, 0x33, sizeof(seedValue)); + p = blob->pub + 2; + PutU16BE(p, TPM_ALG_KEYEDHASH); p += 2; + PutU16BE(p, TPM_ALG_SHA256); p += 2; + PutU32BE(p, attributes); p += 4; + PutU16BE(p, policySz); p += 2; + if (policySz > 0) { + memcpy(p, policy, policySz); p += policySz; + } + PutU16BE(p, TPM_ALG_NULL); p += 2; + PutU16BE(p, WC_SHA256_DIGEST_SIZE); p += 2; + /* unique = H(seedValue || data) */ + AssertIntEQ(wc_Sha256Hash(seedValue, sizeof(seedValue), p), 0); + p += WC_SHA256_DIGEST_SIZE; + blob->pubSz = (UINT16)(p - blob->pub); + PutU16BE(blob->pub, (UINT16)(blob->pubSz - 2)); + + p = blob->dup + 2; + PutU16BE(p, TPM_ALG_KEYEDHASH); p += 2; + PutU16BE(p, sizeof(gDupAuth) - 1); p += 2; + memcpy(p, gDupAuth, sizeof(gDupAuth) - 1); p += sizeof(gDupAuth) - 1; + PutU16BE(p, sizeof(seedValue)); p += 2; + memcpy(p, seedValue, sizeof(seedValue)); p += sizeof(seedValue); + PutU16BE(p, 0); p += 2; + blob->dupSz = (UINT16)(p - blob->dup); + PutU16BE(blob->dup, (UINT16)(blob->dupSz - 2)); + blob->seedSz = 0; +} + +/* A KEYEDHASH object may hold a sensitive area whose data is the Empty + * Buffer. Imported and loaded, it still has its authValue and authPolicy to + * authorize with, unlike an object loaded without a sensitive area. */ +static void test_fwtpm_import_empty_keyedhash_auth(void) +{ + FWTPM_CTX ctx; + const UINT32 persH = 0x81000A20; + UINT32 parentH, objH, sessH; + byte policyIn[WC_SHA256_DIGEST_SIZE + 8]; + byte policy[WC_SHA256_DIGEST_SIZE]; + static const byte badAuth[] = "dupauti"; +#ifndef FWTPM_NO_CONTEXT + byte saved[sizeof(TPMS_CONTEXT)]; + int ctxSz; +#endif + int pos, rspSize = 0, dataSz; +#ifdef HAVE_ECC + TPM_ALG_ID parentAlg = TPM_ALG_ECC; +#else + TPM_ALG_ID parentAlg = TPM_ALG_RSA; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + parentH = CreatePrimaryHelper(&ctx, parentAlg); + AssertIntNE(parentH, 0); + + /* noDA with authPolicy PolicyCommandCode(TPM_CC_Unseal): only a policy + * session that made the assertion authorizes */ + memset(policyIn, 0, sizeof(policyIn)); + PutU32BE(policyIn + WC_SHA256_DIGEST_SIZE, TPM_CC_PolicyCommandCode); + PutU32BE(policyIn + WC_SHA256_DIGEST_SIZE + 4, TPM_CC_Unseal); + AssertIntEQ(wc_Sha256Hash(policyIn, sizeof(policyIn), policy), 0); + DupBuildEmptySealed(&gDup, 0x00000400, policy, sizeof(policy)); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_SUCCESS); + objH = DupLoad(&ctx, parentH, &gDup); + AssertIntEQ(ctx.objects[objH - TRANSIENT_FIRST].privKeySize, 0); + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(sessH, 0); + AssertIntEQ(SendUnseal(&ctx, objH, sessH, NULL, 0, &dataSz), + TPM_RC_POLICY_FAIL); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_PolicyCommandCode); + PutU32BE(gCmd + pos, sessH); pos += 4; + PutU32BE(gCmd + pos, TPM_CC_Unseal); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + dataSz = -1; + AssertIntEQ(SendUnseal(&ctx, objH, sessH, NULL, 0, &dataSz), + TPM_RC_SUCCESS); + AssertIntEQ(dataSz, 0); + FlushHandle(&ctx, sessH); + FlushHandle(&ctx, objH); + + /* userWithAuth | noDA: the password is the authValue */ + DupBuildEmptySealed(&gDup, 0x00000440, NULL, 0); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_SUCCESS); + objH = DupLoad(&ctx, parentH, &gDup); + AssertIntEQ(ctx.objects[objH - TRANSIENT_FIRST].privKeySize, 0); + dataSz = -1; + AssertIntEQ(SendUnseal(&ctx, objH, 0, gDupAuth, sizeof(gDupAuth) - 1, + &dataSz), TPM_RC_SUCCESS); + AssertIntEQ(dataSz, 0); + AssertIntEQ(SendUnseal(&ctx, objH, 0, badAuth, sizeof(badAuth) - 1, + &dataSz), TPM_RC_BAD_AUTH); + +#ifndef FWTPM_NO_CONTEXT + /* A saved context keeps the sensitive area */ + BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 14, TPM_CC_ContextSave); + PutU32BE(gCmd + 10, objH); + FWTPM_ProcessCommand(&ctx, gCmd, 14, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + ctxSz = rspSize - TPM2_HEADER_SIZE; + AssertIntLE(ctxSz, (int)sizeof(saved)); + memcpy(saved, gRsp + TPM2_HEADER_SIZE, (size_t)ctxSz); + FlushHandle(&ctx, objH); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ContextLoad); + memcpy(gCmd + pos, saved, (size_t)ctxSz); pos += ctxSz; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + objH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + AssertIntEQ(SendUnseal(&ctx, objH, 0, gDupAuth, sizeof(gDupAuth) - 1, + &dataSz), TPM_RC_SUCCESS); +#endif + + /* So does the persistent object, also when a restart loads it from NV */ + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_EvictControl); + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, objH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + pos, persH); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + FlushHandle(&ctx, objH); + FlushHandle(&ctx, parentH); +#ifndef FWTPM_NO_NV + FWTPM_Cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); +#endif + dataSz = -1; + AssertIntEQ(SendUnseal(&ctx, persH, 0, gDupAuth, sizeof(gDupAuth) - 1, + &dataSz), TPM_RC_SUCCESS); + AssertIntEQ(dataSz, 0); + AssertIntEQ(SendUnseal(&ctx, persH, 0, badAuth, sizeof(badAuth) - 1, + &dataSz), TPM_RC_BAD_AUTH); + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_EvictControl); + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, persH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + pos, persH); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("Import empty KEYEDHASH authorizes:", 0); +} + #if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) /* A failed small-stack allocation in Duplicate or Rewrap is reported as * TPM_RC_MEMORY and the unallocated buffers are not used. */ @@ -18662,8 +19589,9 @@ static void test_fwtpm_duplicate_rewrap_alloc_failure(void) XMEMCPY(&obj->pub.authPolicy, &sess->policyDigest, sizeof(obj->pub.authPolicy)); - /* encSeedBuf, then outPrivate */ - for (n = 1; n <= 2; n++) { + /* encSeedBuf, outPrivate, then the sensitive component and the key it + * is exported from */ + for (n = 1; n <= 4; n++) { fwtpm_test_fail_alloc_at(n); AssertIntEQ(SendDuplicateToNullCmd(&ctx, keyH, sessH, TPM_ALG_NULL), TPM_RC_MEMORY); @@ -28850,6 +29778,11 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifndef FWTPM_NO_POLICY test_fwtpm_duplicate_encrypted_needs_new_parent(); test_fwtpm_duplicate_needs_command_code(); + test_fwtpm_duplicate_import_roundtrip(); + test_fwtpm_duplicate_rewrap_import(); + test_fwtpm_duplicate_import_rejections(); + test_fwtpm_import_known_duplicate(); + test_fwtpm_import_empty_keyedhash_auth(); #if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) test_fwtpm_duplicate_rewrap_alloc_failure(); #endif diff --git a/wolftpm/fwtpm/fwtpm_crypto.h b/wolftpm/fwtpm/fwtpm_crypto.h index 319d1a9c2..2c43dbfc2 100644 --- a/wolftpm/fwtpm/fwtpm_crypto.h +++ b/wolftpm/fwtpm/fwtpm_crypto.h @@ -318,6 +318,7 @@ TPM_RC FwImportVerifyAndDecrypt( TPM_RC FwImportParseSensitive( const byte* plainSens, int plainSensSz, UINT16* sensType, TPM2B_AUTH* importedAuth, + const byte** seedOut, UINT16* seedSzOut, UINT16* primeSzOut, byte* primeBuf, int primeBufSz); TPM_RC FwImportReconstructKey( From bcfbdc1d62265b1ccf1b0d440fb9d11d627b791a Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:06:26 -0800 Subject: [PATCH 053/124] F-16187 - Fail the fwTPM NV public area marshal when the packet overflows --- src/fwtpm/fwtpm_nv.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index a76029c92..80b2dfa67 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -418,7 +418,8 @@ static int FwNvMarshalPublic(byte* buf, word32* pos, word32 maxSz, XMEMCPY(&pub2b.publicArea, pub, sizeof(TPMT_PUBLIC)); TPM2_Packet_AppendPublic(&pkt, &pub2b); - if (pkt.pos <= 0 || (word32)pkt.pos > (maxSz - *pos)) { + if (pkt.overflow || pkt.pos <= 0 || + (word32)pkt.pos > (maxSz - *pos)) { return TPM_RC_FAILURE; } *pos += pkt.pos; From a2666f0f06c0477ca9c5d95748cb0dd61f41121b Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:14:43 -0800 Subject: [PATCH 054/124] F-16136 - Check the fwTPM Sign inScheme against the key scheme and sign ECC keys with ECDSA only --- src/fwtpm/fwtpm_command.c | 20 ++++++ src/fwtpm/fwtpm_crypto.c | 17 +++-- tests/fwtpm_unit_tests.c | 143 +++++++++++++++++++++++++++++--------- 3 files changed, 144 insertions(+), 36 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 0dd465cac..2405f154a 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -10624,6 +10624,26 @@ static TPM_RC FwCmd_Sign(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + /* Part 3 Sec.20.2: an inScheme has to agree with the scheme and hash + * of a key that has them */ + if (rc == 0 && sigScheme != TPM_ALG_NULL) { + UINT16 keyScheme = TPM_ALG_NULL; + UINT16 keyHashAlg = TPM_ALG_NULL; + if (obj->pub.type == TPM_ALG_RSA) { + keyScheme = obj->pub.parameters.rsaDetail.scheme.scheme; + keyHashAlg = obj->pub.parameters.rsaDetail.scheme.details + .anySig.hashAlg; + } + else if (obj->pub.type == TPM_ALG_ECC) { + keyScheme = obj->pub.parameters.eccDetail.scheme.scheme; + keyHashAlg = obj->pub.parameters.eccDetail.scheme.details + .any.hashAlg; + } + if (keyScheme != TPM_ALG_NULL && + (sigScheme != keyScheme || sigHashAlg != keyHashAlg)) { + rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; + } + } if (rc == 0) { /* Use key's scheme if command scheme is NULL */ FwResolveSignScheme(obj, &sigScheme, &sigHashAlg); diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 93124d928..f5f142080 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -4501,11 +4501,18 @@ TPM_RC FwSignDigestAndAppend(FWTPM_CTX* ctx, FWTPM_Object* obj, FWTPM_ALLOC_VAR(eccKey, ecc_key); FWTPM_ALLOC_BUF(derSig, FWTPM_MAX_DER_SIG_BUF); - wcRc = FwImportEccKeyFromDer(obj, eccKey); - if (wcRc != 0) - rc = TPM_RC_FAILURE; - else - eccInit = 1; + /* ECDSA is the only ECC signing scheme implemented */ + if (rc == 0 && sigScheme != TPM_ALG_ECDSA) { + rc = TPM_RC_SCHEME; + } + + if (rc == 0) { + wcRc = FwImportEccKeyFromDer(obj, eccKey); + if (wcRc != 0) + rc = TPM_RC_FAILURE; + else + eccInit = 1; + } if (rc == 0) { wcRc = wc_ecc_sign_hash(digest, digestSz, diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 689b2bff5..930254b75 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -14610,17 +14610,13 @@ static void test_fwtpm_nv_counter(void) * PCR selection (count=1) verifies that subsequent PCRselect parsing * is not desynchronized. With the bug, pcrSelectionsCount reads as 0 * because the count field is interpreted as the high 16 bits of the - * PCR-selection count. ECC-only because the RSA sign path rejects - * TPM_ALG_ECDAA with TPM_RC_SCHEME. */ + * PCR-selection count, so the undersized selection goes unseen and the + * command gets as far as the ECDAA signature, which is not implemented. */ static void test_fwtpm_quote_ecdaa_scheme(void) { FWTPM_CTX ctx; int pos, rspSize; UINT32 keyH; - UINT16 nameSz; - UINT16 extraSz; - UINT32 pcrSelCount; - int pcrSelOffset; memset(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), 0); @@ -14641,31 +14637,22 @@ static void test_fwtpm_quote_ecdaa_scheme(void) PutU16BE(gCmd + pos, TPM_ALG_ECDAA); pos += 2; PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; PutU16BE(gCmd + pos, 0); pos += 2; /* ECDAA count */ - /* PCRselect: count=1, hashAlg=SHA256, no PCRs */ + /* PCRselect: count=1, hashAlg=SHA256, sizeofSelect below the minimum */ PutU32BE(gCmd + pos, 1); pos += 4; PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; - gCmd[pos++] = (byte)PCR_SELECT_MAX; - XMEMSET(gCmd + pos, 0, PCR_SELECT_MAX); pos += PCR_SELECT_MAX; + gCmd[pos++] = 0; PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_VALUE); - /* Walk response: header(10) + paramSize(4) + TPM2B_ATTEST.size(2) - * + magic(4) + type(2) + qualifiedSigner.size(2) reads N at offset 22 */ - AssertIntGT(rspSize, 24); - nameSz = GetU16BE(gRsp + 22); - AssertIntGT(nameSz, 0); - /* Then qualifiedSigner.name(nameSz) + extraData.size(2) */ - extraSz = GetU16BE(gRsp + 24 + nameSz); - /* Then extraData(extraSz) + clockInfo(17) + firmwareVersion(8) */ - pcrSelOffset = 24 + nameSz + 2 + extraSz + 17 + 8; - AssertIntGT(rspSize, pcrSelOffset + 4); - pcrSelCount = GetU32BE(gRsp + pcrSelOffset); - /* With the ECDAA count consumed correctly, pcrSelCount reflects the - * caller-supplied value of 1. With the bug, the count field is read - * as the high 16 bits of pcrSelCount, yielding 0. */ - AssertIntEQ(pcrSelCount, 1); + /* A well-formed selection reaches the signature */ + PutU32BE(gCmd + 2, (UINT32)(pos + PCR_SELECT_MAX)); + gCmd[pos - 1] = (byte)PCR_SELECT_MAX; + XMEMSET(gCmd + pos, 0, PCR_SELECT_MAX); pos += PCR_SELECT_MAX; + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SCHEME); FlushHandle(&ctx, keyH); FWTPM_Cleanup(&ctx); @@ -14767,7 +14754,9 @@ static void test_fwtpm_sign_ecdaa_scheme(void) PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + /* The ticket parsed, so the command got as far as the ECDAA signature, + * which is not implemented */ + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SCHEME); FlushHandle(&ctx, keyH); FWTPM_Cleanup(&ctx); @@ -15008,8 +14997,8 @@ static void test_fwtpm_quote_unrestricted_sign(void) } /* A key that declares a signing scheme must not be downgraded by a wire - * inScheme: signing with ECDSA-SHA1 against an ECDSA-SHA256 key must emit a - * SHA-256 signature, not SHA-1. */ + * inScheme: signing with ECDSA-SHA1 against an ECDSA-SHA256 key is refused + * (Part 3 Sec.20.2). */ static void test_fwtpm_sign_scheme_downgrade_rejected(void) { FWTPM_CTX ctx; @@ -15074,9 +15063,7 @@ static void test_fwtpm_sign_scheme_downgrade_rejected(void) PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); - /* TPMT_SIGNATURE: sigAlg(2) then hashAlg(2) after paramSize */ - AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4 + 2), TPM_ALG_SHA256); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); FlushHandle(&ctx, keyH); FWTPM_Cleanup(&ctx); @@ -28421,6 +28408,99 @@ static UINT32 CreateEccSignPrimaryScheme(FWTPM_CTX* ctx, UINT32 attributes, return GetU32BE(gRsp + TPM2_HEADER_SIZE); } +/* TPM2_Sign with an ECC key. On success r and s (32 octets each) are + * copied out when r is not NULL. */ +static TPM_RC SendEccSign(FWTPM_CTX* ctx, UINT32 keyH, UINT16 sigScheme, + UINT16 sigHashAlg, const byte* digest, UINT16 digestSz, byte* r, byte* s) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Sign); + int rspSize = 0; + + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, digestSz); pos += 2; + memcpy(gCmd + pos, digest, digestSz); pos += digestSz; + PutU16BE(gCmd + pos, sigScheme); pos += 2; + if (sigScheme != TPM_ALG_NULL) { + PutU16BE(gCmd + pos, sigHashAlg); pos += 2; + } + PutU16BE(gCmd + pos, TPM_ST_HASHCHECK); pos += 2; + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + if (GetRspRC(gRsp) == TPM_RC_SUCCESS && r != NULL) { + pos = TPM2_HEADER_SIZE + 4; + AssertIntEQ(GetU16BE(gRsp + pos), TPM_ALG_ECDSA); + pos += 4; + AssertIntEQ(GetU16BE(gRsp + pos), 32); + memcpy(r, gRsp + pos + 2, 32); pos += 34; + AssertIntEQ(GetU16BE(gRsp + pos), 32); + memcpy(s, gRsp + pos + 2, 32); + } + return GetRspRC(gRsp); +} + +/* TPM2_Sign takes an inScheme that agrees with the scheme of the key, and + * an ECC key signs with ECDSA only (Part 3 Sec.20.2). */ +static void test_fwtpm_ecc_sign_scheme(void) +{ + FWTPM_CTX ctx; + UINT32 openH, fixedH; + byte digest[TPM_SHA384_DIGEST_SIZE]; +#if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) + UINT32 rsaH; + int cmdSz, rspSize = 0; +#endif + + memset(&ctx, 0, sizeof(ctx)); + memset(digest, 0x5C, sizeof(digest)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + /* fixedTPM|fixedParent|sensitiveDataOrigin|userWithAuth|noDA|sign */ + openH = CreateEccSignPrimaryScheme(&ctx, 0x00040472, TPM_ALG_NULL, + TPM_ALG_NULL); + AssertIntEQ(SendEccSign(&ctx, openH, TPM_ALG_ECSCHNORR, TPM_ALG_SHA256, + digest, WC_SHA256_DIGEST_SIZE, NULL, NULL), TPM_RC_SCHEME); + AssertIntEQ(SendEccSign(&ctx, openH, TPM_ALG_ECDSA, TPM_ALG_SHA256, + digest, WC_SHA256_DIGEST_SIZE, NULL, NULL), TPM_RC_SUCCESS); + FlushHandle(&ctx, openH); + + fixedH = CreateEccSignPrimaryScheme(&ctx, 0x00040472, TPM_ALG_ECDSA, + TPM_ALG_SHA256); + AssertIntEQ(SendEccSign(&ctx, fixedH, TPM_ALG_ECSCHNORR, TPM_ALG_SHA256, + digest, WC_SHA256_DIGEST_SIZE, NULL, NULL), + TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendEccSign(&ctx, fixedH, TPM_ALG_ECDSA, TPM_ALG_SHA384, + digest, TPM_SHA384_DIGEST_SIZE, NULL, NULL), + TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendEccSign(&ctx, fixedH, TPM_ALG_ECDSA, TPM_ALG_SHA256, + digest, WC_SHA256_DIGEST_SIZE, NULL, NULL), TPM_RC_SUCCESS); + AssertIntEQ(SendEccSign(&ctx, fixedH, TPM_ALG_NULL, TPM_ALG_NULL, + digest, WC_SHA256_DIGEST_SIZE, NULL, NULL), TPM_RC_SUCCESS); + FlushHandle(&ctx, fixedH); + +#if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) + /* The same holds for the scheme and hash of an RSA key */ + cmdSz = BuildRsa2048SignPrimary(gCmd, TPM_ALG_RSASSA, TPM_ALG_SHA256); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + rsaH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + AssertIntEQ(SendEccSign(&ctx, rsaH, TPM_ALG_RSAPSS, TPM_ALG_SHA256, + digest, WC_SHA256_DIGEST_SIZE, NULL, NULL), + TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendEccSign(&ctx, rsaH, TPM_ALG_RSASSA, TPM_ALG_SHA384, + digest, TPM_SHA384_DIGEST_SIZE, NULL, NULL), + TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendEccSign(&ctx, rsaH, TPM_ALG_RSASSA, TPM_ALG_SHA256, + digest, WC_SHA256_DIGEST_SIZE, NULL, NULL), TPM_RC_SUCCESS); + FlushHandle(&ctx, rsaH); +#endif + + FWTPM_Cleanup(&ctx); + fwtpm_pass("Sign inScheme against the ECC key scheme:", 0); +} + /* Quote FW_TEST_PCR of one bank. On success *pcrDigestSz is the size of the * pcrDigest inside the returned TPMS_ATTEST. */ static TPM_RC SendQuoteScheme(FWTPM_CTX* ctx, UINT32 keyH, UINT16 sigScheme, @@ -30013,6 +30093,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) test_fwtpm_quote_scheme_hash(); + test_fwtpm_ecc_sign_scheme(); #endif #if !defined(FWTPM_NO_POLICY) && !defined(FWTPM_NO_NV) test_fwtpm_policy_session_needs_auth_policy(); From 0f3d7d5c38221f8eec70b38eb89a8eca7923a625 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:16:54 -0800 Subject: [PATCH 055/124] F-15792 - Verify fwTPM ECC signatures under the ECDSA scheme only --- src/fwtpm/fwtpm_crypto.c | 18 +++++++++++----- tests/fwtpm_unit_tests.c | 44 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index f5f142080..a4856e18c 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -4702,11 +4702,19 @@ TPM_RC FwVerifySignatureCore(FWTPM_Object* obj, FWTPM_ALLOC_VAR(eccKey, ecc_key); FWTPM_ALLOC_BUF(derSig, FWTPM_MAX_DER_SIG_BUF); - wcRc = FwImportEccKey(obj, eccKey); - if (wcRc != 0) - rc = TPM_RC_FAILURE; - else - eccInit = 1; + /* ECDSA is the only ECC signature scheme implemented, and the + * other schemes share its R/S encoding */ + if (rc == 0 && sig->sigAlg != TPM_ALG_ECDSA) { + rc = TPM_RC_SCHEME; + } + + if (rc == 0) { + wcRc = FwImportEccKey(obj, eccKey); + if (wcRc != 0) + rc = TPM_RC_FAILURE; + else + eccInit = 1; + } if (rc == 0) { wcRc = wc_ecc_rs_raw_to_sig( diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 930254b75..da68a5e2b 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -28501,6 +28501,49 @@ static void test_fwtpm_ecc_sign_scheme(void) fwtpm_pass("Sign inScheme against the ECC key scheme:", 0); } +/* An ECDSA signature does not verify under another ECC scheme label. */ +static void test_fwtpm_ecc_verify_scheme(void) +{ + FWTPM_CTX ctx; + UINT32 keyH; + byte digest[WC_SHA256_DIGEST_SIZE]; + byte r[32], s[32]; + int i, pos, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + memset(digest, 0x5C, sizeof(digest)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + keyH = CreateEccSignPrimaryScheme(&ctx, 0x00040472, TPM_ALG_NULL, + TPM_ALG_NULL); + AssertIntEQ(SendEccSign(&ctx, keyH, TPM_ALG_ECDSA, TPM_ALG_SHA256, + digest, sizeof(digest), r, s), TPM_RC_SUCCESS); + + for (i = 0; i < 2; i++) { + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_VerifySignature); + PutU32BE(gCmd + pos, keyH); pos += 4; + PutU16BE(gCmd + pos, (UINT16)sizeof(digest)); pos += 2; + memcpy(gCmd + pos, digest, sizeof(digest)); pos += sizeof(digest); + PutU16BE(gCmd + pos, (i == 0) ? TPM_ALG_ECSCHNORR : TPM_ALG_ECDSA); + pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU16BE(gCmd + pos, 32); pos += 2; + memcpy(gCmd + pos, r, 32); pos += 32; + PutU16BE(gCmd + pos, 32); pos += 2; + memcpy(gCmd + pos, s, 32); pos += 32; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), (i == 0) ? TPM_RC_SCHEME : + TPM_RC_SUCCESS); + } + + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("VerifySignature ECC scheme label:", 0); +} + /* Quote FW_TEST_PCR of one bank. On success *pcrDigestSz is the size of the * pcrDigest inside the returned TPMS_ATTEST. */ static TPM_RC SendQuoteScheme(FWTPM_CTX* ctx, UINT32 keyH, UINT16 sigScheme, @@ -30094,6 +30137,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) test_fwtpm_quote_scheme_hash(); test_fwtpm_ecc_sign_scheme(); + test_fwtpm_ecc_verify_scheme(); #endif #if !defined(FWTPM_NO_POLICY) && !defined(FWTPM_NO_NV) test_fwtpm_policy_session_needs_auth_policy(); From dc1388af962fc045c1d674676a570cd6f580f4fc Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:20:02 -0800 Subject: [PATCH 056/124] F-16135 - Load a KEYEDHASH sensitive area in fwTPM LoadExternal --- src/fwtpm/fwtpm_command.c | 55 +++++++++++++++ tests/fwtpm_unit_tests.c | 139 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 194 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 2405f154a..3350aba7f 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -8594,6 +8594,48 @@ static TPM_RC FwCmd_Load(FWTPM_CTX* ctx, TPM2_Packet* cmd, return rc; } +/* Part 3 Sec.12.3.1 checks on an external KEYEDHASH sensitive area: the key + * fits its scheme, and unique is the nameAlg digest of seedValue || key. */ +static TPM_RC FwCheckExternalKeyedHash(const TPMT_PUBLIC* pub, + const byte* seed, UINT16 seedSz, const byte* key, UINT16 keySz) +{ + TPM_RC rc = TPM_RC_SUCCESS; + UINT16 scheme = pub->parameters.keyedHashDetail.scheme.scheme; + int digestSz = TPM2_GetHashDigestSize(pub->nameAlg); + int maxSz = 128; + byte unique[TPM_MAX_DIGEST_SIZE]; + + if (scheme == TPM_ALG_HMAC) { + maxSz = wc_HashGetBlockSize(FwGetWcHashType( + pub->parameters.keyedHashDetail.scheme.details.hmac.hashAlg)); + } + else if (scheme == TPM_ALG_XOR) { + maxSz = wc_HashGetBlockSize(FwGetWcHashType( + pub->parameters.keyedHashDetail.scheme.details.xorr.hashAlg)); + } + else if (scheme != TPM_ALG_NULL) { + rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; + } + if (rc == 0 && (maxSz <= 0 || (int)keySz > maxSz)) { + rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1; + } + if (rc == 0 && pub->nameAlg != TPM_ALG_NULL) { + if (digestSz <= 0 || (int)seedSz != digestSz) { + rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1; + } + else if (FwComputeHashUnique(pub->nameAlg, seed, seedSz, key, keySz, + unique) != digestSz) { + rc = TPM_RC_FAILURE; + } + else if ((int)pub->unique.keyedHash.size != digestSz || + TPM2_ConstantCompare(pub->unique.keyedHash.buffer, unique, + (word32)digestSz) != 0) { + rc = TPM_RC_BINDING; + } + } + return rc; +} + /* --- TPM2_LoadExternal (CC 0x167) --- * Load an external key (public-only or public+private) without a parent. * Response: objectHandle | [paramSz] | name */ @@ -8607,6 +8649,7 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_DECLARE_BUF(qBuf, FWTPM_MAX_DER_SIG_BUF); UINT16 qSz = 0; UINT16 seedSz = 0; + int seedPos = 0; TPM2B_PUBLIC inPublic; UINT32 hierarchy = 0; FWTPM_Object* obj = NULL; @@ -8682,6 +8725,7 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } if (rc == 0) { + seedPos = cmd->pos; cmd->pos += seedSz; } /* sensitive.any (prime q for RSA) */ @@ -8795,6 +8839,17 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, privKeyDerSz = (int)qSz; } } + else if (rc == 0 && inPrivSize > 0 && + sensitiveType == TPM_ALG_KEYEDHASH && + inPublic.publicArea.type == TPM_ALG_KEYEDHASH && qSz > 0) { + /* For KEYEDHASH, qBuf is the HMAC key or the data */ + rc = FwCheckExternalKeyedHash(&inPublic.publicArea, + cmd->buf + seedPos, seedSz, qBuf, qSz); + if (rc == 0) { + XMEMCPY(privKeyDer, qBuf, qSz); + privKeyDerSz = (int)qSz; + } + } #ifdef HAVE_ECC else if (rc == 0 && inPrivSize > 0 && sensitiveType == TPM_ALG_ECC && qSz > 0) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index da68a5e2b..03af59be2 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -18128,6 +18128,144 @@ static void test_fwtpm_rewrap_null_newparent_rejected(void) } #endif /* !FWTPM_NO_KEY_MIGRATION */ +/* LoadExternal of a KEYEDHASH object with its seedValue and unique. scheme + * is TPM_ALG_HMAC or TPM_ALG_XOR with SHA-256, or has no details. */ +static TPM_RC SendLoadExternalKeyedHash(FWTPM_CTX* ctx, UINT32 attributes, + UINT16 scheme, const byte* seed, UINT16 seedSz, const byte* key, + UINT16 keySz, const byte* unique, UINT32* handle) +{ + int pos, privStart, pubStart, rspSize = 0; + + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_LoadExternal); + privStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_KEYEDHASH); pos += 2; /* sensitiveType */ + PutU16BE(gCmd + pos, 0); pos += 2; /* authValue */ + PutU16BE(gCmd + pos, seedSz); pos += 2; + memcpy(gCmd + pos, seed, seedSz); pos += seedSz; + PutU16BE(gCmd + pos, keySz); pos += 2; + memcpy(gCmd + pos, key, keySz); pos += keySz; + PutU16BE(gCmd + privStart, (UINT16)(pos - privStart - 2)); + pubStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_KEYEDHASH); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; /* nameAlg */ + PutU32BE(gCmd + pos, attributes); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; /* authPolicy */ + PutU16BE(gCmd + pos, scheme); pos += 2; + if (scheme == TPM_ALG_HMAC || scheme == TPM_ALG_XOR) { + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + } + if (scheme == TPM_ALG_XOR) { + PutU16BE(gCmd + pos, TPM_ALG_KDF1_SP800_108); pos += 2; + } + PutU16BE(gCmd + pos, WC_SHA256_DIGEST_SIZE); pos += 2; + memcpy(gCmd + pos, unique, WC_SHA256_DIGEST_SIZE); + pos += WC_SHA256_DIGEST_SIZE; + PutU16BE(gCmd + pubStart, (UINT16)(pos - pubStart - 2)); + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; /* hierarchy */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + if (GetRspRC(gRsp) == TPM_RC_SUCCESS) { + *handle = GetU32BE(gRsp + TPM2_HEADER_SIZE); + } + return GetRspRC(gRsp); +} + +/* LoadExternal of an HMAC-SHA256 signing key */ +static TPM_RC SendLoadExternalHmacKey(FWTPM_CTX* ctx, const byte* seed, + UINT16 seedSz, const byte* key, UINT16 keySz, const byte* unique, + UINT32* handle) +{ + /* userWithAuth | sign */ + return SendLoadExternalKeyedHash(ctx, 0x00040040, TPM_ALG_HMAC, seed, + seedSz, key, keySz, unique, handle); +} + +/* An external HMAC key loads with its sensitive area and is usable; its + * unique is checked against seedValue || key (Part 3 Sec.12.3.1). */ +static void test_fwtpm_loadexternal_keyedhash(void) +{ + FWTPM_CTX ctx; + UINT32 keyH = 0; + byte seed[WC_SHA256_DIGEST_SIZE]; + byte key[MAX_SYM_DATA + 1]; + byte hashSrc[sizeof(seed) + 20]; + byte unique[WC_SHA256_DIGEST_SIZE]; +#ifndef FWTPM_NO_HASH_CMDS + Hmac hmac; + byte expect[WC_SHA256_DIGEST_SIZE]; + int pos, rspSize = 0; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + memset(seed, 0x11, sizeof(seed)); + memset(key, 0x22, sizeof(key)); + memcpy(hashSrc, seed, sizeof(seed)); + memcpy(hashSrc + sizeof(seed), key, 20); + AssertIntEQ(wc_Sha256Hash(hashSrc, (word32)sizeof(hashSrc), unique), 0); + + AssertIntEQ(SendLoadExternalHmacKey(&ctx, seed, sizeof(seed), key, + WC_SHA256_BLOCK_SIZE + 1, unique, &keyH), + TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendLoadExternalHmacKey(&ctx, seed, sizeof(seed) - 1, key, + 20, unique, &keyH), TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendLoadExternalHmacKey(&ctx, seed, sizeof(seed), key, 19, + unique, &keyH), TPM_RC_BINDING); + AssertIntEQ(SendLoadExternalHmacKey(&ctx, seed, sizeof(seed), key, 20, + unique, &keyH), TPM_RC_SUCCESS); + +#ifndef FWTPM_NO_HASH_CMDS + AssertIntEQ(wc_HmacInit(&hmac, NULL, INVALID_DEVID), 0); + AssertIntEQ(wc_HmacSetKey(&hmac, WC_SHA256, key, 20), 0); + AssertIntEQ(wc_HmacUpdate(&hmac, (const byte*)"abc", 3), 0); + AssertIntEQ(wc_HmacFinal(&hmac, expect), 0); + wc_HmacFree(&hmac); + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_HMAC); + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 3); pos += 2; + memcpy(gCmd + pos, "abc", 3); pos += 3; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 4), + WC_SHA256_DIGEST_SIZE); + AssertIntEQ(memcmp(gRsp + TPM2_HEADER_SIZE + 6, expect, sizeof(expect)), + 0); +#endif + FlushHandle(&ctx, keyH); + + /* A scheme that is not a keyedHash scheme (userWithAuth | sign) */ + AssertIntEQ(SendLoadExternalKeyedHash(&ctx, 0x00040040, TPM_ALG_RSASSA, + seed, sizeof(seed), key, 20, unique, &keyH), + TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + + /* Sealed data has no scheme and is bounded by MAX_SYM_DATA + * (userWithAuth) */ + AssertIntEQ(SendLoadExternalKeyedHash(&ctx, 0x00000040, TPM_ALG_NULL, + seed, sizeof(seed), key, MAX_SYM_DATA + 1, unique, &keyH), + TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendLoadExternalKeyedHash(&ctx, 0x00000040, TPM_ALG_NULL, + seed, sizeof(seed), key, 20, unique, &keyH), TPM_RC_SUCCESS); + FlushHandle(&ctx, keyH); + + /* An XOR key is bounded by the block size of its hash + * (userWithAuth | decrypt) */ + AssertIntEQ(SendLoadExternalKeyedHash(&ctx, 0x00020040, TPM_ALG_XOR, + seed, sizeof(seed), key, WC_SHA256_BLOCK_SIZE + 1, unique, &keyH), + TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendLoadExternalKeyedHash(&ctx, 0x00020040, TPM_ALG_XOR, + seed, sizeof(seed), key, 20, unique, &keyH), TPM_RC_SUCCESS); + + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("LoadExternal KEYEDHASH sensitive area:", 0); +} + #ifdef HAVE_ECC /* LoadExternal of a P-256 key, public only when d is NULL. */ static TPM_RC SendLoadExternalEcc(FWTPM_CTX* ctx, UINT32 attributes, @@ -29886,6 +30024,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif test_fwtpm_read_public(); test_fwtpm_loadexternal_symcipher_bad_keysize_rejected(); + test_fwtpm_loadexternal_keyedhash(); #if defined(HAVE_ECC) && !defined(FWTPM_NO_ECDH) test_fwtpm_ecc_unpadded_values(); #endif From 32898194aa64f50f5b7038e525563d8d0a642ec9 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:24:03 -0800 Subject: [PATCH 057/124] F-16130 - Fill the fwTPM CreatePrimary creationData from the command and the hierarchy --- src/fwtpm/fwtpm_command.c | 144 ++++++++++++++++++++++++++++++++---- tests/fwtpm_unit_tests.c | 152 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 283 insertions(+), 13 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 3350aba7f..acd5e7072 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -4655,6 +4655,113 @@ void FWTPM_FlushCommandClient(FWTPM_CTX* ctx, UINT32 clientId) #endif } +/* Append TPMS_CREATION_DATA (Part 2 Sec.15.1). creationPcr points at the + * TPML_PCR_SELECTION of the command, already checked against its size, and + * parent is NULL when parentHandle is a permanent handle. */ +static TPM_RC FwAppendCreationData(FWTPM_CTX* ctx, TPM2_Packet* rsp, + TPM_HANDLE parentHandle, FWTPM_Object* parent, TPMI_ALG_HASH nameAlg, + const byte* creationPcr, const byte* outsideInfo, UINT16 outsideInfoSz) +{ + TPM_RC rc = TPM_RC_SUCCESS; + FWTPM_DECLARE_VAR(hashCtx, wc_HashAlg); + enum wc_HashType wcHash = FwGetWcHashType(nameAlg); + int dSz = TPM2_GetHashDigestSize(nameAlg); + byte pcrDigest[TPM_MAX_DIGEST_SIZE]; + UINT32 count = FwLoadU32BE(creationPcr); + UINT32 s; + int hashInit = 0; + + FWTPM_ALLOC_VAR(hashCtx, wc_HashAlg); + + if (rc == 0 && (wcHash == WC_HASH_TYPE_NONE || dSz <= 0)) { + rc = TPM_RC_HASH; + } + if (rc == 0) { + if (wc_HashInit_ex(hashCtx, wcHash, NULL, INVALID_DEVID) != 0) { + rc = TPM_RC_FAILURE; + } + else { + hashInit = 1; + } + } + + /* pcrSelect, less the PCR that are not implemented or allocated, and + * pcrDigest over the PCR that are left */ + if (rc == 0) { + creationPcr += 4; + TPM2_Packet_AppendU32(rsp, count); + } + for (s = 0; s < count && rc == 0; s++) { + UINT16 hashAlg = FwLoadU16BE(creationPcr); + UINT8 sizeofSelect = creationPcr[2]; + int bank = FwGetPcrBankIndex(hashAlg); + int bankDSz = TPM2_GetHashDigestSize(hashAlg); + int j, bit; + + if (bank >= 0 && (ctx->pcrAllocatedBanks & (1u << bank)) == 0) { + bank = -1; + } + creationPcr += 3; + TPM2_Packet_AppendU16(rsp, hashAlg); + TPM2_Packet_AppendU8(rsp, sizeofSelect); + for (j = 0; j < (int)sizeofSelect && rc == 0; j++) { + byte sel = creationPcr[j]; + if (bank < 0 || j >= (int)PCR_SELECT_MAX) { + sel = 0; + } + TPM2_Packet_AppendU8(rsp, sel); + for (bit = 0; bit < 8 && rc == 0; bit++) { + if ((sel & (1 << bit)) != 0 && + wc_HashUpdate(hashCtx, wcHash, + ctx->pcrDigest[j * 8 + bit][bank], + (word32)bankDSz) != 0) { + rc = TPM_RC_FAILURE; + } + } + } + creationPcr += sizeofSelect; + } + if (rc == 0 && wc_HashFinal(hashCtx, wcHash, pcrDigest) != 0) { + rc = TPM_RC_FAILURE; + } + if (hashInit) { + wc_HashFree(hashCtx, wcHash); + } + + if (rc == 0) { + TPM2_Packet_AppendU16(rsp, (UINT16)dSz); + TPM2_Packet_AppendBytes(rsp, pcrDigest, dSz); + /* TPMA_LOCALITY: one bit for each of localities 0-4 */ + TPM2_Packet_AppendU8(rsp, (ctx->activeLocality < 5) ? + (UINT8)(1 << ctx->activeLocality) : (UINT8)ctx->activeLocality); + if (parent == NULL) { + TPM2_Packet_AppendU16(rsp, TPM_ALG_NULL); + TPM2_Packet_AppendU16(rsp, 4); /* parentName */ + TPM2_Packet_AppendU32(rsp, parentHandle); + TPM2_Packet_AppendU16(rsp, 4); /* parentQualifiedName */ + TPM2_Packet_AppendU32(rsp, parentHandle); + } + else { + if (parent->name.size == 0) { + rc = FwComputeObjectName(parent); + } + TPM2_Packet_AppendU16(rsp, parent->pub.nameAlg); + TPM2_Packet_AppendU16(rsp, parent->name.size); + TPM2_Packet_AppendBytes(rsp, (byte*)parent->name.name, + parent->name.size); + /* Qualified Names are not tracked: the Name stands in */ + TPM2_Packet_AppendU16(rsp, parent->name.size); + TPM2_Packet_AppendBytes(rsp, (byte*)parent->name.name, + parent->name.size); + } + TPM2_Packet_AppendU16(rsp, outsideInfoSz); + TPM2_Packet_AppendBytes(rsp, (byte*)outsideInfo, outsideInfoSz); + } + + FWTPM_FREE_VAR(hashCtx); + return rc; +} + /* --- TPM2_CreatePrimary (CC 0x0131) --- */ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, TPM2_Packet* rsp, UINT16 cmdTag) @@ -4673,6 +4780,7 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_PrimaryCache* cached = NULL; int cacheIdx; int cdStart; + int outsideInfoPos = 0, creationPcrPos = 0; FWTPM_DECLARE_BUF(sensData, FWTPM_MAX_DATA_BUF); UINT16 sensDataSize = 0; byte hashUnique[TPM_MAX_DIGEST_SIZE]; @@ -4733,7 +4841,7 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = FwValidateLimitedAttributes(&inPublic->publicArea); } #endif /* WOLFTPM_V185 */ - /* Parse outsideInfo (TPM2B_DATA) - skip */ + /* Parse outsideInfo (TPM2B_DATA) */ if (rc == 0) { if (cmd->pos + 2 > cmdSize) { rc = TPM_RC_COMMAND_SIZE; @@ -4744,12 +4852,16 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (cmd->pos + outsideInfoSize > cmdSize) { rc = TPM_RC_COMMAND_SIZE; } + else if (outsideInfoSize > sizeof(((TPM2B_DATA*)0)->buffer)) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_3; + } } if (rc == 0) { + outsideInfoPos = cmd->pos; cmd->pos += outsideInfoSize; } - /* Parse creationPCR (TPML_PCR_SELECTION) - skip */ + /* Parse creationPCR (TPML_PCR_SELECTION) */ if (rc == 0) { if (cmd->pos + 4 > cmdSize) { rc = TPM_RC_COMMAND_SIZE; @@ -4757,15 +4869,28 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { UINT32 s; + creationPcrPos = cmd->pos; TPM2_Packet_ParseU32(cmd, &creationPcrCount); + if (creationPcrCount > HASH_COUNT) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_4; + } for (s = 0; s < creationPcrCount && rc == 0; s++) { + UINT16 pcrHashAlg; UINT8 selectSize; if (cmd->pos + 3 > cmdSize) { rc = TPM_RC_COMMAND_SIZE; break; } - cmd->pos += 2; /* hashAlg */ + TPM2_Packet_ParseU16(cmd, &pcrHashAlg); TPM2_Packet_ParseU8(cmd, &selectSize); + if (FwGetWcHashType(pcrHashAlg) == WC_HASH_TYPE_NONE) { + rc = TPM_RC_HASH | TPM_RC_P | TPM_RC_4; + break; + } + if (selectSize < PCR_SELECT_MIN || selectSize > PCR_SELECT_MAX) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_4; + break; + } if (cmd->pos + selectSize > cmdSize) { rc = TPM_RC_COMMAND_SIZE; break; @@ -5138,16 +5263,9 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* creationData (TPM2B_CREATION_DATA) */ TPM2_Packet_MarkU16(rsp, &cdMarkPos); cdStart = rsp->pos; /* start of TPMS_CREATION_DATA */ - /* TPMS_CREATION_DATA */ - TPM2_Packet_AppendU32(rsp, 0); /* pcrSelect count = 0 */ - TPM2_Packet_AppendU16(rsp, 0); /* pcrDigest size = 0 */ - TPM2_Packet_AppendU8(rsp, 0); /* locality */ - TPM2_Packet_AppendU16(rsp, TPM_ALG_SHA256); /* parentNameAlg */ - TPM2_Packet_AppendU16(rsp, 4); /* parentName */ - TPM2_Packet_AppendU32(rsp, primaryHandle); - TPM2_Packet_AppendU16(rsp, 4); /* parentQualifiedName */ - TPM2_Packet_AppendU32(rsp, primaryHandle); - TPM2_Packet_AppendU16(rsp, 0); /* outsideInfo */ + rc = FwAppendCreationData(ctx, rsp, primaryHandle, NULL, + obj->pub.nameAlg, cmd->buf + creationPcrPos, + cmd->buf + outsideInfoPos, outsideInfoSize); TPM2_Packet_PlaceU16(rsp, cdMarkPos); FwAppendCreationHashAndTicket(ctx, rsp, primaryHandle, diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 03af59be2..27b58b487 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -11407,6 +11407,155 @@ static void FlushHandle(FWTPM_CTX* ctx, UINT32 handle) FWTPM_ProcessCommand(ctx, gCmd, 14, gRsp, &rspSize, 0); } +#if defined(HAVE_ECC) || (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) +#ifdef HAVE_ECC + #define FW_TEST_CREATE_ALG TPM_ALG_ECC +#else + #define FW_TEST_CREATE_ALG TPM_ALG_RSA +#endif + +/* Replace the empty outsideInfo and creationPCR that end a command from + * BuildCreatePrimaryCmd with "abcde" and SHA-256 PCR 0 and 7. */ +static int SetCreationInputs(byte* buf, int cmdSz) +{ + int pos = cmdSz - 6; + + PutU16BE(buf + pos, 5); pos += 2; + memcpy(buf + pos, "abcde", 5); pos += 5; + PutU32BE(buf + pos, 1); pos += 4; + PutU16BE(buf + pos, TPM_ALG_SHA256); pos += 2; + buf[pos++] = PCR_SELECT_MAX; + memset(buf + pos, 0, PCR_SELECT_MAX); + buf[pos] = 0x81; + pos += PCR_SELECT_MAX; + PutU32BE(buf + 2, (UINT32)pos); + return pos; +} + +/* Send a command from BuildCreatePrimaryCmd whose creationPCR lists count + * selections of hashAlg, each with sizeofSelect zero octets. */ +static TPM_RC SendCreationPcr(FWTPM_CTX* ctx, UINT32 cc, UINT32 parentH, + UINT32 count, UINT16 hashAlg, byte sizeofSelect) +{ + int cmdSz = BuildCreatePrimaryCmd(gCmd, FW_TEST_CREATE_ALG); + int pos = cmdSz - 4; + int rspSize = 0; + UINT32 i; + + PutU32BE(gCmd + 6, cc); + PutU32BE(gCmd + 10, parentH); + PutU32BE(gCmd + pos, count); pos += 4; + for (i = 0; i < count; i++) { + PutU16BE(gCmd + pos, hashAlg); pos += 2; + gCmd[pos++] = sizeofSelect; + memset(gCmd + pos, 0, sizeofSelect); pos += sizeofSelect; + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* Check the TPM2B_CREATION_DATA at gRsp + pos, made from SetCreationInputs, + * and the creationHash after it. */ +static void CheckCreationData(FWTPM_CTX* ctx, int pos, UINT16 parentNameAlg, + const byte* parentName, UINT16 parentNameSz) +{ + byte pcrs[2 * WC_SHA256_DIGEST_SIZE]; + byte digest[WC_SHA256_DIGEST_SIZE]; + int cdSz = GetU16BE(gRsp + pos); + int cdStart = pos + 2; + int i; + + memcpy(pcrs, ctx->pcrDigest[0][FWTPM_PCR_BANK_SHA256], + WC_SHA256_DIGEST_SIZE); + memcpy(pcrs + WC_SHA256_DIGEST_SIZE, + ctx->pcrDigest[7][FWTPM_PCR_BANK_SHA256], WC_SHA256_DIGEST_SIZE); + AssertIntEQ(wc_Sha256Hash(pcrs, (word32)sizeof(pcrs), digest), 0); + + pos = cdStart; + AssertIntEQ(GetU32BE(gRsp + pos), 1); pos += 4; /* pcrSelect */ + AssertIntEQ(GetU16BE(gRsp + pos), TPM_ALG_SHA256); pos += 2; + AssertIntEQ(gRsp[pos], PCR_SELECT_MAX); pos++; + AssertIntEQ(gRsp[pos], 0x81); + for (i = 1; i < PCR_SELECT_MAX; i++) { + AssertIntEQ(gRsp[pos + i], 0x00); + } + pos += PCR_SELECT_MAX; + AssertIntEQ(GetU16BE(gRsp + pos), WC_SHA256_DIGEST_SIZE); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, digest, sizeof(digest)), 0); + pos += WC_SHA256_DIGEST_SIZE; + AssertIntEQ(gRsp[pos], 0x01); pos++; /* TPM_LOC_ZERO */ + AssertIntEQ(GetU16BE(gRsp + pos), parentNameAlg); pos += 2; + AssertIntEQ(GetU16BE(gRsp + pos), parentNameSz); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, parentName, parentNameSz), 0); + pos += parentNameSz; + /* parentQualifiedName */ + AssertIntEQ(GetU16BE(gRsp + pos), parentNameSz); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, parentName, parentNameSz), 0); + pos += parentNameSz; + AssertIntEQ(GetU16BE(gRsp + pos), 5); pos += 2; /* outsideInfo */ + AssertIntEQ(memcmp(gRsp + pos, "abcde", 5), 0); pos += 5; + AssertIntEQ(pos, cdStart + cdSz); + + /* creationHash */ + AssertIntEQ(wc_Sha256Hash(gRsp + cdStart, (word32)cdSz, digest), 0); + AssertIntEQ(GetU16BE(gRsp + pos), WC_SHA256_DIGEST_SIZE); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, digest, sizeof(digest)), 0); +} + +/* CreatePrimary creationData names the hierarchy as the parent under + * TPM_ALG_NULL and carries outsideInfo and the creationPCR selection and + * digest (Part 2 Sec.15.1). */ +static void test_fwtpm_create_primary_creation_data(void) +{ + FWTPM_CTX ctx; + byte owner[4]; + UINT32 keyH; + int pos, cmdSz, rspSize = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + PutU32BE(owner, TPM_RH_OWNER); + + cmdSz = BuildCreatePrimaryCmd(gCmd, FW_TEST_CREATE_ALG); + cmdSz = SetCreationInputs(gCmd, cmdSz); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + keyH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + pos = TPM2_HEADER_SIZE + 4 + 4; + pos += 2 + GetU16BE(gRsp + pos); /* outPublic */ + CheckCreationData(&ctx, pos, TPM_ALG_NULL, owner, sizeof(owner)); + FlushHandle(&ctx, keyH); + + /* outsideInfo larger than a TPM2B_DATA */ + cmdSz = BuildCreatePrimaryCmd(gCmd, FW_TEST_CREATE_ALG); + pos = cmdSz - 6; + PutU16BE(gCmd + pos, sizeof(TPMT_HA) + 1); pos += 2; + memset(gCmd + pos, 0, sizeof(TPMT_HA) + 1); pos += sizeof(TPMT_HA) + 1; + PutU32BE(gCmd + pos, 0); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SIZE | TPM_RC_P | TPM_RC_3); + + /* creationPCR is checked as a TPML_PCR_SELECTION */ + AssertIntEQ(SendCreationPcr(&ctx, TPM_CC_CreatePrimary, TPM_RH_OWNER, + HASH_COUNT + 1, TPM_ALG_SHA256, PCR_SELECT_MAX), + TPM_RC_SIZE | TPM_RC_P | TPM_RC_4); + AssertIntEQ(SendCreationPcr(&ctx, TPM_CC_CreatePrimary, TPM_RH_OWNER, + 1, TPM_ALG_NULL, PCR_SELECT_MAX), TPM_RC_HASH | TPM_RC_P | TPM_RC_4); + AssertIntEQ(SendCreationPcr(&ctx, TPM_CC_CreatePrimary, TPM_RH_OWNER, + 1, TPM_ALG_SHA256, PCR_SELECT_MIN - 1), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_4); + AssertIntEQ(SendCreationPcr(&ctx, TPM_CC_CreatePrimary, TPM_RH_OWNER, + 1, TPM_ALG_SHA256, PCR_SELECT_MAX + 1), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_4); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("CreatePrimary creationData:", 0); +} +#endif /* HAVE_ECC || (!NO_RSA && WOLFSSL_KEY_GEN) */ + /* Helper: build StartAuthSession command. Returns cmd size. */ static int BuildStartAuthSessionCmd(byte* buf, UINT8 sessionType, UINT16 hashAlg) @@ -29851,6 +30000,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifdef HAVE_ECC test_fwtpm_create_primary_ecc(); #endif +#if defined(HAVE_ECC) || (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) + test_fwtpm_create_primary_creation_data(); +#endif #ifdef WOLFTPM_V185 test_fwtpm_create_primary_mlkem(); test_fwtpm_create_primary_mldsa(); From dbf7c25a0f1d6f44294bda7ec507135f4ebf0e45 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:24:08 -0800 Subject: [PATCH 058/124] F-16131 - Fill the fwTPM Create creationData with the parent nameAlg and Name --- src/fwtpm/fwtpm_command.c | 38 ++++++++++++++++--------- tests/fwtpm_unit_tests.c | 59 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 13 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index acd5e7072..0ac01de82 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -8113,6 +8113,7 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_DECLARE_VAR(outPub, TPM2B_PUBLIC); int cdMarkPos = 0; int cdStart2; + int outsideInfoPos = 0, creationPcrPos = 0; UINT32 s; UINT8 selectSize = 0; @@ -8173,7 +8174,7 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = FwValidateLimitedAttributes(&inPublic->publicArea); } #endif /* WOLFTPM_V185 */ - /* Skip outsideInfo */ + /* Parse outsideInfo (TPM2B_DATA) */ if (rc == 0) { if (cmd->pos + 2 > cmdSize) { rc = TPM_RC_COMMAND_SIZE; @@ -8184,26 +8185,43 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (cmd->pos + outsideInfoSize > cmdSize) { rc = TPM_RC_COMMAND_SIZE; } + else if (outsideInfoSize > sizeof(((TPM2B_DATA*)0)->buffer)) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_3; + } else { + outsideInfoPos = cmd->pos; cmd->pos += outsideInfoSize; } } - /* Parse creationPCR (TPML_PCR_SELECTION) - skip */ + /* Parse creationPCR (TPML_PCR_SELECTION) */ if (rc == 0) { if (cmd->pos + 4 > cmdSize) { rc = TPM_RC_COMMAND_SIZE; } } if (rc == 0) { + creationPcrPos = cmd->pos; TPM2_Packet_ParseU32(cmd, &creationPcrCount); + if (creationPcrCount > HASH_COUNT) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_4; + } for (s = 0; s < creationPcrCount && rc == 0; s++) { + UINT16 pcrHashAlg; if (cmd->pos + 3 > cmdSize) { rc = TPM_RC_COMMAND_SIZE; break; } - cmd->pos += 2; /* hashAlg */ + TPM2_Packet_ParseU16(cmd, &pcrHashAlg); TPM2_Packet_ParseU8(cmd, &selectSize); + if (FwGetWcHashType(pcrHashAlg) == WC_HASH_TYPE_NONE) { + rc = TPM_RC_HASH | TPM_RC_P | TPM_RC_4; + break; + } + if (selectSize < PCR_SELECT_MIN || selectSize > PCR_SELECT_MAX) { + rc = TPM_RC_VALUE | TPM_RC_P | TPM_RC_4; + break; + } if (cmd->pos + selectSize > cmdSize) { rc = TPM_RC_COMMAND_SIZE; break; @@ -8426,15 +8444,9 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* creationData (TPM2B_CREATION_DATA) */ TPM2_Packet_MarkU16(rsp, &cdMarkPos); cdStart2 = rsp->pos; - TPM2_Packet_AppendU32(rsp, 0); /* pcrSelect count = 0 */ - TPM2_Packet_AppendU16(rsp, 0); /* pcrDigest size = 0 */ - TPM2_Packet_AppendU8(rsp, 0); /* locality */ - TPM2_Packet_AppendU16(rsp, inPublic->publicArea.nameAlg); - TPM2_Packet_AppendU16(rsp, 4); /* parentName */ - TPM2_Packet_AppendU32(rsp, parentHandle); - TPM2_Packet_AppendU16(rsp, 4); /* parentQualifiedName */ - TPM2_Packet_AppendU32(rsp, parentHandle); - TPM2_Packet_AppendU16(rsp, 0); /* outsideInfo */ + rc = FwAppendCreationData(ctx, rsp, parentHandle, parent, + inPublic->publicArea.nameAlg, cmd->buf + creationPcrPos, + cmd->buf + outsideInfoPos, outsideInfoSize); TPM2_Packet_PlaceU16(rsp, cdMarkPos); /* Compute object name from public area for creation ticket */ @@ -8454,8 +8466,8 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (hashRc == 0) objNameSz = 2 + nameDigSz; } - FWTPM_FREE_BUF(pubBuf2); } + FWTPM_FREE_BUF(pubBuf2); /* Creation ticket hierarchy = parent's hierarchy per Part 2 * Sec.10.6.5 Table 112. */ diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 27b58b487..9111fe6a7 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -11554,6 +11554,64 @@ static void test_fwtpm_create_primary_creation_data(void) FWTPM_Cleanup(&ctx); fwtpm_pass("CreatePrimary creationData:", 0); } + +/* Create creationData carries the nameAlg and Name of the parent object + * (Part 2 Sec.15.1). */ +static void test_fwtpm_create_creation_data(void) +{ + FWTPM_CTX ctx; + FWTPM_Object* parent; + UINT32 parentH; + int pos, cmdSz, rspSize = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + parentH = CreatePrimaryHelper(&ctx, FW_TEST_CREATE_ALG); + AssertIntNE(parentH, 0); + parent = &ctx.objects[parentH - TRANSIENT_FIRST]; + AssertIntEQ(parent->name.size, 2 + WC_SHA256_DIGEST_SIZE); + + cmdSz = BuildCreatePrimaryCmd(gCmd, FW_TEST_CREATE_ALG); + PutU32BE(gCmd + 6, TPM_CC_Create); + PutU32BE(gCmd + 10, parentH); + cmdSz = SetCreationInputs(gCmd, cmdSz); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pos = TPM2_HEADER_SIZE + 4; + pos += 2 + GetU16BE(gRsp + pos); /* outPrivate */ + pos += 2 + GetU16BE(gRsp + pos); /* outPublic */ + CheckCreationData(&ctx, pos, TPM_ALG_SHA256, parent->name.name, + parent->name.size); + + /* outsideInfo larger than a TPM2B_DATA */ + cmdSz = BuildCreatePrimaryCmd(gCmd, FW_TEST_CREATE_ALG); + PutU32BE(gCmd + 6, TPM_CC_Create); + PutU32BE(gCmd + 10, parentH); + pos = cmdSz - 6; + PutU16BE(gCmd + pos, sizeof(TPMT_HA) + 1); pos += 2; + memset(gCmd + pos, 0, sizeof(TPMT_HA) + 1); pos += sizeof(TPMT_HA) + 1; + PutU32BE(gCmd + pos, 0); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SIZE | TPM_RC_P | TPM_RC_3); + + /* creationPCR is checked as a TPML_PCR_SELECTION */ + AssertIntEQ(SendCreationPcr(&ctx, TPM_CC_Create, parentH, HASH_COUNT + 1, + TPM_ALG_SHA256, PCR_SELECT_MAX), TPM_RC_SIZE | TPM_RC_P | TPM_RC_4); + AssertIntEQ(SendCreationPcr(&ctx, TPM_CC_Create, parentH, 1, + TPM_ALG_NULL, PCR_SELECT_MAX), TPM_RC_HASH | TPM_RC_P | TPM_RC_4); + AssertIntEQ(SendCreationPcr(&ctx, TPM_CC_Create, parentH, 1, + TPM_ALG_SHA256, PCR_SELECT_MIN - 1), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_4); + AssertIntEQ(SendCreationPcr(&ctx, TPM_CC_Create, parentH, 1, + TPM_ALG_SHA256, PCR_SELECT_MAX + 1), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_4); + + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Create creationData:", 0); +} #endif /* HAVE_ECC || (!NO_RSA && WOLFSSL_KEY_GEN) */ /* Helper: build StartAuthSession command. Returns cmd size. */ @@ -30002,6 +30060,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif #if defined(HAVE_ECC) || (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) test_fwtpm_create_primary_creation_data(); + test_fwtpm_create_creation_data(); #endif #ifdef WOLFTPM_V185 test_fwtpm_create_primary_mlkem(); From 531d27e06d52d64041c44cb2e4d9e52bdb738074 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:59:21 -0800 Subject: [PATCH 059/124] F-17126 - Describe the key scheme precedence in the fwTPM sign scheme comments --- src/fwtpm/fwtpm_command.c | 3 ++- src/fwtpm/fwtpm_crypto.c | 10 ++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 0ac01de82..4f0142c6c 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -10830,7 +10830,8 @@ static TPM_RC FwCmd_Sign(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } if (rc == 0) { - /* Use key's scheme if command scheme is NULL */ + /* A NULL inScheme takes the key's scheme, or the default for a key + * that has none */ FwResolveSignScheme(obj, &sigScheme, &sigHashAlg); } /* Part 3 Sec.20.2.1: digest size MUST match the scheme hashAlg digest diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index a4856e18c..0e9cafb03 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -4807,9 +4807,10 @@ int FwComputeNvName(FWTPM_NvIndex* nv, byte* buf, UINT16* sz) /* Attestation helpers */ /* ================================================================== */ -/* Helper: resolve signing scheme from key defaults if NULL. - * If sigScheme is TPM_ALG_NULL, use the key's scheme. If still NULL, - * default to RSASSA/ECDSA with SHA-256. */ +/* Helper: resolve the signing scheme and hash to use with a key. + * A key that has a scheme always signs with that scheme and hash, whatever + * the caller passed in. A key with a NULL scheme keeps the caller's pair, + * and a NULL scheme or hash there defaults to RSASSA/ECDSA and SHA-256. */ void FwResolveSignScheme(FWTPM_Object* obj, UINT16* sigScheme, UINT16* sigHashAlg) { @@ -4934,7 +4935,8 @@ static TPM_RC FwSignAttestMldsa(FWTPM_CTX* ctx, FWTPM_Object* obj, /* Helper: sign attestation buffer with signing key. * attestBuf/attestSz: serialized TPMS_ATTEST bytes * obj: signing key object - * sigScheme/sigHashAlg: from command inScheme (TPM_ALG_NULL = use key default) + * sigScheme/sigHashAlg: from command inScheme; a scheme the key has takes + * their place, see FwResolveSignScheme * rsp: where to write TPMT_SIGNATURE */ TPM_RC FwSignAttest(FWTPM_CTX* ctx, FWTPM_Object* obj, UINT16 sigScheme, UINT16 sigHashAlg, From e4120e951cefb5d537a892b3ab4a6e18882b9613 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:59:21 -0800 Subject: [PATCH 060/124] F-16816 - Name bits 8-23 as the burst count in the fwTPM TIS STS comments --- src/fwtpm/fwtpm_tis.c | 2 +- wolftpm/fwtpm/fwtpm_tis.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/fwtpm/fwtpm_tis.c b/src/fwtpm/fwtpm_tis.c index e19765ed3..414181a5d 100644 --- a/src/fwtpm/fwtpm_tis.c +++ b/src/fwtpm/fwtpm_tis.c @@ -341,7 +341,7 @@ static void TisHandleRegAccess(FWTPM_CTX* ctx, FWTPM_TIS_REGS* regs) case FWTPM_TIS_BURST_COUNT_REG: /* Burst count is at offset 0x0019, which is bytes [1..2] * of the 4-byte STS register. Return just the burst count - * portion (upper 16 bits shifted down). A non-owner cannot + * portion (bits 8-23 shifted down). A non-owner cannot * transfer, so it reads a zero burst count. */ val = isOwner ? ((regs->sts >> 8) & 0xFFFFu) : 0; break; diff --git a/wolftpm/fwtpm/fwtpm_tis.h b/wolftpm/fwtpm/fwtpm_tis.h index b99ce158f..cae9f2f9b 100644 --- a/wolftpm/fwtpm/fwtpm_tis.h +++ b/wolftpm/fwtpm/fwtpm_tis.h @@ -142,7 +142,7 @@ typedef struct FWTPM_TIS_REGS { * FWTPM_TIS_HandleRegAccess). Kept for * shared-memory ABI layout stability. */ UINT32 sts; /* TPM_STS register (low byte = status, - * upper 16 bits = burst count) */ + * bits 8-23 = burst count) */ UINT32 int_enable; /* TPM_INT_ENABLE register */ UINT32 int_status; /* TPM_INT_STATUS register */ UINT32 intf_caps; /* TPM_INTF_CAPS register */ From 1e6cd760321c6280ada0268a6ea59fe0c25917fa Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:59:21 -0800 Subject: [PATCH 061/124] F-16102 - Fix the digest named in the fwTPM TPM_MAX_DIGEST_SIZE comment --- wolftpm/fwtpm/fwtpm.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wolftpm/fwtpm/fwtpm.h b/wolftpm/fwtpm/fwtpm.h index 570202387..3ea457995 100644 --- a/wolftpm/fwtpm/fwtpm.h +++ b/wolftpm/fwtpm/fwtpm.h @@ -481,7 +481,7 @@ #endif #endif -/* Max digest size we track (SHA-384 = 48 bytes) */ +/* Max digest size we track (SHA-512 = 64 bytes) */ #ifndef TPM_MAX_DIGEST_SIZE #define TPM_MAX_DIGEST_SIZE 64 #endif From 8480a3927a972e873e797bc7e22e39c43f42b816 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:59:21 -0800 Subject: [PATCH 062/124] F-16103 - Document the error codes FWTPM_Init returns --- wolftpm/fwtpm/fwtpm.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/wolftpm/fwtpm/fwtpm.h b/wolftpm/fwtpm/fwtpm.h index 3ea457995..61da18631 100644 --- a/wolftpm/fwtpm/fwtpm.h +++ b/wolftpm/fwtpm/fwtpm.h @@ -1107,7 +1107,9 @@ typedef struct FWTPM_CTX { default file backend. \return 0 on success - \return TPM_RC_MEMORY if RNG initialization fails + \return BAD_FUNC_ARG if ctx is NULL + \return the wolfCrypt or NV error code if wolfCrypt, RNG or NV + initialization fails \param ctx pointer to caller-allocated FWTPM_CTX (must be zeroed) From b4bae6690c29005f79101b1a6af6ebfb36e72c82 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:59:21 -0800 Subject: [PATCH 063/124] F-18062 - Document the OP-TEE storage rollback protection the fwTPM port needs --- src/fwtpm/ports/optee/README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/fwtpm/ports/optee/README.md b/src/fwtpm/ports/optee/README.md index 598255e4b..8f64cd479 100644 --- a/src/fwtpm/ports/optee/README.md +++ b/src/fwtpm/ports/optee/README.md @@ -77,6 +77,16 @@ fall back to a random key in its own secure storage object. Secure storage is itself hardware-unique-key encrypted and TA bound, so the journal MAC is defense in depth. +Neither the journal MAC nor the encryption detects an older copy of the whole +NV object being put back, which would rewind NV counters, dictionary attack +state and the clock. Rollback protection is a property of the OP-TEE storage +that backs `TEE_STORAGE_PRIVATE`: build OP-TEE so that it is the RPMB file +system (`CFG_RPMB_FS=y` with `CFG_REE_FS=n`), or the REE file system with its +integrity anchored in RPMB (`CFG_REE_FS_INTEGRITY_RPMB=y`, which also needs +`CFG_RPMB_FS=y`). The plain REE file +system does not provide it against an attacker who controls the normal world +file system. + The key is resolved once, when the trusted application starts, and the choice between the two is made only while the journal is empty. The fallback object existing is the record of that choice. Once a journal exists, failing to From 9a49e298ecd4bd8ea827afdc9a08be0ac938c150 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:59:21 -0800 Subject: [PATCH 064/124] F-18002 - Describe the fwTPM NV clock entry as a Clock checkpoint --- wolftpm/fwtpm/fwtpm_nv.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/wolftpm/fwtpm/fwtpm_nv.h b/wolftpm/fwtpm/fwtpm_nv.h index 0302812da..08bf7849c 100644 --- a/wolftpm/fwtpm/fwtpm_nv.h +++ b/wolftpm/fwtpm/fwtpm_nv.h @@ -123,7 +123,8 @@ typedef struct FWTPM_NV_HEADER { /* Hierarchy policies (value: UINT32 hierarchy + UINT16 alg + digest) */ #define FWTPM_NV_TAG_HIERARCHY_POLICY 0x0035 -/* Clock offset (value: UINT64 clockOffset, survives reboot) */ +/* Clock checkpoint (value: UINT64 Clock in ms, HAL time plus clockOffset, + * survives reboot) */ #define FWTPM_NV_TAG_CLOCK 0x0038 /* NV indices (value starts with UINT32 nvHandle) */ @@ -272,8 +273,8 @@ WOLFTPM_API int FWTPM_NV_SaveConfigs(FWTPM_CTX* ctx); /*! \ingroup wolfTPM_fwTPM_NV - \brief Append the TPM clock offset to the NV journal so that time - survives a reboot. + \brief Append a checkpoint of the TPM Clock (HAL time plus the clock + offset, in ms) to the NV journal so that time survives a reboot. \return 0 on success; a nonzero error code on I/O error From d186bd446f456a78e9ac84d3e4d4bf8d3146c131 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:59:21 -0800 Subject: [PATCH 065/124] F-16105 - Document TPM_RC_HIERARCHY for an unknown hierarchy in FWTPM_NV_SaveAuth --- wolftpm/fwtpm/fwtpm_nv.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/wolftpm/fwtpm/fwtpm_nv.h b/wolftpm/fwtpm/fwtpm_nv.h index 08bf7849c..9982848e6 100644 --- a/wolftpm/fwtpm/fwtpm_nv.h +++ b/wolftpm/fwtpm/fwtpm_nv.h @@ -232,7 +232,8 @@ WOLFTPM_API int FWTPM_NV_SaveSeeds(FWTPM_CTX* ctx); \return 0 on success \return a nonzero error code on I/O error - \return BAD_FUNC_ARG for unknown hierarchy + \return BAD_FUNC_ARG if ctx is NULL + \return TPM_RC_HIERARCHY for unknown hierarchy \param ctx pointer to an initialized FWTPM_CTX \param hierarchy one of TPM_RH_OWNER, TPM_RH_ENDORSEMENT, From 3032b51f90fc8dfda149e4c0711375d1ab82c3db Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 09:59:21 -0800 Subject: [PATCH 066/124] F-16108 - Correct the ML-DSA signature sizes in the fwTPM TIS FIFO size comment --- wolftpm/fwtpm/fwtpm_tis.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/wolftpm/fwtpm/fwtpm_tis.h b/wolftpm/fwtpm/fwtpm_tis.h index cae9f2f9b..94d78f59b 100644 --- a/wolftpm/fwtpm/fwtpm_tis.h +++ b/wolftpm/fwtpm/fwtpm_tis.h @@ -68,11 +68,12 @@ #define FWTPM_TIS_BURST_COUNT 64 #endif -/* Maximum FIFO buffer size. Mirrors FWTPM_MAX_COMMAND_SIZE — only lift to - * 8192 when wolfCrypt was built with MLDSA-65 or MLDSA-87 (sig sizes 3309 - * / 4627 bytes won't fit a 4096 response with TPM headers). MLDSA-44-only - * and MLKEM-only v1.85 deployments stay at 4096. Bare-metal deployments - * should revisit board RAM budget — 2x 8 KB FIFOs vs 2x 4 KB. */ +/* Maximum FIFO buffer size. Mirrors FWTPM_MAX_COMMAND_SIZE - only lift to + * 8192 when wolfCrypt was built with MLDSA-65 or MLDSA-87. An MLDSA-87 + * signature (4627 bytes) does not fit a 4096 response; an MLDSA-65 one + * (3309 bytes) fits but leaves little headroom. MLDSA-44-only and + * MLKEM-only v1.85 deployments stay at 4096. Bare-metal deployments + * should revisit board RAM budget - 2x 8 KB FIFOs vs 2x 4 KB. */ #ifndef FWTPM_TIS_FIFO_SIZE #if defined(WOLFTPM_V185) && \ (!defined(WOLFSSL_NO_ML_DSA_65) || !defined(WOLFSSL_NO_ML_DSA_87)) From efac1782531b0b87f8ce6369984d2b69e7403f7d Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:05:24 -0800 Subject: [PATCH 067/124] F-16210 - Test the fwTPM StartAuthSession nonce size and tpmKey checks --- tests/fwtpm_unit_tests.c | 68 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 9111fe6a7..7ba4a6563 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -24742,6 +24742,73 @@ static void test_fwtpm_start_auth_session_salt_rules(void) fwtpm_pass("StartAuthSession salt rules:", 0); } +static TPM_RC SendStartAuthSessionNonce(FWTPM_CTX* ctx, UINT32 tpmKey, + UINT16 nonceSz, UINT16 encSaltSz) +{ + int pos, rspSize = 0; + TPM_RC rc; + + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_StartAuthSession); + PutU32BE(gCmd + pos, tpmKey); pos += 4; + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; /* bind */ + PutU16BE(gCmd + pos, nonceSz); pos += 2; + memset(gCmd + pos, 0xAA, nonceSz); pos += nonceSz; /* nonceCaller */ + PutU16BE(gCmd + pos, encSaltSz); pos += 2; + memset(gCmd + pos, 0x5C, encSaltSz); pos += encSaltSz; + gCmd[pos++] = TPM_SE_HMAC; + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* symmetric */ + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; /* authHash */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + rc = GetRspRC(gRsp); + if (rc == TPM_RC_SUCCESS) { + FlushHandle(ctx, GetU32BE(gRsp + TPM2_HEADER_SIZE)); + } + return rc; +} + +/* nonceCaller is 16 octets up to the authHash digest size, tpmKey is a + * decryption key and comes with a salt (Part 3 Sec.11.1.1). */ +static void test_fwtpm_start_auth_session_input_checks(void) +{ + FWTPM_CTX ctx; + UINT32 keyH; + int cmdSz, rspSize = 0; + + XMEMSET(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), TPM_RC_SUCCESS); + + AssertIntEQ(SendStartAuthSessionNonce(&ctx, TPM_RH_NULL, 15, 0), + TPM_RC_SIZE); + AssertIntEQ(SendStartAuthSessionNonce(&ctx, TPM_RH_NULL, 16, 0), + TPM_RC_SUCCESS); + AssertIntEQ(SendStartAuthSessionNonce(&ctx, TPM_RH_NULL, + WC_SHA256_DIGEST_SIZE, 0), TPM_RC_SUCCESS); + AssertIntEQ(SendStartAuthSessionNonce(&ctx, TPM_RH_NULL, + WC_SHA256_DIGEST_SIZE + 1, 0), TPM_RC_SIZE); + AssertIntEQ(SendStartAuthSessionNonce(&ctx, TPM_RH_NULL, + TPM_MAX_DIGEST_SIZE + 1, 0), TPM_RC_SIZE); + + cmdSz = BuildRsa2048SignPrimary(gCmd, TPM_ALG_NULL, 0); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + keyH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + AssertIntEQ(SendStartAuthSessionNonce(&ctx, keyH, 16, 256), + TPM_RC_ATTRIBUTES); + FlushHandle(&ctx, keyH); + + keyH = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); + AssertIntNE(keyH, 0); + AssertIntEQ(SendStartAuthSessionNonce(&ctx, keyH, 16, 0), + TPM_RC_VALUE | TPM_RC_P | TPM_RC_2); + FlushHandle(&ctx, keyH); + + AssertIntEQ(ctx.sessions[0].used, 0); + FWTPM_Cleanup(&ctx); + fwtpm_pass("StartAuthSession input checks:", 0); +} + static void test_fwtpm_rsa_hash_matrix(void) { test_fwtpm_rsa_seed_hashes(); @@ -29708,6 +29775,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) test_fwtpm_rsa_hash_matrix(); test_fwtpm_start_auth_session_salt_rules(); + test_fwtpm_start_auth_session_input_checks(); #endif } From 05cf6f23c4d82ca526b9f8540d5336a04e8eafb5 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:11:10 -0800 Subject: [PATCH 068/124] F-16203 - Test the fwTPM PolicyAuthorize ticket HMAC and approvedPolicy rejections --- tests/fwtpm_unit_tests.c | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 7ba4a6563..9752411ca 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -12153,7 +12153,7 @@ static void test_fwtpm_verifysignature_policyauthorize_roundtrip(void) { FWTPM_CTX ctx; int rc, rspSize, pos, oi; - UINT32 keyHandle, sessH; + UINT32 keyHandle, sessH, sessH2; UINT16 rSz, sSz, ticketTag, hmacSz, keyNameSz; UINT32 ticketHier; byte approvedPolicy[32]; @@ -12260,6 +12260,8 @@ static void test_fwtpm_verifysignature_policyauthorize_roundtrip(void) /* PolicyAuthorize on a fresh policy session must accept the ticket. */ sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); AssertIntNE(sessH, 0); + sessH2 = StartSessionHelper(&ctx, TPM_SE_POLICY); + AssertIntNE(sessH2, 0); pos = 0; PutU16BE(gCmd + pos, TPM_ST_NO_SESSIONS); pos += 2; @@ -12282,6 +12284,25 @@ static void test_fwtpm_verifysignature_policyauthorize_roundtrip(void) AssertIntEQ(rc, TPM_RC_SUCCESS); AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + /* The ticket still verifies, but the session policyDigest has moved on + * from approvedPolicy. */ + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_VALUE); + + /* A ticket with a modified HMAC is rejected on a session whose + * policyDigest matches approvedPolicy. */ + PutU32BE(gCmd + TPM2_HEADER_SIZE, sessH2); + gCmd[pos - 1] ^= 0x01; + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_VALUE); + gCmd[pos - 1] ^= 0x01; + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + FlushHandle(&ctx, sessH2); FlushHandle(&ctx, sessH); FlushHandle(&ctx, keyHandle); FWTPM_Cleanup(&ctx); From 5cd3ba448c06f8da73f559a026ecf85b38f5b31e Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:14:43 -0800 Subject: [PATCH 069/124] F-16202 - Test that fwTPM VerifySignature rejects a changed digest or signature --- tests/fwtpm_unit_tests.c | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 9752411ca..1174a8c2b 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -3381,7 +3381,16 @@ static void test_fwtpm_rsassa_sha512_sign_verify(void) rc = FWTPM_ProcessCommand(&ctx, gCmd, (int)GetU32BE(gCmd + 2), gRsp, &rspSize, 0); AssertIntEQ(rc, TPM_RC_SUCCESS); - AssertIntNE(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SIGNATURE); + + /* So must changing the last signature byte. */ + gCmd[pos] ^= 0x01; + pos = (int)GetU32BE(gCmd + 2); + gCmd[pos - 1] ^= 0x01; + rspSize = 0; + rc = FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(rc, TPM_RC_SUCCESS); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SIGNATURE); FWTPM_Cleanup(&ctx); FWTPM_FREE_BUF(sig); @@ -28972,6 +28981,25 @@ static void test_fwtpm_ecc_verify_scheme(void) TPM_RC_SUCCESS); } + /* A changed digest, r or s does not verify. */ + for (i = 0; i < 3; i++) { + int off = TPM2_HEADER_SIZE + 4 + 2 + (int)sizeof(digest) - 1; + if (i == 1) { + off = pos - 32 - 2 - 1; + } + else if (i == 2) { + off = pos - 1; + } + gCmd[off] ^= 0x01; + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SIGNATURE); + gCmd[off] ^= 0x01; + } + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + FlushHandle(&ctx, keyH); FWTPM_Cleanup(&ctx); fwtpm_pass("VerifySignature ECC scheme label:", 0); From 39fb81c238cfa41daee3d84282a07c9aec0d93c6 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:19:14 -0800 Subject: [PATCH 070/124] F-16201 - Test the fwTPM PolicySigned signature and expiration checks --- tests/fwtpm_unit_tests.c | 154 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 1174a8c2b..8dbe6f260 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -29005,6 +29005,157 @@ static void test_fwtpm_ecc_verify_scheme(void) fwtpm_pass("VerifySignature ECC scheme label:", 0); } +#ifndef FWTPM_NO_POLICY +/* TPM2_PolicySigned with an ECDSA SHA-256 signature and an empty cpHashA + * and policyRef */ +static TPM_RC SendPolicySigned(FWTPM_CTX* ctx, UINT32 keyH, UINT32 sessH, + const byte* nonce, UINT16 nonceSz, INT32 expiration, const byte* r, + const byte* s) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_PolicySigned); + int rspSize = 0; + + PutU32BE(gCmd + pos, keyH); pos += 4; + PutU32BE(gCmd + pos, sessH); pos += 4; + PutU16BE(gCmd + pos, nonceSz); pos += 2; + if (nonceSz > 0) { + memcpy(gCmd + pos, nonce, nonceSz); + } + pos += nonceSz; + PutU16BE(gCmd + pos, 0); pos += 2; /* cpHashA */ + PutU16BE(gCmd + pos, 0); pos += 2; /* policyRef */ + PutU32BE(gCmd + pos, (UINT32)expiration); pos += 4; + PutU16BE(gCmd + pos, TPM_ALG_ECDSA); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU16BE(gCmd + pos, 32); pos += 2; + memcpy(gCmd + pos, r, 32); pos += 32; + PutU16BE(gCmd + pos, 32); pos += 2; + memcpy(gCmd + pos, s, 32); pos += 32; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* Start a SHA-256 policy session and sign, with keyH, the aHash that + * PolicySigned computes from its nonceTPM and the expiration. */ +static FWTPM_Session* StartPolicySignedSession(FWTPM_CTX* ctx, UINT32 keyH, + INT32 expiration, byte* r, byte* s) +{ + FWTPM_Session* sess = NULL; + UINT32 sessH = StartSessionHelper(ctx, TPM_SE_POLICY); + wc_HashAlg h; + byte exp[4]; + byte aHash[WC_SHA256_DIGEST_SIZE]; + int i; + + for (i = 0; i < FWTPM_MAX_SESSIONS; i++) { + if (ctx->sessions[i].used && ctx->sessions[i].handle == sessH) { + sess = &ctx->sessions[i]; + } + } + AssertNotNull(sess); + PutU32BE(exp, (UINT32)expiration); + AssertIntEQ(wc_HashInit(&h, WC_HASH_TYPE_SHA256), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA256, + sess->nonceTPM.buffer, sess->nonceTPM.size), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA256, exp, sizeof(exp)), 0); + AssertIntEQ(wc_HashFinal(&h, WC_HASH_TYPE_SHA256, aHash), 0); + wc_HashFree(&h, WC_HASH_TYPE_SHA256); + AssertIntEQ(SendEccSign(ctx, keyH, TPM_ALG_NULL, TPM_ALG_NULL, aHash, + sizeof(aHash), r, s), TPM_RC_SUCCESS); + return sess; +} + +/* PolicySigned extends policyDigest only for a signature by authObject + * over the session nonceTPM and an expiration that has not passed (Part 3 + * Sec.23.3). */ +static void test_fwtpm_policysigned(void) +{ + FWTPM_CTX ctx; + FWTPM_Session* sess; + FWTPM_Object* obj; + UINT32 keyH; + wc_HashAlg h; + byte r[32], s[32], cc[4]; + byte zero[WC_SHA256_DIGEST_SIZE]; + byte expected[WC_SHA256_DIGEST_SIZE]; + + memset(&ctx, 0, sizeof(ctx)); + memset(zero, 0, sizeof(zero)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + gMockClockMs = 0; + AssertIntEQ(FWTPM_Clock_SetHAL(&ctx, mock_clock_get_ms, NULL), 0); + + /* fixedTPM|fixedParent|sensitiveDataOrigin|userWithAuth|noDA|sign */ + keyH = CreateEccSignPrimaryScheme(&ctx, 0x00040472, TPM_ALG_ECDSA, + TPM_ALG_SHA256); + obj = &ctx.objects[keyH - TRANSIENT_FIRST]; + AssertIntEQ(obj->handle, keyH); + AssertIntEQ(obj->name.size, 2 + WC_SHA256_DIGEST_SIZE); + + /* H(H(policyDigest || TPM_CC_PolicySigned || authObject Name) || + * policyRef) */ + PutU32BE(cc, TPM_CC_PolicySigned); + AssertIntEQ(wc_HashInit(&h, WC_HASH_TYPE_SHA256), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA256, zero, sizeof(zero)), + 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA256, cc, sizeof(cc)), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA256, obj->name.name, + obj->name.size), 0); + AssertIntEQ(wc_HashFinal(&h, WC_HASH_TYPE_SHA256, expected), 0); + wc_HashFree(&h, WC_HASH_TYPE_SHA256); + AssertIntEQ(wc_HashInit(&h, WC_HASH_TYPE_SHA256), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA256, expected, + sizeof(expected)), 0); + AssertIntEQ(wc_HashFinal(&h, WC_HASH_TYPE_SHA256, expected), 0); + wc_HashFree(&h, WC_HASH_TYPE_SHA256); + + sess = StartPolicySignedSession(&ctx, keyH, 0, r, s); + s[31] ^= 0x01; + AssertIntEQ(SendPolicySigned(&ctx, keyH, sess->handle, + sess->nonceTPM.buffer, sess->nonceTPM.size, 0, r, s), + TPM_RC_SIGNATURE); + s[31] ^= 0x01; + /* the signature covers nonceTPM */ + AssertIntEQ(SendPolicySigned(&ctx, keyH, sess->handle, NULL, 0, 0, r, s), + TPM_RC_SIGNATURE); + AssertIntEQ(memcmp(sess->policyDigest.buffer, zero, sizeof(zero)), 0); + AssertIntEQ(SendPolicySigned(&ctx, keyH, sess->handle, + sess->nonceTPM.buffer, sess->nonceTPM.size, 0, r, s), + TPM_RC_SUCCESS); + /* empty timeout and a NULL ticket */ + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE), 0); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 2), TPM_ST_AUTH_SIGNED); + AssertIntEQ(GetU32BE(gRsp + TPM2_HEADER_SIZE + 4), TPM_RH_NULL); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE + 8), 0); + AssertIntEQ(sess->policyDigest.size, sizeof(expected)); + AssertIntEQ(memcmp(sess->policyDigest.buffer, expected, + sizeof(expected)), 0); + FlushHandle(&ctx, sess->handle); + + /* expiration counts seconds from the start of the session */ + sess = StartPolicySignedSession(&ctx, keyH, 1, r, s); + gMockClockMs = 2000; + AssertIntEQ(SendPolicySigned(&ctx, keyH, sess->handle, + sess->nonceTPM.buffer, sess->nonceTPM.size, 1, r, s), + TPM_RC_EXPIRED); + AssertIntEQ(memcmp(sess->policyDigest.buffer, zero, sizeof(zero)), 0); + gMockClockMs = 0; + AssertIntEQ(SendPolicySigned(&ctx, keyH, sess->handle, + sess->nonceTPM.buffer, sess->nonceTPM.size, 1, r, s), + TPM_RC_SUCCESS); + AssertIntEQ(memcmp(sess->policyDigest.buffer, expected, + sizeof(expected)), 0); + AssertTrue(sess->timeout == sess->startTime + 1000); + FlushHandle(&ctx, sess->handle); + + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("PolicySigned signature and expiration:", 0); +} +#endif /* !FWTPM_NO_POLICY */ + /* Quote FW_TEST_PCR of one bank. On success *pcrDigestSz is the size of the * pcrDigest inside the returned TPMS_ATTEST. */ static TPM_RC SendQuoteScheme(FWTPM_CTX* ctx, UINT32 keyH, UINT16 sigScheme, @@ -30605,6 +30756,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_quote_scheme_hash(); test_fwtpm_ecc_sign_scheme(); test_fwtpm_ecc_verify_scheme(); +#ifndef FWTPM_NO_POLICY + test_fwtpm_policysigned(); +#endif #endif #if !defined(FWTPM_NO_POLICY) && !defined(FWTPM_NO_NV) test_fwtpm_policy_session_needs_auth_policy(); From 4d7da8c1d17a6bc401be06bd70647b9544e90836 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:22:08 -0800 Subject: [PATCH 071/124] F-16207 - Test fwTPM NV access with platformAuth and against an index-auth-only index --- tests/fwtpm_unit_tests.c | 50 +++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 8dbe6f260..35da62151 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -16708,14 +16708,14 @@ static void test_fwtpm_yes_no_range(void) fwtpm_pass("TPMI_YES_NO range:", 0); } -static TPM_RC SendNvOwnerAccessCmd(FWTPM_CTX* ctx, UINT32 nvIndex, - int isWrite) +static TPM_RC SendNvHandleAccessCmd(FWTPM_CTX* ctx, UINT32 authHandle, + UINT32 nvIndex, int isWrite) { int rspSize = 0; int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, isWrite ? TPM_CC_NV_Write : TPM_CC_NV_Read); - PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; /* authHandle */ + PutU32BE(gCmd + pos, authHandle); pos += 4; PutU32BE(gCmd + pos, nvIndex); pos += 4; pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, 1); pos += 2; @@ -16728,13 +16728,21 @@ static TPM_RC SendNvOwnerAccessCmd(FWTPM_CTX* ctx, UINT32 nvIndex, return GetRspRC(gRsp); } +static TPM_RC SendNvOwnerAccessCmd(FWTPM_CTX* ctx, UINT32 nvIndex, + int isWrite) +{ + return SendNvHandleAccessCmd(ctx, TPM_RH_OWNER, nvIndex, isWrite); +} + /* OWNERREAD and OWNERWRITE alone decide whether ownerAuth may access an - * index; TPMA_NV_PLATFORMCREATE only governs who defines and undefines it. */ + * index, and PPREAD and PPWRITE whether platformAuth may; + * TPMA_NV_PLATFORMCREATE only governs who defines and undefines it. */ static void test_fwtpm_nv_owner_access_platform_index(void) { FWTPM_CTX ctx; UINT32 ownerIdx = 0x01400081; UINT32 ppIdx = 0x01400082; + UINT32 authIdx = 0x01400083; int i, pos, cmdSz, rspSize; memset(&ctx, 0, sizeof(ctx)); @@ -16761,12 +16769,42 @@ static void test_fwtpm_nv_owner_access_platform_index(void) TPM_RC_NV_AUTHORIZATION); AssertIntEQ(SendNvOwnerAccessCmd(&ctx, ppIdx, 0), TPM_RC_NV_AUTHORIZATION); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, TPM_RH_PLATFORM, ppIdx, 1), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, TPM_RH_PLATFORM, ppIdx, 0), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, TPM_RH_PLATFORM, ownerIdx, 1), + TPM_RC_NV_AUTHORIZATION); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, TPM_RH_PLATFORM, ownerIdx, 0), + TPM_RC_NV_AUTHORIZATION); - for (i = 0; i < 2; i++) { + /* neither hierarchy may access an index that takes only its own auth */ + cmdSz = BuildNvDefineCmdEx(gCmd, authIdx, 1, TPMA_NV_PLATFORMCREATE | + TPMA_NV_AUTHWRITE | TPMA_NV_AUTHREAD | TPMA_NV_NO_DA, + NULL, 0, NULL, 0); + PutU32BE(gCmd + TPM2_HEADER_SIZE, TPM_RH_PLATFORM); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, authIdx, authIdx, 1), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, authIdx, authIdx, 0), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerAccessCmd(&ctx, authIdx, 1), + TPM_RC_NV_AUTHORIZATION); + AssertIntEQ(SendNvOwnerAccessCmd(&ctx, authIdx, 0), + TPM_RC_NV_AUTHORIZATION); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, TPM_RH_PLATFORM, authIdx, 1), + TPM_RC_NV_AUTHORIZATION); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, TPM_RH_PLATFORM, authIdx, 0), + TPM_RC_NV_AUTHORIZATION); + + for (i = 0; i < 3; i++) { pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_NV_UndefineSpace); PutU32BE(gCmd + pos, TPM_RH_PLATFORM); pos += 4; - PutU32BE(gCmd + pos, (i == 0) ? ownerIdx : ppIdx); pos += 4; + PutU32BE(gCmd + pos, (i == 0) ? ownerIdx : + (i == 1) ? ppIdx : authIdx); pos += 4; pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; From 2768e7cec643a063c66702c863e6c7990310e309 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:24:44 -0800 Subject: [PATCH 072/124] F-16209 - Test that fwTPM SignDigest rejects a forged or mismatched hashcheck ticket --- tests/fwtpm_unit_tests.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 35da62151..77fd3084e 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -7997,6 +7997,21 @@ static void test_fwtpm_signdigest_restricted_valid_ticket_succeeds(void) AssertIntEQ(rc, TPM_RC_SUCCESS); AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + /* A ticket with a modified HMAC is rejected. */ + gCmd[pos - 1] ^= 0x01; + rspSize = 0; + rc = FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(rc, TPM_RC_SUCCESS); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_TICKET); + gCmd[pos - 1] ^= 0x01; + + /* So is the genuine ticket presented with another digest. */ + gCmd[pos - ticketHmacSz - 8 - 1] ^= 0x01; + rspSize = 0; + rc = FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(rc, TPM_RC_SUCCESS); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_TICKET); + FWTPM_Cleanup(&ctx); fwtpm_pass("SignDigest restricted+valid ticket (success):", 1); } From aeb07b000b10c6e82b56065c7e05b0e60de8c12e Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:30:51 -0800 Subject: [PATCH 073/124] F-16200 - Test the fwTPM policy command code, name hash and NV written bindings --- tests/fwtpm_unit_tests.c | 181 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 181 insertions(+) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 77fd3084e..5db024bfc 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -14435,6 +14435,186 @@ static void test_fwtpm_nv_access_matches_auth_method(void) fwtpm_pass("NV access method matches attributes:", 0); } +/* Start a session and run one policy command, given by its parameter octets, + * on it. With digest not NULL the resulting SHA-256 policyDigest is copied + * out. */ +static UINT32 StartPolicyWith(FWTPM_CTX* ctx, UINT8 sessType, UINT32 cc, + const byte* params, int paramsSz, byte* digest) +{ + UINT32 sessH = StartSessionHelper(ctx, sessType); + int pos, rspSize = 0; + + AssertIntNE(sessH, 0); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, cc); + PutU32BE(gCmd + pos, sessH); pos += 4; + memcpy(gCmd + pos, params, paramsSz); pos += paramsSz; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + if (digest != NULL) { + AssertIntEQ(SendPolicyCmd(ctx, TPM_CC_PolicyGetDigest, sessH), + TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp + TPM2_HEADER_SIZE), + WC_SHA256_DIGEST_SIZE); + memcpy(digest, gRsp + TPM2_HEADER_SIZE + 2, WC_SHA256_DIGEST_SIZE); + } + return sessH; +} + +static TPM_RC SendSetOwnerPolicy(FWTPM_CTX* ctx, const byte* policy, + UINT16 policySz, UINT16 hashAlg) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + TPM_CC_SetPrimaryPolicy); + int rspSize = 0; + + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, policySz); pos += 2; + if (policySz > 0) { + memcpy(gCmd + pos, policy, policySz); pos += policySz; + } + PutU16BE(gCmd + pos, hashAlg); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* NV_Write of one octet authorized by ownerPolicy through sessH */ +static TPM_RC SendNvOwnerPolicyWrite(FWTPM_CTX* ctx, UINT32 nvIndex, + UINT32 sessH) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_NV_Write); + int rspSize = 0; + + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, nvIndex); pos += 4; + pos = AppendAuth(gCmd, pos, sessH, TPMA_SESSION_continueSession, + NULL, 0); + PutU16BE(gCmd + pos, 1); pos += 2; + gCmd[pos++] = 0x5A; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* A policy session whose policyDigest matches authPolicy still authorizes + * only the command PolicyCommandCode named, the handles PolicyNameHash + * named and the written state PolicyNvWritten named (Part 1 Sec.19.7). */ +static void test_fwtpm_policy_assertions_enforced(void) +{ + FWTPM_CTX ctx; + FWTPM_NvIndex* nv = NULL; + UINT32 ccIdx = 0x01500091; + UINT32 writtenIdx = 0x01500092; + UINT32 nameIdx = 0x01500093; + UINT32 otherIdx = 0x01500094; + UINT32 sessH; + UINT16 nameSz = 0; + wc_HashAlg h; + byte params[2 + WC_SHA256_DIGEST_SIZE]; + byte policy[WC_SHA256_DIGEST_SIZE]; + byte name[2 + TPM_MAX_DIGEST_SIZE]; + int i, cmdSz, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + /* PolicyCommandCode(NV_Write) does not authorize NV_Read */ + PutU32BE(params, TPM_CC_NV_Write); + sessH = StartPolicyWith(&ctx, TPM_SE_TRIAL, TPM_CC_PolicyCommandCode, + params, 4, policy); + FlushHandle(&ctx, sessH); + cmdSz = BuildNvDefineCmdEx(gCmd, ccIdx, 1, + TPMA_NV_POLICYWRITE | TPMA_NV_POLICYREAD | TPMA_NV_NO_DA, + NULL, 0, policy, sizeof(policy)); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + PutU32BE(params, TPM_CC_NV_Write); + sessH = StartPolicyWith(&ctx, TPM_SE_POLICY, TPM_CC_PolicyCommandCode, + params, 4, NULL); + AssertIntEQ(SendNvAccessCmd(&ctx, ccIdx, sessH, NULL, 0, 0), + TPM_RC_POLICY_CC); + AssertIntEQ(SendNvAccessCmd(&ctx, ccIdx, sessH, NULL, 0, 1), + TPM_RC_SUCCESS); + FlushHandle(&ctx, sessH); + + /* PolicyNvWritten(NO) authorizes the first write only */ + params[0] = 0; + sessH = StartPolicyWith(&ctx, TPM_SE_TRIAL, TPM_CC_PolicyNvWritten, + params, 1, policy); + FlushHandle(&ctx, sessH); + cmdSz = BuildNvDefineCmdEx(gCmd, writtenIdx, 1, + TPMA_NV_POLICYWRITE | TPMA_NV_POLICYREAD | TPMA_NV_NO_DA, + NULL, 0, policy, sizeof(policy)); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + for (i = 0; i < 2; i++) { + params[0] = 0; + sessH = StartPolicyWith(&ctx, TPM_SE_POLICY, TPM_CC_PolicyNvWritten, + params, 1, NULL); + AssertIntEQ(SendNvAccessCmd(&ctx, writtenIdx, sessH, NULL, 0, 1), + (i == 0) ? TPM_RC_SUCCESS : TPM_RC_POLICY_FAIL); + FlushHandle(&ctx, sessH); + } + + /* PolicyNameHash(TPM_RH_OWNER, nameIdx) does not authorize a write to + * otherIdx with ownerPolicy */ + cmdSz = BuildNvDefineCmd(gCmd, nameIdx, 1, + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + cmdSz = BuildNvDefineCmd(gCmd, otherIdx, 1, + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + for (i = 0; i < FWTPM_MAX_NV_INDICES; i++) { + if (ctx.nvIndices[i].inUse && + ctx.nvIndices[i].nvPublic.nvIndex == nameIdx) { + nv = &ctx.nvIndices[i]; + } + } + AssertNotNull(nv); + AssertIntEQ(FwComputeNvName(nv, name, &nameSz), 0); + PutU16BE(params, WC_SHA256_DIGEST_SIZE); + PutU32BE(policy, TPM_RH_OWNER); + AssertIntEQ(wc_HashInit(&h, WC_HASH_TYPE_SHA256), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA256, policy, 4), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA256, name, nameSz), 0); + AssertIntEQ(wc_HashFinal(&h, WC_HASH_TYPE_SHA256, params + 2), 0); + wc_HashFree(&h, WC_HASH_TYPE_SHA256); + sessH = StartPolicyWith(&ctx, TPM_SE_TRIAL, TPM_CC_PolicyNameHash, + params, sizeof(params), policy); + FlushHandle(&ctx, sessH); + AssertIntEQ(SendSetOwnerPolicy(&ctx, policy, sizeof(policy), + TPM_ALG_SHA256), TPM_RC_SUCCESS); + sessH = StartPolicyWith(&ctx, TPM_SE_POLICY, TPM_CC_PolicyNameHash, + params, sizeof(params), NULL); + AssertIntEQ(SendNvOwnerPolicyWrite(&ctx, otherIdx, sessH), + TPM_RC_POLICY_FAIL); + AssertIntEQ(SendNvOwnerPolicyWrite(&ctx, nameIdx, sessH), + TPM_RC_SUCCESS); + FlushHandle(&ctx, sessH); + AssertIntEQ(SendSetOwnerPolicy(&ctx, NULL, 0, TPM_ALG_NULL), + TPM_RC_SUCCESS); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, ccIdx), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, writtenIdx), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nameIdx), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, otherIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Policy command, name and NV written binding:", 0); +} + /* A policy that asserts PolicyAuthValue or PolicyPassword needs authValue * proof in the session HMAC field; only an empty authValue accepts none. */ static void test_fwtpm_nv_policy_auth_proof_required(void) @@ -30737,6 +30917,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifndef FWTPM_NO_POLICY test_fwtpm_nv_access_matches_auth_method(); test_fwtpm_nv_policy_auth_proof_required(); + test_fwtpm_policy_assertions_enforced(); #endif test_fwtpm_nv_read_public(); test_fwtpm_nv_journal_tamper_rejected(); From da3300520d384330d2cb6050b92bb8d379536541 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:33:36 -0800 Subject: [PATCH 074/124] F-16205 - Test that fwTPM Clear returns TPM_RC_DISABLED while disableClear is set --- tests/fwtpm_unit_tests.c | 44 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 5db024bfc..64d22463e 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -16903,6 +16903,49 @@ static void test_fwtpm_yes_no_range(void) fwtpm_pass("TPMI_YES_NO range:", 0); } +static TPM_RC SendClearControl(FWTPM_CTX* ctx, UINT32 authHandle, + byte disable) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ClearControl); + int rspSize = 0; + + PutU32BE(gCmd + pos, authHandle); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + gCmd[pos++] = disable; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* While disableClear is set, Clear fails with TPM_RC_DISABLED for both of + * its authorizations and changes nothing (Part 3 Sec.24.6). */ +static void test_fwtpm_clear_disabled(void) +{ + FWTPM_CTX ctx; + byte ownerSeed[FWTPM_SEED_SIZE]; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + memcpy(ownerSeed, ctx.ownerSeed, sizeof(ownerSeed)); + + AssertIntEQ(SendClearControl(&ctx, TPM_RH_PLATFORM, 1), TPM_RC_SUCCESS); + AssertIntEQ(ctx.disableClear, 1); + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_Clear, TPM_RH_LOCKOUT), + TPM_RC_DISABLED); + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_Clear, TPM_RH_PLATFORM), + TPM_RC_DISABLED); + AssertIntEQ(memcmp(ownerSeed, ctx.ownerSeed, sizeof(ownerSeed)), 0); + + AssertIntEQ(SendClearControl(&ctx, TPM_RH_PLATFORM, 0), TPM_RC_SUCCESS); + AssertIntEQ(ctx.disableClear, 0); + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_Clear, TPM_RH_LOCKOUT), + TPM_RC_SUCCESS); + AssertIntNE(memcmp(ownerSeed, ctx.ownerSeed, sizeof(ownerSeed)), 0); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("Clear while disableClear is set:", 0); +} + static TPM_RC SendNvHandleAccessCmd(FWTPM_CTX* ctx, UINT32 authHandle, UINT32 nvIndex, int isWrite) { @@ -31032,6 +31075,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_nv_define_type_sizes(); test_fwtpm_clear_control_nv_failure(); test_fwtpm_yes_no_range(); + test_fwtpm_clear_disabled(); test_fwtpm_nv_owner_access_platform_index(); test_fwtpm_nv_read_zero_size(); test_fwtpm_nv_buffer_max(); From 311dadbc26f413550477dbb7b97c1d5251afa0c8 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:37:37 -0800 Subject: [PATCH 075/124] F-16204 - Test the fwTPM HierarchyControl authorization and disabled hierarchy handling --- tests/fwtpm_unit_tests.c | 148 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 64d22463e..55b715bf9 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -17054,6 +17054,153 @@ static void test_fwtpm_nv_owner_access_platform_index(void) fwtpm_pass("NV owner access to platform index:", 0); } +static TPM_RC SendHierarchyControl(FWTPM_CTX* ctx, UINT32 authHandle, + UINT32 enable, byte state) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + TPM_CC_HierarchyControl); + int rspSize = 0; + + PutU32BE(gCmd + pos, authHandle); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + pos, enable); pos += 4; + gCmd[pos++] = state; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* ownerAuth and endorsementAuth can only disable their own hierarchy and + * platformAuth changes every enable. A disabled hierarchy takes its + * transient objects with it and makes its handle and NV indexes unusable + * (Part 3 Sec.24.2, Part 1 Sec.14.2). */ +static void test_fwtpm_hierarchy_control(void) +{ + FWTPM_CTX ctx; + UINT32 ownerIdx = 0x01400091; + UINT32 ppIdx = 0x01400092; + int pos, cmdSz, rspSize; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmdSz = BuildNvDefineCmd(gCmd, ownerIdx, 1, + TPMA_NV_AUTHWRITE | TPMA_NV_AUTHREAD | TPMA_NV_NO_DA); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + cmdSz = BuildNvDefineCmd(gCmd, ppIdx, 1, TPMA_NV_PLATFORMCREATE | + TPMA_NV_AUTHWRITE | TPMA_NV_AUTHREAD | TPMA_NV_NO_DA); + PutU32BE(gCmd + TPM2_HEADER_SIZE, TPM_RH_PLATFORM); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, ownerIdx, ownerIdx, 1), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, ppIdx, ppIdx, 1), + TPM_RC_SUCCESS); + + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_PLATFORM, TPM_RH_OWNER, 2), + TPM_RC_VALUE); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_PLATFORM, TPM_RH_LOCKOUT, + 0), TPM_RC_VALUE); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_OWNER, TPM_RH_ENDORSEMENT, + 0), TPM_RC_AUTH_TYPE); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_OWNER, TPM_RH_PLATFORM, 0), + TPM_RC_AUTH_TYPE); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_OWNER, TPM_RH_PLATFORM_NV, + 0), TPM_RC_AUTH_TYPE); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_ENDORSEMENT, TPM_RH_OWNER, + 0), TPM_RC_AUTH_TYPE); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_ENDORSEMENT, + TPM_RH_PLATFORM, 0), TPM_RC_AUTH_TYPE); + AssertIntEQ(ctx.shDisabled | ctx.ehDisabled | ctx.phDisabled | + ctx.phNvDisabled, 0); + + /* stand-ins for a loaded object of each hierarchy */ + ctx.objects[0].used = 1; + ctx.objects[0].handle = TRANSIENT_FIRST; + ctx.objects[0].hierarchy = TPM_RH_OWNER; + ctx.objects[1].used = 1; + ctx.objects[1].handle = TRANSIENT_FIRST + 1; + ctx.objects[1].hierarchy = TPM_RH_ENDORSEMENT; + + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_OWNER, TPM_RH_OWNER, 0), + TPM_RC_SUCCESS); + AssertIntEQ(ctx.shDisabled, 1); + AssertIntEQ(ctx.objects[0].used, 0); + AssertIntEQ(ctx.objects[1].used, 1); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_OWNER, TPM_RH_OWNER, 1), + TPM_RC_HIERARCHY); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_ENDORSEMENT, TPM_RH_OWNER, + 1), TPM_RC_AUTH_TYPE); + cmdSz = BuildNvDefineCmd(gCmd, ownerIdx + 2, 1, + TPMA_NV_AUTHWRITE | TPMA_NV_AUTHREAD | TPMA_NV_NO_DA); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_HIERARCHY); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, ownerIdx, ownerIdx, 0), + TPM_RC_HANDLE); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, ppIdx, ppIdx, 0), + TPM_RC_SUCCESS); + AssertIntEQ(ctx.shDisabled, 1); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_PLATFORM, TPM_RH_OWNER, 1), + TPM_RC_SUCCESS); + AssertIntEQ(ctx.shDisabled, 0); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, ownerIdx, ownerIdx, 0), + TPM_RC_SUCCESS); + + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_ENDORSEMENT, + TPM_RH_ENDORSEMENT, 0), TPM_RC_SUCCESS); + AssertIntEQ(ctx.ehDisabled, 1); + AssertIntEQ(ctx.objects[1].used, 0); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_ENDORSEMENT, + TPM_RH_ENDORSEMENT, 1), TPM_RC_HIERARCHY); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_PLATFORM, + TPM_RH_ENDORSEMENT, 1), TPM_RC_SUCCESS); + AssertIntEQ(ctx.ehDisabled, 0); + + /* phEnableNV governs the indexes the platform created */ + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_PLATFORM, + TPM_RH_PLATFORM_NV, 0), TPM_RC_SUCCESS); + AssertIntEQ(ctx.phNvDisabled, 1); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, ppIdx, ppIdx, 0), + TPM_RC_HANDLE); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, ownerIdx, ownerIdx, 0), + TPM_RC_SUCCESS); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_PLATFORM, + TPM_RH_PLATFORM_NV, 1), TPM_RC_SUCCESS); + AssertIntEQ(ctx.phNvDisabled, 0); + AssertIntEQ(SendNvHandleAccessCmd(&ctx, ppIdx, ppIdx, 0), + TPM_RC_SUCCESS); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, ownerIdx), + TPM_RC_SUCCESS); + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_NV_UndefineSpace); + PutU32BE(gCmd + pos, TPM_RH_PLATFORM); pos += 4; + PutU32BE(gCmd + pos, ppIdx); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + /* phEnable stays clear until the next Startup */ + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_PLATFORM, TPM_RH_PLATFORM, + 0), TPM_RC_SUCCESS); + AssertIntEQ(ctx.phDisabled, 1); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_PLATFORM, TPM_RH_PLATFORM, + 1), TPM_RC_HIERARCHY); + FWTPM_Cleanup(&ctx); + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(ctx.shDisabled | ctx.ehDisabled | ctx.phDisabled | + ctx.phNvDisabled, 0); + FWTPM_Cleanup(&ctx); + fwtpm_pass("HierarchyControl:", 0); +} + /* NV_Read size is the number of octets to return, so zero reads nothing. */ static void test_fwtpm_nv_read_zero_size(void) { @@ -31077,6 +31224,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_yes_no_range(); test_fwtpm_clear_disabled(); test_fwtpm_nv_owner_access_platform_index(); + test_fwtpm_hierarchy_control(); test_fwtpm_nv_read_zero_size(); test_fwtpm_nv_buffer_max(); test_fwtpm_nv_extend_buffer_max(); From d09b7bdf59464c814732e925fcdf0cd3822d0d4e Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:40:43 -0800 Subject: [PATCH 076/124] F-16206 - Test the fwTPM Import outer integrity check --- tests/fwtpm_unit_tests.c | 96 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 55b715bf9..8bd6fd5c5 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -20411,6 +20411,101 @@ static void test_fwtpm_duplicate_rewrap_alloc_failure(void) #endif /* WOLFTPM_FWTPM_UNIT_TEST && WOLFTPM_SMALL_STACK */ #endif /* !FWTPM_NO_KEY_MIGRATION && !FWTPM_NO_POLICY */ +#ifndef FWTPM_NO_KEY_MIGRATION +/* Build integrity || encSens for FwImportVerifyAndDecrypt: integritySz + * octets of HMAC-SHA256(hmacKey, encSens || name) and encSens = + * AES-CFB(aesKey, IV 0, plain). Returns the size. */ +static UINT16 BuildImportDuplicate(byte* dup, const byte* hmacKey, + const byte* aesKey, const byte* name, int nameSz, const byte* plain, + int plainSz, UINT16 integritySz) +{ + Aes aes; + Hmac hmac; + byte iv[AES_BLOCK_SIZE]; + byte mac[WC_SHA256_DIGEST_SIZE]; + byte* encSens = dup + 2 + integritySz; + + memset(iv, 0, sizeof(iv)); + AssertIntEQ(wc_AesInit(&aes, NULL, INVALID_DEVID), 0); + AssertIntEQ(wc_AesSetKey(&aes, aesKey, AES_128_KEY_SIZE, iv, + AES_ENCRYPTION), 0); + AssertIntEQ(wc_AesCfbEncrypt(&aes, encSens, plain, (word32)plainSz), 0); + wc_AesFree(&aes); + + AssertIntEQ(wc_HmacInit(&hmac, NULL, INVALID_DEVID), 0); + AssertIntEQ(wc_HmacSetKey(&hmac, WC_SHA256, hmacKey, + WC_SHA256_DIGEST_SIZE), 0); + AssertIntEQ(wc_HmacUpdate(&hmac, encSens, (word32)plainSz), 0); + AssertIntEQ(wc_HmacUpdate(&hmac, name, (word32)nameSz), 0); + AssertIntEQ(wc_HmacFinal(&hmac, mac), 0); + wc_HmacFree(&hmac); + + PutU16BE(dup, integritySz); + memcpy(dup + 2, mac, integritySz); + return (UINT16)(2 + integritySz + plainSz); +} + +/* The outer wrap of an imported duplicate is released only when its + * integrity HMAC over encSens and the object Name verifies (Part 1 + * Sec.23.3). */ +static void test_fwtpm_import_outer_integrity(void) +{ + byte hmacKey[WC_SHA256_DIGEST_SIZE]; + byte aesKey[AES_128_KEY_SIZE]; + byte name[2 + WC_SHA256_DIGEST_SIZE]; + byte plain[40]; + byte zero[sizeof(plain)]; + byte out[sizeof(plain)]; + byte dup[2 + WC_SHA256_DIGEST_SIZE + sizeof(plain)]; + UINT16 dupSz; + int outSz = 0; + int i; + + memset(hmacKey, 0x11, sizeof(hmacKey)); + memset(aesKey, 0x22, sizeof(aesKey)); + memset(name, 0x33, sizeof(name)); + memset(zero, 0, sizeof(zero)); + PutU16BE(name, TPM_ALG_SHA256); + for (i = 0; i < (int)sizeof(plain); i++) { + plain[i] = (byte)(i + 1); + } + + dupSz = BuildImportDuplicate(dup, hmacKey, aesKey, name, sizeof(name), + plain, sizeof(plain), WC_SHA256_DIGEST_SIZE); + AssertIntEQ(dupSz, sizeof(dup)); + AssertIntEQ(FwImportVerifyAndDecrypt(TPM_ALG_SHA256, hmacKey, + sizeof(hmacKey), aesKey, sizeof(aesKey), name, sizeof(name), + dup, dupSz, out, sizeof(out), &outSz), TPM_RC_SUCCESS); + AssertIntEQ(outSz, sizeof(plain)); + AssertIntEQ(memcmp(out, plain, sizeof(plain)), 0); + + /* a changed encSens, integrity or Name octet */ + for (i = 0; i < 3; i++) { + byte* target = (i == 0) ? &dup[dupSz - 1] : (i == 1) ? &dup[2] : + &name[sizeof(name) - 1]; + *target ^= 0x01; + memset(out, 0xEE, sizeof(out)); + AssertIntEQ(FwImportVerifyAndDecrypt(TPM_ALG_SHA256, hmacKey, + sizeof(hmacKey), aesKey, sizeof(aesKey), name, sizeof(name), + dup, dupSz, out, sizeof(out), &outSz), TPM_RC_INTEGRITY); + AssertIntEQ(memcmp(out, zero, sizeof(out)), 0); + *target ^= 0x01; + } + + /* an integrity value shorter than the digest, although its octets + * match */ + dupSz = BuildImportDuplicate(dup, hmacKey, aesKey, name, sizeof(name), + plain, sizeof(plain), WC_SHA256_DIGEST_SIZE / 2); + memset(out, 0xEE, sizeof(out)); + AssertIntEQ(FwImportVerifyAndDecrypt(TPM_ALG_SHA256, hmacKey, + sizeof(hmacKey), aesKey, sizeof(aesKey), name, sizeof(name), + dup, dupSz, out, sizeof(out), &outSz), TPM_RC_INTEGRITY); + AssertIntEQ(memcmp(out, zero, sizeof(out)), 0); + + fwtpm_pass("Import outer integrity:", 0); +} +#endif /* !FWTPM_NO_KEY_MIGRATION */ + /* ================================================================== */ /* Group D: Hash/HMAC Sequences */ /* ================================================================== */ @@ -30939,6 +31034,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif #ifndef FWTPM_NO_KEY_MIGRATION test_fwtpm_rewrap_null_newparent_rejected(); + test_fwtpm_import_outer_integrity(); #ifndef FWTPM_NO_POLICY test_fwtpm_duplicate_encrypted_needs_new_parent(); test_fwtpm_duplicate_needs_command_code(); From a92db4f9564a5f05bd82dd5de9e160c9e2c1f388 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 10:44:24 -0800 Subject: [PATCH 077/124] F-16211 - Test the fwTPM TIS FIFO and status gates from a non-owning locality --- tests/fwtpm_hal_unit_tests.c | 105 +++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/tests/fwtpm_hal_unit_tests.c b/tests/fwtpm_hal_unit_tests.c index 83acd0847..9196a6b2b 100644 --- a/tests/fwtpm_hal_unit_tests.c +++ b/tests/fwtpm_hal_unit_tests.c @@ -741,6 +741,110 @@ static int TestTisFifoWiped(void) return failed; } +static int TisEngineSame(const FWTPM_TIS_REGS* a, const FWTPM_TIS_REGS* b) +{ + return a->sts == b->sts && a->cmd_len == b->cmd_len && + a->fifo_write_pos == b->fifo_write_pos && + a->fifo_read_pos == b->fifo_read_pos && a->rsp_len == b->rsp_len && + XMEMCMP(a->cmd_buf, b->cmd_buf, sizeof(a->cmd_buf)) == 0 && + XMEMCMP(a->rsp_buf, b->rsp_buf, sizeof(a->rsp_buf)) == 0; +} + +/* A locality that does not own the interface cannot ready, load, run or + * drain the FIFOs, and reads no status or data from them */ +static int TestTisNonOwnerLocality(void) +{ + static const int rspSize = 100; + static const UINT32 loc1 = 1U << 12; + FWTPM_CTX ctx; + FWTPM_TIS_REGS regs; + FWTPM_TIS_REGS before; + byte out[100]; + int failed = 0; + int i; + + TisGoSetup(&ctx, ®s); + gGoRc = TPM_RC_SUCCESS; + gGoRspSize = rspSize; + TisHandleRegAccess(&ctx, ®s); + XMEMSET(regs.cmd_buf, 0xC3, regs.cmd_len); + XMEMCPY(&before, ®s, sizeof(before)); + gGoPrivateBufs = 0; + + regs.reg_addr = loc1 | FWTPM_TIS_STS; + regs.reg_data[0] = FWTPM_STS_COMMAND_READY | FWTPM_STS_GO | + FWTPM_STS_RESP_RETRY; + TisHandleRegAccess(&ctx, ®s); + if (gGoPrivateBufs || !TisEngineSame(®s, &before)) { + failed = 1; + } + + regs.reg_addr = loc1 | FWTPM_TIS_DATA_FIFO; + regs.reg_len = 8; + XMEMSET(regs.reg_data, 0x5A, sizeof(regs.reg_data)); + TisHandleRegAccess(&ctx, ®s); + if (!TisEngineSame(®s, &before)) { + failed = 1; + } + + regs.reg_is_write = 0; + regs.reg_len = 16; + XMEMSET(regs.reg_data, 0xEE, sizeof(regs.reg_data)); + TisHandleRegAccess(&ctx, ®s); + if (!TisBufIsZero(regs.reg_data, sizeof(regs.reg_data)) || + !TisEngineSame(®s, &before)) { + failed = 1; + } + + regs.reg_addr = loc1 | FWTPM_TIS_STS; + regs.reg_len = 4; + TisHandleRegAccess(&ctx, ®s); + if (regs.reg_data[0] != FWTPM_STS_VALID || + !TisBufIsZero(regs.reg_data + 1, sizeof(regs.reg_data) - 1)) { + failed = 1; + } + regs.reg_addr = loc1 | FWTPM_TIS_BURST_COUNT_REG; + regs.reg_len = 2; + XMEMSET(regs.reg_data, 0xEE, sizeof(regs.reg_data)); + TisHandleRegAccess(&ctx, ®s); + if (!TisBufIsZero(regs.reg_data, sizeof(regs.reg_data)) || + !TisEngineSame(®s, &before)) { + failed = 1; + } + + /* the owner still finds its response */ + regs.reg_addr = FWTPM_TIS_BURST_COUNT_REG; + TisHandleRegAccess(&ctx, ®s); + if (regs.reg_data[0] != FWTPM_TIS_BURST_COUNT) { + failed = 1; + } + if (TisDrainFifo(&ctx, ®s, out, sizeof(out)) != (UINT32)rspSize) { + failed = 1; + } + for (i = 0; i < rspSize; i++) { + if (out[i] != TestRspByte(i)) { + failed = 1; + } + } + gGoRegs = NULL; + + /* with no owner, locality 0 is not one either */ + ctx.tisLocality = -1; + XMEMCPY(&before, ®s, sizeof(before)); + regs.reg_addr = FWTPM_TIS_DATA_FIFO; + regs.reg_is_write = 1; + regs.reg_len = 8; + XMEMSET(regs.reg_data, 0x5A, sizeof(regs.reg_data)); + TisHandleRegAccess(&ctx, ®s); + if (!TisEngineSame(®s, &before)) { + failed = 1; + } + + printf("%s: TIS FIFOs are closed to a non-owning locality\n", + failed ? "FAIL" : "PASS"); + return failed; +} + int main(void) { int failures = 0; @@ -782,6 +886,7 @@ int main(void) failures += TestTisGoFailure(TPM_RC_SUCCESS, FWTPM_TIS_FIFO_SIZE + 1, "an oversized response"); failures += TestTisFifoWiped(); + failures += TestTisNonOwnerLocality(); CleanupEndpoint(); printf("fwTPM HAL endpoint tests: %s\n", From ced38e8c631b82488cae0ea4967d465249105602 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 16:33:19 -0800 Subject: [PATCH 078/124] Let only platformAuth re-enable Clear in fwTPM ClearControl --- src/fwtpm/fwtpm_command.c | 10 +++++----- tests/fwtpm_unit_tests.c | 19 ++++++++++++++++++- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 4f0142c6c..d771e0e8b 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -7359,8 +7359,8 @@ static TPM_RC FwCmd_ChangePPS(FWTPM_CTX* ctx, TPM2_Packet* cmd, } /* --- TPM2_ClearControl (CC 0x0127) --- */ -/* Set or clear the disableClear flag. Only TPM_RH_PLATFORM can set - * disable=YES. Both platform and lockout can set disable=NO. */ +/* Set or clear the disableClear flag. Both platform and lockout can set + * disable=YES. Only TPM_RH_PLATFORM can set disable=NO. */ static TPM_RC FwCmd_ClearControl(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, TPM2_Packet* rsp, UINT16 cmdTag) { @@ -7386,9 +7386,9 @@ static TPM_RC FwCmd_ClearControl(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_HIERARCHY; } - /* Only platform can SET disable (disable=YES=1) */ - if (rc == 0 && disable == 1 && authHandle != TPM_RH_PLATFORM) { - rc = TPM_RC_AUTH_TYPE; + /* Only platform can CLEAR disable (disable=NO=0) */ + if (rc == 0 && disable == 0 && authHandle == TPM_RH_LOCKOUT) { + rc = TPM_RC_AUTH_FAIL; } if (rc == 0) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 8bd6fd5c5..caa7f8d2b 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -16936,6 +16936,16 @@ static void test_fwtpm_clear_disabled(void) TPM_RC_DISABLED); AssertIntEQ(memcmp(ownerSeed, ctx.ownerSeed, sizeof(ownerSeed)), 0); + /* lockoutAuth can set disableClear but not clear it */ + AssertIntEQ(SendClearControl(&ctx, TPM_RH_LOCKOUT, 0), TPM_RC_AUTH_FAIL); + AssertIntEQ(ctx.disableClear, 1); + AssertIntEQ(SendClearControl(&ctx, TPM_RH_PLATFORM, 0), TPM_RC_SUCCESS); + AssertIntEQ(ctx.disableClear, 0); + AssertIntEQ(SendClearControl(&ctx, TPM_RH_LOCKOUT, 1), TPM_RC_SUCCESS); + AssertIntEQ(ctx.disableClear, 1); + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_Clear, TPM_RH_LOCKOUT), + TPM_RC_DISABLED); + AssertIntEQ(SendClearControl(&ctx, TPM_RH_PLATFORM, 0), TPM_RC_SUCCESS); AssertIntEQ(ctx.disableClear, 0); AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_Clear, TPM_RH_LOCKOUT), @@ -29038,10 +29048,17 @@ static void test_fwtpm_clear_resets_lockout_auth(void) AssertIntEQ(fwtpm_test_startup(&ctx), 0); AssertIntEQ(ctx.lockoutAuth.size, 0); - /* ClearControl(TPM_RH_LOCKOUT, NO) with the Empty Auth */ + /* ClearControl(TPM_RH_LOCKOUT, YES) with the Empty Auth */ pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ClearControl); PutU32BE(gCmd + pos, TPM_RH_LOCKOUT); pos += 4; pos = AppendPwAuth(gCmd, pos, NULL, 0); + gCmd[pos++] = 1; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ClearControl); + PutU32BE(gCmd + pos, TPM_RH_PLATFORM); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); gCmd[pos++] = 0; PutU32BE(gCmd + 2, (UINT32)pos); FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); From c1205570675623d35122bb265c0a2fcf00fc953c Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 16:42:17 -0800 Subject: [PATCH 079/124] Return TPM_RC_NONCE for a fwTPM PolicySigned nonceTPM mismatch --- src/fwtpm/fwtpm_command.c | 4 +- tests/fwtpm_unit_tests.c | 77 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index d771e0e8b..b186855e4 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -14450,7 +14450,7 @@ static TPM_RC FwCmd_PolicySecret(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (nonceTpmSz != sess->nonceTPM.size || TPM2_ConstantCompare(nonceTpmBuf, sess->nonceTPM.buffer, nonceTpmSz) != 0) { - rc = TPM_RC_VALUE; + rc = TPM_RC_NONCE | TPM_RC_P | TPM_RC_1; } } @@ -15178,7 +15178,7 @@ static TPM_RC FwCmd_PolicySigned(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (nonceTpmSz != sess->nonceTPM.size || TPM2_ConstantCompare(nonceBuf, sess->nonceTPM.buffer, nonceTpmSz) != 0) { - rc = TPM_RC_VALUE; + rc = TPM_RC_NONCE | TPM_RC_P | TPM_RC_1; } } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index caa7f8d2b..efca6d145 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -29615,9 +29615,11 @@ static void test_fwtpm_policysigned(void) byte r[32], s[32], cc[4]; byte zero[WC_SHA256_DIGEST_SIZE]; byte expected[WC_SHA256_DIGEST_SIZE]; + byte nonce[TPM_MAX_DIGEST_SIZE]; memset(&ctx, 0, sizeof(ctx)); memset(zero, 0, sizeof(zero)); + memset(nonce, 0, sizeof(nonce)); AssertIntEQ(fwtpm_test_startup(&ctx), 0); gMockClockMs = 0; AssertIntEQ(FWTPM_Clock_SetHAL(&ctx, mock_clock_get_ms, NULL), 0); @@ -29655,6 +29657,14 @@ static void test_fwtpm_policysigned(void) /* the signature covers nonceTPM */ AssertIntEQ(SendPolicySigned(&ctx, keyH, sess->handle, NULL, 0, 0, r, s), TPM_RC_SIGNATURE); + /* a nonceTPM that is not the one of the session */ + memcpy(nonce, sess->nonceTPM.buffer, sess->nonceTPM.size); + nonce[0] ^= 0x01; + AssertIntEQ(SendPolicySigned(&ctx, keyH, sess->handle, nonce, + sess->nonceTPM.size, 0, r, s), TPM_RC_NONCE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendPolicySigned(&ctx, keyH, sess->handle, nonce, + (UINT16)(sess->nonceTPM.size - 1), 0, r, s), + TPM_RC_NONCE | TPM_RC_P | TPM_RC_1); AssertIntEQ(memcmp(sess->policyDigest.buffer, zero, sizeof(zero)), 0); AssertIntEQ(SendPolicySigned(&ctx, keyH, sess->handle, sess->nonceTPM.buffer, sess->nonceTPM.size, 0, r, s), @@ -29689,6 +29699,72 @@ static void test_fwtpm_policysigned(void) FWTPM_Cleanup(&ctx); fwtpm_pass("PolicySigned signature and expiration:", 0); } + +/* TPM2_PolicySecret by ownerAuth with an empty cpHashA and policyRef and no + * expiration */ +static TPM_RC SendPolicySecret(FWTPM_CTX* ctx, UINT32 sessH, + const byte* nonce, UINT16 nonceSz) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_PolicySecret); + int rspSize = 0; + + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, sessH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, nonceSz); pos += 2; + if (nonceSz > 0) { + memcpy(gCmd + pos, nonce, nonceSz); + } + pos += nonceSz; + PutU16BE(gCmd + pos, 0); pos += 2; /* cpHashA */ + PutU16BE(gCmd + pos, 0); pos += 2; /* policyRef */ + PutU32BE(gCmd + pos, 0); pos += 4; /* expiration */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* PolicySecret takes a nonceTPM only when it is the one of the policy + * session (Part 3 Sec.23.4). */ +static void test_fwtpm_policysecret_nonce(void) +{ + FWTPM_CTX ctx; + FWTPM_Session* sess = NULL; + UINT32 sessH; + byte zero[WC_SHA256_DIGEST_SIZE]; + byte nonce[TPM_MAX_DIGEST_SIZE]; + int i; + + memset(&ctx, 0, sizeof(ctx)); + memset(zero, 0, sizeof(zero)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + for (i = 0; i < FWTPM_MAX_SESSIONS; i++) { + if (ctx.sessions[i].used && ctx.sessions[i].handle == sessH) { + sess = &ctx.sessions[i]; + } + } + AssertNotNull(sess); + AssertIntGT(sess->nonceTPM.size, 1); + + memcpy(nonce, sess->nonceTPM.buffer, sess->nonceTPM.size); + nonce[0] ^= 0x01; + AssertIntEQ(SendPolicySecret(&ctx, sessH, nonce, sess->nonceTPM.size), + TPM_RC_NONCE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendPolicySecret(&ctx, sessH, nonce, + (UINT16)(sess->nonceTPM.size - 1)), + TPM_RC_NONCE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(memcmp(sess->policyDigest.buffer, zero, sizeof(zero)), 0); + nonce[0] ^= 0x01; + AssertIntEQ(SendPolicySecret(&ctx, sessH, nonce, sess->nonceTPM.size), + TPM_RC_SUCCESS); + AssertIntNE(memcmp(sess->policyDigest.buffer, zero, sizeof(zero)), 0); + + FlushHandle(&ctx, sessH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("PolicySecret nonceTPM:", 0); +} #endif /* !FWTPM_NO_POLICY */ /* Quote FW_TEST_PCR of one bank. On success *pcrDigestSz is the size of the @@ -31295,6 +31371,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_ecc_verify_scheme(); #ifndef FWTPM_NO_POLICY test_fwtpm_policysigned(); + test_fwtpm_policysecret_nonce(); #endif #endif #if !defined(FWTPM_NO_POLICY) && !defined(FWTPM_NO_NV) From e22f19fa13e6cf4c840c3bef227bca3dfdbafe9f Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 16:47:53 -0800 Subject: [PATCH 080/124] Hash the fwTPM PolicySigned aHash with the signature hash algorithm --- src/fwtpm/fwtpm_command.c | 22 +++++++++- tests/fwtpm_unit_tests.c | 92 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 106 insertions(+), 8 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index b186855e4..f125082f7 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -15101,6 +15101,7 @@ static TPM_RC FwCmd_PolicySigned(FWTPM_CTX* ctx, TPM2_Packet* cmd, UINT64 wireTimeout = 0; UINT64 now = 0; UINT32 ticketHierarchy = TPM_RH_NULL; + UINT16 aHashAlg = TPM_ALG_NULL; int entityNameSz = 0; int ticketDataSz = 0; int ticketHmacSz = 0; @@ -15208,14 +15209,31 @@ static TPM_RC FwCmd_PolicySigned(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_SIZE; } + /* aHash uses the hash of the signature, which need not be the session + * hash (Part 3 Sec.23.3). A signature that carries no hash keeps the + * session hash. */ + if (rc == 0 && sess->sessionType == TPM_SE_POLICY) { + aHashAlg = sess->authHash; + if (sig.sigAlg == TPM_ALG_RSASSA || sig.sigAlg == TPM_ALG_RSAPSS || + sig.sigAlg == TPM_ALG_ECDSA || sig.sigAlg == TPM_ALG_SM2 || + sig.sigAlg == TPM_ALG_ECSCHNORR || + sig.sigAlg == TPM_ALG_HMAC) { + aHashAlg = sig.signature.any.hashAlg; + } + if (FwGetWcHashType(aHashAlg) == WC_HASH_TYPE_NONE || + TPM2_GetHashDigestSize(aHashAlg) <= 0) { + rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_5; + } + } + /* For policy sessions (not trial): verify signature per TPM 2.0 Part 3 * Section 23.3. Compute aHash = H(nonceTPM || expiration || cpHashA || * policyRef), then verify signature against aHash using authObject's * public key. */ if (rc == 0 && sess->sessionType == TPM_SE_POLICY) { FWTPM_DECLARE_VAR(hashCtx, wc_HashAlg); - enum wc_HashType wcHash = FwGetWcHashType(sess->authHash); - int dSz = TPM2_GetHashDigestSize(sess->authHash); + enum wc_HashType wcHash = FwGetWcHashType(aHashAlg); + int dSz = TPM2_GetHashDigestSize(aHashAlg); byte aHash[TPM_MAX_DIGEST_SIZE]; byte expBuf[4]; int hrc; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index efca6d145..0ad02da87 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -29541,11 +29541,11 @@ static void test_fwtpm_ecc_verify_scheme(void) } #ifndef FWTPM_NO_POLICY -/* TPM2_PolicySigned with an ECDSA SHA-256 signature and an empty cpHashA - * and policyRef */ -static TPM_RC SendPolicySigned(FWTPM_CTX* ctx, UINT32 keyH, UINT32 sessH, - const byte* nonce, UINT16 nonceSz, INT32 expiration, const byte* r, - const byte* s) +/* TPM2_PolicySigned with an ECDSA signature and an empty cpHashA and + * policyRef */ +static TPM_RC SendPolicySignedHash(FWTPM_CTX* ctx, UINT32 keyH, UINT32 sessH, + const byte* nonce, UINT16 nonceSz, INT32 expiration, UINT16 sigHashAlg, + const byte* r, const byte* s) { int pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_PolicySigned); @@ -29562,7 +29562,7 @@ static TPM_RC SendPolicySigned(FWTPM_CTX* ctx, UINT32 keyH, UINT32 sessH, PutU16BE(gCmd + pos, 0); pos += 2; /* policyRef */ PutU32BE(gCmd + pos, (UINT32)expiration); pos += 4; PutU16BE(gCmd + pos, TPM_ALG_ECDSA); pos += 2; - PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU16BE(gCmd + pos, sigHashAlg); pos += 2; PutU16BE(gCmd + pos, 32); pos += 2; memcpy(gCmd + pos, r, 32); pos += 32; PutU16BE(gCmd + pos, 32); pos += 2; @@ -29572,6 +29572,14 @@ static TPM_RC SendPolicySigned(FWTPM_CTX* ctx, UINT32 keyH, UINT32 sessH, return GetRspRC(gRsp); } +static TPM_RC SendPolicySigned(FWTPM_CTX* ctx, UINT32 keyH, UINT32 sessH, + const byte* nonce, UINT16 nonceSz, INT32 expiration, const byte* r, + const byte* s) +{ + return SendPolicySignedHash(ctx, keyH, sessH, nonce, nonceSz, expiration, + TPM_ALG_SHA256, r, s); +} + /* Start a SHA-256 policy session and sign, with keyH, the aHash that * PolicySigned computes from its nonceTPM and the expiration. */ static FWTPM_Session* StartPolicySignedSession(FWTPM_CTX* ctx, UINT32 keyH, @@ -29700,6 +29708,75 @@ static void test_fwtpm_policysigned(void) fwtpm_pass("PolicySigned signature and expiration:", 0); } +#ifdef WOLFSSL_SHA384 +/* aHash is computed with the hash of the signature, here SHA-384 in a + * SHA-256 policy session (Part 3 Sec.23.3). */ +static void test_fwtpm_policysigned_sig_hash(void) +{ + FWTPM_CTX ctx; + FWTPM_Session* sess = NULL; + UINT32 keyH, sessH; + wc_HashAlg h; + byte r[32], s[32], exp[4]; + byte zero[WC_SHA256_DIGEST_SIZE]; + byte aHash[TPM_SHA384_DIGEST_SIZE]; + int i; + + memset(&ctx, 0, sizeof(ctx)); + memset(zero, 0, sizeof(zero)); + memset(exp, 0, sizeof(exp)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + /* fixedTPM|fixedParent|sensitiveDataOrigin|userWithAuth|noDA|sign */ + keyH = CreateEccSignPrimaryScheme(&ctx, 0x00040472, TPM_ALG_NULL, + TPM_ALG_NULL); + sessH = StartSessionHelper(&ctx, TPM_SE_POLICY); + for (i = 0; i < FWTPM_MAX_SESSIONS; i++) { + if (ctx.sessions[i].used && ctx.sessions[i].handle == sessH) { + sess = &ctx.sessions[i]; + } + } + AssertNotNull(sess); + AssertIntEQ(sess->authHash, TPM_ALG_SHA256); + + /* the session hash under a SHA-384 signature label does not verify */ + AssertIntEQ(wc_HashInit(&h, WC_HASH_TYPE_SHA256), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA256, + sess->nonceTPM.buffer, sess->nonceTPM.size), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA256, exp, sizeof(exp)), 0); + AssertIntEQ(wc_HashFinal(&h, WC_HASH_TYPE_SHA256, aHash), 0); + wc_HashFree(&h, WC_HASH_TYPE_SHA256); + AssertIntEQ(SendEccSign(&ctx, keyH, TPM_ALG_ECDSA, TPM_ALG_SHA256, aHash, + WC_SHA256_DIGEST_SIZE, r, s), TPM_RC_SUCCESS); + AssertIntEQ(SendPolicySignedHash(&ctx, keyH, sessH, + sess->nonceTPM.buffer, sess->nonceTPM.size, 0, TPM_ALG_SHA384, r, s), + TPM_RC_SIGNATURE); + AssertIntEQ(memcmp(sess->policyDigest.buffer, zero, sizeof(zero)), 0); + + AssertIntEQ(wc_HashInit(&h, WC_HASH_TYPE_SHA384), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA384, + sess->nonceTPM.buffer, sess->nonceTPM.size), 0); + AssertIntEQ(wc_HashUpdate(&h, WC_HASH_TYPE_SHA384, exp, sizeof(exp)), 0); + AssertIntEQ(wc_HashFinal(&h, WC_HASH_TYPE_SHA384, aHash), 0); + wc_HashFree(&h, WC_HASH_TYPE_SHA384); + AssertIntEQ(SendEccSign(&ctx, keyH, TPM_ALG_ECDSA, TPM_ALG_SHA384, aHash, + sizeof(aHash), r, s), TPM_RC_SUCCESS); + AssertIntEQ(SendPolicySignedHash(&ctx, keyH, sessH, + sess->nonceTPM.buffer, sess->nonceTPM.size, 0, TPM_ALG_NULL, r, s), + TPM_RC_SCHEME | TPM_RC_P | TPM_RC_5); + AssertIntEQ(SendPolicySignedHash(&ctx, keyH, sessH, + sess->nonceTPM.buffer, sess->nonceTPM.size, 0, TPM_ALG_SHA384, r, s), + TPM_RC_SUCCESS); + AssertIntEQ(sess->policyDigest.size, WC_SHA256_DIGEST_SIZE); + AssertIntNE(memcmp(sess->policyDigest.buffer, zero, sizeof(zero)), 0); + + FlushHandle(&ctx, sessH); + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("PolicySigned signature hash:", 0); +} +#endif /* WOLFSSL_SHA384 */ + /* TPM2_PolicySecret by ownerAuth with an empty cpHashA and policyRef and no * expiration */ static TPM_RC SendPolicySecret(FWTPM_CTX* ctx, UINT32 sessH, @@ -31371,6 +31448,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_ecc_verify_scheme(); #ifndef FWTPM_NO_POLICY test_fwtpm_policysigned(); +#ifdef WOLFSSL_SHA384 + test_fwtpm_policysigned_sig_hash(); +#endif test_fwtpm_policysecret_nonce(); #endif #endif From 389555e4fa34229589c4a5e0b8cfa17b9099c165 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 16:52:31 -0800 Subject: [PATCH 081/124] Accept a fwTPM HierarchyControl that enables an already enabled hierarchy --- src/fwtpm/fwtpm_command.c | 10 ++++++---- tests/fwtpm_unit_tests.c | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index f125082f7..bf37e1d6b 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -7452,18 +7452,20 @@ static TPM_RC FwCmd_HierarchyControl(FWTPM_CTX* ctx, TPM2_Packet* cmd, * this handler, so a set request can only be an idempotent no-op. */ /* Authorization (TPM 2.0 Part 3 Sec.24.3): platformAuth may set or clear - * any hierarchy; ownerAuth/endorsementAuth may only CLEAR their own - * hierarchy. Platform enables can only be changed by the platform. */ + * any hierarchy; ownerAuth/endorsementAuth may only select their own + * hierarchy and cannot enable it once it is disabled. Platform enables + * can only be changed by the platform. */ if (rc == 0) { if (authHandle == TPM_RH_PLATFORM) { /* allowed for all combinations */ } else if (authHandle == TPM_RH_OWNER && enable == TPM_RH_OWNER && - state == 0) { + (state == 0 || !ctx->shDisabled)) { /* owner may disable itself */ } else if (authHandle == TPM_RH_ENDORSEMENT && - enable == TPM_RH_ENDORSEMENT && state == 0) { + enable == TPM_RH_ENDORSEMENT && + (state == 0 || !ctx->ehDisabled)) { /* endorsement may disable itself */ } else { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 0ad02da87..67c401ab3 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -17135,6 +17135,24 @@ static void test_fwtpm_hierarchy_control(void) ctx.objects[1].handle = TRANSIENT_FIRST + 1; ctx.objects[1].hierarchy = TPM_RH_ENDORSEMENT; + /* enabling a hierarchy that is enabled changes nothing */ + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_OWNER, TPM_RH_OWNER, 1), + TPM_RC_SUCCESS); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_ENDORSEMENT, + TPM_RH_ENDORSEMENT, 1), TPM_RC_SUCCESS); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_OWNER, TPM_RH_ENDORSEMENT, + 1), TPM_RC_AUTH_TYPE); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_ENDORSEMENT, TPM_RH_OWNER, + 1), TPM_RC_AUTH_TYPE); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_OWNER, TPM_RH_PLATFORM, 1), + TPM_RC_AUTH_TYPE); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_OWNER, TPM_RH_PLATFORM_NV, + 1), TPM_RC_AUTH_TYPE); + AssertIntEQ(ctx.shDisabled | ctx.ehDisabled | ctx.phDisabled | + ctx.phNvDisabled, 0); + AssertIntEQ(ctx.objects[0].used, 1); + AssertIntEQ(ctx.objects[1].used, 1); + AssertIntEQ(SendHierarchyControl(&ctx, TPM_RH_OWNER, TPM_RH_OWNER, 0), TPM_RC_SUCCESS); AssertIntEQ(ctx.shDisabled, 1); From 773eb8a90b522682e40ab127edcfa9883c875e7e Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 17:05:56 -0800 Subject: [PATCH 082/124] Reject a fwTPM attestation inScheme that disagrees with the key scheme --- src/fwtpm/fwtpm_command.c | 60 ++++++--------- src/fwtpm/fwtpm_crypto.c | 36 +++++++++ tests/fwtpm_unit_tests.c | 143 ++++++++++++++++++++++++++++++++++- wolftpm/fwtpm/fwtpm_crypto.h | 3 + 4 files changed, 203 insertions(+), 39 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index bf37e1d6b..5069e05a1 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -80,7 +80,7 @@ /* --- Forward declarations for command-local helpers --- */ #ifndef FWTPM_NO_ATTESTATION static TPM_RC FwParseAttestParams(TPM2_Packet* cmd, int cmdSize, - UINT16 cmdTag, TPM2B_DATA* qualifyingData, + UINT16 cmdTag, const FWTPM_Object* sigObj, TPM2B_DATA* qualifyingData, UINT16* sigScheme, UINT16* sigHashAlg); #endif /* !FWTPM_NO_ATTESTATION */ @@ -10812,28 +10812,12 @@ static TPM_RC FwCmd_Sign(FWTPM_CTX* ctx, TPM2_Packet* cmd, } /* Part 3 Sec.20.2: an inScheme has to agree with the scheme and hash - * of a key that has them */ - if (rc == 0 && sigScheme != TPM_ALG_NULL) { - UINT16 keyScheme = TPM_ALG_NULL; - UINT16 keyHashAlg = TPM_ALG_NULL; - if (obj->pub.type == TPM_ALG_RSA) { - keyScheme = obj->pub.parameters.rsaDetail.scheme.scheme; - keyHashAlg = obj->pub.parameters.rsaDetail.scheme.details - .anySig.hashAlg; - } - else if (obj->pub.type == TPM_ALG_ECC) { - keyScheme = obj->pub.parameters.eccDetail.scheme.scheme; - keyHashAlg = obj->pub.parameters.eccDetail.scheme.details - .any.hashAlg; - } - if (keyScheme != TPM_ALG_NULL && - (sigScheme != keyScheme || sigHashAlg != keyHashAlg)) { - rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; - } + * of a key that has them, and a key that has none needs an inScheme */ + if (rc == 0 && FwCheckSignScheme(obj, sigScheme, sigHashAlg) != 0) { + rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; } if (rc == 0) { - /* A NULL inScheme takes the key's scheme, or the default for a key - * that has none */ + /* A NULL inScheme takes the key's scheme */ FwResolveSignScheme(obj, &sigScheme, &sigHashAlg); } /* Part 3 Sec.20.2.1: digest size MUST match the scheme hashAlg digest @@ -18927,9 +18911,10 @@ static TPM_RC FwAppendAttestCommonHeader(FWTPM_CTX* ctx, TPM2_Packet* pkt, #ifndef FWTPM_NO_ATTESTATION /* Helper: parse common attestation command parameters. * Skips auth area, parses qualifyingData (TPM2B_DATA), and inScheme - * (sigScheme + sigHashAlg). Called after handle parsing is complete. */ + * (sigScheme + sigHashAlg), which has to suit the signing key sigObj. + * Called after handle parsing is complete. */ static TPM_RC FwParseAttestParams(TPM2_Packet* cmd, int cmdSize, - UINT16 cmdTag, TPM2B_DATA* qualifyingData, + UINT16 cmdTag, const FWTPM_Object* sigObj, TPM2B_DATA* qualifyingData, UINT16* sigScheme, UINT16* sigHashAlg) { TPM_RC rc = TPM_RC_SUCCESS; @@ -18977,6 +18962,11 @@ static TPM_RC FwParseAttestParams(TPM2_Packet* cmd, int cmdSize, } } } + /* A key that cannot sign is left for FwSignAttest to reject */ + if (rc == 0 && (sigObj->pub.objectAttributes & TPMA_OBJECT_sign) && + FwCheckSignScheme(sigObj, *sigScheme, *sigHashAlg) != 0) { + rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; + } return rc; } @@ -19049,20 +19039,9 @@ static TPM_RC FwCmd_Quote(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { - rc = FwParseAttestParams(cmd, cmdSize, cmdTag, + rc = FwParseAttestParams(cmd, cmdSize, cmdTag, sigObj, &qualifyingData, &sigScheme, &sigHashAlg); } - /* A key with no scheme of its own needs one from inScheme - * (Part 3 Sec.18.4) */ - if (rc == 0 && sigScheme == TPM_ALG_NULL && - ((sigObj->pub.type == TPM_ALG_RSA && - sigObj->pub.parameters.rsaDetail.scheme.scheme == - TPM_ALG_NULL) || - (sigObj->pub.type == TPM_ALG_ECC && - sigObj->pub.parameters.eccDetail.scheme.scheme == - TPM_ALG_NULL))) { - rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; - } /* PCRselect */ if (rc == 0) { @@ -19212,7 +19191,7 @@ static TPM_RC FwCmd_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { - rc = FwParseAttestParams(cmd, cmdSize, cmdTag, + rc = FwParseAttestParams(cmd, cmdSize, cmdTag, sigObj, &qualifyingData, &sigScheme, &sigHashAlg); } @@ -19345,6 +19324,11 @@ static TPM_RC FwCmd_CertifyCreation(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } } + /* A key that cannot sign is left for FwSignAttest to reject */ + if (rc == 0 && (sigObj->pub.objectAttributes & TPMA_OBJECT_sign) && + FwCheckSignScheme(sigObj, sigScheme, sigHashAlg) != 0) { + rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_3; + } /* creationTicket verification per TPM 2.0 Part 3 Section 18.3 */ if (rc == 0 && cmd->pos + 8 > cmdSize) { @@ -19487,7 +19471,7 @@ static TPM_RC FwCmd_GetTime(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { - rc = FwParseAttestParams(cmd, cmdSize, cmdTag, + rc = FwParseAttestParams(cmd, cmdSize, cmdTag, sigObj, &qualifyingData, &sigScheme, &sigHashAlg); } @@ -19576,7 +19560,7 @@ static TPM_RC FwCmd_NV_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { - rc = FwParseAttestParams(cmd, cmdSize, cmdTag, + rc = FwParseAttestParams(cmd, cmdSize, cmdTag, sigObj, &qualifyingData, &sigScheme, &sigHashAlg); } diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 0e9cafb03..b56cd917b 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -4844,6 +4844,42 @@ void FwResolveSignScheme(FWTPM_Object* obj, UINT16* sigScheme, } } +/* Helper: check a command inScheme against an RSA or ECC signing key + * (Part 3 Sec.18 and Sec.20.2). An inScheme has to agree with the scheme + * and hash of a key that has them, and a key that has none needs one from + * inScheme. Returns TPM_RC_SCHEME for the caller to decorate. */ +TPM_RC FwCheckSignScheme(const FWTPM_Object* obj, UINT16 sigScheme, + UINT16 sigHashAlg) +{ + UINT16 keyScheme = TPM_ALG_NULL; + UINT16 keyHashAlg = TPM_ALG_NULL; + + if (obj->pub.type == TPM_ALG_RSA) { + keyScheme = obj->pub.parameters.rsaDetail.scheme.scheme; + keyHashAlg = obj->pub.parameters.rsaDetail.scheme.details + .anySig.hashAlg; + } + else if (obj->pub.type == TPM_ALG_ECC) { + keyScheme = obj->pub.parameters.eccDetail.scheme.scheme; + keyHashAlg = obj->pub.parameters.eccDetail.scheme.details + .any.hashAlg; + } + else { + return TPM_RC_SUCCESS; + } + + if (keyScheme == TPM_ALG_NULL) { + if (sigScheme == TPM_ALG_NULL) { + return TPM_RC_SCHEME; + } + } + else if (sigScheme != TPM_ALG_NULL && + (sigScheme != keyScheme || sigHashAlg != keyHashAlg)) { + return TPM_RC_SCHEME; + } + return TPM_RC_SUCCESS; +} + #ifndef FWTPM_NO_ATTESTATION /* Helper: build attestation response -- append TPM2B_ATTEST, sign, finalize. * Caller has already built attestBuf via attestPkt. */ diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 67c401ab3..62c8fd2c0 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -4896,7 +4896,7 @@ static void test_fwtpm_quote_mldsa_scheme_on_ecc_rejected(void) PutU32BE(gCmd + 2, (UINT32)pos); AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0), TPM_RC_SUCCESS); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_SCHEME); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); FlushHandle(&ctx, keyH); FWTPM_Cleanup(&ctx); @@ -29941,6 +29941,146 @@ static void test_fwtpm_quote_scheme_hash(void) FWTPM_Cleanup(&ctx); fwtpm_pass("Quote pcrDigest uses scheme hash:", 0); } + +/* An attestation command signed by keyH with the given inScheme. Certify + * certifies keyH itself, CertifyCreation is sent an empty creation ticket + * and NV_Certify reads one octet of nvIndex by ownerAuth. */ +static TPM_RC SendAttestScheme(FWTPM_CTX* ctx, UINT32 cc, UINT32 keyH, + UINT32 nvIndex, UINT16 sigScheme, UINT16 sigHashAlg) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, cc); + int rspSize = 0; + int i; + + if (cc == TPM_CC_GetTime) { + PutU32BE(gCmd + pos, TPM_RH_ENDORSEMENT); pos += 4; + } + PutU32BE(gCmd + pos, keyH); pos += 4; + if (cc == TPM_CC_Certify || cc == TPM_CC_CertifyCreation) { + PutU32BE(gCmd + pos, keyH); pos += 4; + } + if (cc == TPM_CC_NV_Certify) { + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, nvIndex); pos += 4; + } + if (cc == TPM_CC_Quote || cc == TPM_CC_CertifyCreation) { + pos = AppendPwAuth(gCmd, pos, NULL, 0); + } + else { + PutU32BE(gCmd + pos, 18); pos += 4; /* two password sessions */ + for (i = 0; i < 2; i++) { + PutU32BE(gCmd + pos, TPM_RS_PW); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; /* nonce */ + gCmd[pos++] = 0; /* attributes */ + PutU16BE(gCmd + pos, 0); pos += 2; /* hmac */ + } + } + PutU16BE(gCmd + pos, 0); pos += 2; /* qualifyingData */ + if (cc == TPM_CC_CertifyCreation) { + PutU16BE(gCmd + pos, 0); pos += 2; /* creationHash */ + } + PutU16BE(gCmd + pos, sigScheme); pos += 2; + if (sigScheme != TPM_ALG_NULL) { + PutU16BE(gCmd + pos, sigHashAlg); pos += 2; + } + if (cc == TPM_CC_Quote) { + PutU32BE(gCmd + pos, 1); pos += 4; /* PCRselect */ + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + gCmd[pos++] = (byte)PCR_SELECT_MAX; + memset(gCmd + pos, 0, PCR_SELECT_MAX); pos += PCR_SELECT_MAX; + } + else if (cc == TPM_CC_CertifyCreation) { + PutU16BE(gCmd + pos, TPM_ST_CREATION); pos += 2; + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; + } + else if (cc == TPM_CC_NV_Certify) { + PutU16BE(gCmd + pos, 1); pos += 2; /* size */ + PutU16BE(gCmd + pos, 0); pos += 2; /* offset */ + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* An attestation inScheme has to agree with the scheme and hash of a key + * that has them, and a key that has none needs one from inScheme (Part 3 + * Sec.18). The same holds for a Sign of a key with no scheme. */ +static void test_fwtpm_attest_inscheme(void) +{ + FWTPM_CTX ctx; + UINT32 openH, fixedH; + UINT32 nvIdx = 0; + UINT32 cmds[5]; + TPM_RC blame, done; + byte digest[WC_SHA256_DIGEST_SIZE]; + int i, n = 0; +#ifndef FWTPM_NO_NV + int cmdSz, rspSize = 0; +#endif + + memset(&ctx, 0, sizeof(ctx)); + memset(digest, 0x5C, sizeof(digest)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmds[n++] = TPM_CC_Quote; + cmds[n++] = TPM_CC_Certify; + cmds[n++] = TPM_CC_CertifyCreation; + cmds[n++] = TPM_CC_GetTime; +#ifndef FWTPM_NO_NV + nvIdx = 0x01500A20; + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, 1, + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerAccessCmd(&ctx, nvIdx, 1), TPM_RC_SUCCESS); + cmds[n++] = TPM_CC_NV_Certify; +#endif + + /* fixedTPM|fixedParent|sensitiveDataOrigin|userWithAuth|noDA|sign */ + fixedH = CreateEccSignPrimaryScheme(&ctx, 0x00040472, TPM_ALG_ECDSA, + TPM_ALG_SHA256); + openH = CreateEccSignPrimaryScheme(&ctx, 0x00040472, TPM_ALG_NULL, + TPM_ALG_NULL); + + for (i = 0; i < n; i++) { + /* the empty creation ticket is looked at after inScheme */ + blame = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; + done = TPM_RC_SUCCESS; + if (cmds[i] == TPM_CC_CertifyCreation) { + blame = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_3; + done = TPM_RC_TICKET; + } + + AssertIntEQ(SendAttestScheme(&ctx, cmds[i], fixedH, nvIdx, + TPM_ALG_ECDSA, TPM_ALG_SHA384), blame); + AssertIntEQ(SendAttestScheme(&ctx, cmds[i], fixedH, nvIdx, + TPM_ALG_ECSCHNORR, TPM_ALG_SHA256), blame); + AssertIntEQ(SendAttestScheme(&ctx, cmds[i], fixedH, nvIdx, + TPM_ALG_ECDSA, TPM_ALG_SHA256), done); + AssertIntEQ(SendAttestScheme(&ctx, cmds[i], fixedH, nvIdx, + TPM_ALG_NULL, TPM_ALG_NULL), done); + + AssertIntEQ(SendAttestScheme(&ctx, cmds[i], openH, nvIdx, + TPM_ALG_NULL, TPM_ALG_NULL), blame); + AssertIntEQ(SendAttestScheme(&ctx, cmds[i], openH, nvIdx, + TPM_ALG_ECDSA, TPM_ALG_SHA256), done); + } + + AssertIntEQ(SendEccSign(&ctx, openH, TPM_ALG_NULL, TPM_ALG_NULL, digest, + sizeof(digest), NULL, NULL), TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + AssertIntEQ(SendEccSign(&ctx, openH, TPM_ALG_ECDSA, TPM_ALG_SHA256, + digest, sizeof(digest), NULL, NULL), TPM_RC_SUCCESS); + + FlushHandle(&ctx, openH); + FlushHandle(&ctx, fixedH); +#ifndef FWTPM_NO_NV + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); +#endif + FWTPM_Cleanup(&ctx); + fwtpm_pass("Attestation inScheme against the key scheme:", 0); +} #endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION */ #if !defined(FWTPM_NO_POLICY) && !defined(FWTPM_NO_NV) @@ -31462,6 +31602,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) test_fwtpm_quote_scheme_hash(); + test_fwtpm_attest_inscheme(); test_fwtpm_ecc_sign_scheme(); test_fwtpm_ecc_verify_scheme(); #ifndef FWTPM_NO_POLICY diff --git a/wolftpm/fwtpm/fwtpm_crypto.h b/wolftpm/fwtpm/fwtpm_crypto.h index 2c43dbfc2..6f5299849 100644 --- a/wolftpm/fwtpm/fwtpm_crypto.h +++ b/wolftpm/fwtpm/fwtpm_crypto.h @@ -372,6 +372,9 @@ int FwComputeNvName(FWTPM_NvIndex* nv, byte* buf, UINT16* sz); void FwResolveSignScheme(FWTPM_Object* obj, UINT16* sigScheme, UINT16* sigHashAlg); +TPM_RC FwCheckSignScheme(const FWTPM_Object* obj, UINT16 sigScheme, + UINT16 sigHashAlg); + #ifndef FWTPM_NO_ATTESTATION TPM_RC FwBuildAttestResponse(FWTPM_CTX* ctx, TPM2_Packet* rsp, UINT16 cmdTag, FWTPM_Object* sigObj, UINT16 sigScheme, UINT16 sigHashAlg, From ef10b4fb595a8581bb607eb9efc7ab29240a3456 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 18:21:57 -0800 Subject: [PATCH 083/124] F-16226 - Track the Qualified Name of fwTPM objects --- src/fwtpm/fwtpm_command.c | 143 ++++++++++--- src/fwtpm/fwtpm_nv.c | 18 +- tests/fwtpm_unit_tests.c | 437 ++++++++++++++++++++++++++++++++++++-- wolftpm/fwtpm/fwtpm.h | 1 + 4 files changed, 557 insertions(+), 42 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 5069e05a1..4b3a91a92 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -4453,6 +4453,52 @@ static FWTPM_Object* FwFindObject(FWTPM_CTX* ctx, TPM_HANDLE handle) return NULL; } +/* Qualified Name of an object whose Name is set (Part 1 Sec.16): + * nameAlg || H(parent QN || Name). The parent QN of a primary object is the + * handle of its hierarchy. An external object has no parent and its + * Qualified Name is its Name. */ +static TPM_RC FwComputeQualifiedName(const FWTPM_Object* obj, + const FWTPM_Object* parent, TPM_HANDLE hierarchy, int external, + TPM2B_NAME* qualifiedName) +{ + TPM_RC rc = TPM_RC_SUCCESS; + enum wc_HashType wcHash = FwGetWcHashType(obj->pub.nameAlg); + int digestSz = TPM2_GetHashDigestSize(obj->pub.nameAlg); + byte data[2 * sizeof(obj->name.name)]; + word32 dataSz = 0; + + if (external) { + *qualifiedName = obj->name; + return TPM_RC_SUCCESS; + } + if (wcHash == WC_HASH_TYPE_NONE || digestSz <= 0 || + digestSz + 2 > (int)sizeof(qualifiedName->name) || + obj->name.size > sizeof(obj->name.name) || + (parent != NULL && + parent->qualifiedName.size > sizeof(obj->name.name))) { + return TPM_RC_HASH; + } + if (parent != NULL) { + XMEMCPY(data, parent->qualifiedName.name, parent->qualifiedName.size); + dataSz = parent->qualifiedName.size; + } + else { + FwStoreU32BE(data, hierarchy); + dataSz = 4; + } + XMEMCPY(data + dataSz, obj->name.name, obj->name.size); + dataSz += obj->name.size; + if (wc_Hash(wcHash, data, dataSz, qualifiedName->name + 2, + (word32)digestSz) != 0) { + rc = TPM_RC_FAILURE; + } + if (rc == 0) { + FwStoreU16BE(qualifiedName->name, obj->pub.nameAlg); + qualifiedName->size = (UINT16)(digestSz + 2); + } + return rc; +} + /** \brief Free an object slot, securely zeroing all key material. */ static void FwFreeObject(FWTPM_Object* obj) { @@ -4749,10 +4795,9 @@ static TPM_RC FwAppendCreationData(FWTPM_CTX* ctx, TPM2_Packet* rsp, TPM2_Packet_AppendU16(rsp, parent->name.size); TPM2_Packet_AppendBytes(rsp, (byte*)parent->name.name, parent->name.size); - /* Qualified Names are not tracked: the Name stands in */ - TPM2_Packet_AppendU16(rsp, parent->name.size); - TPM2_Packet_AppendBytes(rsp, (byte*)parent->name.name, - parent->name.size); + TPM2_Packet_AppendU16(rsp, parent->qualifiedName.size); + TPM2_Packet_AppendBytes(rsp, (byte*)parent->qualifiedName.name, + parent->qualifiedName.size); } TPM2_Packet_AppendU16(rsp, outsideInfoSz); TPM2_Packet_AppendBytes(rsp, (byte*)outsideInfo, outsideInfoSz); @@ -5244,6 +5289,10 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { rc = FwComputeObjectName(obj); } + if (rc == 0) { + rc = FwComputeQualifiedName(obj, NULL, primaryHandle, 0, + &obj->qualifiedName); + } /* --- Build response --- */ if (rc == 0) { @@ -6384,6 +6433,9 @@ static TPM_RC FwSerializeObjectContext(FWTPM_CTX* ctx, FWTPM_Object* obj, TPM2_Packet_AppendBytes(&packet, obj->authValue.buffer, obj->authValue.size); TPM2_Packet_AppendU16(&packet, (UINT16)obj->privKeySize); TPM2_Packet_AppendBytes(&packet, obj->privKey, obj->privKeySize); + TPM2_Packet_AppendU16(&packet, obj->qualifiedName.size); + TPM2_Packet_AppendBytes(&packet, (byte*)obj->qualifiedName.name, + obj->qualifiedName.size); TPM2_Packet_AppendU8(&packet, (UINT8)(obj->publicOnly != 0)); if (packet.overflow) { rc = TPM_RC_SIZE; @@ -6403,13 +6455,13 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, FWTPM_DECLARE_VAR(pub, TPM2B_PUBLIC); FWTPM_Object* obj = NULL; byte proof[WC_SHA256_DIGEST_SIZE]; - UINT16 pubSz, authSz = 0, privateSz = 0; - int authPos = 0, privatePos = 0, publicEnd; + UINT16 pubSz, authSz = 0, privateSz = 0, qnSz = 0; + int authPos = 0, privatePos = 0, qnPos = 0, publicEnd; int flagPos = 0; UINT32 expectedMarker; - /* hierarchy + proof + public/auth/private size fields */ - if (plainSz < 4 + (int)sizeof(proof) + 6 || + /* hierarchy + proof + public/auth/private/qualifiedName size fields */ + if (plainSz < 4 + (int)sizeof(proof) + 8 || FwLoadU32BE(plain) != hierarchy) { return TPM_RC_INTEGRITY; } @@ -6431,7 +6483,7 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, packet.pos = 4 + sizeof(proof); pubSz = FwLoadU16BE(plain + packet.pos); publicEnd = packet.pos + 2 + pubSz; - if (publicEnd > plainSz - 4) { + if (publicEnd > plainSz - 6) { rc = TPM_RC_INTEGRITY; } else { @@ -6455,7 +6507,7 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, TPM2_Packet_ParseU16(&packet, &authSz); authPos = packet.pos; if (authSz > sizeof(((FWTPM_Object*)0)->authValue.buffer) || - authPos + authSz > plainSz - 2) { + authPos + authSz > plainSz - 4) { rc = TPM_RC_INTEGRITY; } } @@ -6464,14 +6516,23 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, TPM2_Packet_ParseU16(&packet, &privateSz); privatePos = packet.pos; if (privateSz > FWTPM_MAX_PRIVKEY_DER || - privatePos + privateSz > plainSz) { + privatePos + privateSz > plainSz - 2) { + rc = TPM_RC_INTEGRITY; + } + } + if (rc == 0) { + packet.pos += privateSz; + TPM2_Packet_ParseU16(&packet, &qnSz); + qnPos = packet.pos; + if (qnSz > sizeof(((FWTPM_Object*)0)->qualifiedName.name) || + qnPos + qnSz > plainSz) { rc = TPM_RC_INTEGRITY; } } - /* The public-only flag trails the private data; a blob saved without it + /* The public-only flag trails the Qualified Name; a blob saved without it * ends there */ - if (rc == 0 && privatePos + privateSz != plainSz) { - flagPos = privatePos + privateSz; + if (rc == 0 && qnPos + qnSz != plainSz) { + flagPos = qnPos + qnSz; if (flagPos + 1 != plainSz) { rc = TPM_RC_INTEGRITY; } @@ -6489,6 +6550,8 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, XMEMCPY(obj->authValue.buffer, plain + authPos, authSz); obj->privKeySize = privateSz; XMEMCPY(obj->privKey, plain + privatePos, privateSz); + obj->qualifiedName.size = qnSz; + XMEMCPY(obj->qualifiedName.name, plain + qnPos, qnSz); /* Without the flag only an object that has no private data is taken * to be public-only */ obj->publicOnly = (flagPos != 0) ? (plain[flagPos] != 0) : @@ -7006,9 +7069,10 @@ static TPM_RC FwCmd_ReadPublic(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_AppendU16(rsp, obj->name.size); TPM2_Packet_AppendBytes(rsp, obj->name.name, obj->name.size); - /* qualifiedName - same as name for primary keys */ - TPM2_Packet_AppendU16(rsp, obj->name.size); - TPM2_Packet_AppendBytes(rsp, obj->name.name, obj->name.size); + /* qualifiedName */ + TPM2_Packet_AppendU16(rsp, obj->qualifiedName.size); + TPM2_Packet_AppendBytes(rsp, obj->qualifiedName.name, + obj->qualifiedName.size); FwRspParamsEnd(rsp, cmdTag, paramSzPos, paramStart); } @@ -8505,6 +8569,7 @@ static TPM_RC FwCmd_ObjectChangeAuth(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_Object* obj = NULL; FWTPM_Object* parent = NULL; TPM2B_PRIVATE outPrivate; + TPM2B_NAME parentCheck; int paramSzPos = 0, paramStart = 0; XMEMSET(&newAuth, 0, sizeof(newAuth)); @@ -8565,6 +8630,17 @@ static TPM_RC FwCmd_ObjectChangeAuth(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + /* parentHandle has to be the parent of the object: its Qualified Name + * gives the Qualified Name of the object */ + if (rc == 0) { + rc = FwComputeQualifiedName(obj, parent, 0, 0, &parentCheck); + } + if (rc == 0 && (parentCheck.size != obj->qualifiedName.size || + XMEMCMP(parentCheck.name, obj->qualifiedName.name, + parentCheck.size) != 0)) { + rc = TPM_RC_TYPE | TPM_RC_H | TPM_RC_2; + } + /* Re-wrap the private key; the loaded object keeps its current auth. */ if (rc == 0) { rc = FwWrapPrivate(ctx, parent, &ctx->rng, &obj->name, obj->pub.type, @@ -8685,6 +8761,10 @@ static TPM_RC FwCmd_Load(FWTPM_CTX* ctx, TPM2_Packet* cmd, obj->hierarchy = parent->hierarchy; rc = FwComputeObjectName(obj); } + if (rc == 0) { + rc = FwComputeQualifiedName(obj, parent, 0, 0, + &obj->qualifiedName); + } /* Unwrap private */ if (rc == 0) { @@ -9112,6 +9192,9 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { rc = FwComputeObjectName(obj); } + if (rc == 0) { + rc = FwComputeQualifiedName(obj, NULL, 0, 1, &obj->qualifiedName); + } /* --- Build response --- */ if (rc == 0) { @@ -10668,6 +10751,10 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = FwComputeObjectName(obj); } + if (rc == 0) { + rc = FwComputeQualifiedName(obj, parent, 0, 0, + &obj->qualifiedName); + } /* --- Build response --- */ if (rc == 0) { @@ -19071,7 +19158,8 @@ static TPM_RC FwCmd_Quote(FWTPM_CTX* ctx, TPM2_Packet* cmd, attestPkt.size = (int)FWTPM_MAX_ATTEST_BUF; rc = FwAppendAttestCommonHeader(ctx, &attestPkt, - TPM_ST_ATTEST_QUOTE, sigObj, &sigObj->name, &qualifyingData); + TPM_ST_ATTEST_QUOTE, sigObj, &sigObj->qualifiedName, + &qualifyingData); /* attested.quote: pcrSelect (TPML_PCR_SELECTION) + * pcrDigest (TPM2B_DIGEST) */ @@ -19207,16 +19295,17 @@ static TPM_RC FwCmd_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, attestPkt.size = (int)FWTPM_MAX_ATTEST_BUF; rc = FwAppendAttestCommonHeader(ctx, &attestPkt, - TPM_ST_ATTEST_CERTIFY, sigObj, &sigObj->name, &qualifyingData); + TPM_ST_ATTEST_CERTIFY, sigObj, &sigObj->qualifiedName, + &qualifyingData); /* attested.certify: name + qualifiedName */ TPM2_Packet_AppendU16(&attestPkt, objToSign->name.size); TPM2_Packet_AppendBytes(&attestPkt, (byte*)objToSign->name.name, objToSign->name.size); - /* qualifiedName = same as name in our simple hierarchy */ - TPM2_Packet_AppendU16(&attestPkt, objToSign->name.size); - TPM2_Packet_AppendBytes(&attestPkt, (byte*)objToSign->name.name, - objToSign->name.size); + TPM2_Packet_AppendU16(&attestPkt, objToSign->qualifiedName.size); + TPM2_Packet_AppendBytes(&attestPkt, + (byte*)objToSign->qualifiedName.name, + objToSign->qualifiedName.size); /* Build response */ if (rc == 0) { @@ -19414,7 +19503,8 @@ static TPM_RC FwCmd_CertifyCreation(FWTPM_CTX* ctx, TPM2_Packet* cmd, attestPkt.size = (int)FWTPM_MAX_ATTEST_BUF; rc = FwAppendAttestCommonHeader(ctx, &attestPkt, - TPM_ST_ATTEST_CREATION, sigObj, &sigObj->name, &qualifyingData); + TPM_ST_ATTEST_CREATION, sigObj, &sigObj->qualifiedName, + &qualifyingData); /* attested.creation: objectName (TPM2B_NAME) + * creationHash (TPM2B_DIGEST) */ @@ -19483,7 +19573,8 @@ static TPM_RC FwCmd_GetTime(FWTPM_CTX* ctx, TPM2_Packet* cmd, attestPkt.size = (int)FWTPM_MAX_PUB_BUF; rc = FwAppendAttestCommonHeader(ctx, &attestPkt, - TPM_ST_ATTEST_TIME, sigObj, &sigObj->name, &qualifyingData); + TPM_ST_ATTEST_TIME, sigObj, &sigObj->qualifiedName, + &qualifyingData); /* attested.time: TPMS_TIME_INFO (time + clockInfo) + * firmwareVersion */ @@ -19628,7 +19719,7 @@ static TPM_RC FwCmd_NV_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, attestPkt.size = (int)FWTPM_MAX_ATTEST_BUF; rc = FwAppendAttestCommonHeader(ctx, &attestPkt, attestType, - sigObj, &sigObj->name, &qualifyingData); + sigObj, &sigObj->qualifiedName, &qualifyingData); if (digestMode) { /* attested.nvDigest: indexName + nvDigest diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index 80b2dfa67..05880d4ce 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -672,6 +672,10 @@ static int FwNvMarshalObject(byte* buf, word32* pos, word32 maxSz, if (rc == 0) { rc = FwNvMarshalU32(buf, pos, maxSz, obj->hierarchy); } + /* Appended last so an older record still parses */ + if (rc == 0) { + rc = FwNvMarshalName(buf, pos, maxSz, &obj->qualifiedName); + } if (rc == 0) { rc = FwNvMarshalU8(buf, pos, maxSz, (UINT8)(obj->publicOnly != 0)); } @@ -727,6 +731,14 @@ static int FwNvUnmarshalObject(const byte* buf, word32* pos, word32 maxSz, else if (rc == 0 && obj->handle >= PLATFORM_PERSISTENT) { obj->hierarchy = TPM_RH_PLATFORM; } + /* Optional trailing Qualified Name. A record written without it does + * not say what the parent was, so the Name stands in. */ + if (rc == 0 && *pos + 2 <= maxSz) { + rc = FwNvUnmarshalName(buf, pos, maxSz, &obj->qualifiedName); + } + else if (rc == 0) { + obj->qualifiedName = obj->name; + } /* Optional trailing public-only flag. A record written without it holds * a public-only object when it has no private data. */ if (rc == 0 && *pos + 1 <= maxSz) { @@ -2823,7 +2835,8 @@ int FWTPM_NV_Save(FWTPM_CTX* ctx) word32 needed; pos = 0; needed = 4 + FWTPM_NV_PUBAREA_EST + FWTPM_NV_NAME_EST + 2 + - ctx->persistent[i].privKeySize + FWTPM_NV_AUTH_EST + 1; + ctx->persistent[i].privKeySize + FWTPM_NV_AUTH_EST + + 2 + FWTPM_NV_NAME_EST + 1; if (needed > bufSz) { byte* newBuf; newBuf = (byte*)XMALLOC(needed, NULL, @@ -3340,7 +3353,8 @@ int FWTPM_NV_SavePersistent(FWTPM_CTX* ctx, int slot) } bufSz = 4 + FWTPM_NV_PUBAREA_EST + 2 + FWTPM_NV_NAME_EST + 2 + - obj->privKeySize + 2 + FWTPM_NV_AUTH_EST + 1; + obj->privKeySize + 2 + FWTPM_NV_AUTH_EST + + 2 + FWTPM_NV_NAME_EST + 1; buf = (byte*)XMALLOC(bufSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (buf == NULL) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 62c8fd2c0..0b728a0b9 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -11482,7 +11482,8 @@ static TPM_RC SendCreationPcr(FWTPM_CTX* ctx, UINT32 cc, UINT32 parentH, /* Check the TPM2B_CREATION_DATA at gRsp + pos, made from SetCreationInputs, * and the creationHash after it. */ static void CheckCreationData(FWTPM_CTX* ctx, int pos, UINT16 parentNameAlg, - const byte* parentName, UINT16 parentNameSz) + const byte* parentName, UINT16 parentNameSz, const byte* parentQn, + UINT16 parentQnSz) { byte pcrs[2 * WC_SHA256_DIGEST_SIZE]; byte digest[WC_SHA256_DIGEST_SIZE]; @@ -11514,9 +11515,9 @@ static void CheckCreationData(FWTPM_CTX* ctx, int pos, UINT16 parentNameAlg, AssertIntEQ(memcmp(gRsp + pos, parentName, parentNameSz), 0); pos += parentNameSz; /* parentQualifiedName */ - AssertIntEQ(GetU16BE(gRsp + pos), parentNameSz); pos += 2; - AssertIntEQ(memcmp(gRsp + pos, parentName, parentNameSz), 0); - pos += parentNameSz; + AssertIntEQ(GetU16BE(gRsp + pos), parentQnSz); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, parentQn, parentQnSz), 0); + pos += parentQnSz; AssertIntEQ(GetU16BE(gRsp + pos), 5); pos += 2; /* outsideInfo */ AssertIntEQ(memcmp(gRsp + pos, "abcde", 5), 0); pos += 5; AssertIntEQ(pos, cdStart + cdSz); @@ -11548,7 +11549,8 @@ static void test_fwtpm_create_primary_creation_data(void) keyH = GetU32BE(gRsp + TPM2_HEADER_SIZE); pos = TPM2_HEADER_SIZE + 4 + 4; pos += 2 + GetU16BE(gRsp + pos); /* outPublic */ - CheckCreationData(&ctx, pos, TPM_ALG_NULL, owner, sizeof(owner)); + CheckCreationData(&ctx, pos, TPM_ALG_NULL, owner, sizeof(owner), owner, + sizeof(owner)); FlushHandle(&ctx, keyH); /* outsideInfo larger than a TPM2B_DATA */ @@ -11579,8 +11581,8 @@ static void test_fwtpm_create_primary_creation_data(void) fwtpm_pass("CreatePrimary creationData:", 0); } -/* Create creationData carries the nameAlg and Name of the parent object - * (Part 2 Sec.15.1). */ +/* Create creationData carries the nameAlg, Name and Qualified Name of the + * parent object (Part 2 Sec.15.1). */ static void test_fwtpm_create_creation_data(void) { FWTPM_CTX ctx; @@ -11594,6 +11596,9 @@ static void test_fwtpm_create_creation_data(void) AssertIntNE(parentH, 0); parent = &ctx.objects[parentH - TRANSIENT_FIRST]; AssertIntEQ(parent->name.size, 2 + WC_SHA256_DIGEST_SIZE); + AssertIntEQ(parent->qualifiedName.size, 2 + WC_SHA256_DIGEST_SIZE); + AssertIntNE(memcmp(parent->qualifiedName.name, parent->name.name, + parent->name.size), 0); cmdSz = BuildCreatePrimaryCmd(gCmd, FW_TEST_CREATE_ALG); PutU32BE(gCmd + 6, TPM_CC_Create); @@ -11605,7 +11610,8 @@ static void test_fwtpm_create_creation_data(void) pos += 2 + GetU16BE(gRsp + pos); /* outPrivate */ pos += 2 + GetU16BE(gRsp + pos); /* outPublic */ CheckCreationData(&ctx, pos, TPM_ALG_SHA256, parent->name.name, - parent->name.size); + parent->name.size, parent->qualifiedName.name, + parent->qualifiedName.size); /* outsideInfo larger than a TPM2B_DATA */ cmdSz = BuildCreatePrimaryCmd(gCmd, FW_TEST_CREATE_ALG); @@ -14098,8 +14104,11 @@ static void test_fwtpm_admin_authorization_requires_policy(void) FWTPM_CTX ctx; FWTPM_Object* obj = NULL; FWTPM_Session* policySess = NULL; - UINT32 keyHandle; + UINT32 keyHandle, parentHandle; UINT32 policySessHandle; + byte priv[sizeof(TPM2B_PRIVATE)]; + byte pub[sizeof(TPM2B_PUBLIC)]; + UINT16 privSz, pubSz; int pos, rspSize, oi; #ifndef FWTPM_NO_NV UINT32 nvIdx = 0x01500073; @@ -14108,8 +14117,12 @@ static void test_fwtpm_admin_authorization_requires_policy(void) XMEMSET(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), TPM_RC_SUCCESS); - keyHandle = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); - AssertIntNE(keyHandle, 0); + parentHandle = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); + AssertIntNE(parentHandle, 0); + CreateChildBlobs(&ctx, parentHandle, priv, &privSz, pub, &pubSz); + AssertIntEQ(SendLoadCmd(&ctx, parentHandle, priv, privSz, pub, pubSz), + TPM_RC_SUCCESS); + keyHandle = GetU32BE(gRsp + TPM2_HEADER_SIZE); for (oi = 0; oi < FWTPM_MAX_OBJECTS; oi++) { if (ctx.objects[oi].handle == keyHandle) { @@ -14122,7 +14135,7 @@ static void test_fwtpm_admin_authorization_requires_policy(void) pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ObjectChangeAuth); PutU32BE(gCmd + pos, keyHandle); pos += 4; - PutU32BE(gCmd + pos, keyHandle); pos += 4; + PutU32BE(gCmd + pos, parentHandle); pos += 4; pos = AppendPwAuth(gCmd, pos, NULL, 0); PutU16BE(gCmd + pos, 0); pos += 2; PutU32BE(gCmd + 2, (UINT32)pos); @@ -14164,7 +14177,7 @@ static void test_fwtpm_admin_authorization_requires_policy(void) pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ObjectChangeAuth); PutU32BE(gCmd + pos, keyHandle); pos += 4; - PutU32BE(gCmd + pos, keyHandle); pos += 4; + PutU32BE(gCmd + pos, parentHandle); pos += 4; pos = AppendAuth(gCmd, pos, policySessHandle, 0, NULL, 0); PutU16BE(gCmd + pos, 0); pos += 2; PutU32BE(gCmd + 2, (UINT32)pos); @@ -14185,7 +14198,7 @@ static void test_fwtpm_admin_authorization_requires_policy(void) pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_ObjectChangeAuth); PutU32BE(gCmd + pos, keyHandle); pos += 4; - PutU32BE(gCmd + pos, keyHandle); pos += 4; + PutU32BE(gCmd + pos, parentHandle); pos += 4; pos = AppendAuth(gCmd, pos, policySessHandle, 0, NULL, 0); PutU16BE(gCmd + pos, 0); pos += 2; PutU32BE(gCmd + 2, (UINT32)pos); @@ -14195,6 +14208,7 @@ static void test_fwtpm_admin_authorization_requires_policy(void) FlushHandle(&ctx, policySessHandle); FlushHandle(&ctx, keyHandle); + FlushHandle(&ctx, parentHandle); FWTPM_Cleanup(&ctx); fwtpm_pass("ADMIN authorization requires policy:", 0); } @@ -30500,6 +30514,392 @@ static void test_fwtpm_gettime_privacy_admin_handle(void) } #endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION */ +#ifdef HAVE_ECC +/* ReadPublic: copy out the Name and the Qualified Name */ +static void ReadNames(FWTPM_CTX* ctx, UINT32 handle, TPM2B_NAME* name, + TPM2B_NAME* qn) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ReadPublic); + int rspSize = 0; + + PutU32BE(gCmd + pos, handle); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pos = TPM2_HEADER_SIZE; + pos += 2 + GetU16BE(gRsp + pos); /* outPublic */ + name->size = GetU16BE(gRsp + pos); pos += 2; + AssertIntLE(name->size, sizeof(name->name)); + memcpy(name->name, gRsp + pos, name->size); pos += name->size; + qn->size = GetU16BE(gRsp + pos); pos += 2; + AssertIntLE(qn->size, sizeof(qn->name)); + memcpy(qn->name, gRsp + pos, qn->size); pos += qn->size; + AssertIntEQ(pos, rspSize); +} + +/* TPM_ALG_SHA256 || SHA-256(parentQn || name) */ +static void CalcQualifiedName(const byte* parentQn, int parentQnSz, + const TPM2B_NAME* name, TPM2B_NAME* qn) +{ + byte data[2 * sizeof(name->name)]; + + AssertIntLE(parentQnSz, (int)sizeof(name->name)); + memcpy(data, parentQn, parentQnSz); + memcpy(data + parentQnSz, name->name, name->size); + PutU16BE(qn->name, TPM_ALG_SHA256); + AssertIntEQ(wc_Sha256Hash(data, (word32)(parentQnSz + name->size), + qn->name + 2), 0); + qn->size = 2 + WC_SHA256_DIGEST_SIZE; +} + +/* The Qualified Name of handle is that of a child of parentQn */ +static void CheckQualifiedName(FWTPM_CTX* ctx, UINT32 handle, + const byte* parentQn, int parentQnSz, TPM2B_NAME* qn) +{ + TPM2B_NAME name, expect; + + ReadNames(ctx, handle, &name, qn); + CalcQualifiedName(parentQn, parentQnSz, &name, &expect); + AssertIntEQ(qn->size, expect.size); + AssertIntEQ(memcmp(qn->name, expect.name, expect.size), 0); + AssertIntNE(memcmp(qn->name, name.name, name.size), 0); +} + +/* Create an ECC storage key under parentH and Load it */ +static UINT32 CreateLoadStorageChild(FWTPM_CTX* ctx, UINT32 parentH) +{ + byte blobs[sizeof(TPM2B_PRIVATE) + sizeof(TPM2B_PUBLIC)]; + int cmdSz, pos, blobSz, rspSize = 0; + + cmdSz = BuildCreatePrimaryCmd(gCmd, TPM_ALG_ECC); + PutU32BE(gCmd + 6, TPM_CC_Create); + PutU32BE(gCmd + 10, parentH); + FWTPM_ProcessCommand(ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pos = TPM2_HEADER_SIZE + 4; + blobSz = 2 + GetU16BE(gRsp + pos); /* outPrivate */ + blobSz += 2 + GetU16BE(gRsp + pos + blobSz); /* outPublic */ + AssertIntLE(blobSz, (int)sizeof(blobs)); + memcpy(blobs, gRsp + pos, blobSz); + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Load); + PutU32BE(gCmd + pos, parentH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + memcpy(gCmd + pos, blobs, blobSz); pos += blobSz; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + return GetU32BE(gRsp + TPM2_HEADER_SIZE); +} + +static TPM_RC SendObjectChangeAuth(FWTPM_CTX* ctx, UINT32 objectH, + UINT32 parentH) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, + TPM_CC_ObjectChangeAuth); + int rspSize = 0; + + PutU32BE(gCmd + pos, objectH); pos += 4; + PutU32BE(gCmd + pos, parentH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 0); pos += 2; /* newAuth */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* The Qualified Name of an object is nameAlg || H(parent Qualified Name || + * Name), starting from the handle of the hierarchy (Part 1 Sec.16). An + * external object has no parent: its Qualified Name is its Name. */ +static void test_fwtpm_qualified_name_chain(void) +{ + FWTPM_CTX ctx; + UINT32 primaryH, childH, grandH, h; + TPM2B_NAME name, qn, primaryQn, childQn, grandQn; + byte owner[4]; + byte pub[sizeof(TPM2B_PUBLIC)]; + int i, pos, pubSz, cmdSz, rspSize = 0; +#ifndef FWTPM_NO_CONTEXT + byte saved[MAX_CONTEXT_SIZE]; + int savedSz; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + PutU32BE(owner, TPM_RH_OWNER); + + primaryH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); + AssertIntNE(primaryH, 0); + CheckQualifiedName(&ctx, primaryH, owner, sizeof(owner), &primaryQn); + childH = CreateLoadStorageChild(&ctx, primaryH); + CheckQualifiedName(&ctx, childH, primaryQn.name, primaryQn.size, + &childQn); + + /* CreateLoaded */ + cmdSz = BuildCreatePrimaryCmd(gCmd, TPM_ALG_ECC); + PutU32BE(gCmd + 6, TPM_CC_CreateLoaded); + PutU32BE(gCmd + 10, childH); + cmdSz -= 6; /* no outsideInfo or creationPCR */ + PutU32BE(gCmd + 2, (UINT32)cmdSz); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + h = GetU32BE(gRsp + TPM2_HEADER_SIZE); + CheckQualifiedName(&ctx, h, childQn.name, childQn.size, &qn); + FlushHandle(&ctx, h); + + /* Create under a non-primary parent: creationData has its Name and its + * Qualified Name */ + ReadNames(&ctx, childH, &name, &qn); + cmdSz = BuildCreatePrimaryCmd(gCmd, TPM_ALG_ECC); + PutU32BE(gCmd + 6, TPM_CC_Create); + PutU32BE(gCmd + 10, childH); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pos = TPM2_HEADER_SIZE + 4; + pos += 2 + GetU16BE(gRsp + pos); /* outPrivate */ + pos += 2 + GetU16BE(gRsp + pos); /* outPublic */ + pos += 2 + 4; /* creationData size, empty pcrSelect */ + pos += 2 + GetU16BE(gRsp + pos); /* pcrDigest */ + pos += 1; /* locality */ + AssertIntEQ(GetU16BE(gRsp + pos), TPM_ALG_SHA256); pos += 2; + AssertIntEQ(GetU16BE(gRsp + pos), name.size); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, name.name, name.size), 0); + pos += name.size; + AssertIntEQ(GetU16BE(gRsp + pos), childQn.size); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, childQn.name, childQn.size), 0); + + /* LoadExternal of the public area, in a hierarchy and in none */ + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ReadPublic); + PutU32BE(gCmd + pos, childH); pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + pubSz = 2 + GetU16BE(gRsp + TPM2_HEADER_SIZE); + AssertIntLE(pubSz, (int)sizeof(pub)); + memcpy(pub, gRsp + TPM2_HEADER_SIZE, pubSz); + for (i = 0; i < 2; i++) { + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, + TPM_CC_LoadExternal); + PutU16BE(gCmd + pos, 0); pos += 2; /* inPrivate */ + memcpy(gCmd + pos, pub, pubSz); pos += pubSz; + PutU32BE(gCmd + pos, (i == 0) ? TPM_RH_OWNER : TPM_RH_NULL); + pos += 4; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + h = GetU32BE(gRsp + TPM2_HEADER_SIZE); + ReadNames(&ctx, h, &name, &qn); + AssertIntEQ(qn.size, name.size); + AssertIntEQ(memcmp(qn.name, name.name, name.size), 0); + FlushHandle(&ctx, h); + } + + grandH = CreateLoadStorageChild(&ctx, childH); + CheckQualifiedName(&ctx, grandH, childQn.name, childQn.size, &grandQn); + + /* ObjectChangeAuth takes the parent the object was loaded under */ + AssertIntEQ(SendObjectChangeAuth(&ctx, grandH, primaryH), + TPM_RC_TYPE | TPM_RC_H | TPM_RC_2); + AssertIntEQ(SendObjectChangeAuth(&ctx, grandH, grandH), + TPM_RC_TYPE | TPM_RC_H | TPM_RC_2); + AssertIntEQ(SendObjectChangeAuth(&ctx, primaryH, childH), + TPM_RC_TYPE | TPM_RC_H | TPM_RC_2); + AssertIntEQ(SendObjectChangeAuth(&ctx, grandH, childH), TPM_RC_SUCCESS); + +#ifndef FWTPM_NO_CONTEXT + /* A saved context carries the Qualified Name: the parent may be gone + * when it is loaded */ + BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 14, TPM_CC_ContextSave); + PutU32BE(gCmd + 10, grandH); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, 14, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + savedSz = rspSize - TPM2_HEADER_SIZE; + AssertIntLE(savedSz, (int)sizeof(saved)); + memcpy(saved, gRsp + TPM2_HEADER_SIZE, savedSz); + FlushHandle(&ctx, grandH); + FlushHandle(&ctx, childH); + childH = 0; + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ContextLoad); + memcpy(gCmd + pos, saved, savedSz); pos += savedSz; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + grandH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + ReadNames(&ctx, grandH, &name, &qn); + AssertIntEQ(qn.size, grandQn.size); + AssertIntEQ(memcmp(qn.name, grandQn.name, grandQn.size), 0); +#endif + + FlushHandle(&ctx, grandH); + if (childH != 0) { + FlushHandle(&ctx, childH); + } + FlushHandle(&ctx, primaryH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Qualified Name chain:", 0); +} + +#ifndef FWTPM_NO_ATTESTATION +/* Certify reports the Qualified Name of the certified object and, as + * qualifiedSigner, that of the signing key (Part 2 Sec.10.12.3, 10.12.12) */ +static void test_fwtpm_qualified_name_certify(void) +{ + FWTPM_CTX ctx; + UINT32 primaryH, childH, signH; + TPM2B_NAME name, primaryQn, childQn, signQn; + byte owner[4]; + int pos; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + PutU32BE(owner, TPM_RH_OWNER); + + primaryH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); + AssertIntNE(primaryH, 0); + CheckQualifiedName(&ctx, primaryH, owner, sizeof(owner), &primaryQn); + childH = CreateLoadStorageChild(&ctx, primaryH); + CheckQualifiedName(&ctx, childH, primaryQn.name, primaryQn.size, + &childQn); + signH = CreateEccSignPrimaryScheme(&ctx, 0x00050472, TPM_ALG_ECDSA, + TPM_ALG_SHA256); + CheckQualifiedName(&ctx, signH, owner, sizeof(owner), &signQn); + ReadNames(&ctx, childH, &name, &childQn); + + AssertIntEQ(SendCertify(&ctx, childH, signH, 0), TPM_RC_SUCCESS); + pos = TPM2_HEADER_SIZE + 4 + 2; + AssertIntEQ(GetU32BE(gRsp + pos), TPM_GENERATED_VALUE); pos += 4; + AssertIntEQ(GetU16BE(gRsp + pos), TPM_ST_ATTEST_CERTIFY); pos += 2; + AssertIntEQ(GetU16BE(gRsp + pos), signQn.size); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, signQn.name, signQn.size), 0); + pos += signQn.size; + pos += 2 + GetU16BE(gRsp + pos); /* extraData */ + pos += 17 + 8; /* clockInfo, firmwareVersion */ + AssertIntEQ(GetU16BE(gRsp + pos), name.size); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, name.name, name.size), 0); + pos += name.size; + AssertIntEQ(GetU16BE(gRsp + pos), childQn.size); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, childQn.name, childQn.size), 0); + pos += childQn.size; + AssertIntEQ(pos, TPM2_HEADER_SIZE + 4 + 2 + + GetU16BE(gRsp + TPM2_HEADER_SIZE + 4)); + + FlushHandle(&ctx, signH); + FlushHandle(&ctx, childH); + FlushHandle(&ctx, primaryH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Qualified Name in Certify:", 0); +} +#endif /* !FWTPM_NO_ATTESTATION */ + +#ifndef FWTPM_NO_NV +/* A persistent object keeps its Qualified Name across a restart, and a + * record written without one loads with the Name in its place. */ +static void test_fwtpm_qualified_name_persistent(void) +{ + FWTPM_CTX ctx; + const UINT32 persistH = PERSISTENT_FIRST + 0x20; + UINT32 primaryH, childH, grandH; + TPM2B_NAME name, qn, primaryQn, childQn; + byte owner[4]; + byte hdr[4]; + byte record[1024]; + word32 off; + UINT16 tag, len, recordSz = 0; + int i, found = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + PutU32BE(owner, TPM_RH_OWNER); + + primaryH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); + AssertIntNE(primaryH, 0); + CheckQualifiedName(&ctx, primaryH, owner, sizeof(owner), &primaryQn); + childH = CreateLoadStorageChild(&ctx, primaryH); + CheckQualifiedName(&ctx, childH, primaryQn.name, primaryQn.size, + &childQn); + AssertIntEQ(SendEvictControl(&ctx, TPM_RH_OWNER, childH, persistH), + TPM_RC_SUCCESS); + FlushHandle(&ctx, childH); + FlushHandle(&ctx, primaryH); + + /* Copy the journal record of the persistent object */ + off = (word32)sizeof(FWTPM_NV_HEADER); + while (off + sizeof(hdr) <= ctx.nvWritePos) { + AssertIntEQ(ctx.nvHal.read(ctx.nvHal.ctx, off, hdr, sizeof(hdr)), 0); + tag = (UINT16)(hdr[0] | (hdr[1] << 8)); + len = (UINT16)(hdr[2] | (hdr[3] << 8)); + off += (word32)sizeof(hdr); + if (tag == FWTPM_NV_TAG_PERSISTENT) { + AssertIntLE(len, (int)sizeof(record)); + AssertIntEQ(ctx.nvHal.read(ctx.nvHal.ctx, off, record, len), 0); + recordSz = len; + } + off += len; + } + AssertIntGT(recordSz, 2 + childQn.size + 1); + AssertIntEQ(record[0] | (record[1] << 8) | (record[2] << 16) | + ((UINT32)record[3] << 24), persistH); + /* the Qualified Name and the public-only flag end the record */ + off = (word32)(recordSz - 1 - childQn.size - 2); + AssertIntEQ(record[off] | (record[off + 1] << 8), childQn.size); + AssertIntEQ(memcmp(record + off + 2, childQn.name, childQn.size), 0); + + /* Restart from the NV file */ + FWTPM_Cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + ReadNames(&ctx, persistH, &name, &qn); + AssertIntEQ(qn.size, childQn.size); + AssertIntEQ(memcmp(qn.name, childQn.name, childQn.size), 0); + grandH = CreateLoadStorageChild(&ctx, persistH); + CheckQualifiedName(&ctx, grandH, childQn.name, childQn.size, &qn); + FlushHandle(&ctx, grandH); + AssertIntEQ(SendEvictControl(&ctx, TPM_RH_OWNER, persistH, persistH), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + + /* The record as written, then without its trailing Qualified Name and + * public-only flag */ + for (i = 0; i < 2; i++) { + int slot; + + AssertIntEQ(NvLoadCraftedEntry(&ctx, FWTPM_NV_TAG_PERSISTENT, record, + (UINT16)((i == 0) ? recordSz : off)), TPM_RC_SUCCESS); + found = 0; + for (slot = 0; slot < FWTPM_MAX_PERSISTENT; slot++) { + FWTPM_Object* obj = &ctx.persistent[slot]; + + if (!obj->used || obj->handle != persistH) { + continue; + } + found = 1; + AssertIntEQ(obj->hierarchy, TPM_RH_OWNER); + AssertIntEQ(obj->name.size, name.size); + AssertIntEQ(memcmp(obj->name.name, name.name, name.size), 0); + if (i == 0) { + AssertIntEQ(obj->qualifiedName.size, childQn.size); + AssertIntEQ(memcmp(obj->qualifiedName.name, childQn.name, + childQn.size), 0); + } + else { + AssertIntEQ(obj->qualifiedName.size, name.size); + AssertIntEQ(memcmp(obj->qualifiedName.name, name.name, + name.size), 0); + } + } + AssertIntEQ(found, 1); + } + TPM2_ForceZero(&ctx, sizeof(ctx)); + + fwtpm_pass("Qualified Name of a persistent object:", 0); +} +#endif /* !FWTPM_NO_NV */ +#endif /* HAVE_ECC */ + #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) && \ !defined(FWTPM_NO_CREDENTIAL) /* keyHandle has to be a Storage Key: anything else is TPM_RC_TYPE for the @@ -31625,6 +32025,15 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) test_fwtpm_gettime_privacy_admin_handle(); #endif +#ifdef HAVE_ECC + test_fwtpm_qualified_name_chain(); +#ifndef FWTPM_NO_ATTESTATION + test_fwtpm_qualified_name_certify(); +#endif +#ifndef FWTPM_NO_NV + test_fwtpm_qualified_name_persistent(); +#endif +#endif #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) && \ !defined(FWTPM_NO_CREDENTIAL) test_fwtpm_activate_credential_key_type(); diff --git a/wolftpm/fwtpm/fwtpm.h b/wolftpm/fwtpm/fwtpm.h index 61da18631..5b3466f22 100644 --- a/wolftpm/fwtpm/fwtpm.h +++ b/wolftpm/fwtpm/fwtpm.h @@ -613,6 +613,7 @@ typedef struct FWTPM_Object { byte privKey[FWTPM_MAX_PRIVKEY_DER]; /* DER-encoded private key */ int privKeySize; TPM2B_NAME name; /* Object name = nameAlg || H(publicArea) */ + TPM2B_NAME qualifiedName; /* nameAlg || H(parent QN || name) */ int publicOnly; /* Loaded without a sensitive area */ } FWTPM_Object; From ad3836f44627488cc699ff86b1f5bef6ca0163ca Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 18:29:59 -0800 Subject: [PATCH 084/124] F-16837 - Support TPM_RH_NULL as the signHandle in fwTPM attestation commands --- src/fwtpm/fwtpm_command.c | 78 ++++++++---- src/fwtpm/fwtpm_crypto.c | 7 ++ tests/fwtpm_unit_tests.c | 242 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 301 insertions(+), 26 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 4b3a91a92..98d8e8877 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -18929,9 +18929,10 @@ static void FwAppendClockInfo(FWTPM_CTX* ctx, TPM2_Packet* pkt, TPM2_Packet_AppendU8(pkt, (UINT8)ctx->clockSafe); /* safe */ } +/* signer is NULL when signHandle is TPM_RH_NULL: the handle is then the + * qualifiedSigner. */ static TPM_RC FwAppendAttestCommonHeader(FWTPM_CTX* ctx, TPM2_Packet* pkt, UINT16 type, const FWTPM_Object* signer, - const TPM2B_NAME* qualifiedSigner, const TPM2B_DATA* extraData) { TPM_RC rc = TPM_RC_SUCCESS; @@ -18940,9 +18941,19 @@ static TPM_RC FwAppendAttestCommonHeader(FWTPM_CTX* ctx, TPM2_Packet* pkt, UINT32 restartObfuscation = 0; byte proof[TPM_MAX_DIGEST_SIZE]; byte obfuscation[16]; + TPM2B_NAME nullSigner; + const TPM2B_NAME* qualifiedSigner = &nullSigner; - if (signer->hierarchy != TPM_RH_ENDORSEMENT && - signer->hierarchy != TPM_RH_PLATFORM) { + if (signer != NULL) { + qualifiedSigner = &signer->qualifiedName; + } + else { + nullSigner.size = 4; + FwStoreU32BE(nullSigner.name, TPM_RH_NULL); + } + + if (signer == NULL || (signer->hierarchy != TPM_RH_ENDORSEMENT && + signer->hierarchy != TPM_RH_PLATFORM)) { int proofSz = TPM2_GetHashDigestSize(CONTEXT_INTEGRITY_HASH_ALG); if (proofSz <= 0) { @@ -18952,7 +18963,7 @@ static TPM_RC FwAppendAttestCommonHeader(FWTPM_CTX* ctx, TPM2_Packet* pkt, rc = FwComputeProofValue(ctx, TPM_RH_OWNER, CONTEXT_INTEGRITY_HASH_ALG, proof, proofSz); } - if (rc == 0 && TPM2_KDFa_ex(signer->pub.nameAlg, + if (rc == 0 && TPM2_KDFa_ex(CONTEXT_INTEGRITY_HASH_ALG, proof, (UINT32)proofSz, "OBFUSCATE", qualifiedSigner->name, qualifiedSigner->size, NULL, 0, obfuscation, sizeof(obfuscation)) != @@ -18998,7 +19009,9 @@ static TPM_RC FwAppendAttestCommonHeader(FWTPM_CTX* ctx, TPM2_Packet* pkt, #ifndef FWTPM_NO_ATTESTATION /* Helper: parse common attestation command parameters. * Skips auth area, parses qualifyingData (TPM2B_DATA), and inScheme - * (sigScheme + sigHashAlg), which has to suit the signing key sigObj. + * (sigScheme + sigHashAlg), which has to suit the signing key sigObj. With + * no signing key (signHandle TPM_RH_NULL) the scheme is TPM_ALG_NULL + * whatever inScheme asks for. * Called after handle parsing is complete. */ static TPM_RC FwParseAttestParams(TPM2_Packet* cmd, int cmdSize, UINT16 cmdTag, const FWTPM_Object* sigObj, TPM2B_DATA* qualifyingData, @@ -19049,8 +19062,12 @@ static TPM_RC FwParseAttestParams(TPM2_Packet* cmd, int cmdSize, } } } + if (rc == 0 && sigObj == NULL) { + *sigScheme = TPM_ALG_NULL; + *sigHashAlg = TPM_ALG_NULL; + } /* A key that cannot sign is left for FwSignAttest to reject */ - if (rc == 0 && (sigObj->pub.objectAttributes & TPMA_OBJECT_sign) && + else if (rc == 0 && (sigObj->pub.objectAttributes & TPMA_OBJECT_sign) && FwCheckSignScheme(sigObj, *sigScheme, *sigHashAlg) != 0) { rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; } @@ -19115,12 +19132,12 @@ static TPM_RC FwCmd_Quote(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { TPM2_Packet_ParseU32(cmd, &signHandle); sigObj = FwFindObject(ctx, signHandle); - if (sigObj == NULL) { + if (sigObj == NULL && signHandle != TPM_RH_NULL) { rc = TPM_RC_HANDLE; } } /* Quote requires a signing key (Part 3 Sec.18.4) */ - if (rc == 0) { + if (rc == 0 && sigObj != NULL) { if (!(sigObj->pub.objectAttributes & TPMA_OBJECT_sign)) rc = TPM_RC_KEY; } @@ -19150,6 +19167,11 @@ static TPM_RC FwCmd_Quote(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + /* Without a signing key there is no scheme hash for pcrDigest */ + if (rc == 0 && sigObj == NULL) { + rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2; + } + /* Build TPMS_ATTEST for QUOTE */ if (rc == 0) { XMEMSET(attestBuf, 0, FWTPM_MAX_ATTEST_BUF); @@ -19158,8 +19180,7 @@ static TPM_RC FwCmd_Quote(FWTPM_CTX* ctx, TPM2_Packet* cmd, attestPkt.size = (int)FWTPM_MAX_ATTEST_BUF; rc = FwAppendAttestCommonHeader(ctx, &attestPkt, - TPM_ST_ATTEST_QUOTE, sigObj, &sigObj->qualifiedName, - &qualifyingData); + TPM_ST_ATTEST_QUOTE, sigObj, &qualifyingData); /* attested.quote: pcrSelect (TPML_PCR_SELECTION) + * pcrDigest (TPM2B_DIGEST) */ @@ -19273,7 +19294,7 @@ static TPM_RC FwCmd_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { sigObj = FwFindObject(ctx, signHandle); - if (sigObj == NULL) { + if (sigObj == NULL && signHandle != TPM_RH_NULL) { rc = TPM_RC_HANDLE; } } @@ -19295,8 +19316,7 @@ static TPM_RC FwCmd_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, attestPkt.size = (int)FWTPM_MAX_ATTEST_BUF; rc = FwAppendAttestCommonHeader(ctx, &attestPkt, - TPM_ST_ATTEST_CERTIFY, sigObj, &sigObj->qualifiedName, - &qualifyingData); + TPM_ST_ATTEST_CERTIFY, sigObj, &qualifyingData); /* attested.certify: name + qualifiedName */ TPM2_Packet_AppendU16(&attestPkt, objToSign->name.size); @@ -19347,7 +19367,7 @@ static TPM_RC FwCmd_CertifyCreation(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseU32(cmd, &objectHandle); sigObj = FwFindObject(ctx, signHandle); - if (sigObj == NULL) { + if (sigObj == NULL && signHandle != TPM_RH_NULL) { rc = TPM_RC_HANDLE; } } @@ -19413,8 +19433,12 @@ static TPM_RC FwCmd_CertifyCreation(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } } + if (rc == 0 && sigObj == NULL) { + sigScheme = TPM_ALG_NULL; + sigHashAlg = TPM_ALG_NULL; + } /* A key that cannot sign is left for FwSignAttest to reject */ - if (rc == 0 && (sigObj->pub.objectAttributes & TPMA_OBJECT_sign) && + else if (rc == 0 && (sigObj->pub.objectAttributes & TPMA_OBJECT_sign) && FwCheckSignScheme(sigObj, sigScheme, sigHashAlg) != 0) { rc = TPM_RC_SCHEME | TPM_RC_P | TPM_RC_3; } @@ -19503,8 +19527,7 @@ static TPM_RC FwCmd_CertifyCreation(FWTPM_CTX* ctx, TPM2_Packet* cmd, attestPkt.size = (int)FWTPM_MAX_ATTEST_BUF; rc = FwAppendAttestCommonHeader(ctx, &attestPkt, - TPM_ST_ATTEST_CREATION, sigObj, &sigObj->qualifiedName, - &qualifyingData); + TPM_ST_ATTEST_CREATION, sigObj, &qualifyingData); /* attested.creation: objectName (TPM2B_NAME) + * creationHash (TPM2B_DIGEST) */ @@ -19555,7 +19578,7 @@ static TPM_RC FwCmd_GetTime(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { sigObj = FwFindObject(ctx, signHandle); - if (sigObj == NULL) { + if (sigObj == NULL && signHandle != TPM_RH_NULL) { rc = TPM_RC_HANDLE; } } @@ -19573,8 +19596,7 @@ static TPM_RC FwCmd_GetTime(FWTPM_CTX* ctx, TPM2_Packet* cmd, attestPkt.size = (int)FWTPM_MAX_PUB_BUF; rc = FwAppendAttestCommonHeader(ctx, &attestPkt, - TPM_ST_ATTEST_TIME, sigObj, &sigObj->qualifiedName, - &qualifyingData); + TPM_ST_ATTEST_TIME, sigObj, &qualifyingData); /* attested.time: TPMS_TIME_INFO (time + clockInfo) + * firmwareVersion */ @@ -19629,7 +19651,7 @@ static TPM_RC FwCmd_NV_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseU32(cmd, &nvHandle); sigObj = FwFindObject(ctx, signHandle); - if (sigObj == NULL) { + if (sigObj == NULL && signHandle != TPM_RH_NULL) { rc = TPM_RC_HANDLE; } } @@ -19719,7 +19741,7 @@ static TPM_RC FwCmd_NV_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, attestPkt.size = (int)FWTPM_MAX_ATTEST_BUF; rc = FwAppendAttestCommonHeader(ctx, &attestPkt, attestType, - sigObj, &sigObj->qualifiedName, &qualifyingData); + sigObj, &qualifyingData); if (digestMode) { /* attested.nvDigest: indexName + nvDigest @@ -19732,20 +19754,24 @@ static TPM_RC FwCmd_NV_Certify(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* ML-DSA keys have no scheme hash, so resolve nvDigest's hash from * nameAlg (TCG v185 errata) before the classical * FwResolveSignScheme fallback. */ - if (hashAlg == TPM_ALG_NULL) { + if (hashAlg == TPM_ALG_NULL && sigObj != NULL) { hashAlg = FwAttestMldsaHashAlg(sigObj); } - if (hashAlg == TPM_ALG_NULL) { + if (hashAlg == TPM_ALG_NULL && sigObj != NULL) { UINT16 keyScheme = TPM_ALG_NULL; FwResolveSignScheme(sigObj, &keyScheme, &hashAlg); (void)keyScheme; } wcDigH = FwGetWcHashType(hashAlg); hashSz = TPM2_GetHashDigestSize(hashAlg); - if (wcDigH == WC_HASH_TYPE_NONE || hashSz <= 0) { + if (sigObj == NULL) { + /* no scheme hash: nvDigest is the Empty Buffer */ + hashSz = 0; + } + else if (wcDigH == WC_HASH_TYPE_NONE || hashSz <= 0) { rc = TPM_RC_HASH; } - if (rc == 0) { + if (rc == 0 && sigObj != NULL) { if (wc_Hash(wcDigH, nv->data, nv->nvPublic.dataSize, nvDigest, hashSz) != 0) { rc = TPM_RC_FAILURE; diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index b56cd917b..53a0ebbb9 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -4984,6 +4984,13 @@ TPM_RC FwSignAttest(FWTPM_CTX* ctx, FWTPM_Object* obj, int digestSz; enum wc_HashType wcHash; + /* signHandle TPM_RH_NULL: the attestation is returned unsigned, with + * the NULL Signature */ + if (obj == NULL) { + TPM2_Packet_AppendU16(rsp, TPM_ALG_NULL); + return TPM_RC_SUCCESS; + } + /* Attestation must be signed by a signing key (Part 3 Sec.18). Reject * decrypt-only keys so a forged attestation cannot be produced. */ if (!(obj->pub.objectAttributes & TPMA_OBJECT_sign)) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 0b728a0b9..504f5def8 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -30900,6 +30900,245 @@ static void test_fwtpm_qualified_name_persistent(void) #endif /* !FWTPM_NO_NV */ #endif /* HAVE_ECC */ +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) +/* One password entry of an authorization area */ +static int AppendPwEntry(byte* buf, int pos, const byte* pw, int pwSz) +{ + PutU32BE(buf + pos, TPM_RS_PW); pos += 4; + PutU16BE(buf + pos, 0); pos += 2; /* nonce */ + buf[pos++] = 0; /* attributes */ + PutU16BE(buf + pos, (UINT16)pwSz); pos += 2; + if (pwSz > 0) { + memcpy(buf + pos, pw, pwSz); pos += pwSz; + } + return pos; +} + +/* An attestation command with signHandle TPM_RH_NULL, authorized by the + * password pw, with qualifyingData "qd" and the given inScheme. objH is the + * object of Certify and CertifyCreation; creation is its creationHash + * followed by its creationTicket. NV_Certify reads nvSize octets of nvIndex + * by ownerAuth. */ +static TPM_RC SendAttestNullSigner(FWTPM_CTX* ctx, UINT32 cc, UINT32 objH, + UINT32 nvIndex, UINT16 nvSize, UINT16 sigScheme, const byte* pw, int pwSz, + const byte* creation) +{ + int pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, cc); + int rspSize = 0; + int authStart, hashSz = 0, ticketSz; + + if (cc == TPM_CC_GetTime) { + PutU32BE(gCmd + pos, TPM_RH_ENDORSEMENT); pos += 4; + } + if (cc == TPM_CC_Certify) { + PutU32BE(gCmd + pos, objH); pos += 4; + } + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; + if (cc == TPM_CC_CertifyCreation) { + PutU32BE(gCmd + pos, objH); pos += 4; + } + if (cc == TPM_CC_NV_Certify) { + PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + PutU32BE(gCmd + pos, nvIndex); pos += 4; + } + authStart = pos; + pos += 4; + if (cc == TPM_CC_GetTime || cc == TPM_CC_Certify) { + pos = AppendPwEntry(gCmd, pos, NULL, 0); + } + pos = AppendPwEntry(gCmd, pos, pw, pwSz); + if (cc == TPM_CC_NV_Certify) { + pos = AppendPwEntry(gCmd, pos, NULL, 0); + } + PutU32BE(gCmd + authStart, (UINT32)(pos - authStart - 4)); + PutU16BE(gCmd + pos, 2); pos += 2; /* qualifyingData */ + gCmd[pos++] = 'q'; + gCmd[pos++] = 'd'; + if (cc == TPM_CC_CertifyCreation) { + hashSz = 2 + GetU16BE(creation); + memcpy(gCmd + pos, creation, hashSz); pos += hashSz; + } + PutU16BE(gCmd + pos, sigScheme); pos += 2; + if (sigScheme != TPM_ALG_NULL) { + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + } + if (cc == TPM_CC_Quote) { + PutU32BE(gCmd + pos, 1); pos += 4; /* PCRselect */ + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + gCmd[pos++] = (byte)PCR_SELECT_MAX; + memset(gCmd + pos, 0, PCR_SELECT_MAX); pos += PCR_SELECT_MAX; + } + else if (cc == TPM_CC_CertifyCreation) { + ticketSz = 2 + 4 + 2 + GetU16BE(creation + hashSz + 6); + memcpy(gCmd + pos, creation + hashSz, ticketSz); pos += ticketSz; + } + else if (cc == TPM_CC_NV_Certify) { + PutU16BE(gCmd + pos, nvSize); pos += 2; + PutU16BE(gCmd + pos, 0); pos += 2; /* offset */ + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* gRsp holds a TPMS_ATTEST of this type with the handle TPM_RH_NULL as + * qualifiedSigner, "qd" as extraData and the NULL Signature after it. + * Returns the offset of clockInfo. */ +static int CheckNullSignerAttest(UINT16 type) +{ + static const byte nullSigner[6] = { 0x00, 0x04, 0x40, 0x00, 0x00, 0x07 }; + int pos = TPM2_HEADER_SIZE; + int paramSz = (int)GetU32BE(gRsp + pos); + int attestSz = GetU16BE(gRsp + pos + 4); + int clockPos; + + AssertIntEQ(paramSz, 2 + attestSz + 2); + pos += 4 + 2; + AssertIntEQ(GetU16BE(gRsp + pos + attestSz), TPM_ALG_NULL); + AssertIntEQ(GetU32BE(gRsp + pos), TPM_GENERATED_VALUE); pos += 4; + AssertIntEQ(GetU16BE(gRsp + pos), type); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, nullSigner, sizeof(nullSigner)), 0); + pos += (int)sizeof(nullSigner); + AssertIntEQ(GetU16BE(gRsp + pos), 2); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, "qd", 2), 0); pos += 2; + clockPos = pos; + AssertIntLE(clockPos + 17 + 8, TPM2_HEADER_SIZE + 4 + 2 + attestSz); + return clockPos; +} + +/* signHandle TPM_RH_NULL asks for an attestation that is not signed: the + * handle is the qualifiedSigner, the scheme is TPM_ALG_NULL whatever + * inScheme says, and the signature is the NULL Signature. Quote has no + * scheme hash for its pcrDigest then (Part 3 Sec.18). */ +static void test_fwtpm_attest_null_signer(void) +{ + FWTPM_CTX ctx; + UINT32 objH; + TPM2B_NAME name, qn; + byte creation[2 + TPM_MAX_DIGEST_SIZE + 8 + TPM_MAX_DIGEST_SIZE]; + byte proof[WC_SHA256_DIGEST_SIZE]; + byte obfuscation[16]; + byte nullHandle[4]; + static const byte pw[1] = { 'x' }; + static const UINT16 schemes[2] = { TPM_ALG_NULL, TPM_ALG_ECDSA }; + UINT64 firmware = ((UINT64)FWTPM_VERSION_MAJOR << 32) | + FWTPM_VERSION_MINOR; + int i, pos, creationSz; +#ifndef FWTPM_NO_NV + const UINT32 nvIdx = 0x01500A21; + int cmdSz, rspSize = 0; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + /* fixedTPM|fixedParent|sensitiveDataOrigin|userWithAuth|noDA|sign */ + objH = CreateEccSignPrimaryScheme(&ctx, 0x00040472, TPM_ALG_ECDSA, + TPM_ALG_SHA256); + pos = TPM2_HEADER_SIZE + 4 + 4; + pos += 2 + GetU16BE(gRsp + pos); /* outPublic */ + pos += 2 + GetU16BE(gRsp + pos); /* creationData */ + creationSz = 2 + GetU16BE(gRsp + pos); /* creationHash */ + creationSz += 2 + 4 + 2 + GetU16BE(gRsp + pos + creationSz + 6); + AssertIntLE(creationSz, (int)sizeof(creation)); + memcpy(creation, gRsp + pos, creationSz); + ReadNames(&ctx, objH, &name, &qn); + + for (i = 0; i < 2; i++) { + /* GetTime: the reset, restart and firmware values of the common + * part are obfuscated, those of the time information are not */ + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_GetTime, 0, 0, 0, + schemes[i], NULL, 0, NULL), TPM_RC_SUCCESS); + pos = CheckNullSignerAttest(TPM_ST_ATTEST_TIME); + PutU32BE(nullHandle, TPM_RH_NULL); + AssertIntEQ(FwComputeProofValue(&ctx, TPM_RH_OWNER, + CONTEXT_INTEGRITY_HASH_ALG, proof, (int)sizeof(proof)), 0); + AssertIntEQ(TPM2_KDFa_ex(CONTEXT_INTEGRITY_HASH_ALG, proof, + (UINT32)sizeof(proof), "OBFUSCATE", nullHandle, + (UINT32)sizeof(nullHandle), NULL, 0, obfuscation, + (UINT32)sizeof(obfuscation)), (int)sizeof(obfuscation)); + AssertIntEQ(GetU32BE(gRsp + pos + 8), + ctx.resetCount + GetU32BE(obfuscation + 8)); + AssertIntEQ(GetU32BE(gRsp + pos + 12), + ctx.restartCount + GetU32BE(obfuscation + 12)); + AssertIntEQ(GetU32BE(gRsp + pos + 17), (UINT32)((firmware + + (((UINT64)GetU32BE(obfuscation) << 32) | + GetU32BE(obfuscation + 4))) >> 32)); + AssertIntEQ(GetU32BE(gRsp + pos + 21), (UINT32)(firmware + + GetU32BE(obfuscation + 4))); + pos += 17 + 8; + AssertIntEQ(GetU32BE(gRsp + pos + 8 + 8), ctx.resetCount); + AssertIntEQ(GetU32BE(gRsp + pos + 8 + 12), ctx.restartCount); + AssertIntEQ(GetU32BE(gRsp + pos + 8 + 17), (UINT32)(firmware >> 32)); + AssertIntEQ(GetU32BE(gRsp + pos + 8 + 21), (UINT32)firmware); + + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_Certify, objH, 0, 0, + schemes[i], NULL, 0, NULL), TPM_RC_SUCCESS); + pos = CheckNullSignerAttest(TPM_ST_ATTEST_CERTIFY) + 17 + 8; + AssertIntEQ(GetU16BE(gRsp + pos), name.size); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, name.name, name.size), 0); + pos += name.size; + AssertIntEQ(GetU16BE(gRsp + pos), qn.size); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, qn.name, qn.size), 0); + + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_CertifyCreation, objH, + 0, 0, schemes[i], NULL, 0, creation), TPM_RC_SUCCESS); + pos = CheckNullSignerAttest(TPM_ST_ATTEST_CREATION) + 17 + 8; + AssertIntEQ(GetU16BE(gRsp + pos), name.size); pos += 2; + AssertIntEQ(memcmp(gRsp + pos, name.name, name.size), 0); + pos += name.size; + AssertIntEQ(memcmp(gRsp + pos, creation, 2 + GetU16BE(creation)), 0); + + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_Quote, 0, 0, 0, + schemes[i], NULL, 0, NULL), TPM_RC_SCHEME | TPM_RC_P | TPM_RC_2); + } + +#ifndef FWTPM_NO_NV + cmdSz = BuildNvDefineCmd(gCmd, nvIdx, 1, + TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD | TPMA_NV_NO_DA); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(SendNvOwnerAccessCmd(&ctx, nvIdx, 1), TPM_RC_SUCCESS); + for (i = 0; i < 2; i++) { + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_NV_Certify, 0, nvIdx, + 1, schemes[i], NULL, 0, NULL), TPM_RC_SUCCESS); + pos = CheckNullSignerAttest(TPM_ST_ATTEST_NV) + 17 + 8; + pos += 2 + GetU16BE(gRsp + pos); /* indexName */ + AssertIntEQ(GetU16BE(gRsp + pos), 0); pos += 2; /* offset */ + AssertIntEQ(GetU16BE(gRsp + pos), 1); /* nvContents */ + + /* size and offset 0: the digest of the index, which is empty with + * no scheme hash */ + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_NV_Certify, 0, nvIdx, + 0, schemes[i], NULL, 0, NULL), TPM_RC_SUCCESS); + pos = CheckNullSignerAttest(TPM_ST_ATTEST_NV_DIGEST) + 17 + 8; + pos += 2 + GetU16BE(gRsp + pos); /* indexName */ + AssertIntEQ(GetU16BE(gRsp + pos), 0); pos += 2; /* nvDigest */ + AssertIntEQ(pos, TPM2_HEADER_SIZE + 4 + 2 + + GetU16BE(gRsp + TPM2_HEADER_SIZE + 4)); + } + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_NV_Certify, 0, nvIdx, 1, + TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), TPM_RC_BAD_AUTH); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), + TPM_RC_SUCCESS); +#endif + + /* The authValue of TPM_RH_NULL is the Empty Buffer */ + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_GetTime, 0, 0, 0, + TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), TPM_RC_BAD_AUTH); + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_Certify, objH, 0, 0, + TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), TPM_RC_BAD_AUTH); + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_CertifyCreation, objH, 0, + 0, TPM_ALG_NULL, pw, (int)sizeof(pw), creation), TPM_RC_BAD_AUTH); + AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_Quote, 0, 0, 0, + TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), TPM_RC_BAD_AUTH); + + FlushHandle(&ctx, objH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Attestation with signHandle TPM_RH_NULL:", 0); +} +#endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION */ + #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) && \ !defined(FWTPM_NO_CREDENTIAL) /* keyHandle has to be a Storage Key: anything else is TPM_RC_TYPE for the @@ -32034,6 +32273,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_qualified_name_persistent(); #endif #endif +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) + test_fwtpm_attest_null_signer(); +#endif #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) && \ !defined(FWTPM_NO_CREDENTIAL) test_fwtpm_activate_credential_key_type(); From 242b6f49e4ac786ef6f995c30a7310b19ffcc29e Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 20:48:38 -0800 Subject: [PATCH 085/124] Bound the fwTPM Create, CreateLoaded and CreatePrimary sensitive data by MAX_SYM_DATA --- src/fwtpm/fwtpm_command.c | 18 ++++++-- tests/fwtpm_unit_tests.c | 93 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 3 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 98d8e8877..6a2f60a1b 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -4865,6 +4865,10 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM2_Packet_ParseSensitiveCreate(cmd, cmdSize, &userAuth, sensData, (int)FWTPM_SIZEOF_BUF(sensData, FWTPM_MAX_DATA_BUF), &sensDataSize); } + /* A TPM2B_SENSITIVE_DATA holds at most MAX_SYM_DATA octets */ + if (rc == 0 && sensDataSize > MAX_SYM_DATA) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; + } /* Parse inPublic (TPM2B_PUBLIC) */ if (rc == 0) { @@ -8219,6 +8223,10 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, sensData, (int)FWTPM_SIZEOF_BUF(sensData, FWTPM_MAX_DATA_BUF), &sensDataSize); } + /* A TPM2B_SENSITIVE_DATA holds at most MAX_SYM_DATA octets */ + if (rc == 0 && sensDataSize > MAX_SYM_DATA) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; + } /* Parse inPublic */ if (rc == 0) { @@ -8413,7 +8421,7 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0 && sensDataSize > 0) { /* Use caller-supplied key material */ - if (sensDataSize > (UINT16)FWTPM_MAX_DATA_BUF) { + if (sensDataSize > (UINT16)FWTPM_MAX_PRIVKEY_DER) { rc = TPM_RC_SIZE; } if (rc == 0) { @@ -10503,6 +10511,10 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, sensData, (int)FWTPM_SIZEOF_BUF(sensData, FWTPM_MAX_DATA_BUF), &sensDataSize); } + /* A TPM2B_SENSITIVE_DATA holds at most MAX_SYM_DATA octets */ + if (rc == 0 && sensDataSize > MAX_SYM_DATA) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; + } /* Parse inPublic (TPM2B_TEMPLATE = TPM2B_PUBLIC) */ if (rc == 0) { @@ -10653,7 +10665,7 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0 && sensDataSize > 0) { - if (sensDataSize > (UINT16)FWTPM_MAX_DATA_BUF) { + if (sensDataSize > (UINT16)FWTPM_MAX_PRIVKEY_DER) { rc = TPM_RC_SIZE; } if (rc == 0) { @@ -10690,7 +10702,7 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0 && sensDataSize > 0) { - if (sensDataSize > (UINT16)FWTPM_MAX_DATA_BUF) { + if (sensDataSize > (UINT16)FWTPM_MAX_PRIVKEY_DER) { rc = TPM_RC_SIZE; } if (rc == 0) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 504f5def8..4f81b7c3c 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -11642,6 +11642,98 @@ static void test_fwtpm_create_creation_data(void) FWTPM_Cleanup(&ctx); fwtpm_pass("Create creationData:", 0); } + +/* Send Create, CreateLoaded or CreatePrimary for a SHA-256 KEYEDHASH or + * AES-128 SYMCIPHER object with an authValue of authSz octets and the given + * sensitive data. A KEYEDHASH object with sign set is an HMAC key. */ +static TPM_RC SendSymObjectCreate(FWTPM_CTX* ctx, UINT32 cc, UINT32 parentH, + UINT16 type, UINT32 attributes, UINT16 authSz, const byte* data, + UINT16 dataSz) +{ + int pos, sensStart, pubStart, rspSize = 0; + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, cc); + PutU32BE(gCmd + pos, parentH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + sensStart = pos; + pos += 2; + PutU16BE(gCmd + pos, authSz); pos += 2; + memset(gCmd + pos, 0x5A, authSz); pos += authSz; + PutU16BE(gCmd + pos, dataSz); pos += 2; + if (dataSz > 0) { + memcpy(gCmd + pos, data, dataSz); pos += dataSz; + } + PutU16BE(gCmd + sensStart, (UINT16)(pos - sensStart - 2)); + pubStart = pos; + pos += 2; + PutU16BE(gCmd + pos, type); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + pos, attributes); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; /* authPolicy */ + if (type == TPM_ALG_SYMCIPHER) { + PutU16BE(gCmd + pos, TPM_ALG_AES); pos += 2; + PutU16BE(gCmd + pos, 128); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_CFB); pos += 2; + } + else if ((attributes & TPMA_OBJECT_sign) != 0) { + PutU16BE(gCmd + pos, TPM_ALG_HMAC); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + } + else { + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; + } + PutU16BE(gCmd + pos, 0); pos += 2; /* unique */ + PutU16BE(gCmd + pubStart, (UINT16)(pos - pubStart - 2)); + if (cc != TPM_CC_CreateLoaded) { + PutU16BE(gCmd + pos, 0); pos += 2; /* outsideInfo */ + PutU32BE(gCmd + pos, 0); pos += 4; /* creationPCR */ + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* fixedTPM | fixedParent | userWithAuth | noDA */ +#define FW_TEST_SEALED_ATTRS 0x00000452 + +/* Sealed data is a TPM2B_SENSITIVE_DATA, so MAX_SYM_DATA octets at most + * (Part 2 Sec.11.1.14). */ +static void test_fwtpm_create_sensitive_data_size(void) +{ + static const UINT32 cc[] = { + TPM_CC_Create, TPM_CC_CreateLoaded, TPM_CC_CreatePrimary + }; + static byte data[FWTPM_MAX_DATA_BUF]; + FWTPM_CTX ctx; + UINT32 parentH, h; + int i; + + memset(&ctx, 0, sizeof(ctx)); + memset(data, 0xA5, sizeof(data)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + parentH = CreatePrimaryHelper(&ctx, FW_TEST_CREATE_ALG); + AssertIntNE(parentH, 0); + + for (i = 0; i < (int)(sizeof(cc) / sizeof(cc[0])); i++) { + h = (cc[i] == TPM_CC_CreatePrimary) ? (TPM_HANDLE)TPM_RH_OWNER : + parentH; + AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_KEYEDHASH, + FW_TEST_SEALED_ATTRS, 0, data, MAX_SYM_DATA), TPM_RC_SUCCESS); + if (cc[i] != TPM_CC_Create) { + FlushHandle(&ctx, GetU32BE(gRsp + TPM2_HEADER_SIZE)); + } + AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_KEYEDHASH, + FW_TEST_SEALED_ATTRS, 0, data, MAX_SYM_DATA + 1), + TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_KEYEDHASH, + FW_TEST_SEALED_ATTRS, 0, data, (UINT16)sizeof(data)), + TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + } + + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Create sensitive data size:", 0); +} #endif /* HAVE_ECC || (!NO_RSA && WOLFSSL_KEY_GEN) */ /* Helper: build StartAuthSession command. Returns cmd size. */ @@ -31814,6 +31906,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #if defined(HAVE_ECC) || (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) test_fwtpm_create_primary_creation_data(); test_fwtpm_create_creation_data(); + test_fwtpm_create_sensitive_data_size(); #endif #ifdef WOLFTPM_V185 test_fwtpm_create_primary_mlkem(); From 91929cc5030af4f5034afc5954c6d1b9b9dc1f1f Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 20:52:18 -0800 Subject: [PATCH 086/124] Use the caller key for a fwTPM SYMCIPHER object and require it to match keyBits --- src/fwtpm/fwtpm_command.c | 24 ++++++++++++++--- tests/fwtpm_unit_tests.c | 55 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 6a2f60a1b..1540eb382 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -5244,7 +5244,15 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_KEY_SIZE; } - if (rc == 0) { + if (rc == 0 && sensDataSize > 0) { + if ((int)sensDataSize != keySz) { + rc = TPM_RC_KEY_SIZE; + } + else { + XMEMCPY(obj->privKey, sensData, sensDataSize); + } + } + else if (rc == 0) { rc = FwDeriveSymmetricPrimaryKey( inPublic->publicArea.nameAlg, seed, hashUnique, hashUniqueSz, @@ -8459,7 +8467,15 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = TPM_RC_KEY_SIZE; } - if (rc == 0) { + if (rc == 0 && sensDataSize > 0) { + if ((int)sensDataSize != keySz) { + rc = TPM_RC_KEY_SIZE; + } + else { + XMEMCPY(privKeyDer, sensData, sensDataSize); + } + } + else if (rc == 0) { rc = wc_RNG_GenerateBlock(&ctx->rng, privKeyDer, (word32)keySz); if (rc != 0) { @@ -10702,8 +10718,8 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0 && sensDataSize > 0) { - if (sensDataSize > (UINT16)FWTPM_MAX_PRIVKEY_DER) { - rc = TPM_RC_SIZE; + if ((int)sensDataSize != keySz) { + rc = TPM_RC_KEY_SIZE; } if (rc == 0) { XMEMCPY(privKeyDer, sensData, sensDataSize); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 4f81b7c3c..652f80e7c 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -11734,6 +11734,58 @@ static void test_fwtpm_create_sensitive_data_size(void) FWTPM_Cleanup(&ctx); fwtpm_pass("Create sensitive data size:", 0); } + +#ifndef NO_AES +/* A SYMCIPHER object takes the key the caller supplies in the sensitive + * data, which has to be of the size in the public area (Part 3 Sec.12.1). */ +static void test_fwtpm_create_symcipher_caller_key(void) +{ + static const UINT32 cc[] = { + TPM_CC_Create, TPM_CC_CreateLoaded, TPM_CC_CreatePrimary + }; + /* fixedTPM | fixedParent | userWithAuth | noDA | decrypt | sign */ + const UINT32 attrs = 0x00060452; + FWTPM_CTX ctx; + byte key[24]; + byte unique[WC_SHA256_DIGEST_SIZE]; + UINT32 parentH, h; + int i, pos; + + memset(&ctx, 0, sizeof(ctx)); + memset(key, 0x3C, sizeof(key)); + AssertIntEQ(wc_Sha256Hash(key, 16, unique), 0); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + parentH = CreatePrimaryHelper(&ctx, FW_TEST_CREATE_ALG); + AssertIntNE(parentH, 0); + + for (i = 0; i < (int)(sizeof(cc) / sizeof(cc[0])); i++) { + h = (cc[i] == TPM_CC_CreatePrimary) ? (TPM_HANDLE)TPM_RH_OWNER : + parentH; + AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_SYMCIPHER, + attrs, 0, key, 16), TPM_RC_SUCCESS); + pos = TPM2_HEADER_SIZE + 4; + if (cc[i] != TPM_CC_Create) { + pos += 4; + } + if (cc[i] != TPM_CC_CreatePrimary) { + pos += 2 + GetU16BE(gRsp + pos); /* outPrivate */ + } + /* size, type, nameAlg, attributes, authPolicy, sym */ + pos += 2 + 2 + 2 + 4 + 2 + 6; + AssertIntEQ(GetU16BE(gRsp + pos), sizeof(unique)); + AssertIntEQ(memcmp(gRsp + pos + 2, unique, sizeof(unique)), 0); + if (cc[i] != TPM_CC_Create) { + FlushHandle(&ctx, GetU32BE(gRsp + TPM2_HEADER_SIZE)); + } + AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_SYMCIPHER, + attrs, 0, key, sizeof(key)), TPM_RC_KEY_SIZE); + } + + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Create SYMCIPHER caller key:", 0); +} +#endif /* !NO_AES */ #endif /* HAVE_ECC || (!NO_RSA && WOLFSSL_KEY_GEN) */ /* Helper: build StartAuthSession command. Returns cmd size. */ @@ -31907,6 +31959,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_create_primary_creation_data(); test_fwtpm_create_creation_data(); test_fwtpm_create_sensitive_data_size(); +#ifndef NO_AES + test_fwtpm_create_symcipher_caller_key(); +#endif #endif #ifdef WOLFTPM_V185 test_fwtpm_create_primary_mlkem(); From fb82cf2e4dcff4333fedf1feba7aae3c2dad588c Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 20:54:53 -0800 Subject: [PATCH 087/124] Limit the fwTPM Create and CreatePrimary authValue to the nameAlg digest size --- src/fwtpm/fwtpm_command.c | 31 +++++++++++++++++++++++++------ tests/fwtpm_unit_tests.c | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 1540eb382..2cf28fc83 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -3250,6 +3250,23 @@ static TPM_RC FwValidateKeyUsage(const TPMT_PUBLIC* pub) return TPM_RC_SUCCESS; } +/* The authValue of a new object, less its trailing zeros, is no larger than + * the nameAlg digest (Part 3 Sec.12.1). */ +static TPM_RC FwCheckCreateAuthSize(const TPM2B_AUTH* auth, + TPMI_ALG_HASH nameAlg) +{ + int digestSz = TPM2_GetHashDigestSize(nameAlg); + int authSz = (int)auth->size; + + while (authSz > 0 && auth->buffer[authSz - 1] == 0) { + authSz--; + } + if (digestSz > 0 && authSz > digestSz) { + return TPM_RC_SIZE | TPM_RC_P | TPM_RC_1; + } + return TPM_RC_SUCCESS; +} + static TPM_RC FwValidateCreateAttributes(const TPMT_PUBLIC* pub, const FWTPM_Object* parent, UINT16 sensitiveDataSz) { @@ -4890,6 +4907,9 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = FwValidateLimitedAttributes(&inPublic->publicArea); } #endif /* WOLFTPM_V185 */ + if (rc == 0) { + rc = FwCheckCreateAuthSize(&userAuth, inPublic->publicArea.nameAlg); + } /* Parse outsideInfo (TPM2B_DATA) */ if (rc == 0) { if (cmd->pos + 2 > cmdSize) { @@ -8256,6 +8276,9 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = FwValidateLimitedAttributes(&inPublic->publicArea); } #endif /* WOLFTPM_V185 */ + if (rc == 0) { + rc = FwCheckCreateAuthSize(&userAuth, inPublic->publicArea.nameAlg); + } /* Parse outsideInfo (TPM2B_DATA) */ if (rc == 0) { if (cmd->pos + 2 > cmdSize) { @@ -10548,12 +10571,8 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, } #endif /* WOLFTPM_V185 */ - /* userAuth must not exceed the object nameAlg digest size */ - if (rc == 0 && userAuth.size > 0) { - int digestSz = TPM2_GetHashDigestSize(inPublic->publicArea.nameAlg); - if (digestSz > 0 && (int)userAuth.size > digestSz) { - rc = TPM_RC_SIZE; - } + if (rc == 0) { + rc = FwCheckCreateAuthSize(&userAuth, inPublic->publicArea.nameAlg); } /* Note: CreateLoaded does NOT include outsideInfo or creationPCR diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 652f80e7c..8743e4348 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -11735,6 +11735,42 @@ static void test_fwtpm_create_sensitive_data_size(void) fwtpm_pass("Create sensitive data size:", 0); } +/* The authValue of a new object is limited to the nameAlg digest size once + * its trailing zeros are dropped (Part 3 Sec.12.1). */ +static void test_fwtpm_create_auth_size(void) +{ + static const UINT32 cc[] = { + TPM_CC_Create, TPM_CC_CreateLoaded, TPM_CC_CreatePrimary + }; + static const byte data[] = { 1, 2, 3, 4 }; + FWTPM_CTX ctx; + UINT32 parentH, h; + int i; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + parentH = CreatePrimaryHelper(&ctx, FW_TEST_CREATE_ALG); + AssertIntNE(parentH, 0); + + for (i = 0; i < (int)(sizeof(cc) / sizeof(cc[0])); i++) { + h = (cc[i] == TPM_CC_CreatePrimary) ? (TPM_HANDLE)TPM_RH_OWNER : + parentH; + AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_KEYEDHASH, + FW_TEST_SEALED_ATTRS, WC_SHA256_DIGEST_SIZE, data, sizeof(data)), + TPM_RC_SUCCESS); + if (cc[i] != TPM_CC_Create) { + FlushHandle(&ctx, GetU32BE(gRsp + TPM2_HEADER_SIZE)); + } + AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_KEYEDHASH, + FW_TEST_SEALED_ATTRS, WC_SHA256_DIGEST_SIZE + 1, data, + sizeof(data)), TPM_RC_SIZE | TPM_RC_P | TPM_RC_1); + } + + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Create authValue size:", 0); +} + #ifndef NO_AES /* A SYMCIPHER object takes the key the caller supplies in the sensitive * data, which has to be of the size in the public area (Part 3 Sec.12.1). */ @@ -31959,6 +31995,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_create_primary_creation_data(); test_fwtpm_create_creation_data(); test_fwtpm_create_sensitive_data_size(); + test_fwtpm_create_auth_size(); #ifndef NO_AES test_fwtpm_create_symcipher_caller_key(); #endif From a41731a9d8926e63278650dda87c844e939ca1ac Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 20:58:24 -0800 Subject: [PATCH 088/124] Count a failed HMAC on a bound fwTPM session that authorizes no handle toward lockout --- src/fwtpm/fwtpm_command.c | 42 +++++++++++++----- tests/fwtpm_unit_tests.c | 93 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+), 12 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 2cf28fc83..f1f2735cc 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -24248,11 +24248,13 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, * daLockoutRecovery seconds, so lockoutAuth cannot be brute-forced * (Part 1 Sec.19.8.2). Reject any authorization slot that uses * lockoutAuth, directly or through a bound session, but not Clear via - * platformAuth, which is the recovery path. */ + * platformAuth, which is the recovery path. A session that authorizes + * no handle still uses the authValue it is bound to. */ if (ctx->lockoutAuthFailed) { - for (pj = 0; pj < cmdAuthCnt && - pj < (int)entry->authHandleCnt; pj++) { - if ((FwAuthSlotDAUse(ctx, cmdHandles[pj], + for (pj = 0; pj < cmdAuthCnt; pj++) { + if ((FwAuthSlotDAUse(ctx, + pj < (int)entry->authHandleCnt ? + cmdHandles[pj] : (TPM_HANDLE)TPM_RH_NULL, cmdAuths[pj].handle == TPM_RS_PW, cmdAuths[pj].sess, cmdAuths[pj].cmdHmacSize, NULL) & FW_AUTH_USES_LOCKOUT) != 0) { @@ -24266,17 +24268,32 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, if (ctx->daFailedTries >= ctx->daMaxTries && ctx->daMaxTries > 0) { int hasDaAuth = 0; + int hasDaSess = 0; - for (pj = 0; pj < cmdAuthCnt && - pj < (int)entry->authHandleCnt; pj++) { - if ((FwAuthSlotDAUse(ctx, cmdHandles[pj], + for (pj = 0; pj < cmdAuthCnt; pj++) { + int authSlot = pj < (int)entry->authHandleCnt; + if ((FwAuthSlotDAUse(ctx, + authSlot ? cmdHandles[pj] : (TPM_HANDLE)TPM_RH_NULL, cmdAuths[pj].handle == TPM_RS_PW, cmdAuths[pj].sess, cmdAuths[pj].cmdHmacSize, NULL) & (FW_AUTH_USES_ENTITY_DA | FW_AUTH_USES_BIND_DA)) != 0) { - hasDaAuth = 1; - break; + if (authSlot) { + hasDaAuth = 1; + } + else { + hasDaSess = 1; + } } } + /* A session that authorizes no handle and is bound to a DA protected + * entity is refused for every command, or its HMAC would keep testing + * guesses of the bind authValue. */ + if (hasDaSess) { + *rspSize = FwBuildErrorResponse(rspBuf, rspCap, + TPM_ST_NO_SESSIONS, TPM_RC_LOCKOUT); + TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); + return TPM_RC_SUCCESS; + } /* Startup/Shutdown are lifecycle commands and must never be DA-gated: * with failedTries persisted, gating Startup would brick a TPM that * power-cycled while in lockout (Startup blocked, so LockReset can @@ -24309,9 +24326,10 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, * regardless of the macro. */ if (!ctx->daUsed) { int armDa = 0; - for (pj = 0; pj < cmdAuthCnt && pj < (int)entry->authHandleCnt; pj++) { + for (pj = 0; pj < cmdAuthCnt; pj++) { int daUse; - TPM_HANDLE entityH = cmdHandles[pj]; + TPM_HANDLE entityH = pj < (int)entry->authHandleCnt ? + cmdHandles[pj] : (TPM_HANDLE)TPM_RH_NULL; TPM_HANDLE bindH = cmdAuths[pj].sess != NULL ? cmdAuths[pj].sess->bindHandle : 0; int entityIsObj = @@ -24664,7 +24682,7 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, "0x%x (CC=0x%x)\n", entityH, cmdCode); #endif #ifndef FWTPM_NO_DA - if (isAuthSess && FwAuthSlotDAUse(ctx, entityH, 0, hSess, + if (FwAuthSlotDAUse(ctx, entityH, 0, hSess, cmdAuths[hj].cmdHmacSize, &daHandle) != 0) { authRc = TPM_RC_AUTH_FAIL; if (FwDaRegisterFailure(ctx, daHandle)) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 8743e4348..a07c4f65d 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -18879,6 +18879,98 @@ static void test_fwtpm_da_hmac_arms_daused(void) (void)remove(FWTPM_NV_FILE); fwtpm_pass("DA HMAC session arms daUsed:", 0); } + +/* Start an unsalted HMAC session bound to the given entity. */ +static UINT32 DaStartBoundSession(FWTPM_CTX* ctx, UINT32 bind) +{ + int cmdSz, rspSize = 0; + + cmdSz = BuildStartAuthSessionCmd(gCmd, TPM_SE_HMAC, TPM_ALG_SHA256); + PutU32BE(gCmd + TPM2_HEADER_SIZE + 4, bind); + FWTPM_ProcessCommand(ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + if (GetRspRC(gRsp) != TPM_RC_SUCCESS) return 0; + return GetU32BE(gRsp + TPM2_HEADER_SIZE); +} + +/* GetRandom with an audit session that authorizes no handle and carries an + * HMAC that cannot verify. */ +static TPM_RC DaGetRandomBadHmac(FWTPM_CTX* ctx, UINT32 sessH) +{ + int pos, authStart, rspSize = 0; + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_GetRandom); + authStart = pos; + pos += 4; + PutU32BE(gCmd + pos, sessH); pos += 4; + PutU16BE(gCmd + pos, 16); pos += 2; + memset(gCmd + pos, 0xAA, 16); pos += 16; + gCmd[pos++] = TPMA_SESSION_audit | TPMA_SESSION_continueSession; + PutU16BE(gCmd + pos, WC_SHA256_DIGEST_SIZE); pos += 2; + memset(gCmd + pos, 0xCC, WC_SHA256_DIGEST_SIZE); + pos += WC_SHA256_DIGEST_SIZE; + PutU32BE(gCmd + authStart, (UINT32)(pos - authStart - 4)); + PutU16BE(gCmd + pos, 8); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* The HMAC of a bound session depends on the bind authValue in every session + * slot, so a failure counts toward lockout even when the session authorizes + * no handle, and the session is refused once the TPM is locked out + * (Part 1 Sec.19.8.4). */ +static void test_fwtpm_da_bound_session_no_auth_slot(void) +{ + FWTPM_CTX ctx; + UINT32 daKey, noDaKey, sessH; + + (void)remove(FWTPM_NV_FILE); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(DaSetParams(&ctx, 2, 1000, 1000), TPM_RC_SUCCESS); + daKey = DaMakeEccSignKey(&ctx, 0x00040072); + AssertIntNE(daKey, 0); + noDaKey = DaMakeEccSignKey(&ctx, 0x00040472); + AssertIntNE(noDaKey, 0); + + /* Unbound, and bound to a noDA object: not counted */ + sessH = StartSessionHelper(&ctx, TPM_SE_HMAC); + AssertIntNE(sessH, 0); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_BAD_AUTH); + FlushHandle(&ctx, sessH); + sessH = DaStartBoundSession(&ctx, noDaKey); + AssertIntNE(sessH, 0); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_BAD_AUTH); + FlushHandle(&ctx, sessH); + AssertIntEQ((int)ctx.daFailedTries, 0); + AssertIntEQ(ctx.daUsed, 0); + + /* Bound to a DA protected object: counted, then locked out */ + sessH = DaStartBoundSession(&ctx, daKey); + AssertIntNE(sessH, 0); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_AUTH_FAIL); + AssertIntEQ((int)ctx.daFailedTries, 1); + AssertIntEQ(ctx.daUsed, 1); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_LOCKOUT); + AssertIntEQ((int)ctx.daFailedTries, 2); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_LOCKOUT); + AssertIntEQ((int)ctx.daFailedTries, 2); + FlushHandle(&ctx, sessH); + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_DictionaryAttackLockReset, + TPM_RH_LOCKOUT), TPM_RC_SUCCESS); + + /* Bound to lockout: locks lockoutAuth without counting a try */ + sessH = DaStartBoundSession(&ctx, TPM_RH_LOCKOUT); + AssertIntNE(sessH, 0); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_AUTH_FAIL); + AssertIntEQ(ctx.lockoutAuthFailed, 1); + AssertIntEQ((int)ctx.daFailedTries, 0); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_LOCKOUT); + + FWTPM_Cleanup(&ctx); + (void)remove(FWTPM_NV_FILE); + fwtpm_pass("DA bound session in a non-auth slot:", 0); +} #endif /* HAVE_ECC */ #endif /* !FWTPM_NO_DA */ @@ -32286,6 +32378,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_da_selfheal(); test_fwtpm_da_selfheal_partial(); test_fwtpm_da_hmac_arms_daused(); + test_fwtpm_da_bound_session_no_auth_slot(); test_fwtpm_da_lockoutauth_failure(); test_fwtpm_da_clear_resets(); test_fwtpm_da_permanent_bits(); From 643af47c49ee3c4a04039df03049e618906b0059 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:02:04 -0800 Subject: [PATCH 089/124] Skip the authorization area in fwTPM GetCapability, HashSequenceStart and EC_Ephemeral --- src/fwtpm/fwtpm_command.c | 29 +++++++++++----- tests/fwtpm_unit_tests.c | 72 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 9 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index f1f2735cc..b98aae533 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -1978,7 +1978,10 @@ static TPM_RC FwCmd_GetCapability(FWTPM_CTX* ctx, TPM2_Packet* cmd, int paramSzPos, paramStart; int moreDataPos; - if (cmdSize < TPM2_HEADER_SIZE + 12) { + if (cmdTag == TPM_ST_SESSIONS) { + rc = FwSkipAuthArea(cmd, cmdSize); + } + if (rc == 0 && cmdSize - cmd->pos < 12) { rc = TPM_RC_COMMAND_SIZE; } @@ -11959,13 +11962,17 @@ static TPM_RC FwCmd_HashSequenceStart(FWTPM_CTX* ctx, TPM2_Packet* cmd, UINT8 eventBanks = 0; int bank; - (void)cmdSize; + if (cmdTag == TPM_ST_SESSIONS) { + rc = FwSkipAuthArea(cmd, cmdSize); + } /* Parse auth (TPM2B_AUTH) */ XMEMSET(&auth, 0, sizeof(auth)); - TPM2_Packet_ParseU16(cmd, &authSize); - if (authSize > sizeof(auth.buffer)) { - rc = TPM_RC_SIZE; + if (rc == 0) { + TPM2_Packet_ParseU16(cmd, &authSize); + if (authSize > sizeof(auth.buffer)) { + rc = TPM_RC_SIZE; + } } if (rc == 0) { auth.size = authSize; @@ -20424,11 +20431,12 @@ static TPM_RC FwCmd_EC_Ephemeral(FWTPM_CTX* ctx, TPM2_Packet* cmd, word32 derSz; int keyInit = 0; - (void)cmdSize; - FWTPM_ALLOC_VAR(ephKey, ecc_key); - if (cmdSize < TPM2_HEADER_SIZE + 2) { + if (rc == 0 && cmdTag == TPM_ST_SESSIONS) { + rc = FwSkipAuthArea(cmd, cmdSize); + } + if (rc == 0 && cmdSize - cmd->pos < 2) { rc = TPM_RC_COMMAND_SIZE; } @@ -20759,7 +20767,10 @@ static TPM_RC FwCmd_Vendor_TCG_Test(FWTPM_CTX* ctx, TPM2_Packet* cmd, (void)ctx; - if (cmdSize < TPM2_HEADER_SIZE + 2) { + if (cmdTag == TPM_ST_SESSIONS) { + rc = FwSkipAuthArea(cmd, cmdSize); + } + if (rc == 0 && cmdSize - cmd->pos < 2) { rc = TPM_RC_COMMAND_SIZE; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index a07c4f65d..e0f2640fa 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -12023,6 +12023,77 @@ static void test_fwtpm_session_parameter_area(TPM_CC code) "Hash session parameters:", 0); } +/* A command without an authorization handle may still carry an audit + * session, and its parameters then follow the authorization area. */ +static void test_fwtpm_no_handle_session_commands(void) +{ + FWTPM_CTX ctx; + byte params[12], nonce[WC_SHA256_DIGEST_SIZE]; + byte expectedParams[64]; + UINT32 sessH; + int pos, expectedSz, rspSize = 0; + + (void)remove(FWTPM_NV_FILE); + XMEMSET(&ctx, 0, sizeof(ctx)); + XMEMSET(nonce, 0x42, sizeof(nonce)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + sessH = StartSessionHelper(&ctx, TPM_SE_HMAC); + AssertIntNE(sessH, 0); + + PutU32BE(params, TPM_CAP_TPM_PROPERTIES); + PutU32BE(params + 4, TPM_PT_MANUFACTURER); + PutU32BE(params + 8, 1); + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_GetCapability); + XMEMCPY(gCmd + pos, params, 12); pos += 12; + PutU32BE(gCmd + 2, (UINT32)pos); + AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0), 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + expectedSz = rspSize - TPM2_HEADER_SIZE; + AssertIntLE(expectedSz, sizeof(expectedParams)); + XMEMCPY(expectedParams, gRsp + TPM2_HEADER_SIZE, expectedSz); + pos = BuildNoHandleAuditCmd(&ctx, TPM_CC_GetCapability, sessH, params, + 12, nonce); + AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0), 0); + CheckNoHandleAuditReply(TPM_CC_GetCapability, rspSize, nonce, + expectedParams, expectedSz); + pos = BuildNoHandleAuditCmd(&ctx, TPM_CC_GetCapability, sessH, params, + 11, nonce); + AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0), 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_COMMAND_SIZE); + +#ifndef FWTPM_NO_HASH_CMDS + PutU16BE(params, 0); + PutU16BE(params + 2, TPM_ALG_SHA256); + pos = BuildNoHandleAuditCmd(&ctx, TPM_CC_HashSequenceStart, sessH, + params, 4, nonce); + AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0), 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp), TPM_ST_SESSIONS); + FlushHandle(&ctx, GetU32BE(gRsp + TPM2_HEADER_SIZE)); +#endif +#if defined(HAVE_ECC) && !defined(FWTPM_NO_ZGEN_2PHASE) + PutU16BE(params, TPM_ECC_NIST_P256); + pos = BuildNoHandleAuditCmd(&ctx, TPM_CC_EC_Ephemeral, sessH, params, 2, + nonce); + AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0), 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gRsp), TPM_ST_SESSIONS); +#endif +#ifdef WOLFTPM_FWTPM_TCG_TEST + PutU16BE(params, 4); + XMEMSET(params + 2, 0xAB, 4); + pos = BuildNoHandleAuditCmd(&ctx, TPM_CC_Vendor_TCG_Test, sessH, params, + 6, nonce); + AssertIntEQ(FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0), 0); + CheckNoHandleAuditReply(TPM_CC_Vendor_TCG_Test, rspSize, nonce, params, + 6); +#endif + + FWTPM_Cleanup(&ctx); + (void)remove(FWTPM_NV_FILE); + fwtpm_pass("Session on commands with no auth handle:", 0); +} + #ifdef WOLFTPM_FWTPM_UNIT_TEST int FwSessionIsBoundToEntity(FWTPM_CTX* ctx, const FWTPM_Session* sess, TPM_HANDLE handle); @@ -31993,6 +32064,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #ifndef FWTPM_NO_HASH_CMDS test_fwtpm_session_parameter_area(TPM_CC_Hash); #endif + test_fwtpm_no_handle_session_commands(); /* GetCapability */ test_fwtpm_getcap_algorithms(); From 68731c82aefc87881c0d6373f9a86ad1b9787015 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:06:31 -0800 Subject: [PATCH 090/124] Reject a fwTPM PCR selection that lists more than HASH_COUNT hash algorithms --- src/fwtpm/fwtpm_command.c | 6 ++++++ tests/fwtpm_unit_tests.c | 45 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index b98aae533..414c50018 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -449,6 +449,9 @@ static TPM_RC FwValidatePcrSelection(TPM2_Packet* cmd, int cmdSize) check = *cmd; TPM2_Packet_ParseU32(&check, &count); + if (count > HASH_COUNT) { + return TPM_RC_SIZE; + } if (count > (UINT32)(cmdSize - check.pos) / 3U) { return TPM_RC_COMMAND_SIZE; } @@ -19204,6 +19207,9 @@ static TPM_RC FwCmd_Quote(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* PCRselect */ if (rc == 0) { rc = FwValidatePcrSelection(cmd, cmdSize); + if (rc == TPM_RC_SIZE) { + rc |= TPM_RC_P | TPM_RC_3; + } } if (rc == 0) { TPM2_Packet_ParseU32(cmd, &pcrSelCount); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index e0f2640fa..1acc0dad5 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -2508,12 +2508,19 @@ static void test_fwtpm_pcr_allocate(void) /* A selection count that exceeds the remaining packet is truncated */ cmdSz = BuildPcrAllocateCmd(gCmd, TPM_RH_PLATFORM, algs, 1, 1); - PutU32BE(gCmd + TPM2_HEADER_SIZE + 4 + 13, FWTPM_PCR_BANKS * 4 + 1); + PutU32BE(gCmd + TPM2_HEADER_SIZE + 4 + 13, HASH_COUNT); rspSize = 0; rc = FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); AssertIntEQ(rc, TPM_RC_SUCCESS); AssertIntEQ(GetRspRC(gRsp), TPM_RC_COMMAND_SIZE); + /* A TPML_PCR_SELECTION holds HASH_COUNT selections at most */ + PutU32BE(gCmd + TPM2_HEADER_SIZE + 4 + 13, HASH_COUNT + 1); + rspSize = 0; + rc = FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(rc, TPM_RC_SUCCESS); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SIZE); + /* Both banks selected. Per spec 22.5 the change is staged, so the live * allocation must not move until the next Startup(CLEAR). */ cmdSz = BuildPcrAllocateCmd(gCmd, TPM_RH_PLATFORM, algs, 2, 1); @@ -15693,6 +15700,41 @@ static void test_fwtpm_quote_unrestricted_sign(void) fwtpm_pass("Quote(unrestricted sign):", 0); } +/* A TPML_PCR_SELECTION lists HASH_COUNT selections at most, so a quote never + * attests a count it did not marshal (Part 2 Sec.10.9.7). */ +static void test_fwtpm_quote_selection_count(void) +{ + FWTPM_CTX ctx; + int pos, i, rspSize = 0; + UINT32 keyH; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + keyH = CreatePrimaryEccSignHelper(&ctx); + AssertIntNE(keyH, 0); + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Quote); + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 0); pos += 2; /* qualifyingData */ + PutU16BE(gCmd + pos, TPM_ALG_ECDSA); pos += 2; /* inScheme */ + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + pos, HASH_COUNT + 1); pos += 4; + for (i = 0; i < HASH_COUNT + 1; i++) { + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + gCmd[pos++] = (byte)PCR_SELECT_MAX; + XMEMSET(gCmd + pos, 0, PCR_SELECT_MAX); pos += PCR_SELECT_MAX; + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SIZE | TPM_RC_P | TPM_RC_3); + + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Quote PCR selection count:", 0); +} + /* A key that declares a signing scheme must not be downgraded by a wire * inScheme: signing with ECDSA-SHA1 against an ECDSA-SHA256 key is refused * (Part 3 Sec.20.2). */ @@ -32549,6 +32591,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif /* !FWTPM_NO_ECDH */ test_fwtpm_quote_decrypt_key_returns_key(); test_fwtpm_quote_unrestricted_sign(); + test_fwtpm_quote_selection_count(); test_fwtpm_sign_scheme_downgrade_rejected(); test_fwtpm_quote_clockinfo_resetcount_nonzero(); test_fwtpm_certify_decrypt_key_returns_key(); From 94fd4bee17a2368d3f4cdbe7dd31e9bf5d5ffd36 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:10:08 -0800 Subject: [PATCH 091/124] Size the fwTPM PCR auth NV record for the staged allocation and check its marshal --- src/fwtpm/fwtpm_nv.c | 31 +++++++++++++++++++++---------- tests/fwtpm_unit_tests.c | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index 05880d4ce..04810ad74 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -2642,7 +2642,8 @@ int FWTPM_NV_Save(FWTPM_CTX* ctx) } if (hasPcrAuth || ctx->pcrAllocPending || ctx->pcrAllocatedBanks != FWTPM_PCR_ALLOC_DEFAULT) { - word32 needed = 1 + IMPLEMENTATION_PCR * (2 + 64 + 2 + 64 + 2); + word32 needed = 1 + IMPLEMENTATION_PCR * (2 + 64 + 2 + 64 + 2) + + 2; if (needed > bufSz) { byte* newBuf; newBuf = (byte*)XMALLOC(needed, NULL, @@ -3040,7 +3041,7 @@ int FWTPM_NV_SavePcrAuth(FWTPM_CTX* ctx) int i; byte* buf; word32 pos = 0; - word32 bufSz = 1 + IMPLEMENTATION_PCR * (2 + 64 + 2 + 64 + 2); + word32 bufSz = 1 + IMPLEMENTATION_PCR * (2 + 64 + 2 + 64 + 2) + 2; if (ctx == NULL) { return BAD_FUNC_ARG; @@ -3051,17 +3052,27 @@ int FWTPM_NV_SavePcrAuth(FWTPM_CTX* ctx) return TPM_RC_MEMORY; } - FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocatedBanks); - for (i = 0; i < IMPLEMENTATION_PCR; i++) { - FwNvMarshalAuth(buf, &pos, bufSz, &ctx->pcrAuth[i]); - FwNvMarshalDigest(buf, &pos, bufSz, &ctx->pcrPolicy[i]); - FwNvMarshalU16(buf, &pos, bufSz, ctx->pcrPolicyAlg[i]); + rc = FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocatedBanks); + for (i = 0; i < IMPLEMENTATION_PCR && rc == 0; i++) { + rc = FwNvMarshalAuth(buf, &pos, bufSz, &ctx->pcrAuth[i]); + if (rc == 0) { + rc = FwNvMarshalDigest(buf, &pos, bufSz, &ctx->pcrPolicy[i]); + } + if (rc == 0) { + rc = FwNvMarshalU16(buf, &pos, bufSz, ctx->pcrPolicyAlg[i]); + } } /* Appended last so an older record still parses */ - FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocPending); - FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocatedBanksPending); + if (rc == 0) { + rc = FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocPending); + } + if (rc == 0) { + rc = FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocatedBanksPending); + } - rc = FwNvAppendEntry(ctx, FWTPM_NV_TAG_PCR_AUTH, buf, (UINT16)pos); + if (rc == 0) { + rc = FwNvAppendEntry(ctx, FWTPM_NV_TAG_PCR_AUTH, buf, (UINT16)pos); + } TPM2_ForceZero(buf, bufSz); XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 1acc0dad5..1ec89766e 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -24091,6 +24091,42 @@ static void test_fwtpm_nv_pcr_auth_truncated(void) fwtpm_pass("NV truncated PCR auth rejected:", 0); } +/* The PCR auth record has room for the staged allocation after the largest + * authValue and policy on every PCR. It is read back before any full save + * rewrites it. */ +static void test_fwtpm_nv_pcr_auth_full_record(void) +{ + static FWTPM_CTX reload; + FWTPM_CTX ctx; + int i; + + memset(gTnvBuf, 0, sizeof(gTnvBuf)); + TnvSetHal(&ctx); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + for (i = 0; i < IMPLEMENTATION_PCR; i++) { + ctx.pcrAuth[i].size = (UINT16)sizeof(ctx.pcrAuth[i].buffer); + memset(ctx.pcrAuth[i].buffer, 0x11, sizeof(ctx.pcrAuth[i].buffer)); + ctx.pcrPolicy[i].size = (UINT16)sizeof(ctx.pcrPolicy[i].buffer); + memset(ctx.pcrPolicy[i].buffer, 0x22, + sizeof(ctx.pcrPolicy[i].buffer)); + ctx.pcrPolicyAlg[i] = TPM_ALG_SHA256; + } + ctx.pcrAllocPending = 1; + ctx.pcrAllocatedBanksPending = FWTPM_PCR_ALLOC_DEFAULT; + AssertIntEQ(FWTPM_NV_SavePcrAuth(&ctx), TPM_RC_SUCCESS); + + TnvSetHal(&reload); + AssertIntEQ(FWTPM_Init(&reload), TPM_RC_SUCCESS); + AssertIntEQ((int)reload.pcrAllocPending, 1); + AssertIntEQ((int)reload.pcrAllocatedBanksPending, + FWTPM_PCR_ALLOC_DEFAULT); + AssertIntEQ(reload.pcrAuth[IMPLEMENTATION_PCR - 1].size, + sizeof(reload.pcrAuth[0].buffer)); + FWTPM_Cleanup(&reload); + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV full PCR auth record:", 0); +} + static void test_fwtpm_nv_reserved_attributes_rejected(void) { FWTPM_CTX ctx; @@ -32572,6 +32608,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif test_fwtpm_nv_malformed_entry_rejected(); test_fwtpm_nv_pcr_auth_truncated(); + test_fwtpm_nv_pcr_auth_full_record(); test_fwtpm_nv_reserved_attributes_rejected(); test_fwtpm_nv_semantic_entry_skipped(); test_fwtpm_nv_counter(); From 415d296b35042e580eeeb8c19338dd9c036fbac5 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:15:34 -0800 Subject: [PATCH 092/124] Return the allocation failure from fwTPM FwComputeNvName before hashing --- src/fwtpm/fwtpm_crypto.c | 5 ++++- tests/fwtpm_unit_tests.c | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 53a0ebbb9..305db27b0 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -4762,9 +4762,12 @@ int FwComputeNvName(FWTPM_NvIndex* nv, byte* buf, UINT16* sz) FWTPM_DECLARE_VAR(hash, wc_HashAlg); enum wc_HashType hashType = FwGetWcHashType(nv->nvPublic.nameAlg); int hSz = TPM2_GetHashDigestSize(nv->nvPublic.nameAlg); - int rc; + int rc = 0; FWTPM_ALLOC_VAR(hash, wc_HashAlg); + if (rc != 0) { + return rc; + } if (hSz <= 0) { FWTPM_FREE_VAR(hash); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 1ec89766e..1c62f8c7d 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -683,11 +683,25 @@ static void test_fwtpm_crypto_alloc_failure(void) #ifdef HAVE_ECC TPMS_ECC_POINT eccPub; #endif +#ifndef FWTPM_NO_NV + FWTPM_NvIndex nv; + byte nvName[2 + TPM_MAX_DIGEST_SIZE]; + UINT16 nvNameSz = 0; +#endif fwtpm_test_fail_next_alloc(); rc = FwComputeHashUnique(TPM_ALG_SHA256, NULL, 0, NULL, 0, hash); AssertIntEQ(rc, TPM_RC_MEMORY); +#ifndef FWTPM_NO_NV + memset(&nv, 0, sizeof(nv)); + nv.nvPublic.nameAlg = TPM_ALG_SHA256; + fwtpm_test_fail_next_alloc(); + rc = FwComputeNvName(&nv, nvName, &nvNameSz); + AssertIntEQ(rc, TPM_RC_MEMORY); + AssertIntEQ(nvNameSz, 0); +#endif + #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) memset(&rsaPub, 0, sizeof(rsaPub)); fwtpm_test_fail_next_alloc(); From 86523d08a8840abdd24975ca07588af0b05ebb87 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:15:42 -0800 Subject: [PATCH 093/124] Wipe the fwTPM DHKEM labeled extract scratch buffer that holds the ECDH secret --- src/fwtpm/fwtpm_crypto.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 305db27b0..af40ff876 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -1322,6 +1322,7 @@ static TPM_RC FwDhkemExtractAndExpand(enum wc_HashType hashType, UINT16 kemId, scratch, sizeof(scratch), sharedSecret, nSecret); } TPM2_ForceZero(prk, sizeof(prk)); + TPM2_ForceZero(scratch, sizeof(scratch)); return rc; } From 61f2ae0e8981e17501d3c03d7fba0fd0ae2535d3 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:20:20 -0800 Subject: [PATCH 094/124] Pair wc_HmacInit and wc_HmacFree in the fwTPM context blob wrap and the HMAC command --- src/fwtpm/fwtpm_command.c | 10 ++++++++++ src/fwtpm/fwtpm_crypto.c | 16 ++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 414c50018..96a7dbeaa 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -11630,6 +11630,7 @@ static TPM_RC FwCmd_HMAC(FWTPM_CTX* ctx, TPM2_Packet* cmd, int digestSz = 0; FWTPM_Object* obj; FWTPM_DECLARE_VAR(hmac, Hmac); + int hmacInit = 0; int wcHashType = WC_HASH_TYPE_NONE; int paramSzPos, paramStart; enum wc_HashType ht; @@ -11723,6 +11724,12 @@ static TPM_RC FwCmd_HMAC(FWTPM_CTX* ctx, TPM2_Packet* cmd, } /* For KEYEDHASH objects the HMAC key is in privKey. */ + if (rc == 0) { + rc = wc_HmacInit(hmac, NULL, INVALID_DEVID); + if (rc == 0) { + hmacInit = 1; + } + } if (rc == 0) { rc = wc_HmacSetKey(hmac, wcHashType, obj->privKey, (word32)obj->privKeySize); @@ -11751,6 +11758,9 @@ static TPM_RC FwCmd_HMAC(FWTPM_CTX* ctx, TPM2_Packet* cmd, FwRspParamsEnd(rsp, cmdTag, paramSzPos, paramStart); } + if (hmacInit) { + wc_HmacFree(hmac); + } TPM2_ForceZero(digest, sizeof(digest)); FWTPM_FREE_BUF(dataBuf); FWTPM_FREE_VAR(hmac); diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index af40ff876..920699344 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -2615,6 +2615,7 @@ int FwWrapContextBlob(FWTPM_CTX* ctx, UINT64 seq, byte ctxType, FWTPM_DECLARE_VAR(aes, Aes); FWTPM_DECLARE_VAR(hmac, Hmac); int aesInit = 0; + int hmacInit = 0; int totalSz = AES_BLOCK_SIZE + plainSz + WC_SHA256_DIGEST_SIZE; *outSz = 0; @@ -2649,6 +2650,9 @@ int FwWrapContextBlob(FWTPM_CTX* ctx, UINT64 seq, byte ctxType, /* HMAC-SHA256 over iv || ciphertext */ if (rc == 0) { rc = wc_HmacInit(hmac, NULL, INVALID_DEVID); + if (rc == 0) { + hmacInit = 1; + } } if (rc == 0) { rc = wc_HmacSetKey(hmac, WC_SHA256, @@ -2666,7 +2670,9 @@ int FwWrapContextBlob(FWTPM_CTX* ctx, UINT64 seq, byte ctxType, if (rc == 0) { rc = wc_HmacFinal(hmac, out + AES_BLOCK_SIZE + plainSz); } - wc_HmacFree(hmac); + if (hmacInit) { + wc_HmacFree(hmac); + } if (rc == 0) { *outSz = totalSz; @@ -2692,6 +2698,7 @@ int FwUnwrapContextBlob(FWTPM_CTX* ctx, UINT64 seq, byte ctxType, FWTPM_DECLARE_VAR(aes, Aes); FWTPM_DECLARE_VAR(hmac, Hmac); int aesInit = 0; + int hmacInit = 0; int cipherSz; *outSz = 0; @@ -2712,6 +2719,9 @@ int FwUnwrapContextBlob(FWTPM_CTX* ctx, UINT64 seq, byte ctxType, /* Verify HMAC over iv || ciphertext */ if (rc == 0) { rc = wc_HmacInit(hmac, NULL, INVALID_DEVID); + if (rc == 0) { + hmacInit = 1; + } } if (rc == 0) { rc = wc_HmacSetKey(hmac, WC_SHA256, @@ -2729,7 +2739,9 @@ int FwUnwrapContextBlob(FWTPM_CTX* ctx, UINT64 seq, byte ctxType, if (rc == 0) { rc = wc_HmacFinal(hmac, computedHmac); } - wc_HmacFree(hmac); + if (hmacInit) { + wc_HmacFree(hmac); + } if (rc == 0) { if (TPM2_ConstantCompare(computedHmac, From ca751bef5dc94f4a47010f021545f026c3acae35 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:25:00 -0800 Subject: [PATCH 095/124] Bound the fwTPM FwCredentialWrap output by the size of the caller buffer --- src/fwtpm/fwtpm_command.c | 3 ++- src/fwtpm/fwtpm_crypto.c | 6 +++++- tests/fwtpm_unit_tests.c | 37 ++++++++++++++++++++++++++++++++++++ wolftpm/fwtpm/fwtpm_crypto.h | 2 +- 4 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 96a7dbeaa..48663facd 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -20052,7 +20052,8 @@ static TPM_RC FwCmd_MakeCredential(FWTPM_CTX* ctx, TPM2_Packet* cmd, hmacKey, hmacKeySz, keyObj->pub.nameAlg, credential.buffer, credential.size, objectName.name, objectName.size, - encCred, &encCredSz, outerHmac); + encCred, (int)FWTPM_SIZEOF_BUF(encCred, FWTPM_MAX_NV_DATA + 2), + &encCredSz, outerHmac); } /* Build response */ diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 920699344..ae5e02d06 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -5103,7 +5103,7 @@ TPM_RC FwCredentialWrap( TPMI_ALG_HASH nameAlg, const byte* credential, UINT16 credSz, const byte* name, int nameSz, - byte* encCred, word32* encCredSz, + byte* encCred, int encCredBufSz, word32* encCredSz, byte* outerHmac) { TPM_RC rc; @@ -5111,6 +5111,10 @@ TPM_RC FwCredentialWrap( FWTPM_DECLARE_VAR(aes, Aes); FWTPM_DECLARE_VAR(hmac, Hmac); + if (encCredBufSz < 2 + (int)credSz) { + return TPM_RC_SIZE; + } + FWTPM_ALLOC_VAR(aes, Aes); FWTPM_ALLOC_VAR(hmac, Hmac); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 1c62f8c7d..cddbd60c8 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -31574,6 +31574,40 @@ static void test_fwtpm_attest_null_signer(void) } #endif /* HAVE_ECC && !FWTPM_NO_ATTESTATION */ +#ifndef FWTPM_NO_CREDENTIAL +/* The credential wrap output is the credential and its 2-octet size. */ +static void test_fwtpm_credential_wrap_output_size(void) +{ + byte symKey[AES_128_KEY_SIZE]; + byte hmacKey[WC_SHA256_DIGEST_SIZE]; + byte credential[32]; + byte name[2 + WC_SHA256_DIGEST_SIZE]; + byte encCred[2 + sizeof(credential) + 1]; + byte outerHmac[TPM_MAX_DIGEST_SIZE]; + word32 encCredSz = 0; + + memset(symKey, 0x11, sizeof(symKey)); + memset(hmacKey, 0x22, sizeof(hmacKey)); + memset(credential, 0x33, sizeof(credential)); + memset(name, 0x44, sizeof(name)); + memset(encCred, 0xEE, sizeof(encCred)); + + AssertIntEQ(FwCredentialWrap(symKey, sizeof(symKey), hmacKey, + sizeof(hmacKey), TPM_ALG_SHA256, credential, sizeof(credential), + name, sizeof(name), encCred, 2 + sizeof(credential) - 1, &encCredSz, + outerHmac), TPM_RC_SIZE); + AssertIntEQ(encCred[0], 0xEE); + AssertIntEQ(FwCredentialWrap(symKey, sizeof(symKey), hmacKey, + sizeof(hmacKey), TPM_ALG_SHA256, credential, sizeof(credential), + name, sizeof(name), encCred, 2 + sizeof(credential), &encCredSz, + outerHmac), TPM_RC_SUCCESS); + AssertIntEQ(encCredSz, 2 + sizeof(credential)); + AssertIntEQ(encCred[sizeof(encCred) - 1], 0xEE); + + fwtpm_pass("Credential wrap output size:", 0); +} +#endif /* !FWTPM_NO_CREDENTIAL */ + #if defined(HAVE_ECC) && !defined(FWTPM_NO_ATTESTATION) && \ !defined(FWTPM_NO_CREDENTIAL) /* keyHandle has to be a Storage Key: anything else is TPM_RC_TYPE for the @@ -32724,6 +32758,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) !defined(FWTPM_NO_CREDENTIAL) test_fwtpm_activate_credential_key_type(); #endif +#ifndef FWTPM_NO_CREDENTIAL + test_fwtpm_credential_wrap_output_size(); +#endif #if defined(WOLFTPM_FWTPM_UNIT_TEST) && !defined(WOLFTPM_FWTPM_TIS) test_fwtpm_io_command_buffer_wiped(); #endif diff --git a/wolftpm/fwtpm/fwtpm_crypto.h b/wolftpm/fwtpm/fwtpm_crypto.h index 6f5299849..c319d6f8c 100644 --- a/wolftpm/fwtpm/fwtpm_crypto.h +++ b/wolftpm/fwtpm/fwtpm_crypto.h @@ -402,7 +402,7 @@ TPM_RC FwCredentialWrap( TPMI_ALG_HASH nameAlg, const byte* credential, UINT16 credSz, const byte* name, int nameSz, - byte* encCred, word32* encCredSz, + byte* encCred, int encCredBufSz, word32* encCredSz, byte* outerHmac); TPM_RC FwCredentialUnwrap( From 2a0403362a598f5cc7eec06af046f399f625a2ec Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:27:18 -0800 Subject: [PATCH 096/124] Release the saved-context slot when a fwTPM session ContextSave cannot wrap the context --- src/fwtpm/fwtpm_command.c | 3 +++ tests/fwtpm_unit_tests.c | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 48663facd..11711ae0b 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -6721,6 +6721,9 @@ static TPM_RC FwCmd_ContextSave(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { TPM2_ForceZero(sess, sizeof(FWTPM_Session)); } + else { + ctx->contextLiveCount--; + } } else if (isSequence) { FWTPM_DECLARE_BUF(seqPlain, FWTPM_SEQ_CTX_PLAIN_MAX); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index cddbd60c8..f890710d5 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -22824,6 +22824,39 @@ static void test_fwtpm_context_save(void) FWTPM_Cleanup(&ctx); fwtpm_pass("ContextSave:", 0); } + +/* A session ContextSave that cannot wrap the context leaves the session + * loaded and does not keep a saved-context slot for it. */ +static void test_fwtpm_context_save_wrap_failure(void) +{ + FWTPM_CTX ctx; + int rspSize = 0, liveCount; + UINT32 sessH; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + sessH = StartSessionHelper(&ctx, TPM_SE_HMAC); + AssertIntNE(sessH, 0); + liveCount = ctx.contextLiveCount; + + ctx.ctxProtectKeyValid = 0; + BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 14, TPM_CC_ContextSave); + PutU32BE(gCmd + 10, sessH); + FWTPM_ProcessCommand(&ctx, gCmd, 14, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_FAILURE); + AssertIntEQ(ctx.contextLiveCount, liveCount); + + ctx.ctxProtectKeyValid = 1; + BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 14, TPM_CC_ContextSave); + PutU32BE(gCmd + 10, sessH); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, 14, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + AssertIntEQ(ctx.contextLiveCount, liveCount + 1); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("ContextSave wrap failure:", 0); +} #endif /* !FWTPM_NO_CONTEXT */ /* A saved context must load at most once; replaying the same blob is @@ -32496,6 +32529,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_evict_control_persistent_object_rejected(); #ifndef FWTPM_NO_CONTEXT test_fwtpm_context_save(); + test_fwtpm_context_save_wrap_failure(); test_fwtpm_context_load_replay_rejected(); test_fwtpm_contextload_forged_object_blob_rejected(); test_fwtpm_contextload_short_blob_rejected(); From f78378d75a9ad8bcb26415f747993d051d3281c3 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:27:18 -0800 Subject: [PATCH 097/124] Wipe the fwTPM NV integrity key buffer when the HAL key callback fails --- src/fwtpm/fwtpm_nv.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index 04810ad74..86fb2defc 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -942,6 +942,8 @@ static int FwNvGetIntegrityKey(FWTPM_CTX* ctx, byte* key, word32* keySz) *keySz > 0) { return 1; } + TPM2_ForceZero(key, FWTPM_NV_KEY_SIZE); + *keySz = 0; return 0; } #if !defined(NO_FILESYSTEM) From ad8898d5a9c03783d966e146fcb2b25e195780de Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:32:45 -0800 Subject: [PATCH 098/124] Fail the fwTPM NV journal load and save when the HAL integrity key callback fails --- docs/fwtpm/hal-and-porting.md | 2 +- src/fwtpm/fwtpm_nv.c | 57 ++++++++++++++++++++++++++-------- tests/fwtpm_unit_tests.c | 58 +++++++++++++++++++++++++++++++++++ 3 files changed, 104 insertions(+), 13 deletions(-) diff --git a/docs/fwtpm/hal-and-porting.md b/docs/fwtpm/hal-and-porting.md index 6733c8095..d0af6e9f0 100644 --- a/docs/fwtpm/hal-and-porting.md +++ b/docs/fwtpm/hal-and-porting.md @@ -95,7 +95,7 @@ FWTPM_NV_SetHAL(&ctx, &hal); /* before FWTPM_Init() */ In append-only mode the journal buffers a pending program granule internally and flushes full, aligned granules through `write()`. A programmed cell is never rewritten, and a whole sector is erased only on compaction. The header sector is therefore not erased on every append, and a torn final commit (for example from power loss) is ignored on the next load while all previously committed state survives. -A `get_integrity_key` callback is strongly recommended on flash, so the MAC checkpoints authenticate the journal and reject a torn or tampered tail. Setting `writeAlign <= 1` selects no buffering, so byte-writable NV (EEPROM or FRAM) works with a plain `write()`. +A `get_integrity_key` callback is strongly recommended on flash, so the MAC checkpoints authenticate the journal and reject a torn or tampered tail. When the callback returns an error or a zero-length key, `FWTPM_Init()` and NV saves fail instead of running without the MAC. Setting `writeAlign <= 1` selects no buffering, so byte-writable NV (EEPROM or FRAM) works with a plain `write()`. !!! warning Compaction still erases the whole region before rewriting, so a power loss during compaction itself remains a vulnerable window. A future two-region ping-pong layout would close it. diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index 86fb2defc..dcc0d8ce5 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -933,7 +933,10 @@ static int FwNvLoadOrCreateKeyFile(FWTPM_CTX* ctx, byte* key, word32* keySz) #endif /* !NO_FILESYSTEM */ /* Resolve the journal integrity key: a platform-provided device secret if - * the HAL supplies one, else the default file backend's key file. */ + * the HAL supplies one, else the default file backend's key file. Returns 1 + * with a key and 0 when there is none. A HAL key callback that fails returns + * a negative value: the journal it authenticates must then be neither loaded + * nor written. */ static int FwNvGetIntegrityKey(FWTPM_CTX* ctx, byte* key, word32* keySz) { *keySz = 0; @@ -944,7 +947,7 @@ static int FwNvGetIntegrityKey(FWTPM_CTX* ctx, byte* key, word32* keySz) } TPM2_ForceZero(key, FWTPM_NV_KEY_SIZE); *keySz = 0; - return 0; + return -1; } #if !defined(NO_FILESYSTEM) if (ctx->nvHal.read == FwNvFileRead) { @@ -1081,15 +1084,14 @@ static int FwNvComputeJournalMac(FWTPM_CTX* ctx, const byte* key, /* Journal Operations */ /* ========================================================================= */ -/* Write NV header at offset 0 */ -static int FwNvWriteHeader(FWTPM_CTX* ctx) +/* Write NV header at offset 0. The caller resolves the integrity key, as it + * has to be there before the journal is touched; keySz is 0 without one. */ +static int FwNvWriteHeader(FWTPM_CTX* ctx, const byte* key, word32 keySz) { byte hdr[sizeof(FWTPM_NV_HEADER)]; /* 4 x UINT32 = 16 bytes */ FWTPM_NV_HAL* hal = &ctx->nvHal; - byte key[FWTPM_NV_KEY_SIZE]; byte mac[FWTPM_NV_MAC_SIZE]; - word32 keySz = 0; int rc; FwStoreU32LE(hdr + 0, FWTPM_NV_MAGIC); @@ -1101,13 +1103,11 @@ static int FwNvWriteHeader(FWTPM_CTX* ctx) /* Rewrite the trailing MAC in place (byte-addressable only; append-only * commits integrity via FwNvAppendCheckpoint instead). */ - if (rc == TPM_RC_SUCCESS && !FW_NV_APPEND_ONLY(hal) && - FwNvGetIntegrityKey(ctx, key, &keySz)) { + if (rc == TPM_RC_SUCCESS && !FW_NV_APPEND_ONLY(hal) && keySz > 0) { rc = FwNvComputeJournalMac(ctx, key, keySz, mac); if (rc == TPM_RC_SUCCESS) { rc = FwNvHalWrite(ctx, ctx->nvWritePos, mac, sizeof(mac)); } - TPM2_ForceZero(key, sizeof(key)); } return rc; } @@ -1139,6 +1139,9 @@ static int FwNvAppendCheckpoint(FWTPM_CTX* ctx) /* MAC over [header .. current writePos) (this entry not included). */ haveKey = FwNvGetIntegrityKey(ctx, key, &keySz); + if (haveKey < 0) { + return TPM_RC_FAILURE; + } if (haveKey) { rc = FwNvComputeJournalMac(ctx, key, keySz, mac); TPM2_ForceZero(key, sizeof(key)); @@ -1205,6 +1208,8 @@ static int FwNvAppendEntryEx(FWTPM_CTX* ctx, UINT16 tag, word32 entrySize = TLV_HDR_SIZE + valueLen; word32 reserve = FWTPM_NV_MAC_SIZE; byte tlvHdr[TLV_HDR_SIZE]; + byte key[FWTPM_NV_KEY_SIZE]; + word32 keySz = 0; word32 savedWritePos; int rc; @@ -1264,6 +1269,13 @@ static int FwNvAppendEntryEx(FWTPM_CTX* ctx, UINT16 tag, } } + /* The entry overwrites the journal MAC of a byte-addressable backend, so + * the key for the new MAC has to be there first */ + if (!FW_NV_APPEND_ONLY(hal) && + FwNvGetIntegrityKey(ctx, key, &keySz) < 0) { + return TPM_RC_FAILURE; + } + /* Write TLV header */ FwStoreU16LE(tlvHdr, tag); FwStoreU16LE(tlvHdr + 2, valueLen); @@ -1292,9 +1304,11 @@ static int FwNvAppendEntryEx(FWTPM_CTX* ctx, UINT16 tag, else #endif { - rc = FwNvWriteHeader(ctx); /* byte-addressable: header + MAC */ + /* byte-addressable: header + MAC */ + rc = FwNvWriteHeader(ctx, key, keySz); } } + TPM2_ForceZero(key, sizeof(key)); if (rc != TPM_RC_SUCCESS) { /* A failed append must leave no committable remnant. On a byte- * addressable backend roll the write cursor back so the partial entry @@ -2167,6 +2181,9 @@ static int FwNvInitAppendOnly(FWTPM_CTX* ctx, byte** valueBufP, int rc = TPM_RC_SUCCESS; haveKey = FwNvGetIntegrityKey(ctx, vKey, &vKeySz); + if (haveKey < 0) { + return TPM_RC_FAILURE; + } /* Pass 1: locate the last authenticated MAC checkpoint. */ scanPos = (word32)sizeof(FWTPM_NV_HEADER); @@ -2311,6 +2328,7 @@ int FWTPM_NV_Init(FWTPM_CTX* ctx) word32 valueBufSz = FWTPM_NV_MAX_ENTRY; byte vKey[FWTPM_NV_KEY_SIZE]; word32 vKeySz = 0; + int haveKey; if (ctx == NULL) { return BAD_FUNC_ARG; @@ -2391,7 +2409,11 @@ int FWTPM_NV_Init(FWTPM_CTX* ctx) hdr.magic == FWTPM_NV_MAGIC && hdr.version == FWTPM_NV_VERSION) { ctx->nvWritePos = hdr.writePos; - if (FwNvGetIntegrityKey(ctx, vKey, &vKeySz)) { + haveKey = FwNvGetIntegrityKey(ctx, vKey, &vKeySz); + if (haveKey < 0) { + rc = TPM_RC_FAILURE; + } + else if (haveKey) { byte storedMac[FWTPM_NV_MAC_SIZE]; byte calcMac[FWTPM_NV_MAC_SIZE]; if (ctx->nvWritePos + FWTPM_NV_MAC_SIZE > hal->maxSize) { @@ -2536,6 +2558,9 @@ int FWTPM_NV_Save(FWTPM_CTX* ctx) byte* buf = NULL; word32 bufSz = FWTPM_NV_MAX_ENTRY; word32 pos; + byte key[FWTPM_NV_KEY_SIZE]; + word32 keySz = 0; + int haveKey; UINT64 clockValue = 0; int clockSafe; @@ -2553,9 +2578,16 @@ int FWTPM_NV_Save(FWTPM_CTX* ctx) return TPM_RC_FAILURE; } + /* Keep the journal when the new one could not be authenticated */ + haveKey = FwNvGetIntegrityKey(ctx, key, &keySz); + if (haveKey < 0) { + return TPM_RC_FAILURE; + } + /* Allocate marshal buffer for largest single entry */ buf = (byte*)XMALLOC(bufSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (buf == NULL) { + TPM2_ForceZero(key, sizeof(key)); return TPM_RC_MEMORY; } @@ -2579,8 +2611,9 @@ int FWTPM_NV_Save(FWTPM_CTX* ctx) /* Write header (will be updated at end with final writePos) */ if (rc == 0) { - rc = FwNvWriteHeader(ctx); + rc = FwNvWriteHeader(ctx, key, keySz); } + TPM2_ForceZero(key, sizeof(key)); /* --- Seeds --- */ if (rc == 0) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index f890710d5..70ee6f374 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -15143,10 +15143,14 @@ static int TnvWrite(void* c, word32 off, const byte* buf, word32 sz) memcpy(gTnvBuf + off, buf, sz); return TPM_RC_SUCCESS; } +static int gTnvKeyFail; static int TnvKey(void* c, byte* key, word32* keySz) { (void)c; memset(key, 0x5A, 32); + if (gTnvKeyFail) { + return TPM_RC_FAILURE; + } *keySz = 32; return 0; } @@ -15213,6 +15217,59 @@ static void test_fwtpm_nv_read_error_keeps_journal(void) fwtpm_pass("NV read error keeps journal:", 0); } +/* A HAL that supplies the journal integrity key but fails to produce it + * must not get its journal loaded unverified or rewritten without a MAC. */ +static void test_fwtpm_nv_integrity_key_failure(void) +{ + FWTPM_CTX ctx; + byte seed[FWTPM_SEED_SIZE]; + static byte snap[TNV_SIZE]; + + memset(gTnvBuf, 0, sizeof(gTnvBuf)); + TnvSetHal(&ctx); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(FWTPM_NV_Save(&ctx), TPM_RC_SUCCESS); + memcpy(seed, ctx.ownerSeed, sizeof(seed)); + memcpy(snap, gTnvBuf, sizeof(snap)); + + /* Save: the journal stays as it was */ + gTnvKeyFail = 1; + AssertIntNE(FWTPM_NV_Save(&ctx), TPM_RC_SUCCESS); + gTnvKeyFail = 0; + AssertIntEQ(memcmp(snap, gTnvBuf, sizeof(snap)), 0); + + /* Incremental save: the entry would land on the journal MAC */ + gTnvKeyFail = 1; + AssertIntNE(FWTPM_NV_SaveFlags(&ctx), TPM_RC_SUCCESS); + gTnvKeyFail = 0; + AssertIntEQ(memcmp(snap, gTnvBuf, sizeof(snap)), 0); + FWTPM_Cleanup(&ctx); + memcpy(snap, gTnvBuf, sizeof(snap)); + + /* Load: neither replayed nor regenerated */ + TnvSetHal(&ctx); + gTnvKeyFail = 1; + AssertIntNE(FWTPM_Init(&ctx), TPM_RC_SUCCESS); + gTnvKeyFail = 0; + AssertIntEQ(memcmp(snap, gTnvBuf, sizeof(snap)), 0); + + /* First boot on empty storage */ + memset(gTnvBuf, 0, sizeof(gTnvBuf)); + TnvSetHal(&ctx); + gTnvKeyFail = 1; + AssertIntNE(FWTPM_Init(&ctx), TPM_RC_SUCCESS); + gTnvKeyFail = 0; + + /* Once the key is back, the same seeds load */ + memcpy(gTnvBuf, snap, sizeof(snap)); + TnvSetHal(&ctx); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(memcmp(seed, ctx.ownerSeed, sizeof(seed)), 0); + FWTPM_Cleanup(&ctx); + TPM2_ForceZero(seed, sizeof(seed)); + fwtpm_pass("NV integrity key failure:", 0); +} + static void test_fwtpm_nv_journal_tamper_rejected(void) { FWTPM_CTX ctx; @@ -32685,6 +32742,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_nv_read_public(); test_fwtpm_nv_journal_tamper_rejected(); test_fwtpm_nv_read_error_keeps_journal(); + test_fwtpm_nv_integrity_key_failure(); #if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) test_fwtpm_nv_journal_mac_alloc_failure(); #endif From cd1bb665bf217597567b87e802e040fca7eec708 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 17 Nov 2026 21:44:50 -0800 Subject: [PATCH 099/124] Count a failed HMAC on a DA bound fwTPM session after its bind handle is reused --- src/fwtpm/fwtpm_command.c | 31 ++++++++++++++++--------------- tests/fwtpm_unit_tests.c | 11 +++++++++++ 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 11711ae0b..ccdc8d242 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -23306,7 +23306,7 @@ static void FwDaSelfHeal(FWTPM_CTX* ctx) static int FwDaRegisterFailure(FWTPM_CTX* ctx, TPM_HANDLE entityH) { /* Platform authorization is not DA-protected. The other exempt permanent - * hierarchies are handled by FwHandleIsNoDA below. */ + * hierarchies are left out by FwAuthSlotDAUse. */ if (entityH == TPM_RH_PLATFORM) { return 0; } @@ -23322,20 +23322,21 @@ static int FwDaRegisterFailure(FWTPM_CTX* ctx, TPM_HANDLE entityH) } return 0; } - if (!FwHandleIsNoDA(ctx, entityH)) { - /* Cap at maxTries so a command that bypasses the lockout gate (e.g. a - * noDA primary handle with a DA-protected secondary auth) cannot grow - * the counter or append NV entries without bound while already - * locked. */ - if (ctx->daRecoveryTime != 0 && - ctx->daFailedTries < ctx->daMaxTries) { - ctx->daFailedTries++; - ctx->orderly = 0; - (void)FWTPM_NV_SaveFlags(ctx); - } - if (ctx->daFailedTries >= ctx->daMaxTries) { - return 1; - } + /* The caller found the authValue DA protected (FwAuthSlotDAUse). For a + * bound session that was settled when the session started, so whatever + * holds the bind handle now is not looked at again. + * Cap at maxTries so a command that bypasses the lockout gate (e.g. a + * noDA primary handle with a DA-protected secondary auth) cannot grow + * the counter or append NV entries without bound while already + * locked. */ + if (ctx->daRecoveryTime != 0 && + ctx->daFailedTries < ctx->daMaxTries) { + ctx->daFailedTries++; + ctx->orderly = 0; + (void)FWTPM_NV_SaveFlags(ctx); + } + if (ctx->daFailedTries >= ctx->daMaxTries) { + return 1; } return 0; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 70ee6f374..29c3a3e02 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -19143,6 +19143,17 @@ static void test_fwtpm_da_bound_session_no_auth_slot(void) AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_DictionaryAttackLockReset, TPM_RH_LOCKOUT), TPM_RC_SUCCESS); + /* Still counted once a noDA object has taken over the bind handle */ + sessH = DaStartBoundSession(&ctx, daKey); + AssertIntNE(sessH, 0); + FlushHandle(&ctx, daKey); + AssertIntEQ(DaMakeEccSignKey(&ctx, 0x00040472), daKey); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_AUTH_FAIL); + AssertIntEQ((int)ctx.daFailedTries, 1); + FlushHandle(&ctx, sessH); + AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_DictionaryAttackLockReset, + TPM_RH_LOCKOUT), TPM_RC_SUCCESS); + /* Bound to lockout: locks lockoutAuth without counting a try */ sessH = DaStartBoundSession(&ctx, TPM_RH_LOCKOUT); AssertIntNE(sessH, 0); From aed0aa72c3bd1d08e9127e60f5e8d7c19df9d188 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 06:49:19 -0800 Subject: [PATCH 100/124] Limit a caller-supplied fwTPM KEYEDHASH sign or decrypt key to the scheme hash block size --- src/fwtpm/fwtpm_command.c | 41 ++++++++++++++++++++++++++++++++++++ tests/fwtpm_unit_tests.c | 44 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index ccdc8d242..83a492c9e 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -3273,6 +3273,35 @@ static TPM_RC FwCheckCreateAuthSize(const TPM2B_AUTH* auth, return TPM_RC_SUCCESS; } +/* A caller-supplied key for a KEYEDHASH signing or decryption object is no + * larger than the block size of the scheme hash (Part 3 Sec.12.1). */ +static TPM_RC FwCheckCreateKeyedHashSize(const TPMT_PUBLIC* pub, + UINT16 dataSz) +{ + UINT16 scheme = pub->parameters.keyedHashDetail.scheme.scheme; + TPMI_ALG_HASH hashAlg; + int blockSz; + + if ((pub->objectAttributes & + (TPMA_OBJECT_sign | TPMA_OBJECT_decrypt)) == 0) { + return TPM_RC_SUCCESS; + } + if (scheme == TPM_ALG_NULL) { + hashAlg = pub->nameAlg; + } + else if (scheme == TPM_ALG_XOR) { + hashAlg = pub->parameters.keyedHashDetail.scheme.details.xorr.hashAlg; + } + else { + hashAlg = pub->parameters.keyedHashDetail.scheme.details.hmac.hashAlg; + } + blockSz = wc_HashGetBlockSize(FwGetWcHashType(hashAlg)); + if (blockSz <= 0 || (int)dataSz > blockSz) { + return TPM_RC_SIZE; + } + return TPM_RC_SUCCESS; +} + static TPM_RC FwValidateCreateAttributes(const TPMT_PUBLIC* pub, const FWTPM_Object* parent, UINT16 sensitiveDataSz) { @@ -5233,6 +5262,10 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (sensDataSize > (UINT16)FWTPM_MAX_PRIVKEY_DER) { rc = TPM_RC_SIZE; } + if (rc == 0) { + rc = FwCheckCreateKeyedHashSize( + &inPublic->publicArea, sensDataSize); + } if (rc == 0) { XMEMCPY(obj->privKey, sensData, sensDataSize); obj->privKeySize = (int)sensDataSize; @@ -8464,6 +8497,10 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (sensDataSize > (UINT16)FWTPM_MAX_PRIVKEY_DER) { rc = TPM_RC_SIZE; } + if (rc == 0) { + rc = FwCheckCreateKeyedHashSize( + &inPublic->publicArea, sensDataSize); + } if (rc == 0) { XMEMCPY(privKeyDer, sensData, sensDataSize); privKeyDerSz = (int)sensDataSize; @@ -10712,6 +10749,10 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (sensDataSize > (UINT16)FWTPM_MAX_PRIVKEY_DER) { rc = TPM_RC_SIZE; } + if (rc == 0) { + rc = FwCheckCreateKeyedHashSize( + &inPublic->publicArea, sensDataSize); + } if (rc == 0) { XMEMCPY(privKeyDer, sensData, sensDataSize); privKeyDerSz = (int)sensDataSize; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 29c3a3e02..cf33e3267 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -11756,6 +11756,49 @@ static void test_fwtpm_create_sensitive_data_size(void) fwtpm_pass("Create sensitive data size:", 0); } +/* A caller-supplied HMAC key is limited to the block size of the scheme + * hash; sealed data is not (Part 3 Sec.12.1). */ +static void test_fwtpm_create_keyedhash_key_size(void) +{ + static const UINT32 cc[] = { + TPM_CC_Create, TPM_CC_CreateLoaded, TPM_CC_CreatePrimary + }; + /* fixedTPM | fixedParent | userWithAuth | noDA | sign */ + const UINT32 attrs = 0x00040452; + FWTPM_CTX ctx; + byte key[WC_SHA256_BLOCK_SIZE + 1]; + UINT32 parentH, h; + int i; + + memset(&ctx, 0, sizeof(ctx)); + memset(key, 0x6B, sizeof(key)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + parentH = CreatePrimaryHelper(&ctx, FW_TEST_CREATE_ALG); + AssertIntNE(parentH, 0); + + for (i = 0; i < (int)(sizeof(cc) / sizeof(cc[0])); i++) { + h = (cc[i] == TPM_CC_CreatePrimary) ? (TPM_HANDLE)TPM_RH_OWNER : + parentH; + AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_KEYEDHASH, + attrs, 0, key, WC_SHA256_BLOCK_SIZE), TPM_RC_SUCCESS); + if (cc[i] != TPM_CC_Create) { + FlushHandle(&ctx, GetU32BE(gRsp + TPM2_HEADER_SIZE)); + } + AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_KEYEDHASH, + attrs, 0, key, WC_SHA256_BLOCK_SIZE + 1), TPM_RC_SIZE); + AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_KEYEDHASH, + FW_TEST_SEALED_ATTRS, 0, key, WC_SHA256_BLOCK_SIZE + 1), + TPM_RC_SUCCESS); + if (cc[i] != TPM_CC_Create) { + FlushHandle(&ctx, GetU32BE(gRsp + TPM2_HEADER_SIZE)); + } + } + + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Create KEYEDHASH key size:", 0); +} + /* The authValue of a new object is limited to the nameAlg digest size once * its trailing zeros are dropped (Part 3 Sec.12.1). */ static void test_fwtpm_create_auth_size(void) @@ -32386,6 +32429,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_create_primary_creation_data(); test_fwtpm_create_creation_data(); test_fwtpm_create_sensitive_data_size(); + test_fwtpm_create_keyedhash_key_size(); test_fwtpm_create_auth_size(); #ifndef NO_AES test_fwtpm_create_symcipher_caller_key(); From c15e701356202144ff8d3d4621df98ab3c1463a6 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 06:51:49 -0800 Subject: [PATCH 101/124] Keep the allocation failure and skip the HMAC free in fwTPM FwComputeTicketHmac --- src/fwtpm/fwtpm_crypto.c | 16 ++++++++++++---- tests/fwtpm_unit_tests.c | 8 ++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index ae5e02d06..9cfbf6250 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -318,7 +318,8 @@ int FwComputeTicketHmac(FWTPM_CTX* ctx, UINT32 hierarchy, int proofSz = TPM2_GetHashDigestSize(hashAlg); FWTPM_DECLARE_VAR(hmacCtx, Hmac); enum wc_HashType wcHash = FwGetWcHashType(hashAlg); - int rc; + int rc = 0; + int hmacInit = 0; FWTPM_ALLOC_VAR(hmacCtx, Hmac); @@ -330,9 +331,14 @@ int FwComputeTicketHmac(FWTPM_CTX* ctx, UINT32 hierarchy, tagBytes[0] = (byte)(ticketTag >> 8); tagBytes[1] = (byte)(ticketTag); - rc = FwComputeProofValue(ctx, hierarchy, hashAlg, proof, proofSz); + if (rc == 0) { + rc = FwComputeProofValue(ctx, hierarchy, hashAlg, proof, proofSz); + } if (rc == 0) { rc = wc_HmacInit(hmacCtx, NULL, INVALID_DEVID); + if (rc == 0) { + hmacInit = 1; + } } if (rc == 0) { rc = wc_HmacSetKey(hmacCtx, (int)wcHash, proof, (word32)proofSz); @@ -349,12 +355,14 @@ int FwComputeTicketHmac(FWTPM_CTX* ctx, UINT32 hierarchy, if (rc == 0) { rc = wc_HmacFinal(hmacCtx, hmacOut); } - wc_HmacFree(hmacCtx); + if (hmacInit) { + wc_HmacFree(hmacCtx); + } if (rc == 0) { *hmacOutSz = proofSz; } - else { + else if (rc != TPM_RC_MEMORY) { rc = TPM_RC_FAILURE; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index cf33e3267..202419e8b 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -749,6 +749,14 @@ static void test_fwtpm_crypto_alloc_failure(void) &sensitiveType, &auth, der, &derSz); AssertIntEQ(rc, TPM_RC_MEMORY); + memset(&ctx, 0, sizeof(ctx)); + derSz = 0; + fwtpm_test_fail_next_alloc(); + rc = FwComputeTicketHmac(&ctx, TPM_RH_OWNER, TPM_ALG_SHA256, + TPM_ST_HASHCHECK, hash, sizeof(hash), NULL, 0, aesKey, &derSz); + AssertIntEQ(rc, TPM_RC_MEMORY); + AssertIntEQ(derSz, 0); + fwtpm_pass("Crypto allocation failures preserved:", 0); } #endif From c86cab97b4391f9118cfc5c698a7e07a60bc9f09 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 06:51:54 -0800 Subject: [PATCH 102/124] Return the allocation failure from fwTPM FwCredentialWrap before encrypting --- src/fwtpm/fwtpm_crypto.c | 7 ++++++- tests/fwtpm_unit_tests.c | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 9cfbf6250..569ea26df 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -5114,7 +5114,7 @@ TPM_RC FwCredentialWrap( byte* encCred, int encCredBufSz, word32* encCredSz, byte* outerHmac) { - TPM_RC rc; + TPM_RC rc = TPM_RC_SUCCESS; byte iv[AES_BLOCK_SIZE]; FWTPM_DECLARE_VAR(aes, Aes); FWTPM_DECLARE_VAR(hmac, Hmac); @@ -5125,6 +5125,11 @@ TPM_RC FwCredentialWrap( FWTPM_ALLOC_VAR(aes, Aes); FWTPM_ALLOC_VAR(hmac, Hmac); + if (rc != 0) { + FWTPM_FREE_VAR(aes); + FWTPM_FREE_VAR(hmac); + return rc; + } /* Prepend size(2) to credential, then AES-CFB encrypt */ FwStoreU16BE(encCred, credSz); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 202419e8b..ee84b561a 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -676,6 +676,12 @@ static void test_fwtpm_crypto_alloc_failure(void) UINT16 sensitiveType = 0; byte aesKey[WC_SHA256_DIGEST_SIZE]; byte macKey[WC_SHA256_DIGEST_SIZE]; +#ifndef FWTPM_NO_CREDENTIAL + byte encCred[2 + WC_SHA256_DIGEST_SIZE]; + byte outerHmac[WC_SHA256_DIGEST_SIZE]; + word32 encCredSz = 0; + int i; +#endif #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) TPM2B_PUBLIC_KEY_RSA rsaPub; byte seed[FWTPM_SEED_SIZE]; @@ -757,6 +763,16 @@ static void test_fwtpm_crypto_alloc_failure(void) AssertIntEQ(rc, TPM_RC_MEMORY); AssertIntEQ(derSz, 0); +#ifndef FWTPM_NO_CREDENTIAL + for (i = 1; i <= 2; i++) { + fwtpm_test_fail_alloc_at(i); + rc = FwCredentialWrap(aesKey, AES_128_KEY_SIZE, macKey, + sizeof(macKey), TPM_ALG_SHA256, hash, sizeof(hash), name.name, + name.size, encCred, sizeof(encCred), &encCredSz, outerHmac); + AssertIntEQ(rc, TPM_RC_MEMORY); + } +#endif + fwtpm_pass("Crypto allocation failures preserved:", 0); } #endif From 6dded9a1acc068d1bccd2e35aa0e30750985ac65 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 06:53:14 -0800 Subject: [PATCH 103/124] Keep the fwTPM append-only NV granule state when the compaction erase fails --- src/fwtpm/fwtpm_nv.c | 6 ++-- tests/fwtpm_unit_tests.c | 61 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index dcc0d8ce5..92f7d8d6d 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -2600,8 +2600,10 @@ int FWTPM_NV_Save(FWTPM_CTX* ctx) #ifdef WOLFTPM_FWTPM_NV_APPEND_ONLY /* Freshly erased: reset the pending granule so the rewrite streams from 0. */ - ctx->nvGranuleBase = 0; - ctx->nvGranuleFill = 0; + if (rc == 0) { + ctx->nvGranuleBase = 0; + ctx->nvGranuleFill = 0; + } #endif /* Reset write position to after header (only if erase succeeded) */ diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index ee84b561a..4e6c8f38b 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -24587,6 +24587,7 @@ static int gFlashFailRead; /* when set, reads fail (used to fail a checkpoint * MAC computation without touching the log) */ static int gFlashFailReadInCompact; /* fail reads only while compacting */ +static int gFlashFailErase; static FWTPM_CTX* gFlashCtx; static int flash_read(void* c, word32 off, byte* buf, word32 sz) @@ -24606,6 +24607,9 @@ static int flash_read(void* c, word32 off, byte* buf, word32 sz) static int flash_erase(void* c, word32 off, word32 sz) { (void)c; + if (gFlashFailErase) { + return -1; + } if ((off % FNV_SECTOR) != 0 || (sz % FNV_SECTOR) != 0 || sz == 0 || (size_t)off + sz > FNV_SIZE) { return -1; @@ -25042,6 +25046,62 @@ static void test_fwtpm_nv_append_rebuild_probe(void) #endif } +/* Append-only: a compaction whose erase fails has not touched the log, so the + * pending program granule is kept and a later compaction can retry. */ +static void test_fwtpm_nv_append_erase_failure(void) +{ +#if defined(WOLFTPM_FWTPM_NV_APPEND_ONLY) && !defined(FWTPM_NO_NV) + FWTPM_CTX ctx; + FWTPM_NV_HAL hal; + word32 base; + word32 fill; + int rc; + + XMEMSET(gFlashNv, 0xFF, sizeof(gFlashNv)); + gFlashEraseCnt = 0; + gFlashProgCnt = 0; + rc = flash_boot(&ctx, &hal, FNV_PROG, 1); + AssertIntEQ(rc, 0); + + gFlashFailRead = 1; + ctx.disableClear = 1; + rc = FWTPM_NV_SaveFlags(&ctx); /* checkpoint fails */ + gFlashFailRead = 0; + AssertIntNE(rc, 0); + base = ctx.nvGranuleBase; + fill = ctx.nvGranuleFill; + AssertIntGT((int)fill, 0); + + gFlashFailErase = 1; + rc = FWTPM_NV_Save(&ctx); + gFlashFailErase = 0; + AssertIntNE(rc, 0); + AssertIntEQ((int)ctx.nvGranuleBase, (int)base); + AssertIntEQ((int)ctx.nvGranuleFill, (int)fill); + rc = FWTPM_NV_SaveFlags(&ctx); + AssertIntEQ(rc, TPM_RC_NV_UNAVAILABLE); + + rc = FWTPM_NV_Save(&ctx); + AssertIntEQ(rc, 0); + ctx.ownerAuth.size = 4; + XMEMSET(ctx.ownerAuth.buffer, 0xA1, 4); + rc = FWTPM_NV_SaveAuth(&ctx, TPM_RH_OWNER); + AssertIntEQ(rc, 0); + wc_FreeRng(&ctx.rng); /* drop ctx without a save */ + + rc = flash_boot(&ctx, &hal, FNV_PROG, 1); + AssertIntEQ(rc, 0); + AssertIntEQ((int)ctx.disableClear, 1); + AssertIntEQ((int)ctx.ownerAuth.size, 4); + FWTPM_Cleanup(&ctx); + + fwtpm_pass("NV append-only erase failure:", 0); +#else + printf("Test fwTPM: %-6s %-42s Skipped\n", "", + "NV append-only erase failure:"); +#endif +} + #if defined(WOLFTPM_FWTPM_UNIT_TEST) && !defined(_WIN32) static void test_fwtpm_mssim_hash_data_framing(void) { @@ -32426,6 +32486,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_nv_append_checkpoint_failure(); test_fwtpm_nv_append_compaction_failure(); test_fwtpm_nv_append_rebuild_probe(); + test_fwtpm_nv_append_erase_failure(); (void)remove(FWTPM_NV_FILE); /* Key operations */ From ca767f3db3bda094e189f1db087422cd04152f19 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 06:59:14 -0800 Subject: [PATCH 104/124] Refuse a fwTPM session bound to a DA protected entity in every slot during lockout --- src/fwtpm/fwtpm_command.c | 22 ++++---- tests/fwtpm_unit_tests.c | 104 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 114 insertions(+), 12 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 83a492c9e..0015dd4bc 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -24345,22 +24345,20 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, for (pj = 0; pj < cmdAuthCnt; pj++) { int authSlot = pj < (int)entry->authHandleCnt; - if ((FwAuthSlotDAUse(ctx, + int daUse = FwAuthSlotDAUse(ctx, authSlot ? cmdHandles[pj] : (TPM_HANDLE)TPM_RH_NULL, cmdAuths[pj].handle == TPM_RS_PW, - cmdAuths[pj].sess, cmdAuths[pj].cmdHmacSize, NULL) & - (FW_AUTH_USES_ENTITY_DA | FW_AUTH_USES_BIND_DA)) != 0) { - if (authSlot) { - hasDaAuth = 1; - } - else { - hasDaSess = 1; - } + cmdAuths[pj].sess, cmdAuths[pj].cmdHmacSize, NULL); + if ((daUse & FW_AUTH_USES_BIND_DA) != 0) { + hasDaSess = 1; + } + else if ((daUse & FW_AUTH_USES_ENTITY_DA) != 0) { + hasDaAuth = 1; } } - /* A session that authorizes no handle and is bound to a DA protected - * entity is refused for every command, or its HMAC would keep testing - * guesses of the bind authValue. */ + /* A session bound to a DA protected entity is refused for every + * command and in every slot, or its HMAC would keep testing guesses + * of the bind authValue. */ if (hasDaSess) { *rspSize = FwBuildErrorResponse(rspBuf, rspCap, TPM_ST_NO_SESSIONS, TPM_RC_LOCKOUT); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 4e6c8f38b..fc3a2fe9f 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -19233,6 +19233,109 @@ static void test_fwtpm_da_bound_session_no_auth_slot(void) (void)remove(FWTPM_NV_FILE); fwtpm_pass("DA bound session in a non-auth slot:", 0); } + +/* Send cc authorized for a permanent handle with empty auth by an HMAC + * session; the HMAC is correct unless bad is set. */ +static TPM_RC DaSendHierarchyHmacCmd(FWTPM_CTX* ctx, UINT32 cc, + UINT32 handle, UINT32 sessH, int bad) +{ + FWTPM_Session* sess = NULL; + byte nonceCaller[16]; + byte cpBuf[8]; + byte pHash[WC_SHA256_DIGEST_SIZE]; + byte authHmac[WC_SHA256_DIGEST_SIZE]; + UINT8 attrs = TPMA_SESSION_continueSession; + int i, pos, authStart, rspSize = 0; + + for (i = 0; i < FWTPM_MAX_SESSIONS; i++) { + if (ctx->sessions[i].used && ctx->sessions[i].handle == sessH) { + sess = &ctx->sessions[i]; + } + } + AssertNotNull(sess); + memset(nonceCaller, 0x5C, sizeof(nonceCaller)); + PutU32BE(cpBuf, cc); + PutU32BE(cpBuf + 4, handle); + AssertIntEQ(wc_Sha256Hash(cpBuf, sizeof(cpBuf), pHash), 0); + ComputeAuthHmac(sess->sessionKey.buffer, sess->sessionKey.size, pHash, + nonceCaller, sizeof(nonceCaller), sess->nonceTPM.buffer, + sess->nonceTPM.size, NULL, 0, attrs, authHmac); + authHmac[0] ^= (byte)bad; + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, cc); + PutU32BE(gCmd + pos, handle); pos += 4; + authStart = pos; + pos += 4; + PutU32BE(gCmd + pos, sessH); pos += 4; + PutU16BE(gCmd + pos, sizeof(nonceCaller)); pos += 2; + memcpy(gCmd + pos, nonceCaller, sizeof(nonceCaller)); + pos += (int)sizeof(nonceCaller); + gCmd[pos++] = attrs; + PutU16BE(gCmd + pos, sizeof(authHmac)); pos += 2; + memcpy(gCmd + pos, authHmac, sizeof(authHmac)); + pos += (int)sizeof(authHmac); + PutU32BE(gCmd + authStart, (UINT32)(pos - authStart - 4)); + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* A session bound to a DA protected entity is refused while the TPM is + * locked out whatever it authorizes and whether or not its HMAC verifies; + * a session bound to a noDA entity and a password are not + * (Part 1 Sec.19.8.4). */ +static void test_fwtpm_da_bound_session_locked_out(void) +{ + static const struct { + UINT32 cc; + UINT32 handle; + } cmds[] = { + { TPM_CC_Clear, TPM_RH_PLATFORM }, + { TPM_CC_DictionaryAttackLockReset, TPM_RH_LOCKOUT } + }; + FWTPM_CTX ctx; + UINT32 daKey, noDaKey, sessH; + int i; + + (void)remove(FWTPM_NV_FILE); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + for (i = 0; i < (int)(sizeof(cmds) / sizeof(cmds[0])); i++) { + AssertIntEQ(DaSetParams(&ctx, 2, 1000, 1000), TPM_RC_SUCCESS); + daKey = DaMakeEccSignKey(&ctx, 0x00040072); + AssertIntNE(daKey, 0); + noDaKey = DaMakeEccSignKey(&ctx, 0x00040472); + AssertIntNE(noDaKey, 0); + AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_LOCKOUT); + AssertIntEQ((int)ctx.daFailedTries, 2); + + sessH = DaStartBoundSession(&ctx, daKey); + AssertIntNE(sessH, 0); + AssertIntEQ(DaSendHierarchyHmacCmd(&ctx, cmds[i].cc, cmds[i].handle, + sessH, 1), TPM_RC_LOCKOUT); + AssertIntEQ(DaSendHierarchyHmacCmd(&ctx, cmds[i].cc, cmds[i].handle, + sessH, 0), TPM_RC_LOCKOUT); + AssertIntEQ((int)ctx.daFailedTries, 2); + FlushHandle(&ctx, sessH); + + sessH = DaStartBoundSession(&ctx, noDaKey); + AssertIntNE(sessH, 0); + AssertIntEQ(DaSendHierarchyHmacCmd(&ctx, cmds[i].cc, cmds[i].handle, + sessH, 0), TPM_RC_SUCCESS); + AssertIntEQ((int)ctx.daFailedTries, 0); + FlushHandle(&ctx, sessH); + if (cmds[i].cc != TPM_CC_Clear) { + FlushHandle(&ctx, daKey); + FlushHandle(&ctx, noDaKey); + } + } + + FWTPM_Cleanup(&ctx); + (void)remove(FWTPM_NV_FILE); + fwtpm_pass("DA bound session while locked out:", 0); +} #endif /* HAVE_ECC */ #endif /* !FWTPM_NO_DA */ @@ -32808,6 +32911,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_da_selfheal_partial(); test_fwtpm_da_hmac_arms_daused(); test_fwtpm_da_bound_session_no_auth_slot(); + test_fwtpm_da_bound_session_locked_out(); test_fwtpm_da_lockoutauth_failure(); test_fwtpm_da_clear_resets(); test_fwtpm_da_permanent_bits(); From f6174d880969b650b59bc352df2dca2ed3d87ec2 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 06:59:14 -0800 Subject: [PATCH 105/124] Describe fwTPM FWTPM_NV_MAX_ENTRY as the initial NV entry buffer size --- wolftpm/fwtpm/fwtpm_nv.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/wolftpm/fwtpm/fwtpm_nv.h b/wolftpm/fwtpm/fwtpm_nv.h index 9982848e6..880cc52a1 100644 --- a/wolftpm/fwtpm/fwtpm_nv.h +++ b/wolftpm/fwtpm/fwtpm_nv.h @@ -73,7 +73,9 @@ #define FWTPM_NV_NAME_EST 66 /* 2 (alg) + 64 (SHA-512 digest) */ #define FWTPM_NV_AUTH_EST 68 /* 2 (size) + 2 (alg) + 64 (digest) */ -/* Maximum single TLV entry value size (PCR state is largest) */ +/* Initial size of the TLV entry value buffer, sized for the PCR state. The + * saver and the loader grow it for a larger record (PCR auth, NV index, + * persistent object). */ #define FWTPM_NV_MAX_ENTRY (IMPLEMENTATION_PCR * FWTPM_PCR_BANKS * \ TPM_MAX_DIGEST_SIZE + 4) From 4baa18653127536f423e74c556a0976f7584374a Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 07:03:43 -0800 Subject: [PATCH 106/124] Initialize the fwTPM HMAC sequence context in HMAC_Start before setting the key --- src/fwtpm/fwtpm_command.c | 7 +++-- tests/fwtpm_unit_tests.c | 58 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 0015dd4bc..b14468dd2 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -11978,8 +11978,11 @@ static TPM_RC FwCmd_HMAC_Start(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Initialize HMAC with the KEYEDHASH key material */ if (rc == 0) { - rc = wc_HmacSetKey(&seq->ctx.hmac, wcHashType, - seq->hmacKey, seq->hmacKeySz); + rc = wc_HmacInit(&seq->ctx.hmac, NULL, INVALID_DEVID); + if (rc == 0) { + rc = wc_HmacSetKey(&seq->ctx.hmac, wcHashType, + seq->hmacKey, seq->hmacKeySz); + } if (rc != 0) { rc = TPM_RC_FAILURE; } diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index fc3a2fe9f..5c854cb02 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -50,6 +50,9 @@ #if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) #include #endif +#ifdef WOLF_CRYPTO_CB +#include +#endif #include #include @@ -22762,6 +22765,58 @@ static void test_fwtpm_hashcheck_ticket_generated_prefix(void) FWTPM_Cleanup(&ctx); fwtpm_pass("HASHCHECK ticket withheld for generated data:", 0); } + +#if defined(WOLF_CRYPTO_CB) && !defined(FWTPM_NO_PARAM_ENC) && \ + FWTPM_MAX_SESSIONS >= 2 +static int gSeqCryptoCbHmacCnt; + +static int SeqCryptoCb(int devId, wc_CryptoInfo* info, void* cbCtx) +{ + (void)devId; + (void)cbCtx; + if (info->algo_type == WC_ALGO_TYPE_HMAC) { + gSeqCryptoCbHmacCnt++; + } + return CRYPTOCB_UNAVAILABLE; +} + +/* An HMAC sequence runs in software and is not handed to a crypto callback + * device the TPM was never given. */ +static void test_fwtpm_hmac_start_no_crypto_dev(void) +{ + static const byte data[] = { 1, 2, 3, 4 }; + FWTPM_CTX ctx; + UINT32 keyH, seqH; + int pos, rspSize = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + keyH = CreateHmacKeyHelper(&ctx); + AssertIntNE(keyH, 0); + + AssertIntEQ(wc_CryptoCb_RegisterDevice(0, SeqCryptoCb, NULL), 0); + gSeqCryptoCbHmacCnt = 0; + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_HMAC_Start); + PutU32BE(gCmd + pos, keyH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, 0); pos += 2; /* auth */ + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + seqH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + AssertIntEQ(SendSeqDataCmd(&ctx, TPM_CC_SequenceUpdate, seqH, data, + sizeof(data)), TPM_RC_SUCCESS); + AssertIntEQ(SendSeqDataCmd(&ctx, TPM_CC_SequenceComplete, seqH, data, + sizeof(data)), TPM_RC_SUCCESS); + wc_CryptoCb_UnRegisterDevice(0); + AssertIntEQ(gSeqCryptoCbHmacCnt, 0); + + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("HMAC sequence uses no crypto device:", 0); +} +#endif #endif /* !FWTPM_NO_HASH_CMDS */ #if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) @@ -32850,6 +32905,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_read_public_sequence(); test_fwtpm_hashcheck_ticket_generated_prefix(); #if !defined(FWTPM_NO_PARAM_ENC) && FWTPM_MAX_SESSIONS >= 2 +#ifdef WOLF_CRYPTO_CB + test_fwtpm_hmac_start_no_crypto_dev(); +#endif test_fwtpm_param_enc_session_selection(); test_fwtpm_param_enc_entity_auth(); test_fwtpm_param_enc_pcr_zero(); From 5b14651f7ad23b138f32250d005ad4234b4c46af Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 08:02:18 -0800 Subject: [PATCH 107/124] Check the NV marshal results for the PCR auth record in fwTPM FWTPM_NV_Save --- src/fwtpm/fwtpm_nv.c | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index 92f7d8d6d..92a37c857 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -2697,18 +2697,28 @@ int FWTPM_NV_Save(FWTPM_CTX* ctx) } if (rc == 0) { pos = 0; - FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocatedBanks); - for (i = 0; i < IMPLEMENTATION_PCR; i++) { - FwNvMarshalAuth(buf, &pos, bufSz, &ctx->pcrAuth[i]); - FwNvMarshalDigest(buf, &pos, bufSz, + rc = FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocatedBanks); + } + for (i = 0; i < IMPLEMENTATION_PCR && rc == 0; i++) { + rc = FwNvMarshalAuth(buf, &pos, bufSz, &ctx->pcrAuth[i]); + if (rc == 0) { + rc = FwNvMarshalDigest(buf, &pos, bufSz, &ctx->pcrPolicy[i]); - FwNvMarshalU16(buf, &pos, bufSz, + } + if (rc == 0) { + rc = FwNvMarshalU16(buf, &pos, bufSz, ctx->pcrPolicyAlg[i]); } - /* Appended last so an older record still parses */ - FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocPending); - FwNvMarshalU8(buf, &pos, bufSz, + } + /* Appended last so an older record still parses */ + if (rc == 0) { + rc = FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocPending); + } + if (rc == 0) { + rc = FwNvMarshalU8(buf, &pos, bufSz, ctx->pcrAllocatedBanksPending); + } + if (rc == 0) { rc = FwNvAppendEntry(ctx, FWTPM_NV_TAG_PCR_AUTH, buf, (UINT16)pos); } From 7a7ca76b57f150d20a0498d2bdfde72c06707e23 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 08:04:41 -0800 Subject: [PATCH 108/124] Free the fwTPM credential and wrap key AES and HMAC contexts only after a successful init --- src/fwtpm/fwtpm_crypto.c | 44 ++++++++++++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 569ea26df..66e391e95 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -2152,7 +2152,7 @@ int FwDeriveWrapKey(FWTPM_CTX* ctx, const FWTPM_Object* parent, int rc = TPM_RC_SUCCESS; byte proof[WC_SHA256_DIGEST_SIZE]; int useProof; - int hmacTried = 0; + int hmacInit = 0; FWTPM_DECLARE_VAR(hmac, Hmac); if (ctx == NULL || parent == NULL || name == NULL || name->size == 0 || @@ -2169,8 +2169,10 @@ int FwDeriveWrapKey(FWTPM_CTX* ctx, const FWTPM_Object* parent, TPM_ALG_SHA256, proof, sizeof(proof)); } if (rc == 0) { - hmacTried = 1; rc = wc_HmacInit(hmac, NULL, INVALID_DEVID); + if (rc == 0) { + hmacInit = 1; + } } /* AES key = HMAC-SHA256(parentPriv, label || [ehProof] || name). @@ -2215,7 +2217,7 @@ int FwDeriveWrapKey(FWTPM_CTX* ctx, const FWTPM_Object* parent, } TPM2_ForceZero(proof, sizeof(proof)); - if (hmacTried) + if (hmacInit) wc_HmacFree(hmac); FWTPM_FREE_VAR(hmac); return rc; @@ -5118,6 +5120,8 @@ TPM_RC FwCredentialWrap( byte iv[AES_BLOCK_SIZE]; FWTPM_DECLARE_VAR(aes, Aes); FWTPM_DECLARE_VAR(hmac, Hmac); + int aesInit = 0; + int hmacInit = 0; if (encCredBufSz < 2 + (int)credSz) { return TPM_RC_SIZE; @@ -5138,11 +5142,15 @@ TPM_RC FwCredentialWrap( XMEMSET(iv, 0, sizeof(iv)); rc = wc_AesInit(aes, NULL, INVALID_DEVID); - if (rc == 0) + if (rc == 0) { + aesInit = 1; rc = wc_AesSetKey(aes, symKey, (word32)symKeySz, iv, AES_ENCRYPTION); + } if (rc == 0) rc = wc_AesCfbEncrypt(aes, encCred, encCred, *encCredSz); - wc_AesFree(aes); + if (aesInit) { + wc_AesFree(aes); + } if (rc != 0) { rc = TPM_RC_FAILURE; } @@ -5150,16 +5158,20 @@ TPM_RC FwCredentialWrap( /* HMAC(hmacKey, encCred || name) */ if (rc == 0) { rc = wc_HmacInit(hmac, NULL, INVALID_DEVID); - if (rc == 0) + if (rc == 0) { + hmacInit = 1; rc = wc_HmacSetKey(hmac, FwGetWcHashType(nameAlg), hmacKey, (word32)hmacKeySz); + } if (rc == 0) rc = wc_HmacUpdate(hmac, encCred, *encCredSz); if (rc == 0) rc = wc_HmacUpdate(hmac, name, nameSz); if (rc == 0) rc = wc_HmacFinal(hmac, outerHmac); - wc_HmacFree(hmac); + if (hmacInit) { + wc_HmacFree(hmac); + } if (rc != 0) rc = TPM_RC_FAILURE; } @@ -5191,6 +5203,8 @@ TPM_RC FwCredentialUnwrap( byte iv[AES_BLOCK_SIZE]; int sizeMismatch; int hmacDiff; + int aesInit = 0; + int hmacInit = 0; FWTPM_DECLARE_VAR(aes, Aes); FWTPM_DECLARE_VAR(hmac, Hmac); FWTPM_DECLARE_BUF(decBuf, FWTPM_MAX_NV_DATA + 2); @@ -5227,16 +5241,20 @@ TPM_RC FwCredentialUnwrap( /* Verify HMAC(hmacKey, encIdentity || name) */ if (rc == 0) { rc = wc_HmacInit(hmac, NULL, INVALID_DEVID); - if (rc == 0) + if (rc == 0) { + hmacInit = 1; rc = wc_HmacSetKey(hmac, FwGetWcHashType(nameAlg), hmacKey, (word32)hmacKeySz); + } if (rc == 0) rc = wc_HmacUpdate(hmac, encIdentity, encIdentitySz); if (rc == 0) rc = wc_HmacUpdate(hmac, name, nameSz); if (rc == 0) rc = wc_HmacFinal(hmac, computedHmac); - wc_HmacFree(hmac); + if (hmacInit) { + wc_HmacFree(hmac); + } if (rc != 0) { rc = TPM_RC_FAILURE; } @@ -5261,12 +5279,16 @@ TPM_RC FwCredentialUnwrap( XMEMSET(iv, 0, sizeof(iv)); XMEMCPY(decBuf, encIdentity, encIdentitySz); rc = wc_AesInit(aes, NULL, INVALID_DEVID); - if (rc == 0) + if (rc == 0) { + aesInit = 1; rc = wc_AesSetKey(aes, symKey, (word32)symKeySz, iv, AES_ENCRYPTION); + } if (rc == 0) rc = wc_AesCfbDecrypt(aes, decBuf, decBuf, encIdentitySz); - wc_AesFree(aes); + if (aesInit) { + wc_AesFree(aes); + } if (rc != 0) rc = TPM_RC_FAILURE; } From 92c1f351e60918eaccdbb40bb889329397e3c132 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 08:10:40 -0800 Subject: [PATCH 109/124] Verify an empty HMAC from a fwTPM HMAC session instead of refusing it at parse --- src/fwtpm/fwtpm_command.c | 16 ++----- tests/fwtpm_unit_tests.c | 93 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+), 13 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index b14468dd2..f5fef94cd 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -23243,7 +23243,8 @@ static int FwAuthSlotDAUse(FWTPM_CTX* ctx, TPM_HANDLE entityH, (sess->isPasswordPolicy || sess->isAuthValuePolicy)))) { usesEntityAuth = 1; } - usesBindAuth = sess != NULL && cmdHmacSize > 0 && sess->isBound; + usesBindAuth = sess != NULL && sess->isBound && + (cmdHmacSize > 0 || sess->sessionType == TPM_SE_HMAC); if (usesEntityAuth) { if (entityH == TPM_RH_LOCKOUT) { daUse |= FW_AUTH_USES_LOCKOUT; @@ -24035,18 +24036,6 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, } } - /* HMAC sessions require a non-empty HMAC per TPM 2.0 - * Part 1 Section 19.6. Accepting hmacSize=0 would - * bypass command HMAC verification. Policy sessions - * may have empty HMAC when PolicyAuthValue/PolicyPassword - * has not been called. */ - if (rc == 0 && cmdAuths[cmdAuthCnt].sess != NULL && - cmdAuths[cmdAuthCnt].sess->sessionType == TPM_SE_HMAC && - cmdAuths[cmdAuthCnt].cmdHmacSize == 0) { - rc = TPM_RC_AUTH_FAIL; - break; - } - cmdAuthCnt++; } } @@ -24613,6 +24602,7 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, for (hj = 0; hj < cmdAuthCnt; hj++) { int isAuthSess = (hj < (int)entry->authHandleCnt); if (cmdAuths[hj].sess != NULL && (cmdAuths[hj].cmdHmacSize > 0 || + cmdAuths[hj].sess->sessionType == TPM_SE_HMAC || (!isAuthSess && cmdAuths[hj].sess->sessionKey.size > 0) || (cmdAuths[hj].sess->sessionType == TPM_SE_POLICY && (cmdAuths[hj].sess->isPasswordPolicy || diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 5c854cb02..a104da946 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -19339,6 +19339,98 @@ static void test_fwtpm_da_bound_session_locked_out(void) (void)remove(FWTPM_NV_FILE); fwtpm_pass("DA bound session while locked out:", 0); } + +/* Send cc with one HMAC session carrying an empty HMAC. The session + * authorizes handle, or audits GetRandom when handle is 0. */ +static TPM_RC DaSendEmptyHmac(FWTPM_CTX* ctx, UINT32 cc, UINT32 handle, + UINT32 sessH) +{ + int pos, authStart, rspSize = 0; + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, cc); + if (handle != 0) { + PutU32BE(gCmd + pos, handle); pos += 4; + } + authStart = pos; + pos += 4; + PutU32BE(gCmd + pos, sessH); pos += 4; + PutU16BE(gCmd + pos, 16); pos += 2; + memset(gCmd + pos, 0xAA, 16); pos += 16; + gCmd[pos++] = (byte)(TPMA_SESSION_continueSession | + (handle != 0 ? 0 : TPMA_SESSION_audit)); + PutU16BE(gCmd + pos, 0); pos += 2; + PutU32BE(gCmd + authStart, (UINT32)(pos - authStart - 4)); + if (handle == 0) { + PutU16BE(gCmd + pos, 8); pos += 2; + } + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + return GetRspRC(gRsp); +} + +/* An empty HMAC from an HMAC session verifies only against an empty HMAC + * key. Otherwise it is a failed authorization like any other HMAC: counted + * when the session is bound to a DA protected entity, and refused while the + * TPM is locked out. */ +static void test_fwtpm_da_bound_session_empty_hmac(void) +{ + FWTPM_CTX ctx; + UINT32 daKey, noDaKey, sessH; + + (void)remove(FWTPM_NV_FILE); + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(DaSetParams(&ctx, 3, 1000, 1000), TPM_RC_SUCCESS); + daKey = DaMakeEccSignKey(&ctx, 0x00040072); + AssertIntNE(daKey, 0); + noDaKey = DaMakeEccSignKey(&ctx, 0x00040472); + AssertIntNE(noDaKey, 0); + + /* Unbound and unsalted: the HMAC key is empty */ + sessH = StartSessionHelper(&ctx, TPM_SE_HMAC); + AssertIntNE(sessH, 0); + AssertIntEQ(DaSendEmptyHmac(&ctx, TPM_CC_GetRandom, 0, sessH), + TPM_RC_SUCCESS); + FlushHandle(&ctx, sessH); + + /* Bound to a noDA object: fails without being counted */ + sessH = DaStartBoundSession(&ctx, noDaKey); + AssertIntNE(sessH, 0); + AssertIntEQ(DaSendEmptyHmac(&ctx, TPM_CC_GetRandom, 0, sessH), + TPM_RC_BAD_AUTH); + AssertIntEQ((int)ctx.daFailedTries, 0); + FlushHandle(&ctx, sessH); + + /* Bound to a DA protected object: counted */ + sessH = DaStartBoundSession(&ctx, daKey); + AssertIntNE(sessH, 0); + AssertIntEQ(DaSendEmptyHmac(&ctx, TPM_CC_GetRandom, 0, sessH), + TPM_RC_AUTH_FAIL); + AssertIntEQ((int)ctx.daFailedTries, 1); + + /* Locked out: refused in every slot */ + AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_LOCKOUT); + AssertIntEQ((int)ctx.daFailedTries, 3); + AssertIntEQ(DaSendEmptyHmac(&ctx, TPM_CC_GetRandom, 0, sessH), + TPM_RC_LOCKOUT); + AssertIntEQ(DaSendEmptyHmac(&ctx, TPM_CC_Sign, noDaKey, sessH), + TPM_RC_LOCKOUT); + FlushHandle(&ctx, sessH); + + /* An unbound session is refused only for a DA protected entity */ + sessH = StartSessionHelper(&ctx, TPM_SE_HMAC); + AssertIntNE(sessH, 0); + AssertIntEQ(DaSendEmptyHmac(&ctx, TPM_CC_Sign, daKey, sessH), + TPM_RC_LOCKOUT); + AssertIntEQ(DaSendEmptyHmac(&ctx, TPM_CC_GetRandom, 0, sessH), + TPM_RC_SUCCESS); + AssertIntEQ((int)ctx.daFailedTries, 3); + + FWTPM_Cleanup(&ctx); + (void)remove(FWTPM_NV_FILE); + fwtpm_pass("DA bound session with an empty HMAC:", 0); +} #endif /* HAVE_ECC */ #endif /* !FWTPM_NO_DA */ @@ -32970,6 +33062,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_da_hmac_arms_daused(); test_fwtpm_da_bound_session_no_auth_slot(); test_fwtpm_da_bound_session_locked_out(); + test_fwtpm_da_bound_session_empty_hmac(); test_fwtpm_da_lockoutauth_failure(); test_fwtpm_da_clear_resets(); test_fwtpm_da_permanent_bits(); From 07bc7c74c23522be293f05e873e58bcdf3adf7ac Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 17:43:59 -0800 Subject: [PATCH 110/124] Store a seedValue in fwTPM objects and their private blobs and records --- src/fwtpm/fwtpm_command.c | 59 ++++++-- src/fwtpm/fwtpm_crypto.c | 55 ++++++-- src/fwtpm/fwtpm_nv.c | 11 +- tests/fwtpm_unit_tests.c | 258 +++++++++++++++++++++++++++++++++-- wolftpm/fwtpm/fwtpm.h | 1 + wolftpm/fwtpm/fwtpm_crypto.h | 11 +- 6 files changed, 356 insertions(+), 39 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index f5fef94cd..bc577896b 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -6480,6 +6480,7 @@ static TPM_RC FwSerializeObjectContext(FWTPM_CTX* ctx, FWTPM_Object* obj, *plainSz = 0; if (obj->authValue.size > sizeof(obj->authValue.buffer) || + obj->seedValue.size > sizeof(obj->seedValue.buffer) || obj->privKeySize < 0 || obj->privKeySize > (int)sizeof(obj->privKey)) { return TPM_RC_FAILURE; @@ -6507,6 +6508,9 @@ static TPM_RC FwSerializeObjectContext(FWTPM_CTX* ctx, FWTPM_Object* obj, TPM2_Packet_AppendU16(&packet, obj->qualifiedName.size); TPM2_Packet_AppendBytes(&packet, (byte*)obj->qualifiedName.name, obj->qualifiedName.size); + TPM2_Packet_AppendU16(&packet, obj->seedValue.size); + TPM2_Packet_AppendBytes(&packet, obj->seedValue.buffer, + obj->seedValue.size); TPM2_Packet_AppendU8(&packet, (UINT8)(obj->publicOnly != 0)); if (packet.overflow) { rc = TPM_RC_SIZE; @@ -6526,8 +6530,8 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, FWTPM_DECLARE_VAR(pub, TPM2B_PUBLIC); FWTPM_Object* obj = NULL; byte proof[WC_SHA256_DIGEST_SIZE]; - UINT16 pubSz, authSz = 0, privateSz = 0, qnSz = 0; - int authPos = 0, privatePos = 0, qnPos = 0, publicEnd; + UINT16 pubSz, authSz = 0, privateSz = 0, qnSz = 0, seedSz = 0; + int authPos = 0, privatePos = 0, qnPos = 0, seedPos = 0, publicEnd; int flagPos = 0; UINT32 expectedMarker; @@ -6600,10 +6604,26 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, rc = TPM_RC_INTEGRITY; } } - /* The public-only flag trails the Qualified Name; a blob saved without it - * ends there */ + /* The seedValue trails the Qualified Name; a blob saved without it ends + * there */ if (rc == 0 && qnPos + qnSz != plainSz) { - flagPos = qnPos + qnSz; + packet.pos += qnSz; + if (packet.pos + 2 > plainSz) { + rc = TPM_RC_INTEGRITY; + } + else { + TPM2_Packet_ParseU16(&packet, &seedSz); + seedPos = packet.pos; + if (seedSz > sizeof(((FWTPM_Object*)0)->seedValue.buffer) || + seedPos + seedSz > plainSz) { + rc = TPM_RC_INTEGRITY; + } + } + } + /* The public-only flag trails the seedValue; a blob saved without it + * ends there */ + if (rc == 0 && seedPos != 0 && seedPos + seedSz != plainSz) { + flagPos = seedPos + seedSz; if (flagPos + 1 != plainSz) { rc = TPM_RC_INTEGRITY; } @@ -6623,6 +6643,8 @@ static TPM_RC FwRestoreObjectContext(FWTPM_CTX* ctx, byte* plain, XMEMCPY(obj->privKey, plain + privatePos, privateSz); obj->qualifiedName.size = qnSz; XMEMCPY(obj->qualifiedName.name, plain + qnPos, qnSz); + obj->seedValue.size = seedSz; + XMEMCPY(obj->seedValue.buffer, plain + seedPos, seedSz); /* Without the flag only an object that has no private data is taken * to be public-only */ obj->publicOnly = (flagPos != 0) ? (plain[flagPos] != 0) : @@ -8249,6 +8271,7 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_DECLARE_VAR(outPrivate, TPM2B_PRIVATE); FWTPM_DECLARE_BUF(privKeyDer, FWTPM_MAX_PRIVKEY_DER); int privKeyDerSz = 0; + TPM2B_DIGEST seedValue; int paramSzPos = 0, paramStart = 0; FWTPM_DECLARE_VAR(outPub, TPM2B_PUBLIC); int cdMarkPos = 0; @@ -8266,6 +8289,7 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Zero stack-resident locals (heap-allocated TPM2B vars are pre-zeroed * via FWTPM_CALLOC_VAR/BUF above). */ XMEMSET(&userAuth, 0, sizeof(userAuth)); + XMEMSET(&seedValue, 0, sizeof(seedValue)); if (cmdSize < TPM2_HEADER_SIZE + 4) { rc = TPM_RC_COMMAND_SIZE; @@ -8576,7 +8600,7 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { rc = FwWrapPrivate(ctx, parent, &ctx->rng, &childName, inPublic->publicArea.type, &userAuth, - privKeyDer, privKeyDerSz, outPrivate); + privKeyDer, privKeyDerSz, &seedValue, outPrivate); } } @@ -8641,6 +8665,7 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_ForceZero(sensData, FWTPM_SIZEOF_BUF(sensData, FWTPM_MAX_DATA_BUF)); FWTPM_FREE_BUF(sensData); /* outPrivate carries an HMAC-protected blob; XFREE alone is sufficient. */ + TPM2_ForceZero(&seedValue, sizeof(seedValue)); TPM2_ForceZero(privKeyDer, FWTPM_MAX_PRIVKEY_DER); FWTPM_FREE_BUF(privKeyDer); FWTPM_FREE_VAR(inPublic); @@ -8737,7 +8762,8 @@ static TPM_RC FwCmd_ObjectChangeAuth(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Re-wrap the private key; the loaded object keeps its current auth. */ if (rc == 0) { rc = FwWrapPrivate(ctx, parent, &ctx->rng, &obj->name, obj->pub.type, - &newAuth, obj->privKey, obj->privKeySize, &outPrivate); + &newAuth, obj->privKey, obj->privKeySize, &obj->seedValue, + &outPrivate); if (rc != 0) { rc = TPM_RC_FAILURE; } @@ -8863,7 +8889,7 @@ static TPM_RC FwCmd_Load(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { rc = FwUnwrapPrivate(ctx, parent, &obj->name, &inPrivate, &sensitiveType, &obj->authValue, - obj->privKey, &obj->privKeySize); + obj->privKey, &obj->privKeySize, &obj->seedValue); #ifdef DEBUG_WOLFTPM if (rc != TPM_RC_SUCCESS) { printf("fwTPM: Load unwrap failed rc=%d (0x%x)\n", rc, rc); @@ -9329,8 +9355,7 @@ static TPM_RC FwRcAddIndex(TPM_RC rc, TPM_RC index) /* Marshal the TPM2B_SENSITIVE of an object for duplication: one prime for * RSA, the private scalar for ECC and the stored key octets for the other - * types. The authValue is zero padded to the nameAlg digest size. This TPM - * keeps no seedValue. */ + * types. The authValue is zero padded to the nameAlg digest size. */ static TPM_RC FwDupMarshalSensitive(const FWTPM_Object* obj, byte* buf, int bufSz, int* outSz) { @@ -9403,7 +9428,7 @@ static TPM_RC FwDupMarshalSensitive(const FWTPM_Object* obj, byte* buf, if (rc == 0) { sz = FwMarshalSensitiveStd(buf, bufSz, obj->pub.type, &auth, - sens, sensSz); + &obj->seedValue, sens, sensSz); if (sz < 0) { rc = TPM_RC_SIZE; } @@ -9686,6 +9711,7 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, int innerOff = 0; FWTPM_DECLARE_BUF(primeBuf, FWTPM_MAX_DER_SIG_BUF); TPM2B_AUTH importedAuth; + TPM2B_DIGEST importedSeed; TPM_RC rc = TPM_RC_SUCCESS; FWTPM_ALLOC_BUF(dupBuf, FWTPM_MAX_PRIVKEY_DER + 256); @@ -9696,6 +9722,7 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_ALLOC_BUF(primeBuf, FWTPM_MAX_DER_SIG_BUF); FWTPM_CALLOC_VAR(objectPublic, TPM2B_PUBLIC); FWTPM_CALLOC_VAR(outPrivate, TPM2B_PRIVATE); + XMEMSET(&importedSeed, 0, sizeof(importedSeed)); if (cmdSize < TPM2_HEADER_SIZE + 4) { rc = TPM_RC_COMMAND_SIZE; @@ -10012,7 +10039,8 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = FwComputePublicName(&objectPublic->publicArea, &childName); if (rc == 0) { rc = FwWrapPrivate(ctx, parent, &ctx->rng, &childName, sensType, - &importedAuth, privKeyDer, privKeyDerSz, outPrivate); + &importedAuth, privKeyDer, privKeyDerSz, &importedSeed, + outPrivate); } } @@ -10029,6 +10057,7 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_ForceZero(hmacKeyBuf, sizeof(hmacKeyBuf)); TPM2_ForceZero(encKeyBuf, sizeof(encKeyBuf)); TPM2_ForceZero(&importedAuth, sizeof(importedAuth)); + TPM2_ForceZero(&importedSeed, sizeof(importedSeed)); FWTPM_FREE_BUF(dupBuf); FWTPM_FREE_BUF(symSeedBuf); TPM2_ForceZero(privKeyDer, FWTPM_MAX_PRIVKEY_DER); @@ -10560,6 +10589,7 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, int paramSzPos = 0; int paramStart = 0; FWTPM_DECLARE_VAR(outPub, TPM2B_PUBLIC); + TPM2B_DIGEST seedValue; FWTPM_CALLOC_BUF(privKeyDer, FWTPM_MAX_PRIVKEY_DER); FWTPM_CALLOC_BUF(sensData, FWTPM_MAX_DATA_BUF); @@ -10567,6 +10597,7 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_CALLOC_VAR(outPrivate, TPM2B_PRIVATE); FWTPM_CALLOC_VAR(outPub, TPM2B_PUBLIC); XMEMSET(&userAuth, 0, sizeof(userAuth)); + XMEMSET(&seedValue, 0, sizeof(seedValue)); (void)ret; @@ -10827,7 +10858,7 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { rc = FwWrapPrivate(ctx, parent, &ctx->rng, &childName, inPublic->publicArea.type, &userAuth, - privKeyDer, privKeyDerSz, outPrivate); + privKeyDer, privKeyDerSz, &seedValue, outPrivate); } } @@ -10844,6 +10875,7 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, XMEMCPY(obj->privKey, privKeyDer, (size_t)privKeyDerSz); obj->privKeySize = privKeyDerSz; XMEMCPY(&obj->authValue, &userAuth, sizeof(TPM2B_AUTH)); + XMEMCPY(&obj->seedValue, &seedValue, sizeof(TPM2B_DIGEST)); obj->hierarchy = parent->hierarchy; rc = FwComputeObjectName(obj); @@ -10886,6 +10918,7 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, FWTPM_FREE_BUF(sensData); /* outPrivate is the wrapped (HMAC-protected) private blob, not raw key * material — XFREE alone is sufficient. */ + TPM2_ForceZero(&seedValue, sizeof(seedValue)); TPM2_ForceZero(privKeyDer, FWTPM_MAX_PRIVKEY_DER); FWTPM_FREE_BUF(privKeyDer); FWTPM_FREE_VAR(inPublic); diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 66e391e95..b779dd153 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -2223,10 +2223,13 @@ int FwDeriveWrapKey(FWTPM_CTX* ctx, const FWTPM_Object* parent, return rc; } -/* Marshal inner sensitive: type(2) + auth(2+N) + der(2+N) */ +/* Marshal inner sensitive: type(2) + auth(2+N) + der(2+N) + seedValue(2+N). + * The seedValue trails the historic layout so a blob written without it + * still unmarshals. */ int FwMarshalSensitive(byte* buf, int bufSz, UINT16 sensitiveType, const TPM2B_AUTH* auth, - const byte* privKeyDer, int privKeyDerSz) + const byte* privKeyDer, int privKeyDerSz, + const TPM2B_DIGEST* seedValue) { int pos = 0; if (pos + 2 > bufSz) @@ -2250,6 +2253,16 @@ int FwMarshalSensitive(byte* buf, int bufSz, XMEMCPY(buf + pos, privKeyDer, privKeyDerSz); pos += privKeyDerSz; + if (seedValue->size > sizeof(seedValue->buffer) || + pos + 2 + seedValue->size > bufSz) + return -1; + FwStoreU16BE(buf + pos, seedValue->size); + pos += 2; + if (seedValue->size > 0) { + XMEMCPY(buf + pos, seedValue->buffer, seedValue->size); + pos += seedValue->size; + } + return pos; } @@ -2260,6 +2273,7 @@ int FwMarshalSensitive(byte* buf, int bufSz, * This format matches what FwImportParseSensitive and other TPMs expect. */ int FwMarshalSensitiveStd(byte* buf, int bufSz, UINT16 sensitiveType, const TPM2B_AUTH* auth, + const TPM2B_DIGEST* seedValue, const byte* sensData, int sensDataSz) { int pos = 0; @@ -2288,11 +2302,16 @@ int FwMarshalSensitiveStd(byte* buf, int bufSz, pos += auth->size; } - /* seedValue (TPM2B) - empty for non-derived keys */ - if (pos + 2 > bufSz) + /* seedValue (TPM2B) */ + if (seedValue->size > sizeof(seedValue->buffer) || + pos + 2 + seedValue->size > bufSz) return -1; - buf[pos++] = 0; - buf[pos++] = 0; + FwStoreU16BE(buf + pos, seedValue->size); + pos += 2; + if (seedValue->size > 0) { + XMEMCPY(buf + pos, seedValue->buffer, seedValue->size); + pos += seedValue->size; + } /* sensitive data (TPM2B) - raw sensitive component */ if (pos + 2 + sensDataSz > bufSz) @@ -2312,7 +2331,8 @@ int FwMarshalSensitiveStd(byte* buf, int bufSz, /* Unmarshal inner sensitive */ int FwUnmarshalSensitive(const byte* buf, int bufSz, UINT16* sensitiveType, TPM2B_AUTH* auth, - byte* privKeyDer, int* privKeyDerSz) + byte* privKeyDer, int* privKeyDerSz, + TPM2B_DIGEST* seedValue) { int pos = 0; UINT16 sz; @@ -2347,6 +2367,18 @@ int FwUnmarshalSensitive(const byte* buf, int bufSz, *privKeyDerSz = (int)sz; pos += sz; + /* Optional trailing seedValue */ + seedValue->size = 0; + if (pos + 2 <= bufSz) { + sz = FwLoadU16BE(buf + pos); + pos += 2; + if (sz > sizeof(seedValue->buffer) || pos + sz > bufSz) + return -1; + seedValue->size = sz; + XMEMCPY(seedValue->buffer, buf + pos, sz); + pos += sz; + } + return pos; } @@ -2359,6 +2391,7 @@ int FwWrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, WC_RNG* rng, const TPM2B_NAME* name, UINT16 sensitiveType, const TPM2B_AUTH* auth, const byte* privKeyDer, int privKeyDerSz, + const TPM2B_DIGEST* seedValue, TPM2B_PRIVATE* outPriv) { int rc = TPM_RC_SUCCESS; @@ -2381,7 +2414,7 @@ int FwWrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, WC_RNG* rng, if (rc == 0) { sensSz = FwMarshalSensitive(sensBuf, (int)(FWTPM_MAX_PRIVKEY_DER + 128), - sensitiveType, auth, privKeyDer, privKeyDerSz); + sensitiveType, auth, privKeyDer, privKeyDerSz, seedValue); if (sensSz < 0) { rc = TPM_RC_FAILURE; } @@ -2477,7 +2510,8 @@ int FwUnwrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, const TPM2B_NAME* name, const TPM2B_PRIVATE* inPriv, UINT16* sensitiveType, TPM2B_AUTH* auth, - byte* privKeyDer, int* privKeyDerSz) + byte* privKeyDer, int* privKeyDerSz, + TPM2B_DIGEST* seedValue) { int rc = TPM_RC_SUCCESS; byte aesKey[FWTPM_MAX_SYM_KEY_SIZE], aesIV[AES_BLOCK_SIZE]; @@ -2575,7 +2609,8 @@ int FwUnwrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, /* Unmarshal sensitive */ if (rc == 0) { if (FwUnmarshalSensitive(decBuf, encSensSize, - sensitiveType, auth, privKeyDer, privKeyDerSz) < 0) { + sensitiveType, auth, privKeyDer, privKeyDerSz, + seedValue) < 0) { rc = TPM_RC_FAILURE; } } diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index 92a37c857..16da1f1fd 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -676,6 +676,9 @@ static int FwNvMarshalObject(byte* buf, word32* pos, word32 maxSz, if (rc == 0) { rc = FwNvMarshalName(buf, pos, maxSz, &obj->qualifiedName); } + if (rc == 0) { + rc = FwNvMarshalDigest(buf, pos, maxSz, &obj->seedValue); + } if (rc == 0) { rc = FwNvMarshalU8(buf, pos, maxSz, (UINT8)(obj->publicOnly != 0)); } @@ -739,6 +742,10 @@ static int FwNvUnmarshalObject(const byte* buf, word32* pos, word32 maxSz, else if (rc == 0) { obj->qualifiedName = obj->name; } + /* Optional trailing seedValue, empty in a record written without it */ + if (rc == 0 && *pos + 2 <= maxSz) { + rc = FwNvUnmarshalDigest(buf, pos, maxSz, &obj->seedValue); + } /* Optional trailing public-only flag. A record written without it holds * a public-only object when it has no private data. */ if (rc == 0 && *pos + 1 <= maxSz) { @@ -2884,7 +2891,7 @@ int FWTPM_NV_Save(FWTPM_CTX* ctx) pos = 0; needed = 4 + FWTPM_NV_PUBAREA_EST + FWTPM_NV_NAME_EST + 2 + ctx->persistent[i].privKeySize + FWTPM_NV_AUTH_EST + - 2 + FWTPM_NV_NAME_EST + 1; + 2 + FWTPM_NV_NAME_EST + FWTPM_NV_AUTH_EST + 1; if (needed > bufSz) { byte* newBuf; newBuf = (byte*)XMALLOC(needed, NULL, @@ -3412,7 +3419,7 @@ int FWTPM_NV_SavePersistent(FWTPM_CTX* ctx, int slot) bufSz = 4 + FWTPM_NV_PUBAREA_EST + 2 + FWTPM_NV_NAME_EST + 2 + obj->privKeySize + 2 + FWTPM_NV_AUTH_EST + - 2 + FWTPM_NV_NAME_EST + 1; + 2 + FWTPM_NV_NAME_EST + FWTPM_NV_AUTH_EST + 1; buf = (byte*)XMALLOC(bufSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (buf == NULL) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index a104da946..ac6dc9277 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -675,6 +675,7 @@ static void test_fwtpm_crypto_alloc_failure(void) FWTPM_Object parent; TPM2B_NAME name; TPM2B_AUTH auth; + TPM2B_DIGEST seedValue; TPM2B_PRIVATE privateBlob; UINT16 sensitiveType = 0; byte aesKey[WC_SHA256_DIGEST_SIZE]; @@ -737,6 +738,7 @@ static void test_fwtpm_crypto_alloc_failure(void) memset(&parent, 0, sizeof(parent)); memset(&name, 0, sizeof(name)); memset(&auth, 0, sizeof(auth)); + memset(&seedValue, 0, sizeof(seedValue)); memset(&privateBlob, 0, sizeof(privateBlob)); parent.hierarchy = TPM_RH_OWNER; parent.privKeySize = 1; @@ -747,7 +749,7 @@ static void test_fwtpm_crypto_alloc_failure(void) fwtpm_test_fail_next_alloc(); rc = FwWrapPrivate(&ctx, &parent, NULL, &name, TPM_ALG_RSA, &auth, - der, 0, &privateBlob); + der, 0, &seedValue, &privateBlob); AssertIntEQ(rc, TPM_RC_MEMORY); memset(&privateBlob, 0, sizeof(privateBlob)); @@ -755,7 +757,7 @@ static void test_fwtpm_crypto_alloc_failure(void) PutU16BE(privateBlob.buffer, WC_SHA256_DIGEST_SIZE); fwtpm_test_fail_next_alloc(); rc = FwUnwrapPrivate(&ctx, &parent, &name, &privateBlob, - &sensitiveType, &auth, der, &derSz); + &sensitiveType, &auth, der, &derSz, &seedValue); AssertIntEQ(rc, TPM_RC_MEMORY); memset(&ctx, 0, sizeof(ctx)); @@ -20045,6 +20047,133 @@ static void test_fwtpm_rsa_credential_oaep_label(void) } #endif /* !NO_RSA && WOLFSSL_KEY_GEN && !FWTPM_NO_CREDENTIAL */ +/* Wrap a private blob for an HMAC-SHA256 key under parentH as FwWrapPrivate + * does, with the seedValue when seed is not NULL and in the layout that + * predates it otherwise, and Load it. The object handle is returned. */ +static UINT32 LoadCraftedHmacKey(FWTPM_CTX* ctx, UINT32 parentH, + const byte* key, UINT16 keySz, const byte* unique, const byte* seed, + UINT16 seedSz) +{ + FWTPM_Object* parent = &ctx->objects[parentH - TRANSIENT_FIRST]; + byte pub[64]; + byte sens[160]; + byte priv[2 + WC_SHA256_DIGEST_SIZE + AES_BLOCK_SIZE + 2 + sizeof(sens)]; + byte aesKey[FWTPM_MAX_SYM_KEY_SIZE]; + byte macKey[WC_SHA256_DIGEST_SIZE]; + byte iv[AES_BLOCK_SIZE]; + TPM2B_NAME name; + Aes aes; + Hmac hmac; + int pubSz = 0, sensSz = 0, pos, rspSize = 0; + + PutU16BE(pub + pubSz, TPM_ALG_KEYEDHASH); pubSz += 2; + PutU16BE(pub + pubSz, TPM_ALG_SHA256); pubSz += 2; + PutU32BE(pub + pubSz, 0x00040040); pubSz += 4; /* userWithAuth | sign */ + PutU16BE(pub + pubSz, 0); pubSz += 2; /* authPolicy */ + PutU16BE(pub + pubSz, TPM_ALG_HMAC); pubSz += 2; + PutU16BE(pub + pubSz, TPM_ALG_SHA256); pubSz += 2; + PutU16BE(pub + pubSz, WC_SHA256_DIGEST_SIZE); pubSz += 2; + memcpy(pub + pubSz, unique, WC_SHA256_DIGEST_SIZE); + pubSz += WC_SHA256_DIGEST_SIZE; + memset(&name, 0, sizeof(name)); + name.size = 2 + WC_SHA256_DIGEST_SIZE; + PutU16BE(name.name, TPM_ALG_SHA256); + AssertIntEQ(wc_Sha256Hash(pub, (word32)pubSz, name.name + 2), 0); + + PutU16BE(sens + sensSz, TPM_ALG_KEYEDHASH); sensSz += 2; + PutU16BE(sens + sensSz, 0); sensSz += 2; /* authValue */ + PutU16BE(sens + sensSz, keySz); sensSz += 2; + memcpy(sens + sensSz, key, keySz); sensSz += keySz; + if (seed != NULL) { + PutU16BE(sens + sensSz, seedSz); sensSz += 2; + memcpy(sens + sensSz, seed, seedSz); sensSz += seedSz; + } + + AssertIntEQ(FwDeriveWrapKey(ctx, parent, &name, aesKey, macKey), 0); + memset(iv, 0x3C, sizeof(iv)); + pos = 0; + PutU16BE(priv + pos, WC_SHA256_DIGEST_SIZE); pos += 2; + pos += WC_SHA256_DIGEST_SIZE; + memcpy(priv + pos, iv, sizeof(iv)); pos += (int)sizeof(iv); + PutU16BE(priv + pos, (UINT16)sensSz); pos += 2; + AssertIntEQ(wc_AesInit(&aes, NULL, INVALID_DEVID), 0); + AssertIntEQ(wc_AesSetKey(&aes, aesKey, 32, iv, AES_ENCRYPTION), 0); + AssertIntEQ(wc_AesCfbEncrypt(&aes, priv + pos, sens, (word32)sensSz), 0); + wc_AesFree(&aes); + AssertIntEQ(wc_HmacInit(&hmac, NULL, INVALID_DEVID), 0); + AssertIntEQ(wc_HmacSetKey(&hmac, WC_SHA256, macKey, sizeof(macKey)), 0); + AssertIntEQ(wc_HmacUpdate(&hmac, iv, sizeof(iv)), 0); + AssertIntEQ(wc_HmacUpdate(&hmac, priv + pos, (word32)sensSz), 0); + AssertIntEQ(wc_HmacFinal(&hmac, priv + 2), 0); + wc_HmacFree(&hmac); + sensSz += pos; + + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Load); + PutU32BE(gCmd + pos, parentH); pos += 4; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU16BE(gCmd + pos, (UINT16)sensSz); pos += 2; + memcpy(gCmd + pos, priv, sensSz); pos += sensSz; + PutU16BE(gCmd + pos, (UINT16)pubSz); pos += 2; + memcpy(gCmd + pos, pub, pubSz); pos += pubSz; + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + return GetU32BE(gRsp + TPM2_HEADER_SIZE); +} + +/* A private blob written before the seedValue was kept still loads, with an + * empty seedValue and the unique it was created with; a blob that carries a + * seedValue loads with it. */ +static void test_fwtpm_load_private_seed_value(void) +{ + FWTPM_CTX ctx; + UINT32 parentH, keyH; + FWTPM_Object* obj; + byte key[20]; + byte seed[WC_SHA256_DIGEST_SIZE]; + byte hashSrc[sizeof(seed) + sizeof(key)]; + byte unique[WC_SHA256_DIGEST_SIZE]; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); +#ifdef HAVE_ECC + parentH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); +#else + parentH = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); +#endif + AssertIntNE(parentH, 0); + memset(key, 0x47, sizeof(key)); + memset(seed, 0x9A, sizeof(seed)); + + AssertIntEQ(wc_Sha256Hash(key, (word32)sizeof(key), unique), 0); + keyH = LoadCraftedHmacKey(&ctx, parentH, key, sizeof(key), unique, NULL, + 0); + obj = &ctx.objects[keyH - TRANSIENT_FIRST]; + AssertIntEQ(obj->seedValue.size, 0); + AssertIntEQ(obj->privKeySize, (int)sizeof(key)); + AssertIntEQ(memcmp(obj->privKey, key, sizeof(key)), 0); + AssertIntEQ(obj->pub.unique.keyedHash.size, sizeof(unique)); + AssertIntEQ(memcmp(obj->pub.unique.keyedHash.buffer, unique, + sizeof(unique)), 0); + FlushHandle(&ctx, keyH); + + memcpy(hashSrc, seed, sizeof(seed)); + memcpy(hashSrc + sizeof(seed), key, sizeof(key)); + AssertIntEQ(wc_Sha256Hash(hashSrc, (word32)sizeof(hashSrc), unique), 0); + keyH = LoadCraftedHmacKey(&ctx, parentH, key, sizeof(key), unique, seed, + sizeof(seed)); + obj = &ctx.objects[keyH - TRANSIENT_FIRST]; + AssertIntEQ(obj->seedValue.size, sizeof(seed)); + AssertIntEQ(memcmp(obj->seedValue.buffer, seed, sizeof(seed)), 0); + AssertIntEQ(obj->privKeySize, (int)sizeof(key)); + AssertIntEQ(memcmp(obj->privKey, key, sizeof(key)), 0); + FlushHandle(&ctx, keyH); + + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Private blob seedValue:", 0); +} + #if !defined(FWTPM_NO_KEY_MIGRATION) && !defined(FWTPM_NO_POLICY) static TPM_RC SendDuplicateCmd(FWTPM_CTX* ctx, UINT32 objH, UINT32 newParentH, UINT32 sessH, UINT16 symAlg) @@ -23576,6 +23705,83 @@ static void test_fwtpm_context_legacy_hierarchy(void) FWTPM_Cleanup(&ctx); fwtpm_pass("ContextLoad legacy hierarchy object:", 0); } + +/* A saved object context carries the seedValue, and one saved before the + * seedValue was kept loads with an empty one. */ +static void test_fwtpm_context_object_seed_value(void) +{ + FWTPM_CTX ctx; + int rspSize = 0, ctxSz, pos, i, plainSz = 0, wrappedSz = 0; + const int wrapOff = 8 + 4 + 4 + 2 + 4 + 4; + UINT32 keyH, loadedH; + UINT64 seq; + byte savedObj[MAX_CONTEXT_SIZE]; + byte plain[MAX_CONTEXT_SIZE]; + byte seed[WC_SHA256_DIGEST_SIZE]; + FWTPM_Object* obj; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); +#ifdef HAVE_ECC + keyH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); +#else + keyH = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); +#endif + AssertIntNE(keyH, 0); + memset(seed, 0x6D, sizeof(seed)); + obj = &ctx.objects[keyH - TRANSIENT_FIRST]; + obj->seedValue.size = sizeof(seed); + memcpy(obj->seedValue.buffer, seed, sizeof(seed)); + + BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 14, TPM_CC_ContextSave); + PutU32BE(gCmd + 10, keyH); + FWTPM_ProcessCommand(&ctx, gCmd, 14, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + ctxSz = rspSize - TPM2_HEADER_SIZE; + AssertIntGT(ctxSz, wrapOff); + memcpy(savedObj, gRsp + TPM2_HEADER_SIZE, ctxSz); + FlushHandle(&ctx, keyH); + + for (i = 0; i < 2; i++) { + if (i == 1) { + /* Take the trailing seedValue and public-only flag off the + * protected area */ + seq = ((UINT64)GetU32BE(savedObj) << 32) | GetU32BE(savedObj + 4); + AssertIntEQ(FwUnwrapContextBlob(&ctx, seq, FWTPM_CTX_TYPE_OBJECT, + savedObj + wrapOff, ctxSz - wrapOff, plain, + (int)sizeof(plain), &plainSz), 0); + AssertIntGT(plainSz, 2 + (int)sizeof(seed) + 1); + plainSz -= 2 + (int)sizeof(seed) + 1; + AssertIntEQ(GetU16BE(plain + plainSz), sizeof(seed)); + AssertIntEQ(FwWrapContextBlob(&ctx, seq, FWTPM_CTX_TYPE_OBJECT, + plain, plainSz, savedObj + wrapOff, + (int)sizeof(savedObj) - wrapOff, &wrappedSz), 0); + PutU16BE(savedObj + 16, (UINT16)(8 + wrappedSz)); + ctxSz = wrapOff + wrappedSz; + } + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_ContextLoad); + memcpy(gCmd + pos, savedObj, ctxSz); pos += ctxSz; + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + loadedH = GetU32BE(gRsp + TPM2_HEADER_SIZE); + obj = &ctx.objects[loadedH - TRANSIENT_FIRST]; + if (i == 0) { + AssertIntEQ(obj->seedValue.size, sizeof(seed)); + AssertIntEQ(memcmp(obj->seedValue.buffer, seed, sizeof(seed)), 0); + } + else { + AssertIntEQ(obj->seedValue.size, 0); + } + AssertIntGT(obj->privKeySize, 0); + FlushHandle(&ctx, loadedH); + } + + wc_ForceZero(plain, sizeof(plain)); + FWTPM_Cleanup(&ctx); + fwtpm_pass("ContextLoad object seedValue:", 0); +} #endif /* !FWTPM_NO_CONTEXT */ #if !defined(FWTPM_NO_CONTEXT) && !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) @@ -31709,14 +31915,16 @@ static void test_fwtpm_qualified_name_certify(void) #endif /* !FWTPM_NO_ATTESTATION */ #ifndef FWTPM_NO_NV -/* A persistent object keeps its Qualified Name across a restart, and a - * record written without one loads with the Name in its place. */ +/* A persistent object keeps its Qualified Name and seedValue across a + * restart. A record written without the seedValue loads with an empty one, + * and one written without the Qualified Name with the Name in its place. */ static void test_fwtpm_qualified_name_persistent(void) { FWTPM_CTX ctx; const UINT32 persistH = PERSISTENT_FIRST + 0x20; UINT32 primaryH, childH, grandH; TPM2B_NAME name, qn, primaryQn, childQn; + TPM2B_DIGEST seedValue; byte owner[4]; byte hdr[4]; byte record[1024]; @@ -31736,6 +31944,12 @@ static void test_fwtpm_qualified_name_persistent(void) &childQn); AssertIntEQ(SendEvictControl(&ctx, TPM_RH_OWNER, childH, persistH), TPM_RC_SUCCESS); + memset(&seedValue, 0, sizeof(seedValue)); + for (i = 0; i < FWTPM_MAX_PERSISTENT; i++) { + if (ctx.persistent[i].used && ctx.persistent[i].handle == persistH) { + seedValue = ctx.persistent[i].seedValue; + } + } FlushHandle(&ctx, childH); FlushHandle(&ctx, primaryH); @@ -31753,11 +31967,16 @@ static void test_fwtpm_qualified_name_persistent(void) } off += len; } - AssertIntGT(recordSz, 2 + childQn.size + 1); + AssertIntGT(recordSz, 2 + childQn.size + 2 + seedValue.size + 1); AssertIntEQ(record[0] | (record[1] << 8) | (record[2] << 16) | ((UINT32)record[3] << 24), persistH); - /* the Qualified Name and the public-only flag end the record */ - off = (word32)(recordSz - 1 - childQn.size - 2); + /* the Qualified Name, the seedValue and the public-only flag end the + * record */ + off = (word32)(recordSz - 1 - seedValue.size - 2); + AssertIntEQ(record[off] | (record[off + 1] << 8), seedValue.size); + AssertIntEQ(memcmp(record + off + 2, seedValue.buffer, seedValue.size), + 0); + off -= (word32)(childQn.size + 2); AssertIntEQ(record[off] | (record[off + 1] << 8), childQn.size); AssertIntEQ(memcmp(record + off + 2, childQn.name, childQn.size), 0); @@ -31775,13 +31994,20 @@ static void test_fwtpm_qualified_name_persistent(void) TPM_RC_SUCCESS); FWTPM_Cleanup(&ctx); - /* The record as written, then without its trailing Qualified Name and - * public-only flag */ - for (i = 0; i < 2; i++) { + /* The record as written, then without its trailing seedValue and + * public-only flag, then without the Qualified Name either */ + for (i = 0; i < 3; i++) { int slot; + UINT16 sz = recordSz; + if (i == 1) { + sz = (UINT16)(off + 2 + childQn.size); + } + else if (i == 2) { + sz = (UINT16)off; + } AssertIntEQ(NvLoadCraftedEntry(&ctx, FWTPM_NV_TAG_PERSISTENT, record, - (UINT16)((i == 0) ? recordSz : off)), TPM_RC_SUCCESS); + sz), TPM_RC_SUCCESS); found = 0; for (slot = 0; slot < FWTPM_MAX_PERSISTENT; slot++) { FWTPM_Object* obj = &ctx.persistent[slot]; @@ -31794,6 +32020,14 @@ static void test_fwtpm_qualified_name_persistent(void) AssertIntEQ(obj->name.size, name.size); AssertIntEQ(memcmp(obj->name.name, name.name, name.size), 0); if (i == 0) { + AssertIntEQ(obj->seedValue.size, seedValue.size); + AssertIntEQ(memcmp(obj->seedValue.buffer, seedValue.buffer, + seedValue.size), 0); + } + else { + AssertIntEQ(obj->seedValue.size, 0); + } + if (i < 2) { AssertIntEQ(obj->qualifiedName.size, childQn.size); AssertIntEQ(memcmp(obj->qualifiedName.name, childQn.name, childQn.size), 0); @@ -32944,6 +33178,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_read_public(); test_fwtpm_loadexternal_symcipher_bad_keysize_rejected(); test_fwtpm_loadexternal_keyedhash(); + test_fwtpm_load_private_seed_value(); #if defined(HAVE_ECC) && !defined(FWTPM_NO_ECDH) test_fwtpm_ecc_unpadded_values(); #endif @@ -32982,6 +33217,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_contextload_short_blob_rejected(); test_fwtpm_context_object_roundtrip(); test_fwtpm_context_legacy_hierarchy(); + test_fwtpm_context_object_seed_value(); #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) test_fwtpm_context_rsa_max(); #endif diff --git a/wolftpm/fwtpm/fwtpm.h b/wolftpm/fwtpm/fwtpm.h index 5b3466f22..1addc75b1 100644 --- a/wolftpm/fwtpm/fwtpm.h +++ b/wolftpm/fwtpm/fwtpm.h @@ -614,6 +614,7 @@ typedef struct FWTPM_Object { int privKeySize; TPM2B_NAME name; /* Object name = nameAlg || H(publicArea) */ TPM2B_NAME qualifiedName; /* nameAlg || H(parent QN || name) */ + TPM2B_DIGEST seedValue; /* TPMT_SENSITIVE seedValue, may be empty */ int publicOnly; /* Loaded without a sensitive area */ } FWTPM_Object; diff --git a/wolftpm/fwtpm/fwtpm_crypto.h b/wolftpm/fwtpm/fwtpm_crypto.h index c319d6f8c..41bec27d6 100644 --- a/wolftpm/fwtpm/fwtpm_crypto.h +++ b/wolftpm/fwtpm/fwtpm_crypto.h @@ -250,27 +250,32 @@ int FwDeriveWrapKey(FWTPM_CTX* ctx, const FWTPM_Object* parent, int FwMarshalSensitive(byte* buf, int bufSz, UINT16 sensitiveType, const TPM2B_AUTH* auth, - const byte* privKeyDer, int privKeyDerSz); + const byte* privKeyDer, int privKeyDerSz, + const TPM2B_DIGEST* seedValue); int FwMarshalSensitiveStd(byte* buf, int bufSz, UINT16 sensitiveType, const TPM2B_AUTH* auth, + const TPM2B_DIGEST* seedValue, const byte* sensData, int sensDataSz); int FwUnmarshalSensitive(const byte* buf, int bufSz, UINT16* sensitiveType, TPM2B_AUTH* auth, - byte* privKeyDer, int* privKeyDerSz); + byte* privKeyDer, int* privKeyDerSz, + TPM2B_DIGEST* seedValue); int FwWrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, WC_RNG* rng, const TPM2B_NAME* name, UINT16 sensitiveType, const TPM2B_AUTH* auth, const byte* privKeyDer, int privKeyDerSz, + const TPM2B_DIGEST* seedValue, TPM2B_PRIVATE* outPriv); int FwUnwrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, const TPM2B_NAME* name, const TPM2B_PRIVATE* inPriv, UINT16* sensitiveType, TPM2B_AUTH* auth, - byte* privKeyDer, int* privKeyDerSz); + byte* privKeyDer, int* privKeyDerSz, + TPM2B_DIGEST* seedValue); /* --- Context blob wrap/unwrap (ContextSave/Load) --- */ From b1aa0b1253df805427565e717b801f6c486993f5 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 17:44:43 -0800 Subject: [PATCH 111/124] Keep the seedValue of an imported or externally loaded fwTPM object --- src/fwtpm/fwtpm_command.c | 39 ++++++++++++++++++++++++++++++++++++++- tests/fwtpm_unit_tests.c | 8 ++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index bc577896b..8788157c3 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -8981,6 +8981,7 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, UINT16 qSz = 0; UINT16 seedSz = 0; int seedPos = 0; + TPM2B_DIGEST seedValue; TPM2B_PUBLIC inPublic; UINT32 hierarchy = 0; FWTPM_Object* obj = NULL; @@ -9015,6 +9016,7 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, } XMEMSET(&authValue, 0, sizeof(authValue)); + XMEMSET(&seedValue, 0, sizeof(seedValue)); if (rc == 0 && inPrivSize > 0) { /* sensitiveType */ if (cmd->pos + 2 > cmdSize) { @@ -9043,7 +9045,7 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_Packet_ParseBytes(cmd, authValue.buffer, authValue.size); } } - /* seedValue (skip) */ + /* seedValue */ if (rc == 0) { if (cmd->pos + 2 > cmdSize) { rc = TPM_RC_COMMAND_SIZE; @@ -9102,6 +9104,20 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + /* seedValue (present only with inPrivate) must not exceed the object + * nameAlg digest size */ + if (rc == 0 && inPrivSize > 0) { + int digestSz = TPM2_GetHashDigestSize(inPublic.publicArea.nameAlg); + if (seedSz > sizeof(seedValue.buffer) || + (digestSz > 0 && (int)seedSz > digestSz)) { + rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1; + } + else { + seedValue.size = seedSz; + XMEMCPY(seedValue.buffer, cmd->buf + seedPos, seedSz); + } + } + /* Parse hierarchy */ if (rc == 0) { if (cmd->pos + 4 > cmdSize) { @@ -9296,6 +9312,7 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (rc == 0) { XMEMCPY(&obj->pub, &inPublic.publicArea, sizeof(TPMT_PUBLIC)); XMEMCPY(&obj->authValue, &authValue, sizeof(TPM2B_AUTH)); + XMEMCPY(&obj->seedValue, &seedValue, sizeof(TPM2B_DIGEST)); if (privKeyDerSz > 0) { XMEMCPY(obj->privKey, privKeyDer, (size_t)privKeyDerSz); } @@ -9338,6 +9355,7 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, TPM2_ForceZero(privKeyDer, FWTPM_MAX_PRIVKEY_DER); FWTPM_FREE_BUF(privKeyDer); TPM2_ForceZero(&authValue, sizeof(authValue)); + TPM2_ForceZero(&seedValue, sizeof(seedValue)); return rc; } @@ -10012,6 +10030,25 @@ static TPM_RC FwCmd_Import(FWTPM_CTX* ctx, TPM2_Packet* cmd, rc = FwRcAddIndex(rc, TPM_RC_P | TPM_RC_3); } + /* The seedValue is no larger than the nameAlg digest and, when a + * storage key has one, no smaller than half of it */ + if (rc == 0) { + if ((int)sensSeedSz > objDigestSz) { + rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_3; + } + else if (sensSeedSz != 0 && (int)sensSeedSz < objDigestSz / 2 && + (objectPublic->publicArea.objectAttributes & + TPMA_OBJECT_restricted) != 0 && + (objectPublic->publicArea.objectAttributes & + TPMA_OBJECT_decrypt) != 0) { + rc = TPM_RC_SIZE | TPM_RC_P | TPM_RC_3; + } + else { + importedSeed.size = sensSeedSz; + XMEMCPY(importedSeed.buffer, sensSeed, sensSeedSz); + } + } + /* Reconstruct private key from sensitive data */ if (rc == 0 && (objectPublic->publicArea.type == TPM_ALG_KEYEDHASH || objectPublic->publicArea.type == TPM_ALG_SYMCIPHER)) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index ac6dc9277..2fd859b6a 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -19651,6 +19651,10 @@ static void test_fwtpm_loadexternal_keyedhash(void) unique, &keyH), TPM_RC_BINDING); AssertIntEQ(SendLoadExternalHmacKey(&ctx, seed, sizeof(seed), key, 20, unique, &keyH), TPM_RC_SUCCESS); + AssertIntEQ(ctx.objects[keyH - TRANSIENT_FIRST].seedValue.size, + sizeof(seed)); + AssertIntEQ(memcmp(ctx.objects[keyH - TRANSIENT_FIRST].seedValue.buffer, + seed, sizeof(seed)), 0); #ifndef FWTPM_NO_HASH_CMDS AssertIntEQ(wc_HmacInit(&hmac, NULL, INVALID_DEVID), 0); @@ -21025,6 +21029,10 @@ static void test_fwtpm_import_known_duplicate(void) &gDup), TPM_RC_SUCCESS); keyH = DupLoad(&ctx, parentH, &gDup); DupCheckUse(&ctx, TPM_ALG_KEYEDHASH, keyH, 0); + AssertIntEQ(ctx.objects[keyH - TRANSIENT_FIRST].seedValue.size, + sizeof(seedValue)); + AssertIntEQ(memcmp(ctx.objects[keyH - TRANSIENT_FIRST].seedValue.buffer, + seedValue, sizeof(seedValue)), 0); FlushHandle(&ctx, keyH); /* The same sensitive with no wrap, then with a key that unique does From 8100312412d84a724c4d3044b8f2012a27a60013 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 17:51:22 -0800 Subject: [PATCH 112/124] Give fwTPM created objects a seedValue and compute unique from it --- src/fwtpm/fwtpm_command.c | 92 +++++++++----- src/fwtpm/fwtpm_crypto.c | 24 ++++ tests/fwtpm_unit_tests.c | 236 ++++++++++++++++++++++++++++++++--- wolftpm/fwtpm/fwtpm_crypto.h | 6 + 4 files changed, 309 insertions(+), 49 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 8788157c3..ab70d25c5 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -8255,6 +8255,51 @@ static TPM_RC FwCmd_EvictControl(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Create, Load, Sign, Verify, RSA Encrypt/Decrypt */ /* ================================================================== */ +/* Generate the seedValue of a new object as the reference implementation + * does: nameAlg digest sized for a KEYEDHASH or SYMCIPHER object and for an + * asymmetric storage key, none for any other asymmetric key. unique of a + * KEYEDHASH or SYMCIPHER object is computed from it. */ +static TPM_RC FwCreateSeedValue(FWTPM_CTX* ctx, TPMT_PUBLIC* pub, + const byte* key, int keySz, TPM2B_DIGEST* seedValue) +{ + TPM_RC rc = TPM_RC_SUCCESS; + int digestSz = TPM2_GetHashDigestSize(pub->nameAlg); + int isSym = (pub->type == TPM_ALG_KEYEDHASH || + pub->type == TPM_ALG_SYMCIPHER); + int uSz; + + seedValue->size = 0; + if (!isSym && ((pub->objectAttributes & TPMA_OBJECT_restricted) == 0 || + (pub->objectAttributes & TPMA_OBJECT_sign) != 0)) { + return TPM_RC_SUCCESS; + } + if (digestSz <= 0 || digestSz > (int)sizeof(seedValue->buffer)) { + rc = TPM_RC_HASH; + } + else if (wc_RNG_GenerateBlock(&ctx->rng, seedValue->buffer, + (word32)digestSz) != 0) { + rc = TPM_RC_FAILURE; + } + else { + seedValue->size = (UINT16)digestSz; + } + if (rc == 0 && isSym) { + /* keyedHash and sym share the layout of unique */ + uSz = FwComputeSymUnique(pub, seedValue->buffer, seedValue->size, + key, keySz, pub->unique.keyedHash.buffer); + if (uSz == (int)TPM_RC_MEMORY) { + rc = TPM_RC_MEMORY; + } + else if (uSz != digestSz) { + rc = TPM_RC_FAILURE; + } + else { + pub->unique.keyedHash.size = (UINT16)uSz; + } + } + return rc; +} + /* --- TPM2_Create (CC 0x0153) --- */ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, TPM2_Packet* rsp, UINT16 cmdTag) @@ -8540,14 +8585,6 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, privKeyDerSz = keySz; } } - - /* unique = H(key bytes) */ - if (rc == 0) { - inPublic->publicArea.unique.keyedHash.size = (UINT16) - FwComputeUniqueHash(inPublic->publicArea.nameAlg, - privKeyDer, privKeyDerSz, - inPublic->publicArea.unique.keyedHash.buffer); - } break; } case TPM_ALG_SYMCIPHER: { @@ -8577,12 +8614,6 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { privKeyDerSz = keySz; - - /* unique = H(key bytes) */ - inPublic->publicArea.unique.sym.size = (UINT16) - FwComputeUniqueHash(inPublic->publicArea.nameAlg, - privKeyDer, keySz, - inPublic->publicArea.unique.sym.buffer); } break; } @@ -8592,6 +8623,11 @@ static TPM_RC FwCmd_Create(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + if (rc == 0) { + rc = FwCreateSeedValue(ctx, &inPublic->publicArea, privKeyDer, + privKeyDerSz, &seedValue); + } + /* Wrap private key into TPM2B_PRIVATE, bound to the child's Name */ if (rc == 0) { TPM2B_NAME childName; @@ -9614,9 +9650,9 @@ static TPM_RC FwDupOuterWrap(const FWTPM_Object* newParent, const byte* seed, } /* Check an imported KEYEDHASH or SYMCIPHER sensitive area and return its - * key: the key fits the public parameters and unique is the nameAlg digest - * of seedValue || key. Objects created by this TPM have an empty - * seedValue. */ + * key: the key fits the public parameters and unique is the one its + * seedValue and key give. An object duplicated before this TPM kept a + * seedValue arrives with an empty one. */ static TPM_RC FwImportSymSensitive(const TPMT_PUBLIC* pub, UINT16 sensType, const byte* seed, UINT16 seedSz, const byte* key, UINT16 keySz, byte* privKey, int privKeyBufSz, int* privKeySz) @@ -9662,8 +9698,7 @@ static TPM_RC FwImportSymSensitive(const TPMT_PUBLIC* pub, UINT16 sensType, } } if (rc == 0) { - hRc = FwComputeHashUnique(pub->nameAlg, seed, seedSz, key, keySz, - unique); + hRc = FwComputeSymUnique(pub, seed, seedSz, key, keySz, unique); if (hRc != digestSz) { rc = (hRc == (int)TPM_RC_MEMORY) ? TPM_RC_MEMORY : TPM_RC_FAILURE; } @@ -10836,13 +10871,6 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, privKeyDerSz = keySz; } } - - if (rc == 0) { - inPublic->publicArea.unique.keyedHash.size = (UINT16) - FwComputeUniqueHash(inPublic->publicArea.nameAlg, - privKeyDer, privKeyDerSz, - inPublic->publicArea.unique.keyedHash.buffer); - } break; } case TPM_ALG_SYMCIPHER: { @@ -10873,13 +10901,6 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, privKeyDerSz = keySz; } } - - if (rc == 0) { - inPublic->publicArea.unique.sym.size = (UINT16) - FwComputeUniqueHash(inPublic->publicArea.nameAlg, - privKeyDer, keySz, - inPublic->publicArea.unique.sym.buffer); - } break; } default: @@ -10888,6 +10909,11 @@ static TPM_RC FwCmd_CreateLoaded(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + if (rc == 0) { + rc = FwCreateSeedValue(ctx, &inPublic->publicArea, privKeyDer, + privKeyDerSz, &seedValue); + } + /* Wrap private key, bound to the child's Name */ if (rc == 0) { TPM2B_NAME childName; diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index b779dd153..6e15de189 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -178,6 +178,30 @@ int FwComputeHashUnique(TPMI_ALG_HASH nameAlg, return 0; } +/* Compute unique of a KEYEDHASH or SYMCIPHER object as the reference + * implementation does: HMAC_nameAlg(seedValue, key) for a restricted + * decryption key, H_nameAlg(seedValue || key) otherwise. An object that has + * no seedValue keeps the plain digest of its key. + * Returns digest size on success, TPM_RC_MEMORY or 0 on error. */ +int FwComputeSymUnique(const TPMT_PUBLIC* pub, + const byte* seed, int seedSz, const byte* key, int keySz, + byte* uniqueOut) +{ + int hSz = TPM2_GetHashDigestSize(pub->nameAlg); + + if (seedSz > 0 && + (pub->objectAttributes & TPMA_OBJECT_restricted) != 0 && + (pub->objectAttributes & TPMA_OBJECT_decrypt) != 0) { + if (hSz <= 0 || TPM2_HmacCompute(pub->nameAlg, seed, (word32)seedSz, + key, (word32)keySz, NULL, 0, uniqueOut, NULL) != 0) { + return 0; + } + return hSz; + } + return FwComputeHashUnique(pub->nameAlg, seed, seedSz, key, keySz, + uniqueOut); +} + /* Derive a symmetric primary key from hierarchy seed via KDFa. * Per TPM 2.0 Part 1 Section 26.1: * key = KDFa(nameAlg, seed, label, hashUnique, NULL, keySz*8) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 2fd859b6a..810458dd4 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -11875,14 +11875,15 @@ static void test_fwtpm_create_symcipher_caller_key(void) /* fixedTPM | fixedParent | userWithAuth | noDA | decrypt | sign */ const UINT32 attrs = 0x00060452; FWTPM_CTX ctx; + FWTPM_Object* obj; byte key[24]; + byte hashSrc[WC_SHA256_DIGEST_SIZE + 16]; byte unique[WC_SHA256_DIGEST_SIZE]; UINT32 parentH, h; int i, pos; memset(&ctx, 0, sizeof(ctx)); memset(key, 0x3C, sizeof(key)); - AssertIntEQ(wc_Sha256Hash(key, 16, unique), 0); AssertIntEQ(fwtpm_test_startup(&ctx), 0); parentH = CreatePrimaryHelper(&ctx, FW_TEST_CREATE_ALG); AssertIntNE(parentH, 0); @@ -11902,9 +11903,21 @@ static void test_fwtpm_create_symcipher_caller_key(void) /* size, type, nameAlg, attributes, authPolicy, sym */ pos += 2 + 2 + 2 + 4 + 2 + 6; AssertIntEQ(GetU16BE(gRsp + pos), sizeof(unique)); - AssertIntEQ(memcmp(gRsp + pos + 2, unique, sizeof(unique)), 0); if (cc[i] != TPM_CC_Create) { - FlushHandle(&ctx, GetU32BE(gRsp + TPM2_HEADER_SIZE)); + /* the object holds the key, and unique covers it */ + h = GetU32BE(gRsp + TPM2_HEADER_SIZE); + obj = &ctx.objects[h - TRANSIENT_FIRST]; + AssertIntEQ(obj->privKeySize, 16); + AssertIntEQ(memcmp(obj->privKey, key, 16), 0); + AssertIntLE(obj->seedValue.size, WC_SHA256_DIGEST_SIZE); + memcpy(hashSrc, obj->seedValue.buffer, obj->seedValue.size); + memcpy(hashSrc + obj->seedValue.size, key, 16); + AssertIntEQ(wc_Sha256Hash(hashSrc, + (word32)obj->seedValue.size + 16, unique), 0); + AssertIntEQ(memcmp(gRsp + pos + 2, unique, sizeof(unique)), 0); + FlushHandle(&ctx, h); + h = (cc[i] == TPM_CC_CreatePrimary) ? + (TPM_HANDLE)TPM_RH_OWNER : parentH; } AssertIntEQ(SendSymObjectCreate(&ctx, cc[i], h, TPM_ALG_SYMCIPHER, attrs, 0, key, sizeof(key)), TPM_RC_KEY_SIZE); @@ -20322,6 +20335,8 @@ static void test_fwtpm_duplicate_needs_command_code(void) #define DUP_ATTR_HMAC 0x00040440 #define DUP_ATTR_SIGN 0x00040460 #define DUP_ATTR_SYM 0x00060460 +/* userWithAuth | noDA | sensitiveDataOrigin | restricted | decrypt */ +#define DUP_ATTR_STORAGE 0x00030460 static const byte gDupAuth[] = "dupauth"; static const byte gDupHmacKey[20] = { @@ -20350,12 +20365,15 @@ typedef struct DupBlob { } DupBlob; static DupBlob gDup; -/* A primary that may be duplicated: fixedTPM and fixedParent clear, +/* An object that may be duplicated: fixedTPM and fixedParent clear, * authValue gDupAuth and authPolicy PolicyCommandCode(TPM_CC_Duplicate). * KEYEDHASH is an HMAC-SHA256 key holding gDupHmacKey, SYMCIPHER an AES-128 - * key; ECC and RSA are signing keys. Its TPM2B_PUBLIC is copied to blob. */ -static UINT32 DupCreateObject(FWTPM_CTX* ctx, TPM_ALG_ID type, - UINT32 attributes, DupBlob* blob) + * key; ECC and RSA are signing keys, or with restricted in attributes ECC is + * a storage key. cc is TPM_CC_CreatePrimary with a hierarchy in parentH, or + * TPM_CC_CreateLoaded or TPM_CC_Create with a parent. Its TPM2B_PUBLIC is + * copied to blob; Create also copies outPrivate there and returns 0. */ +static UINT32 DupCreateObjectEx(FWTPM_CTX* ctx, UINT32 cc, UINT32 parentH, + TPM_ALG_ID type, UINT32 attributes, DupBlob* blob) { byte policyIn[WC_SHA256_DIGEST_SIZE + 8]; byte policy[WC_SHA256_DIGEST_SIZE]; @@ -20366,8 +20384,8 @@ static UINT32 DupCreateObject(FWTPM_CTX* ctx, TPM_ALG_ID type, PutU32BE(policyIn + WC_SHA256_DIGEST_SIZE + 4, TPM_CC_Duplicate); AssertIntEQ(wc_Sha256Hash(policyIn, sizeof(policyIn), policy), 0); - pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_CreatePrimary); - PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, cc); + PutU32BE(gCmd + pos, parentH); pos += 4; pos = AppendPwAuth(gCmd, pos, NULL, 0); sensStart = pos; PutU16BE(gCmd + pos, 0); pos += 2; @@ -20403,9 +20421,17 @@ static UINT32 DupCreateObject(FWTPM_CTX* ctx, TPM_ALG_ID type, PutU16BE(gCmd + pos, 0); pos += 2; /* unique */ } else if (type == TPM_ALG_ECC) { - PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* symmetric */ - PutU16BE(gCmd + pos, TPM_ALG_ECDSA); pos += 2; - PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + if ((attributes & TPMA_OBJECT_restricted) != 0) { + PutU16BE(gCmd + pos, TPM_ALG_AES); pos += 2; /* symmetric */ + PutU16BE(gCmd + pos, 128); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_CFB); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* scheme */ + } + else { + PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* symmetric */ + PutU16BE(gCmd + pos, TPM_ALG_ECDSA); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; + } PutU16BE(gCmd + pos, TPM_ECC_NIST_P256); pos += 2; PutU16BE(gCmd + pos, TPM_ALG_NULL); pos += 2; /* kdf */ PutU16BE(gCmd + pos, 0); pos += 2; /* unique.x */ @@ -20420,17 +20446,34 @@ static UINT32 DupCreateObject(FWTPM_CTX* ctx, TPM_ALG_ID type, PutU16BE(gCmd + pos, 0); pos += 2; /* unique */ } PutU16BE(gCmd + pubStart, (UINT16)(pos - pubStart - 2)); - PutU16BE(gCmd + pos, 0); pos += 2; /* outsideInfo */ - PutU32BE(gCmd + pos, 0); pos += 4; /* creationPCR */ + if (cc != TPM_CC_CreateLoaded) { + PutU16BE(gCmd + pos, 0); pos += 2; /* outsideInfo */ + PutU32BE(gCmd + pos, 0); pos += 4; /* creationPCR */ + } PutU32BE(gCmd + 2, (UINT32)pos); FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); - pos = TPM2_HEADER_SIZE + 4 + 4; + pos = TPM2_HEADER_SIZE + 4; + if (cc != TPM_CC_Create) { + pos += 4; + } + if (cc != TPM_CC_CreatePrimary) { + blob->privSz = GetU16BE(gRsp + pos); pos += 2; + AssertIntLE(blob->privSz, sizeof(blob->priv)); + memcpy(blob->priv, gRsp + pos, blob->privSz); pos += blob->privSz; + } blob->pubSz = (UINT16)(2 + GetU16BE(gRsp + pos)); AssertIntLE(blob->pubSz, sizeof(blob->pub)); memcpy(blob->pub, gRsp + pos, blob->pubSz); - return GetU32BE(gRsp + TPM2_HEADER_SIZE); + return (cc == TPM_CC_Create) ? 0 : GetU32BE(gRsp + TPM2_HEADER_SIZE); +} + +static UINT32 DupCreateObject(FWTPM_CTX* ctx, TPM_ALG_ID type, + UINT32 attributes, DupBlob* blob) +{ + return DupCreateObjectEx(ctx, TPM_CC_CreatePrimary, TPM_RH_OWNER, type, + attributes, blob); } /* Duplicate objH on a new policy session bound to TPM_CC_Duplicate and copy @@ -20717,6 +20760,166 @@ static void test_fwtpm_duplicate_import_roundtrip(void) fwtpm_pass("Duplicate/Import round trip:", 0); } +/* Duplicate objH with no wrap and check the seedValue in its + * TPM2B_SENSITIVE: seedSz octets, the ones the object holds, and for a + * KEYEDHASH or SYMCIPHER object the unique in blob->pub is + * H_nameAlg(seedValue || sensitive), or HMAC_nameAlg(seedValue, sensitive) + * when hmacUnique is set. */ +static void DupCheckSeedValue(FWTPM_CTX* ctx, TPM_ALG_ID type, UINT32 objH, + UINT16 seedSz, int hmacUnique, DupBlob* blob) +{ + FWTPM_Object* obj = &ctx->objects[objH - TRANSIENT_FIRST]; + const byte* seed; + const byte* sens; + const byte* unique = blob->pub + blob->pubSz - WC_SHA256_DIGEST_SIZE; + byte expect[WC_SHA256_DIGEST_SIZE]; + wc_HashAlg hash; + Hmac hmac; + UINT16 sensSz; + int pos = 0; + + AssertIntEQ(DupSend(ctx, objH, TPM_RH_NULL, NULL, 0, TPM_ALG_NULL, 0, + blob), TPM_RC_SUCCESS); + AssertIntEQ(blob->seedSz, 0); + AssertIntEQ(GetU16BE(blob->dup + pos), blob->dupSz - 2); pos += 2; + AssertIntEQ(GetU16BE(blob->dup + pos), type); pos += 2; + pos += 2 + GetU16BE(blob->dup + pos); /* authValue */ + AssertIntEQ(GetU16BE(blob->dup + pos), seedSz); pos += 2; + seed = blob->dup + pos; pos += seedSz; + sensSz = GetU16BE(blob->dup + pos); pos += 2; + sens = blob->dup + pos; pos += sensSz; + AssertIntEQ(pos, blob->dupSz); + + AssertIntEQ(obj->seedValue.size, seedSz); + AssertIntEQ(memcmp(obj->seedValue.buffer, seed, seedSz), 0); + if (type != TPM_ALG_KEYEDHASH && type != TPM_ALG_SYMCIPHER) { + return; + } + AssertIntEQ(seedSz, WC_SHA256_DIGEST_SIZE); + if (type == TPM_ALG_KEYEDHASH) { + AssertIntEQ(sensSz, sizeof(gDupHmacKey)); + AssertIntEQ(memcmp(sens, gDupHmacKey, sizeof(gDupHmacKey)), 0); + } + if (hmacUnique) { + AssertIntEQ(wc_HmacInit(&hmac, NULL, INVALID_DEVID), 0); + AssertIntEQ(wc_HmacSetKey(&hmac, WC_SHA256, seed, seedSz), 0); + AssertIntEQ(wc_HmacUpdate(&hmac, sens, sensSz), 0); + AssertIntEQ(wc_HmacFinal(&hmac, expect), 0); + wc_HmacFree(&hmac); + } + else { + AssertIntEQ(wc_HashInit(&hash, WC_HASH_TYPE_SHA256), 0); + AssertIntEQ(wc_HashUpdate(&hash, WC_HASH_TYPE_SHA256, seed, seedSz), + 0); + AssertIntEQ(wc_HashUpdate(&hash, WC_HASH_TYPE_SHA256, sens, sensSz), + 0); + AssertIntEQ(wc_HashFinal(&hash, WC_HASH_TYPE_SHA256, expect), 0); + wc_HashFree(&hash, WC_HASH_TYPE_SHA256); + } + AssertIntEQ(GetU16BE(unique - 2), sizeof(expect)); + AssertIntEQ(memcmp(unique, expect, sizeof(expect)), 0); +} + +/* Create and CreateLoaded give a KEYEDHASH or SYMCIPHER object and an + * asymmetric storage key a seedValue of the nameAlg digest size, any other + * asymmetric key none, and compute unique of a KEYEDHASH or SYMCIPHER + * object from it as the reference implementation does. The duplicate + * imports again with that seedValue. */ +static void test_fwtpm_create_seed_value(void) +{ + FWTPM_CTX ctx; + static const UINT32 cmds[] = { TPM_CC_CreateLoaded, TPM_CC_Create }; + UINT32 parentH, objH, newH; + byte seed[2][WC_SHA256_DIGEST_SIZE]; + int i; +#ifdef HAVE_ECC + TPM_ALG_ID parentAlg = TPM_ALG_ECC; +#else + TPM_ALG_ID parentAlg = TPM_ALG_RSA; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + parentH = CreatePrimaryHelper(&ctx, parentAlg); + AssertIntNE(parentH, 0); + + for (i = 0; i < 2; i++) { + objH = DupCreateObjectEx(&ctx, cmds[i], parentH, TPM_ALG_KEYEDHASH, + DUP_ATTR_HMAC, &gDup); + if (cmds[i] == TPM_CC_Create) { + objH = DupLoad(&ctx, parentH, &gDup); + } + DupCheckSeedValue(&ctx, TPM_ALG_KEYEDHASH, objH, + WC_SHA256_DIGEST_SIZE, 0, &gDup); + memcpy(seed[i], ctx.objects[objH - TRANSIENT_FIRST].seedValue.buffer, + sizeof(seed[i])); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, + &gDup), TPM_RC_SUCCESS); + newH = DupLoad(&ctx, parentH, &gDup); + DupCheckUse(&ctx, TPM_ALG_KEYEDHASH, newH, objH); + DupCheckSeedValue(&ctx, TPM_ALG_KEYEDHASH, newH, + WC_SHA256_DIGEST_SIZE, 0, &gDup); + AssertIntEQ(memcmp(seed[i], + ctx.objects[newH - TRANSIENT_FIRST].seedValue.buffer, + sizeof(seed[i])), 0); + FlushHandle(&ctx, newH); + FlushHandle(&ctx, objH); + +#ifndef NO_AES + objH = DupCreateObjectEx(&ctx, cmds[i], parentH, TPM_ALG_SYMCIPHER, + DUP_ATTR_SYM, &gDup); + if (cmds[i] == TPM_CC_Create) { + objH = DupLoad(&ctx, parentH, &gDup); + } + DupCheckSeedValue(&ctx, TPM_ALG_SYMCIPHER, objH, + WC_SHA256_DIGEST_SIZE, 0, &gDup); + FlushHandle(&ctx, objH); + + /* a symmetric storage key */ + objH = DupCreateObjectEx(&ctx, cmds[i], parentH, TPM_ALG_SYMCIPHER, + DUP_ATTR_STORAGE, &gDup); + if (cmds[i] == TPM_CC_Create) { + objH = DupLoad(&ctx, parentH, &gDup); + } + DupCheckSeedValue(&ctx, TPM_ALG_SYMCIPHER, objH, + WC_SHA256_DIGEST_SIZE, 1, &gDup); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, + &gDup), TPM_RC_SUCCESS); + FlushHandle(&ctx, objH); +#endif +#ifdef HAVE_ECC + objH = DupCreateObjectEx(&ctx, cmds[i], parentH, TPM_ALG_ECC, + DUP_ATTR_SIGN, &gDup); + if (cmds[i] == TPM_CC_Create) { + objH = DupLoad(&ctx, parentH, &gDup); + } + DupCheckSeedValue(&ctx, TPM_ALG_ECC, objH, 0, 0, &gDup); + FlushHandle(&ctx, objH); + + objH = DupCreateObjectEx(&ctx, cmds[i], parentH, TPM_ALG_ECC, + DUP_ATTR_STORAGE, &gDup); + if (cmds[i] == TPM_CC_Create) { + objH = DupLoad(&ctx, parentH, &gDup); + } + DupCheckSeedValue(&ctx, TPM_ALG_ECC, objH, WC_SHA256_DIGEST_SIZE, 0, + &gDup); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, + &gDup), TPM_RC_SUCCESS); + newH = DupLoad(&ctx, parentH, &gDup); + DupCheckSeedValue(&ctx, TPM_ALG_ECC, newH, WC_SHA256_DIGEST_SIZE, 0, + &gDup); + FlushHandle(&ctx, newH); + FlushHandle(&ctx, objH); +#endif + } + /* each object has a seedValue of its own */ + AssertIntNE(memcmp(seed[0], seed[1], sizeof(seed[0])), 0); + + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Create seedValue and unique:", 0); +} + /* Rewrap replaces the outer wrap only: an inner and outer wrapped duplicate * moved to a second parent imports there with the inner key. */ static void test_fwtpm_duplicate_rewrap_import(void) @@ -33204,6 +33407,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_duplicate_encrypted_needs_new_parent(); test_fwtpm_duplicate_needs_command_code(); test_fwtpm_duplicate_import_roundtrip(); + test_fwtpm_create_seed_value(); test_fwtpm_duplicate_rewrap_import(); test_fwtpm_duplicate_import_rejections(); test_fwtpm_import_known_duplicate(); diff --git a/wolftpm/fwtpm/fwtpm_crypto.h b/wolftpm/fwtpm/fwtpm_crypto.h index 41bec27d6..c5aa513c9 100644 --- a/wolftpm/fwtpm/fwtpm_crypto.h +++ b/wolftpm/fwtpm/fwtpm_crypto.h @@ -64,6 +64,12 @@ int FwComputeHashUnique(TPMI_ALG_HASH nameAlg, const byte* uniqueData, int uniqueDataSz, byte* hashOut); +/* unique of a KEYEDHASH or SYMCIPHER object from its sensitive area. Returns + * as FwComputeHashUnique does. */ +int FwComputeSymUnique(const TPMT_PUBLIC* pub, + const byte* seed, int seedSz, const byte* key, int keySz, + byte* uniqueOut); + /* Derive symmetric primary key via KDFa (KEYEDHASH / SYMCIPHER) */ TPM_RC FwDeriveSymmetricPrimaryKey(TPMI_ALG_HASH nameAlg, const byte* seed, const byte* hashUnique, int hashUniqueSz, From 22c82c50b334f1bc0620cac0253a9a3d5116eb84 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 17:53:52 -0800 Subject: [PATCH 113/124] Check unique of an external SYMCIPHER key in fwTPM LoadExternal --- src/fwtpm/fwtpm_command.c | 56 ++++++++++++++++------- tests/fwtpm_unit_tests.c | 93 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 17 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index ab70d25c5..905e579be 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -8961,16 +8961,45 @@ static TPM_RC FwCmd_Load(FWTPM_CTX* ctx, TPM2_Packet* cmd, return rc; } +/* Part 3 Sec.12.3.1 binding of an external KEYEDHASH or SYMCIPHER sensitive + * area: the seedValue has the nameAlg digest size and unique is the one the + * seedValue and key give. */ +static TPM_RC FwCheckExternalSymUnique(const TPMT_PUBLIC* pub, + const byte* seed, UINT16 seedSz, const byte* key, UINT16 keySz) +{ + TPM_RC rc = TPM_RC_SUCCESS; + int digestSz = TPM2_GetHashDigestSize(pub->nameAlg); + int hRc; + byte unique[TPM_MAX_DIGEST_SIZE]; + + if (pub->nameAlg == TPM_ALG_NULL) { + return TPM_RC_SUCCESS; + } + if (digestSz <= 0 || (int)seedSz != digestSz) { + rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1; + } + else { + hRc = FwComputeSymUnique(pub, seed, seedSz, key, keySz, unique); + if (hRc != digestSz) { + rc = (hRc == (int)TPM_RC_MEMORY) ? TPM_RC_MEMORY : TPM_RC_FAILURE; + } + else if ((int)pub->unique.keyedHash.size != digestSz || + TPM2_ConstantCompare(pub->unique.keyedHash.buffer, unique, + (word32)digestSz) != 0) { + rc = TPM_RC_BINDING; + } + } + return rc; +} + /* Part 3 Sec.12.3.1 checks on an external KEYEDHASH sensitive area: the key - * fits its scheme, and unique is the nameAlg digest of seedValue || key. */ + * fits its scheme and unique is bound to it. */ static TPM_RC FwCheckExternalKeyedHash(const TPMT_PUBLIC* pub, const byte* seed, UINT16 seedSz, const byte* key, UINT16 keySz) { TPM_RC rc = TPM_RC_SUCCESS; UINT16 scheme = pub->parameters.keyedHashDetail.scheme.scheme; - int digestSz = TPM2_GetHashDigestSize(pub->nameAlg); int maxSz = 128; - byte unique[TPM_MAX_DIGEST_SIZE]; if (scheme == TPM_ALG_HMAC) { maxSz = wc_HashGetBlockSize(FwGetWcHashType( @@ -8986,19 +9015,8 @@ static TPM_RC FwCheckExternalKeyedHash(const TPMT_PUBLIC* pub, if (rc == 0 && (maxSz <= 0 || (int)keySz > maxSz)) { rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1; } - if (rc == 0 && pub->nameAlg != TPM_ALG_NULL) { - if (digestSz <= 0 || (int)seedSz != digestSz) { - rc = TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1; - } - else if (FwComputeHashUnique(pub->nameAlg, seed, seedSz, key, keySz, - unique) != digestSz) { - rc = TPM_RC_FAILURE; - } - else if ((int)pub->unique.keyedHash.size != digestSz || - TPM2_ConstantCompare(pub->unique.keyedHash.buffer, unique, - (word32)digestSz) != 0) { - rc = TPM_RC_BINDING; - } + if (rc == 0) { + rc = FwCheckExternalSymUnique(pub, seed, seedSz, key, keySz); } return rc; } @@ -9207,7 +9225,7 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Reconstruct/store private key if private area was provided */ if (rc == 0 && inPrivSize > 0 && sensitiveType == TPM_ALG_SYMCIPHER && - qSz > 0) { + inPublic.publicArea.type == TPM_ALG_SYMCIPHER && qSz > 0) { /* For SYMCIPHER, qBuf contains the raw AES key bytes. Per Part 2 * Sec.11.1.9 a TPM2B_SYM_KEY for AES is 16, 24, or 32 bytes. * Reject any other length up front - the outer FWTPM_MAX_DER_SIG_BUF @@ -9217,6 +9235,10 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, if (qSz != 16 && qSz != 24 && qSz != 32) { rc = TPM_RC_SIZE; } + if (rc == 0) { + rc = FwCheckExternalSymUnique(&inPublic.publicArea, + cmd->buf + seedPos, seedSz, qBuf, qSz); + } if (rc == 0) { XMEMCPY(privKeyDer, qBuf, qSz); privKeyDerSz = (int)qSz; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 810458dd4..a5ef717a1 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -19543,6 +19543,98 @@ static void test_fwtpm_loadexternal_symcipher_bad_keysize_rejected(void) fwtpm_pass("LoadExternal SYMCIPHER bad keySz (SIZE):", 0); } +/* LoadExternal of an AES-128 CFB key (userWithAuth | sign | decrypt) with + * its seedValue and unique */ +static TPM_RC SendLoadExternalAesKey(FWTPM_CTX* ctx, const byte* seed, + UINT16 seedSz, const byte* key, const byte* unique, UINT32* handle) +{ + int pos, privStart, pubStart, rspSize = 0; + + pos = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 0, TPM_CC_LoadExternal); + privStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SYMCIPHER); pos += 2; /* sensitiveType */ + PutU16BE(gCmd + pos, 0); pos += 2; /* authValue */ + PutU16BE(gCmd + pos, seedSz); pos += 2; + memcpy(gCmd + pos, seed, seedSz); pos += seedSz; + PutU16BE(gCmd + pos, AES_128_KEY_SIZE); pos += 2; + memcpy(gCmd + pos, key, AES_128_KEY_SIZE); pos += AES_128_KEY_SIZE; + PutU16BE(gCmd + privStart, (UINT16)(pos - privStart - 2)); + pubStart = pos; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SYMCIPHER); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_SHA256); pos += 2; /* nameAlg */ + PutU32BE(gCmd + pos, 0x00060040); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; /* authPolicy */ + PutU16BE(gCmd + pos, TPM_ALG_AES); pos += 2; + PutU16BE(gCmd + pos, 128); pos += 2; + PutU16BE(gCmd + pos, TPM_ALG_CFB); pos += 2; + PutU16BE(gCmd + pos, WC_SHA256_DIGEST_SIZE); pos += 2; + memcpy(gCmd + pos, unique, WC_SHA256_DIGEST_SIZE); + pos += WC_SHA256_DIGEST_SIZE; + PutU16BE(gCmd + pubStart, (UINT16)(pos - pubStart - 2)); + PutU32BE(gCmd + pos, TPM_RH_NULL); pos += 4; /* hierarchy */ + PutU32BE(gCmd + 2, (UINT32)pos); + FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); + if (GetRspRC(gRsp) == TPM_RC_SUCCESS) { + *handle = GetU32BE(gRsp + TPM2_HEADER_SIZE); + } + return GetRspRC(gRsp); +} + +/* An external SYMCIPHER key loads when its seedValue has the nameAlg digest + * size and its unique is H_nameAlg(seedValue || key), with the response + * codes of the reference implementation otherwise (Part 3 Sec.12.3.1). */ +static void test_fwtpm_loadexternal_symcipher_unique(void) +{ + FWTPM_CTX ctx; + UINT32 keyH = 0; + byte seed[WC_SHA256_DIGEST_SIZE + 1]; + byte key[AES_128_KEY_SIZE]; + byte hashSrc[WC_SHA256_DIGEST_SIZE + sizeof(key)]; + byte unique[WC_SHA256_DIGEST_SIZE]; + FWTPM_Object* obj; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + memset(seed, 0x31, sizeof(seed)); + memset(key, 0x52, sizeof(key)); + memcpy(hashSrc, seed, WC_SHA256_DIGEST_SIZE); + memcpy(hashSrc + WC_SHA256_DIGEST_SIZE, key, sizeof(key)); + AssertIntEQ(wc_Sha256Hash(hashSrc, (word32)sizeof(hashSrc), unique), 0); + + /* a seedValue that is empty, short, or longer than the digest */ + AssertIntEQ(SendLoadExternalAesKey(&ctx, seed, 0, key, unique, &keyH), + TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendLoadExternalAesKey(&ctx, seed, WC_SHA256_DIGEST_SIZE - 1, + key, unique, &keyH), TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1); + AssertIntEQ(SendLoadExternalAesKey(&ctx, seed, WC_SHA256_DIGEST_SIZE + 1, + key, unique, &keyH), TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_1); + + /* a unique that the seedValue and key do not give */ + unique[0] ^= 0x01; + AssertIntEQ(SendLoadExternalAesKey(&ctx, seed, WC_SHA256_DIGEST_SIZE, + key, unique, &keyH), TPM_RC_BINDING); + unique[0] ^= 0x01; + key[0] ^= 0x01; + AssertIntEQ(SendLoadExternalAesKey(&ctx, seed, WC_SHA256_DIGEST_SIZE, + key, unique, &keyH), TPM_RC_BINDING); + key[0] ^= 0x01; + + AssertIntEQ(SendLoadExternalAesKey(&ctx, seed, WC_SHA256_DIGEST_SIZE, + key, unique, &keyH), TPM_RC_SUCCESS); + obj = &ctx.objects[keyH - TRANSIENT_FIRST]; + AssertIntEQ(obj->seedValue.size, WC_SHA256_DIGEST_SIZE); + AssertIntEQ(memcmp(obj->seedValue.buffer, seed, WC_SHA256_DIGEST_SIZE), + 0); + AssertIntEQ(obj->privKeySize, (int)sizeof(key)); + AssertIntEQ(memcmp(obj->privKey, key, sizeof(key)), 0); + + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("LoadExternal SYMCIPHER unique:", 0); +} + /* Rewrap must re-encrypt under a storage parent. A TPM_RH_NULL newParent * would serialize the unwrapped TPMT_SENSITIVE in the clear, so it must be * rejected per Part 3 Sec.23.4.2. */ @@ -33388,6 +33480,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif test_fwtpm_read_public(); test_fwtpm_loadexternal_symcipher_bad_keysize_rejected(); + test_fwtpm_loadexternal_symcipher_unique(); test_fwtpm_loadexternal_keyedhash(); test_fwtpm_load_private_seed_value(); #if defined(HAVE_ECC) && !defined(FWTPM_NO_ECDH) From 62c7376ebf40826d4d96917072ee3c592d67ae2b Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 18:02:20 -0800 Subject: [PATCH 114/124] Derive a seedValue for fwTPM primary storage keys from the hierarchy seed --- src/fwtpm/fwtpm_command.c | 33 +++++++++++++++++++++++++++++ tests/fwtpm_unit_tests.c | 44 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 905e579be..d0ca68086 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -4859,6 +4859,35 @@ static TPM_RC FwAppendCreationData(FWTPM_CTX* ctx, TPM2_Packet* rsp, return rc; } +/* Set the seedValue of an asymmetric primary storage key (see + * FwCreateSeedValue). It is derived from the hierarchy seed so that the same + * template gives the same object. */ +static TPM_RC FwPrimarySeedValue(const byte* seed, const byte* hashUnique, + int hashUniqueSz, FWTPM_Object* obj) +{ + TPM_RC rc = TPM_RC_SUCCESS; + TPMT_PUBLIC* pub = &obj->pub; + int digestSz = TPM2_GetHashDigestSize(pub->nameAlg); + + if (pub->type == TPM_ALG_KEYEDHASH || pub->type == TPM_ALG_SYMCIPHER || + (pub->objectAttributes & TPMA_OBJECT_restricted) == 0 || + (pub->objectAttributes & TPMA_OBJECT_sign) != 0) { + return TPM_RC_SUCCESS; + } + if (digestSz <= 0 || digestSz > (int)sizeof(obj->seedValue.buffer)) { + rc = TPM_RC_HASH; + } + else if (TPM2_KDFa_ex(pub->nameAlg, seed, FWTPM_SEED_SIZE, "SEEDVALUE", + hashUnique, (UINT32)hashUniqueSz, NULL, 0, + obj->seedValue.buffer, (UINT32)digestSz) != digestSz) { + rc = TPM_RC_FAILURE; + } + else { + obj->seedValue.size = (UINT16)digestSz; + } + return rc; +} + /* --- TPM2_CreatePrimary (CC 0x0131) --- */ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, int cmdSize, TPM2_Packet* rsp, UINT16 cmdTag) @@ -5336,6 +5365,10 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } + if (rc == 0) { + rc = FwPrimarySeedValue(seed, hashUnique, hashUniqueSz, obj); + } + /* Store in primary key cache */ if (rc == 0 && cached == NULL) { for (cacheIdx = 0; cacheIdx < FWTPM_MAX_PRIMARY_CACHE; cacheIdx++) { diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index a5ef717a1..9e895768a 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -21012,6 +21012,47 @@ static void test_fwtpm_create_seed_value(void) fwtpm_pass("Create seedValue and unique:", 0); } +#ifdef HAVE_ECC +/* A primary storage key gets its seedValue from the hierarchy seed: the same + * template gives the same seedValue with or without the primary cache. A + * signing key has none. */ +static void test_fwtpm_create_primary_seed_value(void) +{ + FWTPM_CTX ctx; + UINT32 objH; + FWTPM_Object* obj; + byte seed[WC_SHA256_DIGEST_SIZE]; + int pass; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + /* created, from the cache, and created again without the cache */ + for (pass = 0; pass < 3; pass++) { + if (pass == 2) { + memset(ctx.primaryCache, 0, sizeof(ctx.primaryCache)); + } + objH = DupCreateObject(&ctx, TPM_ALG_ECC, DUP_ATTR_STORAGE, &gDup); + DupCheckSeedValue(&ctx, TPM_ALG_ECC, objH, WC_SHA256_DIGEST_SIZE, 0, + &gDup); + obj = &ctx.objects[objH - TRANSIENT_FIRST]; + if (pass == 0) { + memcpy(seed, obj->seedValue.buffer, sizeof(seed)); + } + else { + AssertIntEQ(memcmp(seed, obj->seedValue.buffer, sizeof(seed)), 0); + } + FlushHandle(&ctx, objH); + } + objH = DupCreateObject(&ctx, TPM_ALG_ECC, DUP_ATTR_SIGN, &gDup); + DupCheckSeedValue(&ctx, TPM_ALG_ECC, objH, 0, 0, &gDup); + FlushHandle(&ctx, objH); + + FWTPM_Cleanup(&ctx); + fwtpm_pass("CreatePrimary seedValue:", 0); +} +#endif /* HAVE_ECC */ + /* Rewrap replaces the outer wrap only: an inner and outer wrapped duplicate * moved to a second parent imports there with the inner key. */ static void test_fwtpm_duplicate_rewrap_import(void) @@ -33501,6 +33542,9 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_duplicate_needs_command_code(); test_fwtpm_duplicate_import_roundtrip(); test_fwtpm_create_seed_value(); +#ifdef HAVE_ECC + test_fwtpm_create_primary_seed_value(); +#endif test_fwtpm_duplicate_rewrap_import(); test_fwtpm_duplicate_import_rejections(); test_fwtpm_import_known_duplicate(); From e8ed44337a7a2adb619933a8fedee07ac69acd84 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 18:05:07 -0800 Subject: [PATCH 115/124] Compute unique of a fwTPM KEYEDHASH or SYMCIPHER primary from a seedValue --- src/fwtpm/fwtpm_command.c | 58 +++++++++++------- src/fwtpm/fwtpm_crypto.c | 28 --------- tests/fwtpm_unit_tests.c | 110 +++++++++++++++++++++++++++-------- wolftpm/fwtpm/fwtpm_crypto.h | 3 - 4 files changed, 122 insertions(+), 77 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index d0ca68086..b4f056f44 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -4859,19 +4859,25 @@ static TPM_RC FwAppendCreationData(FWTPM_CTX* ctx, TPM2_Packet* rsp, return rc; } -/* Set the seedValue of an asymmetric primary storage key (see - * FwCreateSeedValue). It is derived from the hierarchy seed so that the same - * template gives the same object. */ +/* Set the seedValue of a primary object, for the object types that have one + * (see FwCreateSeedValue). It is derived from the hierarchy seed so that the + * same template gives the same object, and unique of a KEYEDHASH or + * SYMCIPHER primary is computed from it. A cached KEYEDHASH or SYMCIPHER + * primary whose unique is not the one it gives was created without a + * seedValue and stays as it is. */ static TPM_RC FwPrimarySeedValue(const byte* seed, const byte* hashUnique, - int hashUniqueSz, FWTPM_Object* obj) + int hashUniqueSz, int cached, FWTPM_Object* obj) { TPM_RC rc = TPM_RC_SUCCESS; TPMT_PUBLIC* pub = &obj->pub; int digestSz = TPM2_GetHashDigestSize(pub->nameAlg); + int isSym = (pub->type == TPM_ALG_KEYEDHASH || + pub->type == TPM_ALG_SYMCIPHER); + int uSz; + byte unique[TPM_MAX_DIGEST_SIZE]; - if (pub->type == TPM_ALG_KEYEDHASH || pub->type == TPM_ALG_SYMCIPHER || - (pub->objectAttributes & TPMA_OBJECT_restricted) == 0 || - (pub->objectAttributes & TPMA_OBJECT_sign) != 0) { + if (!isSym && ((pub->objectAttributes & TPMA_OBJECT_restricted) == 0 || + (pub->objectAttributes & TPMA_OBJECT_sign) != 0)) { return TPM_RC_SUCCESS; } if (digestSz <= 0 || digestSz > (int)sizeof(obj->seedValue.buffer)) { @@ -4885,6 +4891,27 @@ static TPM_RC FwPrimarySeedValue(const byte* seed, const byte* hashUnique, else { obj->seedValue.size = (UINT16)digestSz; } + if (rc == 0 && isSym) { + /* keyedHash and sym share the layout of unique */ + uSz = FwComputeSymUnique(pub, obj->seedValue.buffer, + obj->seedValue.size, obj->privKey, obj->privKeySize, unique); + if (uSz == (int)TPM_RC_MEMORY) { + rc = TPM_RC_MEMORY; + } + else if (uSz != digestSz) { + rc = TPM_RC_FAILURE; + } + else if (!cached) { + pub->unique.keyedHash.size = (UINT16)uSz; + XMEMCPY(pub->unique.keyedHash.buffer, unique, (size_t)uSz); + } + else if ((int)pub->unique.keyedHash.size != uSz || + XMEMCMP(pub->unique.keyedHash.buffer, unique, + (size_t)uSz) != 0) { + TPM2_ForceZero(&obj->seedValue, sizeof(obj->seedValue)); + } + } + TPM2_ForceZero(unique, sizeof(unique)); return rc; } @@ -5310,14 +5337,6 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, obj->privKeySize = keySz; } } - - /* unique = H(key bytes) */ - if (rc == 0) { - obj->pub.unique.keyedHash.size = (UINT16) - FwComputeUniqueHash(inPublic->publicArea.nameAlg, - obj->privKey, obj->privKeySize, - obj->pub.unique.keyedHash.buffer); - } break; } @@ -5348,12 +5367,6 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { obj->privKeySize = keySz; - - /* unique = H(key bytes) */ - obj->pub.unique.sym.size = (UINT16) - FwComputeUniqueHash(inPublic->publicArea.nameAlg, - obj->privKey, keySz, - obj->pub.unique.sym.buffer); } break; } @@ -5366,7 +5379,8 @@ static TPM_RC FwCmd_CreatePrimary(FWTPM_CTX* ctx, TPM2_Packet* cmd, } if (rc == 0) { - rc = FwPrimarySeedValue(seed, hashUnique, hashUniqueSz, obj); + rc = FwPrimarySeedValue(seed, hashUnique, hashUniqueSz, + cached != NULL, obj); } /* Store in primary key cache */ diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 6e15de189..62ab827d2 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -109,34 +109,6 @@ int FwGetMgfType(UINT16 hashAlg) } #endif /* !NO_RSA */ -/* Compute unique = H(keyData) for KEYEDHASH/SYMCIPHER key types. - * Stores the hash in outBuf and returns the digest size, or 0 on error. */ -int FwComputeUniqueHash(TPMI_ALG_HASH nameAlg, const byte* keyData, - int keyDataSz, byte* outBuf) -{ - int rc = 0; - enum wc_HashType wcHash = FwGetWcHashType(nameAlg); - int hSz = TPM2_GetHashDigestSize(nameAlg); - - if (hSz > 0) { - FWTPM_DECLARE_VAR(hCtx, wc_HashAlg); - FWTPM_ALLOC_VAR(hCtx, wc_HashAlg); - if (rc == 0 && wc_HashInit(hCtx, wcHash) == 0) { - rc = wc_HashUpdate(hCtx, wcHash, keyData, (word32)keyDataSz); - if (rc == 0) { - rc = wc_HashFinal(hCtx, wcHash, outBuf); - } - wc_HashFree(hCtx, wcHash); - if (rc == 0) { - FWTPM_FREE_VAR(hCtx); - return hSz; - } - } - FWTPM_FREE_VAR(hCtx); - } - return 0; -} - /* Compute hashUnique = H_nameAlg(sensitiveCreate.data || unique_bytes). * Per TPM 2.0 Part 1 Section 26.1: used as context for primary key derivation. * Returns digest size on success, 0 on error. */ diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 9e895768a..2cf77e69e 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -21012,46 +21012,110 @@ static void test_fwtpm_create_seed_value(void) fwtpm_pass("Create seedValue and unique:", 0); } -#ifdef HAVE_ECC -/* A primary storage key gets its seedValue from the hierarchy seed: the same - * template gives the same seedValue with or without the primary cache. A - * signing key has none. */ +/* A primary gets its seedValue from the hierarchy seed: the same template + * gives the same seedValue and unique with or without the primary cache, + * and a KEYEDHASH primary cached with the plain digest of its key as unique + * keeps that unique and has no seedValue. */ static void test_fwtpm_create_primary_seed_value(void) { FWTPM_CTX ctx; + static const TPM_ALG_ID types[] = { + TPM_ALG_KEYEDHASH, +#ifndef NO_AES + TPM_ALG_SYMCIPHER, +#endif +#ifdef HAVE_ECC + TPM_ALG_ECC +#endif + }; UINT32 objH; FWTPM_Object* obj; byte seed[WC_SHA256_DIGEST_SIZE]; - int pass; + byte unique[WC_SHA256_DIGEST_SIZE]; + byte legacy[WC_SHA256_DIGEST_SIZE]; + UINT16 pubSz; + int i, j, k, pass; memset(&ctx, 0, sizeof(ctx)); AssertIntEQ(fwtpm_test_startup(&ctx), 0); - /* created, from the cache, and created again without the cache */ - for (pass = 0; pass < 3; pass++) { - if (pass == 2) { - memset(ctx.primaryCache, 0, sizeof(ctx.primaryCache)); - } - objH = DupCreateObject(&ctx, TPM_ALG_ECC, DUP_ATTR_STORAGE, &gDup); - DupCheckSeedValue(&ctx, TPM_ALG_ECC, objH, WC_SHA256_DIGEST_SIZE, 0, - &gDup); - obj = &ctx.objects[objH - TRANSIENT_FIRST]; - if (pass == 0) { - memcpy(seed, obj->seedValue.buffer, sizeof(seed)); - } - else { - AssertIntEQ(memcmp(seed, obj->seedValue.buffer, sizeof(seed)), 0); + for (i = 0; i < (int)(sizeof(types) / sizeof(types[0])); i++) { + UINT32 attributes = (types[i] == TPM_ALG_KEYEDHASH) ? DUP_ATTR_HMAC : + (types[i] == TPM_ALG_SYMCIPHER) ? DUP_ATTR_SYM : + DUP_ATTR_STORAGE; + + /* created, from the cache, and created again without the cache */ + for (pass = 0; pass < 3; pass++) { + if (pass == 2) { + memset(ctx.primaryCache, 0, sizeof(ctx.primaryCache)); + } + objH = DupCreateObject(&ctx, types[i], attributes, &gDup); + pubSz = gDup.pubSz; + DupCheckSeedValue(&ctx, types[i], objH, WC_SHA256_DIGEST_SIZE, 0, + &gDup); + obj = &ctx.objects[objH - TRANSIENT_FIRST]; + if (pass == 0) { + memcpy(seed, obj->seedValue.buffer, sizeof(seed)); + memcpy(unique, gDup.pub + pubSz - sizeof(unique), + sizeof(unique)); + } + else { + AssertIntEQ(memcmp(seed, obj->seedValue.buffer, sizeof(seed)), + 0); + AssertIntEQ(memcmp(unique, gDup.pub + pubSz - sizeof(unique), + sizeof(unique)), 0); + } + FlushHandle(&ctx, objH); } - FlushHandle(&ctx, objH); } +#ifdef HAVE_ECC + /* a signing key has no seedValue */ objH = DupCreateObject(&ctx, TPM_ALG_ECC, DUP_ATTR_SIGN, &gDup); DupCheckSeedValue(&ctx, TPM_ALG_ECC, objH, 0, 0, &gDup); FlushHandle(&ctx, objH); +#endif + + /* The cache entry of the HMAC key as it was written without a + * seedValue */ + memset(ctx.primaryCache, 0, sizeof(ctx.primaryCache)); + objH = DupCreateObject(&ctx, TPM_ALG_KEYEDHASH, DUP_ATTR_HMAC, &gDup); + FlushHandle(&ctx, objH); + AssertIntEQ(wc_Sha256Hash(gDupHmacKey, (word32)sizeof(gDupHmacKey), + legacy), 0); + k = -1; + for (j = 0; j < FWTPM_MAX_PRIMARY_CACHE; j++) { + if (ctx.primaryCache[j].used && + ctx.primaryCache[j].pub.type == TPM_ALG_KEYEDHASH) { + k = j; + } + } + AssertIntNE(k, -1); + memcpy(ctx.primaryCache[k].pub.unique.keyedHash.buffer, legacy, + sizeof(legacy)); + objH = DupCreateObject(&ctx, TPM_ALG_KEYEDHASH, DUP_ATTR_HMAC, &gDup); + obj = &ctx.objects[objH - TRANSIENT_FIRST]; + AssertIntEQ(obj->seedValue.size, 0); + AssertIntEQ(memcmp(gDup.pub + gDup.pubSz - sizeof(legacy), legacy, + sizeof(legacy)), 0); + DupCheckUse(&ctx, TPM_ALG_KEYEDHASH, objH, 0); + /* it duplicates with an empty seedValue and imports again */ + AssertIntEQ(DupSend(&ctx, objH, TPM_RH_NULL, NULL, 0, TPM_ALG_NULL, 0, + &gDup), TPM_RC_SUCCESS); + AssertIntEQ(GetU16BE(gDup.dup + 2 + 2 + 2 + WC_SHA256_DIGEST_SIZE), 0); + FlushHandle(&ctx, objH); +#ifdef HAVE_ECC + objH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); +#else + objH = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); +#endif + AssertIntNE(objH, 0); + AssertIntEQ(DupImport(&ctx, objH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_SUCCESS); + FlushHandle(&ctx, objH); FWTPM_Cleanup(&ctx); - fwtpm_pass("CreatePrimary seedValue:", 0); + fwtpm_pass("CreatePrimary seedValue and unique:", 0); } -#endif /* HAVE_ECC */ /* Rewrap replaces the outer wrap only: an inner and outer wrapped duplicate * moved to a second parent imports there with the inner key. */ @@ -33542,9 +33606,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_duplicate_needs_command_code(); test_fwtpm_duplicate_import_roundtrip(); test_fwtpm_create_seed_value(); -#ifdef HAVE_ECC test_fwtpm_create_primary_seed_value(); -#endif test_fwtpm_duplicate_rewrap_import(); test_fwtpm_duplicate_import_rejections(); test_fwtpm_import_known_duplicate(); diff --git a/wolftpm/fwtpm/fwtpm_crypto.h b/wolftpm/fwtpm/fwtpm_crypto.h index c5aa513c9..fdca39eee 100644 --- a/wolftpm/fwtpm/fwtpm_crypto.h +++ b/wolftpm/fwtpm/fwtpm_crypto.h @@ -53,9 +53,6 @@ enum wc_HashType FwGetWcHashType(UINT16 hashAlg); int FwGetMgfType(UINT16 hashAlg); #endif -int FwComputeUniqueHash(TPMI_ALG_HASH nameAlg, const byte* keyData, - int keyDataSz, byte* outBuf); - /* hashUnique = H(sensitiveCreate.data || unique_bytes) for primary derivation. * Returns the digest size, TPM_RC_MEMORY on allocation failure, or 0 for any * other error. */ From 5f0a156eaae4167acc8e79f1dd5ed3aee6dc9f98 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 21:04:50 -0800 Subject: [PATCH 116/124] Report an allocation failure from the fwTPM restricted key unique HMAC --- src/fwtpm/fwtpm_crypto.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index 62ab827d2..c5e7791df 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -160,15 +160,20 @@ int FwComputeSymUnique(const TPMT_PUBLIC* pub, byte* uniqueOut) { int hSz = TPM2_GetHashDigestSize(pub->nameAlg); + int rc; if (seedSz > 0 && (pub->objectAttributes & TPMA_OBJECT_restricted) != 0 && (pub->objectAttributes & TPMA_OBJECT_decrypt) != 0) { - if (hSz <= 0 || TPM2_HmacCompute(pub->nameAlg, seed, (word32)seedSz, - key, (word32)keySz, NULL, 0, uniqueOut, NULL) != 0) { + if (hSz <= 0) { return 0; } - return hSz; + rc = TPM2_HmacCompute(pub->nameAlg, seed, (word32)seedSz, + key, (word32)keySz, NULL, 0, uniqueOut, NULL); + if (rc == MEMORY_E) { + return (int)TPM_RC_MEMORY; + } + return (rc == 0) ? hSz : 0; } return FwComputeHashUnique(pub->nameAlg, seed, seedSz, key, keySz, uniqueOut); From cb8febae7e424acac66f8737cfcc66622130b5d8 Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 21:27:40 -0800 Subject: [PATCH 117/124] Size the fwTPM private blob buffers for a full authValue and seedValue --- src/fwtpm/fwtpm_crypto.c | 16 +++++------ tests/fwtpm_unit_tests.c | 59 ++++++++++++++++++++++++++++++++++++++++ wolftpm/fwtpm/fwtpm.h | 5 ++-- 3 files changed, 70 insertions(+), 10 deletions(-) diff --git a/src/fwtpm/fwtpm_crypto.c b/src/fwtpm/fwtpm_crypto.c index c5e7791df..8476fce4c 100644 --- a/src/fwtpm/fwtpm_crypto.c +++ b/src/fwtpm/fwtpm_crypto.c @@ -2398,7 +2398,7 @@ int FwWrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, WC_RNG* rng, int rc = TPM_RC_SUCCESS; byte aesKey[FWTPM_MAX_SYM_KEY_SIZE], aesIV[AES_BLOCK_SIZE]; byte macKey[WC_SHA256_DIGEST_SIZE]; - FWTPM_DECLARE_BUF(sensBuf, FWTPM_MAX_PRIVKEY_DER + 128); + FWTPM_DECLARE_BUF(sensBuf, FWTPM_MAX_SENSITIVE_SIZE); byte hmacDigest[WC_SHA256_DIGEST_SIZE]; FWTPM_DECLARE_VAR(aes, Aes); FWTPM_DECLARE_VAR(hmac, Hmac); @@ -2407,14 +2407,14 @@ int FwWrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, WC_RNG* rng, int hmacInit = 0; int pos = 0; - FWTPM_ALLOC_BUF(sensBuf, FWTPM_MAX_PRIVKEY_DER + 128); + FWTPM_ALLOC_BUF(sensBuf, FWTPM_MAX_SENSITIVE_SIZE); FWTPM_ALLOC_VAR(aes, Aes); FWTPM_ALLOC_VAR(hmac, Hmac); /* Marshal inner sensitive */ if (rc == 0) { sensSz = FwMarshalSensitive(sensBuf, - (int)(FWTPM_MAX_PRIVKEY_DER + 128), + (int)FWTPM_MAX_SENSITIVE_SIZE, sensitiveType, auth, privKeyDer, privKeyDerSz, seedValue); if (sensSz < 0) { rc = TPM_RC_FAILURE; @@ -2499,7 +2499,7 @@ int FwWrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, WC_RNG* rng, TPM2_ForceZero(macKey, sizeof(macKey)); TPM2_ForceZero(aesIV, sizeof(aesIV)); TPM2_ForceZero(hmacDigest, sizeof(hmacDigest)); - TPM2_ForceZero(sensBuf, FWTPM_MAX_PRIVKEY_DER + 128); + TPM2_ForceZero(sensBuf, FWTPM_MAX_SENSITIVE_SIZE); FWTPM_FREE_BUF(sensBuf); FWTPM_FREE_VAR(aes); FWTPM_FREE_VAR(hmac); @@ -2519,14 +2519,14 @@ int FwUnwrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, byte macKey[WC_SHA256_DIGEST_SIZE]; byte hmacDigest[WC_SHA256_DIGEST_SIZE]; byte hmacCheck[WC_SHA256_DIGEST_SIZE]; - FWTPM_DECLARE_BUF(decBuf, FWTPM_MAX_PRIVKEY_DER + 128); + FWTPM_DECLARE_BUF(decBuf, FWTPM_MAX_SENSITIVE_SIZE); FWTPM_DECLARE_VAR(aes, Aes); FWTPM_DECLARE_VAR(hmac, Hmac); int aesInit = 0; int pos = 0; UINT16 integritySize = 0, encSensSize = 0; - FWTPM_ALLOC_BUF(decBuf, FWTPM_MAX_PRIVKEY_DER + 128); + FWTPM_ALLOC_BUF(decBuf, FWTPM_MAX_SENSITIVE_SIZE); FWTPM_ALLOC_VAR(aes, Aes); FWTPM_ALLOC_VAR(hmac, Hmac); @@ -2559,7 +2559,7 @@ int FwUnwrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, encSensSize = FwLoadU16BE(inPriv->buffer + pos); pos += 2; if (pos + encSensSize > inPriv->size || - encSensSize > (int)(FWTPM_MAX_PRIVKEY_DER + 128)) { + encSensSize > (int)FWTPM_MAX_SENSITIVE_SIZE) { rc = TPM_RC_FAILURE; } } @@ -2625,7 +2625,7 @@ int FwUnwrapPrivate(FWTPM_CTX* ctx, FWTPM_Object* parent, TPM2_ForceZero(macKey, sizeof(macKey)); TPM2_ForceZero(aesIV, sizeof(aesIV)); TPM2_ForceZero(hmacCheck, sizeof(hmacCheck)); - TPM2_ForceZero(decBuf, FWTPM_MAX_PRIVKEY_DER + 128); + TPM2_ForceZero(decBuf, FWTPM_MAX_SENSITIVE_SIZE); FWTPM_FREE_BUF(decBuf); FWTPM_FREE_VAR(aes); FWTPM_FREE_VAR(hmac); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 2cf77e69e..85a4f8a6e 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -20283,6 +20283,64 @@ static void test_fwtpm_load_private_seed_value(void) fwtpm_pass("Private blob seedValue:", 0); } +/* A private key of FWTPM_MAX_PRIVKEY_DER octets wraps and unwraps with an + * authValue and a seedValue of the largest digest size. */ +static void test_fwtpm_wrap_private_max_sensitive(void) +{ + FWTPM_CTX ctx; + FWTPM_Object* parent; + UINT32 parentH; + static byte der[FWTPM_MAX_PRIVKEY_DER]; + static byte derOut[FWTPM_MAX_PRIVKEY_DER]; + static TPM2B_PRIVATE priv; + TPM2B_NAME name; + TPM2B_AUTH auth, authOut; + TPM2B_DIGEST seed, seedOut; + UINT16 sensType = 0; + int derOutSz = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); +#ifdef HAVE_ECC + parentH = CreatePrimaryHelper(&ctx, TPM_ALG_ECC); +#else + parentH = CreatePrimaryHelper(&ctx, TPM_ALG_RSA); +#endif + AssertIntNE(parentH, 0); + parent = &ctx.objects[parentH - TRANSIENT_FIRST]; + + memset(&name, 0, sizeof(name)); + name.size = 2 + WC_SHA256_DIGEST_SIZE; + PutU16BE(name.name, TPM_ALG_SHA256); + memset(der, 0x6B, sizeof(der)); + memset(&auth, 0, sizeof(auth)); + auth.size = sizeof(auth.buffer); + memset(auth.buffer, 0xA1, sizeof(auth.buffer)); + memset(&seed, 0, sizeof(seed)); + seed.size = sizeof(seed.buffer); + memset(seed.buffer, 0xC3, sizeof(seed.buffer)); + memset(&priv, 0, sizeof(priv)); + memset(&authOut, 0, sizeof(authOut)); + memset(&seedOut, 0, sizeof(seedOut)); + + AssertIntEQ(FwWrapPrivate(&ctx, parent, &ctx.rng, &name, + TPM_ALG_KEYEDHASH, &auth, der, (int)sizeof(der), &seed, &priv), + TPM_RC_SUCCESS); + AssertIntEQ(FwUnwrapPrivate(&ctx, parent, &name, &priv, &sensType, + &authOut, derOut, &derOutSz, &seedOut), TPM_RC_SUCCESS); + AssertIntEQ(sensType, TPM_ALG_KEYEDHASH); + AssertIntEQ(authOut.size, auth.size); + AssertIntEQ(memcmp(authOut.buffer, auth.buffer, auth.size), 0); + AssertIntEQ(derOutSz, (int)sizeof(der)); + AssertIntEQ(memcmp(derOut, der, sizeof(der)), 0); + AssertIntEQ(seedOut.size, seed.size); + AssertIntEQ(memcmp(seedOut.buffer, seed.buffer, seed.size), 0); + + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Private blob maximum sensitive:", 0); +} + #if !defined(FWTPM_NO_KEY_MIGRATION) && !defined(FWTPM_NO_POLICY) static TPM_RC SendDuplicateCmd(FWTPM_CTX* ctx, UINT32 objH, UINT32 newParentH, UINT32 sessH, UINT16 symAlg) @@ -33588,6 +33646,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_loadexternal_symcipher_unique(); test_fwtpm_loadexternal_keyedhash(); test_fwtpm_load_private_seed_value(); + test_fwtpm_wrap_private_max_sensitive(); #if defined(HAVE_ECC) && !defined(FWTPM_NO_ECDH) test_fwtpm_ecc_unpadded_values(); #endif diff --git a/wolftpm/fwtpm/fwtpm.h b/wolftpm/fwtpm/fwtpm.h index 1addc75b1..dd83673ff 100644 --- a/wolftpm/fwtpm/fwtpm.h +++ b/wolftpm/fwtpm/fwtpm.h @@ -233,8 +233,9 @@ #endif /* Maximum sensitive area buffer: private key DER + wire-format overhead - * (sensitiveType(2) + authValue(2+64) + seedValue(2+48) + size(2) = ~120) */ -#define FWTPM_MAX_SENSITIVE_SIZE (FWTPM_MAX_PRIVKEY_DER + 128) + * (size(2) + sensitiveType(2) + authValue(2+64) + seedValue(2+64) + size(2) + * = 138) */ +#define FWTPM_MAX_SENSITIVE_SIZE (FWTPM_MAX_PRIVKEY_DER + 144) /* Maximum concurrent hash sequences */ #ifndef FWTPM_MAX_HASH_SEQ From 0ad6949a20bd025179fe09d297f8b5d189d6a41a Mon Sep 17 00:00:00 2001 From: David Garske Date: Wed, 18 Nov 2026 21:27:40 -0800 Subject: [PATCH 118/124] Test the fwTPM Import rejections of a seedValue of the wrong size --- tests/fwtpm_unit_tests.c | 70 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 85a4f8a6e..3abdcf96c 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -21696,6 +21696,75 @@ static void test_fwtpm_import_empty_keyedhash_auth(void) fwtpm_pass("Import empty KEYEDHASH authorizes:", 0); } +/* Give the seedValue of the unwrapped TPM2B_SENSITIVE in blob->dup seedSz + * octets, keeping the leading ones it has */ +static void DupSetSeedSize(DupBlob* blob, UINT16 seedSz) +{ + int pos = 4, oldSz, tailSz; + + pos += 2 + GetU16BE(blob->dup + pos); /* authValue */ + oldSz = GetU16BE(blob->dup + pos); + tailSz = blob->dupSz - (pos + 2 + oldSz); + AssertIntGT(tailSz, 1); + AssertIntLE(pos + 2 + seedSz + tailSz, (int)sizeof(blob->dup)); + memmove(blob->dup + pos + 2 + seedSz, blob->dup + pos + 2 + oldSz, + (size_t)tailSz); + if (seedSz > oldSz) { + memset(blob->dup + pos + 2 + oldSz, 0x5A, (size_t)(seedSz - oldSz)); + } + PutU16BE(blob->dup + pos, seedSz); + blob->dupSz = (UINT16)(pos + 2 + seedSz + tailSz); + PutU16BE(blob->dup, (UINT16)(blob->dupSz - 2)); +} + +/* Import refuses a seedValue larger than the nameAlg digest, and for a + * storage key one that is not empty and smaller than half of it. */ +static void test_fwtpm_import_seed_value_size(void) +{ + FWTPM_CTX ctx; + UINT32 parentH, objH; +#ifdef HAVE_ECC + TPM_ALG_ID parentAlg = TPM_ALG_ECC; + TPM_ALG_ID objType = TPM_ALG_ECC; +#else + TPM_ALG_ID parentAlg = TPM_ALG_RSA; + TPM_ALG_ID objType = TPM_ALG_SYMCIPHER; +#endif + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + parentH = CreatePrimaryHelper(&ctx, parentAlg); + AssertIntNE(parentH, 0); + objH = DupCreateObjectEx(&ctx, TPM_CC_CreateLoaded, parentH, objType, + DUP_ATTR_STORAGE, &gDup); + DupCheckSeedValue(&ctx, objType, objH, WC_SHA256_DIGEST_SIZE, 1, &gDup); + FlushHandle(&ctx, objH); + + DupSetSeedSize(&gDup, WC_SHA256_DIGEST_SIZE + 1); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_KEY_SIZE | TPM_RC_P | TPM_RC_3); + DupSetSeedSize(&gDup, WC_SHA256_DIGEST_SIZE / 2 - 1); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_SIZE | TPM_RC_P | TPM_RC_3); + DupSetSeedSize(&gDup, 1); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_SIZE | TPM_RC_P | TPM_RC_3); +#ifdef HAVE_ECC + /* half the digest is enough, and a duplicate made before this TPM kept + * a seedValue has none */ + DupSetSeedSize(&gDup, WC_SHA256_DIGEST_SIZE / 2); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_SUCCESS); + DupSetSeedSize(&gDup, 0); + AssertIntEQ(DupImport(&ctx, parentH, NULL, 0, TPM_ALG_NULL, 0, &gDup), + TPM_RC_SUCCESS); +#endif + + FlushHandle(&ctx, parentH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("Import seedValue size:", 0); +} + #if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) /* A failed small-stack allocation in Duplicate or Rewrap is reported as * TPM_RC_MEMORY and the unallocated buffers are not used. */ @@ -33670,6 +33739,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_duplicate_import_rejections(); test_fwtpm_import_known_duplicate(); test_fwtpm_import_empty_keyedhash_auth(); + test_fwtpm_import_seed_value_size(); #if defined(WOLFTPM_FWTPM_UNIT_TEST) && defined(WOLFTPM_SMALL_STACK) test_fwtpm_duplicate_rewrap_alloc_failure(); #endif From c5afbbbbad61bcbfa7ce7046678696ae057eb9ff Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 24 Nov 2026 11:34:12 -0800 Subject: [PATCH 119/124] Add the session number to fwTPM session attribute response codes --- src/fwtpm/fwtpm_command.c | 8 ++++++-- tests/fwtpm_unit_tests.c | 42 ++++++++++++++++++++++++++++----------- 2 files changed, 36 insertions(+), 14 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index b4f056f44..a03a97f90 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -24082,6 +24082,9 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, UINT16 nonceSize, hmacSize; UINT8 attribs; byte nonceBuf[TPM_MAX_DIGEST_SIZE]; + /* Session number of a format-one response code */ + TPM_RC rcSession = TPM_RC_S | + (TPM_RC)(TPM_RC_1 * (cmdAuthCnt + 1)); TPM2_Packet_ParseU32(&cmdPkt, &sessHandle); TPM2_Packet_ParseU16(&cmdPkt, &nonceSize); @@ -24130,6 +24133,7 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, rc = FwCheckSessionAttributes(entry, sessHandle, attribs, cmdAuthCnt, &auditCnt); if (rc != 0) { + rc |= rcSession; break; } @@ -24153,13 +24157,13 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, decSess != NULL) || ((attribs & TPMA_SESSION_encrypt) != 0 && encSess != NULL)) { - rc = TPM_RC_ATTRIBUTES; + rc = TPM_RC_ATTRIBUTES | rcSession; break; } if ((attribs & (TPMA_SESSION_decrypt | TPMA_SESSION_encrypt)) != 0 && sess->symmetric.algorithm == TPM_ALG_NULL) { - rc = TPM_RC_SYMMETRIC; + rc = TPM_RC_SYMMETRIC | rcSession; break; } /* The first authHandleCnt handles are the ones diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 3abdcf96c..cbb0c1d3e 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -22210,7 +22210,7 @@ static void test_fwtpm_param_enc_session_selection(void) sessB, cont | TPMA_SESSION_decrypt, nonceCaller, plain, sizeof(plain)); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES | TPM_RC_S | TPM_RC_3); FlushHandle(&ctx, sessB); nullSess = StartParamEncSessionHelper(&ctx, TPM_SE_POLICY, TPM_ALG_NULL, @@ -22220,7 +22220,7 @@ static void test_fwtpm_param_enc_session_selection(void) 0, 0, nonceCaller, plain, sizeof(plain)); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_SYMMETRIC); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SYMMETRIC | TPM_RC_S | TPM_RC_2); FlushHandle(&ctx, nullSess); FlushHandle(&ctx, sessA); @@ -22713,12 +22713,12 @@ static void test_fwtpm_session_hmac_sweep(void) for (withPw = 0; withPw <= 1; withPw++) { expectRc = TPM_RC_BAD_AUTH; if (withPw && nHandles == 0) { - expectRc = TPM_RC_HANDLE; + expectRc = TPM_RC_HANDLE | TPM_RC_S | TPM_RC_1; } for (j = 0; withPw && j < sizeof(noAuth) / sizeof(noAuth[0]); j++) { if (noAuth[j] == cc) { - expectRc = TPM_RC_HANDLE; + expectRc = TPM_RC_HANDLE | TPM_RC_S | TPM_RC_1; } } for (j = 0; j < sizeof(early) / sizeof(early[0]); j++) { @@ -23160,18 +23160,21 @@ static void test_fwtpm_session_attribute_rules(void) UINT8 attrs; TPM_RC rc; } cases[] = { - { TPMA_SESSION_continueSession, TPM_RC_ATTRIBUTES }, + { TPMA_SESSION_continueSession, TPM_RC_ATTRIBUTES | TPM_RC_S | + TPM_RC_1 }, { TPMA_SESSION_continueSession | TPMA_SESSION_audit, TPM_RC_SUCCESS }, { TPMA_SESSION_continueSession | TPMA_SESSION_encrypt, TPM_RC_SUCCESS }, { TPMA_SESSION_continueSession | TPMA_SESSION_decrypt, - TPM_RC_ATTRIBUTES }, + TPM_RC_ATTRIBUTES | TPM_RC_S | TPM_RC_1 }, { TPMA_SESSION_continueSession | TPMA_SESSION_encrypt | - TPMA_SESSION_decrypt, TPM_RC_ATTRIBUTES }, + TPMA_SESSION_decrypt, TPM_RC_ATTRIBUTES | TPM_RC_S | TPM_RC_1 }, { TPMA_SESSION_continueSession | TPMA_SESSION_encrypt | - TPMA_SESSION_auditExclusive, TPM_RC_ATTRIBUTES }, + TPMA_SESSION_auditExclusive, TPM_RC_ATTRIBUTES | TPM_RC_S | + TPM_RC_1 }, { TPMA_SESSION_continueSession | TPMA_SESSION_encrypt | - TPMA_SESSION_auditReset, TPM_RC_ATTRIBUTES } + TPMA_SESSION_auditReset, TPM_RC_ATTRIBUTES | TPM_RC_S | + TPM_RC_1 } }; FWTPM_CTX ctx; FWTPM_Session* sess = NULL; @@ -23183,7 +23186,7 @@ static void test_fwtpm_session_attribute_rules(void) byte cpBuf[6]; byte pHash[WC_SHA256_DIGEST_SIZE]; byte authHmac[WC_SHA256_DIGEST_SIZE]; - int pos, rspSize; + int pos, authStart, rspSize; size_t i; memset(&ctx, 0, sizeof(ctx)); @@ -23221,7 +23224,7 @@ static void test_fwtpm_session_attribute_rules(void) PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_HANDLE); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_HANDLE | TPM_RC_S | TPM_RC_1); /* and cannot decrypt, encrypt or audit */ pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Clear); @@ -23230,7 +23233,22 @@ static void test_fwtpm_session_attribute_rules(void) PutU32BE(gCmd + 2, (UINT32)pos); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_ATTRIBUTES | TPM_RC_S | TPM_RC_1); + + /* the response code names the session at fault */ + pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_Clear); + PutU32BE(gCmd + pos, TPM_RH_LOCKOUT); pos += 4; + authStart = pos; + pos = AppendPwAuth(gCmd, pos, NULL, 0); + PutU32BE(gCmd + pos, TPM_RS_PW); pos += 4; + PutU16BE(gCmd + pos, 0); pos += 2; + gCmd[pos++] = 0; + PutU16BE(gCmd + pos, 0); pos += 2; + PutU32BE(gCmd + authStart, (UINT32)(pos - authStart - 4)); + PutU32BE(gCmd + 2, (UINT32)pos); + rspSize = 0; + FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_HANDLE | TPM_RC_S | TPM_RC_2); FlushHandle(&ctx, sessH); FWTPM_Cleanup(&ctx); From 04175d3ceec5897931cf2b9de9cacc11b78c1525 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 24 Nov 2026 11:34:12 -0800 Subject: [PATCH 120/124] Apply the global NV write lock flag of an older fwTPM image on load --- src/fwtpm/fwtpm_nv.c | 8 +++++++ tests/fwtpm_unit_tests.c | 48 ++++++++++++++++++++++++++++++++++++++++ wolftpm/fwtpm/fwtpm.h | 3 ++- 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_nv.c b/src/fwtpm/fwtpm_nv.c index 16da1f1fd..6a1449dea 100644 --- a/src/fwtpm/fwtpm_nv.c +++ b/src/fwtpm/fwtpm_nv.c @@ -2546,6 +2546,14 @@ int FWTPM_NV_Init(FWTPM_CTX* ctx) rc = FwNvGenFreshState(ctx); } +#ifndef FWTPM_NO_NV + /* An image saved with the global write lock flag set has no lock record + * and its indexes do not carry the lock */ + if (rc == TPM_RC_SUCCESS && ctx->globalNvWriteLock) { + FwNvApplyGlobalLock(ctx); + } +#endif + TPM2_ForceZero(valueBuf, valueBufSz); XFREE(valueBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); return rc; diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index cbb0c1d3e..8a3cdd7f2 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -30856,6 +30856,53 @@ static void test_fwtpm_nv_global_write_lock_attribute(void) fwtpm_pass("NV_GlobalWriteLock sets WRITELOCKED:", 0); } +/* The global write lock flag of an older NV image write-locks its GLOBALLOCK + * indexes when the image is loaded, until Startup(CLEAR). */ +static void test_fwtpm_nv_global_write_lock_flag(void) +{ + FWTPM_CTX ctx; + const UINT32 lockIdx = 0x01500A14; + const UINT32 plainIdx = 0x01500A15; + const UINT32 attrs = TPMA_NV_OWNERWRITE | TPMA_NV_OWNERREAD; + int cmdSz, rspSize = 0; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + + cmdSz = BuildNvDefineCmd(gCmd, lockIdx, 8, attrs | TPMA_NV_GLOBALLOCK); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + cmdSz = BuildNvDefineCmd(gCmd, plainIdx, 8, attrs); + FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); + AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); + + ctx.globalNvWriteLock = 1; + AssertIntEQ(FWTPM_NV_SaveFlags(&ctx), TPM_RC_SUCCESS); + AssertIntEQ(fwtpm_test_cycle(&ctx, TPM_SU_STATE, TPM_SU_STATE), 0); + AssertIntNE(NvReadPublicAttributes(&ctx, lockIdx) & + TPMA_NV_WRITELOCKED, 0); + AssertIntEQ(NvReadPublicAttributes(&ctx, plainIdx) & + TPMA_NV_WRITELOCKED, 0); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, lockIdx, NULL, 8, 0), + TPM_RC_NV_LOCKED); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, plainIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + + AssertIntEQ(fwtpm_test_cycle(&ctx, TPM_SU_CLEAR, TPM_SU_CLEAR), 0); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, lockIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + AssertIntEQ(fwtpm_test_cycle(&ctx, TPM_SU_STATE, TPM_SU_STATE), 0); + AssertIntEQ(SendNvOwnerCmd(&ctx, TPM_CC_NV_Write, lockIdx, NULL, 8, 0), + TPM_RC_SUCCESS); + + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, lockIdx), + TPM_RC_SUCCESS); + AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, plainIdx), + TPM_RC_SUCCESS); + FWTPM_Cleanup(&ctx); + fwtpm_pass("NV global write lock flag of an older image:", 0); +} + static FWTPM_NV_HAL gNvFailAfterHal; static int gNvFailAfterWrites; @@ -33992,6 +34039,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) test_fwtpm_clear_resets_lockout_auth(); #ifndef FWTPM_NO_NV test_fwtpm_nv_global_write_lock_attribute(); + test_fwtpm_nv_global_write_lock_flag(); test_fwtpm_nv_global_write_lock_all_or_none(); test_fwtpm_nv_global_write_lock_at_capacity(); #endif diff --git a/wolftpm/fwtpm/fwtpm.h b/wolftpm/fwtpm/fwtpm.h index dd83673ff..fd19dc2f4 100644 --- a/wolftpm/fwtpm/fwtpm.h +++ b/wolftpm/fwtpm/fwtpm.h @@ -879,7 +879,8 @@ typedef struct FWTPM_CTX { int shutdownStateSaved; /* Previous Shutdown(STATE), persisted */ int pendingClear; /* Deferred clear (after response auth) */ int disableClear; /* ClearControl: 1 = Clear is disabled */ - int globalNvWriteLock; /* Persisted in the NV flags; not enforced */ + int globalNvWriteLock; /* NV flag of an older image: GLOBALLOCK + * indexes are write locked on load */ /* HierarchyControl enable state (0 = enabled). Re-enabled on Startup * CLEAR per TPM 2.0 Part 1 (TPMS_STARTUP_CLEAR). */ int shDisabled; /* !shEnable: owner hierarchy */ From 8d622aa8abe8e740f30e80c363396499149c4202 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 24 Nov 2026 11:34:12 -0800 Subject: [PATCH 121/124] Reject a LoadExternal sensitive type that differs from the public type --- src/fwtpm/fwtpm_command.c | 11 +++++--- tests/fwtpm_unit_tests.c | 54 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index a03a97f90..08155fbf2 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -9270,9 +9270,15 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, } #endif + /* The sensitive area is of the type of the public area */ + if (rc == 0 && inPrivSize > 0 && + sensitiveType != inPublic.publicArea.type) { + rc = TPM_RC_TYPE | TPM_RC_P | TPM_RC_1; + } + /* Reconstruct/store private key if private area was provided */ if (rc == 0 && inPrivSize > 0 && sensitiveType == TPM_ALG_SYMCIPHER && - inPublic.publicArea.type == TPM_ALG_SYMCIPHER && qSz > 0) { + qSz > 0) { /* For SYMCIPHER, qBuf contains the raw AES key bytes. Per Part 2 * Sec.11.1.9 a TPM2B_SYM_KEY for AES is 16, 24, or 32 bytes. * Reject any other length up front - the outer FWTPM_MAX_DER_SIG_BUF @@ -9292,8 +9298,7 @@ static TPM_RC FwCmd_LoadExternal(FWTPM_CTX* ctx, TPM2_Packet* cmd, } } else if (rc == 0 && inPrivSize > 0 && - sensitiveType == TPM_ALG_KEYEDHASH && - inPublic.publicArea.type == TPM_ALG_KEYEDHASH && qSz > 0) { + sensitiveType == TPM_ALG_KEYEDHASH && qSz > 0) { /* For KEYEDHASH, qBuf is the HMAC key or the data */ rc = FwCheckExternalKeyedHash(&inPublic.publicArea, cmd->buf + seedPos, seedSz, qBuf, qSz); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index 8a3cdd7f2..e093ab8da 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -19812,9 +19812,10 @@ static void test_fwtpm_loadexternal_keyedhash(void) } #ifdef HAVE_ECC -/* LoadExternal of a P-256 key, public only when d is NULL. */ -static TPM_RC SendLoadExternalEcc(FWTPM_CTX* ctx, UINT32 attributes, - const byte* x, UINT16 xSz, const byte* y, UINT16 ySz, +/* LoadExternal of a P-256 key, public only when d is NULL. sensType is the + * sensitiveType sent with d. */ +static TPM_RC SendLoadExternalEccType(FWTPM_CTX* ctx, UINT16 sensType, + UINT32 attributes, const byte* x, UINT16 xSz, const byte* y, UINT16 ySz, const byte* d, UINT16 dSz, UINT32* handle) { int pos, privStart, pubStart, rspSize = 0; @@ -19823,7 +19824,7 @@ static TPM_RC SendLoadExternalEcc(FWTPM_CTX* ctx, UINT32 attributes, privStart = pos; PutU16BE(gCmd + pos, 0); pos += 2; if (d != NULL) { - PutU16BE(gCmd + pos, TPM_ALG_ECC); pos += 2; /* sensitiveType */ + PutU16BE(gCmd + pos, sensType); pos += 2; /* sensitiveType */ PutU16BE(gCmd + pos, 0); pos += 2; /* authValue */ PutU16BE(gCmd + pos, 0); pos += 2; /* seedValue */ PutU16BE(gCmd + pos, dSz); pos += 2; @@ -19854,6 +19855,14 @@ static TPM_RC SendLoadExternalEcc(FWTPM_CTX* ctx, UINT32 attributes, return GetRspRC(gRsp); } +static TPM_RC SendLoadExternalEcc(FWTPM_CTX* ctx, UINT32 attributes, + const byte* x, UINT16 xSz, const byte* y, UINT16 ySz, + const byte* d, UINT16 dSz, UINT32* handle) +{ + return SendLoadExternalEccType(ctx, TPM_ALG_ECC, attributes, x, xSz, y, + ySz, d, dSz, handle); +} + /* Make a P-256 key whose x coordinate (wantX) or private scalar starts with * a zero octet, and export its fixed-width values. */ static void MakeEccKeyLeadingZero(WC_RNG* rng, ecc_key* key, int wantX, @@ -19935,6 +19944,42 @@ static void test_fwtpm_ecc_private_binding(void) fwtpm_pass("ECC private scalar bound to public point:", 0); } +/* The sensitive area of an external object has the type of its public area + * (Part 3 Sec.12.3.1). */ +static void test_fwtpm_loadexternal_sensitive_type(void) +{ + static const UINT16 types[] = { + TPM_ALG_RSA, TPM_ALG_KEYEDHASH, TPM_ALG_SYMCIPHER + }; + FWTPM_CTX ctx; + ecc_key key; + UINT32 keyH = 0; + byte x[32], y[32], d[32]; + word32 xSz = sizeof(x), ySz = sizeof(y), dSz = sizeof(d); + size_t i; + + memset(&ctx, 0, sizeof(ctx)); + AssertIntEQ(fwtpm_test_startup(&ctx), 0); + AssertIntEQ(wc_ecc_init(&key), 0); + AssertIntEQ(wc_ecc_make_key_ex(&ctx.rng, 32, &key, ECC_SECP256R1), 0); + AssertIntEQ(wc_ecc_export_private_raw(&key, x, &xSz, y, &ySz, d, &dSz), + 0); + wc_ecc_free(&key); + + /* userWithAuth | sign */ + for (i = 0; i < sizeof(types) / sizeof(types[0]); i++) { + AssertIntEQ(SendLoadExternalEccType(&ctx, types[i], 0x00040040, x, + (UINT16)xSz, y, (UINT16)ySz, d, (UINT16)dSz, &keyH), + TPM_RC_TYPE | TPM_RC_P | TPM_RC_1); + } + AssertIntEQ(SendLoadExternalEcc(&ctx, 0x00040040, x, (UINT16)xSz, y, + (UINT16)ySz, d, (UINT16)dSz, &keyH), TPM_RC_SUCCESS); + + FlushHandle(&ctx, keyH); + FWTPM_Cleanup(&ctx); + fwtpm_pass("LoadExternal sensitive type matches public:", 0); +} + #ifndef FWTPM_NO_ECDH static TPM_RC SendEcdhZGen(FWTPM_CTX* ctx, UINT32 keyH, const byte* x, UINT16 xSz, const byte* y, UINT16 ySz) @@ -33786,6 +33831,7 @@ int fwtpm_unit_tests(int argc, char *argv[]) #endif #ifdef HAVE_ECC test_fwtpm_ecc_private_binding(); + test_fwtpm_loadexternal_sensitive_type(); #endif #if !defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) && \ !defined(FWTPM_NO_CREDENTIAL) From 0ad8f315866f52ececc13b823e91bef5f9812e60 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 24 Nov 2026 11:34:12 -0800 Subject: [PATCH 122/124] Use FwDupOuterWrap for the outer wrap in fwTPM Rewrap --- src/fwtpm/fwtpm_command.c | 61 +++++---------------------------------- 1 file changed, 8 insertions(+), 53 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 08155fbf2..2d3cbfcb6 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -10618,23 +10618,10 @@ static TPM_RC FwCmd_Rewrap(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* === Re-wrap under newParent === */ if (rc == 0 && newParent != NULL) { - TPMI_ALG_HASH parentNameAlg = newParent->pub.nameAlg; - int symKeySz, digestSz; + int digestSz; int encSeedSz = 0; - byte hmacDigest[TPM_MAX_DIGEST_SIZE]; - int outPos = 0; - if (newParent->pub.type == TPM_ALG_RSA) { - symKeySz = (int)(newParent->pub.parameters.rsaDetail.symmetric.keyBits.sym / 8); - } - else { - symKeySz = (int)(newParent->pub.parameters.eccDetail.symmetric.keyBits.sym / 8); - } - if (symKeySz <= 0) symKeySz = 16; - if (symKeySz > FWTPM_MAX_SYM_KEY_SIZE) { - rc = TPM_RC_SYMMETRIC; - } - digestSz = TPM2_GetHashDigestSize(parentNameAlg); + digestSz = TPM2_GetHashDigestSize(newParent->pub.nameAlg); if (digestSz <= 0) rc = TPM_RC_HASH; @@ -10645,48 +10632,17 @@ static TPM_RC FwCmd_Rewrap(FWTPM_CTX* ctx, TPM2_Packet* cmd, seedBuf, (int)sizeof(seedBuf), &seedSz, encSeedBuf, (int)FWTPM_MAX_PUB_BUF, &encSeedSz); } - /* Derive new AES + HMAC keys */ - if (rc == 0) { - rc = TPM2_KDFa_ex(parentNameAlg, seedBuf, seedSz, - "STORAGE", nameBuf, nameSz, NULL, 0, aesKey, symKeySz); - rc = (rc == symKeySz) ? 0 : TPM_RC_FAILURE; - } - if (rc == 0) { - rc = TPM2_KDFa_ex(parentNameAlg, seedBuf, seedSz, - "INTEGRITY", NULL, 0, NULL, 0, hmacKeyBuf, digestSz); - rc = (rc == digestSz) ? 0 : TPM_RC_FAILURE; - } - /* AES-CFB encrypt plainSens */ - if (rc == 0) { - rc = TPM2_AesCfbEncrypt(aesKey, symKeySz, - NULL, plainSens, (word32)plainSensSz); - if (rc != 0) - rc = TPM_RC_FAILURE; - } - /* HMAC(hmacKey, encSens || name) */ - if (rc == 0) { - rc = TPM2_HmacCompute(parentNameAlg, - hmacKeyBuf, (word32)digestSz, - plainSens, (word32)plainSensSz, - (nameSz > 0) ? nameBuf : NULL, (word32)nameSz, - hmacDigest, NULL); - if (rc != 0) - rc = TPM_RC_FAILURE; - } - /* Pack outDuplicate: integritySize(2) || integrity || encSens */ + /* outDuplicate: integritySize(2) || integrity || encSens */ if (rc == 0) { if (2 + digestSz + plainSensSz > (int)(FWTPM_MAX_PRIVKEY_DER + 256)) { rc = TPM_RC_SIZE; } } if (rc == 0) { - FwStoreU16BE(dupBuf + outPos, (UINT16)digestSz); - outPos += 2; - XMEMCPY(dupBuf + outPos, hmacDigest, digestSz); - outPos += digestSz; - XMEMCPY(dupBuf + outPos, plainSens, plainSensSz); - outPos += plainSensSz; - dupSz = (UINT16)outPos; + XMEMCPY(dupBuf + 2 + digestSz, plainSens, plainSensSz); + dupSz = (UINT16)(2 + digestSz + plainSensSz); + rc = FwDupOuterWrap(newParent, seedBuf, seedSz, nameBuf, nameSz, + dupBuf, plainSensSz); } /* Build response: outDuplicate(TPM2B) + outSymSeed(TPM2B) */ @@ -10700,11 +10656,10 @@ static TPM_RC FwCmd_Rewrap(FWTPM_CTX* ctx, TPM2_Packet* cmd, } TPM2_ForceZero(seedBuf, sizeof(seedBuf)); - TPM2_ForceZero(aesKey, sizeof(aesKey)); - TPM2_ForceZero(hmacKeyBuf, sizeof(hmacKeyBuf)); } TPM2_ForceZero(plainSens, FWTPM_MAX_SENSITIVE_SIZE); + TPM2_ForceZero(dupBuf, FWTPM_MAX_PRIVKEY_DER + 256); FWTPM_FREE_BUF(dupBuf); FWTPM_FREE_BUF(symSeedBuf); FWTPM_FREE_BUF(plainSens); From 93190436490cd32804a10730cdc0865cb8074559 Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 24 Nov 2026 15:19:46 -0800 Subject: [PATCH 123/124] Add the session number to fwTPM authorization failure codes --- src/fwtpm/fwtpm_command.c | 3 + tests/fwtpm_unit_tests.c | 115 +++++++++++++++++++++----------------- 2 files changed, 66 insertions(+), 52 deletions(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index 2d3cbfcb6..a1caf68d4 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -24717,6 +24717,7 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, } } #endif + authRc |= TPM_RC_S | (TPM_RC)(TPM_RC_1 * (pj + 1)); *rspSize = FwBuildErrorResponse(rspBuf, rspCap, TPM_ST_NO_SESSIONS, authRc); TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); @@ -24811,6 +24812,7 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, } } #endif + authRc |= TPM_RC_S | (TPM_RC)(TPM_RC_1 * (hj + 1)); *rspSize = FwBuildErrorResponse(rspBuf, rspCap, TPM_ST_NO_SESSIONS, authRc); TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); @@ -24886,6 +24888,7 @@ int FWTPM_ProcessCommand(FWTPM_CTX* ctx, } } #endif + authRc |= TPM_RC_S | (TPM_RC)(TPM_RC_1 * (hj + 1)); *rspSize = FwBuildErrorResponse(rspBuf, rspCap, TPM_ST_NO_SESSIONS, authRc); TPM2_ForceZero(cmdAuths, sizeof(cmdAuths)); diff --git a/tests/fwtpm_unit_tests.c b/tests/fwtpm_unit_tests.c index e093ab8da..3307fa79b 100644 --- a/tests/fwtpm_unit_tests.c +++ b/tests/fwtpm_unit_tests.c @@ -210,6 +210,9 @@ static void ParseRspHeader(const byte* buf, UINT16* tag, UINT32* size, if (rc) *rc = (TPM_RC)GetU32BE(buf + 6); } +/* rc with the number of the session it is reported for */ +#define FW_RC_S(rc, n) ((rc) | TPM_RC_S | (TPM_RC)(TPM_RC_1 * (n))) + /* Get response RC from a response buffer */ static TPM_RC GetRspRC(const byte* rsp) { @@ -2867,7 +2870,7 @@ static void test_fwtpm_pcr_extend_empty_pw_rejected_after_setauth(void) rspSize = 0; rc = FWTPM_ProcessCommand(&ctx, gCmd, cmdSz, gRsp, &rspSize, 0); AssertIntEQ(rc, TPM_RC_SUCCESS); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_BAD_AUTH); + AssertIntEQ(GetRspRC(gRsp), FW_RC_S(TPM_RC_BAD_AUTH, 1)); /* Restore PCR 16 to empty auth so the NV journal doesn't contaminate * later tests that share FWTPM_NV_FILE. */ @@ -15030,7 +15033,7 @@ static void test_fwtpm_nv_policy_auth_proof_required(void) AssertIntEQ(GetRspRC(gRsp), TPM_RC_SUCCESS); AssertIntEQ(SendNvAccessCmd(&ctx, nvIdx, sessH, NULL, 0, 1), - hasAuth ? TPM_RC_BAD_AUTH : TPM_RC_SUCCESS); + hasAuth ? FW_RC_S(TPM_RC_BAD_AUTH, 1) : TPM_RC_SUCCESS); FlushHandle(&ctx, sessH); } @@ -18473,11 +18476,11 @@ static void test_fwtpm_da_platform_exempt(void) AssertIntEQ(fwtpm_test_startup(&ctx), 0); AssertIntEQ(DaSendBadAuthTo(&ctx, TPM_CC_Clear, TPM_RH_PLATFORM), - TPM_RC_BAD_AUTH); + FW_RC_S(TPM_RC_BAD_AUTH, 1)); AssertIntEQ((int)ctx.daFailedTries, 0); /* Repeated failures must neither count nor lock. */ AssertIntEQ(DaSendBadAuthTo(&ctx, TPM_CC_Clear, TPM_RH_PLATFORM), - TPM_RC_BAD_AUTH); + FW_RC_S(TPM_RC_BAD_AUTH, 1)); AssertIntEQ((int)ctx.daFailedTries, 0); AssertIntEQ(ctx.lockoutAuthFailed, 0); @@ -18592,14 +18595,14 @@ static void test_fwtpm_da_noda_object_exempt(void) /* noDA sign key (attr includes TPMA_OBJECT_noDA = 0x400) */ noDaKey = DaMakeEccSignKey(&ctx, 0x00040472); AssertIntNE(noDaKey, 0); - AssertIntEQ(DaSignWrongAuth(&ctx, noDaKey), TPM_RC_BAD_AUTH); + AssertIntEQ(DaSignWrongAuth(&ctx, noDaKey), FW_RC_S(TPM_RC_BAD_AUTH, 1)); AssertIntEQ((int)ctx.daFailedTries, 0); AssertIntEQ(ctx.daUsed, 0); /* DA-protected sign key (no noDA bit) */ daKey = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(daKey, 0); - AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, daKey), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)ctx.daFailedTries, 1); AssertIntEQ(ctx.daUsed, 1); @@ -18625,7 +18628,7 @@ static void test_fwtpm_da_lockout_and_reset(void) key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)DaGetCapProp(&ctx, TPM_PT_LOCKOUT_COUNTER), 1); AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_LOCKOUT); AssertIntEQ((int)DaGetCapProp(&ctx, TPM_PT_LOCKOUT_COUNTER), 2); @@ -18669,13 +18672,13 @@ static void test_fwtpm_da_noda_usable_during_lockout(void) AssertIntNE(daKey, 0); /* Drive lockout with the DA key. */ - AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, daKey), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_LOCKOUT); /* The DA key is now gated... */ AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_LOCKOUT); /* ...but the noDA key is still processed (BAD_AUTH, not LOCKOUT) and does * not feed the counter. */ - AssertIntEQ(DaSignWrongAuth(&ctx, noDaKey), TPM_RC_BAD_AUTH); + AssertIntEQ(DaSignWrongAuth(&ctx, noDaKey), FW_RC_S(TPM_RC_BAD_AUTH, 1)); AssertIntEQ((int)ctx.daFailedTries, 2); FWTPM_Cleanup(&ctx); @@ -18705,8 +18708,8 @@ static void test_fwtpm_da_selfheal(void) key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)ctx.daFailedTries, 2); /* Advance 3s (>= 2 recovery intervals) and run a benign command. */ @@ -18735,8 +18738,8 @@ static void test_fwtpm_da_persist_failedtries(void) AssertIntEQ(DaSetParams(&ctx, 100, 1000, 0), TPM_RC_SUCCESS); key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)ctx.daFailedTries, 2); cmdSz = BuildCmdHeader(gCmd, TPM_ST_NO_SESSIONS, 12, TPM_CC_Shutdown); PutU16BE(gCmd + cmdSz, TPM_SU_CLEAR); cmdSz += 2; @@ -18753,7 +18756,7 @@ static void test_fwtpm_da_persist_failedtries(void) /* One more failure, then drop power without Shutdown (non-orderly). */ key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)ctx.daFailedTries, 3); FWTPM_Cleanup(&ctx); @@ -18791,7 +18794,7 @@ static void test_fwtpm_da_nonorderly_penalty(void) AssertIntEQ(DaSetParams(&ctx, 100, 1000, 0), TPM_RC_SUCCESS); key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)ctx.daFailedTries, 1); FWTPM_Cleanup(&ctx); @@ -18826,7 +18829,7 @@ static void test_fwtpm_da_reboot_in_lockout_recovers(void) AssertIntEQ(DaSetParams(&ctx, 2, 1000, 0), TPM_RC_SUCCESS); key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_LOCKOUT); AssertTrue(ctx.daFailedTries >= ctx.daMaxTries); FWTPM_Cleanup(&ctx); @@ -18893,7 +18896,7 @@ static void test_fwtpm_da_lockoutauth_failure(void) /* The first wrong lockoutAuth reports AUTH_FAIL but arms the lock. */ AssertIntEQ(DaSendLockoutCmd(&ctx, TPM_CC_DictionaryAttackLockReset, - NULL, 0), TPM_RC_AUTH_FAIL); + NULL, 0), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(ctx.lockoutAuthFailed, 1); /* Even the correct auth is now rejected while the lockout lock holds. */ @@ -18955,7 +18958,7 @@ static void test_fwtpm_da_lockoutauth_persist(void) ctx.lockoutAuth.size = (UINT16)sizeof(lkAuth); memcpy(ctx.lockoutAuth.buffer, lkAuth, sizeof(lkAuth)); AssertIntEQ(DaSendLockoutCmd(&ctx, TPM_CC_DictionaryAttackLockReset, - NULL, 0), TPM_RC_AUTH_FAIL); + NULL, 0), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(ctx.lockoutAuthFailed, 1); FWTPM_Cleanup(&ctx); @@ -18973,7 +18976,7 @@ static void test_fwtpm_da_lockoutauth_persist(void) ctx.lockoutAuth.size = (UINT16)sizeof(lkAuth); memcpy(ctx.lockoutAuth.buffer, lkAuth, sizeof(lkAuth)); AssertIntEQ(DaSendLockoutCmd(&ctx, TPM_CC_DictionaryAttackLockReset, - NULL, 0), TPM_RC_AUTH_FAIL); + NULL, 0), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(ctx.lockoutAuthFailed, 1); FWTPM_Cleanup(&ctx); @@ -18994,7 +18997,7 @@ static void test_fwtpm_da_lockoutauth_persist(void) ctx.lockoutAuth.size = (UINT16)sizeof(lkAuth); memcpy(ctx.lockoutAuth.buffer, lkAuth, sizeof(lkAuth)); AssertIntEQ(DaSendLockoutCmd(&ctx, TPM_CC_DictionaryAttackLockReset, - NULL, 0), TPM_RC_AUTH_FAIL); + NULL, 0), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(ctx.lockoutAuthFailed, 1); FWTPM_Cleanup(&ctx); @@ -19020,7 +19023,7 @@ static void test_fwtpm_da_clear_resets(void) key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); /* Drive into full lockout so the inLockout bit is set. */ - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_LOCKOUT); AssertTrue(DaGetCapProp(&ctx, TPM_PT_PERMANENT) & TPMA_PERMANENT_inLockout); @@ -19085,9 +19088,9 @@ static void test_fwtpm_da_selfheal_partial(void) AssertIntEQ(DaSetParams(&ctx, 10, 1 /*sec*/, 0), TPM_RC_SUCCESS); key = DaMakeEccSignKey(&ctx, 0x00040072); AssertIntNE(key, 0); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)ctx.daFailedTries, 3); /* One recovery interval forgives exactly one try (partial). */ @@ -19141,7 +19144,7 @@ static void test_fwtpm_da_hmac_arms_daused(void) PutU32BE(gCmd + 2, (UINT32)pos); FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_AUTH_FAIL); + AssertIntEQ(GetRspRC(gRsp), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(ctx.daUsed, 1); FWTPM_Cleanup(&ctx); @@ -19205,11 +19208,11 @@ static void test_fwtpm_da_bound_session_no_auth_slot(void) /* Unbound, and bound to a noDA object: not counted */ sessH = StartSessionHelper(&ctx, TPM_SE_HMAC); AssertIntNE(sessH, 0); - AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_BAD_AUTH); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), FW_RC_S(TPM_RC_BAD_AUTH, 1)); FlushHandle(&ctx, sessH); sessH = DaStartBoundSession(&ctx, noDaKey); AssertIntNE(sessH, 0); - AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_BAD_AUTH); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), FW_RC_S(TPM_RC_BAD_AUTH, 1)); FlushHandle(&ctx, sessH); AssertIntEQ((int)ctx.daFailedTries, 0); AssertIntEQ(ctx.daUsed, 0); @@ -19217,7 +19220,7 @@ static void test_fwtpm_da_bound_session_no_auth_slot(void) /* Bound to a DA protected object: counted, then locked out */ sessH = DaStartBoundSession(&ctx, daKey); AssertIntNE(sessH, 0); - AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)ctx.daFailedTries, 1); AssertIntEQ(ctx.daUsed, 1); AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_LOCKOUT); @@ -19233,7 +19236,7 @@ static void test_fwtpm_da_bound_session_no_auth_slot(void) AssertIntNE(sessH, 0); FlushHandle(&ctx, daKey); AssertIntEQ(DaMakeEccSignKey(&ctx, 0x00040472), daKey); - AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)ctx.daFailedTries, 1); FlushHandle(&ctx, sessH); AssertIntEQ(SendSimpleSessionCmd(&ctx, TPM_CC_DictionaryAttackLockReset, @@ -19242,7 +19245,7 @@ static void test_fwtpm_da_bound_session_no_auth_slot(void) /* Bound to lockout: locks lockoutAuth without counting a try */ sessH = DaStartBoundSession(&ctx, TPM_RH_LOCKOUT); AssertIntNE(sessH, 0); - AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(ctx.lockoutAuthFailed, 1); AssertIntEQ((int)ctx.daFailedTries, 0); AssertIntEQ(DaGetRandomBadHmac(&ctx, sessH), TPM_RC_LOCKOUT); @@ -19325,7 +19328,7 @@ static void test_fwtpm_da_bound_session_locked_out(void) AssertIntNE(daKey, 0); noDaKey = DaMakeEccSignKey(&ctx, 0x00040472); AssertIntNE(noDaKey, 0); - AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, daKey), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_LOCKOUT); AssertIntEQ((int)ctx.daFailedTries, 2); @@ -19412,7 +19415,7 @@ static void test_fwtpm_da_bound_session_empty_hmac(void) sessH = DaStartBoundSession(&ctx, noDaKey); AssertIntNE(sessH, 0); AssertIntEQ(DaSendEmptyHmac(&ctx, TPM_CC_GetRandom, 0, sessH), - TPM_RC_BAD_AUTH); + FW_RC_S(TPM_RC_BAD_AUTH, 1)); AssertIntEQ((int)ctx.daFailedTries, 0); FlushHandle(&ctx, sessH); @@ -19420,11 +19423,11 @@ static void test_fwtpm_da_bound_session_empty_hmac(void) sessH = DaStartBoundSession(&ctx, daKey); AssertIntNE(sessH, 0); AssertIntEQ(DaSendEmptyHmac(&ctx, TPM_CC_GetRandom, 0, sessH), - TPM_RC_AUTH_FAIL); + FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)ctx.daFailedTries, 1); /* Locked out: refused in every slot */ - AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, daKey), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(DaSignWrongAuth(&ctx, daKey), TPM_RC_LOCKOUT); AssertIntEQ((int)ctx.daFailedTries, 3); AssertIntEQ(DaSendEmptyHmac(&ctx, TPM_CC_GetRandom, 0, sessH), @@ -21684,7 +21687,7 @@ static void test_fwtpm_import_empty_keyedhash_auth(void) &dataSz), TPM_RC_SUCCESS); AssertIntEQ(dataSz, 0); AssertIntEQ(SendUnseal(&ctx, objH, 0, badAuth, sizeof(badAuth) - 1, - &dataSz), TPM_RC_BAD_AUTH); + &dataSz), FW_RC_S(TPM_RC_BAD_AUTH, 1)); #ifndef FWTPM_NO_CONTEXT /* A saved context keeps the sensitive area */ @@ -21727,7 +21730,7 @@ static void test_fwtpm_import_empty_keyedhash_auth(void) &dataSz), TPM_RC_SUCCESS); AssertIntEQ(dataSz, 0); AssertIntEQ(SendUnseal(&ctx, persH, 0, badAuth, sizeof(badAuth) - 1, - &dataSz), TPM_RC_BAD_AUTH); + &dataSz), FW_RC_S(TPM_RC_BAD_AUTH, 1)); pos = BuildCmdHeader(gCmd, TPM_ST_SESSIONS, 0, TPM_CC_EvictControl); PutU32BE(gCmd + pos, TPM_RH_OWNER); pos += 4; PutU32BE(gCmd + pos, persH); pos += 4; @@ -22589,7 +22592,11 @@ static void SweepSessionHmac(FWTPM_CTX* ctx, FWTPM_Session* sess, UINT32 cc, UINT8 attrs = TPMA_SESSION_continueSession | TPMA_SESSION_audit; int pos, rspSize, h, bad, rejected, cpSz = 0; TPM_RC rc; + TPM_RC wantRc = expectRc; + if (expectRc == TPM_RC_BAD_AUTH) { + wantRc |= TPM_RC_S | (withPw ? TPM_RC_2 : TPM_RC_1); + } XMEMSET(nonceCaller, 0x5C, sizeof(nonceCaller)); XMEMCPY(nonceTPM, sess->nonceTPM.buffer, nonceSz); PutU32BE(cpBuf + cpSz, cc); cpSz += 4; @@ -22610,11 +22617,11 @@ static void SweepSessionHmac(FWTPM_CTX* ctx, FWTPM_Session* sess, UINT32 cc, FWTPM_ProcessCommand(ctx, gCmd, pos, gRsp, &rspSize, 0); rc = GetRspRC(gRsp); if (bad) { - if (rc != expectRc) { + if (rc != wantRc) { printf("CC 0x%x (password %d): 0x%x, expected 0x%x\n", - (unsigned)cc, withPw, (unsigned)rc, (unsigned)expectRc); + (unsigned)cc, withPw, (unsigned)rc, (unsigned)wantRc); } - AssertIntEQ(rc, expectRc); + AssertIntEQ(rc, wantRc); AssertIntEQ(sess->nonceTPM.size, nonceSz); AssertIntEQ(XMEMCMP(sess->nonceTPM.buffer, nonceTPM, nonceSz), 0); if (expectRc != TPM_RC_BAD_AUTH) { @@ -22622,7 +22629,8 @@ static void SweepSessionHmac(FWTPM_CTX* ctx, FWTPM_Session* sess, UINT32 cc, } } else { - rejected = (rc == TPM_RC_BAD_AUTH || rc == TPM_RC_AUTH_FAIL); + rejected = ((rc & RC_MAX_FMT1) == TPM_RC_BAD_AUTH || + (rc & RC_MAX_FMT1) == TPM_RC_AUTH_FAIL); if (rejected) { printf("CC 0x%x (password %d): correct HMAC rejected\n", (unsigned)cc, withPw); @@ -23188,7 +23196,7 @@ static void test_fwtpm_param_enc_session_no_handle(void) rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); AssertIntEQ(GetRspRC(gRsp), - withNonce ? TPM_RC_SUCCESS : TPM_RC_BAD_AUTH); + withNonce ? TPM_RC_SUCCESS : FW_RC_S(TPM_RC_BAD_AUTH, 1)); } FlushHandle(&ctx, hmacSess); @@ -23357,7 +23365,7 @@ static void test_fwtpm_param_enc_session_bound_to_auth(void) nonceCaller, plain, sizeof(plain)); rspSize = 0; FWTPM_ProcessCommand(&ctx, gCmd, pos, gRsp, &rspSize, 0); - AssertIntEQ(GetRspRC(gRsp), TPM_RC_BAD_AUTH); + AssertIntEQ(GetRspRC(gRsp), FW_RC_S(TPM_RC_BAD_AUTH, 1)); pos = BuildBoundHmacCmd(gCmd, keyH, name, nameSz, hmacSess, nonceH, nonceHSz, encSess, cont | TPMA_SESSION_encrypt, nonceE, nonceESz, 1, @@ -30396,11 +30404,13 @@ static void test_fwtpm_pcr_auth_startup_clear(void) AssertIntEQ(fwtpm_test_startup(&ctx), 0); AssertIntEQ(SendPcrSetAuthValue(&ctx, FW_TEST_PCR, NULL, 0, pcrAuth, pcrAuthSz), TPM_RC_SUCCESS); - AssertIntEQ(SendPcrExtendLoc(&ctx, FW_TEST_PCR, 0), TPM_RC_BAD_AUTH); + AssertIntEQ(SendPcrExtendLoc(&ctx, FW_TEST_PCR, 0), + FW_RC_S(TPM_RC_BAD_AUTH, 1)); #ifndef FWTPM_NO_NV AssertIntEQ(fwtpm_test_cycle(&ctx, TPM_SU_STATE, TPM_SU_STATE), 0); - AssertIntEQ(SendPcrExtendLoc(&ctx, FW_TEST_PCR, 0), TPM_RC_BAD_AUTH); + AssertIntEQ(SendPcrExtendLoc(&ctx, FW_TEST_PCR, 0), + FW_RC_S(TPM_RC_BAD_AUTH, 1)); AssertIntEQ(fwtpm_test_cycle(&ctx, TPM_SU_STATE, TPM_SU_CLEAR), 0); AssertIntEQ(SendPcrExtendLoc(&ctx, FW_TEST_PCR, 0), TPM_RC_SUCCESS); @@ -31121,7 +31131,7 @@ static void test_fwtpm_da_recovery_zero_disables(void) AssertIntNE(key, 0); for (i = 0; i < 4; i++) { - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ((int)DaGetCapProp(&ctx, TPM_PT_LOCKOUT_COUNTER), 0); } AssertIntEQ(DaGetCapProp(&ctx, TPM_PT_PERMANENT) & @@ -31130,11 +31140,11 @@ static void test_fwtpm_da_recovery_zero_disables(void) /* Failures counted earlier are forgotten at once */ ctx.daFailedTries = 2; AssertIntEQ((int)DaGetCapProp(&ctx, TPM_PT_LOCKOUT_COUNTER), 0); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); /* A non-zero recovery time counts failures again */ AssertIntEQ(DaSetParams(&ctx, 2, 1000, 0), TPM_RC_SUCCESS); - AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_AUTH_FAIL); + AssertIntEQ(DaSignWrongAuth(&ctx, key), FW_RC_S(TPM_RC_AUTH_FAIL, 1)); AssertIntEQ(DaSignWrongAuth(&ctx, key), TPM_RC_LOCKOUT); AssertIntEQ((int)DaGetCapProp(&ctx, TPM_PT_LOCKOUT_COUNTER), 2); @@ -32910,20 +32920,21 @@ static void test_fwtpm_attest_null_signer(void) GetU16BE(gRsp + TPM2_HEADER_SIZE + 4)); } AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_NV_Certify, 0, nvIdx, 1, - TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), TPM_RC_BAD_AUTH); + TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), FW_RC_S(TPM_RC_BAD_AUTH, 1)); AssertIntEQ(SendNvLockCmd(&ctx, TPM_CC_NV_UndefineSpace, nvIdx), TPM_RC_SUCCESS); #endif /* The authValue of TPM_RH_NULL is the Empty Buffer */ AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_GetTime, 0, 0, 0, - TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), TPM_RC_BAD_AUTH); + TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), FW_RC_S(TPM_RC_BAD_AUTH, 2)); AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_Certify, objH, 0, 0, - TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), TPM_RC_BAD_AUTH); + TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), FW_RC_S(TPM_RC_BAD_AUTH, 2)); AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_CertifyCreation, objH, 0, - 0, TPM_ALG_NULL, pw, (int)sizeof(pw), creation), TPM_RC_BAD_AUTH); + 0, TPM_ALG_NULL, pw, (int)sizeof(pw), creation), + FW_RC_S(TPM_RC_BAD_AUTH, 1)); AssertIntEQ(SendAttestNullSigner(&ctx, TPM_CC_Quote, 0, 0, 0, - TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), TPM_RC_BAD_AUTH); + TPM_ALG_NULL, pw, (int)sizeof(pw), NULL), FW_RC_S(TPM_RC_BAD_AUTH, 1)); FlushHandle(&ctx, objH); FWTPM_Cleanup(&ctx); From e596618203b68c7ef74f9f36e69d1e2524092bbc Mon Sep 17 00:00:00 2001 From: David Garske Date: Tue, 24 Nov 2026 15:19:46 -0800 Subject: [PATCH 124/124] Return the parameter number with a fwTPM Load type mismatch --- src/fwtpm/fwtpm_command.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fwtpm/fwtpm_command.c b/src/fwtpm/fwtpm_command.c index a1caf68d4..d4eaaeb24 100644 --- a/src/fwtpm/fwtpm_command.c +++ b/src/fwtpm/fwtpm_command.c @@ -8983,7 +8983,7 @@ static TPM_RC FwCmd_Load(FWTPM_CTX* ctx, TPM2_Packet* cmd, /* Verify type matches */ if (rc == 0) { if (sensitiveType != inPublic.publicArea.type) { - rc = TPM_RC_TYPE; + rc = TPM_RC_TYPE | TPM_RC_P | TPM_RC_1; } }