diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 2e28fcb..574b6a2 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -103,6 +103,9 @@ jobs: - variant: tcg-pure configure: '--enable-nuvoton --enable-nations --enable-responder --disable-mctp' forbid: std + - variant: tpm-profile + configure: '--disable-mctp --enable-tcg --enable-psk --enable-nuvoton --enable-nations CFLAGS=-DWOLFSPDM_PROFILE_TPM' + forbid: std - variant: no-session-ext configure: '--disable-heartbeat --disable-key-update' forbid: tpm @@ -115,6 +118,9 @@ jobs: - variant: no-app-data configure: '--disable-app-data' forbid: tpm + - variant: no-cert-date + configure: 'CFLAGS=-DWOLFSPDM_NO_CERT_DATE_CHECK' + forbid: tpm - variant: lean configure: '--disable-cert --disable-heartbeat --disable-key-update --disable-app-data' forbid: tpm diff --git a/.github/workflows/multi-compiler.yml b/.github/workflows/multi-compiler.yml index 5755d0e..c2a160e 100644 --- a/.github/workflows/multi-compiler.yml +++ b/.github/workflows/multi-compiler.yml @@ -15,7 +15,8 @@ concurrency: jobs: compiler_test: name: ${{ matrix.cc }} - runs-on: ubuntu-latest + # 26.04 dropped the older gcc and clang packages this matrix installs + runs-on: ubuntu-24.04 timeout-minutes: 10 strategy: fail-fast: false @@ -41,7 +42,7 @@ jobs: uses: actions/cache@v4 with: path: ~/wolfssl-install - key: wolfssl-ubuntu-latest-v1 + key: wolfssl-ubuntu-24.04-v1 - name: Build wolfSSL if: steps.cache-wolfssl.outputs.cache-hit != 'true' diff --git a/README.md b/README.md index f53cc65..e536f7c 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,8 @@ sudo ldconfig `--enable-sp` enables Single Precision math with optimized ECC P-384, required for SPDM Algorithm Set B on ARM64 and other constrained targets. `--enable-all` works as a superset. +The responder and TCG builds sign with long-term identity keys, so they also require wolfSSL's default `--enable-harden` (`ECC_TIMING_RESISTANT`). Configure and the build reject a wolfSSL built with `--disable-harden`. + For post-quantum support, build wolfSSL with `--enable-mldsa` (FIPS 204) and/or `--enable-mlkem` (FIPS 203). Use wolfSSL master or a release carrying the `wc_MlDsaKey` and `wc_MlKemKey` APIs. wolfSPDM auto-enables each when the linked wolfSSL provides it (`--disable-mldsa` / `--disable-mlkem` force them off); enabling both gives a fully post-quantum handshake (ML-KEM key exchange + ML-DSA authentication). ## Build diff --git a/configure.ac b/configure.ac index 8825cfd..7e8dbe8 100644 --- a/configure.ac +++ b/configure.ac @@ -307,6 +307,21 @@ if test "x$enable_responder" = "xyes"; then AC_DEFINE([WOLFSPDM_RESPONDER], [1], [Enable the SPDM responder]) fi +# The responder and TCG mutual auth sign with long-term identity keys +if test "x$enable_responder" = "xyes" || test "x$enable_tcg" = "xyes"; then + AC_MSG_CHECKING([for wolfSSL ECC timing resistance]) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ + #include + #include + #ifndef ECC_TIMING_RESISTANT + #error "no ECC timing resistance" + #endif + ]], [[]])], + [AC_MSG_RESULT([yes])], + [AC_MSG_RESULT([no]) + AC_MSG_ERROR([--enable-responder and --enable-tcg require wolfSSL built with --enable-harden (ECC_TIMING_RESISTANT)])]) +fi + AM_CONDITIONAL([BUILD_TCG], [test "x$enable_tcg" = "xyes"]) AM_CONDITIONAL([BUILD_PSK], [test "x$enable_psk" = "xyes"]) AM_CONDITIONAL([BUILD_NUVOTON], [test "x$enable_nuvoton" = "xyes"]) diff --git a/docs/API-Reference.md b/docs/API-Reference.md index f1e2810..e4ecbad 100644 --- a/docs/API-Reference.md +++ b/docs/API-Reference.md @@ -19,7 +19,7 @@ otherwise; failures are negative error codes from `wolfspdm/spdm_error.h`. - `wolfSPDM_SetIO` / `wolfSPDM_HasIO` - `wolfSPDM_SetMode` / `wolfSPDM_GetMode` *(`WOLFSPDM_MODE_AUTO` / `_NUVOTON` / `_NATIONS` / `_NATIONS_PSK`, alias `_PSK` / `_TCG`)*. `_TCG` is the TCG binding with no vendor commands, which is what the SLB9678 uses; `_AUTO` is the standard DMTF requester, so a TPM caller sets the mode explicitly. -- `wolfSPDM_SetResponderPubKey`: pin the responder key (96-byte P-384 X‖Y) for cert-less operation +- `wolfSPDM_SetResponderPubKey`: pin the responder key (96-byte P-384 X‖Y). The TCG binding uses it without a certificate (SlotID 0xFF); the standard binding matches it against the leaf of the retrieved chain, so `KEY_EXCHANGE` returns `WOLFSPDM_E_BAD_STATE` until `GET_CERTIFICATE` has run - `wolfSPDM_SetRequesterKeyPair` *(`WOLFSPDM_MUTUAL_AUTH` builds, TCG or TPM profile)* - `wolfSPDM_SetMaxVersion`: cap the negotiated version (0x12-0x14) - `wolfSPDM_SetRequesterSessionId`: rejects `0x0000`, `0xFFFF`, and low bytes `0x10`-`0x1F` @@ -65,7 +65,7 @@ otherwise; failures are negative error codes from `wolfspdm/spdm_error.h`. ## Session maintenance - `wolfSPDM_Heartbeat` *(`WOLFSPDM_HAS_HEARTBEAT`)* -- `wolfSPDM_KeyUpdate` *(`WOLFSPDM_HAS_KEY_UPDATE`)* +- `wolfSPDM_KeyUpdate` *(`WOLFSPDM_HAS_KEY_UPDATE`)*: if `VerifyNewKey` fails after the responder acknowledged the update, the session ends and must be re-established ## TCG SPDM binding (`wolfspdm/spdm_tcg.h`, `WOLFSPDM_TCG`) diff --git a/docs/Attestation-Notes.md b/docs/Attestation-Notes.md index 1745fc4..69b3943 100644 --- a/docs/Attestation-Notes.md +++ b/docs/Attestation-Notes.md @@ -29,7 +29,9 @@ exchanges: each call restarts the hash at the VCA transcript unless the previous `GET_MEASUREMENTS` left it open (`WOLFSPDM_RUN_OPEN`, i.e. the prior call was unsigned). A signed request closes the run and verifies the signature over it; an unsigned request adds itself to the hash and leaves the -run open for the next call. +run open for the next call. Any other SPDM request sealed in the session ends +an open run, including `KEY_UPDATE` and messages sealed with +`wolfSPDM_EncryptMessage`. Signature verification (measurements and `CHALLENGE_AUTH`) uses whichever asymmetric algorithm was negotiated: ECDSA P-384 or, on SPDM 1.4 with ML-DSA diff --git a/docs/Configuration-and-Macros.md b/docs/Configuration-and-Macros.md index fe547b0..b5b063c 100644 --- a/docs/Configuration-and-Macros.md +++ b/docs/Configuration-and-Macros.md @@ -30,6 +30,18 @@ From `configure.ac`: (42 to `WOLFSPDM_MAX_MSG_SIZE`); smaller values shrink transport buffers and rely more on chunking. +Certificate validity dates are checked against the wolfCrypt clock. On a +target without a clock, or before time sync, define +`CFLAGS=-DWOLFSPDM_NO_CERT_DATE_CHECK` to skip the date checks; wolfSSL's +`NO_ASN_TIME` or `NO_ASN_TIME_CHECK` skips them too. Chain signature, Key +Usage, and CA path length checks still apply. + +Builds that sign with a long-term identity key (`WOLFSPDM_RESPONDER`, and +`WOLFSPDM_MUTUAL_AUTH`, which TCG and the wolfTPM profile turn on) require +wolfSSL's `ECC_TIMING_RESISTANT`. wolfSSL's default `--enable-harden` sets +it. A `user_settings.h` build must define it, or the build stops with an +`#error`. + ## wolfTPM build profile Built inside wolfTPM (`WOLFTPM_SPDM`), `WOLFSPDM_PROFILE_TPM` is implied, and diff --git a/docs/Post-Quantum-ML-KEM.md b/docs/Post-Quantum-ML-KEM.md index b3e9bf2..40e646e 100644 --- a/docs/Post-Quantum-ML-KEM.md +++ b/docs/Post-Quantum-ML-KEM.md @@ -27,9 +27,9 @@ post-quantum SPDM handshake**. (§12.2). TH1/TH2 and all downstream derivation are unchanged from the ECDHE path. -Per FIPS 203 implicit rejection, a `K′ ≠ K` mismatch surfaces only as a FINISH -integrity-check failure and is handled like any other session-message -failure. +With FIPS 203 implicit rejection, decapsulation returns a fallback shared +secret. The requester detects the mismatch when checking `ResponderVerifyData` +in `KEY_EXCHANGE_RSP` and returns `WOLFSPDM_E_BAD_HMAC`. ## How negotiation works diff --git a/examples/spdm_demo.c b/examples/spdm_demo.c index ce70b8d..e97d35c 100644 --- a/examples/spdm_demo.c +++ b/examples/spdm_demo.c @@ -224,7 +224,7 @@ static byte* load_der(const char* path, word32* outSz) if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } sz = ftell(f); if (sz <= 0) { fclose(f); return NULL; } - rewind(f); + if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } buf = (byte*)malloc((size_t)sz); if (buf == NULL) { fclose(f); return NULL; } diff --git a/src/spdm_attest.c b/src/spdm_attest.c index 7bc126d..21d95e7 100644 --- a/src/spdm_attest.c +++ b/src/spdm_attest.c @@ -161,10 +161,10 @@ int wolfSPDM_BuildGetMeasurements(WOLFSPDM_CTX* ctx, byte* buf, rc = wolfSPDM_GetRandom(ctx, &buf[4], SPDM_NONCE_SZ); buf[4 + SPDM_NONCE_SZ] = ctx->currentSlotId; } - if (rc == WOLFSPDM_SUCCESS && ctxSz > 0) { - rc = wolfSPDM_GetRandom(ctx, &buf[sz - ctxSz], ctxSz); - } if (rc == WOLFSPDM_SUCCESS) { + if (ctxSz > 0) { + XMEMSET(&buf[sz - ctxSz], 0, ctxSz); + } *bufSz = sz; } return rc; @@ -271,6 +271,7 @@ int wolfSPDM_GetMeasurements(WOLFSPDM_CTX* ctx, byte measOperation, ctx->measRecordLen = recLen; ctx->measBlockCount = rsp[4]; } + wc_ForceZero(rsp, sizeof(rsp)); return rc; } @@ -351,6 +352,7 @@ int wolfSPDM_M1Add(WOLFSPDM_CTX* ctx, const byte* req, word32 reqSz, int wolfSPDM_BuildChallenge(WOLFSPDM_CTX* ctx, byte* buf, word32* bufSz, int slotId, byte measHashType) { + word32 ctxSz; word32 sz; int rc; @@ -358,7 +360,8 @@ int wolfSPDM_BuildChallenge(WOLFSPDM_CTX* ctx, byte* buf, word32* bufSz, slotId > 7) { return WOLFSPDM_E_INVALID_ARG; } - sz = 4 + SPDM_NONCE_SZ + wolfSPDM_ReqContextSz(ctx); + ctxSz = wolfSPDM_ReqContextSz(ctx); + sz = 4 + SPDM_NONCE_SZ + ctxSz; if (*bufSz < sz) { return WOLFSPDM_E_BUFFER_SMALL; } @@ -367,9 +370,11 @@ int wolfSPDM_BuildChallenge(WOLFSPDM_CTX* ctx, byte* buf, word32* bufSz, buf[1] = SPDM_CHALLENGE; buf[2] = (byte)slotId; buf[3] = measHashType; - /* Nonce, then the 1.3+ RequesterContext */ - rc = wolfSPDM_GetRandom(ctx, &buf[4], sz - 4); + rc = wolfSPDM_GetRandom(ctx, &buf[4], SPDM_NONCE_SZ); if (rc == WOLFSPDM_SUCCESS) { + if (ctxSz > 0) { + XMEMSET(&buf[4 + SPDM_NONCE_SZ], 0, ctxSz); + } *bufSz = sz; } return rc; @@ -409,7 +414,9 @@ int wolfSPDM_Challenge(WOLFSPDM_CTX* ctx, int slotId, byte measHashType) word32 sigOff = 0; int rc; - if (ctx == NULL) { + if (ctx == NULL || (measHashType != SPDM_MEAS_SUMMARY_HASH_NONE && + measHashType != SPDM_MEAS_SUMMARY_HASH_TCB && + measHashType != SPDM_MEAS_SUMMARY_HASH_ALL)) { return WOLFSPDM_E_INVALID_ARG; } /* M1 covers the chain fetched for this slot */ @@ -419,7 +426,10 @@ int wolfSPDM_Challenge(WOLFSPDM_CTX* ctx, int slotId, byte measHashType) slotId != (int)ctx->currentSlotId) { return WOLFSPDM_E_BAD_STATE; } - if ((ctx->rspCaps & SPDM_CAP_CHAL_CAP) == 0) { + if ((ctx->rspCaps & SPDM_CAP_CHAL_CAP) == 0 || + (measHashType != SPDM_MEAS_SUMMARY_HASH_NONE && + (ctx->rspCaps & (SPDM_CAP_MEAS_CAP_NO_SIG | + SPDM_CAP_MEAS_CAP_SIG)) == 0)) { return WOLFSPDM_E_CAPS_MISMATCH; } diff --git a/src/spdm_context.c b/src/spdm_context.c index d04689c..bc61cf0 100644 --- a/src/spdm_context.c +++ b/src/spdm_context.c @@ -168,6 +168,9 @@ int wolfSPDM_SetResponderPubKey(WOLFSPDM_CTX* ctx, if (pubKeySz != WOLFSPDM_ECC_POINT_SIZE) { return WOLFSPDM_E_INVALID_ARG; } + if (pubKeySz > sizeof(ctx->rspPubKey)) { + return WOLFSPDM_E_BUFFER_SMALL; + } XMEMCPY(ctx->rspPubKey, pubKey, pubKeySz); ctx->rspPubKeyLen = pubKeySz; @@ -420,8 +423,9 @@ int wolfSPDM_Connect(WOLFSPDM_CTX* ctx) return WOLFSPDM_E_INVALID_ARG; } -/* Drop session state and wipe session-scoped secrets; configured identity - * keys, PSK and trust anchors stay for a later connection */ +/* Drop session state and wipe session-scoped secrets. Configured identity + * keys, trust anchors and an unused PSK stay in the context. Set the PSK again + * with wolfSPDM_SetPSK when key derivation has consumed it. */ void wolfSPDM_ResetSession(WOLFSPDM_CTX* ctx) { ctx->state = WOLFSPDM_STATE_INIT; @@ -432,26 +436,14 @@ void wolfSPDM_ResetSession(WOLFSPDM_CTX* ctx) ctx->mutAuthRequested = 0; ctx->reqSlotIdParam = 0; /* App data keys */ - wc_ForceZero(ctx->reqDataKey, sizeof(ctx->reqDataKey)); - wc_ForceZero(ctx->rspDataKey, sizeof(ctx->rspDataKey)); - wc_ForceZero(ctx->reqDataIv, sizeof(ctx->reqDataIv)); - wc_ForceZero(ctx->rspDataIv, sizeof(ctx->rspDataIv)); + wolfSPDM_ClearTrafficKeys(ctx); #ifndef WOLFSPDM_NO_KEY_UPDATE wc_ForceZero(ctx->reqAppSecret, sizeof(ctx->reqAppSecret)); wc_ForceZero(ctx->rspAppSecret, sizeof(ctx->rspAppSecret)); #endif - /* Handshake keys */ - wc_ForceZero(ctx->reqHsSecret, sizeof(ctx->reqHsSecret)); - wc_ForceZero(ctx->rspHsSecret, sizeof(ctx->rspHsSecret)); - wc_ForceZero(ctx->reqFinishedKey, sizeof(ctx->reqFinishedKey)); - wc_ForceZero(ctx->rspFinishedKey, sizeof(ctx->rspFinishedKey)); - /* Secrets and hashes */ - wc_ForceZero(ctx->handshakeSecret, sizeof(ctx->handshakeSecret)); - wc_ForceZero(ctx->sharedSecret, sizeof(ctx->sharedSecret)); - ctx->sharedSecretSz = 0; + wolfSPDM_ClearHandshakeSecrets(ctx); wc_ForceZero(ctx->th1, sizeof(ctx->th1)); wc_ForceZero(ctx->th2, sizeof(ctx->th2)); - wolfSPDM_FreeEphemeralKey(ctx); #ifndef WOLFSPDM_NO_CERT ctx->rspCaps = 0; ctx->dataTransferSize = 0; @@ -460,12 +452,19 @@ void wolfSPDM_ResetSession(WOLFSPDM_CTX* ctx) #ifndef WOLFSPDM_NO_MEAS ctx->measBlockCount = 0; ctx->measRecordLen = 0; + wc_ForceZero(ctx->measRecord, sizeof(ctx->measRecord)); #endif #if !defined(WOLFSPDM_NO_MEAS) || !defined(WOLFSPDM_NO_CHALLENGE) wolfSPDM_AttestFree(ctx); #endif } +void wolfSPDM_RetireSession(WOLFSPDM_CTX* ctx) +{ + wolfSPDM_ResetSession(ctx); + ctx->state = WOLFSPDM_STATE_ERROR; +} + int wolfSPDM_Disconnect(WOLFSPDM_CTX* ctx) { int rc = WOLFSPDM_E_NOT_CONNECTED; @@ -480,6 +479,7 @@ int wolfSPDM_Disconnect(WOLFSPDM_CTX* ctx) byte rxBuf[16]; /* END_SESSION_ACK: 4 bytes */ word32 txSz = sizeof(txBuf); word32 rxSz; + int peerError = 0; rc = wolfSPDM_BuildEndSession(ctx, txBuf, &txSz); if (rc == WOLFSPDM_SUCCESS) { @@ -490,12 +490,12 @@ int wolfSPDM_Disconnect(WOLFSPDM_CTX* ctx) if (rxSz < 4) { rc = WOLFSPDM_E_BUFFER_SMALL; } - else if (wolfSPDM_CheckError(rxBuf, rxSz, NULL)) { + else if (wolfSPDM_CheckError(rxBuf, rxSz, &peerError)) { + ctx->lastPeerErrorCode = (byte)peerError; rc = WOLFSPDM_E_PEER_ERROR; } else if (rxSz != 4 || rxBuf[0] != ctx->spdmVersion || - rxBuf[1] != SPDM_END_SESSION_ACK || - rxBuf[2] != 0 || rxBuf[3] != 0) { + rxBuf[1] != SPDM_END_SESSION_ACK) { rc = WOLFSPDM_E_PEER_ERROR; } } @@ -573,12 +573,6 @@ static int wolfSPDM_TcgSendReceive(WOLFSPDM_CTX* ctx, } } if (rc == WOLFSPDM_SUCCESS) { - /* Capture FIPS indicator from response if non-zero */ - tag = SPDM_Get16BE(tcgRx + 10); - if (tag != 0) { - ctx->fipsIndicator = tag; - } - /* Extract payload (everything after 16-byte TCG header) */ msgSize = SPDM_Get32BE(tcgRx + 2); if (msgSize < WOLFSPDM_TCG_HEADER_SIZE || msgSize > tcgRxSz) { @@ -598,6 +592,12 @@ static int wolfSPDM_TcgSendReceive(WOLFSPDM_CTX* ctx, *rxSz = payloadSz; } } + /* Each exchange replaces the indicator; only an exact APPROVED counts */ + ctx->fipsIndicator = WOLFSPDM_FIPS_NON_FIPS; + if (rc == WOLFSPDM_SUCCESS && + SPDM_Get16BE(tcgRx + 10) == WOLFSPDM_FIPS_APPROVED) { + ctx->fipsIndicator = WOLFSPDM_FIPS_APPROVED; + } /* Clear vendor messages carry PSK material */ wc_ForceZero(tcgTx, sizeof(tcgTx)); diff --git a/src/spdm_crypto.c b/src/spdm_crypto.c index 6a701f9..5648785 100644 --- a/src/spdm_crypto.c +++ b/src/spdm_crypto.c @@ -298,8 +298,9 @@ int wolfSPDM_GenerateMlKemKey(WOLFSPDM_CTX* ctx, byte* ek, word32* ekSz) return rc; } -/* Recover the shared secret from the responder's ciphertext; FIPS 203 - * implicit rejection means a bad ciphertext only shows up at FINISH */ +/* Recover the shared secret from the responder's ciphertext. After FIPS 203 + * implicit rejection, the secret mismatch is detected when verifying + * ResponderVerifyData in KEY_EXCHANGE_RSP. */ int wolfSPDM_MlKemDecapsulate(WOLFSPDM_CTX* ctx, const byte* ct, word32 ctSz) { word32 expCtSz = 0; diff --git a/src/spdm_internal.h b/src/spdm_internal.h index 3d63565..05f749a 100644 --- a/src/spdm_internal.h +++ b/src/spdm_internal.h @@ -40,6 +40,12 @@ /* cppcheck-suppress preprocessorErrorDirective */ #error "wolfSPDM requires SHA-384 (--enable-sha384 in wolfSSL)" #endif +/* A peer can make these builds sign with a long-term identity key */ +#if (defined(WOLFSPDM_RESPONDER) || defined(WOLFSPDM_MUTUAL_AUTH)) && \ + !defined(ECC_TIMING_RESISTANT) + /* cppcheck-suppress preprocessorErrorDirective */ + #error "wolfSPDM signing requires ECC_TIMING_RESISTANT (--enable-harden in wolfSSL)" +#endif #include #include #include @@ -484,16 +490,14 @@ static WC_INLINE void wolfSPDM_BuildIV(byte* iv, const byte* baseIv, /* ----- Response Code Check Macro ----- */ +WOLFSPDM_LOCAL int wolfSPDM_CheckResponse(WOLFSPDM_CTX* ctx, const byte* buf, + word32 bufSz, byte expected, int fallbackErr); #define SPDM_CHECK_RESPONSE(ctx, buf, bufSz, expected, fallbackErr) \ do { \ - if ((buf)[1] != (expected)) { \ - int _ec; \ - if (wolfSPDM_CheckError((buf), (bufSz), &_ec)) { \ - (ctx)->lastPeerErrorCode = (byte)_ec; \ - wolfSPDM_DebugPrint((ctx), "SPDM error: 0x%02x\n", _ec); \ - return WOLFSPDM_E_PEER_ERROR; \ - } \ - return (fallbackErr); \ + int _crc = wolfSPDM_CheckResponse((ctx), (buf), (bufSz), \ + (expected), (fallbackErr)); \ + if (_crc != WOLFSPDM_SUCCESS) { \ + return _crc; \ } \ } while (0) @@ -543,6 +547,11 @@ WOLFSPDM_API int wolfSPDM_MlKemDecapsulate(WOLFSPDM_CTX* ctx, const byte* ct, WOLFSPDM_API int wolfSPDM_DeriveHandshakeKeys(WOLFSPDM_CTX* ctx, const byte* th1Hash); WOLFSPDM_API int wolfSPDM_DeriveFromHandshakeSecret(WOLFSPDM_CTX* ctx, const byte* th1Hash); +WOLFSPDM_LOCAL void wolfSPDM_ClearHandshakeSecrets(WOLFSPDM_CTX* ctx); +WOLFSPDM_LOCAL void wolfSPDM_ClearTrafficKeys(WOLFSPDM_CTX* ctx); +WOLFSPDM_LOCAL void wolfSPDM_RetireSession(WOLFSPDM_CTX* ctx); +WOLFSPDM_LOCAL int wolfSPDM_FinishRspLen(WOLFSPDM_CTX* ctx, const byte* buf, + word32 bufSz, word32* rspMsgLen); WOLFSPDM_API int wolfSPDM_DeriveAppDataKeys(WOLFSPDM_CTX* ctx); WOLFSPDM_API int wolfSPDM_HkdfExpandLabel(byte spdmVersion, const byte* secret, word32 secretSz, const char* label, const byte* context, word32 contextSz, @@ -584,6 +593,13 @@ WOLFSPDM_API int wolfSPDM_EncryptInternal(WOLFSPDM_CTX* ctx, WOLFSPDM_API int wolfSPDM_DecryptInternal(WOLFSPDM_CTX* ctx, const byte* enc, word32 encSz, byte* plain, word32* plainSz); +WOLFSPDM_LOCAL int wolfSPDM_ClearPeerError(WOLFSPDM_CTX* ctx, + const byte* rx, word32 rxSz); +#ifdef WOLFSPDM_RESPONDER +WOLFSPDM_LOCAL int wolfSPDM_DecryptRequest(WOLFSPDM_CTX* ctx, + const byte* enc, word32 encSz, + byte* plain, word32* plainSz); +#endif /* ----- Internal Utility Functions ----- */ @@ -613,10 +629,11 @@ WOLFSPDM_LOCAL int wolfSPDM_KeyExchangeValidated(WOLFSPDM_CTX* ctx); #endif #if !defined(WOLFSPDM_NO_MEAS) || !defined(WOLFSPDM_NO_CHALLENGE) -/* Running transcript hash states */ +/* Running transcript hash states. M1 can still append in RUN_LIVE. + * L1/L2 continues across GET_MEASUREMENTS exchanges only in RUN_OPEN. */ #define WOLFSPDM_RUN_NONE 0 -#define WOLFSPDM_RUN_LIVE 1 /* initialized, not extendable */ -#define WOLFSPDM_RUN_OPEN 2 /* extendable by the next message */ +#define WOLFSPDM_RUN_LIVE 1 /* hash initialized */ +#define WOLFSPDM_RUN_OPEN 2 /* L1/L2 measurement run open */ WOLFSPDM_LOCAL void wolfSPDM_AttestFree(WOLFSPDM_CTX* ctx); #endif #ifndef WOLFSPDM_NO_MEAS diff --git a/src/spdm_kdf.c b/src/spdm_kdf.c index b58b310..1d057ef 100644 --- a/src/spdm_kdf.c +++ b/src/spdm_kdf.c @@ -25,8 +25,9 @@ #include "spdm_internal.h" -/* SPDM key derivation (DSP0277): HKDF with - * info = Length(2,LE) || "spdm1.2 " || Label || Context. */ +/* SPDM key derivation (DSP0274) uses HKDF with + * info = Length (2 bytes, little endian) || "spdmX.Y " || Label || Context. + * X.Y is the negotiated SPDM version. */ int wolfSPDM_HkdfExpandLabel(byte spdmVersion, const byte* secret, word32 secretSz, const char* label, const byte* context, word32 contextSz, @@ -100,18 +101,13 @@ int wolfSPDM_ComputeVerifyData(const byte* finishedKey, const byte* thHash, } rc = wc_HmacSetKey(&hmac, WC_SHA384, finishedKey, WOLFSPDM_HASH_SIZE); - if (rc != 0) { - wc_HmacFree(&hmac); - return WOLFSPDM_E_CRYPTO_FAIL; + if (rc == 0) { + rc = wc_HmacUpdate(&hmac, thHash, WOLFSPDM_HASH_SIZE); } - - rc = wc_HmacUpdate(&hmac, thHash, WOLFSPDM_HASH_SIZE); - if (rc != 0) { - wc_HmacFree(&hmac); - return WOLFSPDM_E_CRYPTO_FAIL; + if (rc == 0) { + rc = wc_HmacFinal(&hmac, verifyData); } - rc = wc_HmacFinal(&hmac, verifyData); wc_HmacFree(&hmac); wc_ForceZero(&hmac, sizeof(hmac)); @@ -173,16 +169,13 @@ int wolfSPDM_DeriveFromHandshakeSecret(WOLFSPDM_CTX* ctx, } if (rc != WOLFSPDM_SUCCESS) { - /* wipe any partially derived material so it cannot carry into a - * reused ctx */ + /* Wipe the root and any partially derived material. */ + wc_ForceZero(ctx->handshakeSecret, sizeof(ctx->handshakeSecret)); wc_ForceZero(ctx->reqHsSecret, sizeof(ctx->reqHsSecret)); wc_ForceZero(ctx->rspHsSecret, sizeof(ctx->rspHsSecret)); wc_ForceZero(ctx->reqFinishedKey, sizeof(ctx->reqFinishedKey)); wc_ForceZero(ctx->rspFinishedKey, sizeof(ctx->rspFinishedKey)); - wc_ForceZero(ctx->reqDataKey, sizeof(ctx->reqDataKey)); - wc_ForceZero(ctx->rspDataKey, sizeof(ctx->rspDataKey)); - wc_ForceZero(ctx->reqDataIv, sizeof(ctx->reqDataIv)); - wc_ForceZero(ctx->rspDataIv, sizeof(ctx->rspDataIv)); + wolfSPDM_ClearTrafficKeys(ctx); } return rc; @@ -213,6 +206,26 @@ int wolfSPDM_DeriveHandshakeKeys(WOLFSPDM_CTX* ctx, const byte* th1Hash) /* PSK key derivation moved to spdm_psk.c */ +void wolfSPDM_ClearTrafficKeys(WOLFSPDM_CTX* ctx) +{ + wc_ForceZero(ctx->reqDataKey, sizeof(ctx->reqDataKey)); + wc_ForceZero(ctx->rspDataKey, sizeof(ctx->rspDataKey)); + wc_ForceZero(ctx->reqDataIv, sizeof(ctx->reqDataIv)); + wc_ForceZero(ctx->rspDataIv, sizeof(ctx->rspDataIv)); +} + +void wolfSPDM_ClearHandshakeSecrets(WOLFSPDM_CTX* ctx) +{ + wc_ForceZero(ctx->sharedSecret, sizeof(ctx->sharedSecret)); + ctx->sharedSecretSz = 0; + wc_ForceZero(ctx->handshakeSecret, sizeof(ctx->handshakeSecret)); + wc_ForceZero(ctx->reqHsSecret, sizeof(ctx->reqHsSecret)); + wc_ForceZero(ctx->rspHsSecret, sizeof(ctx->rspHsSecret)); + wc_ForceZero(ctx->reqFinishedKey, sizeof(ctx->reqFinishedKey)); + wc_ForceZero(ctx->rspFinishedKey, sizeof(ctx->rspFinishedKey)); + wolfSPDM_FreeEphemeralKey(ctx); +} + int wolfSPDM_DeriveAppDataKeys(WOLFSPDM_CTX* ctx) { byte th2Hash[WOLFSPDM_HASH_SIZE]; @@ -274,6 +287,7 @@ int wolfSPDM_DeriveAppDataKeys(WOLFSPDM_CTX* ctx) XMEMCPY(ctx->reqAppSecret, reqAppSecret, WOLFSPDM_HASH_SIZE); XMEMCPY(ctx->rspAppSecret, rspAppSecret, WOLFSPDM_HASH_SIZE); #endif + wolfSPDM_ClearHandshakeSecrets(ctx); /* Reset sequence numbers for application phase */ ctx->reqSeqNum = 0; ctx->rspSeqNum = 0; diff --git a/src/spdm_msg.c b/src/spdm_msg.c index bac56e9..46c41ce 100644 --- a/src/spdm_msg.c +++ b/src/spdm_msg.c @@ -136,6 +136,14 @@ int wolfSPDM_BuildKeyExchange(WOLFSPDM_CTX* ctx, byte* buf, word32* bufSz) if (ctx == NULL) { return WOLFSPDM_E_INVALID_ARG; } +#ifndef WOLFSPDM_NO_CERT + /* The standard binding defines no provisioned-key format for Ct, so a + * pin needs a retrieved chain to name a slot (DSP0274 KEY_EXCHANGE). */ + if (!wolfSPDM_IsTcgMode(ctx) && ctx->flags.hasRspPubKey && + !ctx->flags.rspKeyFromCert && ctx->certChainLen == 0) { + return WOLFSPDM_E_BAD_STATE; + } +#endif wolfSPDM_KeyExOpaque(ctx, &opaque, &opaqueSz); if (opaque == NULL) { return WOLFSPDM_E_NOT_AVAILABLE; @@ -448,6 +456,52 @@ int wolfSPDM_BuildEndSession(WOLFSPDM_CTX* ctx, byte* buf, word32* bufSz) return wolfSPDM_BuildSimpleMsg(ctx, SPDM_END_SESSION, buf, bufSz); } +int wolfSPDM_CheckResponse(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz, + byte expected, int fallbackErr) +{ + int ec; + + if (buf[1] != expected) { + if (wolfSPDM_CheckError(buf, bufSz, &ec)) { + ctx->lastPeerErrorCode = (byte)ec; + wolfSPDM_DebugPrint(ctx, "SPDM error: 0x%02x\n", ec); + return WOLFSPDM_E_PEER_ERROR; + } + return fallbackErr; + } + if (expected != SPDM_VERSION && ctx->spdmVersion != 0 && + buf[0] != ctx->spdmVersion) { + return fallbackErr; + } + return WOLFSPDM_SUCCESS; +} + +/* FINISH_RSP and PSK_FINISH_RSP: header(4) [+ OpaqueLength(2) + Opaque, 1.4] */ +int wolfSPDM_FinishRspLen(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz, + word32* rspMsgLen) +{ + if (ctx->spdmVersion != 0 && buf[0] != ctx->spdmVersion) { + return WOLFSPDM_E_BAD_STATE; + } + *rspMsgLen = 4; + if (ctx->spdmVersion >= SPDM_VERSION_14) { + word16 opaqueLen; + + if (bufSz < 6) { + return WOLFSPDM_E_BUFFER_SMALL; + } + opaqueLen = SPDM_Get16LE(&buf[4]); + if (opaqueLen > WOLFSPDM_FINISH_OPAQUE_MAX) { + return WOLFSPDM_E_INVALID_ARG; + } + *rspMsgLen = 4 + 2 + (word32)opaqueLen; + if (bufSz < *rspMsgLen) { + return WOLFSPDM_E_BUFFER_SMALL; + } + } + return WOLFSPDM_SUCCESS; +} + int wolfSPDM_CheckError(const byte* buf, word32 bufSz, int* errorCode) { if (buf == NULL || bufSz < 4) { @@ -470,16 +524,20 @@ int wolfSPDM_ParseVersion(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz) word32 i; byte highestVersion = 0; /* No version found yet */ byte maxVer; + int legacyCount; SPDM_CHECK_PARSE_OR_ERROR_ARGS(ctx, buf, bufSz, 6); SPDM_CHECK_RESPONSE(ctx, buf, bufSz, SPDM_VERSION, WOLFSPDM_E_VERSION_MISMATCH); - /* VersionNumberEntryCount is the one-byte field at offset 5 (byte 4 - * reserved) per DSP0274; older wolfTPM responders placed it at - * offset 4, so fall back to that when offset 5 is zero. - * Offset 6+: VersionNumberEntry array (2 bytes each, LE) */ + /* DSP0274 puts the count at offset 5; older wolfTPM responders used 4. + * Allow that only for TCG, which is all the TPM profile speaks. */ +#ifdef WOLFSPDM_PROFILE_TPM + legacyCount = 1; +#else + legacyCount = wolfSPDM_IsTcgMode(ctx); +#endif entryCount = buf[5]; - if (entryCount == 0) { + if (entryCount == 0 && legacyCount) { entryCount = buf[4]; } @@ -518,7 +576,8 @@ int wolfSPDM_ParseVersion(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz) return WOLFSPDM_SUCCESS; } -int wolfSPDM_ParseKeyExchangeRsp(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz) +static int wolfSPDM_ProcessKeyExchangeRsp(WOLFSPDM_CTX* ctx, const byte* buf, + word32 bufSz) { word32 exSz = WOLFSPDM_ECC_POINT_SIZE; word32 sigSz; @@ -528,6 +587,7 @@ int wolfSPDM_ParseKeyExchangeRsp(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufS byte expectedHmac[WOLFSPDM_HASH_SIZE]; const byte* signature; const byte* rspVerifyData; + int haveSharedSecret = 0; int rc; SPDM_CHECK_PARSE_OR_ERROR_ARGS(ctx, buf, bufSz, 140); @@ -592,6 +652,7 @@ int wolfSPDM_ParseKeyExchangeRsp(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufS &buf[40 + WOLFSPDM_ECC_KEY_SIZE]); } if (rc == WOLFSPDM_SUCCESS) { + haveSharedSecret = 1; rc = wolfSPDM_TranscriptHash(ctx, ctx->th1); } if (rc == WOLFSPDM_SUCCESS) { @@ -619,36 +680,38 @@ int wolfSPDM_ParseKeyExchangeRsp(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufS ctx->reqSlotIdParam = buf[7]; ctx->state = WOLFSPDM_STATE_KEY_EX; } + else if (haveSharedSecret) { + wolfSPDM_ClearTrafficKeys(ctx); + ctx->state = WOLFSPDM_STATE_ERROR; + } wc_ForceZero(expectedHmac, sizeof(expectedHmac)); wc_ForceZero(th1SigHash, sizeof(th1SigHash)); return rc; } +int wolfSPDM_ParseKeyExchangeRsp(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz) +{ + int rc = wolfSPDM_ProcessKeyExchangeRsp(ctx, buf, bufSz); + + if (rc != WOLFSPDM_SUCCESS && ctx != NULL && ctx->flags.ephemeralKeyInit) { + wolfSPDM_ClearHandshakeSecrets(ctx); + } + return rc; +} + int wolfSPDM_ParseFinishRsp(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz) { SPDM_CHECK_PARSE_ARGS(ctx, buf, bufSz, 4); if (buf[1] == SPDM_FINISH_RSP) { int addRc; - word32 rspMsgLen = 4; - - /* SPDM 1.4 adds OpaqueLength(2) + OpaqueData(var) to FINISH_RSP */ - if (ctx->spdmVersion >= SPDM_VERSION_14) { - word16 opaqueLen; - if (bufSz < 6) { - return WOLFSPDM_E_BUFFER_SMALL; - } - opaqueLen = SPDM_Get16LE(&buf[4]); - if (opaqueLen > WOLFSPDM_FINISH_OPAQUE_MAX) { - return WOLFSPDM_E_INVALID_ARG; - } - rspMsgLen = 4 + 2 + opaqueLen; - if (bufSz < rspMsgLen) { - return WOLFSPDM_E_BUFFER_SMALL; - } - } + word32 rspMsgLen; + addRc = wolfSPDM_FinishRspLen(ctx, buf, bufSz, &rspMsgLen); + if (addRc != WOLFSPDM_SUCCESS) { + return addRc; + } /* Add FINISH_RSP (header + OpaqueData for 1.4) to transcript */ addRc = wolfSPDM_TranscriptAdd(ctx, buf, rspMsgLen); if (addRc != WOLFSPDM_SUCCESS) { @@ -660,6 +723,7 @@ int wolfSPDM_ParseFinishRsp(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz) } if (buf[1] == SPDM_ERROR) { + ctx->lastPeerErrorCode = buf[2]; wolfSPDM_DebugPrint(ctx, "FINISH error: 0x%02x\n", buf[2]); return WOLFSPDM_E_PEER_ERROR; } diff --git a/src/spdm_psk.c b/src/spdm_psk.c index 37eb50e..35adc2f 100644 --- a/src/spdm_psk.c +++ b/src/spdm_psk.c @@ -130,27 +130,29 @@ int wolfSPDM_BuildPskExchange(WOLFSPDM_CTX* ctx, byte* buf, word32* bufSz) int wolfSPDM_ParsePskExchangeRsp(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz) { + const word32 fixedSz = 12; word16 rspContextLen, opaqueLen; word32 verifyOffset; word32 rspPartialLen; byte th1Hash[WOLFSPDM_HASH_SIZE]; byte expectedHmac[WOLFSPDM_HASH_SIZE]; const byte* rspVerifyData; + int usedPsk = 0; int rc; - /* Minimum: header(4) + RspSessionID(2) + Reserved(1) + RspContextLen(2) + - * OpaqueLen(2) + VerifyData(48) = 59 */ - SPDM_CHECK_PARSE_OR_ERROR_ARGS(ctx, buf, bufSz, 59); + /* The fixed fields take 12 bytes, followed by variable fields and + * ResponderVerifyData. */ + SPDM_CHECK_PARSE_OR_ERROR_ARGS(ctx, buf, bufSz, + fixedSz + WOLFSPDM_HASH_SIZE); SPDM_CHECK_RESPONSE(ctx, buf, bufSz, SPDM_PSK_EXCHANGE_RSP, WOLFSPDM_E_KEY_EXCHANGE); - /* Per SPDM 1.3 DSP0274 Table 65: - * [4-5] RspSessionID, [6] MutAuthRequested, [7] ReqSlotIDParam, - * [8-9] RspContextLength, [10-11] OpaqueDataLength */ + /* DSP0274 places RspSessionID at bytes 4-5 and reserves bytes 6-7. + * Bytes 8-9 hold ResponderContext length and 10-11 OpaqueDataLength. */ rspContextLen = SPDM_Get16LE(&buf[8]); opaqueLen = SPDM_Get16LE(&buf[10]); - verifyOffset = 12 + (word32)rspContextLen + opaqueLen; + verifyOffset = fixedSz + (word32)rspContextLen + opaqueLen; rspPartialLen = verifyOffset; if (bufSz < verifyOffset + WOLFSPDM_HASH_SIZE) { @@ -168,6 +170,7 @@ int wolfSPDM_ParsePskExchangeRsp(WOLFSPDM_CTX* ctx, const byte* buf, } if (rc == WOLFSPDM_SUCCESS) { XMEMCPY(ctx->th1, th1Hash, WOLFSPDM_HASH_SIZE); + usedPsk = (ctx->pskSz != 0); rc = wolfSPDM_DeriveHandshakeKeysPsk(ctx, th1Hash); } @@ -177,8 +180,6 @@ int wolfSPDM_ParsePskExchangeRsp(WOLFSPDM_CTX* ctx, const byte* buf, expectedHmac); } if (rc == WOLFSPDM_SUCCESS) { - wolfSPDM_DebugHex(ctx, "Expected HMAC", expectedHmac, - WOLFSPDM_HASH_SIZE); wolfSPDM_DebugHex(ctx, "Received HMAC", rspVerifyData, WOLFSPDM_HASH_SIZE); if (wolfSPDM_ConstCompare(expectedHmac, rspVerifyData, @@ -198,6 +199,9 @@ int wolfSPDM_ParsePskExchangeRsp(WOLFSPDM_CTX* ctx, const byte* buf, ((word32)ctx->rspSessionId << 16); ctx->state = WOLFSPDM_STATE_KEY_EX; } + else if (usedPsk) { + wolfSPDM_RetireSession(ctx); + } wc_ForceZero(expectedHmac, sizeof(expectedHmac)); wc_ForceZero(th1Hash, sizeof(th1Hash)); @@ -209,14 +213,19 @@ int wolfSPDM_BuildPskFinish(WOLFSPDM_CTX* ctx, byte* buf, word32* bufSz) byte th2Hash[WOLFSPDM_HASH_SIZE]; byte verifyData[WOLFSPDM_HASH_SIZE]; word32 offset = 0; + word32 minSz; int rc; if (ctx == NULL || buf == NULL || bufSz == NULL) { return WOLFSPDM_E_INVALID_ARG; } - /* PSK_FINISH = header(4) + VerifyData(48) = 52 bytes */ - if (*bufSz < 4 + WOLFSPDM_HASH_SIZE) { + /* header(4) + [OpaqueDataLength(2) for 1.4+] + VerifyData(48) */ + minSz = 4 + WOLFSPDM_HASH_SIZE; + if (ctx->spdmVersion >= SPDM_VERSION_14) { + minSz += 2; + } + if (*bufSz < minSz) { return WOLFSPDM_E_BUFFER_SMALL; } @@ -225,8 +234,12 @@ int wolfSPDM_BuildPskFinish(WOLFSPDM_CTX* ctx, byte* buf, word32* bufSz) buf[offset++] = SPDM_PSK_FINISH; buf[offset++] = 0x00; /* Param1 */ buf[offset++] = 0x00; /* Param2 */ + if (ctx->spdmVersion >= SPDM_VERSION_14) { + buf[offset++] = 0x00; /* OpaqueDataLength = 0 (LE) */ + buf[offset++] = 0x00; + } - /* Add PSK_FINISH header to transcript, compute TH2 */ + /* Add PSK_FINISH up to VerifyData to transcript, compute TH2 */ rc = wolfSPDM_TranscriptAdd(ctx, buf, offset); if (rc == WOLFSPDM_SUCCESS) { rc = wolfSPDM_TranscriptHash(ctx, th2Hash); @@ -260,7 +273,14 @@ int wolfSPDM_ParsePskFinishRsp(WOLFSPDM_CTX* ctx, const byte* buf, SPDM_CHECK_PARSE_ARGS(ctx, buf, bufSz, 4); if (buf[1] == SPDM_PSK_FINISH_RSP) { - int addRc = wolfSPDM_TranscriptAdd(ctx, buf, 4); + int addRc; + word32 rspMsgLen; + + addRc = wolfSPDM_FinishRspLen(ctx, buf, bufSz, &rspMsgLen); + if (addRc != WOLFSPDM_SUCCESS) { + return addRc; + } + addRc = wolfSPDM_TranscriptAdd(ctx, buf, rspMsgLen); if (addRc != WOLFSPDM_SUCCESS) { return addRc; } @@ -270,6 +290,7 @@ int wolfSPDM_ParsePskFinishRsp(WOLFSPDM_CTX* ctx, const byte* buf, } if (buf[1] == SPDM_ERROR) { + ctx->lastPeerErrorCode = buf[2]; wolfSPDM_DebugPrint(ctx, "PSK_FINISH error: 0x%02x\n", buf[2]); return WOLFSPDM_E_PEER_ERROR; } @@ -297,13 +318,15 @@ int wolfSPDM_DeriveHandshakeKeysPsk(WOLFSPDM_CTX* ctx, const byte* th1Hash) /* HandshakeSecret = HKDF-Extract(0xFF-salt, PSK) */ rc = wc_HKDF_Extract(WC_SHA384, salt, sizeof(salt), ctx->psk, ctx->pskSz, ctx->handshakeSecret); - if (rc != 0) { - wc_ForceZero(ctx->psk, sizeof(ctx->psk)); - ctx->pskSz = 0; - return WOLFSPDM_E_CRYPTO_FAIL; + if (rc == 0) { + rc = wolfSPDM_DeriveFromHandshakeSecret(ctx, th1Hash); + } + else { + rc = WOLFSPDM_E_CRYPTO_FAIL; + } + if (rc != WOLFSPDM_SUCCESS) { + wc_ForceZero(ctx->handshakeSecret, sizeof(ctx->handshakeSecret)); } - - rc = wolfSPDM_DeriveFromHandshakeSecret(ctx, th1Hash); /* Zero PSK immediately after key derivation */ wc_ForceZero(ctx->psk, sizeof(ctx->psk)); @@ -314,8 +337,8 @@ int wolfSPDM_DeriveHandshakeKeysPsk(WOLFSPDM_CTX* ctx, const byte* th1Hash) /* ----- Shared PSK Connection Flow ----- */ -/* GET_VERSION -> GET_CAPABILITIES -> NEGOTIATE_ALGORITHMS -> - * PSK_EXCHANGE -> PSK_FINISH -> app key derivation */ +/* GET_VERSION -> PSK_EXCHANGE -> [PSK_FINISH] -> application key derivation. + * This PSK flow skips GET_CAPABILITIES and NEGOTIATE_ALGORITHMS. */ int wolfSPDM_ConnectPsk(WOLFSPDM_CTX* ctx) { int rc; @@ -323,12 +346,13 @@ int wolfSPDM_ConnectPsk(WOLFSPDM_CTX* ctx) byte rxBuf[WOLFSPDM_MAX_MSG_SIZE + WOLFSPDM_AEAD_OVERHEAD]; byte finBuf[64]; byte encBuf[WOLFSPDM_MAX_MSG_SIZE + WOLFSPDM_AEAD_OVERHEAD]; - byte decBuf[64]; + byte decBuf[WOLFSPDM_FINISH_RSP_MAX]; word32 txSz; word32 rxSz; word32 finSz; word32 encSz; word32 decSz; + int finish = 0; if (ctx == NULL) { return WOLFSPDM_E_INVALID_ARG; @@ -349,9 +373,6 @@ int wolfSPDM_ConnectPsk(WOLFSPDM_CTX* ctx) wolfSPDM_DebugPrint(ctx, "PSK: Starting SPDM connection\n"); - ctx->state = WOLFSPDM_STATE_INIT; - wolfSPDM_TranscriptReset(ctx); - /* Step 1: GET_VERSION */ wolfSPDM_DebugPrint(ctx, "PSK Step 1: GET_VERSION\n"); rc = wolfSPDM_GetVersion(ctx); @@ -377,9 +398,14 @@ int wolfSPDM_ConnectPsk(WOLFSPDM_CTX* ctx) if (rc == WOLFSPDM_SUCCESS) { rc = wolfSPDM_ParsePskExchangeRsp(ctx, rxBuf, rxSz); } + /* DSP0274 10.20: PSK_FINISH follows only when ResponderContext is present; + * otherwise PSK_EXCHANGE_RSP completes the handshake. */ + if (rc == WOLFSPDM_SUCCESS) { + finish = (SPDM_Get16LE(&rxBuf[8]) != 0); + } /* Step 5: PSK_FINISH / PSK_FINISH_RSP (encrypted) */ - if (rc == WOLFSPDM_SUCCESS) { + if (rc == WOLFSPDM_SUCCESS && finish) { finSz = sizeof(finBuf); encSz = sizeof(encBuf); rxSz = sizeof(rxBuf); @@ -387,18 +413,22 @@ int wolfSPDM_ConnectPsk(WOLFSPDM_CTX* ctx) wolfSPDM_DebugPrint(ctx, "PSK Step 5: PSK_FINISH\n"); rc = wolfSPDM_BuildPskFinish(ctx, finBuf, &finSz); - } - if (rc == WOLFSPDM_SUCCESS) { - rc = wolfSPDM_EncryptInternal(ctx, finBuf, finSz, encBuf, &encSz); - } - if (rc == WOLFSPDM_SUCCESS) { - rc = wolfSPDM_SendReceive(ctx, encBuf, encSz, rxBuf, &rxSz); - } - if (rc == WOLFSPDM_SUCCESS) { - rc = wolfSPDM_DecryptInternal(ctx, rxBuf, rxSz, decBuf, &decSz); - } - if (rc == WOLFSPDM_SUCCESS) { - rc = wolfSPDM_ParsePskFinishRsp(ctx, decBuf, decSz); + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_EncryptInternal(ctx, finBuf, finSz, encBuf, &encSz); + } + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_SendReceive(ctx, encBuf, encSz, rxBuf, &rxSz); + } + if (rc == WOLFSPDM_SUCCESS && + wolfSPDM_ClearPeerError(ctx, rxBuf, rxSz)) { + rc = WOLFSPDM_E_PEER_ERROR; + } + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_DecryptInternal(ctx, rxBuf, rxSz, decBuf, &decSz); + } + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_ParsePskFinishRsp(ctx, decBuf, decSz); + } } /* Derive application data keys */ @@ -412,7 +442,7 @@ int wolfSPDM_ConnectPsk(WOLFSPDM_CTX* ctx) "SessionID=0x%08x\n", ctx->sessionId); } else { - ctx->state = WOLFSPDM_STATE_ERROR; + wolfSPDM_RetireSession(ctx); } /* Always zero sensitive stack buffers */ diff --git a/src/spdm_responder.c b/src/spdm_responder.c index 41a3e14..b101729 100644 --- a/src/spdm_responder.c +++ b/src/spdm_responder.c @@ -256,6 +256,19 @@ word32 wolfSPDM_RespGetIdentityKey(const WOLFSPDM_RESP_CTX* ctx, return ctx->idPubKeyLen; } +/* Wipe session keys, handshake secrets and the ephemeral key */ +static void RespClearSessionKeys(WOLFSPDM_RESP_CTX* ctx) +{ + wolfSPDM_ClearTrafficKeys(&ctx->ctx); + wolfSPDM_ClearHandshakeSecrets(&ctx->ctx); +#ifndef WOLFSPDM_NO_KEY_UPDATE + wc_ForceZero(ctx->ctx.reqAppSecret, sizeof(ctx->ctx.reqAppSecret)); + wc_ForceZero(ctx->ctx.rspAppSecret, sizeof(ctx->ctx.rspAppSecret)); +#endif + ctx->ctx.sessionId = 0; + ctx->flags.pendingAsym = 0; +} + void wolfSPDM_RespReset(WOLFSPDM_RESP_CTX* ctx) { if (ctx == NULL) { @@ -263,33 +276,14 @@ void wolfSPDM_RespReset(WOLFSPDM_RESP_CTX* ctx) } /* Identity key, PSK, mode flags survive; only session-scoped material * is wiped. */ - wc_ForceZero(ctx->ctx.reqDataKey, sizeof(ctx->ctx.reqDataKey)); - wc_ForceZero(ctx->ctx.rspDataKey, sizeof(ctx->ctx.rspDataKey)); - wc_ForceZero(ctx->ctx.reqDataIv, sizeof(ctx->ctx.reqDataIv)); - wc_ForceZero(ctx->ctx.rspDataIv, sizeof(ctx->ctx.rspDataIv)); - wc_ForceZero(ctx->ctx.handshakeSecret, - sizeof(ctx->ctx.handshakeSecret)); - wc_ForceZero(ctx->ctx.reqHsSecret, sizeof(ctx->ctx.reqHsSecret)); - wc_ForceZero(ctx->ctx.rspHsSecret, sizeof(ctx->ctx.rspHsSecret)); - wc_ForceZero(ctx->ctx.reqFinishedKey, - sizeof(ctx->ctx.reqFinishedKey)); - wc_ForceZero(ctx->ctx.rspFinishedKey, - sizeof(ctx->ctx.rspFinishedKey)); - wc_ForceZero(ctx->ctx.sharedSecret, sizeof(ctx->ctx.sharedSecret)); - ctx->ctx.sharedSecretSz = 0; -#ifndef WOLFSPDM_NO_KEY_UPDATE - wc_ForceZero(ctx->ctx.reqAppSecret, sizeof(ctx->ctx.reqAppSecret)); - wc_ForceZero(ctx->ctx.rspAppSecret, sizeof(ctx->ctx.rspAppSecret)); -#endif - /* The ephemeral key and transcript would rebuild every session key */ - wolfSPDM_FreeEphemeralKey(&ctx->ctx); + RespClearSessionKeys(ctx); wolfSPDM_TranscriptReset(&ctx->ctx); + /* The VCA left with the transcript; GET_VERSION must renegotiate. */ + ctx->ctx.spdmVersion = 0; ctx->ctx.reqSeqNum = 0; ctx->ctx.rspSeqNum = 0; - ctx->ctx.sessionId = 0; ctx->ctx.state = WOLFSPDM_STATE_INIT; ctx->flags.sessionAsym = 0; - ctx->flags.pendingAsym = 0; wc_ForceZero(ctx->secureInPlain, sizeof(ctx->secureInPlain)); wc_ForceZero(ctx->secureOutPlain, sizeof(ctx->secureOutPlain)); wc_ForceZero(ctx->vdInPayload, sizeof(ctx->vdInPayload)); @@ -363,7 +357,7 @@ static int RespDecrypt(WOLFSPDM_CTX* ctx, { int rc; RespSwapDataDir(ctx); - rc = wolfSPDM_DecryptInternal(ctx, enc, encSz, plain, plainSz); + rc = wolfSPDM_DecryptRequest(ctx, enc, encSz, plain, plainSz); RespSwapDataDir(ctx); return rc; } @@ -381,15 +375,11 @@ static int RespDecrypt(WOLFSPDM_CTX* ctx, #define WOLFSPDM_RESP_VERSION_COUNT \ (WOLFSPDM_RESP_MAX_VERSION - WOLFSPDM_MIN_SPDM_VERSION + 1) -static int RespBuildVersion(WOLFSPDM_CTX* ctx, - const byte* req, word32 reqSz, - byte* out, word32* outSz) +static int RespBuildVersion(WOLFSPDM_CTX* ctx, byte* out, word32* outSz) { word32 off; byte ver; - (void)req; - (void)reqSz; if (*outSz < 6 + 2 * WOLFSPDM_RESP_VERSION_COUNT) { return WOLFSPDM_E_BUFFER_SMALL; } @@ -597,6 +587,7 @@ static int RespDispatchClear(WOLFSPDM_RESP_CTX* rctx, byte* out, word32* outSz) { WOLFSPDM_CTX* ctx = &rctx->ctx; + word32 transcriptMark; byte code; int rc; int handlerManagesTranscript = 0; @@ -609,7 +600,12 @@ static int RespDispatchClear(WOLFSPDM_RESP_CTX* rctx, XMEMSET(vdCode, 0, sizeof(vdCode)); if (code == SPDM_GET_VERSION) { - wolfSPDM_TranscriptReset(ctx); + if (inSz != 4) { + return WOLFSPDM_E_FRAMING; + } + if (in[0] != SPDM_VERSION_10) { + return WOLFSPDM_E_VERSION_MISMATCH; + } wolfSPDM_RespReset(rctx); } else { @@ -643,6 +639,7 @@ static int RespDispatchClear(WOLFSPDM_RESP_CTX* rctx, * requester's wolfSPDM_TCG_VendorCmdClear doesn't add them, so the * responder mustn't either. GET_PUBK contributes via Ct = SHA-384 * of its response payload, added separately below. */ + transcriptMark = ctx->transcriptLen; if (code != SPDM_VENDOR_DEFINED_REQUEST) { rc = wolfSPDM_TranscriptAdd(ctx, in, inSz); if (rc != WOLFSPDM_SUCCESS) { @@ -652,7 +649,7 @@ static int RespDispatchClear(WOLFSPDM_RESP_CTX* rctx, switch (code) { case SPDM_GET_VERSION: - rc = RespBuildVersion(ctx, in, inSz, out, outSz); + rc = RespBuildVersion(ctx, out, outSz); break; case WOLFSPDM_GET_CAPABILITIES: rc = RespBuildCapabilities(ctx, rctx->flags.usePsk, @@ -694,6 +691,7 @@ static int RespDispatchClear(WOLFSPDM_RESP_CTX* rctx, } break; default: + ctx->transcriptLen = transcriptMark; return RespBuildErrorClear(ctx, SPDM_ERROR_UNSUPPORTED_REQUEST, code, out, outSz); } @@ -701,6 +699,14 @@ static int RespDispatchClear(WOLFSPDM_RESP_CTX* rctx, if (rc == WOLFSPDM_SUCCESS && !handlerManagesTranscript) { rc = wolfSPDM_TranscriptAdd(ctx, out, *outSz); } + if (rc != WOLFSPDM_SUCCESS && ctx->transcriptLen > transcriptMark) { + ctx->transcriptLen = transcriptMark; + } + /* Only reached without a live session (checked above) */ + if (rc != WOLFSPDM_SUCCESS && + (code == SPDM_KEY_EXCHANGE || code == SPDM_PSK_EXCHANGE)) { + RespClearSessionKeys(rctx); + } return rc; } @@ -734,9 +740,13 @@ static int RespBuildKeyExchangeRsp(WOLFSPDM_RESP_CTX* rctx, word32 partialLen; int rc; - if (inSz < 136 || !rctx->flags.hasIdKey) { + if (inSz < 138 || !rctx->flags.hasIdKey) { return WOLFSPDM_E_BAD_STATE; } + /* OpaqueDataLength follows the P-384 ExchangeData and ends the request */ + if (SPDM_Get16LE(&in[136]) != inSz - 138) { + return WOLFSPDM_E_FRAMING; + } if (*outSz < 138u + WOLFSPDM_ECC_SIG_SIZE + WOLFSPDM_HASH_SIZE) { return WOLFSPDM_E_BUFFER_SMALL; } @@ -883,11 +893,6 @@ static int RespHandleFinish(WOLFSPDM_RESP_CTX* rctx, *outSz = 4; rc = wolfSPDM_TranscriptAdd(ctx, out, 4); } - if (rc == WOLFSPDM_SUCCESS) { - ctx->state = WOLFSPDM_STATE_CONNECTED; - rctx->flags.sessionAsym = 1; - } - wc_ForceZero(expectedHmac, sizeof(expectedHmac)); wc_ForceZero(th2, sizeof(th2)); return rc; @@ -935,25 +940,18 @@ static int RespHandlePskFinish(WOLFSPDM_RESP_CTX* rctx, *outSz = 4; rc = wolfSPDM_TranscriptAdd(ctx, out, 4); } - /* App-key derivation runs in the caller AFTER PSK_FINISH_RSP is - * encrypted with the still-current handshake keys (otherwise the - * requester decrypts with handshake keys but we wrote with app keys). */ - if (rc == WOLFSPDM_SUCCESS) { - ctx->state = WOLFSPDM_STATE_CONNECTED; - rctx->flags.sessionAsym = 0; - } - wc_ForceZero(expectedHmac, sizeof(expectedHmac)); wc_ForceZero(th2Hash, sizeof(th2Hash)); return rc; } #endif /* WOLFSPDM_PSK */ -static int RespBuildEndSessionAck(WOLFSPDM_CTX* ctx, - const byte* in, word32 inSz, byte* out, word32* outSz) +static int RespBuildEndSessionAck(WOLFSPDM_CTX* ctx, word32 inSz, + byte* out, word32* outSz) { - (void)in; - (void)inSz; + if (inSz != 4) { + return WOLFSPDM_E_FRAMING; + } if (*outSz < 4) { return WOLFSPDM_E_BUFFER_SMALL; } @@ -1143,7 +1141,7 @@ static int RespHandleVendorDefinedInner(WOLFSPDM_RESP_CTX* rctx, return WOLFSPDM_E_BUFFER_SMALL; } off = 0; - out[off++] = ctx->spdmVersion; + out[off++] = ctx->spdmVersion != 0 ? ctx->spdmVersion : in[0]; out[off++] = WOLFSPDM_VENDOR_DEFINED_RSP; out[off++] = 0x00; out[off++] = 0x00; @@ -1185,7 +1183,8 @@ static int RespDispatchSecuredInner(WOLFSPDM_RESP_CTX* rctx, byte code; int rc; int sessionEnded = 0; - int derivedAppKeys = 0; + int finishAttempted = 0; + int finishAccepted = 0; /* KEY_EX has handshake traffic keys; CONNECTED has application traffic * keys. In every other state, decryption would use unestablished key @@ -1200,12 +1199,21 @@ static int RespDispatchSecuredInner(WOLFSPDM_RESP_CTX* rctx, if (rc != WOLFSPDM_SUCCESS) { return rc; } - if (plainSz < 2) { + if (plainSz < 4) { return WOLFSPDM_E_FRAMING; } - code = plain[1]; respPlainSz = WOLFSPDM_MAX_MSG_SIZE; + if (plain[0] != ctx->spdmVersion) { + rc = RespBuildErrorClear(ctx, SPDM_ERROR_MAJOR_VERSION_MISMATCH, 0, + respPlain, &respPlainSz); + if (rc == WOLFSPDM_SUCCESS) { + rc = RespEncrypt(ctx, respPlain, respPlainSz, + securedOut, securedOutSz); + } + return rc; + } + code = plain[1]; switch (code) { /* A finish must match the exchange that opened KEY_EX and cannot run * again once connected, or a PSK peer could relabel its session as @@ -1216,9 +1224,10 @@ static int RespDispatchSecuredInner(WOLFSPDM_RESP_CTX* rctx, rctx->flags.pendingAsym) { return WOLFSPDM_E_BAD_STATE; } + finishAttempted = 1; rc = RespHandlePskFinish(rctx, plain, plainSz, respPlain, &respPlainSz); - derivedAppKeys = (rc == WOLFSPDM_SUCCESS) ? 1 : 0; + finishAccepted = (rc == WOLFSPDM_SUCCESS) ? 1 : 0; break; #endif case SPDM_FINISH: @@ -1226,14 +1235,14 @@ static int RespDispatchSecuredInner(WOLFSPDM_RESP_CTX* rctx, !rctx->flags.pendingAsym) { return WOLFSPDM_E_BAD_STATE; } + finishAttempted = 1; rc = RespHandleFinish(rctx, plain, plainSz, respPlain, &respPlainSz); - derivedAppKeys = (rc == WOLFSPDM_SUCCESS) ? 1 : 0; + finishAccepted = (rc == WOLFSPDM_SUCCESS) ? 1 : 0; break; case SPDM_END_SESSION: - rc = RespBuildEndSessionAck(ctx, plain, plainSz, - respPlain, &respPlainSz); - sessionEnded = 1; + rc = RespBuildEndSessionAck(ctx, plainSz, respPlain, &respPlainSz); + sessionEnded = (rc == WOLFSPDM_SUCCESS) ? 1 : 0; break; case SPDM_VENDOR_DEFINED_REQUEST: rc = RespHandleVendorDefined(rctx, plain, plainSz, @@ -1250,11 +1259,24 @@ static int RespDispatchSecuredInner(WOLFSPDM_RESP_CTX* rctx, rc = RespEncrypt(ctx, respPlain, respPlainSz, securedOut, securedOutSz); } - if (rc == WOLFSPDM_SUCCESS && derivedAppKeys) { - rc = wolfSPDM_DeriveAppDataKeys(ctx); + if (finishAccepted) { + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_DeriveAppDataKeys(ctx); + } + if (rc == WOLFSPDM_SUCCESS) { + ctx->state = WOLFSPDM_STATE_CONNECTED; + rctx->flags.sessionAsym = rctx->flags.pendingAsym; + } + else { + wolfSPDM_RespReset(rctx); + } + } + else if (finishAttempted) { + /* The failed FINISH is in the transcript, so no retry can verify */ + wolfSPDM_RespReset(rctx); } - if (sessionEnded && rc == WOLFSPDM_SUCCESS) { + if (sessionEnded) { wolfSPDM_RespReset(rctx); } return rc; @@ -1285,6 +1307,9 @@ int wolfSPDM_RespHandleMessage(WOLFSPDM_RESP_CTX* ctx, word32 spdmOutSz; word32 totalSz; int rc; + #ifdef WOLFSPDM_NATIONS + int pskWasProvisioned; + #endif #endif if (ctx == NULL || inBuf == NULL || outBuf == NULL || outSz == NULL) { @@ -1323,6 +1348,9 @@ int wolfSPDM_RespHandleMessage(WOLFSPDM_RESP_CTX* ctx, return WOLFSPDM_E_BUFFER_SMALL; } spdmOutSz = *outSz - WOLFSPDM_TCG_HEADER_SIZE; + #ifdef WOLFSPDM_NATIONS + pskWasProvisioned = ctx->flags.pskProvisioned; + #endif if (tag == WOLFSPDM_TCG_TAG_CLEAR) { rc = RespDispatchClear(ctx, @@ -1335,6 +1363,17 @@ int wolfSPDM_RespHandleMessage(WOLFSPDM_RESP_CTX* ctx, outBuf + WOLFSPDM_TCG_HEADER_SIZE, &spdmOutSz); } + #ifdef WOLFSPDM_NATIONS + /* Keep the traffic keys until any secured clear reply has been sealed. */ + if (pskWasProvisioned && !ctx->flags.pskProvisioned && + ((ctx->ctx.state == WOLFSPDM_STATE_KEY_EX && + !ctx->flags.pendingAsym) || + (ctx->ctx.state == WOLFSPDM_STATE_CONNECTED && + !ctx->flags.sessionAsym))) { + wolfSPDM_RespReset(ctx); + } + #endif + if (rc != WOLFSPDM_SUCCESS) { return rc; } diff --git a/src/spdm_secured.c b/src/spdm_secured.c index aae7707..867408b 100644 --- a/src/spdm_secured.c +++ b/src/spdm_secured.c @@ -25,6 +25,9 @@ #include "spdm_internal.h" +#define MCTP_MESSAGE_TYPE_SECURED_SPDM 0x06 +#define MCTP_MESSAGE_TYPE_MASK 0x7F + /* * SPDM Secured Message Format (DSP0277): * @@ -51,7 +54,7 @@ static int wolfSPDM_EncryptRecord(WOLFSPDM_CTX* ctx, int appMsg, byte plainBuf[WOLFSPDM_XFER_MSG_SIZE + 2 + 16]; /* AppDataLength, pad */ byte tag[WOLFSPDM_AEAD_TAG_SIZE]; word32 plainBufSz; - word16 recordLen; + word32 recordLen; word32 hdrSz; word32 aadSz; int aesInit = 0; @@ -70,24 +73,23 @@ static int wolfSPDM_EncryptRecord(WOLFSPDM_CTX* ctx, int appMsg, * Header/AAD: SessionID(4 LE) + SeqNum(8 LE) + Length(2 LE) = 14 bytes * IV XOR: Leftmost 8 bytes (bytes 0-7) with 8-byte LE sequence number */ - word16 appDataLen = (word16)plainSz; - - word16 unpadded = (word16)(2 + appDataLen); - word16 padLen = (word16)((16 - (unpadded % 16)) % 16); - word16 encPayloadSz = (word16)(unpadded + padLen); + word32 unpadded = 2 + plainSz; + word32 padLen = (16 - (unpadded % 16)) % 16; + word32 encPayloadSz = unpadded + padLen; plainBufSz = encPayloadSz; /* Length field = ciphertext + MAC * (per Nuvoton spec page 25: Length=160=144+16) */ - recordLen = (word16)(encPayloadSz + WOLFSPDM_AEAD_TAG_SIZE); + recordLen = encPayloadSz + WOLFSPDM_AEAD_TAG_SIZE; hdrSz = 14; /* 4 + 8 + 2 (TCG binding format) */ - if (*encSz < hdrSz + plainBufSz + WOLFSPDM_AEAD_TAG_SIZE) { + if (recordLen > 0xFFFF || + *encSz < hdrSz + plainBufSz + WOLFSPDM_AEAD_TAG_SIZE) { return WOLFSPDM_E_BUFFER_SMALL; } /* Build plaintext: AppDataLength(2 LE) || SPDM message || RandomData */ - SPDM_Set16LE(plainBuf, appDataLen); + SPDM_Set16LE(plainBuf, (word16)plainSz); XMEMCPY(&plainBuf[2], plain, plainSz); /* Fill RandomData with actual random bytes per Nuvoton spec */ if (padLen > 0) { @@ -102,7 +104,7 @@ static int wolfSPDM_EncryptRecord(WOLFSPDM_CTX* ctx, int appMsg, * Length(2 LE) = 14 bytes */ SPDM_Set32LE(&enc[0], ctx->sessionId); SPDM_Set64LE(&enc[4], ctx->reqSeqNum); - SPDM_Set16LE(&enc[12], recordLen); + SPDM_Set16LE(&enc[12], (word16)recordLen); aadSz = 14; XMEMCPY(aad, enc, aadSz); @@ -118,25 +120,20 @@ static int wolfSPDM_EncryptRecord(WOLFSPDM_CTX* ctx, int appMsg, * Header: SessionID(4 LE) + SeqNum(2 LE) + Length(2 LE) = 8 bytes * AAD = Header */ - word16 appDataLen = (word16)(appMsg ? plainSz : 1 + plainSz); - word16 encDataLen = (word16)(2 + appDataLen); - - /* MCTP carries a 16-bit sequence number; fail rather than let the wire - * value and the 64-bit IV counter diverge past 0xFFFF */ - if (ctx->reqSeqNum > 0xFFFF) { - return WOLFSPDM_E_SEQUENCE; - } + word32 appDataLen = appMsg ? plainSz : 1 + plainSz; + word32 encDataLen = 2 + appDataLen; plainBufSz = encDataLen; - recordLen = (word16)(encDataLen + WOLFSPDM_AEAD_TAG_SIZE); + recordLen = encDataLen + WOLFSPDM_AEAD_TAG_SIZE; hdrSz = 8; /* 4 + 2 + 2 */ - if (*encSz < hdrSz + recordLen) { + /* The record Length is a 16-bit field */ + if (recordLen > 0xFFFF || *encSz < hdrSz + recordLen) { return WOLFSPDM_E_BUFFER_SMALL; } /* Build plaintext: AppDataLen(2 LE) || MCTP header(0x05) || SPDM msg */ - SPDM_Set16LE(plainBuf, appDataLen); + SPDM_Set16LE(plainBuf, (word16)appDataLen); if (appMsg) { XMEMCPY(&plainBuf[2], plain, plainSz); } else { @@ -146,8 +143,10 @@ static int wolfSPDM_EncryptRecord(WOLFSPDM_CTX* ctx, int appMsg, /* Build header/AAD: SessionID(4 LE) + SeqNum(2 LE) + Length(2 LE) */ SPDM_Set32LE(&enc[0], ctx->sessionId); + /* DSP0276 1.3 4.1: the wire carries the low 16 bits and both ends + * track the upper 48, so the DSP0277 IV uses the full counter */ SPDM_Set16LE(&enc[4], (word16)ctx->reqSeqNum); - SPDM_Set16LE(&enc[6], recordLen); + SPDM_Set16LE(&enc[6], (word16)recordLen); aadSz = 8; XMEMCPY(aad, enc, aadSz); @@ -167,14 +166,22 @@ static int wolfSPDM_EncryptRecord(WOLFSPDM_CTX* ctx, int appMsg, rc = wc_AesGcmEncrypt(&aes, &enc[hdrSz], plainBuf, plainBufSz, iv, WOLFSPDM_AEAD_IV_SIZE, tag, WOLFSPDM_AEAD_TAG_SIZE, aad, aadSz); } + wc_ForceZero(iv, sizeof(iv)); if (aesInit) { wc_AesFree(&aes); + wc_ForceZero(&aes, sizeof(aes)); } if (rc == 0) { XMEMCPY(&enc[hdrSz + plainBufSz], tag, WOLFSPDM_AEAD_TAG_SIZE); *encSz = hdrSz + plainBufSz + WOLFSPDM_AEAD_TAG_SIZE; ctx->reqSeqNum++; +#ifndef WOLFSPDM_NO_MEAS + /* Only back-to-back GET_MEASUREMENTS extend L1/L2 */ + if (!appMsg && ctx->l1l2State == WOLFSPDM_RUN_OPEN) { + ctx->l1l2State = WOLFSPDM_RUN_LIVE; + } +#endif wolfSPDM_DebugPrint(ctx, "Encrypted %u bytes -> %u bytes (seq=%llu)\n", plainSz, *encSz, (unsigned long long)(ctx->reqSeqNum - 1)); } @@ -241,7 +248,7 @@ static int wolfSPDM_DecryptRecord(WOLFSPDM_CTX* ctx, int appMsg, (unsigned long long)ctx->rspSeqNum); return WOLFSPDM_E_SEQUENCE; } - if (rspLen < WOLFSPDM_AEAD_TAG_SIZE || encSz < hdrSz + rspLen) + if (rspLen < WOLFSPDM_AEAD_TAG_SIZE || encSz != hdrSz + rspLen) return WOLFSPDM_E_BUFFER_SMALL; cipherLen = (word32)(rspLen - WOLFSPDM_AEAD_TAG_SIZE); @@ -276,7 +283,8 @@ static int wolfSPDM_DecryptRecord(WOLFSPDM_CTX* ctx, int appMsg, rspSessionId, ctx->sessionId); return WOLFSPDM_E_SESSION_INVALID; } - if ((word64)rspSeqNum != ctx->rspSeqNum) { + /* Partial sequence number against the tracked 64-bit counter */ + if (rspSeqNum != (word16)ctx->rspSeqNum) { wolfSPDM_DebugPrint(ctx, "Seq mismatch: %u != %llu\n", rspSeqNum, (unsigned long long)ctx->rspSeqNum); return WOLFSPDM_E_SEQUENCE; @@ -292,7 +300,7 @@ static int wolfSPDM_DecryptRecord(WOLFSPDM_CTX* ctx, int appMsg, ciphertext = enc + hdrSz; tag = enc + hdrSz + cipherLen; XMEMCPY(aad, enc, aadSz); - wolfSPDM_BuildIV(iv, ctx->rspDataIv, (word64)rspSeqNum); + wolfSPDM_BuildIV(iv, ctx->rspDataIv, ctx->rspSeqNum); #endif } @@ -320,8 +328,10 @@ static int wolfSPDM_DecryptRecord(WOLFSPDM_CTX* ctx, int appMsg, ctx->rspSeqNum++; } } + wc_ForceZero(iv, sizeof(iv)); if (aesInit) { wc_AesFree(&aes); + wc_ForceZero(&aes, sizeof(aes)); } /* ----- Parse decrypted payload ----- */ @@ -356,6 +366,9 @@ static int wolfSPDM_DecryptRecord(WOLFSPDM_CTX* ctx, int appMsg, ret = WOLFSPDM_E_BUFFER_SMALL; } else if (!appMsg && decrypted[2] != MCTP_MESSAGE_TYPE_SPDM) { ret = WOLFSPDM_E_DECRYPT_FAIL; + } else if (appMsg && (decrypted[2] & MCTP_MESSAGE_TYPE_MASK) == + MCTP_MESSAGE_TYPE_SECURED_SPDM) { + ret = WOLFSPDM_E_DECRYPT_FAIL; } else { XMEMCPY(plain, &decrypted[2 + typeSz], appDataLen - typeSz); *plainSz = appDataLen - typeSz; @@ -374,12 +387,55 @@ static int wolfSPDM_DecryptRecord(WOLFSPDM_CTX* ctx, int appMsg, return ret; } +/* DSP0274 section 11: an authenticated DecryptError ends the session */ +static void wolfSPDM_CheckSessionEnd(WOLFSPDM_CTX* ctx, const byte* msg, + word32 msgSz) +{ + int errorCode = 0; + + if (wolfSPDM_CheckError(msg, msgSz, &errorCode) && + errorCode == SPDM_ERROR_DECRYPT_ERROR) { + wolfSPDM_RetireSession(ctx); + } +} + int wolfSPDM_DecryptInternal(WOLFSPDM_CTX* ctx, const byte* enc, word32 encSz, byte* plain, word32* plainSz) +{ + int rc = wolfSPDM_DecryptRecord(ctx, 0, enc, encSz, plain, plainSz); + + if (rc == WOLFSPDM_SUCCESS) { + wolfSPDM_CheckSessionEnd(ctx, plain, *plainSz); + } + return rc; +} + +#ifdef WOLFSPDM_RESPONDER +/* The responder retires its sessions through its own reset */ +int wolfSPDM_DecryptRequest(WOLFSPDM_CTX* ctx, + const byte* enc, word32 encSz, + byte* plain, word32* plainSz) { return wolfSPDM_DecryptRecord(ctx, 0, enc, encSz, plain, plainSz); } +#endif + +/* Returns 1 for a cleartext SPDM reply, which only an ERROR should be. + * A record starts with our session ID, whose requester half keeps its first + * byte out of 0x10-0x1F (wolfSPDM_SetRequesterSessionId). */ +int wolfSPDM_ClearPeerError(WOLFSPDM_CTX* ctx, const byte* rx, word32 rxSz) +{ + if (rxSz < 2 || rx[0] < 0x10 || rx[0] > 0x1F || + (rxSz >= 4 && SPDM_Get32LE(rx) == ctx->sessionId)) { + return 0; + } + if (rxSz >= 4 && rx[1] == SPDM_ERROR) { + ctx->lastPeerErrorCode = rx[2]; + wolfSPDM_DebugPrint(ctx, "SPDM ERROR 0x%02x in the clear\n", rx[2]); + } + return 1; +} int wolfSPDM_SecuredXfer(WOLFSPDM_CTX* ctx, const byte* cmdPlain, word32 cmdSz, @@ -395,6 +451,9 @@ int wolfSPDM_SecuredXfer(WOLFSPDM_CTX* ctx, if (rc == WOLFSPDM_SUCCESS) { rc = wolfSPDM_SendReceive(ctx, encBuf, encSz, rxBuf, &rxSz); } + if (rc == WOLFSPDM_SUCCESS && wolfSPDM_ClearPeerError(ctx, rxBuf, rxSz)) { + rc = WOLFSPDM_E_PEER_ERROR; + } if (rc == WOLFSPDM_SUCCESS) { rc = wolfSPDM_DecryptInternal(ctx, rxBuf, rxSz, rspPlain, rspSz); } @@ -417,12 +476,6 @@ int wolfSPDM_SecuredExchange(WOLFSPDM_CTX* ctx, !wolfSPDM_IsTcgMode(ctx))) { return WOLFSPDM_E_NOT_CONNECTED; } -#ifndef WOLFSPDM_NO_MEAS - /* Only back-to-back GET_MEASUREMENTS extend L1/L2 */ - if (ctx->l1l2State == WOLFSPDM_RUN_OPEN) { - ctx->l1l2State = WOLFSPDM_RUN_LIVE; - } -#endif #ifndef WOLFSPDM_NO_CHUNK if (wolfSPDM_ChunkOn(ctx)) { return wolfSPDM_ChunkExchange(ctx, 1, cmdPlain, cmdSz, rspPlain, @@ -456,7 +509,7 @@ int wolfSPDM_DecryptMessage(WOLFSPDM_CTX* ctx, if (ctx->state != WOLFSPDM_STATE_CONNECTED) { return WOLFSPDM_E_NOT_CONNECTED; } - return wolfSPDM_DecryptRecord(ctx, 0, enc, encSz, plain, plainSz); + return wolfSPDM_DecryptInternal(ctx, enc, encSz, plain, plainSz); } static int wolfSPDM_AppDataReady(const WOLFSPDM_CTX* ctx) @@ -484,8 +537,10 @@ int wolfSPDM_SendData(WOLFSPDM_CTX* ctx, const byte* data, word32 dataSz) if (ctx == NULL || data == NULL || dataSz == 0) { return WOLFSPDM_E_INVALID_ARG; } - /* Type 0x05 would reach the peer as an SPDM request */ - if (data[0] == MCTP_MESSAGE_TYPE_SPDM) { + /* SPDM requests have a separate API. DSP0276 forbids nesting records. */ + if (data[0] == MCTP_MESSAGE_TYPE_SPDM || + (data[0] & MCTP_MESSAGE_TYPE_MASK) == + MCTP_MESSAGE_TYPE_SECURED_SPDM) { return WOLFSPDM_E_INVALID_ARG; } @@ -525,6 +580,7 @@ int wolfSPDM_ReceiveData(WOLFSPDM_CTX* ctx, byte* data, word32* dataSz) if (*dataSz >= 4 && data[2] == SPDM_ERROR) { ctx->lastPeerErrorCode = data[3]; } + wolfSPDM_CheckSessionEnd(ctx, data + 1, *dataSz - 1); rc = WOLFSPDM_E_PEER_ERROR; } diff --git a/src/spdm_session.c b/src/spdm_session.c index 84b1f27..abf6ca6 100644 --- a/src/spdm_session.c +++ b/src/spdm_session.c @@ -67,7 +67,44 @@ static int wolfSPDM_BuildGetVersionAdapter(WOLFSPDM_CTX* ctx, byte* buf, int wolfSPDM_GetVersion(WOLFSPDM_CTX* ctx) { byte txBuf[8]; - byte rxBuf[32]; /* VERSION: 4 hdr + 2 count + up to 8 entries * 2 = 22 */ + byte rxBuf[SPDM_MIN_DATA_TRANSFER_SIZE]; + + if (ctx == NULL) { + return WOLFSPDM_E_INVALID_ARG; + } + if (!ctx->flags.initialized) { + return WOLFSPDM_E_BAD_STATE; + } + if (ctx->ioCb == NULL) { + return WOLFSPDM_E_IO_FAIL; + } + + /* GET_VERSION starts a new negotiation and ends any prior session. */ + wolfSPDM_ResetSession(ctx); + wolfSPDM_TranscriptReset(ctx); + ctx->spdmVersion = 0; + ctx->lastPeerErrorCode = 0; +#ifndef WOLFSPDM_NO_CERT + ctx->vcaLen = 0; + ctx->certChainLen = 0; + ctx->slotMask = 0; + ctx->currentSlotId = 0; + if (ctx->flags.rspKeyFromCert) { + ctx->flags.hasRspPubKey = 0; + ctx->flags.rspKeyFromCert = 0; + ctx->rspPubKeyLen = 0; + wc_ForceZero(ctx->rspPubKey, sizeof(ctx->rspPubKey)); + } + #ifndef WOLFSPDM_NO_CHUNK + ctx->chunkHandle = 0; + #endif + #ifdef WOLFSPDM_HAVE_MLDSA + ctx->pqcAsymSel = 0; + #endif + #ifdef WOLFSPDM_HAVE_MLKEM + ctx->kemAlgSel = 0; + #endif +#endif return wolfSPDM_ExchangeMsg(ctx, wolfSPDM_BuildGetVersionAdapter, wolfSPDM_ParseVersion, txBuf, sizeof(txBuf), rxBuf, sizeof(rxBuf)); @@ -79,6 +116,7 @@ static int wolfSPDM_KeyExchangeEx(WOLFSPDM_CTX* ctx, int revalidate) byte rxBuf[WOLFSPDM_KEY_EX_RX_SZ]; word32 txSz = sizeof(txBuf); word32 rxSz = sizeof(rxBuf); + word32 mark = (ctx != NULL) ? ctx->transcriptLen : 0; int rc; /* The signature in KEY_EXCHANGE_RSP can only be checked against a @@ -92,17 +130,22 @@ static int wolfSPDM_KeyExchangeEx(WOLFSPDM_CTX* ctx, int revalidate) else { rc = WOLFSPDM_SUCCESS; #ifndef WOLFSPDM_NO_CERT - if (revalidate && !wolfSPDM_IsTcgMode(ctx) && - ctx->flags.rspKeyFromCert) { - rc = wolfSPDM_ValidateCertChain(ctx); + if (ctx->flags.rspKeyFromCert) { + if (wolfSPDM_IsTcgMode(ctx)) { + rc = WOLFSPDM_E_BAD_STATE; + } + else if (revalidate) { + rc = wolfSPDM_ValidateCertChain(ctx); + } } #else (void)revalidate; #endif } - if (rc == WOLFSPDM_SUCCESS) { - rc = wolfSPDM_BuildKeyExchange(ctx, txBuf, &txSz); + if (rc != WOLFSPDM_SUCCESS) { + return rc; } + rc = wolfSPDM_BuildKeyExchange(ctx, txBuf, &txSz); #ifndef WOLFSPDM_NO_CHALLENGE /* KEY_EXCHANGE drops DIGESTS and CERTIFICATE from M1 */ if (rc == WOLFSPDM_SUCCESS && ctx->m1State != WOLFSPDM_RUN_NONE) { @@ -122,6 +165,12 @@ static int wolfSPDM_KeyExchangeEx(WOLFSPDM_CTX* ctx, int revalidate) wolfSPDM_DebugPrint(ctx, "KEY_EXCHANGE_RSP: received %u bytes\n", rxSz); rc = wolfSPDM_ParseKeyExchangeRsp(ctx, rxBuf, rxSz); } + else if (ctx->flags.ephemeralKeyInit) { + wolfSPDM_ClearHandshakeSecrets(ctx); + } + if (rc != WOLFSPDM_SUCCESS && ctx->transcriptLen > mark) { + ctx->transcriptLen = mark; + } return rc; } @@ -161,13 +210,7 @@ static int wolfSPDM_FinishXfer(WOLFSPDM_CTX* ctx, const byte* finishBuf, rc = wolfSPDM_SendReceive(ctx, encBuf, encSz, rxBuf, &rxSz); } - /* Check for unencrypted SPDM error response */ - if (rc == WOLFSPDM_SUCCESS && - rxSz >= 2 && rxBuf[0] >= 0x10 && rxBuf[0] <= 0x1F) { - if (rxSz >= 4 && rxBuf[1] == SPDM_ERROR) { - ctx->lastPeerErrorCode = rxBuf[2]; - wolfSPDM_DebugPrint(ctx, "FINISH: SPDM ERROR 0x%02x\n", rxBuf[2]); - } + if (rc == WOLFSPDM_SUCCESS && wolfSPDM_ClearPeerError(ctx, rxBuf, rxSz)) { rc = WOLFSPDM_E_PEER_ERROR; } @@ -184,6 +227,7 @@ int wolfSPDM_Finish(WOLFSPDM_CTX* ctx) byte decBuf[WOLFSPDM_FINISH_RSP_MAX]; word32 finishSz = sizeof(finishBuf); word32 decSz = sizeof(decBuf); + word32 mark; int rc; /* FINISH is only valid after a successful KEY_EXCHANGE; otherwise the @@ -192,6 +236,7 @@ int wolfSPDM_Finish(WOLFSPDM_CTX* ctx) return WOLFSPDM_E_BAD_STATE; } + mark = ctx->transcriptLen; rc = wolfSPDM_BuildFinish(ctx, finishBuf, &finishSz); if (rc == WOLFSPDM_SUCCESS) { rc = wolfSPDM_FinishXfer(ctx, finishBuf, finishSz, decBuf, &decSz); @@ -205,6 +250,13 @@ int wolfSPDM_Finish(WOLFSPDM_CTX* ctx) rc = wolfSPDM_DeriveAppDataKeys(ctx); } + if (rc == WOLFSPDM_SUCCESS) { + ctx->state = WOLFSPDM_STATE_CONNECTED; + } + else { + ctx->transcriptLen = mark; + } + /* Always zero sensitive stack buffers */ wc_ForceZero(finishBuf, sizeof(finishBuf)); wc_ForceZero(decBuf, sizeof(decBuf)); @@ -313,6 +365,7 @@ int wolfSPDM_KeyUpdate(WOLFSPDM_CTX* ctx, int updateAll) byte op; byte tag = 0; int rotated = 0; + int verifying = 0; int rc; op = updateAll ? SPDM_KEY_UPDATE_OP_UPDATE_ALL_KEYS : @@ -328,6 +381,9 @@ int wolfSPDM_KeyUpdate(WOLFSPDM_CTX* ctx, int updateAll) if (rc == WOLFSPDM_SUCCESS) { rc = wolfSPDM_SendReceive(ctx, encBuf, encSz, rawBuf, &rawSz); } + if (rc == WOLFSPDM_SUCCESS && wolfSPDM_ClearPeerError(ctx, rawBuf, rawSz)) { + rc = WOLFSPDM_E_PEER_ERROR; + } /* A rejection arrives under the current keys, an UpdateAllKeys ACK under * the new ones, so keys rotate only once the response proves it */ if (rc == WOLFSPDM_SUCCESS) { @@ -361,10 +417,18 @@ int wolfSPDM_KeyUpdate(WOLFSPDM_CTX* ctx, int updateAll) } if (rc == WOLFSPDM_SUCCESS && !updateAll) { rc = wolfSPDM_DeriveUpdatedKeys(ctx, 0); - ctx->reqSeqNum = 0; + if (rc == WOLFSPDM_SUCCESS) { + ctx->reqSeqNum = 0; + } + else { + /* The peer acknowledged the update. Retire the session when + * we cannot install the new keys. */ + wolfSPDM_RetireSession(ctx); + } } if (rc == WOLFSPDM_SUCCESS) { + verifying = 1; txSz = sizeof(txBuf); rc = wolfSPDM_BuildKeyUpdate(ctx, txBuf, &txSz, SPDM_KEY_UPDATE_OP_VERIFY_NEW_KEY, &tag); @@ -377,6 +441,10 @@ int wolfSPDM_KeyUpdate(WOLFSPDM_CTX* ctx, int updateAll) rc = wolfSPDM_ParseKeyUpdateAck(ctx, rxBuf, rxSz, SPDM_KEY_UPDATE_OP_VERIFY_NEW_KEY, tag); } + /* DSP0274: an unconfirmed new key is retried or ends the session */ + if (rc != WOLFSPDM_SUCCESS && verifying) { + wolfSPDM_RetireSession(ctx); + } wc_ForceZero(saved, sizeof(saved)); return rc; diff --git a/src/spdm_standard.c b/src/spdm_standard.c index 5678b48..46d4782 100644 --- a/src/spdm_standard.c +++ b/src/spdm_standard.c @@ -28,6 +28,7 @@ #ifndef WOLFSPDM_NO_CERT #include +#include /* Largest certificate portion requested per GET_CERTIFICATE; the response * fills our DataTransferSize so certificates are never chunked */ @@ -37,6 +38,10 @@ /* ----- VCA: GET_CAPABILITIES / NEGOTIATE_ALGORITHMS ----- */ +#define SPDM_OPAQUE_FORMAT_MASK 0x03 +#define SPDM_OPAQUE_FORMAT_1 0x02 +#define SPDM_REQUESTER_MULTI_KEY 0x10 + int wolfSPDM_BuildGetCapabilities(WOLFSPDM_CTX* ctx, byte* buf, word32* bufSz) { SPDM_CHECK_BUILD_ARGS(ctx, buf, bufSz, 20); @@ -86,6 +91,18 @@ int wolfSPDM_ParseCapabilities(WOLFSPDM_CTX* ctx, const byte* buf, return WOLFSPDM_SUCCESS; } +#ifdef WOLFSPDM_HAVE_MLDSA +static word32 wolfSPDM_OfferedPqcAsym(const WOLFSPDM_CTX* ctx) +{ + /* Provisioned P-384 pins can authenticate only P-384 peers. */ + if (ctx->spdmVersion < SPDM_VERSION_14 || + (ctx->flags.hasRspPubKey && !ctx->flags.rspKeyFromCert)) { + return 0; + } + return WOLFSPDM_MLDSA_SETS; +} +#endif + int wolfSPDM_BuildNegotiateAlgorithms(WOLFSPDM_CTX* ctx, byte* buf, word32* bufSz) { @@ -112,14 +129,11 @@ int wolfSPDM_BuildNegotiateAlgorithms(WOLFSPDM_CTX* ctx, byte* buf, buf[0] = ctx->spdmVersion; buf[1] = SPDM_NEGOTIATE_ALGORITHMS; buf[6] = 0x01; /* MeasurementSpecification = DMTF */ - buf[7] = 0x02; /* OtherParams = OpaqueDataFmt1 */ + buf[7] = SPDM_OPAQUE_FORMAT_1; SPDM_Set32LE(&buf[8], SPDM_ASYM_ALGO_ECDSA_P384); SPDM_Set32LE(&buf[12], SPDM_HASH_ALGO_SHA_384); #ifdef WOLFSPDM_HAVE_MLDSA - /* PqcAsymAlgo, reserved before 1.4 */ - if (ctx->spdmVersion >= SPDM_VERSION_14) { - SPDM_Set32LE(&buf[16], WOLFSPDM_MLDSA_SETS); - } + SPDM_Set32LE(&buf[16], wolfSPDM_OfferedPqcAsym(ctx)); #endif if (advDhe) { @@ -132,10 +146,8 @@ int wolfSPDM_BuildNegotiateAlgorithms(WOLFSPDM_CTX* ctx, byte* buf, buf[off + 1] = 0x20; SPDM_Set16LE(&buf[off + 2], SPDM_AEAD_ALGO_AES_256_GCM); off += 4; - buf[off] = SPDM_ALG_TYPE_REQ_BASE_ASYM; - buf[off + 1] = 0x20; - SPDM_Set16LE(&buf[off + 2], (word16)SPDM_ASYM_ALGO_ECDSA_P384); - off += 4; + /* No ReqBaseAsymAlg: this binding sends no MUT_AUTH_CAP and refuses + * MutAuthRequested, so the requester never signs (DSP0274 10.4) */ buf[off] = SPDM_ALG_TYPE_KEY_SCHEDULE; buf[off + 1] = 0x20; SPDM_Set16LE(&buf[off + 2], SPDM_KEY_SCHEDULE_SPDM); @@ -168,6 +180,7 @@ int wolfSPDM_ParseAlgorithms(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz) #endif byte numAlgs; byte i; + byte otherParamsMask = SPDM_OPAQUE_FORMAT_MASK; int dheOk = 0; int kemOk = 0; int aeadOk = 0; @@ -181,8 +194,11 @@ int wolfSPDM_ParseAlgorithms(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz) SPDM_Get16LE(&buf[4]) != bufSz) { return WOLFSPDM_E_ALGO_MISMATCH; } - /* MeasurementSpecificationSel (none or DMTF), OtherParamsSel */ - if (buf[6] > 0x01 || buf[7] != 0x02) { + /* RequesterMultiKeyConnSel is defined since 1.3 and never offered. */ + if (ctx->spdmVersion >= SPDM_VERSION_13) { + otherParamsMask |= SPDM_REQUESTER_MULTI_KEY; + } + if (buf[6] > 0x01 || (buf[7] & otherParamsMask) != SPDM_OPAQUE_FORMAT_1) { return WOLFSPDM_E_ALGO_MISMATCH; } if (SPDM_Get32LE(&buf[16]) != SPDM_HASH_ALGO_SHA_384) { @@ -201,7 +217,8 @@ int wolfSPDM_ParseAlgorithms(WOLFSPDM_CTX* ctx, const byte* buf, word32 bufSz) } if (pqcAsymSel != 0) { #ifdef WOLFSPDM_HAVE_MLDSA - if (baseAsymSel != 0 || wolfSPDM_MlDsaLevel(pqcAsymSel) == 0) { + if (baseAsymSel != 0 || wolfSPDM_MlDsaLevel(pqcAsymSel) == 0 || + (pqcAsymSel & wolfSPDM_OfferedPqcAsym(ctx)) == 0) { return WOLFSPDM_E_ALGO_MISMATCH; } #else @@ -391,6 +408,16 @@ int wolfSPDM_GetCertificate(WOLFSPDM_CTX* ctx, int slotId) if (ctx == NULL || slotId < 0 || slotId > 7) { return WOLFSPDM_E_INVALID_ARG; } + /* The fetched chain and transcript are used by the current session. */ + if (ctx->state >= WOLFSPDM_STATE_KEY_EX && + ctx->state <= WOLFSPDM_STATE_CONNECTED) { + return WOLFSPDM_E_BAD_STATE; + } + + /* TH uses one certificate hash. M1 includes each certificate exchange. */ + if (ctx->transcriptLen > ctx->vcaLen) { + ctx->transcriptLen = ctx->vcaLen; + } /* The CERTIFICATE response (8-byte header + portion) must fit the * responder's DataTransferSize */ @@ -513,8 +540,15 @@ typedef struct { word32 oid; word32 len; byte der[WOLFSPDM_CERT_KEY_SZ]; + int canIssue; } WOLFSPDM_CERT_KEY; +typedef enum { + WOLFSPDM_CERT_ANCHOR, + WOLFSPDM_CERT_INTERMEDIATE, + WOLFSPDM_CERT_LEAF +} WOLFSPDM_CERT_ROLE; + #ifdef WOLFSPDM_HAVE_MLDSA static byte wolfSPDM_KeyOidMlDsaLevel(word32 oid) { @@ -545,35 +579,77 @@ static byte wolfSPDM_SigOidMlDsaLevel(word32 oid) } #endif /* WOLFSPDM_HAVE_MLDSA */ -/* Read the subject key and CA flag of a certificate */ +static int wolfSPDM_CheckCertUsage(const DecodedCert* cert, + WOLFSPDM_CERT_ROLE role, word32* pathLen) +{ + if (role == WOLFSPDM_CERT_LEAF) { + if (cert->isCA || (cert->extKeyUsageSet && + (cert->extKeyUsage & KEYUSE_DIGITAL_SIG) == 0)) { + return WOLFSPDM_E_CERT_FAIL; + } + } + else { + /* RFC 5280 counts non-self-issued intermediate CAs. */ + if (role == WOLFSPDM_CERT_INTERMEDIATE && + XMEMCMP(cert->issuerHash, cert->subjectHash, + sizeof(cert->issuerHash)) != 0) { + if (*pathLen == 0) { + return WOLFSPDM_E_CERT_FAIL; + } + (*pathLen)--; + } + if (cert->pathLengthSet && cert->pathLength < *pathLen) { + *pathLen = cert->pathLength; + } + } + return WOLFSPDM_SUCCESS; +} + +/* Read the subject key and its authorization for use in this chain. */ static int wolfSPDM_CertKey(const byte* der, word32 derSz, - WOLFSPDM_CERT_KEY* key, int* isCA) + WOLFSPDM_CERT_KEY* key, WOLFSPDM_CERT_ROLE role, word32* pathLen) { +#if defined(NO_ASN_TIME) || defined(NO_ASN_TIME_CHECK) || \ + defined(WOLFSPDM_NO_CERT_DATE_CHECK) + const int verify = NO_VERIFY; +#else + const int verify = VERIFY; +#endif DecodedCert cert; int rc; wc_InitDecodedCert(&cert, der, derSz, NULL); - rc = wc_ParseCert(&cert, CERT_TYPE, NO_VERIFY, NULL); - if (rc == 0 && cert.keyOID != ECDSAk + /* CA_TYPE even for the leaf: VERIFY checks dates without a CertManager + * issuer lookup. CertSignedBy verifies the issuer's signature. */ + rc = wc_ParseCert(&cert, CA_TYPE, verify, NULL); + if (rc != 0) { + rc = (rc == ASN_BEFORE_DATE_E || rc == ASN_AFTER_DATE_E) ? + WOLFSPDM_E_CERT_FAIL : WOLFSPDM_E_CERT_PARSE; + goto cleanup; + } + if (cert.keyOID != ECDSAk #ifdef WOLFSPDM_HAVE_MLDSA && wolfSPDM_KeyOidMlDsaLevel(cert.keyOID) == 0 #endif ) { - rc = -1; + rc = WOLFSPDM_E_CERT_PARSE; + goto cleanup; } - if (rc == 0 && (cert.publicKey == NULL || - cert.pubKeySize > sizeof(key->der))) { - rc = -1; + if (cert.publicKey == NULL || cert.pubKeySize > sizeof(key->der)) { + rc = WOLFSPDM_E_CERT_PARSE; + goto cleanup; } - if (rc == 0) { + rc = wolfSPDM_CheckCertUsage(&cert, role, pathLen); + if (rc == WOLFSPDM_SUCCESS) { key->oid = cert.keyOID; key->len = cert.pubKeySize; XMEMCPY(key->der, cert.publicKey, cert.pubKeySize); - *isCA = cert.isCA; + key->canIssue = cert.isCA && (!cert.extKeyUsageSet || + (cert.extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0); } +cleanup: wc_FreeDecodedCert(&cert); - - return (rc == 0) ? WOLFSPDM_SUCCESS : WOLFSPDM_E_CERT_PARSE; + return rc; } /* ECDSA verify of hash under an ECC SubjectPublicKeyInfo */ @@ -703,8 +779,8 @@ int wolfSPDM_ValidateCertChain(WOLFSPDM_CTX* ctx) WOLFSPDM_CERT_KEY key; word32 leafSz = WOLFSPDM_RSP_PUBKEY_SZ; word32 pos = WOLFSPDM_CERT_CHAIN_HDR_SZ; + word32 pathLen = WOLFSPDM_MAX_CERT_CHAIN; int haveKey = 0; - int isCA = 0; int anchored = 0; int rc = WOLFSPDM_SUCCESS; @@ -734,7 +810,7 @@ int wolfSPDM_ValidateCertChain(WOLFSPDM_CTX* ctx) } if (rc == WOLFSPDM_SUCCESS) { rc = wolfSPDM_CertKey(ctx->trustedCA, ctx->trustedCASz, &key, - &isCA); + WOLFSPDM_CERT_ANCHOR, &pathLen); haveKey = (rc == WOLFSPDM_SUCCESS); } anchored = 1; @@ -743,20 +819,30 @@ int wolfSPDM_ValidateCertChain(WOLFSPDM_CTX* ctx) while (rc == WOLFSPDM_SUCCESS && pos < ctx->certChainLen) { word32 certSz = wolfSPDM_DerSeqLen(ctx->certChain + pos, ctx->certChainLen - pos); + int anchorCopy = (anchored && pos == WOLFSPDM_CERT_CHAIN_HDR_SZ && + certSz == ctx->trustedCASz && + XMEMCMP(ctx->certChain + pos, ctx->trustedCA, certSz) == 0); + if (certSz == 0) { rc = WOLFSPDM_E_CERT_PARSE; } /* The configured root is the anchor; its own signature adds nothing */ - if (rc == WOLFSPDM_SUCCESS && haveKey && - !(anchored && pos == WOLFSPDM_CERT_CHAIN_HDR_SZ && - certSz == ctx->trustedCASz && - XMEMCMP(ctx->certChain + pos, ctx->trustedCA, - certSz) == 0)) { - rc = isCA ? wolfSPDM_CertSignedBy(ctx->certChain + pos, certSz, - &key) : WOLFSPDM_E_CERT_FAIL; + if (rc == WOLFSPDM_SUCCESS && haveKey && !anchorCopy) { + rc = key.canIssue ? wolfSPDM_CertSignedBy(ctx->certChain + pos, + certSz, &key) : WOLFSPDM_E_CERT_FAIL; } if (rc == WOLFSPDM_SUCCESS) { - rc = wolfSPDM_CertKey(ctx->certChain + pos, certSz, &key, &isCA); + WOLFSPDM_CERT_ROLE role; + + if (certSz == ctx->certChainLen - pos) { + role = WOLFSPDM_CERT_LEAF; + } + else { + role = (anchorCopy || !haveKey) ? WOLFSPDM_CERT_ANCHOR : + WOLFSPDM_CERT_INTERMEDIATE; + } + rc = wolfSPDM_CertKey(ctx->certChain + pos, certSz, &key, role, + &pathLen); haveKey = (rc == WOLFSPDM_SUCCESS); } pos += certSz; @@ -848,21 +934,6 @@ int wolfSPDM_ConnectStandard(WOLFSPDM_CTX* ctx) int slot = 0; int rc; - /* A key taken from a previous responder's chain is not a trust anchor */ - if (ctx->flags.rspKeyFromCert) { - ctx->flags.hasRspPubKey = 0; - ctx->flags.rspKeyFromCert = 0; - ctx->rspPubKeyLen = 0; - } - ctx->state = WOLFSPDM_STATE_INIT; - ctx->lastPeerErrorCode = 0; - /* No chunking or other peer capability until CAPABILITIES says so */ - ctx->rspCaps = 0; - wolfSPDM_TranscriptReset(ctx); -#if !defined(WOLFSPDM_NO_MEAS) || !defined(WOLFSPDM_NO_CHALLENGE) - wolfSPDM_AttestFree(ctx); -#endif - SPDM_CONNECT_STEP(ctx, "GET_VERSION\n", wolfSPDM_GetVersion(ctx)); SPDM_CONNECT_STEP(ctx, "GET_CAPABILITIES\n", wolfSPDM_GetCapabilities(ctx)); @@ -881,9 +952,13 @@ int wolfSPDM_ConnectStandard(WOLFSPDM_CTX* ctx) wolfSPDM_ValidateCertChain(ctx)); SPDM_CONNECT_STEP(ctx, "KEY_EXCHANGE\n", wolfSPDM_KeyExchangeValidated(ctx)); - SPDM_CONNECT_STEP(ctx, "FINISH\n", wolfSPDM_Finish(ctx)); + wolfSPDM_DebugPrint(ctx, "FINISH\n"); + rc = wolfSPDM_Finish(ctx); + if (rc != WOLFSPDM_SUCCESS) { + wolfSPDM_RetireSession(ctx); + return rc; + } - ctx->state = WOLFSPDM_STATE_CONNECTED; wolfSPDM_DebugPrint(ctx, "SPDM session established, SessionID=0x%08x\n", ctx->sessionId); return WOLFSPDM_SUCCESS; diff --git a/src/spdm_tcg.c b/src/spdm_tcg.c index b3848c0..0f7cd6a 100644 --- a/src/spdm_tcg.c +++ b/src/spdm_tcg.c @@ -31,8 +31,91 @@ #include +/* VENDOR_DEFINED responses use the same payload layout as requests. */ +static int VendorDefinedPayload(const byte* buf, word32 bufSz, + word32* offset, word32* len) +{ + if (bufSz < 9 + WOLFSPDM_VDCODE_LEN) { + return WOLFSPDM_E_BUFFER_SMALL; + } + + *offset = 7 + buf[6]; /* Skip StandardID and VendorID. */ + if (*offset + 2 > bufSz) { + return WOLFSPDM_E_BUFFER_SMALL; + } + *len = SPDM_Get16LE(buf + *offset); + *offset += 2; + if (*len < WOLFSPDM_VDCODE_LEN || *len > bufSz - *offset) { + return WOLFSPDM_E_BUFFER_SMALL; + } + + return WOLFSPDM_SUCCESS; +} + /* ----- Vendor Command Helpers ----- */ +/* Every locality-aware TPM2CMDn request is answered with TPM2_CMD. */ +static const char* TcgResponseVdCode(const char* vdCode) +{ + char locality = vdCode[WOLFSPDM_VDCODE_LEN - 1]; + + if (XMEMCMP(vdCode, WOLFSPDM_VDCODE_TPM2CMD0, + WOLFSPDM_VDCODE_LEN - 1) == 0 && + locality >= '0' && locality <= '4') { + return WOLFSPDM_VDCODE_TPM2_CMD; + } + return vdCode; +} + +static int TcgCheckVendorResponse(WOLFSPDM_CTX* ctx, byte ver, + const char* vdCode, const byte* buf, word32 bufSz, WOLFSPDM_VENDOR_RSP* rsp) +{ + word32 offset; + word32 len; + int rc; + + if (bufSz >= 4 && buf[1] == SPDM_ERROR) { + wolfSPDM_DebugPrint(ctx, "%s: SPDM ERROR 0x%02x 0x%02x\n", + vdCode, buf[2], buf[3]); + ctx->lastPeerErrorCode = buf[2]; + return WOLFSPDM_E_PEER_ERROR; + } + if (bufSz < 4) { + return WOLFSPDM_E_BUFFER_SMALL; + } + /* The requests use the 16-bit length form. */ + if (buf[0] != ver || buf[1] != SPDM_VENDOR_DEFINED_RESPONSE || + (buf[2] & 0x80) != 0) { + return WOLFSPDM_E_FRAMING; + } + + rc = VendorDefinedPayload(buf, bufSz, &offset, &len); + if (rc != WOLFSPDM_SUCCESS) { + return rc; + } + if (len != bufSz - offset || SPDM_Get16LE(buf + 4) != 0x0001) { + return WOLFSPDM_E_FRAMING; + } + if (XMEMCMP(buf + offset, TcgResponseVdCode(vdCode), + WOLFSPDM_VDCODE_LEN) != 0) { + wolfSPDM_DebugPrint(ctx, "%s: unexpected VdCode '%.8s'\n", + vdCode, buf + offset); + return WOLFSPDM_E_PEER_ERROR; + } + if (rsp != NULL) { + len -= WOLFSPDM_VDCODE_LEN; + if (len > sizeof(rsp->payload)) { + return WOLFSPDM_E_BUFFER_SMALL; + } + XMEMCPY(rsp->vdCode, buf + offset, WOLFSPDM_VDCODE_LEN); + rsp->vdCode[WOLFSPDM_VDCODE_LEN] = '\0'; + XMEMCPY(rsp->payload, buf + offset + WOLFSPDM_VDCODE_LEN, len); + rsp->payloadSz = len; + } + + return WOLFSPDM_SUCCESS; +} + int wolfSPDM_TCG_VendorCmdClear(WOLFSPDM_CTX* ctx, const char* vdCode, const byte* payload, word32 payloadSz, WOLFSPDM_VENDOR_RSP* rsp) { @@ -58,28 +141,8 @@ int wolfSPDM_TCG_VendorCmdClear(WOLFSPDM_CTX* ctx, const char* vdCode, &rxSz); } - if (rc == WOLFSPDM_SUCCESS && rxSz >= 4 && rxBuf[1] == SPDM_ERROR) { - wolfSPDM_DebugPrint(ctx, "%s: SPDM ERROR 0x%02x 0x%02x\n", - vdCode, rxBuf[2], rxBuf[3]); - ctx->lastPeerErrorCode = rxBuf[2]; - rc = WOLFSPDM_E_PEER_ERROR; - } - - if (rc == WOLFSPDM_SUCCESS && rsp != NULL) { - rsp->payloadSz = sizeof(rsp->payload); - XMEMSET(rsp->vdCode, 0, sizeof(rsp->vdCode)); - rc = wolfSPDM_ParseVendorDefined(rxBuf, rxSz, - rsp->vdCode, rsp->payload, &rsp->payloadSz); - if (rc >= 0) { - rc = WOLFSPDM_SUCCESS; - } - /* Validate response VdCode matches the request */ - if (rc == WOLFSPDM_SUCCESS && - XMEMCMP(rsp->vdCode, vdCode, WOLFSPDM_VDCODE_LEN) != 0) { - wolfSPDM_DebugPrint(ctx, "%s: unexpected VdCode '%.8s'\n", - vdCode, rsp->vdCode); - rc = WOLFSPDM_E_PEER_ERROR; - } + if (rc == WOLFSPDM_SUCCESS) { + rc = TcgCheckVendorResponse(ctx, ver, vdCode, rxBuf, rxSz, rsp); } /* PSK_SET_ and PSK_CLR_ carry secrets */ @@ -114,10 +177,8 @@ int wolfSPDM_TCG_VendorCmdSecured(WOLFSPDM_CTX* ctx, const char* vdCode, decBuf, &decSz); } - if (rc == WOLFSPDM_SUCCESS && decSz >= 4 && decBuf[1] == SPDM_ERROR) { - wolfSPDM_DebugPrint(ctx, "%s: SPDM ERROR 0x%02x 0x%02x\n", - vdCode, decBuf[2], decBuf[3]); - rc = WOLFSPDM_E_PEER_ERROR; + if (rc == WOLFSPDM_SUCCESS) { + rc = TcgCheckVendorResponse(ctx, ver, vdCode, decBuf, decSz, NULL); } /* Always zero sensitive stack buffers */ @@ -140,12 +201,13 @@ int wolfSPDM_BuildTcgClearMessage( return WOLFSPDM_E_INVALID_ARG; } - totalSz = WOLFSPDM_TCG_HEADER_SIZE + spdmPayloadSz; - - if (outBufSz < totalSz) { + if (outBufSz < WOLFSPDM_TCG_HEADER_SIZE || + spdmPayloadSz > outBufSz - WOLFSPDM_TCG_HEADER_SIZE || + spdmPayloadSz > WOLFSPDM_MAX_MSG_SIZE) { return WOLFSPDM_E_BUFFER_SMALL; } + totalSz = WOLFSPDM_TCG_HEADER_SIZE + spdmPayloadSz; wolfSPDM_WriteTcgHeader(outBuf, WOLFSPDM_TCG_TAG_CLEAR, totalSz, ctx->connectionHandle, ctx->fipsIndicator); XMEMCPY(outBuf + WOLFSPDM_TCG_HEADER_SIZE, spdmPayload, spdmPayloadSz); @@ -268,41 +330,19 @@ int wolfSPDM_ParseVendorDefined( char* vdCode, byte* payload, word32* payloadSz) { - word32 offset = 0; - word16 reqLength; + word32 offset; + word32 reqLength; word32 dataLen; - byte vendorIdLen; + int rc; if (inBuf == NULL || vdCode == NULL || payload == NULL || payloadSz == NULL) { return WOLFSPDM_E_INVALID_ARG; } - /* Minimum: version(1) + code(1) + param1(1) + param2(1) + stdId(2/LE) + - * vidLen(1) + reqLen(2/LE) + vdCode(8) = 17 */ - if (inBufSz < 17) { - return WOLFSPDM_E_BUFFER_SMALL; - } - - offset += 1; /* SPDM version */ - offset += 3; /* request/response code + params */ - offset += 2; /* standard ID */ - vendorIdLen = inBuf[offset]; - offset += 1 + vendorIdLen; - - if (offset + 2 > inBufSz) { - return WOLFSPDM_E_BUFFER_SMALL; - } - - reqLength = SPDM_Get16LE(inBuf + offset); - offset += 2; - - if (reqLength < WOLFSPDM_VDCODE_LEN) { - return WOLFSPDM_E_BUFFER_SMALL; - } - - if (offset + reqLength > inBufSz) { - return WOLFSPDM_E_BUFFER_SMALL; + rc = VendorDefinedPayload(inBuf, inBufSz, &offset, &reqLength); + if (rc != WOLFSPDM_SUCCESS) { + return rc; } XMEMCPY(vdCode, inBuf + offset, WOLFSPDM_VDCODE_LEN); @@ -366,7 +406,6 @@ int wolfSPDM_TCG_GetPubKey( /* Responders reject GET_PUBK with UnexpectedRequest before GET_VERSION */ if (ctx->state == WOLFSPDM_STATE_INIT) { - wolfSPDM_TranscriptReset(ctx); rc = wolfSPDM_GetVersion(ctx); if (rc != WOLFSPDM_SUCCESS) { wolfSPDM_DebugPrint(ctx, "GET_PUBK: GET_VERSION failed %d\n", rc); @@ -458,6 +497,7 @@ static int wolfSPDM_TCG_CheckResponse(WOLFSPDM_CTX* ctx, const byte* rsp, return WOLFSPDM_E_BUFFER_SMALL; } if (wolfSPDM_CheckError(rsp, rspSz, &errorCode)) { + ctx->lastPeerErrorCode = (byte)errorCode; wolfSPDM_DebugPrint(ctx, "SPDM error: 0x%02x\n", errorCode); return WOLFSPDM_E_PEER_ERROR; } @@ -608,7 +648,8 @@ int wolfSPDM_TCG_NegotiateAlgorithms(WOLFSPDM_CTX* ctx) algReq[off++] = 0x04; /* Param1: NumAlgStructs = 4 */ algReq[off++] = 0x00; algReq[off++] = 0x30; algReq[off++] = 0x00; /* Length = 48 */ - algReq[off++] = 0x00; algReq[off++] = 0x02; /* MeasurementSpec + Reserved */ + algReq[off++] = 0x00; /* MeasurementSpecification */ + algReq[off++] = 0x02; /* OtherParamsSupport advertises OpaqueDataFmt1 */ /* BaseAsymAlgo: ECDSA_ECC_NIST_P384 */ algReq[off++] = 0x80; algReq[off++] = 0x00; algReq[off++] = 0x00; algReq[off++] = 0x00; @@ -663,7 +704,10 @@ int wolfSPDM_ConnectTCG(WOLFSPDM_CTX* ctx) } if (!ctx->flags.hasRspPubKey || - ctx->rspPubKeyLen != WOLFSPDM_ECC_POINT_SIZE) { +#ifndef WOLFSPDM_NO_CERT + ctx->flags.rspKeyFromCert || +#endif + ctx->rspPubKeyLen != WOLFSPDM_ECC_POINT_SIZE) { wolfSPDM_DebugPrint(ctx, "TCG: Trusted responder public key is not configured\n"); return WOLFSPDM_E_BAD_STATE; @@ -675,9 +719,6 @@ int wolfSPDM_ConnectTCG(WOLFSPDM_CTX* ctx) wolfSPDM_DebugPrint(ctx, "TCG: Starting SPDM connection\n"); - ctx->state = WOLFSPDM_STATE_INIT; - wolfSPDM_TranscriptReset(ctx); - /* Step 1: GET_VERSION */ SPDM_CONNECT_STEP(ctx, "TCG Step 1: GET_VERSION\n", wolfSPDM_GetVersion(ctx)); @@ -731,8 +772,6 @@ int wolfSPDM_ConnectTCG(WOLFSPDM_CTX* ctx) ctx->reqPubKeyTPMTLen); if (rc != WOLFSPDM_SUCCESS) { wolfSPDM_DebugPrint(ctx, "GIVE_PUB failed: %d\n", rc); - ctx->state = WOLFSPDM_STATE_ERROR; - return rc; } } else { wolfSPDM_DebugPrint(ctx, @@ -740,10 +779,15 @@ int wolfSPDM_ConnectTCG(WOLFSPDM_CTX* ctx) } /* Step 7: FINISH */ - SPDM_CONNECT_STEP(ctx, "TCG Step 7: FINISH\n", - wolfSPDM_Finish(ctx)); + if (rc == WOLFSPDM_SUCCESS) { + wolfSPDM_DebugPrint(ctx, "TCG Step 7: FINISH\n"); + rc = wolfSPDM_Finish(ctx); + } + if (rc != WOLFSPDM_SUCCESS) { + wolfSPDM_RetireSession(ctx); + return rc; + } - ctx->state = WOLFSPDM_STATE_CONNECTED; wolfSPDM_DebugPrint(ctx, "TCG: SPDM Session Established! " "SessionID=0x%08x\n", ctx->sessionId); diff --git a/src/spdm_transcript.c b/src/spdm_transcript.c index 3b1ee55..b74118b 100644 --- a/src/spdm_transcript.c +++ b/src/spdm_transcript.c @@ -74,21 +74,24 @@ int wolfSPDM_Sha384Hash(byte* out, int rc; rc = wc_InitSha384(&sha); - if (rc != 0) return WOLFSPDM_E_CRYPTO_FAIL; + if (rc != 0) { + return WOLFSPDM_E_CRYPTO_FAIL; + } if (d1 != NULL && d1Sz > 0) { rc = wc_Sha384Update(&sha, d1, d1Sz); - if (rc != 0) { wc_Sha384Free(&sha); return WOLFSPDM_E_CRYPTO_FAIL; } } - if (d2 != NULL && d2Sz > 0) { + if (rc == 0 && d2 != NULL && d2Sz > 0) { rc = wc_Sha384Update(&sha, d2, d2Sz); - if (rc != 0) { wc_Sha384Free(&sha); return WOLFSPDM_E_CRYPTO_FAIL; } } - if (d3 != NULL && d3Sz > 0) { + if (rc == 0 && d3 != NULL && d3Sz > 0) { rc = wc_Sha384Update(&sha, d3, d3Sz); - if (rc != 0) { wc_Sha384Free(&sha); return WOLFSPDM_E_CRYPTO_FAIL; } } - rc = wc_Sha384Final(&sha, out); + if (rc == 0) { + rc = wc_Sha384Final(&sha, out); + } wc_Sha384Free(&sha); + wc_ForceZero(&sha, sizeof(sha)); + return (rc == 0) ? WOLFSPDM_SUCCESS : WOLFSPDM_E_CRYPTO_FAIL; } diff --git a/src/vendor/spdm_nations.c b/src/vendor/spdm_nations.c index 37f8e05..a50a651 100644 --- a/src/vendor/spdm_nations.c +++ b/src/vendor/spdm_nations.c @@ -68,6 +68,7 @@ int wolfSPDM_Nations_GetStatus(WOLFSPDM_CTX* ctx, status->spdmEnabled = 1; status->pskProvisioned = (rsp.payload[2] != 0); status->spdmOnlyLocked = (rsp.payload[3] != 0); + status->spdmOnlyPending = (rsp.payload[3] == 0x81); wolfSPDM_DebugPrint(ctx, "GET_STS_: v%u.%u PSK=%s SPDMOnly=0x%02x\n", rsp.payload[0], rsp.payload[1], status->pskProvisioned ? "YES" : "NO", diff --git a/test/unit_test.c b/test/unit_test.c index 86f0307..8fcb7ec 100644 --- a/test/unit_test.c +++ b/test/unit_test.c @@ -29,6 +29,7 @@ #endif #include "spdm_internal.h" #ifndef WOLFSPDM_NO_CERT + #include #include "test_certs.h" #endif #ifdef WOLFSPDM_HAVE_MLDSA @@ -41,6 +42,20 @@ static int g_testsPassed = 0; static int g_testsFailed = 0; +#if !defined(WOLFSPDM_NO_CERT) && !defined(NO_ASN_TIME) && \ + !defined(NO_ASN_TIME_CHECK) +/* Keep the certificate fixtures inside their validity periods. */ +static time_t g_certificateTime = 1798761600; /* 2027-01-01 UTC */ + +static time_t test_certificate_clock(time_t* now) +{ + if (now != NULL) { + *now = g_certificateTime; + } + return g_certificateTime; +} +#endif + #define TEST_ASSERT(cond, msg) do { \ if (!(cond)) { \ printf(" FAIL: %s (line %d)\n", msg, __LINE__); \ @@ -74,6 +89,19 @@ static int g_testsFailed = 0; #define TEST_CTX_FREE() \ wolfSPDM_Free(ctx) +static int test_handshake_secrets_cleared(const WOLFSPDM_CTX* ctx) +{ + static const byte zero[WOLFSPDM_HASH_SIZE]; + + return ctx->sharedSecretSz == 0 && !ctx->flags.ephemeralKeyInit && + XMEMCMP(ctx->sharedSecret, zero, sizeof(ctx->sharedSecret)) == 0 && + XMEMCMP(ctx->handshakeSecret, zero, sizeof(ctx->handshakeSecret)) == 0 && + XMEMCMP(ctx->reqHsSecret, zero, sizeof(ctx->reqHsSecret)) == 0 && + XMEMCMP(ctx->rspHsSecret, zero, sizeof(ctx->rspHsSecret)) == 0 && + XMEMCMP(ctx->reqFinishedKey, zero, sizeof(ctx->reqFinishedKey)) == 0 && + XMEMCMP(ctx->rspFinishedKey, zero, sizeof(ctx->rspFinishedKey)) == 0; +} + /* Dummy I/O callback for testing */ static int dummy_io_cb(WOLFSPDM_CTX* ctx, const byte* txBuf, word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) @@ -372,6 +400,67 @@ static int test_check_error(void) TEST_PASS(); } +/* After negotiation every response must carry the negotiated SPDMVersion */ +static int test_response_version_matches(void) +{ + byte buf[160]; + word32 start; +#ifndef WOLFSPDM_NO_CERT + word16 portionLen; + word16 remainderLen; +#endif + TEST_CTX_SETUP_V12(); + + printf("test_response_version_matches...\n"); + XMEMSET(buf, 0, sizeof(buf)); + buf[0] = SPDM_VERSION_13; + + buf[1] = SPDM_FINISH_RSP; + start = ctx->transcriptLen; + TEST_ASSERT(wolfSPDM_ParseFinishRsp(ctx, buf, 4) != WOLFSPDM_SUCCESS, + "FINISH_RSP version"); + ASSERT_EQ(ctx->transcriptLen, start, "FINISH_RSP not added"); + + buf[1] = SPDM_KEY_EXCHANGE_RSP; + ASSERT_EQ(wolfSPDM_ParseKeyExchangeRsp(ctx, buf, sizeof(buf)), + WOLFSPDM_E_KEY_EXCHANGE, "KEY_EXCHANGE_RSP version"); + ASSERT_EQ(ctx->transcriptLen, start, "KEY_EXCHANGE_RSP not added"); + +#ifdef WOLFSPDM_PSK + buf[1] = SPDM_PSK_EXCHANGE_RSP; + ASSERT_EQ(wolfSPDM_ParsePskExchangeRsp(ctx, buf, 12 + WOLFSPDM_HASH_SIZE), + WOLFSPDM_E_KEY_EXCHANGE, "PSK_EXCHANGE_RSP version"); + ASSERT_EQ(ctx->transcriptLen, start, "PSK_EXCHANGE_RSP not added"); + + buf[1] = SPDM_PSK_FINISH_RSP; + TEST_ASSERT(wolfSPDM_ParsePskFinishRsp(ctx, buf, 4) != WOLFSPDM_SUCCESS, + "PSK_FINISH_RSP version"); + ASSERT_EQ(ctx->transcriptLen, start, "PSK_FINISH_RSP not added"); +#endif + +#ifndef WOLFSPDM_NO_CERT + buf[1] = SPDM_DIGESTS; + ASSERT_EQ(wolfSPDM_ParseDigests(ctx, buf, 4), WOLFSPDM_E_CERT_FAIL, + "DIGESTS version"); + buf[1] = SPDM_CERTIFICATE; + ASSERT_EQ(wolfSPDM_ParseCertificate(ctx, buf, 8, &portionLen, + &remainderLen), WOLFSPDM_E_CERT_FAIL, "CERTIFICATE version"); + + buf[0] = SPDM_VERSION_12; + buf[1] = SPDM_DIGESTS; + ASSERT_SUCCESS(wolfSPDM_ParseDigests(ctx, buf, 4)); + buf[1] = SPDM_CERTIFICATE; + ASSERT_SUCCESS(wolfSPDM_ParseCertificate(ctx, buf, 8, &portionLen, + &remainderLen)); +#endif + buf[0] = SPDM_VERSION_12; + buf[1] = SPDM_FINISH_RSP; + ASSERT_SUCCESS(wolfSPDM_ParseFinishRsp(ctx, buf, 4)); + + TEST_CTX_FREE(); + TEST_PASS(); +} + static int test_error_strings(void) { printf("test_error_strings...\n"); @@ -488,6 +577,24 @@ static int test_version_fallback(void) printf("test_version_fallback...\n"); +#ifdef WOLFSPDM_PROFILE_TPM + /* The TPM profile speaks only TCG, even before a mode is set */ + ASSERT_SUCCESS(wolfSPDM_ParseVersion(ctx, rsp, sizeof(rsp))); + ASSERT_EQ(ctx->spdmVersion, SPDM_VERSION_13, "TPM profile legacy count"); + ctx->state = WOLFSPDM_STATE_INIT; + ctx->spdmVersion = 0; +#elif !defined(WOLFSPDM_NO_MCTP) + ASSERT_EQ(wolfSPDM_ParseVersion(ctx, rsp, sizeof(rsp)), + WOLFSPDM_E_VERSION_MISMATCH, "Standard VERSION needs its entry count"); + ASSERT_EQ(ctx->state, WOLFSPDM_STATE_INIT, "No version was negotiated"); +#endif + +#ifdef WOLFSPDM_TCG + ASSERT_SUCCESS(wolfSPDM_SetMode(ctx, WOLFSPDM_MODE_TCG)); +#else + rsp[5] = 4; +#endif + /* With no maxVersion set, should select 1.3 (highest mutual) */ ASSERT_SUCCESS(wolfSPDM_ParseVersion(ctx, rsp, sizeof(rsp))); ASSERT_EQ(ctx->spdmVersion, SPDM_VERSION_13, @@ -778,6 +885,8 @@ static int test_key_exchange_rsp_hmac_check(void) rc = wolfSPDM_ParseKeyExchangeRsp(ctx, keRsp, keRspLen); ASSERT_EQ(rc, WOLFSPDM_E_BAD_HMAC, "flipped rspVerifyData byte must return BAD_HMAC"); + TEST_ASSERT(test_handshake_secrets_cleared(ctx), + "Rejected key exchange must retire handshake material"); wc_ecc_free(<Key); wc_ecc_free(&respEphem); @@ -845,6 +954,8 @@ static int test_extract_ecc_point(void) #ifdef WOLFSPDM_TCG #define SPDM_TEST_VENDOR_DEFINED_RSP 0x7E +#define SPDM_TEST_GET_CAPABILITIES 0xE1 +#define SPDM_TEST_CAPABILITIES 0x61 typedef struct TCG_GET_PUB_KEY_IO_CTX { const byte* pubKey; @@ -913,6 +1024,81 @@ static int tcg_get_pub_key_io_cb(WOLFSPDM_CTX* ctx, const byte* txBuf, return 0; } +typedef struct TEST_FIPS_IO { + word32 sizeAdjust; + word16 indicator; +} TEST_FIPS_IO; + +static int test_fips_io_cb(WOLFSPDM_CTX* ctx, const byte* txBuf, + word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + const TEST_FIPS_IO* io = (const TEST_FIPS_IO*)userCtx; + static const byte versionRsp[] = { + SPDM_VERSION_10, SPDM_VERSION, 0x00, 0x00, 0x00, 0x01, + 0x00, SPDM_VERSION_13 + }; + word32 totalSz = WOLFSPDM_TCG_HEADER_SIZE + (word32)sizeof(versionRsp); + + (void)txBuf; + (void)txSz; + if (*rxSz < totalSz) { + return -1; + } + wolfSPDM_WriteTcgHeader(rxBuf, WOLFSPDM_TCG_TAG_CLEAR, + totalSz + io->sizeAdjust, ctx->connectionHandle, io->indicator); + XMEMCPY(rxBuf + WOLFSPDM_TCG_HEADER_SIZE, versionRsp, sizeof(versionRsp)); + *rxSz = totalSz; + return 0; +} + +/* The cached FIPS indicator follows the last well-framed response */ +static int test_tcg_fips_indicator_tracks_response(void) +{ + byte getVersion[4] = { SPDM_VERSION_10, SPDM_GET_VERSION, 0, 0 }; + byte rx[64]; + word32 rxSz; + static TEST_FIPS_IO io; + TEST_CTX_SETUP(); + + printf("test_tcg_fips_indicator_tracks_response...\n"); + XMEMSET(&io, 0, sizeof(io)); + ASSERT_SUCCESS(wolfSPDM_SetMode(ctx, WOLFSPDM_MODE_TCG)); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, test_fips_io_cb, &io)); + + io.indicator = WOLFSPDM_FIPS_APPROVED; + rxSz = sizeof(rx); + ASSERT_SUCCESS(wolfSPDM_SendReceive(ctx, getVersion, sizeof(getVersion), + rx, &rxSz)); + ASSERT_EQ(wolfSPDM_GetFipsIndicator(ctx), WOLFSPDM_FIPS_APPROVED, + "Approved response"); + + io.indicator = WOLFSPDM_FIPS_NON_FIPS; + rxSz = sizeof(rx); + ASSERT_SUCCESS(wolfSPDM_SendReceive(ctx, getVersion, sizeof(getVersion), + rx, &rxSz)); + ASSERT_EQ(wolfSPDM_GetFipsIndicator(ctx), WOLFSPDM_FIPS_NON_FIPS, + "Zero replaces an earlier approval"); + + io.indicator = WOLFSPDM_FIPS_APPROVED; + io.sizeAdjust = 1; + rxSz = sizeof(rx); + TEST_ASSERT(wolfSPDM_SendReceive(ctx, getVersion, sizeof(getVersion), + rx, &rxSz) != WOLFSPDM_SUCCESS, "Oversized TCG length"); + ASSERT_EQ(wolfSPDM_GetFipsIndicator(ctx), WOLFSPDM_FIPS_NON_FIPS, + "Malformed framing sets no approval"); + + io.indicator = 0x0003; + io.sizeAdjust = 0; + rxSz = sizeof(rx); + ASSERT_SUCCESS(wolfSPDM_SendReceive(ctx, getVersion, sizeof(getVersion), + rx, &rxSz)); + ASSERT_EQ(wolfSPDM_GetFipsIndicator(ctx), WOLFSPDM_FIPS_NON_FIPS, + "Reserved bits are not an approval"); + + TEST_CTX_FREE(); + TEST_PASS(); +} + static int test_tcg_get_pub_key_preserves_pin(void) { byte trustedKey[WOLFSPDM_ECC_POINT_SIZE]; @@ -921,7 +1107,7 @@ static int test_tcg_get_pub_key_preserves_pin(void) byte pubKey[sizeof(tpmtPublic)]; word32 pubKeySz; int rc; - TCG_GET_PUB_KEY_IO_CTX ioCtx; + static TCG_GET_PUB_KEY_IO_CTX ioCtx; TEST_CTX_SETUP(); printf("test_tcg_get_pub_key_preserves_pin...\n"); @@ -1092,6 +1278,167 @@ static int test_tcg_get_pub_key_version_failure(void) TEST_PASS(); } +static int test_tcg_reply(const byte* txBuf, word32 txSz, byte* rxBuf, + word32* rxSz, WOLFSPDM_CTX* peer, const byte* reply, word32 replySz) +{ + word32 payloadSz; + word16 tag; + + if (txSz < WOLFSPDM_TCG_HEADER_SIZE || + *rxSz < WOLFSPDM_TCG_HEADER_SIZE + replySz) { + return -1; + } + tag = SPDM_Get16BE(txBuf); + if (tag == WOLFSPDM_TCG_TAG_CLEAR) { + XMEMCPY(rxBuf + WOLFSPDM_TCG_HEADER_SIZE, reply, replySz); + payloadSz = replySz; + } + else if (tag == WOLFSPDM_TCG_TAG_SECURED && peer != NULL) { + payloadSz = *rxSz - WOLFSPDM_TCG_HEADER_SIZE; + if (wolfSPDM_EncryptInternal(peer, reply, + replySz, rxBuf + WOLFSPDM_TCG_HEADER_SIZE, + &payloadSz) != WOLFSPDM_SUCCESS) { + return -1; + } + } + else { + return -1; + } + *rxSz = WOLFSPDM_TCG_HEADER_SIZE + payloadSz; + wolfSPDM_WriteTcgHeader(rxBuf, tag, *rxSz, 0, 0); + return 0; +} + +static int test_tcg_peer_error_io(WOLFSPDM_CTX* ctx, const byte* txBuf, + word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + byte error[] = { ctx->spdmVersion, SPDM_ERROR, SPDM_ERROR_BUSY, 0 }; + + return test_tcg_reply(txBuf, txSz, rxBuf, rxSz, (WOLFSPDM_CTX*)userCtx, + error, sizeof(error)); +} + +static int test_tcg_vca_reports_peer_error(void) +{ + TEST_CTX_SETUP_V12(); + printf("test_tcg_vca_reports_peer_error...\n"); + ASSERT_SUCCESS(wolfSPDM_SetMode(ctx, WOLFSPDM_MODE_TCG)); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, test_tcg_peer_error_io, NULL)); + + ASSERT_EQ(wolfSPDM_TCG_GetCapabilities(ctx, WOLFSPDM_TCG_CAPS_FLAGS_DEFAULT), + WOLFSPDM_E_PEER_ERROR, "CAPABILITIES rejection"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), SPDM_ERROR_BUSY, + "CAPABILITIES peer error code"); + ctx->lastPeerErrorCode = 0; + ASSERT_EQ(wolfSPDM_TCG_NegotiateAlgorithms(ctx), WOLFSPDM_E_PEER_ERROR, + "ALGORITHMS rejection"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), SPDM_ERROR_BUSY, + "ALGORITHMS peer error code"); + + TEST_CTX_FREE(); + TEST_PASS(); +} + +static int test_tcg_setup_session(WOLFSPDM_CTX* ctx, WOLFSPDM_CTX* peer) +{ + ASSERT_SUCCESS(wolfSPDM_Init(peer)); + ASSERT_SUCCESS(wolfSPDM_SetMode(ctx, WOLFSPDM_MODE_TCG)); + ASSERT_SUCCESS(wolfSPDM_SetMode(peer, WOLFSPDM_MODE_TCG)); + ctx->state = WOLFSPDM_STATE_CONNECTED; + ctx->sessionId = 0x00020001; + peer->sessionId = ctx->sessionId; + XMEMSET(ctx->reqDataKey, 0x11, sizeof(ctx->reqDataKey)); + XMEMSET(ctx->reqDataIv, 0x22, sizeof(ctx->reqDataIv)); + XMEMSET(ctx->rspDataKey, 0x33, sizeof(ctx->rspDataKey)); + XMEMSET(ctx->rspDataIv, 0x44, sizeof(ctx->rspDataIv)); + XMEMCPY(peer->reqDataKey, ctx->rspDataKey, sizeof(peer->reqDataKey)); + XMEMCPY(peer->reqDataIv, ctx->rspDataIv, sizeof(peer->reqDataIv)); + return 0; +} + +static int test_tcg_secured_vendor_reports_peer_error(void) +{ + WOLFSPDM_CTX peer; + TEST_CTX_SETUP_V12(); + printf("test_tcg_secured_vendor_reports_peer_error...\n"); + ASSERT_SUCCESS(test_tcg_setup_session(ctx, &peer)); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, test_tcg_peer_error_io, &peer)); + + ASSERT_EQ(wolfSPDM_TCG_VendorCmdSecured(ctx, WOLFSPDM_VDCODE_GET_STS, + NULL, 0), WOLFSPDM_E_PEER_ERROR, "Secured vendor command rejection"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), SPDM_ERROR_BUSY, + "Secured vendor command peer error code"); + + wolfSPDM_Free(&peer); + TEST_CTX_FREE(); + TEST_PASS(); +} + +typedef struct TEST_TCG_VENDOR_REPLY { + WOLFSPDM_CTX* peer; + const char* vdCode; +} TEST_TCG_VENDOR_REPLY; + +static int test_tcg_vendor_reply_io(WOLFSPDM_CTX* ctx, const byte* txBuf, + word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + const TEST_TCG_VENDOR_REPLY* reply = (const TEST_TCG_VENDOR_REPLY*)userCtx; + byte msg[WOLFSPDM_VENDOR_BUF_SZ]; + int sz; + + sz = wolfSPDM_BuildVendorDefined(ctx->spdmVersion, reply->vdCode, + NULL, 0, msg, sizeof(msg)); + if (sz < 0) { + return sz; + } + msg[1] = SPDM_TEST_VENDOR_DEFINED_RSP; + return test_tcg_reply(txBuf, txSz, rxBuf, rxSz, reply->peer, + msg, (word32)sz); +} + +static int test_tcg_clear_vendor_ack(void) +{ + TEST_TCG_VENDOR_REPLY reply = { NULL, WOLFSPDM_VDCODE_GET_STS }; + TEST_CTX_SETUP_V12(); + + printf("test_tcg_clear_vendor_ack...\n"); + ASSERT_SUCCESS(wolfSPDM_SetMode(ctx, WOLFSPDM_MODE_TCG)); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, test_tcg_vendor_reply_io, &reply)); + ASSERT_SUCCESS(wolfSPDM_TCG_VendorCmdClear(ctx, reply.vdCode, NULL, 0, + NULL)); + ASSERT_EQ(wolfSPDM_TCG_VendorCmdClear(ctx, WOLFSPDM_VDCODE_GET_PUBK, + NULL, 0, NULL), WOLFSPDM_E_PEER_ERROR, "Unrelated reply is rejected"); + TEST_CTX_FREE(); + TEST_PASS(); +} + +static int test_tcg_secured_vendor_ack(void) +{ + WOLFSPDM_CTX peer; + TEST_TCG_VENDOR_REPLY reply = { &peer, WOLFSPDM_VDCODE_GET_STS }; + TEST_CTX_SETUP_V12(); + + printf("test_tcg_secured_vendor_ack...\n"); + ASSERT_SUCCESS(test_tcg_setup_session(ctx, &peer)); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, test_tcg_vendor_reply_io, &reply)); + ASSERT_SUCCESS(wolfSPDM_TCG_VendorCmdSecured(ctx, reply.vdCode, NULL, 0)); + ASSERT_EQ(wolfSPDM_TCG_VendorCmdSecured(ctx, WOLFSPDM_VDCODE_GET_PUBK, + NULL, 0), WOLFSPDM_E_PEER_ERROR, "Unrelated reply is rejected"); + + reply.vdCode = WOLFSPDM_VDCODE_TPM2_CMD; + ASSERT_SUCCESS(wolfSPDM_TCG_VendorCmdSecured(ctx, + WOLFSPDM_VDCODE_TPM2_CMD, NULL, 0)); + ASSERT_SUCCESS(wolfSPDM_TCG_VendorCmdSecured(ctx, + WOLFSPDM_VDCODE_TPM2CMD0, NULL, 0)); + ASSERT_SUCCESS(wolfSPDM_TCG_VendorCmdSecured(ctx, + WOLFSPDM_VDCODE_TPM2CMD4, NULL, 0)); + ASSERT_EQ(wolfSPDM_TCG_VendorCmdSecured(ctx, WOLFSPDM_VDCODE_GET_STS, + NULL, 0), WOLFSPDM_E_PEER_ERROR, "TPM reply only answers TPM codes"); + wolfSPDM_Free(&peer); + TEST_CTX_FREE(); + TEST_PASS(); +} + static int test_tcg_connect_requires_responder_key(void) { int rc; @@ -1500,8 +1847,11 @@ static int test_oob_read_error(void) printf("test_oob_read_error...\n"); + ctx->lastPeerErrorCode = SPDM_ERROR_BUSY; rc = wolfSPDM_ParseFinishRsp(ctx, fullErr, sizeof(fullErr)); ASSERT_EQ(rc, WOLFSPDM_E_PEER_ERROR, "Should return peer error"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), fullErr[2], + "FINISH should record the peer error code"); rc = wolfSPDM_ParseFinishRsp(ctx, shortErr, sizeof(shortErr)); ASSERT_EQ(rc, WOLFSPDM_E_INVALID_ARG, "Short buffer should fail"); @@ -1687,6 +2037,113 @@ static int test_get_version_no_io(void) TEST_PASS(); } +#ifndef WOLFSPDM_NO_MCTP +static const byte test_version_reply[] = { + SPDM_VERSION_10, SPDM_VERSION, 0, 0, 0, 1, 0, SPDM_VERSION_12 +}; + +static int test_version_restart_io(WOLFSPDM_CTX* ctx, const byte* txBuf, + word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + (void)ctx; + (void)userCtx; + if (txSz != 4 || txBuf[1] != SPDM_GET_VERSION || + *rxSz < sizeof(test_version_reply)) { + return -1; + } + XMEMCPY(rxBuf, test_version_reply, sizeof(test_version_reply)); + *rxSz = sizeof(test_version_reply); + return 0; +} + +static int test_version_min_transfer_io(WOLFSPDM_CTX* ctx, const byte* txBuf, + word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + const word32 count = (SPDM_MIN_DATA_TRANSFER_SIZE - 6) / 2; + word32 i; + + (void)ctx; + (void)userCtx; + if (txSz != 4 || txBuf[1] != SPDM_GET_VERSION || + *rxSz < SPDM_MIN_DATA_TRANSFER_SIZE) { + return -1; + } + + XMEMSET(rxBuf, 0, SPDM_MIN_DATA_TRANSFER_SIZE); + rxBuf[0] = SPDM_VERSION_10; + rxBuf[1] = SPDM_VERSION; + rxBuf[5] = (byte)count; + for (i = 0; i < count; i++) { + rxBuf[6 + i * 2] = (byte)((i % 4) << 4); + rxBuf[7 + i * 2] = (byte)(SPDM_VERSION_10 + i / 4); + } + *rxSz = SPDM_MIN_DATA_TRANSFER_SIZE; + return 0; +} + +static int test_get_version_accepts_minimum_transfer(void) +{ + TEST_CTX_SETUP(); + + printf("test_get_version_accepts_minimum_transfer...\n"); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, test_version_min_transfer_io, NULL)); + ASSERT_SUCCESS(wolfSPDM_GetVersion(ctx)); + ASSERT_EQ(ctx->spdmVersion, WOLFSPDM_MAX_SPDM_VERSION, + "Negotiate the highest supported version"); + TEST_CTX_FREE(); + TEST_PASS(); +} + +static int test_get_version_restarts_connection(void) +{ + static const byte zero[WOLFSPDM_AEAD_KEY_SIZE]; + static const byte previous[] = { SPDM_VERSION_12, SPDM_FINISH, 0, 0 }; + TEST_CTX_SETUP_V12(); + + printf("test_get_version_restarts_connection...\n"); + ctx->state = WOLFSPDM_STATE_CONNECTED; + ctx->sessionId = 0x00020001; + ctx->reqSeqNum = 3; + ctx->rspSeqNum = 2; + XMEMSET(ctx->reqDataKey, 0x5A, sizeof(ctx->reqDataKey)); +#ifndef WOLFSPDM_NO_CERT + ctx->vcaLen = sizeof(previous); + ctx->certChainLen = sizeof(previous); + ASSERT_SUCCESS(wolfSPDM_SetResponderPubKey(ctx, test_rsp_leaf_pub, + sizeof(test_rsp_leaf_pub))); + ctx->flags.rspKeyFromCert = 1; +#endif + ASSERT_SUCCESS(wolfSPDM_TranscriptAdd(ctx, previous, sizeof(previous))); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, test_version_restart_io, NULL)); + ASSERT_SUCCESS(wolfSPDM_GetVersion(ctx)); + ASSERT_EQ(ctx->state, WOLFSPDM_STATE_VERSION, "Fresh VERSION state"); + ASSERT_EQ(ctx->transcriptLen, (word32)(4 + sizeof(test_version_reply)), + "Transcript should contain the fresh VERSION exchange"); + ASSERT_EQ(ctx->transcript[1], SPDM_GET_VERSION, "Fresh transcript start"); + ASSERT_EQ(XMEMCMP(ctx->transcript + 4, test_version_reply, + sizeof(test_version_reply)), 0, "Fresh transcript reply"); + ASSERT_EQ(ctx->sessionId, 0, "Previous session must be retired"); + ASSERT_EQ(ctx->reqSeqNum, 0, "Previous request sequence must be reset"); + ASSERT_EQ(ctx->rspSeqNum, 0, "Previous response sequence must be reset"); + ASSERT_EQ(XMEMCMP(ctx->reqDataKey, zero, sizeof(ctx->reqDataKey)), 0, + "Previous traffic key must be retired"); +#ifndef WOLFSPDM_NO_CERT + ASSERT_EQ(ctx->vcaLen, 0, "Prior VCA length must be cleared"); + ASSERT_EQ(ctx->certChainLen, 0, "Prior certificate chain must be cleared"); + ASSERT_EQ(ctx->flags.hasRspPubKey, 0, "Prior leaf key must be invalidated"); + ASSERT_SUCCESS(wolfSPDM_SetResponderPubKey(ctx, test_rsp_leaf_pub, + sizeof(test_rsp_leaf_pub))); + ASSERT_SUCCESS(wolfSPDM_GetVersion(ctx)); + ASSERT_EQ(ctx->flags.hasRspPubKey, 1, "The configured pin must survive"); + ASSERT_EQ(XMEMCMP(ctx->rspPubKey, test_rsp_leaf_pub, + sizeof(test_rsp_leaf_pub)), 0, "The configured pin must stay intact"); +#endif + + TEST_CTX_FREE(); + TEST_PASS(); +} +#endif /* !WOLFSPDM_NO_MCTP */ + static int test_key_exchange_no_io(void) { TEST_CTX_SETUP(); @@ -1699,6 +2156,41 @@ static int test_key_exchange_no_io(void) TEST_PASS(); } +static int test_key_exchange_preserves_transcript_on_io_failure(void) +{ + static const byte transcript[] = { SPDM_VERSION_10, SPDM_GET_VERSION, 0, 0 }; + byte publicKey[WOLFSPDM_ECC_POINT_SIZE]; + word32 xSz = WOLFSPDM_ECC_KEY_SIZE; + word32 ySz = WOLFSPDM_ECC_KEY_SIZE; + TEST_CTX_SETUP_V12(); + + printf("test_key_exchange_preserves_transcript_on_io_failure...\n"); +#ifdef WOLFSPDM_NO_MCTP + ASSERT_SUCCESS(wolfSPDM_SetMode(ctx, WOLFSPDM_MODE_TCG)); +#elif !defined(WOLFSPDM_NO_CERT) + /* A standard-binding pin is matched against a retrieved chain */ + ctx->certChainLen = WOLFSPDM_CERT_CHAIN_HDR_SZ + 1; +#endif + ASSERT_SUCCESS(wolfSPDM_GenerateEphemeralKey(ctx)); + ASSERT_SUCCESS(wolfSPDM_ExportEphemeralPubKey(ctx, publicKey, &xSz, + publicKey + WOLFSPDM_ECC_KEY_SIZE, &ySz)); + ASSERT_SUCCESS(wolfSPDM_SetResponderPubKey(ctx, publicKey, + sizeof(publicKey))); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, dummy_io_cb, NULL)); + ASSERT_SUCCESS(wolfSPDM_TranscriptAdd(ctx, transcript, sizeof(transcript))); + ASSERT_EQ(wolfSPDM_KeyExchange(ctx), WOLFSPDM_E_IO_FAIL, + "Transport failure should be returned"); + ASSERT_EQ(ctx->transcriptLen, (word32)sizeof(transcript), + "Failed key exchange should preserve the transcript length"); + ASSERT_EQ(XMEMCMP(ctx->transcript, transcript, sizeof(transcript)), 0, + "Failed key exchange should preserve the transcript bytes"); + TEST_ASSERT(test_handshake_secrets_cleared(ctx), + "Transport failure releases the handshake keys"); + + TEST_CTX_FREE(); + TEST_PASS(); +} + static int test_finish_no_io(void) { TEST_CTX_SETUP(); @@ -1723,6 +2215,35 @@ static int test_finish_no_io(void) TEST_PASS(); } +static int test_finish_preserves_transcript_on_io_failure(void) +{ + static const byte transcript[] = { SPDM_VERSION_12, SPDM_KEY_EXCHANGE, 0, 0 }; + byte th1[WOLFSPDM_HASH_SIZE] = {0}; + TEST_CTX_SETUP_V12(); + + printf("test_finish_preserves_transcript_on_io_failure...\n"); +#ifdef WOLFSPDM_NO_MCTP + ASSERT_SUCCESS(wolfSPDM_SetMode(ctx, WOLFSPDM_MODE_TCG)); +#endif + ctx->sessionId = 0x00020001; + ctx->state = WOLFSPDM_STATE_KEY_EX; + XMEMSET(ctx->sharedSecret, 0x5A, sizeof(ctx->sharedSecret)); + ctx->sharedSecretSz = sizeof(ctx->sharedSecret); + ASSERT_SUCCESS(wolfSPDM_DeriveHandshakeKeys(ctx, th1)); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, dummy_io_cb, NULL)); + ASSERT_SUCCESS(wolfSPDM_TranscriptAdd(ctx, transcript, sizeof(transcript))); + ASSERT_EQ(wolfSPDM_Finish(ctx), WOLFSPDM_E_IO_FAIL, + "Transport failure should be returned"); + ASSERT_EQ(ctx->transcriptLen, (word32)sizeof(transcript), + "Failed FINISH should preserve the transcript length"); + ASSERT_EQ(XMEMCMP(ctx->transcript, transcript, sizeof(transcript)), 0, + "Failed FINISH should preserve the transcript bytes"); + ASSERT_EQ(ctx->reqSeqNum, 1, "Sealing FINISH consumes a sequence number"); + + TEST_CTX_FREE(); + TEST_PASS(); +} + static int test_secured_exchange_null_args(void) { byte cmd[4] = {0}, rsp[64]; @@ -1748,6 +2269,9 @@ static int test_disconnect_states(void) byte cmd[4] = { SPDM_VERSION_12, 0xE8, 0x00, 0x00 }; byte rsp[16]; byte err[4] = { SPDM_VERSION_12, SPDM_ERROR, SPDM_ERROR_BUSY, 0x00 }; +#ifndef WOLFSPDM_NO_MEAS + static const byte zeroRecord[WOLFSPDM_MAX_MEAS_RECORD]; +#endif byte zero[WOLFSPDM_AEAD_KEY_SIZE]; word32 rspSz = sizeof(rsp); TEST_CTX_SETUP(); @@ -1773,6 +2297,8 @@ static int test_disconnect_states(void) #endif #ifndef WOLFSPDM_NO_MEAS ctx->measBlockCount = 2; + ctx->measRecordLen = sizeof(ctx->measRecord); + XMEMSET(ctx->measRecord, 0x33, sizeof(ctx->measRecord)); #endif ASSERT_EQ(wolfSPDM_SecuredExchange(ctx, cmd, sizeof(cmd), rsp, &rspSz), WOLFSPDM_E_NOT_CONNECTED, "secured message after a failure"); @@ -1794,6 +2320,8 @@ static int test_disconnect_states(void) #ifndef WOLFSPDM_NO_MEAS ASSERT_EQ(wolfSPDM_GetMeasurementCount(ctx), 0, "previous session's measurements dropped"); + ASSERT_EQ(XMEMCMP(ctx->measRecord, zeroRecord, sizeof(zeroRecord)), 0, + "Previous session's measurement record must be wiped"); #endif /* A retry starts from sequence number 0 even if it fails early */ @@ -1805,10 +2333,13 @@ static int test_disconnect_states(void) ASSERT_EQ(ctx->rspSeqNum, 0, "response sequence reset on connect"); /* A 4-byte SPDM ERROR is reported as such, not as a short buffer */ + ASSERT_SUCCESS(wolfSPDM_GenerateEphemeralKey(ctx)); ASSERT_EQ(wolfSPDM_ParseKeyExchangeRsp(ctx, err, sizeof(err)), WOLFSPDM_E_PEER_ERROR, "short ERROR to KEY_EXCHANGE"); ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), SPDM_ERROR_BUSY, "peer error recorded"); + TEST_ASSERT(test_handshake_secrets_cleared(ctx), + "Rejected key exchange releases the ephemeral key"); ASSERT_EQ(wolfSPDM_ParseVersion(ctx, err, sizeof(err)), WOLFSPDM_E_PEER_ERROR, "short ERROR to GET_VERSION"); err[1] = SPDM_KEY_EXCHANGE_RSP; @@ -1825,7 +2356,10 @@ static int test_disconnect_states(void) static int test_build_tcg_clear_message(void) { + static byte bigPayload[WOLFSPDM_MAX_MSG_SIZE + 1]; + static byte bigFrame[WOLFSPDM_TCG_HEADER_SIZE + WOLFSPDM_MAX_MSG_SIZE + 1]; byte outBuf[64]; + const word32 frameSz = WOLFSPDM_TCG_HEADER_SIZE + 4; int rc; TEST_CTX_SETUP(); printf("test_build_tcg_clear_message...\n"); @@ -1844,10 +2378,20 @@ static int test_build_tcg_clear_message(void) /* Buffer too small */ TEST_ASSERT(wolfSPDM_BuildTcgClearMessage(ctx, (byte*)"AB", 2, outBuf, 4) < 0, "small buffer"); + ASSERT_EQ(wolfSPDM_BuildTcgClearMessage(ctx, (const byte*)"TEST", 4, + outBuf, frameSz - 1), WOLFSPDM_E_BUFFER_SMALL, + "Payload must fit after the header"); + ASSERT_EQ(wolfSPDM_BuildTcgClearMessage(ctx, bigPayload, + WOLFSPDM_MAX_MSG_SIZE + 1, bigFrame, sizeof(bigFrame)), + WOLFSPDM_E_BUFFER_SMALL, "Payload above the SPDM message limit"); + ASSERT_EQ(wolfSPDM_BuildTcgClearMessage(ctx, bigPayload, + WOLFSPDM_MAX_MSG_SIZE, bigFrame, sizeof(bigFrame)), + WOLFSPDM_TCG_HEADER_SIZE + WOLFSPDM_MAX_MSG_SIZE, + "Largest SPDM message fits a TCG frame"); /* Valid build: 16 header + 4 payload = 20 bytes */ - rc = wolfSPDM_BuildTcgClearMessage(ctx, (byte*)"TEST", 4, outBuf, - sizeof(outBuf)); + rc = wolfSPDM_BuildTcgClearMessage(ctx, (const byte*)"TEST", 4, outBuf, + frameSz); TEST_ASSERT(rc == 20, "expected 20 bytes"); /* Tag at [0-1] should be 0x8101 big-endian */ TEST_ASSERT(outBuf[0] == 0x81 && outBuf[1] == 0x01, "wrong tag"); @@ -1972,12 +2516,14 @@ static int test_vendor_defined_roundtrip(void) byte outBuf[64], payload[32]; char vdCode[9]; word32 payloadSz; - int i, built; - int parsed; + int i; printf("test_vendor_defined_roundtrip...\n"); for (i = 0; i < 5; i++) { byte testData[4] = {(byte)i, 0x11, 0x22, 0x33}; + int built; + int parsed; + built = wolfSPDM_BuildVendorDefined(SPDM_VERSION_12, codes[i], testData, 4, outBuf, sizeof(outBuf)); TEST_ASSERT(built > 0, "build failed"); @@ -2095,6 +2641,55 @@ static int test_nuvoton_set_only_mode_null_args(void) #ifdef WOLFSPDM_NATIONS +static int nations_status_io_cb(WOLFSPDM_CTX* ctx, const byte* txBuf, + word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + byte status[] = { 0x01, 0x00, 0x01, *(const byte*)userCtx }; + byte msg[WOLFSPDM_VENDOR_BUF_SZ]; + int sz; + + (void)txBuf; + (void)txSz; + sz = wolfSPDM_BuildVendorDefined(SPDM_VERSION_13, WOLFSPDM_VDCODE_GET_STS, + status, sizeof(status), msg, sizeof(msg)); + if (sz < 0) { + return sz; + } + msg[1] = SPDM_TEST_VENDOR_DEFINED_RSP; + sz = wolfSPDM_BuildTcgClearMessage(ctx, msg, (word32)sz, rxBuf, *rxSz); + if (sz < 0) { + return sz; + } + *rxSz = (word32)sz; + return 0; +} + +static int test_nations_get_status_pending_disable(void) +{ + WOLFSPDM_NATIONS_STATUS status; + byte lockState = 0x81; + TEST_CTX_SETUP(); + + printf("test_nations_get_status_pending_disable...\n"); + ASSERT_SUCCESS(wolfSPDM_SetMode(ctx, WOLFSPDM_MODE_NATIONS_PSK)); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, nations_status_io_cb, &lockState)); + ASSERT_SUCCESS(wolfSPDM_Nations_GetStatus(ctx, &status)); + ASSERT_EQ(status.spdmOnlyLocked, 1, "Pending disable stays locked"); + ASSERT_EQ(status.spdmOnlyPending, 1, "Pending disable is reported"); + + lockState = 0x01; + ASSERT_SUCCESS(wolfSPDM_Nations_GetStatus(ctx, &status)); + ASSERT_EQ(status.spdmOnlyLocked, 1, "Enabled stays locked"); + ASSERT_EQ(status.spdmOnlyPending, 0, "Enabled is not pending disable"); + + lockState = 0x00; + ASSERT_SUCCESS(wolfSPDM_Nations_GetStatus(ctx, &status)); + ASSERT_EQ(status.spdmOnlyLocked, 0, "Disabled is unlocked"); + ASSERT_EQ(status.spdmOnlyPending, 0, "Disabled is not pending disable"); + TEST_CTX_FREE(); + TEST_PASS(); +} + static int test_nations_get_status_null_args(void) { WOLFSPDM_NATIONS_STATUS status; @@ -2170,6 +2765,8 @@ static int test_nations_psk_clear_vca_null_args(void) static int test_parse_psk_exchange_rsp_null_args(void) { + static const byte error[] = { SPDM_VERSION_12, SPDM_ERROR, + SPDM_ERROR_BUSY, 0 }; byte buf[64]; TEST_CTX_SETUP_V12(); printf("test_parse_psk_exchange_rsp_null_args...\n"); @@ -2180,6 +2777,16 @@ static int test_parse_psk_exchange_rsp_null_args(void) != WOLFSPDM_SUCCESS, "NULL buf"); TEST_ASSERT(wolfSPDM_ParsePskExchangeRsp(ctx, buf, 4) != WOLFSPDM_SUCCESS, "short buf"); + + buf[0] = SPDM_VERSION_12; + buf[1] = SPDM_PSK_EXCHANGE_RSP; + ASSERT_EQ(wolfSPDM_ParsePskExchangeRsp(ctx, buf, + 11 + WOLFSPDM_HASH_SIZE), WOLFSPDM_E_INVALID_ARG, + "PSK exchange response needs its full header and verify data"); + ASSERT_EQ(wolfSPDM_ParsePskExchangeRsp(ctx, error, sizeof(error)), + WOLFSPDM_E_PEER_ERROR, "A short peer error can still be returned"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), SPDM_ERROR_BUSY, + "Preserve the peer error code"); TEST_CTX_FREE(); TEST_PASS(); } @@ -2248,6 +2855,8 @@ static int test_parse_psk_exchange_rsp_hmac_check(void) ASSERT_EQ(rc, WOLFSPDM_E_BAD_HMAC, "flipped PSK rspVerifyData byte must return BAD_HMAC"); ASSERT_EQ(ctx->sessionId, 0, "no session ID from an unverified reply"); + TEST_ASSERT(test_handshake_secrets_cleared(ctx), + "Rejected PSK exchange must retire handshake material"); TEST_CTX_FREE(); TEST_PASS(); @@ -2317,29 +2926,84 @@ static int test_parse_psk_finish_rsp(void) /* Error response */ buf[1] = 0x7F; /* SPDM_ERROR */ buf[2] = 0x01; - TEST_ASSERT(wolfSPDM_ParsePskFinishRsp(ctx, buf, 4) - != WOLFSPDM_SUCCESS, "error not detected"); + ctx->lastPeerErrorCode = SPDM_ERROR_BUSY; + ASSERT_EQ(wolfSPDM_ParsePskFinishRsp(ctx, buf, 4), WOLFSPDM_E_PEER_ERROR, + "PSK_FINISH error response should be reported"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), buf[2], + "PSK_FINISH should record the peer error code"); TEST_CTX_FREE(); TEST_PASS(); } -static int test_connect_psk_null_args(void) +/* SPDM 1.4 PSK_FINISH and PSK_FINISH_RSP carry OpaqueDataLength into TH2 */ +static int test_psk_finish_v14_opaque(void) { + byte buf[WOLFSPDM_FINISH_RSP_MAX + 1]; + word32 bufSz = sizeof(buf); + word32 start; TEST_CTX_SETUP(); - printf("test_connect_psk_null_args...\n"); - TEST_ASSERT(wolfSPDM_ConnectPsk(NULL) != WOLFSPDM_SUCCESS, - "NULL ctx should fail"); - /* No PSK set, no IO */ - TEST_ASSERT(wolfSPDM_ConnectPsk(ctx) != WOLFSPDM_SUCCESS, - "No PSK/IO should fail"); - TEST_CTX_FREE(); - TEST_PASS(); -} - -#endif /* WOLFSPDM_PSK */ -/* ----- Group F: Internal Crypto ----- */ + printf("test_psk_finish_v14_opaque...\n"); + ctx->spdmVersion = SPDM_VERSION_14; + XMEMSET(ctx->reqFinishedKey, 0x5A, WOLFSPDM_HASH_SIZE); + start = ctx->transcriptLen; + ASSERT_SUCCESS(wolfSPDM_BuildPskFinish(ctx, buf, &bufSz)); + ASSERT_EQ(bufSz, 6 + WOLFSPDM_HASH_SIZE, + "1.4 PSK_FINISH includes OpaqueDataLength"); + ASSERT_EQ(SPDM_Get16LE(&buf[4]), 0, "no requester OpaqueData"); + ASSERT_EQ(ctx->transcriptLen - start, bufSz, "request transcript size"); + ASSERT_EQ(memcmp(ctx->transcript + start, buf, bufSz), 0, + "request transcript contents"); + + bufSz = 6 + WOLFSPDM_HASH_SIZE - 1; + ASSERT_EQ(wolfSPDM_BuildPskFinish(ctx, buf, &bufSz), + WOLFSPDM_E_BUFFER_SMALL, "1.4 PSK_FINISH output capacity"); + + XMEMSET(buf, 0, sizeof(buf)); + buf[0] = SPDM_VERSION_14; + buf[1] = SPDM_PSK_FINISH_RSP; + SPDM_Set16LE(&buf[4], 3); + buf[6] = 0xA1; + buf[7] = 0xA2; + buf[8] = 0xA3; + start = ctx->transcriptLen; + ASSERT_EQ(wolfSPDM_ParsePskFinishRsp(ctx, buf, 5), + WOLFSPDM_E_BUFFER_SMALL, "response needs OpaqueDataLength"); + ASSERT_EQ(wolfSPDM_ParsePskFinishRsp(ctx, buf, 8), + WOLFSPDM_E_BUFFER_SMALL, "response needs all OpaqueData"); + ASSERT_EQ(ctx->transcriptLen, start, "rejected response not added"); + ASSERT_SUCCESS(wolfSPDM_ParsePskFinishRsp(ctx, buf, 9)); + ASSERT_EQ(ctx->transcriptLen - start, 9, "response transcript size"); + ASSERT_EQ(memcmp(ctx->transcript + start, buf, 9), 0, + "response transcript contents"); + + SPDM_Set16LE(&buf[4], WOLFSPDM_FINISH_OPAQUE_MAX + 1); + start = ctx->transcriptLen; + TEST_ASSERT(wolfSPDM_ParsePskFinishRsp(ctx, buf, sizeof(buf)) + != WOLFSPDM_SUCCESS, "response OpaqueData limit"); + ASSERT_EQ(ctx->transcriptLen, start, "oversized response not added"); + + TEST_CTX_FREE(); + TEST_PASS(); +} + +static int test_connect_psk_null_args(void) +{ + TEST_CTX_SETUP(); + printf("test_connect_psk_null_args...\n"); + TEST_ASSERT(wolfSPDM_ConnectPsk(NULL) != WOLFSPDM_SUCCESS, + "NULL ctx should fail"); + /* No PSK set, no IO */ + TEST_ASSERT(wolfSPDM_ConnectPsk(ctx) != WOLFSPDM_SUCCESS, + "No PSK/IO should fail"); + TEST_CTX_FREE(); + TEST_PASS(); +} + +#endif /* WOLFSPDM_PSK */ + +/* ----- Group F: Internal Crypto ----- */ static int test_sha384_hash(void) { @@ -2563,8 +3227,11 @@ static int test_derive_app_data_keys(void) TEST_ASSERT(wolfSPDM_DeriveAppDataKeys(NULL) != WOLFSPDM_SUCCESS, "NULL ctx"); - /* Set up handshake secret and transcript */ - XMEMSET(ctx->handshakeSecret, 0x5A, WOLFSPDM_HASH_SIZE); + /* Set up handshake material and a transcript for the key transition. */ + ASSERT_SUCCESS(wolfSPDM_GenerateEphemeralKey(ctx)); + XMEMSET(ctx->sharedSecret, 0x5A, sizeof(ctx->sharedSecret)); + ctx->sharedSecretSz = sizeof(ctx->sharedSecret); + ASSERT_SUCCESS(wolfSPDM_DeriveHandshakeKeys(ctx, zeros)); wolfSPDM_TranscriptAdd(ctx, (byte*)"test data for th2", 17); ctx->reqSeqNum = 99; ctx->rspSeqNum = 99; @@ -2576,6 +3243,8 @@ static int test_derive_app_data_keys(void) "rspDataKey is zero"); ASSERT_EQ(ctx->reqSeqNum, 0, "reqSeqNum not reset"); ASSERT_EQ(ctx->rspSeqNum, 0, "rspSeqNum not reset"); + TEST_ASSERT(test_handshake_secrets_cleared(ctx), + "Application key installation must retire handshake material"); TEST_CTX_FREE(); TEST_PASS(); @@ -2626,6 +3295,33 @@ static int test_build_key_exchange_format(void) TEST_CTX_FREE(); TEST_PASS(); } + +#ifndef WOLFSPDM_NO_CERT +/* A standard-binding pin names a slot only through a retrieved chain */ +static int test_build_key_exchange_pinned_slot(void) +{ + byte buf[256]; + word32 bufSz = sizeof(buf); + TEST_CTX_SETUP_V12(); + printf("test_build_key_exchange_pinned_slot...\n"); + + ctx->reqSessionId = 0x0001; + ctx->currentSlotId = 2; + ASSERT_SUCCESS(wolfSPDM_SetResponderPubKey(ctx, test_rsp_leaf_pub, + sizeof(test_rsp_leaf_pub))); + ASSERT_EQ(wolfSPDM_BuildKeyExchange(ctx, buf, &bufSz), + WOLFSPDM_E_BAD_STATE, "Pinned key without a certificate chain"); + ASSERT_EQ(ctx->flags.ephemeralKeyInit, 0, "No ephemeral key generated"); + + ctx->certChainLen = WOLFSPDM_CERT_CHAIN_HDR_SZ + 1; + bufSz = sizeof(buf); + ASSERT_SUCCESS(wolfSPDM_BuildKeyExchange(ctx, buf, &bufSz)); + ASSERT_EQ(buf[3], 2, "Chain-backed pin uses the chain's slot"); + + TEST_CTX_FREE(); + TEST_PASS(); +} +#endif #endif #ifdef WOLFSPDM_TCG @@ -2739,14 +3435,39 @@ static int test_decrypt_mctp_random_padding(void) #endif #ifndef WOLFSPDM_NO_MCTP +static int test_build_mctp_record(const WOLFSPDM_CTX* ctx, const byte* inner, + word32 innerSz, byte* rec, word32 recSz) +{ + Aes aes; + byte iv[WOLFSPDM_AEAD_IV_SIZE]; + int rc; + + TEST_ASSERT(recSz >= 8 + WOLFSPDM_AEAD_TAG_SIZE && + innerSz <= recSz - 8 - WOLFSPDM_AEAD_TAG_SIZE, + "Record fixture fits the output buffer"); + SPDM_Set32LE(&rec[0], ctx->sessionId); + SPDM_Set16LE(&rec[4], (word16)ctx->rspSeqNum); + SPDM_Set16LE(&rec[6], (word16)(innerSz + WOLFSPDM_AEAD_TAG_SIZE)); + wolfSPDM_BuildIV(iv, ctx->rspDataIv, ctx->rspSeqNum); + + ASSERT_SUCCESS(wc_AesInit(&aes, NULL, INVALID_DEVID)); + rc = wc_AesGcmSetKey(&aes, ctx->rspDataKey, WOLFSPDM_AEAD_KEY_SIZE); + if (rc == 0) { + rc = wc_AesGcmEncrypt(&aes, &rec[8], inner, innerSz, iv, sizeof(iv), + &rec[8 + innerSz], WOLFSPDM_AEAD_TAG_SIZE, rec, 8); + } + wc_AesFree(&aes); + wc_ForceZero(&aes, sizeof(aes)); + wc_ForceZero(iv, sizeof(iv)); + return rc; +} + static int test_decrypt_rejects_wrong_mctp_type(void) { /* An authenticated record whose inner MCTP type is not SPDM must be * rejected, and the sequence still advances past the verified tag */ - Aes aes; byte inner[4]; byte rec[8 + sizeof(inner) + WOLFSPDM_AEAD_TAG_SIZE]; - byte iv[WOLFSPDM_AEAD_IV_SIZE]; byte dec[64]; word32 decSz = sizeof(dec); TEST_CTX_SETUP_V12(); @@ -2759,18 +3480,8 @@ static int test_decrypt_rejects_wrong_mctp_type(void) SPDM_Set16LE(inner, 2); inner[2] = 0x06; inner[3] = SPDM_VERSION_12; - SPDM_Set32LE(&rec[0], ctx->sessionId); - SPDM_Set16LE(&rec[4], 0); - SPDM_Set16LE(&rec[6], (word16)(sizeof(inner) + WOLFSPDM_AEAD_TAG_SIZE)); - wolfSPDM_BuildIV(iv, ctx->rspDataIv, 0); - - ASSERT_SUCCESS(wc_AesInit(&aes, NULL, INVALID_DEVID)); - ASSERT_SUCCESS(wc_AesGcmSetKey(&aes, ctx->rspDataKey, - WOLFSPDM_AEAD_KEY_SIZE)); - ASSERT_SUCCESS(wc_AesGcmEncrypt(&aes, &rec[8], inner, sizeof(inner), - iv, sizeof(iv), &rec[8 + sizeof(inner)], WOLFSPDM_AEAD_TAG_SIZE, - rec, 8)); - wc_AesFree(&aes); + ASSERT_SUCCESS(test_build_mctp_record(ctx, inner, sizeof(inner), rec, + sizeof(rec))); ASSERT_EQ(wolfSPDM_DecryptInternal(ctx, rec, sizeof(rec), dec, &decSz), WOLFSPDM_E_DECRYPT_FAIL, "wrong inner MCTP type must fail"); @@ -2920,6 +3631,10 @@ static int test_encrypt_decrypt_roundtrip_tcg(void) TEST_ASSERT(encSz > 16, "encrypted should be larger"); ctx->rspSeqNum = 0; + enc[encSz] = 0; + ASSERT_EQ(wolfSPDM_DecryptInternal(ctx, enc, encSz + 1, dec, &decSz), + WOLFSPDM_E_BUFFER_SMALL, "TCG record size must match its header"); + ASSERT_EQ(ctx->rspSeqNum, 0, "Framing rejection keeps the sequence"); ASSERT_SUCCESS(wolfSPDM_DecryptInternal(ctx, enc, encSz, dec, &decSz)); ASSERT_EQ(decSz, 16, "decrypted size mismatch"); TEST_ASSERT(memcmp(dec, plain, 16) == 0, "plaintext mismatch"); @@ -2929,6 +3644,50 @@ static int test_encrypt_decrypt_roundtrip_tcg(void) } #endif /* WOLFSPDM_TCG */ +#if WOLFSPDM_XFER_MSG_SIZE + 3 + WOLFSPDM_AEAD_TAG_SIZE > 0xFFFF +/* A record too long for the 16-bit Length field is refused, not truncated */ +static int test_secured_record_length_limit(void) +{ + static byte plain[WOLFSPDM_XFER_MSG_SIZE]; + static byte enc[WOLFSPDM_XFER_MSG_SIZE + WOLFSPDM_AEAD_OVERHEAD]; + word32 encSz; + word32 maxSz; + TEST_CTX_SETUP_V12(); + + printf("test_secured_record_length_limit...\n"); + ctx->sessionId = 0x00020001; + XMEMSET(ctx->reqDataKey, 0x33, WOLFSPDM_AEAD_KEY_SIZE); + XMEMSET(ctx->reqDataIv, 0x44, WOLFSPDM_AEAD_IV_SIZE); + XMEMSET(plain, 0x5A, sizeof(plain)); +#ifndef WOLFSPDM_NO_MCTP + /* AppDataLen(2) + MCTP type(1) + message + tag */ + maxSz = 0xFFFFU - 3U - WOLFSPDM_AEAD_TAG_SIZE; + encSz = sizeof(enc); + ASSERT_EQ(wolfSPDM_EncryptInternal(ctx, plain, maxSz + 1, enc, &encSz), + WOLFSPDM_E_BUFFER_SMALL, "MCTP record one byte too long"); + encSz = sizeof(enc); + ASSERT_SUCCESS(wolfSPDM_EncryptInternal(ctx, plain, maxSz, enc, &encSz)); + ASSERT_EQ(SPDM_Get16LE(&enc[6]), 0xFFFF, "Longest MCTP record"); + ASSERT_EQ(encSz, 8 + 0xFFFF, "MCTP record size"); +#endif +#ifdef WOLFSPDM_TCG + /* AppDataLen(2) + message, padded to 16 bytes, + tag */ + ctx->mode = WOLFSPDM_MODE_TCG; + maxSz = 0xFFF0U - WOLFSPDM_AEAD_TAG_SIZE - 2U; + encSz = sizeof(enc); + ASSERT_EQ(wolfSPDM_EncryptInternal(ctx, plain, maxSz + 1, enc, &encSz), + WOLFSPDM_E_BUFFER_SMALL, "TCG record one byte too long"); + encSz = sizeof(enc); + ASSERT_SUCCESS(wolfSPDM_EncryptInternal(ctx, plain, maxSz, enc, &encSz)); + ASSERT_EQ(SPDM_Get16LE(&enc[12]), 0xFFF0, "Longest TCG record"); + ASSERT_EQ(encSz, 14 + 0xFFF0, "TCG record size"); +#endif + + TEST_CTX_FREE(); + TEST_PASS(); +} +#endif + #ifndef WOLFSPDM_NO_APP_DATA /* One-slot mailbox standing in for a message-oriented MCTP link */ static byte g_mbox[WOLFSPDM_XFER_MSG_SIZE + WOLFSPDM_AEAD_OVERHEAD]; @@ -3110,6 +3869,42 @@ static int test_app_data(void) TEST_CTX_FREE(); TEST_PASS(); } + +static int test_app_data_secured_type(void) +{ + static const byte types[] = { 0x06, 0x86 }; + static WOLFSPDM_CTX peer; + byte inner[3] = { 1, 0, 0 }; + byte buf[8]; + word32 bufSz; + word32 i; + TEST_CTX_SETUP(); + + printf("test_app_data_secured_type...\n"); + test_app_data_pair(ctx, &peer); + for (i = 0; i < sizeof(types); i++) { + int sent; + int received; + + sent = wolfSPDM_SendData(ctx, &types[i], 1); + inner[2] = types[i]; + ASSERT_SUCCESS(test_build_mctp_record(ctx, inner, sizeof(inner), + g_mbox, sizeof(g_mbox))); + g_mboxSz = 8 + sizeof(inner) + WOLFSPDM_AEAD_TAG_SIZE; + bufSz = sizeof(buf); + received = wolfSPDM_ReceiveData(ctx, buf, &bufSz); + ASSERT_EQ(sent, WOLFSPDM_E_INVALID_ARG, + "SendData rejects the secured MCTP type"); + ASSERT_EQ(received, WOLFSPDM_E_DECRYPT_FAIL, + "ReceiveData rejects the secured MCTP type"); + ASSERT_EQ(bufSz, sizeof(buf), "Rejected record delivers no payload"); + ASSERT_EQ(ctx->reqSeqNum, 0, "Invalid send uses no sequence"); + ASSERT_EQ(ctx->rspSeqNum, i + 1, "Authenticated record uses sequence"); + } + wolfSPDM_Free(&peer); + TEST_CTX_FREE(); + TEST_PASS(); +} #endif /* !WOLFSPDM_NO_APP_DATA */ #ifdef WOLFSPDM_RESPONDER @@ -3313,6 +4108,83 @@ static int test_responder_secured_requires_session(void) TEST_PASS(); } +static int test_responder_get_version_reserved(void) +{ + byte rctxBuf[WOLFSPDM_RESP_CTX_STATIC_SIZE]; + WOLFSPDM_RESP_CTX* rctx = (WOLFSPDM_RESP_CTX*)rctxBuf; + byte request[] = { SPDM_VERSION_10, SPDM_GET_VERSION, 0x42, 0xA5 }; + byte response[64]; + byte frame[WOLFSPDM_TCG_HEADER_SIZE + sizeof(request)]; + word32 responseSz = sizeof(response); + + printf("test_responder_get_version_reserved...\n"); + ASSERT_SUCCESS(wolfSPDM_RespInit(rctx)); + ASSERT_SUCCESS(wolfSPDM_RespSetMode(rctx, 1, 0)); + wolfSPDM_WriteTcgHeader(frame, WOLFSPDM_TCG_TAG_CLEAR, + sizeof(frame), 0, 0); + XMEMCPY(frame + WOLFSPDM_TCG_HEADER_SIZE, request, sizeof(request)); + ASSERT_SUCCESS(wolfSPDM_RespHandleMessage(rctx, frame, sizeof(frame), + response, &responseSz)); + TEST_ASSERT(responseSz >= WOLFSPDM_TCG_HEADER_SIZE + 4, + "VERSION reply includes its header"); + ASSERT_EQ(response[WOLFSPDM_TCG_HEADER_SIZE + 1], SPDM_VERSION, + "GET_VERSION ignores reserved fields"); + wolfSPDM_RespFree(rctx); + TEST_PASS(); +} + +/* Reset discards the negotiated version with the transcript, so the next + * connection starts again from GET_VERSION. */ +static int test_responder_reset_clears_version(void) +{ + byte rctxBuf[WOLFSPDM_RESP_CTX_STATIC_SIZE]; + WOLFSPDM_RESP_CTX* rctx = (WOLFSPDM_RESP_CTX*)rctxBuf; + byte getVersion[4] = { SPDM_VERSION_10, SPDM_GET_VERSION, 0, 0 }; + byte getCaps[4] = { SPDM_VERSION_13, SPDM_TEST_GET_CAPABILITIES, 0, 0 }; + byte frame[WOLFSPDM_TCG_HEADER_SIZE + 4]; + byte response[64]; + word32 responseSz; + int i; + + printf("test_responder_reset_clears_version...\n"); + ASSERT_SUCCESS(wolfSPDM_RespInit(rctx)); + ASSERT_SUCCESS(wolfSPDM_RespSetMode(rctx, 1, 0)); + wolfSPDM_WriteTcgHeader(frame, WOLFSPDM_TCG_TAG_CLEAR, + sizeof(frame), 0, 0); + + for (i = 0; i < 3; i++) { + if (i == 1) { + wolfSPDM_RespReset(rctx); + } + if (i != 1) { + XMEMCPY(frame + WOLFSPDM_TCG_HEADER_SIZE, getVersion, + sizeof(getVersion)); + responseSz = sizeof(response); + ASSERT_SUCCESS(wolfSPDM_RespHandleMessage(rctx, frame, + sizeof(frame), response, &responseSz)); + } + XMEMCPY(frame + WOLFSPDM_TCG_HEADER_SIZE, getCaps, sizeof(getCaps)); + responseSz = sizeof(response); + ASSERT_SUCCESS(wolfSPDM_RespHandleMessage(rctx, frame, sizeof(frame), + response, &responseSz)); + TEST_ASSERT(responseSz >= WOLFSPDM_TCG_HEADER_SIZE + 4, + "GET_CAPABILITIES reply includes its header"); + if (i == 1) { + ASSERT_EQ(response[WOLFSPDM_TCG_HEADER_SIZE + 1], SPDM_ERROR, + "Reset requires a new GET_VERSION"); + ASSERT_EQ(response[WOLFSPDM_TCG_HEADER_SIZE + 2], + SPDM_ERROR_UNEXPECTED_REQUEST, "Reset request is unexpected"); + } + else { + ASSERT_EQ(response[WOLFSPDM_TCG_HEADER_SIZE + 1], + SPDM_TEST_CAPABILITIES, "Negotiated version is accepted"); + } + } + + wolfSPDM_RespFree(rctx); + TEST_PASS(); +} + #ifdef WOLFSPDM_NATIONS /* Send one vendor-defined command in a TCG clear frame. */ static int resp_send_clear_vd(WOLFSPDM_RESP_CTX* rctx, const char* vdCode, @@ -3336,6 +4208,28 @@ static int resp_send_clear_vd(WOLFSPDM_RESP_CTX* rctx, const char* vdCode, (word32)spdmMsgSz + WOLFSPDM_TCG_HEADER_SIZE, out, outSz); } +static int test_responder_pre_negotiation_status_version(void) +{ + byte rctxBuf[WOLFSPDM_RESP_CTX_STATIC_SIZE]; + WOLFSPDM_RESP_CTX* rctx = (WOLFSPDM_RESP_CTX*)rctxBuf; + byte response[64]; + word32 responseSz = sizeof(response); + + printf("test_responder_pre_negotiation_status_version...\n"); + ASSERT_SUCCESS(wolfSPDM_RespInit(rctx)); + ASSERT_SUCCESS(wolfSPDM_RespSetMode(rctx, 1, 0)); + ASSERT_SUCCESS(resp_send_clear_vd(rctx, WOLFSPDM_VDCODE_GET_STS, + NULL, 0, response, &responseSz)); + TEST_ASSERT(responseSz >= WOLFSPDM_TCG_HEADER_SIZE + 4, + "GET_STS reply includes its header"); + ASSERT_EQ(response[WOLFSPDM_TCG_HEADER_SIZE + 1], + SPDM_TEST_VENDOR_DEFINED_RSP, "GET_STS reply code"); + ASSERT_EQ(response[WOLFSPDM_TCG_HEADER_SIZE], SPDM_VERSION_13, + "GET_STS reply must use the request version"); + wolfSPDM_RespFree(rctx); + TEST_PASS(); +} + /* A clear SPDM message in a TCG clear frame */ static int resp_send_clear(WOLFSPDM_RESP_CTX* rctx, const byte* msg, word32 msgSz, byte* out, word32* outSz) @@ -3486,8 +4380,62 @@ static int requester_to_responder_iocb(WOLFSPDM_CTX* spdmCtx, return wolfSPDM_RespHandleMessage(rctx, txBuf, txSz, rxBuf, rxSz); } +static int test_responder_limited_reply_io(WOLFSPDM_CTX* ctx, + const byte* txBuf, word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + word32 limitedSz = WOLFSPDM_TCG_HEADER_SIZE; + int rc = requester_to_responder_iocb(ctx, txBuf, txSz, rxBuf, + &limitedSz, userCtx); + + (void)rxSz; + ASSERT_EQ(rc, WOLFSPDM_E_BUFFER_SMALL, "Reply needs more space"); + return rc; +} + +static int test_responder_reply_capacity_io(WOLFSPDM_CTX* ctx, + const byte* txBuf, word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + if (txSz >= WOLFSPDM_TCG_HEADER_SIZE && + SPDM_Get16BE(txBuf) == WOLFSPDM_TCG_TAG_SECURED) { + return test_responder_limited_reply_io(ctx, txBuf, txSz, rxBuf, + rxSz, userCtx); + } + return requester_to_responder_iocb(ctx, txBuf, txSz, rxBuf, rxSz, userCtx); +} + +static int test_tcg_handshake_io_failure(WOLFSPDM_CTX* ctx, + const byte* txBuf, word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + if (txSz >= WOLFSPDM_TCG_HEADER_SIZE && + SPDM_Get16BE(txBuf) == WOLFSPDM_TCG_TAG_SECURED) { + return -1; + } + return requester_to_responder_iocb(ctx, txBuf, txSz, rxBuf, rxSz, userCtx); +} + +static int test_tcg_connect_releases_session(WOLFSPDM_CTX* ctx) +{ + static const byte zero[WOLFSPDM_HASH_SIZE]; + + printf("test_tcg_connect_releases_session (%s requester key)...\n", + ctx->flags.hasReqKeyPair ? "with" : "without"); + ASSERT_EQ(wolfSPDM_ConnectTCG(ctx), WOLFSPDM_E_IO_FAIL, + "Secured handshake I/O failure"); + ASSERT_EQ(ctx->state, WOLFSPDM_STATE_ERROR, "Aborted TCG session state"); + TEST_ASSERT(test_handshake_secrets_cleared(ctx), + "Aborted TCG session must retire handshake material"); + TEST_ASSERT(XMEMCMP(ctx->reqDataKey, zero, sizeof(ctx->reqDataKey)) == 0 && + XMEMCMP(ctx->rspDataKey, zero, sizeof(ctx->rspDataKey)) == 0 && + XMEMCMP(ctx->reqDataIv, zero, sizeof(ctx->reqDataIv)) == 0 && + XMEMCMP(ctx->rspDataIv, zero, sizeof(ctx->rspDataIv)) == 0, + "Aborted TCG session must retire traffic material"); + ASSERT_EQ(ctx->sessionId, 0, "Aborted TCG session ID"); + ASSERT_EQ(ctx->flags.hasRspPubKey, 1, "Responder pin remains configured"); + return 0; +} + /* Pinned identity handshake + tunneled TPM2_CMD + END_SESSION, end-to-end. */ -static int test_responder_identity_roundtrip(void) +static int test_responder_identity_roundtrip(int fineGrained) { WOLFSPDM_CTX req; byte rctxBuf[WOLFSPDM_RESP_CTX_STATIC_SIZE]; @@ -3503,7 +4451,8 @@ static int test_responder_identity_roundtrip(void) word32 idPubYSz = sizeof(idPubY); int rc; - printf("test_responder_identity_roundtrip...\n"); + printf("%s...\n", fineGrained ? "test_finish_connects" : + "test_responder_identity_roundtrip"); ASSERT_SUCCESS(wolfSPDM_Init(&req)); ASSERT_SUCCESS(wolfSPDM_RespInit(rctx)); @@ -3536,8 +4485,48 @@ static int test_responder_identity_roundtrip(void) NULL)); ASSERT_SUCCESS(wolfSPDM_SetIO(&req, requester_to_responder_iocb, rctx)); - rc = wolfSPDM_ConnectTCG(&req); - TEST_ASSERT(rc == WOLFSPDM_SUCCESS, "identity ConnectTCG failed"); + if (fineGrained) { + byte wireKey[WOLFSPDM_PUBKEY_BUF_SZ]; + word32 wireKeySz = sizeof(wireKey); + const byte* publishedKey = NULL; + + ASSERT_SUCCESS(wolfSPDM_SetMaxVersion(&req, WOLFSPDM_MIN_SPDM_VERSION)); + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, test_responder_reply_capacity_io, + rctx)); + ASSERT_EQ(wolfSPDM_ConnectTCG(&req), WOLFSPDM_E_IO_FAIL, + "A FINISH reply must fit before the session is established"); + ASSERT_EQ(wolfSPDM_RespIsSessionActive(rctx), 0, + "A failed FINISH reply leaves no active session"); + ASSERT_EQ(wolfSPDM_RespGetIdentityKey(rctx, &publishedKey), 0, + "A failed FINISH reply leaves no session identity"); + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, requester_to_responder_iocb, + rctx)); + ASSERT_SUCCESS(wolfSPDM_GetVersion(&req)); + ASSERT_EQ(req.spdmVersion, WOLFSPDM_MIN_SPDM_VERSION, + "The fine-grained loopback uses the minimum supported version"); +#ifndef WOLFSPDM_NO_CERT + ASSERT_EQ(wolfSPDM_GetDigests(&req), WOLFSPDM_E_PEER_ERROR, + "This responder does not support certificate digests"); +#endif + ASSERT_SUCCESS(wolfSPDM_TCG_GetPubKey(&req, wireKey, &wireKeySz)); + ASSERT_SUCCESS(wolfSPDM_Sha384Hash(req.certChainHash, wireKey, + wireKeySz, NULL, 0, NULL, 0)); + ASSERT_SUCCESS(wolfSPDM_TranscriptAdd(&req, req.certChainHash, + WOLFSPDM_HASH_SIZE)); + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, test_responder_limited_reply_io, + rctx)); + ASSERT_EQ(wolfSPDM_KeyExchange(&req), WOLFSPDM_E_IO_FAIL, + "The first key exchange reply did not fit"); + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, requester_to_responder_iocb, + rctx)); + ASSERT_SUCCESS(wolfSPDM_KeyExchange(&req)); + ASSERT_EQ(wolfSPDM_IsConnected(&req), 0, "Connected before FINISH"); + ASSERT_SUCCESS(wolfSPDM_Finish(&req)); + } + else { + rc = wolfSPDM_ConnectTCG(&req); + TEST_ASSERT(rc == WOLFSPDM_SUCCESS, "identity ConnectTCG failed"); + } ASSERT_EQ(wolfSPDM_IsConnected(&req), 1, "Requester not connected"); XMEMSET(cmd, 0, sizeof(cmd)); @@ -3549,6 +4538,227 @@ static int test_responder_identity_roundtrip(void) TEST_ASSERT(rc == WOLFSPDM_SUCCESS, "TPM2_CMD passthrough failed"); ASSERT_EQ(g_tpmCbInvocations, 1, "TPM stub must have run once"); + if (fineGrained) { + byte end[] = { req.spdmVersion, SPDM_END_SESSION, 0x80, 0x42 }; + byte ack[4]; + word32 ackSz = sizeof(ack); + + ASSERT_SUCCESS(wolfSPDM_SecuredExchange(&req, end, sizeof(end), + ack, &ackSz)); + ASSERT_EQ(ackSz, sizeof(ack), "END_SESSION_ACK header size"); + ASSERT_EQ(ack[1], SPDM_END_SESSION_ACK, + "END_SESSION ignores reserved fields"); + ASSERT_EQ(wolfSPDM_RespIsSessionActive(rctx), 0, + "The acknowledged session is closed"); + } + else { + ASSERT_SUCCESS(wolfSPDM_Disconnect(&req)); + } + + wc_ForceZero(idPriv, sizeof(idPriv)); + wolfSPDM_RespFree(rctx); + wolfSPDM_Free(&req); + TEST_PASS(); +} + +typedef struct { + WOLFSPDM_RESP_CTX* rctx; + int resize; + byte rspCode; +} TEST_KEX_ENVELOPE; + +/* Resizes the clear KEY_EXCHANGE: 1 ends it at ExchangeData, 2 appends a + * byte, 3 drops its last OpaqueData byte. */ +static int test_kex_envelope_io(WOLFSPDM_CTX* ctx, const byte* txBuf, + word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + TEST_KEX_ENVELOPE* t = (TEST_KEX_ENVELOPE*)userCtx; + byte frame[WOLFSPDM_TCG_HEADER_SIZE + WOLFSPDM_KEY_EX_TX_SZ + 1]; + word32 frameSz = txSz; + int rc; + + if (t->resize == 0 || txSz <= WOLFSPDM_TCG_HEADER_SIZE + 138 || + txSz >= sizeof(frame) || + SPDM_Get16BE(txBuf) != WOLFSPDM_TCG_TAG_CLEAR || + txBuf[WOLFSPDM_TCG_HEADER_SIZE + 1] != SPDM_KEY_EXCHANGE) { + return requester_to_responder_iocb(ctx, txBuf, txSz, rxBuf, rxSz, + t->rctx); + } + + XMEMCPY(frame, txBuf, txSz); + if (t->resize == 1) { + frameSz = WOLFSPDM_TCG_HEADER_SIZE + 136; + } + else if (t->resize == 2) { + frame[txSz] = 0; + frameSz = txSz + 1; + } + else { + frameSz = txSz - 1; + } + wolfSPDM_WriteTcgHeader(frame, WOLFSPDM_TCG_TAG_CLEAR, frameSz, + ctx->connectionHandle, ctx->fipsIndicator); + rc = wolfSPDM_RespHandleMessage(t->rctx, frame, frameSz, rxBuf, rxSz); + if (rc == WOLFSPDM_SUCCESS && *rxSz > WOLFSPDM_TCG_HEADER_SIZE + 1) { + t->rspCode = rxBuf[WOLFSPDM_TCG_HEADER_SIZE + 1]; + } + return rc; +} + +/* KEY_EXCHANGE must end with OpaqueDataLength and exactly that much data */ +static int test_responder_key_exchange_envelope(void) +{ + WOLFSPDM_CTX req; + byte rctxBuf[WOLFSPDM_RESP_CTX_STATIC_SIZE]; + WOLFSPDM_RESP_CTX* rctx = (WOLFSPDM_RESP_CTX*)rctxBuf; + TEST_KEX_ENVELOPE t; + ecc_key idKey; + byte idPriv[WOLFSPDM_ECC_KEY_SIZE]; + byte idPub[WOLFSPDM_ECC_POINT_SIZE]; + word32 idPrivSz = sizeof(idPriv); + word32 idPubXSz = WOLFSPDM_ECC_KEY_SIZE; + word32 idPubYSz = WOLFSPDM_ECC_KEY_SIZE; + + printf("test_responder_key_exchange_envelope...\n"); + ASSERT_SUCCESS(wolfSPDM_Init(&req)); + ASSERT_SUCCESS(wolfSPDM_RespInit(rctx)); + ASSERT_SUCCESS(wc_ecc_init(&idKey)); + ASSERT_SUCCESS(wc_ecc_make_key(&req.rng, WOLFSPDM_ECC_KEY_SIZE, + &idKey)); + ASSERT_SUCCESS(wc_ecc_export_private_only(&idKey, idPriv, &idPrivSz)); + ASSERT_SUCCESS(wc_ecc_export_public_raw(&idKey, idPub, &idPubXSz, + idPub + WOLFSPDM_ECC_KEY_SIZE, &idPubYSz)); + wc_ecc_free(&idKey); + ASSERT_EQ(idPrivSz + idPubXSz + idPubYSz, 3 * WOLFSPDM_ECC_KEY_SIZE, + "identity key size mismatch"); + + req.mode = WOLFSPDM_MODE_NUVOTON; + ASSERT_SUCCESS(wolfSPDM_SetResponderPubKey(&req, idPub, sizeof(idPub))); + ASSERT_SUCCESS(wolfSPDM_RespSetMode(rctx, 1, 0)); + ASSERT_SUCCESS(wolfSPDM_RespSetIdentityKey(rctx, idPriv, sizeof(idPriv), + idPub, sizeof(idPub))); + XMEMSET(&t, 0, sizeof(t)); + t.rctx = rctx; + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, test_kex_envelope_io, &t)); + + for (t.resize = 1; t.resize <= 3; t.resize++) { + t.rspCode = 0; + TEST_ASSERT(wolfSPDM_ConnectTCG(&req) != WOLFSPDM_SUCCESS, + "Resized KEY_EXCHANGE must not connect"); + TEST_ASSERT(t.rspCode != SPDM_KEY_EXCHANGE_RSP, + "Responder rejects a resized KEY_EXCHANGE"); + ASSERT_EQ(wolfSPDM_RespIsSessionActive(rctx), 0, + "Resized KEY_EXCHANGE leaves no session"); + } + + t.resize = 0; + ASSERT_SUCCESS(wolfSPDM_ConnectTCG(&req)); + ASSERT_EQ(wolfSPDM_IsConnected(&req), 1, "Well-formed KEY_EXCHANGE"); + ASSERT_SUCCESS(wolfSPDM_Disconnect(&req)); + + wc_ForceZero(idPriv, sizeof(idPriv)); + wolfSPDM_RespFree(rctx); + wolfSPDM_Free(&req); + TEST_PASS(); +} + +/* WOLFSPDM_CTX is the first member of the responder context */ +#define TEST_RESP_SPDM_CTX(r) ((const WOLFSPDM_CTX*)(const void*)(r)) + +/* A failed responder handshake keeps no handshake secrets, ephemeral key or + * session, and a later handshake still completes. */ +static int test_responder_failed_handshake_cleanup(void) +{ + static const byte zero[WOLFSPDM_AEAD_KEY_SIZE]; + WOLFSPDM_CTX req; + byte rctxBuf[WOLFSPDM_RESP_CTX_STATIC_SIZE]; + WOLFSPDM_RESP_CTX* rctx = (WOLFSPDM_RESP_CTX*)rctxBuf; + const WOLFSPDM_CTX* inner = TEST_RESP_SPDM_CTX(rctxBuf); + ecc_key idKey; + byte idPriv[WOLFSPDM_ECC_KEY_SIZE]; + byte idPub[WOLFSPDM_ECC_POINT_SIZE]; + word32 idPrivSz = sizeof(idPriv); + word32 idPubXSz = WOLFSPDM_ECC_KEY_SIZE; + word32 idPubYSz = WOLFSPDM_ECC_KEY_SIZE; + byte getVersion[4] = { SPDM_VERSION_10, SPDM_GET_VERSION, 0, 0 }; + byte keyEx[138]; + byte frame[WOLFSPDM_TCG_HEADER_SIZE + sizeof(keyEx)]; + byte wireKey[WOLFSPDM_PUBKEY_BUF_SZ]; + word32 wireKeySz = sizeof(wireKey); + byte outBuf[512]; + word32 outSz; + int rc; + + printf("test_responder_failed_handshake_cleanup...\n"); + ASSERT_SUCCESS(wolfSPDM_Init(&req)); + ASSERT_SUCCESS(wolfSPDM_RespInit(rctx)); + ASSERT_SUCCESS(wc_ecc_init(&idKey)); + ASSERT_SUCCESS(wc_ecc_make_key(&req.rng, WOLFSPDM_ECC_KEY_SIZE, + &idKey)); + ASSERT_SUCCESS(wc_ecc_export_private_only(&idKey, idPriv, &idPrivSz)); + ASSERT_SUCCESS(wc_ecc_export_public_raw(&idKey, idPub, &idPubXSz, + idPub + WOLFSPDM_ECC_KEY_SIZE, &idPubYSz)); + wc_ecc_free(&idKey); + ASSERT_EQ(idPrivSz + idPubXSz + idPubYSz, 3 * WOLFSPDM_ECC_KEY_SIZE, + "identity key size mismatch"); + req.mode = WOLFSPDM_MODE_NUVOTON; + ASSERT_SUCCESS(wolfSPDM_SetResponderPubKey(&req, idPub, sizeof(idPub))); + ASSERT_SUCCESS(wolfSPDM_RespSetMode(rctx, 1, 0)); + ASSERT_SUCCESS(wolfSPDM_RespSetIdentityKey(rctx, idPriv, sizeof(idPriv), + idPub, sizeof(idPub))); + + /* An off-curve ExchangeData fails after the ephemeral key exists */ + wolfSPDM_WriteTcgHeader(frame, WOLFSPDM_TCG_TAG_CLEAR, + WOLFSPDM_TCG_HEADER_SIZE + sizeof(getVersion), 0, 0); + XMEMCPY(frame + WOLFSPDM_TCG_HEADER_SIZE, getVersion, sizeof(getVersion)); + outSz = sizeof(outBuf); + ASSERT_SUCCESS(wolfSPDM_RespHandleMessage(rctx, frame, + WOLFSPDM_TCG_HEADER_SIZE + sizeof(getVersion), outBuf, &outSz)); + XMEMSET(keyEx, 0, sizeof(keyEx)); + keyEx[0] = SPDM_VERSION_13; + keyEx[1] = SPDM_KEY_EXCHANGE; + keyEx[4] = 0x01; + keyEx[40 + WOLFSPDM_ECC_KEY_SIZE - 1] = 0x01; + keyEx[88 + WOLFSPDM_ECC_KEY_SIZE - 1] = 0x01; + wolfSPDM_WriteTcgHeader(frame, WOLFSPDM_TCG_TAG_CLEAR, sizeof(frame), + 0, 0); + XMEMCPY(frame + WOLFSPDM_TCG_HEADER_SIZE, keyEx, sizeof(keyEx)); + outSz = sizeof(outBuf); + rc = wolfSPDM_RespHandleMessage(rctx, frame, sizeof(frame), outBuf, + &outSz); + TEST_ASSERT(rc != WOLFSPDM_SUCCESS || + outBuf[WOLFSPDM_TCG_HEADER_SIZE + 1] == SPDM_ERROR, + "Off-curve KEY_EXCHANGE must fail"); + TEST_ASSERT(test_handshake_secrets_cleared(inner), + "Failed KEY_EXCHANGE must clear its handshake material"); + ASSERT_EQ(inner->sessionId, 0, "Failed KEY_EXCHANGE leaves no session"); + + /* A RequesterVerifyData mismatch ends the handshake */ + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, requester_to_responder_iocb, rctx)); + ASSERT_SUCCESS(wolfSPDM_GetVersion(&req)); + ASSERT_SUCCESS(wolfSPDM_TCG_GetPubKey(&req, wireKey, &wireKeySz)); + ASSERT_SUCCESS(wolfSPDM_Sha384Hash(req.certChainHash, wireKey, + wireKeySz, NULL, 0, NULL, 0)); + ASSERT_SUCCESS(wolfSPDM_TranscriptAdd(&req, req.certChainHash, + WOLFSPDM_HASH_SIZE)); + ASSERT_SUCCESS(wolfSPDM_KeyExchange(&req)); + ASSERT_EQ(inner->state, WOLFSPDM_STATE_KEY_EX, "Responder in handshake"); + req.reqFinishedKey[0] ^= 0x01; + TEST_ASSERT(wolfSPDM_Finish(&req) != WOLFSPDM_SUCCESS, + "Mismatched FINISH must fail"); + ASSERT_EQ(wolfSPDM_RespIsSessionActive(rctx), 0, "No responder session"); + ASSERT_EQ(inner->sessionId, 0, "Failed FINISH retires the session ID"); + TEST_ASSERT(inner->state != WOLFSPDM_STATE_KEY_EX, + "Failed FINISH ends the handshake"); + TEST_ASSERT(test_handshake_secrets_cleared(inner), + "Failed FINISH must clear its handshake material"); + ASSERT_EQ(XMEMCMP(inner->reqDataKey, zero, sizeof(zero)), 0, + "Failed FINISH clears the request handshake key"); + ASSERT_EQ(XMEMCMP(inner->rspDataKey, zero, sizeof(zero)), 0, + "Failed FINISH clears the response handshake key"); + + ASSERT_SUCCESS(wolfSPDM_ConnectTCG(&req)); + ASSERT_EQ(wolfSPDM_IsConnected(&req), 1, "Later handshake completes"); ASSERT_SUCCESS(wolfSPDM_Disconnect(&req)); wc_ForceZero(idPriv, sizeof(idPriv)); @@ -3571,6 +4781,7 @@ static int test_tcg_mode_connect_roundtrip(void) byte idPubX[WOLFSPDM_ECC_KEY_SIZE]; byte idPubY[WOLFSPDM_ECC_KEY_SIZE]; byte idPub[WOLFSPDM_ECC_POINT_SIZE]; + byte requesterTpmt[120] = { 0 }; byte cmd[10]; word32 idPrivSz = sizeof(idPriv); word32 idPubXSz = sizeof(idPubX); @@ -3616,7 +4827,30 @@ static int test_tcg_mode_connect_roundtrip(void) TEST_ASSERT(rc == WOLFSPDM_SUCCESS, "TPM2_CMD passthrough failed"); ASSERT_EQ(g_tpmCbInvocations, 1, "TPM stub must have run once"); - ASSERT_SUCCESS(wolfSPDM_Disconnect(&req)); + ASSERT_SUCCESS(wolfSPDM_ConnectTCG(&req)); + ASSERT_EQ(wolfSPDM_IsConnected(&req), 1, "Requester must reconnect"); + ASSERT_EQ(req.reqSeqNum, 0, "New session must use a new request sequence"); + ASSERT_EQ(req.rspSeqNum, 0, "New session must use a new response sequence"); + + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, test_responder_reply_capacity_io, + rctx)); + ASSERT_EQ(wolfSPDM_Disconnect(&req), WOLFSPDM_E_IO_FAIL, + "END_SESSION acknowledgment did not fit"); + ASSERT_EQ(wolfSPDM_RespIsSessionActive(rctx), 0, + "Accepted END_SESSION is final even without an acknowledgment"); + + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, test_tcg_handshake_io_failure, rctx)); + ASSERT_SUCCESS(test_tcg_connect_releases_session(&req)); + + SPDM_Set16BE(requesterTpmt + 20, WOLFSPDM_ECC_KEY_SIZE); + XMEMCPY(requesterTpmt + 22, idPubX, sizeof(idPubX)); + SPDM_Set16BE(requesterTpmt + 70, WOLFSPDM_ECC_KEY_SIZE); + XMEMCPY(requesterTpmt + 72, idPubY, sizeof(idPubY)); + ASSERT_SUCCESS(wolfSPDM_SetRequesterKeyPair(&req, idPriv, sizeof(idPriv), + idPub, sizeof(idPub))); + ASSERT_SUCCESS(wolfSPDM_SetRequesterKeyTPMT(&req, requesterTpmt, + sizeof(requesterTpmt))); + ASSERT_SUCCESS(test_tcg_connect_releases_session(&req)); wc_ForceZero(idPriv, sizeof(idPriv)); wolfSPDM_RespFree(rctx); @@ -3625,9 +4859,184 @@ static int test_tcg_mode_connect_roundtrip(void) } #ifdef WOLFSPDM_PSK +#ifdef WOLFSPDM_NATIONS +static int test_responder_psk_clear_retires_session(void) +{ + WOLFSPDM_CTX req; + byte rctxBuf[WOLFSPDM_RESP_CTX_STATIC_SIZE]; + WOLFSPDM_RESP_CTX* rctx = (WOLFSPDM_RESP_CTX*)rctxBuf; + byte provision[WOLFSPDM_PSK_MAX_SIZE + WOLFSPDM_HASH_SIZE]; + byte clearAuth[32]; + WOLFSPDM_NATIONS_STATUS status; + + printf("test_responder_psk_clear_retires_session...\n"); + ASSERT_SUCCESS(wolfSPDM_Init(&req)); + ASSERT_SUCCESS(wolfSPDM_RespInit(rctx)); + ASSERT_SUCCESS(wolfSPDM_SetMode(&req, WOLFSPDM_MODE_NATIONS_PSK)); + ASSERT_SUCCESS(wolfSPDM_RespSetMode(rctx, 0, 1)); + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, requester_to_responder_iocb, rctx)); + ASSERT_SUCCESS(wolfSPDM_GetRandom(&req, provision, WOLFSPDM_PSK_MAX_SIZE)); + ASSERT_SUCCESS(wolfSPDM_GetRandom(&req, clearAuth, sizeof(clearAuth))); + ASSERT_SUCCESS(wolfSPDM_Sha384Hash(provision + WOLFSPDM_PSK_MAX_SIZE, + clearAuth, sizeof(clearAuth), NULL, 0, NULL, 0)); + ASSERT_SUCCESS(wolfSPDM_Nations_PskSet(&req, provision, sizeof(provision))); + ASSERT_SUCCESS(wolfSPDM_SetPSK(&req, provision, WOLFSPDM_PSK_MAX_SIZE, + NULL, 0)); + ASSERT_SUCCESS(wolfSPDM_ConnectPsk(&req)); + ASSERT_EQ(wolfSPDM_RespIsSessionActive(rctx), 1, "PSK session active"); + + ASSERT_SUCCESS(wolfSPDM_Nations_PskClear(&req, clearAuth, + sizeof(clearAuth))); + ASSERT_EQ(wolfSPDM_RespIsSessionActive(rctx), 0, + "Clearing the PSK ends its session"); + ASSERT_SUCCESS(wolfSPDM_Nations_GetStatus(&req, &status)); + ASSERT_EQ(status.pskProvisioned, 0, "PSK was cleared"); + + wc_ForceZero(provision, sizeof(provision)); + wc_ForceZero(clearAuth, sizeof(clearAuth)); + wolfSPDM_RespFree(rctx); + wolfSPDM_Free(&req); + TEST_PASS(); +} +#endif /* WOLFSPDM_NATIONS */ + +static int test_psk_finish_clear_error_io(WOLFSPDM_CTX* ctx, const byte* txBuf, + word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + if (txSz >= WOLFSPDM_TCG_HEADER_SIZE && + SPDM_Get16BE(txBuf) == WOLFSPDM_TCG_TAG_SECURED) { + byte error[] = { ctx->spdmVersion, SPDM_ERROR, + SPDM_ERROR_DECRYPT_ERROR, 0 }; + int size = wolfSPDM_BuildTcgClearMessage(ctx, error, sizeof(error), + rxBuf, *rxSz); + if (size < 0) { + return size; + } + *rxSz = (word32)size; + return 0; + } + return requester_to_responder_iocb(ctx, txBuf, txSz, rxBuf, rxSz, userCtx); +} + +typedef struct { + WOLFSPDM_CTX peer; + WOLFSPDM_RESP_CTX* rctx; + const byte* psk; + word32 pskSz; + int securedSent; +} TEST_PSK_NO_CONTEXT; + +/* Answers PSK_EXCHANGE with no ResponderContext; peer tracks its keys. */ +static int test_psk_no_context_io(WOLFSPDM_CTX* ctx, const byte* txBuf, + word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + TEST_PSK_NO_CONTEXT* t = (TEST_PSK_NO_CONTEXT*)userCtx; + byte rsp[12 + WOLFSPDM_HASH_SIZE]; + byte th1[WOLFSPDM_HASH_SIZE]; + int rc; + + if (txSz >= WOLFSPDM_TCG_HEADER_SIZE && + SPDM_Get16BE(txBuf) == WOLFSPDM_TCG_TAG_SECURED) { + t->securedSent++; + return WOLFSPDM_E_IO_FAIL; + } + if (txSz < WOLFSPDM_TCG_HEADER_SIZE + 2 || + txBuf[WOLFSPDM_TCG_HEADER_SIZE + 1] != SPDM_PSK_EXCHANGE) { + return requester_to_responder_iocb(ctx, txBuf, txSz, rxBuf, rxSz, + t->rctx); + } + + XMEMSET(rsp, 0, sizeof(rsp)); + rsp[0] = ctx->spdmVersion; + rsp[1] = SPDM_PSK_EXCHANGE_RSP; + SPDM_Set16LE(&rsp[4], 0x0102); + XMEMCPY(t->peer.transcript, ctx->transcript, ctx->transcriptLen); + t->peer.transcriptLen = ctx->transcriptLen; + t->peer.spdmVersion = ctx->spdmVersion; + t->peer.mode = ctx->mode; + rc = wolfSPDM_SetPSK(&t->peer, t->psk, t->pskSz, NULL, 0); + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_TranscriptAdd(&t->peer, rsp, 12); + } + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_TranscriptHash(&t->peer, th1); + } + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_DeriveHandshakeKeysPsk(&t->peer, th1); + } + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_ComputeVerifyData(t->peer.rspFinishedKey, th1, + rsp + 12); + } + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_TranscriptAdd(&t->peer, rsp + 12, WOLFSPDM_HASH_SIZE); + } + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_DeriveAppDataKeys(&t->peer); + } + if (rc == WOLFSPDM_SUCCESS) { + rc = wolfSPDM_BuildTcgClearMessage(ctx, rsp, sizeof(rsp), rxBuf, + *rxSz); + if (rc >= 0) { + *rxSz = (word32)rc; + rc = WOLFSPDM_SUCCESS; + } + } + wc_ForceZero(th1, sizeof(th1)); + return rc; +} + +/* Without a ResponderContext the PSK session is established by + * PSK_EXCHANGE_RSP alone, and the application keys cover that transcript. */ +static int test_psk_exchange_without_responder_context(void) +{ + static const byte testPsk[48] = { + 0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88, + 0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xf0,0x01, + 0x12,0x23,0x34,0x45,0x56,0x67,0x78,0x89, + 0x9a,0xab,0xbc,0xcd,0xde,0xef,0xf1,0x02, + 0x13,0x24,0x35,0x46,0x57,0x68,0x79,0x8a, + 0x9b,0xac,0xbd,0xce,0xdf,0xe0,0xf2,0x03 + }; + WOLFSPDM_CTX req; + byte rctxBuf[WOLFSPDM_RESP_CTX_STATIC_SIZE]; + WOLFSPDM_RESP_CTX* rctx = (WOLFSPDM_RESP_CTX*)rctxBuf; + TEST_PSK_NO_CONTEXT t; + + printf("test_psk_exchange_without_responder_context...\n"); + + XMEMSET(&t, 0, sizeof(t)); + ASSERT_SUCCESS(wolfSPDM_Init(&req)); + ASSERT_SUCCESS(wolfSPDM_Init(&t.peer)); + ASSERT_SUCCESS(wolfSPDM_RespInit(rctx)); + req.mode = WOLFSPDM_MODE_NATIONS_PSK; + ASSERT_SUCCESS(wolfSPDM_RespSetMode(rctx, 0, 1)); + ASSERT_SUCCESS(wolfSPDM_SetPSK(&req, testPsk, sizeof(testPsk), NULL, 0)); + t.rctx = rctx; + t.psk = testPsk; + t.pskSz = sizeof(testPsk); + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, test_psk_no_context_io, &t)); + + ASSERT_SUCCESS(wolfSPDM_ConnectPsk(&req)); + ASSERT_EQ(t.securedSent, 0, "No PSK_FINISH without ResponderContext"); + ASSERT_EQ(wolfSPDM_IsConnected(&req), 1, "Requester connected"); + ASSERT_EQ(XMEMCMP(req.reqDataKey, t.peer.reqDataKey, + sizeof(req.reqDataKey)), 0, "Request key matches the peer"); + ASSERT_EQ(XMEMCMP(req.rspDataKey, t.peer.rspDataKey, + sizeof(req.rspDataKey)), 0, "Response key matches the peer"); + TEST_ASSERT(test_handshake_secrets_cleared(&req), + "Established PSK session must retire handshake material"); + + wolfSPDM_Free(&t.peer); + wolfSPDM_RespFree(rctx); + wolfSPDM_Free(&req); + TEST_PASS(); +} + /* PSK handshake + tunneled TPM2_CMD round-trip + END_SESSION, end-to-end. */ static int test_responder_psk_roundtrip(void) { + static const byte zero[WOLFSPDM_AEAD_KEY_SIZE]; static const byte testPsk[64] = { 0xdb,0xc2,0x19,0x22,0x91,0xd8,0x07,0x74, 0x24,0x41,0xb9,0x63,0xf6,0x71,0x28,0x41, @@ -3663,11 +5072,20 @@ static int test_responder_psk_roundtrip(void) g_tpmCbInvocations = 0; ASSERT_SUCCESS(wolfSPDM_RespSetTpmCallback(rctx, responder_tpm_stub, NULL)); + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, test_responder_reply_capacity_io, + rctx)); + ASSERT_EQ(wolfSPDM_ConnectPsk(&req), WOLFSPDM_E_IO_FAIL, + "A PSK_FINISH reply must fit before the session is established"); + ASSERT_EQ(wolfSPDM_RespIsSessionActive(rctx), 0, + "A failed PSK_FINISH reply leaves no active session"); + ASSERT_SUCCESS(wolfSPDM_SetPSK(&req, testPsk, sizeof(testPsk), NULL, 0)); ASSERT_SUCCESS(wolfSPDM_SetIO(&req, requester_to_responder_iocb, rctx)); rc = wolfSPDM_Connect(&req); TEST_ASSERT(rc == WOLFSPDM_SUCCESS, "PSK Connect failed"); ASSERT_EQ(wolfSPDM_IsConnected(&req), 1, "Requester not connected"); + TEST_ASSERT(test_handshake_secrets_cleared(&req), + "Established PSK session must retire handshake material"); /* Tunnel a fake TPM2_Startup command via the VENDOR_DEFINED "TPM2_CMD" * vendor message - same wrapping the real Nuvoton/Nations requester uses. */ @@ -3680,6 +5098,12 @@ static int test_responder_psk_roundtrip(void) TEST_ASSERT(rc == WOLFSPDM_SUCCESS, "TPM2_CMD passthrough failed"); ASSERT_EQ(g_tpmCbInvocations, 1, "TPM stub must have run once"); + ASSERT_SUCCESS(wolfSPDM_SetPSK(&req, testPsk, sizeof(testPsk), NULL, 0)); + ASSERT_SUCCESS(wolfSPDM_ConnectPsk(&req)); + ASSERT_EQ(wolfSPDM_IsConnected(&req), 1, "Requester must reconnect"); + ASSERT_EQ(req.reqSeqNum, 0, "New session must use a new request sequence"); + ASSERT_EQ(req.rspSeqNum, 0, "New session must use a new response sequence"); + ASSERT_SUCCESS(wolfSPDM_Disconnect(&req)); /* Session teardown must reject any later secured record until a new @@ -3695,6 +5119,25 @@ static int test_responder_psk_roundtrip(void) ASSERT_EQ(g_tpmCbInvocations, 1, "sessionless record must not reach the TPM callback"); + ASSERT_SUCCESS(wolfSPDM_SetIO(&req, test_psk_finish_clear_error_io, rctx)); + ASSERT_SUCCESS(wolfSPDM_SetPSK(&req, testPsk, sizeof(testPsk), NULL, 0)); + ASSERT_EQ(wolfSPDM_ConnectPsk(&req), WOLFSPDM_E_PEER_ERROR, + "Clear PSK_FINISH rejection should be reported as a peer error"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(&req), SPDM_ERROR_DECRYPT_ERROR, + "PSK_FINISH should record the clear peer error code"); + ASSERT_EQ(req.state, WOLFSPDM_STATE_ERROR, "PSK handshake failed"); + ASSERT_EQ(req.sessionId, 0, "The provisional session must be retired"); + TEST_ASSERT(test_handshake_secrets_cleared(&req), + "Failed PSK handshake must clear its secrets"); + ASSERT_EQ(XMEMCMP(req.reqDataKey, zero, sizeof(req.reqDataKey)), 0, + "Failed PSK handshake must clear its request key"); + ASSERT_EQ(XMEMCMP(req.rspDataKey, zero, sizeof(req.rspDataKey)), 0, + "Failed PSK handshake must clear its response key"); + ASSERT_EQ(XMEMCMP(req.reqDataIv, zero, sizeof(req.reqDataIv)), 0, + "Failed PSK handshake must clear its request IV"); + ASSERT_EQ(XMEMCMP(req.rspDataIv, zero, sizeof(req.rspDataIv)), 0, + "Failed PSK handshake must clear its response IV"); + wolfSPDM_RespFree(rctx); wolfSPDM_Free(&req); TEST_PASS(); @@ -3754,26 +5197,46 @@ static int test_parse_capabilities(void) static int test_negotiate_algorithms_roundtrip(void) { byte req[WOLFSPDM_NEG_ALGO_SZ]; - byte rsp[52]; + byte rsp[48]; word32 reqSz = sizeof(req); TEST_CTX_SETUP_V12(); printf("test_negotiate_algorithms_roundtrip...\n"); ASSERT_SUCCESS(wolfSPDM_BuildNegotiateAlgorithms(ctx, req, &reqSz)); - ASSERT_EQ(reqSz, (word32)48, "NEGOTIATE_ALGORITHMS size"); + ASSERT_EQ(req[2], 3, "Offer DHE, AEAD and key schedule"); + ASSERT_EQ(req[40], SPDM_ALG_TYPE_KEY_SCHEDULE, + "No requester signature algorithm"); + ASSERT_EQ(reqSz, (word32)44, "NEGOTIATE_ALGORITHMS size"); + ASSERT_EQ(SPDM_Get16LE(&req[4]), reqSz, "Declared request length"); - /* Algorithm Set B selection with DHE, AEAD, ReqBaseAsym, KeySchedule */ + /* Algorithm Set B selection with DHE, AEAD and KeySchedule */ XMEMSET(rsp, 0, sizeof(rsp)); rsp[0] = SPDM_VERSION_12; - rsp[1] = SPDM_ALGORITHMS; - rsp[2] = 4; - SPDM_Set16LE(&rsp[4], sizeof(rsp)); - rsp[6] = 0x01; + rsp[1] = SPDM_ALGORITHMS; + rsp[2] = 3; + SPDM_Set16LE(&rsp[4], sizeof(rsp)); + rsp[6] = 0x01; + rsp[7] = 0x02; + SPDM_Set32LE(&rsp[12], SPDM_ASYM_ALGO_ECDSA_P384); + SPDM_Set32LE(&rsp[16], SPDM_HASH_ALGO_SHA_384); + XMEMCPY(&rsp[36], &req[32], 12); + ASSERT_SUCCESS(wolfSPDM_ParseAlgorithms(ctx, rsp, sizeof(rsp))); + + rsp[7] = 0xFE; + ASSERT_SUCCESS(wolfSPDM_ParseAlgorithms(ctx, rsp, sizeof(rsp))); + ctx->spdmVersion = SPDM_VERSION_13; + rsp[0] = SPDM_VERSION_13; + rsp[7] = 0xEE; + ASSERT_SUCCESS(wolfSPDM_ParseAlgorithms(ctx, rsp, sizeof(rsp))); + rsp[7] = 0xFE; + ASSERT_EQ(wolfSPDM_ParseAlgorithms(ctx, rsp, sizeof(rsp)), + WOLFSPDM_E_ALGO_MISMATCH, "Multi-key selection requires an offer"); + rsp[7] = 0x03; + ASSERT_EQ(wolfSPDM_ParseAlgorithms(ctx, rsp, sizeof(rsp)), + WOLFSPDM_E_ALGO_MISMATCH, "The peer must select one opaque format"); + ctx->spdmVersion = SPDM_VERSION_12; + rsp[0] = SPDM_VERSION_12; rsp[7] = 0x02; - SPDM_Set32LE(&rsp[12], SPDM_ASYM_ALGO_ECDSA_P384); - SPDM_Set32LE(&rsp[16], SPDM_HASH_ALGO_SHA_384); - XMEMCPY(&rsp[36], &req[32], 16); - ASSERT_SUCCESS(wolfSPDM_ParseAlgorithms(ctx, rsp, sizeof(rsp))); /* Declared Length must equal the received size */ SPDM_Set16LE(&rsp[4], sizeof(rsp) - 1); @@ -3788,7 +5251,7 @@ static int test_negotiate_algorithms_roundtrip(void) SPDM_Set16LE(&rsp[42], SPDM_AEAD_ALGO_AES_256_GCM); /* AlgStruct count past the end of the response */ - rsp[2] = 5; + rsp[2] = 4; ASSERT_EQ(wolfSPDM_ParseAlgorithms(ctx, rsp, sizeof(rsp)), WOLFSPDM_E_ALGO_MISMATCH, "truncated AlgStructs must fail"); @@ -3878,6 +5341,39 @@ static int test_load_sample_chain(WOLFSPDM_CTX* ctx) return 0; } +#ifdef WOLFSPDM_TCG +static int test_tcg_requires_explicit_responder_pin(void) +{ + int keyExchangeRc; + int connectRc; + TEST_CTX_SETUP_V12(); + + printf("test_tcg_requires_explicit_responder_pin...\n"); + ASSERT_SUCCESS(test_load_sample_chain(ctx)); + ASSERT_SUCCESS(wolfSPDM_SetTrustedCAs(ctx, test_ca_cert_der, + sizeof(test_ca_cert_der))); + ASSERT_SUCCESS(wolfSPDM_ValidateCertChain(ctx)); + ASSERT_SUCCESS(wolfSPDM_SetMode(ctx, WOLFSPDM_MODE_TCG)); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, dummy_io_cb, NULL)); + + keyExchangeRc = wolfSPDM_KeyExchange(ctx); + connectRc = wolfSPDM_ConnectTCG(ctx); + ASSERT_EQ(keyExchangeRc, WOLFSPDM_E_BAD_STATE, + "TCG key exchange must require a configured responder pin"); + ASSERT_EQ(connectRc, WOLFSPDM_E_BAD_STATE, + "TCG connect must require a configured responder pin"); + + ASSERT_SUCCESS(wolfSPDM_SetResponderPubKey(ctx, test_rsp_leaf_pub, + sizeof(test_rsp_leaf_pub))); + ASSERT_EQ(wolfSPDM_KeyExchange(ctx), WOLFSPDM_E_IO_FAIL, + "Configured pin allows key exchange to reach the transport"); + ASSERT_EQ(wolfSPDM_ConnectTCG(ctx), WOLFSPDM_E_IO_FAIL, + "Configured pin allows connect to reach the transport"); + TEST_CTX_FREE(); + TEST_PASS(); +} +#endif /* WOLFSPDM_TCG */ + static int test_validate_cert_chain(void) { byte leafKey[WOLFSPDM_ECC_POINT_SIZE]; @@ -3981,6 +5477,44 @@ static int test_validate_cert_chain(void) TEST_CTX_FREE(); TEST_PASS(); } + +#if !defined(NO_ASN_TIME) && !defined(NO_ASN_TIME_CHECK) +static int test_certificate_validity(void) +{ + const time_t original = g_certificateTime; +#ifdef WOLFSPDM_NO_CERT_DATE_CHECK + const int dateRc = WOLFSPDM_SUCCESS; +#else + const int dateRc = WOLFSPDM_E_CERT_FAIL; +#endif + int rc; + TEST_CTX_SETUP_V12(); + + printf("test_certificate_validity...\n"); + ASSERT_SUCCESS(test_load_sample_chain(ctx)); + ASSERT_SUCCESS(wolfSPDM_SetTrustedCAs(ctx, test_ca_cert_der, + sizeof(test_ca_cert_der))); + ASSERT_SUCCESS(wolfSPDM_ValidateCertChain(ctx)); + + g_certificateTime = 1767225600; /* 2026-01-01 UTC */ + rc = wolfSPDM_ValidateCertChain(ctx); + g_certificateTime = original; + ASSERT_EQ(rc, dateRc, "Certificate is not yet valid"); + ASSERT_EQ(ctx->flags.hasRspPubKey, dateRc == WOLFSPDM_SUCCESS, + "Keep the leaf only when dates are not checked"); + + ASSERT_SUCCESS(wolfSPDM_ValidateCertChain(ctx)); + g_certificateTime = 2114380800; /* 2037-01-01 UTC */ + rc = wolfSPDM_ValidateCertChain(ctx); + g_certificateTime = original; + ASSERT_EQ(rc, dateRc, "Certificate has expired"); + ASSERT_EQ(ctx->flags.hasRspPubKey, dateRc == WOLFSPDM_SUCCESS, + "Keep the leaf only when dates are not checked"); + + TEST_CTX_FREE(); + TEST_PASS(); +} +#endif /* Serves the sample chain in small CERTIFICATE portions and hashes the * exchanged bytes the way M1 must */ typedef struct { @@ -4030,11 +5564,17 @@ static int cert_portion_io_cb(WOLFSPDM_CTX* ctx, const byte* txBuf, static int test_get_certificate_portions(void) { + static const byte vca[] = { SPDM_VERSION_12, SPDM_ALGORITHMS, 0, 0 }; + static const int sessionStates[] = { + WOLFSPDM_STATE_KEY_EX, WOLFSPDM_STATE_FINISH, WOLFSPDM_STATE_CONNECTED + }; + word32 i; + word32 mark; + word32 exchanges; static TEST_CERT_RSP r; #ifndef WOLFSPDM_NO_CHALLENGE byte want[WOLFSPDM_HASH_SIZE]; byte got[WOLFSPDM_HASH_SIZE]; - wc_Sha384 m1; #endif TEST_CTX_SETUP_V12(); printf("test_get_certificate_portions...\n"); @@ -4047,7 +5587,10 @@ static int test_get_certificate_portions(void) XMEMCPY(r.chain + WOLFSPDM_CERT_CHAIN_HDR_SZ, test_rsp_chain_der, sizeof(test_rsp_chain_der)); ASSERT_EQ(wc_InitSha384(&r.m1), 0, "init expected M1"); + ASSERT_SUCCESS(wolfSPDM_TranscriptAdd(ctx, vca, sizeof(vca))); + ctx->vcaLen = ctx->transcriptLen; #ifndef WOLFSPDM_NO_CHALLENGE + ASSERT_EQ(wc_Sha384Update(&r.m1, vca, sizeof(vca)), 0, "VCA in M1"); ASSERT_SUCCESS(wolfSPDM_M1Start(ctx)); #endif @@ -4060,31 +5603,213 @@ static int test_get_certificate_portions(void) #ifndef WOLFSPDM_NO_CHALLENGE /* M1 holds each GET_CERTIFICATE and its full CERTIFICATE response */ - ASSERT_EQ(wc_Sha384Final(&r.m1, want), 0, "expected M1"); - ASSERT_EQ(wc_Sha384Copy(&ctx->m1Hash, &m1), 0, "copy M1"); - ASSERT_EQ(wc_Sha384Final(&m1, got), 0, "final M1"); - wc_Sha384Free(&m1); + ASSERT_EQ(wc_Sha384GetHash(&r.m1, want), 0, "expected M1"); + ASSERT_EQ(wc_Sha384GetHash(&ctx->m1Hash, got), 0, "requester M1"); ASSERT_EQ(XMEMCMP(want, got, sizeof(want)), 0, "M1 matches the exchanged bytes"); #endif + mark = ctx->transcriptLen; + exchanges = r.exchanges; + for (i = 0; i < sizeof(sessionStates) / sizeof(sessionStates[0]); i++) { + ctx->state = sessionStates[i]; + ASSERT_EQ(wolfSPDM_GetCertificate(ctx, 1), WOLFSPDM_E_BAD_STATE, + "Certificate fetching must not interrupt a session"); + ASSERT_EQ(ctx->state, sessionStates[i], "Preserve session state"); + } + ASSERT_EQ(ctx->transcriptLen, mark, "Preserve the session transcript"); + ASSERT_EQ(ctx->certChainLen, r.chainSz, "Preserve the current chain"); + ASSERT_EQ(ctx->currentSlotId, 0, "Preserve the current certificate slot"); + ASSERT_EQ(r.exchanges, exchanges, "Reject before contacting the peer"); + + ctx->state = WOLFSPDM_STATE_CERT; + ASSERT_SUCCESS(wolfSPDM_GetCertificate(ctx, 1)); + ASSERT_EQ(ctx->currentSlotId, 1, "Use the newly fetched certificate slot"); + ASSERT_EQ(ctx->transcriptLen, sizeof(vca) + WOLFSPDM_HASH_SIZE, + "TH starts with VCA and one certificate hash"); + ASSERT_EQ(XMEMCMP(ctx->transcript, vca, sizeof(vca)), 0, "Preserve VCA"); + ASSERT_EQ(XMEMCMP(ctx->transcript + sizeof(vca), ctx->certChainHash, + WOLFSPDM_HASH_SIZE), 0, "TH includes the current certificate hash"); +#ifndef WOLFSPDM_NO_CHALLENGE + ASSERT_EQ(wc_Sha384GetHash(&r.m1, want), 0, "expected M1 after refetch"); + ASSERT_EQ(wc_Sha384GetHash(&ctx->m1Hash, got), 0, "requester M1 after refetch"); + ASSERT_EQ(XMEMCMP(want, got, sizeof(want)), 0, + "M1 covers certificate exchanges for both slots"); +#endif + wolfSPDM_SetIO(ctx, dummy_io_cb, NULL); + ASSERT_EQ(wolfSPDM_GetCertificate(ctx, 0), WOLFSPDM_E_IO_FAIL, + "Transport failure fetching another certificate"); + ASSERT_EQ(ctx->transcriptLen, sizeof(vca), + "The failed fetch leaves only VCA in TH"); + wc_Sha384Free(&r.m1); TEST_CTX_FREE(); TEST_PASS(); } + +#ifndef WOLFSPDM_NO_MCTP +typedef struct { + WOLFSPDM_CTX ctx; + TEST_CERT_RSP certs; + int finishIoCalls; +} TEST_STANDARD_PEER; + +static int test_build_standard_key_exchange(WOLFSPDM_CTX* peer, + const WOLFSPDM_CTX* ctx, const byte* txBuf, word32 txSz, + byte* rxBuf, word32* rxSz) +{ + const word32 sigOffset = 40 + WOLFSPDM_ECC_POINT_SIZE + 2; + const word32 hmacOffset = sigOffset + WOLFSPDM_ECC_SIG_SIZE; + const word32 responseSz = hmacOffset + WOLFSPDM_HASH_SIZE; + word32 xSz = WOLFSPDM_ECC_KEY_SIZE; + word32 ySz = WOLFSPDM_ECC_KEY_SIZE; + byte digest[WOLFSPDM_HASH_SIZE]; + byte signedDigest[WOLFSPDM_HASH_SIZE]; + + if (txSz < 40 + WOLFSPDM_ECC_POINT_SIZE || *rxSz < responseSz) { + return -1; + } + XMEMSET(rxBuf, 0, responseSz); + peer->spdmVersion = txBuf[0]; + rxBuf[0] = txBuf[0]; + rxBuf[1] = SPDM_KEY_EXCHANGE_RSP; + SPDM_Set16LE(&rxBuf[4], 2); + ASSERT_SUCCESS(wolfSPDM_GetRandom(peer, &rxBuf[8], 32)); + ASSERT_SUCCESS(wolfSPDM_GenerateEphemeralKey(peer)); + ASSERT_SUCCESS(wolfSPDM_ExportEphemeralPubKey(peer, &rxBuf[40], &xSz, + &rxBuf[40 + WOLFSPDM_ECC_KEY_SIZE], &ySz)); + ASSERT_SUCCESS(wolfSPDM_ComputeSharedSecret(peer, &txBuf[40], + &txBuf[40 + WOLFSPDM_ECC_KEY_SIZE])); + ASSERT_SUCCESS(wolfSPDM_TranscriptAdd(peer, ctx->transcript, + ctx->transcriptLen)); + ASSERT_SUCCESS(wolfSPDM_TranscriptAdd(peer, rxBuf, sigOffset)); + ASSERT_SUCCESS(wolfSPDM_TranscriptHash(peer, digest)); + ASSERT_SUCCESS(wolfSPDM_BuildSignedHash(peer->spdmVersion, + "responder-key_exchange_rsp signing", 34, digest, signedDigest)); + ASSERT_SUCCESS(test_ecc_sign(&peer->rng, test_rsp_leaf_priv, + test_rsp_leaf_pub, signedDigest, &rxBuf[sigOffset])); + ASSERT_SUCCESS(wolfSPDM_TranscriptAdd(peer, &rxBuf[sigOffset], + WOLFSPDM_ECC_SIG_SIZE)); + ASSERT_SUCCESS(wolfSPDM_TranscriptHash(peer, digest)); + ASSERT_SUCCESS(wolfSPDM_DeriveHandshakeKeys(peer, digest)); + ASSERT_SUCCESS(wolfSPDM_ComputeVerifyData(peer->rspFinishedKey, digest, + &rxBuf[hmacOffset])); + *rxSz = responseSz; + return 0; +} + +static int standard_connect_io(WOLFSPDM_CTX* ctx, const byte* txBuf, + word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + TEST_STANDARD_PEER* peer = (TEST_STANDARD_PEER*)userCtx; + + if (ctx->state == WOLFSPDM_STATE_KEY_EX) { + peer->finishIoCalls++; + return -1; + } + if (txSz < 4) { + return -1; + } + switch (txBuf[1]) { + case SPDM_GET_VERSION: + return test_version_restart_io(ctx, txBuf, txSz, rxBuf, rxSz, + NULL); + case SPDM_GET_CAPABILITIES: + if (*rxSz < 20) { + return -1; + } + *rxSz = 20; + XMEMSET(rxBuf, 0, *rxSz); + rxBuf[0] = txBuf[0]; + rxBuf[1] = SPDM_CAPABILITIES; + SPDM_Set32LE(&rxBuf[8], SPDM_CAP_CERT_CAP | SPDM_CAP_ENCRYPT_CAP | + SPDM_CAP_MAC_CAP | SPDM_CAP_KEY_EX_CAP); + SPDM_Set32LE(&rxBuf[12], 1024); + SPDM_Set32LE(&rxBuf[16], 1024); + return 0; + case SPDM_NEGOTIATE_ALGORITHMS: + if (*rxSz < 48 || txSz != 44) { + return -1; + } + *rxSz = 48; + XMEMSET(rxBuf, 0, *rxSz); + rxBuf[0] = txBuf[0]; + rxBuf[1] = SPDM_ALGORITHMS; + rxBuf[2] = 3; + SPDM_Set16LE(&rxBuf[4], 48); + rxBuf[6] = 1; + rxBuf[7] = 2; + SPDM_Set32LE(&rxBuf[12], SPDM_ASYM_ALGO_ECDSA_P384); + SPDM_Set32LE(&rxBuf[16], SPDM_HASH_ALGO_SHA_384); + XMEMCPY(&rxBuf[36], &txBuf[32], 12); + return 0; + case SPDM_GET_DIGESTS: + if (*rxSz < 4 + WOLFSPDM_HASH_SIZE) { + return -1; + } + rxBuf[0] = txBuf[0]; + rxBuf[1] = SPDM_DIGESTS; + rxBuf[2] = 0; + rxBuf[3] = 1; + *rxSz = 4 + WOLFSPDM_HASH_SIZE; + return wolfSPDM_Sha384Hash(&rxBuf[4], peer->certs.chain, + peer->certs.chainSz, NULL, 0, NULL, 0); + case SPDM_GET_CERTIFICATE: + return cert_portion_io_cb(ctx, txBuf, txSz, rxBuf, rxSz, + &peer->certs); + case SPDM_KEY_EXCHANGE: + return test_build_standard_key_exchange(&peer->ctx, ctx, txBuf, + txSz, rxBuf, rxSz); + default: + return -1; + } +} + +static int test_standard_connect_releases_session(void) +{ + static const byte zero[WOLFSPDM_HASH_SIZE]; + static TEST_STANDARD_PEER peer; + TEST_CTX_SETUP(); + + puts("test_standard_connect_releases_session..."); + ASSERT_SUCCESS(wolfSPDM_Init(&peer.ctx)); + ASSERT_SUCCESS(test_load_sample_chain(&peer.ctx)); + peer.certs.chainSz = peer.ctx.certChainLen; + XMEMCPY(peer.certs.chain, peer.ctx.certChain, peer.certs.chainSz); + ASSERT_SUCCESS(wc_InitSha384(&peer.certs.m1)); + ASSERT_SUCCESS(wolfSPDM_SetTrustedCAs(ctx, test_ca_cert_der, + sizeof(test_ca_cert_der))); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, standard_connect_io, &peer)); + ASSERT_EQ(wolfSPDM_Connect(ctx), WOLFSPDM_E_IO_FAIL, "FINISH I/O failure"); + ASSERT_EQ(peer.finishIoCalls, 1, "One I/O failure after key exchange"); + ASSERT_EQ(ctx->state, WOLFSPDM_STATE_ERROR, "Aborted standard session"); + TEST_ASSERT(test_handshake_secrets_cleared(ctx), + "Aborted standard connection must retire handshake material"); + TEST_ASSERT(XMEMCMP(ctx->reqDataKey, zero, sizeof(ctx->reqDataKey)) == 0 && + XMEMCMP(ctx->rspDataKey, zero, sizeof(ctx->rspDataKey)) == 0 && + XMEMCMP(ctx->reqDataIv, zero, sizeof(ctx->reqDataIv)) == 0 && + XMEMCMP(ctx->rspDataIv, zero, sizeof(ctx->rspDataIv)) == 0, + "Aborted standard connection must retire traffic material"); + ASSERT_EQ(ctx->sessionId, 0, "Aborted standard session ID"); + TEST_CTX_FREE(); + wc_Sha384Free(&peer.certs.m1); + wolfSPDM_Free(&peer.ctx); + TEST_PASS(); +} +#endif /* !WOLFSPDM_NO_MCTP */ + #endif /* !WOLFSPDM_NO_CERT */ #if defined(WOLFSPDM_HAVE_MLDSA) || defined(WOLFSPDM_HAVE_MLKEM) -/* ALGORITHMS response: fixed fields, then DHE, AEAD, ReqBaseAsym, KeySchedule - * and KEMAlg structs */ +/* ALGORITHMS response with DHE, AEAD, KeySchedule and KEMAlg structs */ static word32 test_algo_rsp(byte* rsp, byte ver, word32 baseAsym, word32 pqc, word16 dhe, word16 kem) { - XMEMSET(rsp, 0, 56); + XMEMSET(rsp, 0, 52); rsp[0] = ver; rsp[1] = SPDM_ALGORITHMS; - rsp[2] = 5; - SPDM_Set16LE(&rsp[4], 56); + rsp[2] = 4; + SPDM_Set16LE(&rsp[4], 52); rsp[6] = 0x01; rsp[7] = 0x02; SPDM_Set32LE(&rsp[12], baseAsym); @@ -4096,21 +5821,19 @@ static word32 test_algo_rsp(byte* rsp, byte ver, word32 baseAsym, word32 pqc, rsp[40] = SPDM_ALG_TYPE_AEAD; rsp[41] = 0x20; SPDM_Set16LE(&rsp[42], SPDM_AEAD_ALGO_AES_256_GCM); - rsp[44] = SPDM_ALG_TYPE_REQ_BASE_ASYM; + rsp[44] = SPDM_ALG_TYPE_KEY_SCHEDULE; rsp[45] = 0x20; - rsp[48] = SPDM_ALG_TYPE_KEY_SCHEDULE; + SPDM_Set16LE(&rsp[46], SPDM_KEY_SCHEDULE_SPDM); + rsp[48] = SPDM_ALG_TYPE_KEM; rsp[49] = 0x20; - SPDM_Set16LE(&rsp[50], SPDM_KEY_SCHEDULE_SPDM); - rsp[52] = SPDM_ALG_TYPE_KEM; - rsp[53] = 0x20; - SPDM_Set16LE(&rsp[54], kem); - return 56; + SPDM_Set16LE(&rsp[50], kem); + return 52; } static int test_negotiate_algorithms_pqc(void) { byte req[WOLFSPDM_NEG_ALGO_SZ]; - byte rsp[56]; + byte rsp[52]; word32 reqSz = sizeof(req); word32 rspSz; #ifdef WOLFSPDM_HAVE_MLKEM @@ -4127,7 +5850,7 @@ static int test_negotiate_algorithms_pqc(void) /* Before 1.4 the request carries neither PqcAsymAlgo nor KEMAlg */ ctx->spdmVersion = SPDM_VERSION_13; ASSERT_SUCCESS(wolfSPDM_BuildNegotiateAlgorithms(ctx, req, &reqSz)); - ASSERT_EQ(reqSz, (word32)48, "classical request below 1.4"); + ASSERT_EQ(reqSz, (word32)44, "classical request below 1.4"); ASSERT_EQ(SPDM_Get32LE(&req[16]), 0, "PqcAsymAlgo reserved below 1.4"); ctx->spdmVersion = SPDM_VERSION_14; @@ -4140,11 +5863,11 @@ static int test_negotiate_algorithms_pqc(void) "ML-DSA sets offered at 1.4"); #endif #ifdef WOLFSPDM_HAVE_MLKEM - ASSERT_EQ(reqSz, (word32)52, "KEMAlg appended at 1.4"); - ASSERT_EQ(req[2], 5, "five AlgStructs"); + ASSERT_EQ(reqSz, (word32)48, "KEMAlg appended at 1.4"); + ASSERT_EQ(req[2], 4, "four AlgStructs"); ASSERT_EQ(req[32], SPDM_ALG_TYPE_DHE, "DHE on offer"); - ASSERT_EQ(req[48], SPDM_ALG_TYPE_KEM, "KEMAlg type"); - ASSERT_EQ(SPDM_Get16LE(&req[50]), WOLFSPDM_MLKEM_SETS, + ASSERT_EQ(req[44], SPDM_ALG_TYPE_KEM, "KEMAlg type"); + ASSERT_EQ(SPDM_Get16LE(&req[46]), WOLFSPDM_MLKEM_SETS, "every built ML-KEM set offered"); #endif @@ -4191,6 +5914,28 @@ static int test_negotiate_algorithms_pqc(void) ASSERT_SUCCESS(wolfSPDM_ParseAlgorithms(ctx, rsp, rspSz)); ASSERT_EQ(ctx->pqcAsymSel, 0, "PqcAsymSel ignored below 1.4"); ctx->spdmVersion = SPDM_VERSION_14; + + ASSERT_SUCCESS(test_load_sample_chain(ctx)); + ASSERT_SUCCESS(wolfSPDM_SetTrustedCAs(ctx, test_ca_cert_der, + sizeof(test_ca_cert_der))); + ASSERT_SUCCESS(wolfSPDM_ValidateCertChain(ctx)); + ASSERT_EQ(ctx->flags.rspKeyFromCert, 1, "Certificate-derived leaf"); + reqSz = sizeof(req); + ASSERT_SUCCESS(wolfSPDM_BuildNegotiateAlgorithms(ctx, req, &reqSz)); + ASSERT_EQ(SPDM_Get32LE(&req[16]), WOLFSPDM_MLDSA_SETS, + "An earlier certificate leaf does not restrict the offer"); + + ASSERT_SUCCESS(wolfSPDM_SetResponderPubKey(ctx, test_rsp_leaf_pub, + sizeof(test_rsp_leaf_pub))); + reqSz = sizeof(req); + ASSERT_SUCCESS(wolfSPDM_BuildNegotiateAlgorithms(ctx, req, &reqSz)); + ASSERT_EQ(SPDM_Get32LE(&req[8]), SPDM_ASYM_ALGO_ECDSA_P384, + "Offer the pinned signature algorithm"); + ASSERT_EQ(SPDM_Get32LE(&req[16]), 0, "A P-384 pin limits the offer"); + rspSz = test_algo_rsp(rsp, SPDM_VERSION_14, 0, pqc, + SPDM_DHE_ALGO_SECP384R1, 0); + ASSERT_EQ(wolfSPDM_ParseAlgorithms(ctx, rsp, rspSz), + WOLFSPDM_E_ALGO_MISMATCH, "Reject an incompatible selection"); #endif #ifdef WOLFSPDM_HAVE_MLKEM @@ -4224,7 +5969,7 @@ static int test_negotiate_algorithms_pqc(void) ASSERT_SUCCESS(wolfSPDM_SetKeyExchangePref(ctx, 0, kem)); reqSz = sizeof(req); ASSERT_SUCCESS(wolfSPDM_BuildNegotiateAlgorithms(ctx, req, &reqSz)); - ASSERT_EQ(reqSz, (word32)48, "four AlgStructs"); + ASSERT_EQ(reqSz, (word32)44, "three AlgStructs"); ASSERT_EQ(req[32], SPDM_ALG_TYPE_AEAD, "no DHE struct"); rspSz = test_algo_rsp(rsp, SPDM_VERSION_14, SPDM_ASYM_ALGO_ECDSA_P384, 0, SPDM_DHE_ALGO_SECP384R1, 0); @@ -4467,8 +6212,10 @@ static int test_mlkem_key_exchange(void) rsp[1] = SPDM_KEY_EXCHANGE_RSP; ASSERT_EQ(wolfSPDM_ParseKeyExchangeRsp(ctx, rsp, sizeof(rsp)), WOLFSPDM_E_BUFFER_SMALL, "ciphertext past the response"); + TEST_ASSERT(test_handshake_secrets_cleared(ctx), + "Rejected ML-KEM response releases the key and shared secret"); - /* Renegotiating ECDHE replaces the ML-KEM key */ + /* A fresh ECDHE exchange can follow the rejected response */ ctx->kemAlgSel = 0; reqSz = sizeof(req); ASSERT_SUCCESS(wolfSPDM_BuildKeyExchange(ctx, req, &reqSz)); @@ -4576,18 +6323,32 @@ static int test_secured_record_edges(void) WOLFSPDM_E_SESSION_INVALID, "session ID mismatch"); ctx->sessionId = 0x00020001; - /* MCTP carries 16 sequence bits and must not wrap */ - ctx->reqSeqNum = 0x10000; - encSz = sizeof(enc); - ASSERT_EQ(wolfSPDM_EncryptInternal(ctx, plain, 1, enc, &encSz), - WOLFSPDM_E_SEQUENCE, "request sequence past 16 bits"); + /* DSP0276 1.3 4.1: MCTP sends the low 16 bits; peers track all 64 */ + ctx->reqSeqNum = 0xFFFF; + ctx->rspSeqNum = 0xFFFF; + for (i = 0; i < 3; i++) { + encSz = sizeof(enc); + ASSERT_SUCCESS(wolfSPDM_EncryptInternal(ctx, plain, 1, enc, &encSz)); + ASSERT_EQ(SPDM_Get16LE(&enc[4]), (word16)(0xFFFF + i), + "wire sequence is the low 16 bits"); + decSz = sizeof(dec); + ASSERT_SUCCESS(wolfSPDM_DecryptInternal(ctx, enc, encSz, dec, + &decSz)); + } + ASSERT_EQ(ctx->rspSeqNum, 0x10002, "full receive counter"); + + /* The upper bits stay in the nonce, so an old record does not verify */ ctx->reqSeqNum = 0; encSz = sizeof(enc); ASSERT_SUCCESS(wolfSPDM_EncryptInternal(ctx, plain, 1, enc, &encSz)); ctx->rspSeqNum = 0x10000; decSz = sizeof(dec); ASSERT_EQ(wolfSPDM_DecryptInternal(ctx, enc, encSz, dec, &decSz), - WOLFSPDM_E_SEQUENCE, "response sequence past 16 bits"); + WOLFSPDM_E_DECRYPT_FAIL, "record from an earlier 16-bit epoch"); + ctx->rspSeqNum = 1; + decSz = sizeof(dec); + ASSERT_EQ(wolfSPDM_DecryptInternal(ctx, enc, encSz, dec, &decSz), + WOLFSPDM_E_SEQUENCE, "wire sequence mismatch"); TEST_CTX_FREE(); TEST_PASS(); @@ -4863,8 +6624,12 @@ static int test_derive_updated_keys(void) static WOLFSPDM_CTX g_peer; static int g_peerRejects; static int g_peerGarble; /* corrupt the next secured response */ +static byte g_peerRejectCode; /* ErrorCode when rejecting, else Busy */ +static int g_peerClearReply; /* answer the next secured request in clear */ #ifndef WOLFSPDM_NO_KEY_UPDATE +static int g_peerRejectVerify; /* refuse KEY_UPDATE VerifyNewKey */ + static void test_swap(byte* a, byte* b, word32 sz) { word32 i; @@ -5048,7 +6813,13 @@ static int test_peer_dispatch(WOLFSPDM_CTX* ctx, WOLFSPDM_CTX* p, rsp[3] = 0; *rspSz = 4; if (g_peerRejects) { - rsp[2] = SPDM_ERROR_BUSY; + rsp[2] = (g_peerRejectCode != 0) ? g_peerRejectCode : + SPDM_ERROR_BUSY; + } + else if (req[1] == SPDM_END_SESSION) { + rsp[1] = SPDM_END_SESSION_ACK; + rsp[2] = 0xA5; + rsp[3] = 0x5A; } else if (req[1] == SPDM_VENDOR_DEFINED_REQUEST) { /* Echo sized by the request, to drive chunking */ @@ -5057,6 +6828,10 @@ static int test_peer_dispatch(WOLFSPDM_CTX* ctx, WOLFSPDM_CTX* p, *rspSz = reqSz; } #ifndef WOLFSPDM_NO_KEY_UPDATE + else if (req[1] == SPDM_KEY_UPDATE && g_peerRejectVerify && + req[2] == SPDM_KEY_UPDATE_OP_VERIFY_NEW_KEY) { + rsp[2] = SPDM_ERROR_BUSY; + } else if (req[1] == SPDM_KEY_UPDATE) { rsp[1] = SPDM_KEY_UPDATE_ACK; rsp[2] = req[2]; @@ -5333,7 +7108,8 @@ static int test_peer_io_cb(WOLFSPDM_CTX* ctx, const byte* txBuf, word32 txSz, if (rc != 0) { return -1; } - if (clear) { + if (clear || g_peerClearReply) { + g_peerClearReply = 0; if (rspSz > *rxSz) { return -1; } @@ -5405,6 +7181,163 @@ static void test_session_loopback(WOLFSPDM_CTX* ctx) g_peerRejects = 0; wolfSPDM_SetIO(ctx, test_peer_io_cb, p); } +static int test_disconnect_reports_peer_error(void) +{ + int rc; + TEST_CTX_SETUP(); + + printf("test_disconnect_reports_peer_error...\n"); + test_session_loopback(ctx); + g_peerRejects = 1; + rc = wolfSPDM_Disconnect(ctx); + g_peerRejects = 0; + + ASSERT_EQ(rc, WOLFSPDM_E_PEER_ERROR, "END_SESSION should report rejection"); + ASSERT_EQ(wolfSPDM_IsConnected(ctx), 0, "Local session should be retired"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), SPDM_ERROR_BUSY, + "END_SESSION peer error should survive local teardown"); + + wolfSPDM_Free(&g_peer); + TEST_CTX_FREE(); + TEST_PASS(); +} + +static int test_disconnect_ignores_reserved_parameters(void) +{ + TEST_CTX_SETUP(); + + printf("test_disconnect_ignores_reserved_parameters...\n"); + test_session_loopback(ctx); + ASSERT_SUCCESS(wolfSPDM_Disconnect(ctx)); + ASSERT_EQ(wolfSPDM_IsConnected(ctx), 0, "Local session should be retired"); + + wolfSPDM_Free(&g_peer); + TEST_CTX_FREE(); + TEST_PASS(); +} + +#ifndef WOLFSPDM_NO_APP_DATA +static int test_unsolicited_decrypt_error_io(WOLFSPDM_CTX* ctx, + const byte* txBuf, word32 txSz, byte* rxBuf, word32* rxSz, void* userCtx) +{ + static const byte err[4] = { + SPDM_VERSION_12, SPDM_ERROR, SPDM_ERROR_DECRYPT_ERROR, 0 + }; + + (void)ctx; + (void)txBuf; + (void)txSz; + (void)userCtx; + return wolfSPDM_EncryptInternal(&g_peer, err, sizeof(err), rxBuf, rxSz); +} +#endif + +static int test_session_retired(const WOLFSPDM_CTX* ctx) +{ + static const byte zero[WOLFSPDM_AEAD_KEY_SIZE]; + + return ctx->state == WOLFSPDM_STATE_ERROR && ctx->sessionId == 0 && + XMEMCMP(ctx->reqDataKey, zero, sizeof(zero)) == 0 && + XMEMCMP(ctx->rspDataKey, zero, sizeof(zero)) == 0; +} + +/* An authenticated DecryptError ends the session and destroys its keys */ +static int test_peer_decrypt_error_ends_session(void) +{ + byte req[8] = { SPDM_VERSION_12, SPDM_VENDOR_DEFINED_REQUEST, 0, 0, + 0, 0, 0, 0 }; + byte rsp[64]; + word32 rspSz; +#ifndef WOLFSPDM_NO_APP_DATA + byte data[64]; + word32 dataSz = sizeof(data); +#endif + TEST_CTX_SETUP(); + + printf("test_peer_decrypt_error_ends_session...\n"); + test_session_loopback(ctx); + g_peerRejects = 1; + rspSz = sizeof(rsp); + ASSERT_SUCCESS(wolfSPDM_SecuredExchange(ctx, req, sizeof(req), rsp, + &rspSz)); + ASSERT_EQ(wolfSPDM_IsConnected(ctx), 1, "Busy keeps the session"); + + g_peerRejects = 1; + g_peerRejectCode = SPDM_ERROR_DECRYPT_ERROR; + rspSz = sizeof(rsp); + (void)wolfSPDM_SecuredExchange(ctx, req, sizeof(req), rsp, &rspSz); + g_peerRejects = 0; + g_peerRejectCode = 0; + ASSERT_EQ(wolfSPDM_IsConnected(ctx), 0, "DecryptError ends the session"); + TEST_ASSERT(test_session_retired(ctx), "Session keys must be destroyed"); + rspSz = sizeof(rsp); + ASSERT_EQ(wolfSPDM_SecuredExchange(ctx, req, sizeof(req), rsp, &rspSz), + WOLFSPDM_E_NOT_CONNECTED, "No exchange after DecryptError"); + wolfSPDM_Free(&g_peer); + TEST_CTX_FREE(); + +#ifndef WOLFSPDM_NO_APP_DATA + ASSERT_SUCCESS(wolfSPDM_Init(ctx)); + test_session_loopback(ctx); + rspSz = sizeof(rsp); + ASSERT_SUCCESS(test_unsolicited_decrypt_error_io(ctx, NULL, 0, rsp, + &rspSz, NULL)); + ASSERT_SUCCESS(wolfSPDM_DecryptMessage(ctx, rsp, rspSz, data, &dataSz)); + TEST_ASSERT(test_session_retired(ctx), + "DecryptMessage retires the session on authenticated DecryptError"); + wolfSPDM_Free(&g_peer); + TEST_CTX_FREE(); + + ASSERT_SUCCESS(wolfSPDM_Init(ctx)); + test_session_loopback(ctx); + dataSz = sizeof(data); + ASSERT_SUCCESS(wolfSPDM_SetIO(ctx, test_unsolicited_decrypt_error_io, + NULL)); + ASSERT_EQ(wolfSPDM_ReceiveData(ctx, data, &dataSz), WOLFSPDM_E_PEER_ERROR, + "Unsolicited ERROR"); + ASSERT_EQ(wolfSPDM_IsConnected(ctx), 0, + "Unsolicited DecryptError ends the session"); + TEST_ASSERT(test_session_retired(ctx), "Session keys must be destroyed"); + wolfSPDM_Free(&g_peer); + TEST_CTX_FREE(); +#endif + TEST_PASS(); +} + +/* A cleartext ERROR to a secured request is the responder's rejection */ +static int test_secured_clear_error_reply(void) +{ + byte req[8] = { SPDM_VERSION_12, SPDM_VENDOR_DEFINED_REQUEST, 0, 0, + 0, 0, 0, 0 }; + byte rsp[64]; + word32 rspSz = sizeof(rsp); + int rc; + TEST_CTX_SETUP(); + + printf("test_secured_clear_error_reply...\n"); + test_session_loopback(ctx); + g_peerRejects = 1; + g_peerClearReply = 1; + rc = wolfSPDM_SecuredExchange(ctx, req, sizeof(req), rsp, &rspSz); + ASSERT_EQ(rc, WOLFSPDM_E_PEER_ERROR, "Secured exchange rejection"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), SPDM_ERROR_BUSY, + "Secured exchange rejection code"); + + ctx->lastPeerErrorCode = 0; + ctx->state = WOLFSPDM_STATE_KEY_EX; + g_peerRejects = 1; + g_peerClearReply = 1; + rc = wolfSPDM_Finish(ctx); + g_peerRejects = 0; + g_peerClearReply = 0; + ASSERT_EQ(rc, WOLFSPDM_E_PEER_ERROR, "FINISH rejection"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), SPDM_ERROR_BUSY, + "FINISH rejection code"); + + wolfSPDM_Free(&g_peer); + TEST_CTX_FREE(); + TEST_PASS(); +} #endif /* loopback */ #ifndef WOLFSPDM_NO_KEY_UPDATE @@ -5413,6 +7346,7 @@ static void test_session_loopback(WOLFSPDM_CTX* ctx) static int test_key_update_loopback(void) { byte reqKey[WOLFSPDM_AEAD_KEY_SIZE]; + byte reqIv[WOLFSPDM_AEAD_IV_SIZE]; byte rspKey[WOLFSPDM_AEAD_KEY_SIZE]; word64 reqSeq; TEST_CTX_SETUP(); @@ -5424,10 +7358,14 @@ static int test_key_update_loopback(void) #endif XMEMCPY(reqKey, ctx->reqDataKey, sizeof(reqKey)); + XMEMCPY(reqIv, ctx->reqDataIv, sizeof(reqIv)); XMEMCPY(rspKey, ctx->rspDataKey, sizeof(rspKey)); ASSERT_SUCCESS(wolfSPDM_KeyUpdate(ctx, 0)); ASSERT_NE(memcmp(reqKey, ctx->reqDataKey, sizeof(reqKey)), 0, "UpdateKey should rotate the request key"); + ASSERT_NE(XMEMCMP(reqIv, ctx->reqDataIv, sizeof(reqIv)), 0, + "UpdateKey should install the new request IV"); + ASSERT_EQ(ctx->reqSeqNum, 1, "VerifyNewKey consumes the first sequence"); ASSERT_EQ(memcmp(rspKey, ctx->rspDataKey, sizeof(rspKey)), 0, "UpdateKey should keep the response key"); @@ -5448,6 +7386,14 @@ static int test_key_update_loopback(void) ASSERT_EQ(ctx->reqSeqNum, reqSeq + 1, "Sequence must advance"); ASSERT_EQ(wolfSPDM_KeyUpdate(ctx, 0), WOLFSPDM_E_PEER_ERROR, "Rejected UpdateKey should fail"); + ctx->lastPeerErrorCode = 0; + g_peerClearReply = 1; + reqSeq = ctx->reqSeqNum; + ASSERT_EQ(wolfSPDM_KeyUpdate(ctx, 1), WOLFSPDM_E_PEER_ERROR, + "Cleartext rejection of UpdateAllKeys"); + ASSERT_EQ(wolfSPDM_GetLastPeerError(ctx), SPDM_ERROR_BUSY, + "Cleartext KEY_UPDATE rejection code"); + ASSERT_EQ(ctx->reqSeqNum, reqSeq + 1, "Request sequence must advance"); ASSERT_EQ(memcmp(reqKey, ctx->reqDataKey, sizeof(reqKey)), 0, "Rejected update should keep the request key"); ASSERT_EQ(memcmp(rspKey, ctx->rspDataKey, sizeof(rspKey)), 0, @@ -5478,12 +7424,35 @@ static int test_key_update_loopback(void) TEST_CTX_FREE(); TEST_PASS(); } + +/* A failed VerifyNewKey ends the session rather than leaving it half-updated */ +static int test_key_update_verify_failure(void) +{ + int rc; + TEST_CTX_SETUP(); + + printf("test_key_update_verify_failure...\n"); + test_session_loopback(ctx); + g_peerRejectVerify = 1; + rc = wolfSPDM_KeyUpdate(ctx, 0); + g_peerRejectVerify = 0; + ASSERT_EQ(rc, WOLFSPDM_E_PEER_ERROR, "VerifyNewKey rejection"); + ASSERT_EQ(wolfSPDM_IsConnected(ctx), 0, "Unverified key ends the session"); + TEST_ASSERT(test_session_retired(ctx), "Session keys must be destroyed"); + TEST_ASSERT(wolfSPDM_KeyUpdate(ctx, 0) != WOLFSPDM_SUCCESS, + "No fresh update on a session with an unverified key"); + + wolfSPDM_Free(&g_peer); + TEST_CTX_FREE(); + TEST_PASS(); +} #endif #endif /* !WOLFSPDM_NO_KEY_UPDATE */ #ifndef WOLFSPDM_NO_MEAS static int test_measurements_msgs(void) { + static const byte zeroContext[8]; byte req[64]; byte rsp[256]; byte err[] = {0x12, SPDM_ERROR, SPDM_ERROR_BUSY, 0, 0, 0, 0, 0}; @@ -5502,12 +7471,23 @@ static int test_measurements_msgs(void) ASSERT_SUCCESS(wolfSPDM_BuildGetMeasurements(ctx, req, &reqSz, SPDM_MEAS_OPERATION_ALL, 0)); ASSERT_EQ(reqSz, 12, "1.3 unsigned request carries RequesterContext"); + ASSERT_EQ(XMEMCMP(&req[4], zeroContext, sizeof(zeroContext)), 0, + "Unsigned request has no application context"); reqSz = 44; ASSERT_EQ(wolfSPDM_BuildGetMeasurements(ctx, req, &reqSz, SPDM_MEAS_OPERATION_ALL, 1), WOLFSPDM_E_BUFFER_SMALL, "1.3 signed request needs 45 bytes"); + ctx->spdmVersion = SPDM_VERSION_14; + reqSz = sizeof(req); + ASSERT_SUCCESS(wolfSPDM_BuildGetMeasurements(ctx, req, &reqSz, + SPDM_MEAS_OPERATION_ALL, 1)); + ASSERT_EQ(reqSz, 45, "1.4 signed request carries RequesterContext"); + ASSERT_EQ(XMEMCMP(&req[37], zeroContext, sizeof(zeroContext)), 0, + "Signed request has no application context"); + /* 1.3 unsigned response echoing the RequesterContext */ + ctx->spdmVersion = SPDM_VERSION_13; reqSz = sizeof(req); ASSERT_SUCCESS(wolfSPDM_BuildGetMeasurements(ctx, req, &reqSz, SPDM_MEAS_OPERATION_ALL, 0)); @@ -5548,6 +7528,16 @@ static int test_measurements_loopback(void) byte type = 0; byte val[16]; word32 valSz = sizeof(val); +#ifndef WOLFSPDM_NO_APP_DATA + byte vdReq[8] = { SPDM_VERSION_12, SPDM_VENDOR_DEFINED_REQUEST, 0, 0, + 0, 0, 0, 0 }; + byte enc[256]; + byte rx[256]; + byte plain[64]; + word32 encSz; + word32 rxSz; + word32 plainSz; +#endif TEST_CTX_SETUP(); printf("test_measurements_loopback...\n"); @@ -5585,6 +7575,27 @@ static int test_measurements_loopback(void) ASSERT_SUCCESS(wolfSPDM_Heartbeat(ctx)); ASSERT_SUCCESS(wolfSPDM_GetMeasurements(ctx, SPDM_MEAS_OPERATION_ALL, 1)); #endif +#ifndef WOLFSPDM_NO_KEY_UPDATE + /* A rejected KEY_UPDATE still reached the responder */ + ASSERT_SUCCESS(wolfSPDM_GetMeasurements(ctx, SPDM_MEAS_OPERATION_ALL, 0)); + g_peerRejects = 1; + TEST_ASSERT(wolfSPDM_KeyUpdate(ctx, 0) != WOLFSPDM_SUCCESS, + "Rejected KEY_UPDATE"); + g_peerRejects = 0; + ASSERT_SUCCESS(wolfSPDM_GetMeasurements(ctx, SPDM_MEAS_OPERATION_ALL, 1)); +#endif +#ifndef WOLFSPDM_NO_APP_DATA + /* So does a request the caller seals and carries itself */ + ASSERT_SUCCESS(wolfSPDM_GetMeasurements(ctx, SPDM_MEAS_OPERATION_ALL, 0)); + encSz = sizeof(enc); + ASSERT_SUCCESS(wolfSPDM_EncryptMessage(ctx, vdReq, sizeof(vdReq), enc, + &encSz)); + rxSz = sizeof(rx); + ASSERT_SUCCESS(test_peer_io_cb(ctx, enc, encSz, rx, &rxSz, &g_peer)); + plainSz = sizeof(plain); + ASSERT_SUCCESS(wolfSPDM_DecryptMessage(ctx, rx, rxSz, plain, &plainSz)); + ASSERT_SUCCESS(wolfSPDM_GetMeasurements(ctx, SPDM_MEAS_OPERATION_ALL, 1)); +#endif g_peerTamper = 1; ASSERT_EQ(wolfSPDM_GetMeasurements(ctx, SPDM_MEAS_OPERATION_ALL, 1), @@ -5607,6 +7618,7 @@ static int test_measurements_loopback(void) #ifndef WOLFSPDM_NO_CHALLENGE static int test_challenge_msgs(void) { + static const byte zeroContext[8]; byte req[64]; byte rsp[256]; word32 reqSz = sizeof(req); @@ -5630,6 +7642,8 @@ static int test_challenge_msgs(void) reqSz = sizeof(req); ASSERT_SUCCESS(wolfSPDM_BuildChallenge(ctx, req, &reqSz, 0, SPDM_MEAS_SUMMARY_HASH_TCB)); + ASSERT_EQ(XMEMCMP(&req[36], zeroContext, sizeof(zeroContext)), 0, + "Challenge has no application context"); XMEMSET(ctx->certChainHash, 0xC7, WOLFSPDM_HASH_SIZE); n = test_chal_rsp(ctx, req, reqSz, rsp); XMEMSET(rsp + n, 0, WOLFSPDM_ECC_SIG_SIZE); @@ -5677,7 +7691,14 @@ static int test_challenge_loopback(void) WOLFSPDM_E_BAD_STATE, "M1 starts at NEGOTIATE_ALGORITHMS"); ASSERT_SUCCESS(wolfSPDM_M1Start(ctx)); + ctx->rspCaps &= ~(word32)(SPDM_CAP_MEAS_CAP_NO_SIG | + SPDM_CAP_MEAS_CAP_SIG); + ASSERT_EQ(wolfSPDM_Challenge(ctx, 0, SPDM_MEAS_SUMMARY_HASH_ALL), + WOLFSPDM_E_CAPS_MISMATCH, "Summary requires measurement capability"); ASSERT_SUCCESS(wolfSPDM_Challenge(ctx, 0, SPDM_MEAS_SUMMARY_HASH_NONE)); + ctx->rspCaps |= SPDM_CAP_MEAS_CAP_NO_SIG; + ASSERT_EQ(wolfSPDM_Challenge(ctx, 0, 0x02), WOLFSPDM_E_INVALID_ARG, + "Reserved measurement summary type"); ASSERT_SUCCESS(wolfSPDM_Challenge(ctx, 0, SPDM_MEAS_SUMMARY_HASH_ALL)); ASSERT_EQ(wolfSPDM_Challenge(ctx, 1, SPDM_MEAS_SUMMARY_HASH_NONE), WOLFSPDM_E_BAD_STATE, "No chain held for slot 1"); @@ -5834,6 +7855,10 @@ static int test_chunk_transfers(void) int main(void) { +#if !defined(WOLFSPDM_NO_CERT) && !defined(NO_ASN_TIME) && \ + !defined(NO_ASN_TIME_CHECK) + ASSERT_SUCCESS(wc_SetTimeCb(test_certificate_clock)); +#endif printf("===========================================\n"); printf("wolfSPDM Unit Tests\n"); printf("===========================================\n\n"); @@ -5864,6 +7889,7 @@ int main(void) /* Error tests */ test_check_error(); + test_response_version_matches(); test_error_strings(); /* Multi-version tests */ @@ -5881,10 +7907,15 @@ int main(void) test_invalid_curve_point(); test_extract_ecc_point(); #ifdef WOLFSPDM_TCG + test_tcg_fips_indicator_tracks_response(); test_tcg_get_pub_key_preserves_pin(); test_tcg_get_pub_key_discovery_is_not_trusted(); test_tcg_get_pub_key_negotiates_version(); test_tcg_get_pub_key_version_failure(); + test_tcg_vca_reports_peer_error(); + test_tcg_secured_vendor_reports_peer_error(); + test_tcg_clear_vendor_ack(); + test_tcg_secured_vendor_ack(); test_tcg_connect_requires_responder_key(); test_tcg_underflow(); #endif @@ -5914,8 +7945,14 @@ int main(void) #endif test_connect_null_args(); test_get_version_no_io(); +#ifndef WOLFSPDM_NO_MCTP + test_get_version_restarts_connection(); + test_get_version_accepts_minimum_transfer(); +#endif test_key_exchange_no_io(); + test_key_exchange_preserves_transcript_on_io_failure(); test_finish_no_io(); + test_finish_preserves_transcript_on_io_failure(); test_secured_exchange_null_args(); test_disconnect_states(); @@ -5937,6 +7974,7 @@ int main(void) #endif #ifdef WOLFSPDM_NATIONS test_nations_get_status_null_args(); + test_nations_get_status_pending_disable(); test_nations_set_only_mode_null_args(); test_nations_psk_set_null_args(); test_nations_psk_clear_null_args(); @@ -5948,6 +7986,7 @@ int main(void) test_build_psk_finish_null_args(); test_build_psk_finish_format(); test_parse_psk_finish_rsp(); + test_psk_finish_v14_opaque(); test_connect_psk_null_args(); #endif @@ -5971,6 +8010,9 @@ int main(void) test_build_key_exchange_null_args(); #ifndef WOLFSPDM_NO_MCTP test_build_key_exchange_format(); +#ifndef WOLFSPDM_NO_CERT + test_build_key_exchange_pinned_slot(); +#endif #endif test_build_key_exchange_mode_opaque(); test_build_finish_null_args(); @@ -5993,7 +8035,16 @@ int main(void) test_parse_certificate(); test_mutual_auth_rejected_in_standard_mode(); test_validate_cert_chain(); +#if !defined(NO_ASN_TIME) && !defined(NO_ASN_TIME_CHECK) + test_certificate_validity(); +#endif test_get_certificate_portions(); +#ifdef WOLFSPDM_TCG + test_tcg_requires_explicit_responder_pin(); +#endif +#ifndef WOLFSPDM_NO_MCTP + test_standard_connect_releases_session(); +#endif test_clear_exchange_dts(); #endif #if defined(WOLFSPDM_HAVE_MLDSA) || defined(WOLFSPDM_HAVE_MLKEM) @@ -6025,17 +8076,30 @@ int main(void) #ifdef WOLFSPDM_TCG test_encrypt_decrypt_roundtrip_tcg(); #endif +#if WOLFSPDM_XFER_MSG_SIZE + 3 + WOLFSPDM_AEAD_TAG_SIZE > 0xFFFF + test_secured_record_length_limit(); +#endif #ifndef WOLFSPDM_NO_APP_DATA test_app_data(); + test_app_data_secured_type(); #endif #ifndef WOLFSPDM_NO_HEARTBEAT test_heartbeat_msgs(); #endif +#if (!defined(WOLFSPDM_NO_KEY_UPDATE) || !defined(WOLFSPDM_NO_MEAS) || \ + !defined(WOLFSPDM_NO_CHALLENGE) || !defined(WOLFSPDM_NO_CHUNK)) && \ + !defined(WOLFSPDM_NO_MCTP) + test_disconnect_reports_peer_error(); + test_disconnect_ignores_reserved_parameters(); + test_peer_decrypt_error_ends_session(); + test_secured_clear_error_reply(); +#endif #ifndef WOLFSPDM_NO_KEY_UPDATE test_key_update_msgs(); test_derive_updated_keys(); #ifndef WOLFSPDM_NO_MCTP test_key_update_loopback(); + test_key_update_verify_failure(); #endif #endif #ifndef WOLFSPDM_NO_MEAS @@ -6057,15 +8121,25 @@ int main(void) #ifdef WOLFSPDM_TCG test_responder_no_clear_tpm2_cmd(); test_responder_secured_requires_session(); + test_responder_get_version_reserved(); + test_responder_reset_clears_version(); #ifdef WOLFSPDM_NATIONS + test_responder_pre_negotiation_status_version(); test_responder_psk_replace_guard(); test_responder_configured_psk(); #endif - test_responder_identity_roundtrip(); + test_responder_identity_roundtrip(0); + test_responder_identity_roundtrip(1); + test_responder_key_exchange_envelope(); + test_responder_failed_handshake_cleanup(); test_tcg_mode_connect_roundtrip(); #endif #if defined(WOLFSPDM_PSK) && defined(WOLFSPDM_TCG) +#ifdef WOLFSPDM_NATIONS + test_responder_psk_clear_retires_session(); +#endif test_responder_psk_roundtrip(); + test_psk_exchange_without_responder_context(); #endif #endif diff --git a/wolfspdm/spdm.h b/wolfspdm/spdm.h index 58a8c01..4ae69da 100644 --- a/wolfspdm/spdm.h +++ b/wolfspdm/spdm.h @@ -29,8 +29,10 @@ extern "C" { #endif -/* Protocol mode: TCG binding + vendor commands. - * For standard SPDM (emulator, measurements, challenge), see wolfSPDM standalone. */ +/* Protocol modes depend on the enabled build features. + * AUTO selects the standard DMTF certificate requester over MCTP. + * TCG selects the TPM binding. NUVOTON and NATIONS select vendor profiles. + * PSK selects the pre-shared key handshake when PSK support is enabled. */ typedef enum { WOLFSPDM_MODE_AUTO = 0, WOLFSPDM_MODE_NUVOTON = 1, @@ -160,11 +162,13 @@ WOLFSPDM_API int wolfSPDM_IsConnected(WOLFSPDM_CTX* ctx); WOLFSPDM_API int wolfSPDM_Disconnect(WOLFSPDM_CTX* ctx); /* Individual handshake steps (for fine-grained control) */ +/* Start a fresh negotiation and retire any previous session. */ WOLFSPDM_API int wolfSPDM_GetVersion(WOLFSPDM_CTX* ctx); #ifndef WOLFSPDM_NO_CERT WOLFSPDM_API int wolfSPDM_GetCapabilities(WOLFSPDM_CTX* ctx); WOLFSPDM_API int wolfSPDM_NegotiateAlgorithms(WOLFSPDM_CTX* ctx); WOLFSPDM_API int wolfSPDM_GetDigests(WOLFSPDM_CTX* ctx); +/* Fetch the certificate chain before starting a session. */ WOLFSPDM_API int wolfSPDM_GetCertificate(WOLFSPDM_CTX* ctx, int slotId); /* Verify the fetched chain against the trust anchor and install its leaf as * the responder key; call between GetCertificate and KeyExchange */ @@ -236,6 +240,7 @@ WOLFSPDM_API byte wolfSPDM_GetVersion_Negotiated(WOLFSPDM_CTX* ctx); WOLFSPDM_API byte wolfSPDM_GetLastPeerError(WOLFSPDM_CTX* ctx); #ifdef WOLFSPDM_TCG WOLFSPDM_API word32 wolfSPDM_GetConnectionHandle(WOLFSPDM_CTX* ctx); +/* From the last response's TCG header, which no SPDM key authenticates */ WOLFSPDM_API word16 wolfSPDM_GetFipsIndicator(WOLFSPDM_CTX* ctx); #endif diff --git a/wolfspdm/spdm_psk.h b/wolfspdm/spdm_psk.h index 29f10a5..6c07f25 100644 --- a/wolfspdm/spdm_psk.h +++ b/wolfspdm/spdm_psk.h @@ -71,8 +71,8 @@ WOLFSPDM_API int wolfSPDM_DeriveHandshakeKeysPsk(WOLFSPDM_CTX* ctx, /** * Perform PSK SPDM connection. - * GET_VERSION -> GET_CAPABILITIES -> NEGOTIATE_ALGORITHMS -> - * PSK_EXCHANGE -> PSK_FINISH -> app key derivation. + * GET_VERSION -> PSK_EXCHANGE -> PSK_FINISH -> application key derivation. + * This PSK flow skips GET_CAPABILITIES and NEGOTIATE_ALGORITHMS. * * @param ctx wolfSPDM context (must have PSK set via wolfSPDM_SetPSK) * @return WOLFSPDM_SUCCESS or negative error code diff --git a/wolfspdm/spdm_types.h b/wolfspdm/spdm_types.h index c4b7eaf..623102c 100644 --- a/wolfspdm/spdm_types.h +++ b/wolfspdm/spdm_types.h @@ -98,6 +98,7 @@ extern "C" { #define SPDM_KEY_EXCHANGE_RSP 0x64 #define SPDM_FINISH_RSP 0x65 #define SPDM_END_SESSION_ACK 0x6C +#define SPDM_VENDOR_DEFINED_RESPONSE 0x7E #define SPDM_ERROR 0x7F /* SPDM Error Codes (in Param1 of ERROR response) */ @@ -248,6 +249,9 @@ extern "C" { #define WOLFSPDM_MAX_SIG_SIZE WOLFSPDM_ECC_SIG_SIZE #define WOLFSPDM_RSP_PUBKEY_SZ (WOLFSPDM_PUBKEY_BUF_SZ / 2) #endif +#if WOLFSPDM_RSP_PUBKEY_SZ < WOLFSPDM_ECC_POINT_SIZE + #error "WOLFSPDM_RSP_PUBKEY_SZ must hold a raw P-384 public key" +#endif #ifdef WOLFSPDM_HAVE_MLKEM /* ExchangeData: the ML-KEM-1024 encapsulation key and ciphertext are largest */ #define WOLFSPDM_MAX_KEX_DATA 1568 @@ -352,11 +356,11 @@ extern "C" { #define SPDM_KEM_ALGO_ML_KEM_768 0x0002 #define SPDM_KEM_ALGO_ML_KEM_1024 0x0004 -/* NEGOTIATE_ALGORITHMS: 32-byte header and up to five AlgStructs */ +/* NEGOTIATE_ALGORITHMS: 32-byte header and up to four AlgStructs */ #ifdef WOLFSPDM_HAVE_MLKEM -#define WOLFSPDM_NEG_ALGO_SZ 52 -#else #define WOLFSPDM_NEG_ALGO_SZ 48 +#else +#define WOLFSPDM_NEG_ALGO_SZ 44 #endif /* SPDM cert chain header: Length(2) + Reserved(2) + RootHash(48) */