From fe8319e32f74c1a9464360d797d6bd460911cb12 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 15:15:29 +0000 Subject: [PATCH 01/23] F-1970: Treat a zero-length SE050 hash update as a no-op se050_hash_update() returned BAD_FUNC_ARG for any update with len == 0, so a valid zero-length update such as wc_ShaUpdate(sha, buf, 0), or wc_Sha256Update() / wc_Sha384Update() / wc_Sha512Update() with a non-NULL buffer and len 0, failed on SE050 builds while the software hashes accept it as a no-op. Return 0 for len == 0 after the context and data pointer checks. wc_ShaUpdate() in the SE050 arm also passed &sha->se050Ctx straight through without checking sha, so add the NULL check the other SE050 hash wrappers already have. --- wolfcrypt/src/port/nxp/se050_port.c | 10 ++++++++-- wolfcrypt/src/sha.c | 4 +++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index 6201b3d183f..f747d6eae65 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -1208,8 +1208,14 @@ int se050_hash_update(SE050_HASH_Context* se050Ctx, const byte* data, word32 len byte* tmp = NULL; word32 usedSz = 0; - if (se050Ctx == NULL || (len > 0 && data == NULL) || (len == 0) || - !WC_SAFE_SUM_WORD32(se050Ctx->used, len, usedSz)) { + if (se050Ctx == NULL || (len > 0 && data == NULL)) { + return BAD_FUNC_ARG; + } + /* A zero-length update is a valid no-op, as for the software hashes. */ + if (len == 0) { + return 0; + } + if (!WC_SAFE_SUM_WORD32(se050Ctx->used, len, usedSz)) { return BAD_FUNC_ARG; } diff --git a/wolfcrypt/src/sha.c b/wolfcrypt/src/sha.c index 4f8b0aa2cd4..ef99aeb5bd0 100644 --- a/wolfcrypt/src/sha.c +++ b/wolfcrypt/src/sha.c @@ -411,8 +411,10 @@ int wc_ShaUpdate(wc_Sha* sha, const byte* data, word32 len) { + if (sha == NULL) { + return BAD_FUNC_ARG; + } return se050_hash_update(&sha->se050Ctx, data, len); - } int wc_ShaFinal(wc_Sha* sha, byte* hash) From d5296feb5620b60e96ade2e3fa108c424f81df56 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 15:16:15 +0000 Subject: [PATCH 02/23] F-11174: Validate pointers in the SE050 SHA-256 and SHA-224 wrappers The SE050 arms of wc_Sha256Final(), wc_Sha224Update() and wc_Sha224Final() took &sha->se050Ctx and passed the data/digest pointers to the port without checking them, unlike the software implementations and the other SE050 hash wrappers. A NULL context made the wrapper hand the port a bogus context pointer, and a NULL digest pointer reached sss_digest_finish(). Mirror the software contract: BAD_FUNC_ARG for a NULL context or digest buffer, and for wc_Sha224Update() treat (NULL, 0) as a no-op and reject NULL data with a non-zero length, as wc_Sha256Update() already does. The SE050 SHA-1 wc_ShaFinal() / wc_ShaFinalRaw() wrappers had the same gap and get the same checks. se050_hash_final() itself now rejects a NULL context or digest buffer before it reads the context, so every hash type is covered at the port as well. --- wolfcrypt/src/port/nxp/se050_port.c | 17 +++++++++++++---- wolfcrypt/src/sha.c | 6 ++++++ wolfcrypt/src/sha256.c | 17 +++++++++++++++++ 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index f747d6eae65..5d3f2ee7e0b 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -1254,10 +1254,19 @@ int se050_hash_final(SE050_HASH_Context* se050Ctx, byte* hash, size_t digestLen, int ret; sss_status_t status; sss_digest_t digest_ctx; - const byte* data = se050Ctx->msg; - int size = (se050Ctx->used) / SSS_BLOCK_SIZE; - int leftover = (se050Ctx->used) % SSS_BLOCK_SIZE; - const byte* blocks = data; + const byte* data; + int size; + int leftover; + const byte* blocks; + + if (se050Ctx == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } + + data = se050Ctx->msg; + size = (int)(se050Ctx->used / SSS_BLOCK_SIZE); + leftover = (int)(se050Ctx->used % SSS_BLOCK_SIZE); + blocks = data; if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; diff --git a/wolfcrypt/src/sha.c b/wolfcrypt/src/sha.c index ef99aeb5bd0..5874184c945 100644 --- a/wolfcrypt/src/sha.c +++ b/wolfcrypt/src/sha.c @@ -420,6 +420,9 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) { int ret = 0; + if (sha == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } ret = se050_hash_final(&sha->se050Ctx, hash, WC_SHA_DIGEST_SIZE, kAlgorithm_SSS_SHA1); return ret; @@ -427,6 +430,9 @@ int wc_ShaFinalRaw(wc_Sha* sha, byte* hash) { int ret = 0; + if (sha == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } ret = se050_hash_final(&sha->se050Ctx, hash, WC_SHA_DIGEST_SIZE, kAlgorithm_SSS_SHA1); return ret; diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 3811aa4b45d..11b27ae35c5 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -1168,6 +1168,9 @@ wc_static_assert(sizeof(Sha256TScratch) == WC_SHA256_TSCRATCH_SIZE); int wc_Sha256Final(wc_Sha256* sha256, byte* hash) { int ret = 0; + if (sha256 == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } ret = se050_hash_final(&sha256->se050Ctx, hash, WC_SHA256_DIGEST_SIZE, kAlgorithm_SSS_SHA256); return ret; @@ -2885,12 +2888,26 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, int wc_Sha224Update(wc_Sha224* sha224, const byte* data, word32 len) { + if (sha224 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { + return BAD_FUNC_ARG; + } + return se050_hash_update(&sha224->se050Ctx, data, len); } int wc_Sha224Final(wc_Sha224* sha224, byte* hash) { int ret = 0; + if (sha224 == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } ret = se050_hash_final(&sha224->se050Ctx, hash, WC_SHA224_DIGEST_SIZE, kAlgorithm_SSS_SHA224); (void)wc_InitSha224(sha224); From b5b946de948c35e72e487eed8e74c94a3396c008 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 15:16:44 +0000 Subject: [PATCH 03/23] F-11175: Validate pointers in the SE050 SHA-512 and SHA-384 final/free The SE050 arms of wc_Sha512Final(), wc_Sha512FinalRaw() and wc_Sha384Final() passed the digest pointer to the port unchecked (wc_Sha384Final() did not check the context either), and the SE050 wc_Sha512Free() dereferenced its argument, so wc_Sha512Free(NULL) crashed where the software version is a no-op. Return BAD_FUNC_ARG for a NULL context or digest buffer in the final functions and make wc_Sha512Free(NULL) and se050_hash_free(NULL) safe. The two SHA-512 final wrappers also assigned a devId from the context that they never used, which trips -Wunused-but-set-variable in WOLF_CRYPTO_CB builds; drop it. --- wolfcrypt/src/port/nxp/se050_port.c | 3 +++ wolfcrypt/src/sha512.c | 18 ++++++++---------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index 5d3f2ee7e0b..9dabd5fcc29 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -1311,6 +1311,9 @@ int se050_hash_final(SE050_HASH_Context* se050Ctx, byte* hash, size_t digestLen, void se050_hash_free(SE050_HASH_Context* se050Ctx) { + if (se050Ctx == NULL) { + return; + } XFREE(se050Ctx->msg, se050Ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); se050Ctx->msg = NULL; se050Ctx->len = 0; diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index c66309eb8ce..12e76690dfd 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -339,13 +339,9 @@ wc_static_assert(sizeof(Sha512TScratch) == WC_SHA512_TSCRATCH_SIZE); int wc_Sha512Final(wc_Sha512* sha512, byte* hash) { int ret = 0; - int devId = INVALID_DEVID; - if (sha512 == NULL) { + if (sha512 == NULL || hash == NULL) { return BAD_FUNC_ARG; } - #ifdef WOLF_CRYPTO_CB - devId = sha512->devId; - #endif ret = se050_hash_final(&sha512->se050Ctx, hash, WC_SHA512_DIGEST_SIZE, kAlgorithm_SSS_SHA512); return ret; @@ -353,19 +349,18 @@ wc_static_assert(sizeof(Sha512TScratch) == WC_SHA512_TSCRATCH_SIZE); int wc_Sha512FinalRaw(wc_Sha512* sha512, byte* hash) { int ret = 0; - int devId = INVALID_DEVID; - if (sha512 == NULL) { + if (sha512 == NULL || hash == NULL) { return BAD_FUNC_ARG; } - #ifdef WOLF_CRYPTO_CB - devId = sha512->devId; - #endif ret = se050_hash_final(&sha512->se050Ctx, hash, WC_SHA512_DIGEST_SIZE, kAlgorithm_SSS_SHA512); return ret; } void wc_Sha512Free(wc_Sha512* sha512) { + if (sha512 == NULL) { + return; + } se050_hash_free(&sha512->se050Ctx); } #elif defined(STM32_HASH_SHA512) @@ -3008,6 +3003,9 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) int wc_Sha384Final(wc_Sha384* sha384, byte* hash) { int ret = 0; + if (sha384 == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } ret = se050_hash_final(&sha384->se050Ctx, hash, WC_SHA384_DIGEST_SIZE, kAlgorithm_SSS_SHA384); return ret; From d08940985d7123999be36cf5b631b028899dd114 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 15:54:28 +0000 Subject: [PATCH 04/23] Deep-copy the SE050 hash buffer in the SHA-2 Copy functions With WOLFSSL_SE050_HASH the SE050 hash backend keeps the whole message in se050Ctx.msg until final. wc_ShaCopy() gives the copy its own buffer through se050_hash_copy(), but wc_Sha224Copy(), wc_Sha256Copy(), wc_Sha384Copy() and wc_Sha512Copy() only copied the struct, so source and copy shared one buffer. wc_Sha256GetHash() and friends are a Copy followed by Final on the copy, and Final frees the buffer: the original was left pointing at freed memory, and its own Final or Free then read it and freed it a second time. TLS transcript hashing (GetHash, then more updates) and the wolfCrypt SHA-2 GetHash tests take this path. Call se050_hash_copy() in the four Copy functions as wc_ShaCopy() already does. se050_hash_copy() also now leaves the destination empty if it cannot allocate the buffer, instead of keeping a length for a buffer it does not have, and reports that through WOLFSSL_MSG() rather than PRINTF(), which nothing in wolfSSL defines: a WOLFSSL_SE050_HASH build only linked where the platform SDK happened to provide one, and fails with an undefined reference to PRINTF on Linux. --- wolfcrypt/src/port/nxp/se050_port.c | 5 ++++- wolfcrypt/src/sha256.c | 18 ++++++++++++++++++ wolfcrypt/src/sha512.c | 18 ++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index 9dabd5fcc29..dd2b4e1db1c 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -1187,7 +1187,10 @@ int se050_hash_copy(SE050_HASH_Context* src, SE050_HASH_Context* dst) dst->msg = (byte*)XMALLOC(src->used, dst->heap, DYNAMIC_TYPE_TMP_BUFFER); if (dst->msg == NULL) { - PRINTF("Tried to allocate %d bytes\n", dst->used); + WOLFSSL_MSG("se050_hash_copy: buffer allocation failed"); + /* Leave dst empty rather than describing a buffer it lacks. */ + dst->len = 0; + dst->used = 0; return MEMORY_E; } XMEMSET(dst->msg, 0, dst->used); diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 11b27ae35c5..8a390d052ef 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -3668,6 +3668,15 @@ int wc_Sha224Reset(wc_Sha224* sha224) { * buffer, W cache, hardware contexts). XMEMCPY overwrites dst. */ wc_Sha224Free(dst); XMEMCPY(dst, src, sizeof(wc_Sha224)); + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE050 hash buffers the whole message: give the copy a buffer of + * its own instead of sharing the source's, which the first Final or Free + * of either object would release under the other. */ + ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); + if (ret != 0) { + return ret; + } + #endif #ifdef WOLFSSL_SMALL_STACK_CACHE dst->W = (word32*)XMALLOC(WC_SHA256_TSCRATCH_SIZE, @@ -3832,6 +3841,15 @@ int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) * buffer, W cache, hardware contexts). XMEMCPY overwrites dst. */ wc_Sha256Free(dst); XMEMCPY(dst, src, sizeof(wc_Sha256)); +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE050 hash buffers the whole message: give the copy a buffer of + * its own instead of sharing the source's, which the first Final or Free + * of either object would release under the other. */ + ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); + if (ret != 0) { + return ret; + } +#endif #ifdef WOLFSSL_MAXQ10XX_CRYPTO wc_MAXQ10XX_Sha256Copy(src); diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index 12e76690dfd..a6148a0ad5a 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -3493,6 +3493,15 @@ int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst) * buffer, W cache, hardware contexts). XMEMCPY overwrites dst. */ wc_Sha512Free(dst); XMEMCPY(dst, src, sizeof(wc_Sha512)); +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE050 hash buffers the whole message: give the copy a buffer of + * its own instead of sharing the source's, which the first Final or Free + * of either object would release under the other. */ + ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); + if (ret != 0) { + return ret; + } +#endif #ifdef WOLFSSL_SMALL_STACK_CACHE /* This allocation combines the customary W buffer used by * _Transform_Sha512() with additional buffer space used by @@ -3947,6 +3956,15 @@ int wc_Sha384Copy(wc_Sha384* src, wc_Sha384* dst) * buffer, W cache, hardware contexts). XMEMCPY overwrites dst. */ wc_Sha384Free(dst); XMEMCPY(dst, src, sizeof(wc_Sha384)); +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE050 hash buffers the whole message: give the copy a buffer of + * its own instead of sharing the source's, which the first Final or Free + * of either object would release under the other. */ + ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); + if (ret != 0) { + return ret; + } +#endif #ifdef WOLFSSL_SMALL_STACK_CACHE /* This allocation combines the customary W buffer used by From beed8a7c27dbbb1a203d2e202d43e6b9b8ac529e Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 15:17:10 +0000 Subject: [PATCH 05/23] F-12323: Wipe the SE050 hash input buffer before freeing it The SE050 hash backend buffers the whole message in se050Ctx->msg and only sends it to the secure element at final. The buffer was released without clearing it when it grew, after a successful final and in se050_hash_free(). HMAC runs its key-derived ipad/opad blocks through this backend, so key material was left behind in freed heap memory. ForceZero() the whole allocation before every free: when the buffer is grown, in se050_hash_free(), and at final, which now resets through se050_hash_free(). The SE050 wc_Sha224Final() also re-initialized the context after se050_hash_final(), which on a failed final dropped the buffered message without wiping or freeing it. se050_hash_final() already resets the context on success, so remove the re-init and leave a failed final's buffer for wc_Sha224Free(), as the other SE050 hashes do. --- wolfcrypt/src/port/nxp/se050_port.c | 11 +++++++++-- wolfcrypt/src/sha256.c | 4 +++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index dd2b4e1db1c..713a0adb50a 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -1239,6 +1239,9 @@ int se050_hash_update(SE050_HASH_Context* se050Ctx, const byte* data, word32 len } XMEMSET(tmp, 0, usedSz); XMEMCPY(tmp, se050Ctx->msg, se050Ctx->used); + /* The buffered input may be secret (HMAC feeds key-derived pad + * blocks through here), so wipe it before releasing it. */ + ForceZero(se050Ctx->msg, se050Ctx->len); XFREE(se050Ctx->msg, se050Ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); se050Ctx->msg = tmp; } @@ -1301,7 +1304,7 @@ int se050_hash_final(SE050_HASH_Context* se050Ctx, byte* hash, size_t digestLen, if (status == kStatus_SSS_Success) { /* reset state */ - XFREE(se050Ctx->msg, se050Ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + se050_hash_free(se050Ctx); ret = se050_hash_init(se050Ctx, se050Ctx->heap); } else { ret = WC_HW_E; @@ -1317,7 +1320,11 @@ void se050_hash_free(SE050_HASH_Context* se050Ctx) if (se050Ctx == NULL) { return; } - XFREE(se050Ctx->msg, se050Ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (se050Ctx->msg != NULL) { + /* May hold secret input such as HMAC key-derived pad blocks. */ + ForceZero(se050Ctx->msg, se050Ctx->len); + XFREE(se050Ctx->msg, se050Ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + } se050Ctx->msg = NULL; se050Ctx->len = 0; se050Ctx->used = 0; diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 8a390d052ef..4bc86e3ed38 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -2908,9 +2908,11 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, if (sha224 == NULL || hash == NULL) { return BAD_FUNC_ARG; } + /* se050_hash_final() resets the context on success. On failure the + * buffered message stays for wc_Sha224Free() to wipe and release; + * re-initializing here would drop it without either. */ ret = se050_hash_final(&sha224->se050Ctx, hash, WC_SHA224_DIGEST_SIZE, kAlgorithm_SSS_SHA224); - (void)wc_InitSha224(sha224); return ret; } From 7f85617df2a40e3e0bebb6a68898e499c80d7103 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 15:18:23 +0000 Subject: [PATCH 06/23] F-11245: Release the SE050 AES key object when storing the key fails se050_aes_set_key() only set keyCreated once both the object handle allocation and sss_key_store_set_key() had succeeded, so the failure branch, which is the only place that reads it, never erased or freed anything. A key store failure after the handle was allocated (for example an APDU error while writing the key) left the object behind on the SE050 and its key ID unused. Set keyCreated as soon as the handle is allocated so the existing erase/free cleanup runs for every later failure. --- wolfcrypt/src/port/nxp/se050_port.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index 713a0adb50a..a114d8ee6fd 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -1380,6 +1380,10 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, status = sss_key_object_allocate_handle(&newKey, keyId, kSSS_KeyPart_Default, kSSS_CipherType_AES, keylen, kKeyObject_Mode_Transient); + if (status == kStatus_SSS_Success) { + /* From here on the object must be released on any failure. */ + keyCreated = 1; + } } if (status == kStatus_SSS_Success) { status = sss_key_store_set_key(&host_keystore, &newKey, key, keylen, @@ -1387,7 +1391,6 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, } if (status == kStatus_SSS_Success) { - keyCreated = 1; aes->keyId = keyId; aes->keyIdSet = 1; ret = 0; From ec8c1ffb27e704d3095d35d87e76a4e8a07aeb5b Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 15:18:49 +0000 Subject: [PATCH 07/23] F-12324: Erase the SE050 AES key object in se050_aes_free() se050_aes_set_key() creates a transient key object on the SE050 for every key it is given, but se050_aes_free() only released the cipher context and then cleared aes->keyId / keyIdSet without erasing the object. Every wc_AesSetKey() / wc_AesFree() cycle therefore left an object allocated on the secure element, and the IDs are never reused, so a long-running application keeps consuming object slots until the SE050 is reset or runs out. Erase the key object when the Aes is freed, under the SE050 lock. The lock now also covers sss_symmetric_context_free(), which sends APDUs to delete the crypto object and was previously called without it. A failed erase (or lock) is logged; wc_AesFree() wipes the Aes straight afterwards, so there is nothing left to retry from. With no SE050 session open there is nothing to talk to and the host state is just cleared as before. --- wolfcrypt/src/port/nxp/se050_port.c | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index a114d8ee6fd..e0827d4a45f 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -1477,6 +1477,22 @@ void se050_aes_free(Aes* aes) return; } + if (cfg_se050_i2c_pi == NULL) { + /* No session to release the SE050 objects through. */ + aes->ctxInitDone = 0; + aes->keyId = 0; + aes->keyIdSet = 0; + return; + } + + /* Freeing the cipher context and erasing the key both talk to the + * SE050. Without the lock neither can be done safely; wc_AesFree() wipes + * the Aes next either way. */ + if (wc_se050_lock() != 0) { + WOLFSSL_MSG("SE050 lock failed, AES key object not erased"); + return; + } + if (aes->ctxInitDone) { sss_symmetric_context_free(&aes->aes_ctx); @@ -1484,8 +1500,17 @@ void se050_aes_free(Aes* aes) aes->ctxInitDone = 0; } - aes->keyId = 0; - aes->keyIdSet = 0; + /* Erase the transient key object se050_aes_set_key() created, otherwise + * every set key / free cycle leaves an object behind on the SE050. */ + if (aes->keyIdSet != 0U) { + if (se050_erase_object_locked(aes->keyId) != 0) { + WOLFSSL_MSG("Failed to erase SE050 AES key object"); + } + aes->keyId = 0; + aes->keyIdSet = 0; + } + + wc_se050_unlock(); } #endif /* WOLFSSL_SE050_CRYPT && !NO_AES */ From 860e14efef78c43f1bc7509f1b34eb33b28228cb Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 15:22:29 +0000 Subject: [PATCH 08/23] F-15216: Stop the SE050 replacing the requested RSA-OAEP parameters The SE050 RSA encrypt/decrypt path mapped every WC_RSA_OAEP_PAD request to kAlgorithm_SSS_RSAES_PKCS1_OAEP_SHA1 and ignored the hash, MGF and label. The SE05x applet only implements OAEP with SHA-1, MGF1-SHA1 and an empty label, so a caller asking for, say, OAEP-SHA256 or a non-empty label got a successful operation with different parameters: ciphertext that a standards-conforming peer cannot decrypt, and a decrypt that accepted ciphertext made with the empty label whatever label was passed (RFC 8017 7.1.1 / 7.1.2). The SE050 still serves OAEP natively when the request is exactly SHA-1 / MGF1-SHA1 / no label. For any other OAEP parameters rsa.c now does the OAEP encoding or decoding on the host with wc_RsaPad_ex() / wc_RsaUnPad_ex() and has the SE050 perform only the raw RSA operation (WC_RSA_NO_PAD) with the key it holds, so the requested hash, MGF and label are honored and SE050-resident keys keep working. In the port, se050_get_rsa_encrypt_type() now only maps OAEP for SHA-1 with MGF1-SHA1, and se050_rsa_public_encrypt() / se050_rsa_private_decrypt() refuse an OAEP label, so a build without the software padding layer (WOLFSSL_NO_RSA_SW without RSA-PSS) returns BAD_FUNC_ARG instead of substituting parameters. The OAEP padding test no longer skips its label and hash mismatch checks on SE050 builds, and a hardware-only build without the padding layer checks that the unsupported parameters are refused. --- wolfcrypt/src/port/nxp/se050_port.c | 43 ++++++---- wolfcrypt/src/rsa.c | 127 ++++++++++++++++++++++++++++ wolfcrypt/test/test.c | 41 +++++++-- 3 files changed, 187 insertions(+), 24 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index e0827d4a45f..b421adfbb84 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -3094,19 +3094,22 @@ static sss_algorithm_t se050_get_rsa_signature_type(int padType, } static sss_algorithm_t se050_get_rsa_encrypt_type(int padType, - enum wc_HashType hash) + enum wc_HashType hash, int mgf) { sss_algorithm_t alg = kAlgorithm_None; - (void)hash; switch (padType) { case WC_RSA_PKCSV15_PAD: alg = kAlgorithm_SSS_RSAES_PKCS1_V1_5; break; case WC_RSA_OAEP_PAD: - /* lower level Se05x API translation maps OAEP-SHA1 alg type to - * kSE05x_RSAEncryptionAlgo_PKCS1_OAEP (generic) */ - alg = kAlgorithm_SSS_RSAES_PKCS1_OAEP_SHA1; + /* The SE05x applet implements OAEP with SHA-1 and MGF1-SHA1 + * only (the SDK maps the other OAEP algorithms to "not + * available"). Refuse anything else rather than silently + * encrypting or decrypting with different parameters. */ + if ((hash == WC_HASH_TYPE_SHA) && (mgf == WC_MGF1SHA1)) { + alg = kAlgorithm_SSS_RSAES_PKCS1_OAEP_SHA1; + } break; case WC_RSA_NO_PAD: alg = kAlgorithm_SSS_RSASSA_NO_PADDING; @@ -3587,8 +3590,8 @@ int se050_rsa_verify(const byte* in, word32 inLen, byte* out, word32 outLen, * WC_RSA_NO_PAD, WC_RSA_PSS_PAD * hash type of hash algorithm, found in wolfssl/wolfcrypt/hash.h * mgf type of mask generation function to use - * label optional label, not supported by SE050, must be NULL - * labelSz size of label, not supported by SE050, must be 0 + * label optional label, not supported by SE050 for OAEP + * labelSz size of label, must be 0 for OAEP * keySz size of RSA key, bytes * * Returns size of encrypted data on success, negative on error. @@ -3611,10 +3614,9 @@ int se050_rsa_public_encrypt(const byte* in, word32 inLen, byte* out, byte* derBuf = NULL; int derSz = 0; - /* SE050 does not support optional label */ + /* The SE050 OAEP implementation has no label input: only the empty + * label can be honored. */ (void)label; - (void)labelSz; - (void)mgf; #ifdef SE050_DEBUG printf("se050_rsa_public_encrypt: key %p, in %p (%d), out %p (%d), " @@ -3625,6 +3627,10 @@ int se050_rsa_public_encrypt(const byte* in, word32 inLen, byte* out, rsa_type != RSA_PUBLIC_ENCRYPT || pad_value != RSA_BLOCK_TYPE_2) { return BAD_FUNC_ARG; } + if ((pad_type == WC_RSA_OAEP_PAD) && (labelSz != 0)) { + WOLFSSL_MSG("SE050 RSA-OAEP does not support a label"); + return BAD_FUNC_ARG; + } if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; @@ -3642,7 +3648,7 @@ int se050_rsa_public_encrypt(const byte* in, word32 inLen, byte* out, return BAD_MUTEX_E; } - algorithm = se050_get_rsa_encrypt_type(pad_type, hash); + algorithm = se050_get_rsa_encrypt_type(pad_type, hash, mgf); if (algorithm == kAlgorithm_None) { WOLFSSL_MSG("Unsupported padding/hash/mgf combination for SE050"); wc_se050_unlock(); @@ -3763,8 +3769,8 @@ int se050_rsa_public_encrypt(const byte* in, word32 inLen, byte* out, * WC_RSA_NO_PAD, WC_RSA_PSS_PAD * hash type of hash algorithm, found in wolfssl/wolfcrypt/hash.h * mgf type of mask generation function to use - * label optional label, not supported by SE050, must be NULL - * labelSz size of label, not supported by SE050, must be 0 + * label optional label, not supported by SE050 for OAEP + * labelSz size of label, must be 0 for OAEP * * Returns size of decrypted data on success, negative on error. */ @@ -3788,10 +3794,9 @@ int se050_rsa_private_decrypt(const byte* in, word32 inLen, byte* out, int derSz = 0; int derBufSz = 0; - /* SE050 does not support optional label */ + /* The SE050 OAEP implementation has no label input: only the empty + * label can be honored. */ (void)label; - (void)labelSz; - (void)mgf; #ifdef SE050_DEBUG printf("se050_rsa_public_decrypt: key %p, in %p (%d), out %p (%d), " @@ -3802,6 +3807,10 @@ int se050_rsa_private_decrypt(const byte* in, word32 inLen, byte* out, rsa_type != RSA_PRIVATE_DECRYPT || pad_value != RSA_BLOCK_TYPE_2) { return BAD_FUNC_ARG; } + if ((pad_type == WC_RSA_OAEP_PAD) && (labelSz != 0)) { + WOLFSSL_MSG("SE050 RSA-OAEP does not support a label"); + return BAD_FUNC_ARG; + } if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; @@ -3819,7 +3828,7 @@ int se050_rsa_private_decrypt(const byte* in, word32 inLen, byte* out, return BAD_MUTEX_E; } - algorithm = se050_get_rsa_encrypt_type(pad_type, hash); + algorithm = se050_get_rsa_encrypt_type(pad_type, hash, mgf); if (algorithm == kAlgorithm_None) { WOLFSSL_MSG("Unsupported padding/hash/mgf combination for SE050"); wc_se050_unlock(); diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index 9456e98efdc..b06bf1b4de4 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -3801,6 +3801,118 @@ static int RsaModulusBits(const RsaKey* key) } #endif +#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA) && \ + !defined(WC_NO_RSA_OAEP) && !defined(WOLFSSL_NO_RSA_SW_PAD) +/* The SE050 implements RSAES-OAEP with SHA-1, MGF1-SHA1 and an empty label + * only. True when the requested OAEP parameters are exactly those. */ +#define SE050_RSA_OAEP_NATIVE(hash, mgf, labelSz) \ + (((hash) == WC_HASH_TYPE_SHA) && ((mgf) == WC_MGF1SHA1) && \ + ((labelSz) == 0)) + +#ifndef WOLFSSL_RSA_VERIFY_ONLY +/* RSAES-OAEP encryption with parameters the SE050 cannot apply itself: encode + * the message here and have the SE050 perform only the raw RSA public key + * operation, so the requested hash, MGF and label are used as asked. */ +static int Se050RsaOaepEncrypt(const byte* in, word32 inLen, byte* out, + word32 outLen, RsaKey* key, int sz, + enum wc_HashType hash, int mgf, byte* label, + word32 labelSz, WC_RNG* rng) +{ + int ret; + + ret = wc_RsaPad_ex(in, inLen, out, (word32)sz, RSA_BLOCK_TYPE_2, rng, + WC_RSA_OAEP_PAD, hash, mgf, label, labelSz, 0, + RsaModulusBits(key), key->heap); + if (ret == 0) { + /* The whole encoded message goes to the SE050 before the ciphertext + * comes back, so out can carry both. */ + ret = se050_rsa_public_encrypt(out, (word32)sz, out, outLen, key, + RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, + WC_RSA_NO_PAD, WC_HASH_TYPE_NONE, + WC_MGF1NONE, NULL, 0, sz); + } + if (ret < 0) { + /* SP 800-56Br2 7.2.2.3: destroy EM on an error exit. */ + ForceZero(out, (word32)sz); + } + + return ret; +} +#endif /* !WOLFSSL_RSA_VERIFY_ONLY */ + +#ifndef WOLFSSL_RSA_PUBLIC_ONLY +/* RSAES-OAEP decryption with parameters the SE050 cannot apply itself: the + * SE050 performs only the raw RSA private key operation and the encoded + * message is checked and decoded here. */ +static int Se050RsaOaepDecrypt(const byte* in, word32 inLen, byte* out, + word32 outLen, byte** outPtr, RsaKey* key, + enum wc_HashType hash, int mgf, byte* label, + word32 labelSz) +{ + int ret; + int sz; + word32 emSz; + byte* em; + byte* msg = NULL; + + sz = wc_RsaEncryptSize(key); + if (sz <= 0) { + return BAD_FUNC_ARG; + } + emSz = (word32)sz; + + em = (byte*)XMALLOC(emSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (em == NULL) { + return MEMORY_E; + } + + ret = se050_rsa_private_decrypt(in, inLen, em, emSz, key, + RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, + WC_RSA_NO_PAD, WC_HASH_TYPE_NONE, + WC_MGF1NONE, NULL, 0); + if (ret > (int)emSz) { + ret = WC_HW_E; + } + else if (ret >= 0) { + /* The SE050 returns a raw RSA result at the full modulus length. If a + * shorter one ever came back, right-align it into the encoded message + * block; its length is already visible in the APDU response. */ + if ((word32)ret < emSz) { + XMEMMOVE(em + (emSz - (word32)ret), em, (size_t)ret); + XMEMSET(em, 0, emSz - (word32)ret); + } + ret = wc_RsaUnPad_ex(em, emSz, &msg, RSA_BLOCK_TYPE_2, + WC_RSA_OAEP_PAD, hash, mgf, label, labelSz, 0, + RsaModulusBits(key), key->heap); + if (ret >= 0) { + /* As on the software path: OAEP decoding reports an invalid + * encoding as a zero-length message, so that is an error unless + * empty messages are allowed, and the message must fit in out. */ + ret = ctMaskSelInt(ctMaskLTE(ret, (int)outLen), ret, + WC_NO_ERR_TRACE(RSA_BUFFER_E)); + #ifndef WOLFSSL_RSA_DECRYPT_TO_0_LEN + ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, + WC_NO_ERR_TRACE(RSA_BUFFER_E)); + #endif + } + } + if (ret >= 0) { + if (ret > 0) { + XMEMCPY(out, msg, (size_t)ret); + } + if (outPtr != NULL) { + *outPtr = out; + } + } + + ForceZero(em, emSz); + XFREE(em, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + + return ret; +} +#endif /* !WOLFSSL_RSA_PUBLIC_ONLY */ +#endif /* WOLFSSL_SE050 && !WC_NO_RSA_OAEP && !WOLFSSL_NO_RSA_SW_PAD */ + #ifndef WOLFSSL_RSA_VERIFY_ONLY /* Internal Wrappers */ /* Gives the option of choosing padding type @@ -3914,6 +4026,13 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, #endif { if (rsa_type == RSA_PUBLIC_ENCRYPT && pad_value == RSA_BLOCK_TYPE_2) { + #if !defined(WC_NO_RSA_OAEP) && !defined(WOLFSSL_NO_RSA_SW_PAD) + if ((pad_type == WC_RSA_OAEP_PAD) && + !SE050_RSA_OAEP_NATIVE(hash, mgf, labelSz)) { + return Se050RsaOaepEncrypt(in, inLen, out, outLen, key, sz, + hash, mgf, label, labelSz, rng); + } + #endif return se050_rsa_public_encrypt(in, inLen, out, outLen, key, rsa_type, pad_value, pad_type, hash, mgf, label, labelSz, sz); @@ -4123,6 +4242,14 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, #endif { if (rsa_type == RSA_PRIVATE_DECRYPT && pad_value == RSA_BLOCK_TYPE_2) { + #if !defined(WC_NO_RSA_OAEP) && !defined(WOLFSSL_NO_RSA_SW_PAD) && \ + !defined(WOLFSSL_RSA_PUBLIC_ONLY) + if ((pad_type == WC_RSA_OAEP_PAD) && + !SE050_RSA_OAEP_NATIVE(hash, mgf, labelSz)) { + return Se050RsaOaepDecrypt(in, inLen, out, outLen, outPtr, + key, hash, mgf, label, labelSz); + } + #endif ret = se050_rsa_private_decrypt(in, inLen, out, outLen, key, rsa_type, pad_value, pad_type, hash, mgf, label, labelSz); diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index e824cfe5d38..ab6e9060ba8 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -43708,6 +43708,25 @@ static wc_test_ret_t rsa_oaep_padding_test(RsaKey* key, WC_RNG* rng) #endif /* NO_SHA */ #endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_NO_RSA_SW) && \ + !defined(WC_RSA_PSS) + /* Hardware only with no software padding layer: the SE050 offers OAEP + * with SHA-1, MGF1-SHA1 and an empty label only, so other parameters + * must be refused rather than replaced. */ + #ifndef NO_SHA256 + ret = wc_RsaPublicEncrypt_ex(in, inLen, out, outSz, key, rng, + WC_RSA_OAEP_PAD, WC_HASH_TYPE_SHA256, WC_MGF1SHA256, NULL, 0); + if (ret != WC_NO_ERR_TRACE(BAD_FUNC_ARG)) + ERROR_OUT(WC_TEST_RET_ENC_EC(ret), exit_rsa); + #endif + #ifndef NO_SHA + ret = wc_RsaPublicEncrypt_ex(in, inLen, out, outSz, key, rng, + WC_RSA_OAEP_PAD, WC_HASH_TYPE_SHA, WC_MGF1SHA1, in, inLen); + if (ret != WC_NO_ERR_TRACE(BAD_FUNC_ARG)) + ERROR_OUT(WC_TEST_RET_ENC_EC(ret), exit_rsa); + #endif + ret = 0; +#else #ifndef NO_SHA256 XMEMSET(plain, 0, plainSz); WC_TEST_RSA_ASYNC_DO(&key->asyncDev, @@ -43756,14 +43775,17 @@ static wc_test_ret_t rsa_oaep_padding_test(RsaKey* key, WC_RNG* rng) TEST_SLEEP(); /* TODO: investigate why Cavium Nitrox doesn't detect decrypt error here */ -#if !defined(HAVE_CAVIUM) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \ - !defined(WOLFSSL_SE050) - /* Label is unused in SE050 so it won't detect decrypt error. */ +#if !defined(HAVE_CAVIUM) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) idx = (word32)ret; WC_TEST_RSA_ASYNC_DO(&key->asyncDev, wc_RsaPrivateDecrypt_ex(out, idx, plain, plainSz, key, WC_RSA_OAEP_PAD, WC_HASH_TYPE_SHA256, WC_MGF1SHA256, in, inLen)); - if (ret > 0) { /* in this case decrypt should fail */ + /* in this case decrypt should fail */ +#ifdef WOLFSSL_RSA_DECRYPT_TO_0_LEN + if (ret > 0) { +#else + if (ret >= 0) { +#endif ERROR_OUT(WC_TEST_RET_ENC_NC, exit_rsa); } ret = 0; @@ -43804,14 +43826,18 @@ static wc_test_ret_t rsa_oaep_padding_test(RsaKey* key, WC_RNG* rng) TEST_SLEEP(); /* TODO: investigate why Cavium Nitrox doesn't detect decrypt error here */ -#if !defined(HAVE_CAVIUM) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \ - !defined(WOLFSSL_SE050) +#if !defined(HAVE_CAVIUM) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) idx = (word32)ret; WC_TEST_RSA_ASYNC_DO(&key->asyncDev, wc_RsaPrivateDecrypt_ex(out, idx, plain, plainSz, key, WC_RSA_OAEP_PAD, WC_HASH_TYPE_SHA256, WC_MGF1SHA256, in, inLen)); - if (ret > 0) { /* should fail */ + /* should fail */ + #ifdef WOLFSSL_RSA_DECRYPT_TO_0_LEN + if (ret > 0) { + #else + if (ret >= 0) { + #endif ERROR_OUT(WC_TEST_RET_ENC_NC, exit_rsa); } ret = 0; @@ -43849,6 +43875,7 @@ static wc_test_ret_t rsa_oaep_padding_test(RsaKey* key, WC_RNG* rng) #endif /* WOLFSSL_RSA_PUBLIC_ONLY */ } #endif /* WOLFSSL_SHA512 */ +#endif /* WOLFSSL_SE050 && WOLFSSL_NO_RSA_SW && !WC_RSA_PSS */ /* check using pkcsv15 padding with _ex API */ XMEMSET(plain, 0, plainSz); From 68daf949c575cdf4e89c9bef21f406b67cf818d3 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 15:26:30 +0000 Subject: [PATCH 09/23] F-9983: Make the EdDSA sign-time key check work and enable it for faultharden WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN snapshots the private scalar before an Ed25519/Ed448 signature and compares it afterwards (CVE-2024-2881 mitigation), but nothing turned it on: not --enable-faultharden, not the CMake WOLFSSL_FAULTHARDEN option. It also did not work when defined by hand: the mismatch result was computed as ret = ctMaskGT(c, 0) & SIG_VERIFY_E; and ctMaskGT() returns a byte, so a detected change returned 0xff & SIG_VERIFY_E = 27, a positive value that callers checking for a negative error take as success, with the faulty signature left in the output buffer. Select SIG_VERIFY_E with ctMaskSelInt() instead and wipe the signature when the key changed, in both ed25519.c and ed448.c. Add the macro to the --enable-faultharden and WOLFSSL_FAULTHARDEN sets (and cmake/options.h.in) next to the other fault-hardening macros. The SE050 (WOLFSSL_SE050_ONLY_KEY_ID) and crypto callback signing paths return before the check by design: the device signs with the key it holds and there is no host copy of the scalar to compare. Say so where they return and in the macro description, so protecting offloaded keys is clearly the device's job. Checked by flipping one bit of key->k from a debugger part way through signing, with WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN defined: before this change Ed25519 and Ed448 returned 27 and left the signature in place, now they return SIG_VERIFY_E with a zeroed signature buffer. --- CMakeLists.txt | 1 + cmake/options.h.in | 2 ++ configure.ac | 2 +- wolfcrypt/src/ed25519.c | 18 ++++++++++++++++-- wolfcrypt/src/ed448.c | 15 ++++++++++++++- 5 files changed, 34 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4309d387325..8b71b46717d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4228,6 +4228,7 @@ add_option("WOLFSSL_FAULTHARDEN" if(WOLFSSL_FAULTHARDEN) list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_CHECK_SIG_FAULTS" "-DWOLFSSL_CHECK_VER_FAULTS" "-DWC_SHA3_FAULT_HARDEN" "-DWC_MLKEM_FAULT_HARDEN" "-DWC_MLDSA_FAULT_HARDEN" + "-DWOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN" ) endif() diff --git a/cmake/options.h.in b/cmake/options.h.in index c19d8fc163d..2b7eb5b18d7 100644 --- a/cmake/options.h.in +++ b/cmake/options.h.in @@ -620,6 +620,8 @@ extern "C" { #cmakedefine WC_MLKEM_FAULT_HARDEN #undef WC_MLDSA_FAULT_HARDEN #cmakedefine WC_MLDSA_FAULT_HARDEN +#undef WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN +#cmakedefine WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN #undef WOLFSSL_SM3 #cmakedefine WOLFSSL_SM3 #undef WOLFSSL_SM3_SMALL diff --git a/configure.ac b/configure.ac index dbc86034e1c..1580db380a0 100644 --- a/configure.ac +++ b/configure.ac @@ -3640,7 +3640,7 @@ AC_ARG_ENABLE([faultharden], if test "$ENABLED_FAULTHARDEN" = "yes" then - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CHECK_SIG_FAULTS -DWOLFSSL_CHECK_VER_FAULTS -DWC_SHA3_FAULT_HARDEN -DWC_MLKEM_FAULT_HARDEN -DWC_MLDSA_FAULT_HARDEN" + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CHECK_SIG_FAULTS -DWOLFSSL_CHECK_VER_FAULTS -DWC_SHA3_FAULT_HARDEN -DWC_MLKEM_FAULT_HARDEN -DWC_MLDSA_FAULT_HARDEN -DWOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN" fi AC_ARG_ENABLE([compileharden], diff --git a/wolfcrypt/src/ed25519.c b/wolfcrypt/src/ed25519.c index 4e881a3c5da..3630d672182 100644 --- a/wolfcrypt/src/ed25519.c +++ b/wolfcrypt/src/ed25519.c @@ -26,6 +26,9 @@ /* Possible Ed25519 enable options: * WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN Default: OFF * Check that the private key didn't change during the signing operations. + * Enabled by --enable-faultharden. Covers the software signer only: a + * signature made by a device (SE050, crypto callback) uses the key the + * device holds and is that device's responsibility. */ #define WC_FIPS_LL_CRYPTO @@ -663,7 +666,9 @@ int wc_ed25519_sign_msg_ex(const byte* in, word32 inLen, byte* out, #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_ONLY_KEY_ID) /* Key resident in the SE050: sign in hardware. Software keys fall through - * to the wolfCrypt software implementation below. */ + * to the wolfCrypt software implementation below. The private key never + * leaves the SE050 here, so WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN has no host + * copy to compare; protecting it is the secure element's job. */ if (key->keyIdSet) { /* The SE050 performs only PureEdDSA; it cannot apply the Ed25519ctx or * Ed25519ph variants, so reject them rather than silently signing with @@ -686,6 +691,9 @@ int wc_ed25519_sign_msg_ex(const byte* in, word32 inLen, byte* out, if (key->devId != INVALID_DEVID) #endif { + /* A device that signs uses the key it holds, so the + * WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN check below, which guards the + * software signer's copy of the key, is the device's to provide. */ ret = wc_CryptoCb_Ed25519Sign(in, inLen, out, outLen, key, type, context, contextLen); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) @@ -860,7 +868,13 @@ int wc_ed25519_sign_msg_ex(const byte* in, word32 inLen, byte* out, for (i = 0; i < ED25519_KEY_SIZE; i++) { c |= key->k[i] ^ orig_k[i]; } - ret = ctMaskGT(c, 0) & SIG_VERIFY_E; + /* ctMaskGT() gives a byte mask: select the error code with it rather + * than AND it into the (negative) error code. */ + ret = ctMaskSelInt(ctMaskGT(c, 0), SIG_VERIFY_E, 0); + if (ret != 0) { + /* Do not hand out a signature made while the key changed. */ + ForceZero(out, ED25519_SIG_SIZE); + } } ForceZero(orig_k, sizeof(orig_k)); #ifdef WOLFSSL_CHECK_MEM_ZERO diff --git a/wolfcrypt/src/ed448.c b/wolfcrypt/src/ed448.c index 93ab3c0d58a..00d0c5ac626 100644 --- a/wolfcrypt/src/ed448.c +++ b/wolfcrypt/src/ed448.c @@ -28,6 +28,9 @@ /* Possible Ed448 enable options: * WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN Default: OFF * Check that the private key didn't change during the signing operations. + * Enabled by --enable-faultharden. Covers the software signer only: a + * signature made by a device (SE050, crypto callback) uses the key the + * device holds and is that device's responsibility. */ #define WC_FIPS_LL_CRYPTO @@ -623,6 +626,10 @@ int wc_ed448_sign_msg_ex(const byte* in, word32 inLen, byte* out, if (key->devId != INVALID_DEVID) #endif { + /* A device that signs uses the key it holds, so the + * WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN check below, which guards the + * software signer's copy of the key, is the device's to + * provide. */ ret = wc_CryptoCb_Ed448Sign(in, inLen, out, outLen, key, type, context, contextLen); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) @@ -777,7 +784,13 @@ int wc_ed448_sign_msg_ex(const byte* in, word32 inLen, byte* out, for (i = 0; i < ED448_KEY_SIZE; i++) { c |= key->k[i] ^ orig_k[i]; } - ret = ctMaskGT(c, 0) & SIG_VERIFY_E; + /* ctMaskGT() gives a byte mask: select the error code with it rather + * than AND it into the (negative) error code. */ + ret = ctMaskSelInt(ctMaskGT(c, 0), SIG_VERIFY_E, 0); + if (ret != 0) { + /* Do not hand out a signature made while the key changed. */ + ForceZero(out, ED448_SIG_SIZE); + } } ForceZero(orig_k, sizeof(orig_k)); #ifdef WOLFSSL_CHECK_MEM_ZERO From 7ea0821f4b27105b1b74fd148f6106024bea71d1 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 15:28:44 +0000 Subject: [PATCH 10/23] F-15132: Zero CMAC storage before init in the Rust wrapper and one-shots In SE050 builds _InitCmac_common() reads cmac->useSWCrypt before it clears the object and restores it afterwards, so the NXP host-crypto layer can ask for software CMAC by setting it before init. A caller that passes uninitialized storage therefore picks the backend with whatever byte happens to be there; a stray 1 silently moves the CMAC off the SE050, and reading it is undefined behaviour in the first place: - the Rust CMAC::new_ex() passed MaybeUninit::uninit() storage; - the C one-shot wc_AesCmacGenerate() and wc_AesCmacVerify(), which the Rust CMAC::generate() / verify() call, pass a stack or freshly allocated Cmac. Zero the storage in CMAC::new_ex() and set useSWCrypt to 0 (use the SE050, the default) in the two C one-shot functions before init. --- wolfcrypt/src/cmac.c | 10 ++++++++++ wrapper/rust/wolfssl-wolfcrypt/src/cmac.rs | 5 ++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/wolfcrypt/src/cmac.c b/wolfcrypt/src/cmac.c index 430ff67ff81..f52ba8bb051 100644 --- a/wolfcrypt/src/cmac.c +++ b/wolfcrypt/src/cmac.c @@ -652,6 +652,12 @@ int wc_AesCmacGenerate(byte* out, word32* outSz, wc_MemZero_Add("wc_AesCmacGenerate_ex cmac", ((unsigned char *)cmac) + sizeof(Aes), sizeof(Cmac) - sizeof(Aes)); #endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) + /* wc_InitCmac_ex() carries useSWCrypt over its reset of the object, so + * give it the default (use the SE050) rather than whatever this + * uninitialized buffer holds. */ + cmac->useSWCrypt = 0; +#endif ret = wc_AesCmacGenerate_ex(cmac, out, outSz, @@ -754,6 +760,10 @@ int wc_AesCmacVerify(const byte* check, word32 checkSz, wc_MemZero_Add("wc_AesCmacGenerate_ex cmac", ((unsigned char *)cmac) + sizeof(Aes), sizeof(Cmac) - sizeof(Aes)); #endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) + /* See wc_AesCmacGenerate(). */ + cmac->useSWCrypt = 0; +#endif ret = wc_AesCmacVerify_ex(cmac, check, checkSz, diff --git a/wrapper/rust/wolfssl-wolfcrypt/src/cmac.rs b/wrapper/rust/wolfssl-wolfcrypt/src/cmac.rs index cd23cc34c7e..c7f54c25fd5 100644 --- a/wrapper/rust/wolfssl-wolfcrypt/src/cmac.rs +++ b/wrapper/rust/wolfssl-wolfcrypt/src/cmac.rs @@ -135,7 +135,10 @@ impl CMAC { /// ``` pub fn new_ex(key: &[u8], heap: Option<*mut core::ffi::c_void>, dev_id: Option) -> Result { let key_size = crate::buffer_len_to_u32(key.len())?; - let mut ws_cmac: MaybeUninit = MaybeUninit::uninit(); + // Zeroed rather than uninitialized: in SE050 builds wc_InitCmac_ex() + // reads the useSWCrypt backend selection from the object before it + // resets it, and zero selects the default (the SE050). + let mut ws_cmac: MaybeUninit = MaybeUninit::zeroed(); let typ = sys::CmacType_WC_CMAC_AES as i32; let heap = match heap { Some(heap) => heap, From 13c3b82cceec8b0c1cf7311b87e5d719f5f82cfa Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 21:04:29 +0000 Subject: [PATCH 11/23] Use stateless one-shot SE050 AES operations se050_aes_crypt() opened one multi-step cipher context per Aes on the first call and then only ever called sss_cipher_update() on it. The context was never reset when the Aes was given a new key, used in the other direction or switched between ECB and CBC, and a new CBC IV from wc_AesSetIV() was ignored. It also cannot be made to work per Aes: the SE05x keeps a single crypto object per cipher mode (AES_ECB_NOPAD, AES_CBC_NOPAD) for the whole session, so every Aes using that mode shared one key, direction and chaining state, and freeing any of them deleted the object the others were still using. Two Aes objects in use at once, such as the read and write keys of a TLS connection, silently produced wrong output. Do each call as a CipherOneShot with the Aes's own key object instead, in chunks of up to 448 bytes (SE050_AES_ONESHOT_MAX). For CBC, pass aes->reg as the IV and leave the last ciphertext block in it afterwards, as the software implementation does, so chaining across calls and wc_AesSetIV() both work. Only whole blocks are processed, matching the software path. The per-Aes cipher context is no longer needed, so drop aes_ctx and ctxInitDone from the Aes struct (SE050 builds only). Checked on an SE051 (applet 7.2) and the SE050 simulator against the software AES: two interleaved Aes objects, re-keying, encrypt then decrypt on one Aes, CBC split across calls, in-place CBC decrypt, a new IV, and inputs over 448 bytes. Before this change 8 of those 11 checks failed; all pass now. --- wolfcrypt/src/port/nxp/se050_port.c | 114 +++++++++++++++++++--------- wolfssl/wolfcrypt/aes.h | 2 - 2 files changed, 80 insertions(+), 36 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index b421adfbb84..b74faaa7f6d 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -1408,6 +1408,21 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, return ret; } +/* Largest input sent in one CipherOneShot command. It is a multiple of the + * AES block size and, with the TLV and SCP03 overhead, fits the SE05x + * command and response buffers. */ +#ifndef SE050_AES_ONESHOT_MAX + #define SE050_AES_ONESHOT_MAX 448 +#endif +#if (SE050_AES_ONESHOT_MAX < 16) || ((SE050_AES_ONESHOT_MAX % 16) != 0) + #error "SE050_AES_ONESHOT_MAX must be a non-zero multiple of 16" +#endif + +/* Each call is a stateless CipherOneShot. A multi-step cipher context cannot + * be used here: the SE05x keeps one crypto object per cipher mode for the + * whole session, so every Aes using that mode would share its key, direction + * and chaining state. For CBC the chaining value is kept in aes->reg, as in + * the software implementation. */ int se050_aes_crypt(Aes* aes, const byte* in, byte* out, word32 sz, int dir, sss_algorithm_t algorithm) { @@ -1415,7 +1430,26 @@ int se050_aes_crypt(Aes* aes, const byte* in, byte* out, word32 sz, int dir, sss_status_t status; sss_object_t keyObject; sss_key_store_t host_keystore; + sss_symmetric_t ctx; + int ctxInit = 0; + int isCbc = (algorithm == kAlgorithm_SSS_AES_CBC); + byte nextIv[WC_AES_BLOCK_SIZE]; + + if (aes == NULL || + (dir != AES_ENCRYPTION && dir != AES_DECRYPTION) || + (algorithm != kAlgorithm_SSS_AES_ECB && !isCbc)) { + return BAD_FUNC_ARG; + } + /* The SE05x NOPAD modes only take whole blocks. Like the software path, + * any trailing partial block is left unprocessed. */ + sz -= sz % WC_AES_BLOCK_SIZE; + if (sz == 0) { + return 0; + } + if (in == NULL || out == NULL) { + return BAD_FUNC_ARG; + } if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; } @@ -1423,6 +1457,9 @@ int se050_aes_crypt(Aes* aes, const byte* in, byte* out, word32 sz, int dir, return BAD_FUNC_ARG; } + XMEMSET(&ctx, 0, sizeof(ctx)); + XMEMSET(nextIv, 0, sizeof(nextIv)); + if (wc_se050_lock() != 0) { return BAD_MUTEX_E; } @@ -1437,34 +1474,52 @@ int se050_aes_crypt(Aes* aes, const byte* in, byte* out, word32 sz, int dir, if (status == kStatus_SSS_Success) { status = sss_key_object_get_handle(&keyObject, aes->keyId); } + if (status == kStatus_SSS_Success) { + status = sss_symmetric_context_init(&ctx, cfg_se050_i2c_pi, + &keyObject, algorithm, + (dir == AES_DECRYPTION) ? kMode_SSS_Decrypt : kMode_SSS_Encrypt); + if (status == kStatus_SSS_Success) { + ctxInit = 1; + } + } - /* The first call to this function needs an initialization call, - * subsequent calls just need to call update */ - if (status == kStatus_SSS_Success && aes->ctxInitDone == 0) { - sss_mode_t mode; - - XMEMSET(&mode, 0, sizeof(mode)); - if (dir == AES_DECRYPTION) - mode = kMode_SSS_Decrypt; - else if (dir == AES_ENCRYPTION) - mode = kMode_SSS_Encrypt; + while (status == kStatus_SSS_Success && sz > 0) { + word32 chunk = (sz > SE050_AES_ONESHOT_MAX) ? SE050_AES_ONESHOT_MAX + : sz; - if (status == kStatus_SSS_Success) { - status = sss_symmetric_context_init(&aes->aes_ctx, - cfg_se050_i2c_pi, &keyObject, algorithm, mode); + if (isCbc && dir == AES_DECRYPTION) { + /* Save the next chaining value before an in-place decrypt + * overwrites it. */ + XMEMCPY(nextIv, in + chunk - WC_AES_BLOCK_SIZE, + WC_AES_BLOCK_SIZE); } - if (status == kStatus_SSS_Success) { - aes->ctxInitDone = 1; - status = sss_cipher_init(&aes->aes_ctx, (uint8_t*)aes->reg, - sizeof(aes->reg)); + + status = sss_cipher_one_go(&ctx, + isCbc ? (uint8_t*)aes->reg : NULL, + isCbc ? (size_t)WC_AES_BLOCK_SIZE : 0, + in, out, (size_t)chunk); + + if (status == kStatus_SSS_Success && isCbc) { + if (dir == AES_DECRYPTION) { + XMEMCPY(aes->reg, nextIv, WC_AES_BLOCK_SIZE); + } + else { + XMEMCPY(aes->reg, out + chunk - WC_AES_BLOCK_SIZE, + WC_AES_BLOCK_SIZE); + } } - } - if (status == kStatus_SSS_Success) { - size_t outSz = (size_t)sz; - status = sss_cipher_update(&aes->aes_ctx, in, sz, out, &outSz); + + in += chunk; + out += chunk; + sz -= chunk; } - ret = (status == kStatus_SSS_Success) ? 0 : WC_HW_E; + if (ctxInit) { + sss_symmetric_context_free(&ctx); + } + if (status != kStatus_SSS_Success) { + ret = WC_HW_E; + } wc_se050_unlock(); @@ -1478,28 +1533,19 @@ void se050_aes_free(Aes* aes) } if (cfg_se050_i2c_pi == NULL) { - /* No session to release the SE050 objects through. */ - aes->ctxInitDone = 0; + /* No session to release the SE050 object through. */ aes->keyId = 0; aes->keyIdSet = 0; return; } - /* Freeing the cipher context and erasing the key both talk to the - * SE050. Without the lock neither can be done safely; wc_AesFree() wipes - * the Aes next either way. */ + /* Erasing the key talks to the SE050 and cannot be done safely without + * the lock; wc_AesFree() wipes the Aes next either way. */ if (wc_se050_lock() != 0) { WOLFSSL_MSG("SE050 lock failed, AES key object not erased"); return; } - if (aes->ctxInitDone) { - sss_symmetric_context_free(&aes->aes_ctx); - - /* sets back to zero to indicate that a free has been called */ - aes->ctxInitDone = 0; - } - /* Erase the transient key object se050_aes_set_key() created, otherwise * every set key / free cycle leaves an object behind on the SE050. */ if (aes->keyIdSet != 0U) { diff --git a/wolfssl/wolfcrypt/aes.h b/wolfssl/wolfcrypt/aes.h index d9cd9e2a2bd..2ac5df6c2d5 100644 --- a/wolfssl/wolfcrypt/aes.h +++ b/wolfssl/wolfcrypt/aes.h @@ -375,8 +375,6 @@ struct Aes { #ifdef HAVE_AESGCM Gcm gcm; #ifdef WOLFSSL_SE050 - sss_symmetric_t aes_ctx; /* used as the function context */ - int ctxInitDone; word32 keyId; byte keyIdSet; byte useSWCrypt; /* Use SW crypt instead of SE050, before SCP03 auth */ From 05923ef949ff98c90aa76008a8ed547c8493ef2c Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 27 Nov 2026 21:04:29 +0000 Subject: [PATCH 12/23] Send wc_AesEcbEncrypt() and wc_AesEcbDecrypt() to the SE050 With WOLFSSL_SE050_CRYPT, wc_AesSetKey() stores the key only on the SE050 and leaves no software key schedule, and the single-block wc_AesEncrypt()/wc_AesDecrypt() go to the SE050. The multi-block wc_AesEcbEncrypt() and wc_AesEcbDecrypt() had no SE050 branch, so they ran the software AES with an empty key schedule and returned wrong output with no error. AES-GCM and AES-CTR use wc_AesEcbEncrypt() for their counter blocks, so with WOLFSSL_SE050_CRYPT their output did not match AES-GCM or AES-CTR done anywhere else. Call se050_aes_crypt() in ECB mode from both, after the missing key check, unless useSWCrypt is set. The wolfCrypt AES, AES-CBC, AES-CTR, AES-GCM, GMAC and AES key wrap tests now pass on an SE051 and the SE050 simulator with the AES offload on. --- wolfcrypt/src/aes.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index bcda61001da..e3a48b5f073 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -17508,6 +17508,14 @@ static WARN_UNUSED_RESULT int _AesEcbEncrypt( return MISSING_KEY; } +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) + /* The key is only on the SE050, so there is no software schedule. */ + if (aes->useSWCrypt == 0) { + return se050_aes_crypt(aes, in, out, sz, AES_ENCRYPTION, + kAlgorithm_SSS_AES_ECB); + } +#endif + VECTOR_REGISTERS_PUSH; #if defined(WOLFSSL_RISCV_ASM) @@ -17627,6 +17635,14 @@ static WARN_UNUSED_RESULT int _AesEcbDecrypt( return MISSING_KEY; } +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) + /* The key is only on the SE050, so there is no software schedule. */ + if (aes->useSWCrypt == 0) { + return se050_aes_crypt(aes, in, out, sz, AES_DECRYPTION, + kAlgorithm_SSS_AES_ECB); + } +#endif + VECTOR_REGISTERS_PUSH; #if defined(WOLFSSL_RISCV_ASM) From cbbc1a543ada3a1a9cf8a8ddebea0741f1f0569a Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 08:05:02 +0000 Subject: [PATCH 13/23] Sign and verify empty messages with SE050 Ed25519 keys Se05x_API_EdDSASign() and Se05x_API_EdDSAVerify() in Plug&Trust add the input TLV (TAG_3) with tlvSet_u8bufOptional(), which leaves the TLV out of the command when the input length is 0. An SE051 with applet 7.2 rejects EdDSASign and EdDSAVerify without TAG_3 (SW 0x6A80), so wc_ed25519_sign_msg() and wc_ed25519_verify_msg() of an empty message failed with WC_HW_E. The first RFC 8032 test vector has an empty message, so ed25519_test and cryptocb_test failed on the device. The SE050 simulator accepts the command without TAG_3, so CI did not see it. With TAG_3 present at length 0 the SE05x signs and verifies the empty message correctly. For a zero-length message, se050_ed25519_sign_msg() and se050_ed25519_verify_msg() now build the EdDSASign / EdDSAVerify command themselves with an empty TAG_3 and send it on the existing SE05x session. The SE05x keeps each 32-byte half of the signature in the reverse byte order of RFC 8032, which Plug&Trust normally swaps in sss_se05x_asymmetric_sign() and _verify(), so the new helper does the same. Non-empty messages still use the Plug&Trust API. Tested on an SE051 (applet 7.2): the empty message signature matches RFC 8032 test vector 1, verify accepts it and rejects a corrupted signature, and ed25519_test and cryptocb_test pass. The SE050 simulator still passes with the default flags, -DWOLFSSL_NO_RSA_SW -DWOLFSSL_NO_ECC_SW and -DWOLFSSL_SE050_ONLY_KEY_ID. --- wolfcrypt/src/port/nxp/se050_port.c | 126 ++++++++++++++++++++++++++-- 1 file changed, 118 insertions(+), 8 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index b74faaa7f6d..d86c027979f 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -5204,6 +5204,103 @@ int se050_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, #ifdef HAVE_ED25519 +/* The SE05x keeps each 32-byte half (R and S) of an Ed25519 signature in the + * reverse byte order of RFC 8032; Plug&Trust swaps them in + * sss_se05x_asymmetric_sign() and _verify(). */ +static void se050_ed25519_reverse_sig(byte* sig) +{ + word32 half; + word32 i; + + for (half = 0; half < ED25519_SIG_SIZE; half += ED25519_SIG_SIZE / 2) { + for (i = 0; i < ED25519_SIG_SIZE / 4; i++) { + byte t = sig[half + i]; + sig[half + i] = sig[half + (ED25519_SIG_SIZE / 2) - 1 - i]; + sig[half + (ED25519_SIG_SIZE / 2) - 1 - i] = t; + } + } +} + +/* EdDSASign / EdDSAVerify of an empty message with Ed25519 key object keyId. + * Plug&Trust's Se05x_API_EdDSASign() and Se05x_API_EdDSAVerify() leave the + * input TLV (TAG_3) out of the command when the input length is 0, and the + * applet rejects that with SW 0x6A80 (seen on an SE051, applet 7.2). With + * TAG_3 present at length 0 it signs and verifies the empty message, so + * build that command here. Verifies verifySig when it is not NULL, else + * writes the signature to signOut; both are ED25519_SIG_SIZE bytes in RFC + * 8032 order. Called only while the SE050 mutex is held. */ +static sss_status_t se050_ed25519_empty_msg(word32 keyId, + const byte* verifySig, byte* signOut) +{ + tlvHeader_t hdr = {{kSE05x_CLA, kSE05x_INS_CRYPTO, kSE05x_P1_SIGNATURE, + kSE05x_P2_SIGN}}; + pSe05xSession_t session = wc_se050_get_se05x_session(); + /* TAG_1 key ID, TAG_2 algorithm, empty TAG_3, TAG_5 signature */ + uint8_t cmd[6 + 3 + 2 + 2 + ED25519_SIG_SIZE]; + uint8_t* pCmd = cmd; + size_t cmdLen = 0; + uint8_t rsp[2 * ED25519_SIG_SIZE]; + size_t rspLen = sizeof(rsp); + size_t rspIdx = 0; + byte seSig[ED25519_SIG_SIZE]; + size_t seSigLen = sizeof(seSig); + SE05x_Result_t result = kSE05x_Result_NA; + int verify = (verifySig != NULL); + int tlvRet; + + if ((session == NULL) || (!verify && (signOut == NULL))) { + return kStatus_SSS_Fail; + } + if (verify) { + hdr.hdr[3] = kSE05x_P2_VERIFY; + XMEMCPY(seSig, verifySig, ED25519_SIG_SIZE); + se050_ed25519_reverse_sig(seSig); + } + + tlvRet = tlvSet_U32(&pCmd, &cmdLen, kSE05x_TAG_1, keyId); + if (tlvRet == 0) { + tlvRet = tlvSet_U8(&pCmd, &cmdLen, kSE05x_TAG_2, + (uint8_t)kSE05x_EDSignatureAlgo_ED25519PURE_SHA_512); + } + if (tlvRet == 0) { + tlvRet = tlvSet_u8buf(&pCmd, &cmdLen, kSE05x_TAG_3, seSig, 0); + } + if ((tlvRet == 0) && verify) { + tlvRet = tlvSet_u8buf(&pCmd, &cmdLen, kSE05x_TAG_5, seSig, + ED25519_SIG_SIZE); + } + if ((tlvRet != 0) || + (DoAPDUTxRx_s_Case4(session, &hdr, cmd, cmdLen, rsp, &rspLen) != + SM_OK)) { + return kStatus_SSS_Fail; + } + + if (verify) { + tlvRet = tlvGet_Result(rsp, &rspIdx, rspLen, kSE05x_TAG_1, &result); + if (result != kSE05x_Result_SUCCESS) { + tlvRet = 1; + } + } + else { + tlvRet = tlvGet_u8buf(rsp, &rspIdx, rspLen, kSE05x_TAG_1, seSig, + &seSigLen); + if (seSigLen != ED25519_SIG_SIZE) { + tlvRet = 1; + } + } + /* the response must end with SW 0x9000 right after the TLV */ + if ((tlvRet != 0) || (rspIdx + 2 != rspLen) || + ((((word32)rsp[rspIdx] << 8) | rsp[rspIdx + 1]) != SM_OK)) { + return kStatus_SSS_Fail; + } + + if (!verify) { + se050_ed25519_reverse_sig(seSig); + XMEMCPY(signOut, seSig, ED25519_SIG_SIZE); + } + return kStatus_SSS_Success; +} + int se050_ed25519_create_key(ed25519_key* key) { int ret = 0; @@ -5333,9 +5430,6 @@ int se050_ed25519_sign_msg(const byte* in, word32 inLen, byte* out, "keyId %ld\n", key, in, inLen, out, *outLen, key->keyId); #endif - if (in == NULL) - in = (const byte *)""; - if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; } @@ -5391,7 +5485,18 @@ int se050_ed25519_sign_msg(const byte* in, word32 inLen, byte* out, status = sss_key_object_get_handle(&newKey, keyId); } } - if (status == kStatus_SSS_Success) { + if ((status == kStatus_SSS_Success) && (inLen == 0)) { + if (*outLen < ED25519_SIG_SIZE) { + status = kStatus_SSS_Fail; + } + else { + status = se050_ed25519_empty_msg(keyId, NULL, out); + if (status == kStatus_SSS_Success) { + *outLen = ED25519_SIG_SIZE; + } + } + } + else if (status == kStatus_SSS_Success) { status = sss_asymmetric_context_init(&ctx_asymm, cfg_se050_i2c_pi, &newKey, kAlgorithm_SSS_SHA512, kMode_SSS_Sign); if (status == kStatus_SSS_Success) { @@ -5448,9 +5553,6 @@ int se050_ed25519_verify_msg(const byte* signature, word32 signatureLen, key, signature, signatureLen, msg, msgLen); #endif - if (msg == NULL) - msg = (const byte *)""; - *res = 0; if (cfg_se050_i2c_pi == NULL) { @@ -5509,7 +5611,15 @@ int se050_ed25519_verify_msg(const byte* signature, word32 signatureLen, } } - if (status == kStatus_SSS_Success) { + if ((status == kStatus_SSS_Success) && (msgLen == 0)) { + if (signatureLen != ED25519_SIG_SIZE) { + status = kStatus_SSS_Fail; + } + else { + status = se050_ed25519_empty_msg(keyId, signature, NULL); + } + } + else if (status == kStatus_SSS_Success) { status = sss_asymmetric_context_init(&ctx_asymm, cfg_se050_i2c_pi, &newKey, kAlgorithm_SSS_SHA512, kMode_SSS_Verify); if (status == kStatus_SSS_Success) { From 676eae8cc67b7383a45d4baf44740e61e8d959d8 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 08:05:33 +0000 Subject: [PATCH 14/23] Drop the per-call key lookup APDUs from the SE050 AES offload se050_aes_crypt() called sss_key_object_get_handle() before every CipherOneShot. That sends CheckObjectExists and ReadType to the SE050, so each AES call cost three APDUs where one would do. se050_aes_set_key() called sss_key_object_allocate_handle(), which sends a CheckObjectExists that only logs a warning. Deleting the key in se050_aes_free() or on re-key also went through get_handle first. The port creates every AES key object itself, so fill in the object handle directly (key ID, kSSS_KeyPart_Default, kSSS_CipherType_AES) without sending an APDU. In Plug&Trust 04.07.01, CipherOneShot and DeleteSecureObject only use the key ID. The SE05x answers 0x6985 for an ID that does not exist or does not hold an AES key, so a missing or wrong key still fails with WC_HW_E. The generic se050_erase_object_locked() is unchanged for the other key types. APDUs per call on an SE051 (applet 7.2), before -> after: wc_AesEncryptDirect() 3 -> 1 wc_AesCbcEncrypt(), 1024 bytes 5 -> 3 wc_AesSetKey(), re-key 6 -> 3 wc_AesFree() 3 -> 1 wc_AesGcmEncrypt(), 100 bytes 9 -> 3 wc_AesGcmEncrypt(), 100 bytes in place 24 -> 8 On the board, the wolfCrypt AES-family tests (AES, CBC, CTR, GCM, GMAC, key wrap, CMAC, PKCS#7) now take 1562 s instead of 1823 s, and AES-GCM alone takes 244 s instead of 436 s. No SE objects are left behind. The SE050 simulator configurations pass as before. --- wolfcrypt/src/port/nxp/se050_port.c | 83 +++++++++++++++++++---------- 1 file changed, 54 insertions(+), 29 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index d86c027979f..779ed2221cb 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -1334,6 +1334,52 @@ void se050_hash_free(SE050_HASH_Context* se050Ctx) #if defined(WOLFSSL_SE050_CRYPT) && !defined(NO_AES) +/* Set up a handle for the transient AES key object at keyId without sending + * any APDU. The port creates every AES key itself (se050_aes_set_key()), so + * it fills in the fields that sss_key_object_allocate_handle() would set + * (one CheckObjectExists APDU) or sss_key_object_get_handle() would read + * back (CheckObjectExists and ReadType, two APDUs). CipherOneShot and + * DeleteSecureObject only use the key ID, and the SE05x itself rejects an ID + * that does not exist or is not an AES key, so a bad ID still fails. */ +static sss_status_t se050_aes_key_object(sss_object_t* keyObject, + sss_key_store_t* keyStore, word32 keyId) +{ + sss_status_t status; + + status = sss_key_store_context_init(keyStore, cfg_se050_i2c_pi); + if (status == kStatus_SSS_Success) { + status = sss_key_store_allocate(keyStore, SE050_KEYSTOREID_AES); + } + if (status == kStatus_SSS_Success) { + /* Zeroes the object: transient, no curve. */ + status = sss_key_object_init(keyObject, keyStore); + } + if (status == kStatus_SSS_Success) { + keyObject->objectType = kSSS_KeyPart_Default; + keyObject->cipherType = kSSS_CipherType_AES; + keyObject->keyId = keyId; + } + + return status; +} + +/* Delete an AES key object se050_aes_set_key() created: one + * DeleteSecureObject APDU. Call with the SE050 lock held. */ +static int se050_aes_erase_key_locked(word32 keyId) +{ + sss_status_t status; + sss_object_t keyObject; + sss_key_store_t host_keystore; + + status = se050_aes_key_object(&keyObject, &host_keystore, keyId); + if (status == kStatus_SSS_Success) { + status = sss_key_store_erase_key(&host_keystore, &keyObject); + sss_key_object_free(&keyObject); + } + + return (status == kStatus_SSS_Success) ? 0 : WC_HW_E; +} + int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, const byte* iv, int dir) { @@ -1359,7 +1405,7 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, /* Free an existing key in the slot before storing a replacement. */ if (aes->keyIdSet != 0U) { - ret = se050_erase_object_locked(aes->keyId); + ret = se050_aes_erase_key_locked(aes->keyId); if (ret != 0) { wc_se050_unlock(); return ret; @@ -1368,24 +1414,11 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, aes->keyIdSet = 0; } - status = sss_key_store_context_init(&host_keystore, cfg_se050_i2c_pi); - if (status == kStatus_SSS_Success) { - status = sss_key_store_allocate(&host_keystore, SE050_KEYSTOREID_AES); - } - if (status == kStatus_SSS_Success) { - status = sss_key_object_init(&newKey, &host_keystore); - } - if (status == kStatus_SSS_Success) { - keyId = se050_allocate_key(SE050_AES_KEY); - status = sss_key_object_allocate_handle(&newKey, keyId, - kSSS_KeyPart_Default, kSSS_CipherType_AES, keylen, - kKeyObject_Mode_Transient); - if (status == kStatus_SSS_Success) { - /* From here on the object must be released on any failure. */ - keyCreated = 1; - } - } + keyId = se050_allocate_key(SE050_AES_KEY); + status = se050_aes_key_object(&newKey, &host_keystore, keyId); if (status == kStatus_SSS_Success) { + /* From here on the object must be released on any failure. */ + keyCreated = 1; status = sss_key_store_set_key(&host_keystore, &newKey, key, keylen, keylen * 8, NULL, 0); } @@ -1464,16 +1497,8 @@ int se050_aes_crypt(Aes* aes, const byte* in, byte* out, word32 sz, int dir, return BAD_MUTEX_E; } - status = sss_key_store_context_init(&host_keystore, cfg_se050_i2c_pi); - if (status == kStatus_SSS_Success) { - status = sss_key_store_allocate(&host_keystore, SE050_KEYSTOREID_AES); - } - if (status == kStatus_SSS_Success) { - status = sss_key_object_init(&keyObject, &host_keystore); - } - if (status == kStatus_SSS_Success) { - status = sss_key_object_get_handle(&keyObject, aes->keyId); - } + /* No lookup APDUs: each chunk below is the only command sent. */ + status = se050_aes_key_object(&keyObject, &host_keystore, aes->keyId); if (status == kStatus_SSS_Success) { status = sss_symmetric_context_init(&ctx, cfg_se050_i2c_pi, &keyObject, algorithm, @@ -1549,7 +1574,7 @@ void se050_aes_free(Aes* aes) /* Erase the transient key object se050_aes_set_key() created, otherwise * every set key / free cycle leaves an object behind on the SE050. */ if (aes->keyIdSet != 0U) { - if (se050_erase_object_locked(aes->keyId) != 0) { + if (se050_aes_erase_key_locked(aes->keyId) != 0) { WOLFSSL_MSG("Failed to erase SE050 AES key object"); } aes->keyId = 0; From 5c676f8616906ef2789a7415ce0b942574a9cb42 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 08:55:06 +0000 Subject: [PATCH 15/23] Skip SE050 object IDs that are in use when creating an AES key se050_allocate_key() hands out IDs from a counter that starts again in every process, so an object left on the SE050 by an earlier run or another session can already hold the ID it returns. se050_aes_set_key() no longer sends the CheckObjectExists that only logged a warning, and since F-11245 its failure path deletes the object at the new ID. A key store over an existing object therefore either replaced that object's key or, if the store failed, deleted the object. Check the ID with se050_require_new_object() before writing the key and move on to the next ID if it is in use, up to SE050_AES_KEYID_TRIES (8) IDs. This adds one APDU to wc_AesSetKey(); the per-call AES path is unchanged. --- wolfcrypt/src/port/nxp/se050_port.c | 30 +++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index 779ed2221cb..43e9db0c7ad 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -1363,6 +1363,15 @@ static sss_status_t se050_aes_key_object(sss_object_t* keyObject, return status; } +/* How many IDs se050_aes_set_key() tries before it gives up when objects + * already on the SE050 hold the IDs the allocator returns. */ +#ifndef SE050_AES_KEYID_TRIES + #define SE050_AES_KEYID_TRIES 8 +#endif +#if SE050_AES_KEYID_TRIES < 1 + #error "SE050_AES_KEYID_TRIES must be at least 1" +#endif + /* Delete an AES key object se050_aes_set_key() created: one * DeleteSecureObject APDU. Call with the SE050 lock held. */ static int se050_aes_erase_key_locked(word32 keyId) @@ -1384,11 +1393,12 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, const byte* iv, int dir) { int ret = 0; - sss_status_t status; + sss_status_t status = kStatus_SSS_Fail; sss_object_t newKey; sss_key_store_t host_keystore; - word32 keyId; + word32 keyId = 0; int keyCreated = 0; + int tries; if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; @@ -1414,8 +1424,20 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, aes->keyIdSet = 0; } - keyId = se050_allocate_key(SE050_AES_KEY); - status = se050_aes_key_object(&newKey, &host_keystore, keyId); + /* The ID allocator starts again in every process, so an object left by + * an earlier run or another session can already hold the ID it returns. + * Writing the key there would replace that object's key and the failure + * path below would delete it, so skip IDs that are in use. */ + for (tries = 0; tries < SE050_AES_KEYID_TRIES; tries++) { + keyId = se050_allocate_key(SE050_AES_KEY); + status = se050_require_new_object(keyId); + if (status == kStatus_SSS_Success) { + break; + } + } + if (status == kStatus_SSS_Success) { + status = se050_aes_key_object(&newKey, &host_keystore, keyId); + } if (status == kStatus_SSS_Success) { /* From here on the object must be released on any failure. */ keyCreated = 1; From 33f64fd4ba815e3098b875d5ca82d8d3fce0b18e Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 08:55:23 +0000 Subject: [PATCH 16/23] Reject SE050 RSA keys over RSA_MAX_SIZE in the host OAEP path Since F-15216, OAEP with parameters the SE050 cannot apply is encoded and decoded on the host around a raw RSA operation on the SE050. The SE050 can hold a key larger than the build's RSA_MAX_SIZE, and RsaUnPad_OAEP() clears and fills a stack buffer of RSA_MAX_SIZE / 8 bytes (when not WOLFSSL_SMALL_STACK) for the full modulus length without checking it. A 4096-bit SE050 key in a build with RSA_MAX_SIZE 2048 would overflow that buffer on decryption. Return WC_KEY_SIZE_E from Se050RsaOaepDecrypt() and Se050RsaOaepEncrypt() when the modulus is longer than RSA_MAX_SIZE / 8 bytes, before any SE050 operation. The encrypt side was already caught by the size check in RsaPad_OAEP(); it now fails the same way and as early. --- wolfcrypt/src/rsa.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index b06bf1b4de4..bbbcb898094 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -3820,6 +3820,11 @@ static int Se050RsaOaepEncrypt(const byte* in, word32 inLen, byte* out, { int ret; + /* As for decryption: the OAEP encoding works in RSA_MAX_SIZE buffers. */ + if (sz > RSA_MAX_SIZE / 8) { + return WC_KEY_SIZE_E; + } + ret = wc_RsaPad_ex(in, inLen, out, (word32)sz, RSA_BLOCK_TYPE_2, rng, WC_RSA_OAEP_PAD, hash, mgf, label, labelSz, 0, RsaModulusBits(key), key->heap); @@ -3859,6 +3864,11 @@ static int Se050RsaOaepDecrypt(const byte* in, word32 inLen, byte* out, if (sz <= 0) { return BAD_FUNC_ARG; } + /* The SE050 can hold a key larger than this build's software limit, and + * the OAEP decoding below works in buffers sized for RSA_MAX_SIZE. */ + if (sz > RSA_MAX_SIZE / 8) { + return WC_KEY_SIZE_E; + } emSz = (word32)sz; em = (byte*)XMALLOC(emSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER); From 9b1bc48be8365676326825c6d5b06560454f497a Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 08:55:39 +0000 Subject: [PATCH 17/23] Free the SE050 hash buffer in wc_Sha224Free() With WOLFSSL_SE050_HASH the SE050 backend keeps the whole message in se050Ctx.msg until final. wc_Sha256Free(), wc_Sha384Free() and wc_Sha512Free() release it with se050_hash_free(), but wc_Sha224Free() only cleared the context. A SHA-224 object freed before a successful final (after a failed final, or never finalized, including a copy made by wc_Sha224Copy()) leaked the buffered message without wiping it, and the buffer may hold secret input such as HMAC key blocks. Call se050_hash_free() in wc_Sha224Free(), which wipes and frees the buffer, as the other SHA-2 free functions do. --- wolfcrypt/src/sha256.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 4bc86e3ed38..0f5e2029a18 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -3365,6 +3365,9 @@ int wc_Sha224Reset(wc_Sha224* sha224) { sha224->msg = NULL; } #endif + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&sha224->se050Ctx); + #endif #if defined(PSOC6_HASH_SHA2) wc_Psoc6_Sha_Free(); #endif From dcae1f6758c8aaffa9c5997a9db4c1e55971d146 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 08:56:24 +0000 Subject: [PATCH 18/23] Clean up the SHA-2 Copy destination when an SE050 copy step fails wc_Sha224Copy(), wc_Sha256Copy(), wc_Sha384Copy() and wc_Sha512Copy() copy the whole struct and then give the destination its own SE050 message buffer with se050_hash_copy(). With WOLFSSL_SMALL_STACK_CACHE two failure paths left the destination in a bad state: - If se050_hash_copy() failed, the function returned with dst->W still pointing at the source's scratch buffer, so freeing the destination freed the source's buffer under it. - If the scratch buffer allocation failed after the SE050 copy, the destination was cleared with ForceZero() and its new message buffer was leaked without being wiped. Clear dst->W before the SE050 copy, and release the copied message with se050_hash_free() before clearing the destination when the scratch allocation fails. --- wolfcrypt/src/sha256.c | 14 ++++++++++++++ wolfcrypt/src/sha512.c | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 0f5e2029a18..89f12c97b19 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -3677,6 +3677,10 @@ int wc_Sha224Reset(wc_Sha224* sha224) { /* The SE050 hash buffers the whole message: give the copy a buffer of * its own instead of sharing the source's, which the first Final or Free * of either object would release under the other. */ + #ifdef WOLFSSL_SMALL_STACK_CACHE + /* If the copy fails, dst must not keep the source's scratch buffer. */ + dst->W = NULL; + #endif ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); if (ret != 0) { return ret; @@ -3687,6 +3691,9 @@ int wc_Sha224Reset(wc_Sha224* sha224) { dst->W = (word32*)XMALLOC(WC_SHA256_TSCRATCH_SIZE, dst->heap, DYNAMIC_TYPE_DIGEST); if (dst->W == NULL) { + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&dst->se050Ctx); + #endif ForceZero(dst, sizeof(wc_Sha224)); return MEMORY_E; } @@ -3850,6 +3857,10 @@ int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) /* The SE050 hash buffers the whole message: give the copy a buffer of * its own instead of sharing the source's, which the first Final or Free * of either object would release under the other. */ + #ifdef WOLFSSL_SMALL_STACK_CACHE + /* If the copy fails, dst must not keep the source's scratch buffer. */ + dst->W = NULL; + #endif ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); if (ret != 0) { return ret; @@ -3865,6 +3876,9 @@ int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) dst->W = (word32*)XMALLOC(WC_SHA256_TSCRATCH_SIZE, dst->heap, DYNAMIC_TYPE_DIGEST); if (dst->W == NULL) { + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&dst->se050Ctx); + #endif ForceZero(dst, sizeof(wc_Sha256)); return MEMORY_E; } diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index a6148a0ad5a..1fcfaef790b 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -3497,6 +3497,10 @@ int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst) /* The SE050 hash buffers the whole message: give the copy a buffer of * its own instead of sharing the source's, which the first Final or Free * of either object would release under the other. */ + #ifdef WOLFSSL_SMALL_STACK_CACHE + /* If the copy fails, dst must not keep the source's scratch buffer. */ + dst->W = NULL; + #endif ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); if (ret != 0) { return ret; @@ -3510,6 +3514,9 @@ int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst) dst->W = (word64 *)XMALLOC(sizeof(Sha512TScratch) + WC_SHA512_BLOCK_SIZE, dst->heap, DYNAMIC_TYPE_DIGEST); if (dst->W == NULL) { + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&dst->se050Ctx); + #endif ForceZero(dst, sizeof(wc_Sha512)); return MEMORY_E; } @@ -3960,6 +3967,10 @@ int wc_Sha384Copy(wc_Sha384* src, wc_Sha384* dst) /* The SE050 hash buffers the whole message: give the copy a buffer of * its own instead of sharing the source's, which the first Final or Free * of either object would release under the other. */ + #ifdef WOLFSSL_SMALL_STACK_CACHE + /* If the copy fails, dst must not keep the source's scratch buffer. */ + dst->W = NULL; + #endif ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); if (ret != 0) { return ret; @@ -3974,6 +3985,9 @@ int wc_Sha384Copy(wc_Sha384* src, wc_Sha384* dst) dst->W = (word64 *)XMALLOC(sizeof(Sha512TScratch) + WC_SHA384_BLOCK_SIZE, dst->heap, DYNAMIC_TYPE_DIGEST); if (dst->W == NULL) { + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&dst->se050Ctx); + #endif ForceZero(dst, sizeof(wc_Sha384)); return MEMORY_E; } From cd83007d69ca82d304ad08f1f55ea6e115a8421f Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 09:19:10 +0000 Subject: [PATCH 19/23] Leave room for SCP03 padding in the empty-message EdDSA command se050_ed25519_empty_msg() builds the EdDSASign / EdDSAVerify command in a stack buffer sized exactly for its TLVs, 77 bytes for verify. On an SCP03 session DoAPDUTxRx_s_Case4() encrypts the command data in place, and nxSCP03_PadCommandAPDU() first pads it with 0x80 and zero bytes to a multiple of 16, so an empty-message verify wrote 3 bytes past the end of the buffer. Plug&Trust's own API functions avoid this by building commands in SE05X_MAX_BUF_SIZE_CMD buffers. Add 16 bytes to the buffer, enough for the largest padding. The C-MAC goes into a separate transmit buffer, so nothing else is written into the command buffer. --- wolfcrypt/src/port/nxp/se050_port.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index 43e9db0c7ad..cb00852a949 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -5282,8 +5282,10 @@ static sss_status_t se050_ed25519_empty_msg(word32 keyId, tlvHeader_t hdr = {{kSE05x_CLA, kSE05x_INS_CRYPTO, kSE05x_P1_SIGNATURE, kSE05x_P2_SIGN}}; pSe05xSession_t session = wc_se050_get_se05x_session(); - /* TAG_1 key ID, TAG_2 algorithm, empty TAG_3, TAG_5 signature */ - uint8_t cmd[6 + 3 + 2 + 2 + ED25519_SIG_SIZE]; + /* TAG_1 key ID, TAG_2 algorithm, empty TAG_3, TAG_5 signature, plus 16 + * bytes because on an SCP03 session Plug&Trust pads the command data in + * place to a multiple of the 16-byte AES block before encrypting it. */ + uint8_t cmd[6 + 3 + 2 + 2 + ED25519_SIG_SIZE + 16]; uint8_t* pCmd = cmd; size_t cmdLen = 0; uint8_t rsp[2 * ED25519_SIG_SIZE]; From d7b193067b2973652ecc703f6c231f95887f484f Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 10:24:09 +0000 Subject: [PATCH 20/23] Refuse the parent's SE05x session in a fork() child A fork() child inherits the port's se050Mutex, possibly locked by a parent thread that does not exist in the child, so its first SE05x operation could wait forever. The wolfCrypt RNG fork test hung this way with WOLFSSL_SE050_HASH: the child's DRBG reseed hashes on the SE05x, and the parent's churn thread held the mutex at the fork. A child that got past the mutex would instead share the parent's session (transport fd, T=1 state, SCP03 MAC chain) and interleave its APDUs with the parent's. Record the process that configured the session and, where getpid() exists, refuse the session in any other process: wc_se050_lock() returns BAD_STATE_E before touching the mutex, so every SE05x operation in a child fails at once and sends nothing. In a child, wc_se050_close() discards the inherited session without any traffic, and wc_se050_set_config() (or wc_se050_init() after that close) gives the child a session of its own with a fresh mutex. A child whose DRBG hashes or seeds on the SE05x (WOLFSSL_SE050_HASH, or the SE05x TRNG) can no longer reseed, so the RNG fork tests are left out of those builds. A new SE05x fork test forks while another thread holds the port lock and checks that the child is refused at once and that the parent's session still works. --- wolfcrypt/src/port/nxp/README_SE050.md | 29 ++++ wolfcrypt/src/port/nxp/se050_port.c | 107 ++++++++++++++- wolfcrypt/test/test.c | 171 ++++++++++++++++++++++++ wolfcrypt/test/test.h | 12 +- wolfssl/wolfcrypt/port/nxp/se050_port.h | 4 +- 5 files changed, 314 insertions(+), 9 deletions(-) diff --git a/wolfcrypt/src/port/nxp/README_SE050.md b/wolfcrypt/src/port/nxp/README_SE050.md index 363b975c56e..daee47720d6 100644 --- a/wolfcrypt/src/port/nxp/README_SE050.md +++ b/wolfcrypt/src/port/nxp/README_SE050.md @@ -582,6 +582,35 @@ build routes to the SE05x, while holding this lock; those acquire it internally. wolfCrypt operations on other hardware, such as an on-chip accelerator, do not take this lock and may be used while it is held. +### SE05x Sessions and fork() + +A child created with `fork()` inherits the parent's SE05x session: the +transport file descriptor, the T=1 protocol state and, with Platform SCP03, +the secure channel state. If both processes sent commands on it, the commands +would interleave and break the session for both. The child also inherits the +SE05x mutex, possibly locked by a parent thread that does not exist in the +child. + +On systems with `getpid()`, the port records which process configured the +session and refuses the session in any other process. In a forked child, +`wc_se050_lock()` and every wolfCrypt operation that the build routes to the +SE05x fail with an error (for example `BAD_STATE_E`, `BAD_MUTEX_E` or +`WC_HW_E`) and send nothing. The parent's session is not affected. With +`WOLFSSL_SE050_HASH` this includes the SHA-256 that the DRBG uses, and without +`WOLFSSL_SE050_NO_TRNG` it includes the seed, so a child cannot reseed or draw +from a `WC_RNG` in those builds either. + +A child that needs the SE05x must set up its own session, and only once the +parent no longer uses its session (for example after the parent of a +daemonizing `fork()` has exited): + +- With `WOLFSSL_SE050_INIT`, call `wc_se050_close()` (or `wolfCrypt_Cleanup()` + for the last reference) in the child. In a child this discards the inherited + session without sending anything. Then call `wc_se050_init()` or + `wc_se050_init_ex()`, or `wolfCrypt_Init()`, to open a new one. +- With an application session, open a new one through the middleware and pass + it to `wc_se050_set_config()` in the child. + ### wolfSSL SE050 Key Generation wolfSSL includes APIs for key generation when `WOLFSSL_KEY_GEN` has been diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index cb00852a949..06828e64477 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -55,6 +55,12 @@ #include +#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) + /* getpid(), to keep a fork() child off the parent's session */ + #include + #define SE050_FORK_CHECK +#endif + #ifdef WOLFSSL_SE050_INIT #ifndef SE050_DEFAULT_PORT #define SE050_DEFAULT_PORT "/dev/i2c-1" @@ -124,6 +130,26 @@ static int se050MutexInit = 0; #endif #endif /* !SINGLE_THREADED */ +#ifdef SE050_FORK_CHECK +/* The process that configured the session, 0 while none is configured. + * A fork() child inherits the session (transport fd, T=1 sequence state and + * any SCP03 MAC chain) along with se050Mutex, which may be locked by a + * parent thread that does not exist in the child. The child must touch + * neither: its APDUs would interleave with the parent's on the one session, + * and the inherited mutex might never be released. */ +static pid_t se050OwnerPid = 0; +#endif + +/* Nonzero in a fork() child of the process that configured the session. */ +static int se050_in_fork_child(void) +{ +#ifdef SE050_FORK_CHECK + return (se050OwnerPid != 0) && (se050OwnerPid != getpid()); +#else + return 0; +#endif +} + static int se050_mutex_init(void) { int ret = 0; @@ -138,6 +164,25 @@ static int se050_mutex_init(void) return ret; } +#ifdef SE050_FORK_CHECK +/* Give a fork() child a fresh port mutex. Its inherited copy may be locked + * by a thread that exists only in the parent, and nothing in the child can + * be holding it: wc_se050_lock() refuses the child until it has a session of + * its own. */ +static int se050_mutex_reset(void) +{ + int ret = 0; +#ifndef SINGLE_THREADED + XMEMSET(&se050Mutex, 0, sizeof(se050Mutex)); + ret = wc_InitMutex(&se050Mutex); +#ifndef WOLFSSL_MUTEX_INITIALIZER + se050MutexInit = (ret == 0) ? 1 : 0; +#endif +#endif + return ret; +} +#endif /* SE050_FORK_CHECK */ + int wc_se050_set_config(sss_session_t *pSession, sss_key_store_t *pHostKeyStore, sss_key_store_t *pKeyStore) { @@ -146,7 +191,16 @@ int wc_se050_set_config(sss_session_t *pSession, sss_key_store_t *pHostKeyStore, if ((pSession == NULL) || (pKeyStore == NULL)) { return BAD_FUNC_ARG; } - ret = se050_mutex_init(); +#ifdef SE050_FORK_CHECK + if (se050_in_fork_child()) { + /* A fork() child adopting a session of its own. */ + ret = se050_mutex_reset(); + } + else +#endif + { + ret = se050_mutex_init(); + } if (ret != 0) { return ret; } @@ -156,6 +210,9 @@ int wc_se050_set_config(sss_session_t *pSession, sss_key_store_t *pHostKeyStore, cfg_se050_i2c_pi = pSession; gHostKeyStore = pHostKeyStore; gKeyStore = pKeyStore; +#ifdef SE050_FORK_CHECK + se050OwnerPid = getpid(); +#endif return 0; } @@ -198,16 +255,22 @@ pSe05xSession_t wc_se050_get_se05x_session(void) int wc_se050_lock(void) { -#ifdef SINGLE_THREADED - return 0; -#else + int ret = 0; + + /* Before the mutex is touched: in a fork() child it may be held by a + * thread that does not exist there. */ + if (se050_in_fork_child()) { + WOLFSSL_MSG("SE05x session belongs to the parent process"); + return BAD_STATE_E; + } +#ifndef SINGLE_THREADED /* Make sure the mutex has been initialized */ - int ret = se050_mutex_init(); + ret = se050_mutex_init(); if (ret == 0) { ret = wc_LockMutex(&se050Mutex); } - return ret; #endif + return ret; } void wc_se050_unlock(void) @@ -699,6 +762,9 @@ static int se050_close_internal(int preservePortName) cfg_se050_i2c_pi = NULL; gHostKeyStore = NULL; gKeyStore = NULL; +#ifdef SE050_FORK_CHECK + se050OwnerPid = 0; +#endif XMEMSET(&gBootCtx, 0, sizeof(gBootCtx)); wc_se050_unlock(); #if defined(SE050_RUNTIME_SCP03) && \ @@ -712,8 +778,37 @@ static int se050_close_internal(int preservePortName) return 0; } +#ifdef SE050_FORK_CHECK +/* wc_se050_close() in a fork() child: forget the session inherited from the + * parent without sending anything. ex_sss_session_close() would end the + * transport session the parent is still using. The child's copies of the + * transport fd and of the middleware's allocations are left as they are. */ +static int se050_drop_inherited_session(void) +{ + if (cfg_se050_i2c_pi != &gBootCtx.session) { + return WC_NO_ERR_TRACE(BAD_STATE_E); + } + cfg_se050_i2c_pi = NULL; + gHostKeyStore = NULL; + gKeyStore = NULL; + se050OwnerPid = 0; + /* May hold SCP03 session state. */ + ForceZero(&gBootCtx, sizeof(gBootCtx)); +#if defined(SE050_RUNTIME_SCP03) && \ + defined(WOLFSSL_SE050_SCP03_ROTATE) + se050_free_port_name(); +#endif + return se050_mutex_reset(); +} +#endif /* SE050_FORK_CHECK */ + int wc_se050_close(void) { +#ifdef SE050_FORK_CHECK + if (se050_in_fork_child()) { + return se050_drop_inherited_session(); + } +#endif return se050_close_internal(0); } #endif diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index ab6e9060ba8..704f013e826 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -199,6 +199,18 @@ static const byte const_byte_array[] = "A+Gd\0\0\0"; #include #include #endif +/* fork() while another thread holds the SE05x port lock: needs threads, a + * process model and the port's pid check. */ +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_PTHREADS) && \ + !defined(SINGLE_THREADED) && defined(HAVE_GETPID) && \ + !defined(WOLFSSL_NO_GETPID) && !defined(__STRICT_ANSI__) && \ + (defined(__unix__) || defined(__linux__) || defined(__APPLE__)) + #define WC_TEST_SE050_FORK + #include + #include + #include + #include +#endif /* WOLF_CRYPTO_CB_SEED_ONLY_TEST: a NO_DEV_RANDOM crypto callback build * where the callback is the only seed source, so a missing devId fails. */ #ifdef WOLF_CRYPTO_CB_SEED_ONLY_TEST @@ -1039,6 +1051,9 @@ WOLFSSL_TEST_SUBROUTINE wc_test_ret_t random_test(void); #ifdef WC_TEST_RNG_AUTOLOCK WOLFSSL_TEST_SUBROUTINE wc_test_ret_t random_thread_test(void); #endif +#ifdef WC_TEST_SE050_FORK +WOLFSSL_TEST_SUBROUTINE wc_test_ret_t se050_fork_test(void); +#endif #ifdef HAVE_WC_RNG_BANK WOLFSSL_TEST_SUBROUTINE wc_test_ret_t random_bank_test(void); #endif @@ -2930,6 +2945,12 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ else TEST_PASS("RNGTHRD test passed!\n"); #endif +#ifdef WC_TEST_SE050_FORK + if ((ret = se050_fork_test()) != 0) + TEST_FAIL("SE05XFRK test failed!\n", ret); + else + TEST_PASS("SE05XFRK test passed!\n"); +#endif #ifdef HAVE_WC_RNG_BANK if ((ret = random_bank_test()) != 0) TEST_FAIL("RNGBANK test failed!\n", ret); @@ -33401,6 +33422,156 @@ WOLFSSL_TEST_SUBROUTINE wc_test_ret_t random_thread_test(void) #endif /* WC_TEST_RNG_AUTOLOCK */ +#ifdef WC_TEST_SE050_FORK +struct se050_fork_holder_args { + int heldFd; /* gets one byte once the lock is held */ + int goFd; /* the lock is let go at a byte or EOF here */ + int ret; +}; + +/* Holds the SE05x port lock until told to let go, as a thread in the middle + * of an SE05x transaction would. */ +static THREAD_RETURN WOLFSSL_THREAD se050_fork_test_holder(void* arg) +{ + struct se050_fork_holder_args* a = (struct se050_fork_holder_args*)arg; + byte b = 1; + + a->ret = wc_se050_lock(); + if (a->ret == 0) { + if (write(a->heldFd, &b, 1) == 1) { + if (read(a->goFd, &b, 1) < 0) + a->ret = WC_TEST_RET_ENC_NC; + } + wc_se050_unlock(); + } + close(a->heldFd); /* EOF if the lock was never held */ + WOLFSSL_RETURN_FROM_THREAD(0); +} + +/* fork() while another thread holds the SE05x port lock. The child must be + * refused the parent's session at once: waiting for a lock whose holder does + * not exist in the child would never end, and using the session would + * interleave its APDUs with the parent's. The parent's session must still + * work afterwards. */ +WOLFSSL_TEST_SUBROUTINE wc_test_ret_t se050_fork_test(void) +{ + struct se050_fork_holder_args h; + THREAD_TYPE holder = INVALID_THREAD_VAL; /* joined only if started */ + int started = 0; + int hfd[2] = { -1, -1 }; + int gfd[2] = { -1, -1 }; + int cfd[2] = { -1, -1 }; + pid_t pid = -1; + int status = 0; + int rc; + byte b = 0; + wc_test_ret_t ret = 0; +#if defined(WOLFSSL_SE050_HASH) && !defined(NO_SHA256) + static const byte abcHash[WC_SHA256_DIGEST_SIZE] = { + 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, + 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, + 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, + 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad + }; + byte digest[WC_SHA256_DIGEST_SIZE]; +#endif + + WOLFSSL_ENTER("se050_fork_test"); + + if (wc_se050_get_session() == NULL) + return 0; /* no session for a child to inherit */ + + if ((pipe(hfd) != 0) || (pipe(gfd) != 0) || (pipe(cfd) != 0)) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + + h.heldFd = hfd[1]; + h.goFd = gfd[0]; + h.ret = 0; + if (wolfSSL_NewThread(&holder, &se050_fork_test_holder, &h) != 0) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + started = 1; + hfd[1] = -1; /* the holder closes it */ + if (read(hfd[0], &b, 1) != 1) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + + pid = fork(); + if (pid == 0) { + /* The lock's holder is not in this process. The alarm turns a wait + * for it into a death, which the parent reads as EOF. */ + byte res = 1; + (void)alarm(10); + rc = wc_se050_lock(); + if (rc == 0) + wc_se050_unlock(); + else if (rc == WC_NO_ERR_TRACE(BAD_STATE_E)) + res = 0; +#if defined(WOLFSSL_SE050_HASH) && !defined(NO_SHA256) + /* the DRBG's hash, which hung the RNG fork test */ + if ((res == 0) && (wc_Sha256Hash((const byte*)"abc", 3, digest) == 0)) + res = 2; +#endif + if (write(cfd[1], &res, 1) != 1) + _exit(1); + _exit(0); + } + if (pid < 0) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + close(cfd[1]); + cfd[1] = -1; + if (read(cfd[0], &b, 1) != 1) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); /* the child hung and died */ + rc = (int)b; /* 1: not refused, 2: the hash reached the SE05x */ + if (rc != 0) + ERROR_OUT(WC_TEST_RET_ENC_I(rc), done); + if (waitpid(pid, &status, 0) != pid) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + pid = -1; + if ((! WIFEXITED(status)) || (WEXITSTATUS(status) != 0)) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + + /* let the holder go, then the parent's session must still serve */ + close(gfd[1]); + gfd[1] = -1; + started = 0; + if (wolfSSL_JoinThread(holder) != 0) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + if (h.ret != 0) + ERROR_OUT(WC_TEST_RET_ENC_EC(h.ret), done); + rc = wc_se050_lock(); + if (rc != 0) + ERROR_OUT(WC_TEST_RET_ENC_EC(rc), done); + wc_se050_unlock(); +#if defined(WOLFSSL_SE050_HASH) && !defined(NO_SHA256) + rc = wc_Sha256Hash((const byte*)"abc", 3, digest); + if (rc != 0) + ERROR_OUT(WC_TEST_RET_ENC_EC(rc), done); + if (XMEMCMP(digest, abcHash, sizeof(abcHash)) != 0) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); +#endif + +done: + if (pid > 0) { + (void)kill(pid, SIGKILL); + (void)waitpid(pid, NULL, 0); + } + if (gfd[1] >= 0) + close(gfd[1]); /* EOF lets the holder go */ + if (started) + (void)wolfSSL_JoinThread(holder); + if (hfd[0] >= 0) + close(hfd[0]); + if (hfd[1] >= 0) + close(hfd[1]); + if (gfd[0] >= 0) + close(gfd[0]); + if (cfd[0] >= 0) + close(cfd[0]); + if (cfd[1] >= 0) + close(cfd[1]); + return ret; +} +#endif /* WC_TEST_SE050_FORK */ + #ifdef WC_RNG_HAVE_RBGC /* Post-init credited reseeds relabel RBGCStratum unless * WC_RNG_RBGC_STRATUM_IMMUTABLE (required for FIPS), wherein the stratum is diff --git a/wolfcrypt/test/test.h b/wolfcrypt/test/test.h index d6919564eae..b2093e0a080 100644 --- a/wolfcrypt/test/test.h +++ b/wolfcrypt/test/test.h @@ -61,8 +61,16 @@ (defined(__unix__) || defined(__linux__) || defined(__APPLE__)) #define WC_TEST_RNG_HOLD #endif +/* The SE05x port refuses a fork() child the parent's session, so a child + * whose DRBG hashes or seeds on the SE05x cannot reseed and draw. The fork + * tests below need a child that can. */ +#if defined(WOLFSSL_SE050) && \ + (defined(WOLFSSL_SE050_HASH) || !defined(WOLFSSL_SE050_NO_TRNG)) + #define WC_TEST_RNG_NO_FORK_CHILD +#endif /* The fork test needs a real process model on top of the handlers. */ -#if defined(WC_TEST_RNG_HOLD) && defined(WC_RNG_LOCK_ATFORK) +#if defined(WC_TEST_RNG_HOLD) && defined(WC_RNG_LOCK_ATFORK) && \ + !defined(WC_TEST_RNG_NO_FORK_CHILD) #define WC_TEST_RNG_AUTOFORK #endif /* fork() across a held WC_RNG.lock word: needs the word, a pid to compare, @@ -70,7 +78,7 @@ * orphan. */ #if defined(WC_RNG_HAVE_LOCK) && defined(HAVE_HASHDRBG) && \ defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \ - !defined(__STRICT_ANSI__) && \ + !defined(__STRICT_ANSI__) && !defined(WC_TEST_RNG_NO_FORK_CHILD) && \ (defined(__unix__) || defined(__linux__) || defined(__APPLE__)) #define WC_TEST_RNG_LOCKFORK #endif diff --git a/wolfssl/wolfcrypt/port/nxp/se050_port.h b/wolfssl/wolfcrypt/port/nxp/se050_port.h index b2bb519b203..f4920cf6e44 100644 --- a/wolfssl/wolfcrypt/port/nxp/se050_port.h +++ b/wolfssl/wolfcrypt/port/nxp/se050_port.h @@ -173,7 +173,9 @@ WOLFSSL_API sss_session_t* wc_se050_get_session(void); /** Return the low-level SE05x session, or NULL when none is configured. */ WOLFSSL_API pSe05xSession_t wc_se050_get_se05x_session(void); /** Acquire/release the SE05x session/transport lock. This is separate from - * the wolfCrypt hardware accelerator lock (wolfSSL_CryptHwMutexLock). */ + * the wolfCrypt hardware accelerator lock (wolfSSL_CryptHwMutexLock). + * wc_se050_lock() returns BAD_STATE_E in a fork() child of the process that + * configured the session, which must not use it (see README_SE050.md). */ WOLFSSL_API int wc_se050_lock(void); WOLFSSL_API void wc_se050_unlock(void); #ifdef WOLFSSL_SE050_INIT From 6483c7737f820a829e7fa9efb1b7cee769a94a7e Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 14:21:30 +0000 Subject: [PATCH 21/23] Keep options.h out of the SE050 port's SDK includes With the wolfSSL host crypto, ex_sss_boot.h pulls in the middleware's fsl_sss_wolfssl_types.h, which includes after settings.h has run. options.h then puts back macros that settings.h removed, such as WOLFSSL_SMALL_STACK_CACHE without WOLFSSL_SMALL_STACK, and ecc.h, first read after it, gave ecc_point an extra member in se050_port.c only. keyId and keyIdSet were then 8 bytes off from where ecc.c has them, so ECDH with an SE050 key ran in software with a zero scalar and failed with ECC_INF_E. Define WOLFSSL_NO_OPTIONS_H before the SDK include. Library objects take their configuration from CFLAGS. --- wolfcrypt/src/port/nxp/se050_port.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index 06828e64477..9f1f6616407 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -66,6 +66,16 @@ #define SE050_DEFAULT_PORT "/dev/i2c-1" #endif + /* With the wolfSSL host crypto, ex_sss_boot.h includes the middleware's + * fsl_sss_wolfssl_types.h, which includes . This file + * is a library object configured through CFLAGS and settings.h has + * already run, so options.h would put back macros that settings.h + * removed, such as WOLFSSL_SMALL_STACK_CACHE without WOLFSSL_SMALL_STACK. + * Headers first read after that point (ecc.h) would then lay out their + * structs differently from the rest of the library. */ + #ifndef WOLFSSL_NO_OPTIONS_H + #define WOLFSSL_NO_OPTIONS_H + #endif #include "ex_sss_boot.h" #if defined(SSS_HAVE_SE05X_AUTH_PLATFSCP03) && \ SSS_HAVE_SE05X_AUTH_PLATFSCP03 From d37095dfc81d89a72a19c13f6d6be8a10b5d2876 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 14:31:25 +0000 Subject: [PATCH 22/23] Keep the Hash DRBG's SHA-256 and SHA-512 off the SE050 With WOLFSSL_SE050_HASH every SHA-256 and SHA-512 went to the SE050: struct wc_Sha256 held only the SE050 context and neither file compiled a software hash. The Hash DRBG hashes V, C and the seed material, so its state crossed the I2C bus (in clear without SCP03), every generate cost SE050 APDUs, the DRBG hashed before an SCP03 session existed, and a fork() child, which the port refuses the parent's session, could not reseed. wc_InitRng() prefers the SHA-512 DRBG when SHA-512 is built, so both DRBGs are affected. Keep the software SHA-256 and SHA-512 compiled in and add a useSWCrypt flag next to se050Ctx in struct wc_Sha256 and struct wc_Sha512, as struct Aes has. Update and Final send an object to the SE050 unless the flag is set. New helpers in random.c initialize the DRBG's SHA-256 and SHA-512 objects and set it. All other hashes still go to the SE050, and SHA-224 and SHA-384 are unchanged. - sha256.c: drop the SE050 branch from the transform chain, so objects that hash in software use the platform's transform. Each software wc_InitSha256_ex() starts the object on the SE050. FinalRaw and Transform return NOT_COMPILED_IN for an SE050 object, and Reset frees its buffered message and keeps the flag. - sha512.c: the same, with the SE050 init in InitSha512_Family(). wc_Sha512FinalRaw() keeps its old SE050 behaviour. Correct the swapped #endif comments after wc_Sha512Transform(). - test.h: run the RNG fork tests again with WOLFSSL_SE050_HASH. Only the SE050 TRNG seed still keeps them out. - README_SE050.md: document that the DRBG hashes in software. --- wolfcrypt/src/port/nxp/README_SE050.md | 12 ++- wolfcrypt/src/random.c | 105 ++++++++++---------- wolfcrypt/src/sha256.c | 106 +++++++++++--------- wolfcrypt/src/sha512.c | 129 ++++++++++--------------- wolfcrypt/test/test.c | 2 +- wolfcrypt/test/test.h | 8 +- wolfssl/wolfcrypt/sha256.h | 9 +- wolfssl/wolfcrypt/sha512.h | 4 + 8 files changed, 188 insertions(+), 187 deletions(-) diff --git a/wolfcrypt/src/port/nxp/README_SE050.md b/wolfcrypt/src/port/nxp/README_SE050.md index daee47720d6..654857eae18 100644 --- a/wolfcrypt/src/port/nxp/README_SE050.md +++ b/wolfcrypt/src/port/nxp/README_SE050.md @@ -224,6 +224,10 @@ SHA2-384, SHA2-512) to the SE050. This is MUCH slower than using wolfCrypt software cryptography due to the I2C communication channel. This support is disabled by default unless this define explicitly enables it. +The SHA-256 or SHA-512 inside wolfCrypt's Hash DRBG stays in software either +way, so the DRBG state (V, C and seed material) never crosses the I2C bus and +generating random data sends no commands to the SE050. + **`WOLFSSL_SE050_CRYPT`** wolfSSL supports offloading symmetric crypto operations (AES-ECB/CBC) to the @@ -595,10 +599,10 @@ On systems with `getpid()`, the port records which process configured the session and refuses the session in any other process. In a forked child, `wc_se050_lock()` and every wolfCrypt operation that the build routes to the SE05x fail with an error (for example `BAD_STATE_E`, `BAD_MUTEX_E` or -`WC_HW_E`) and send nothing. The parent's session is not affected. With -`WOLFSSL_SE050_HASH` this includes the SHA-256 that the DRBG uses, and without -`WOLFSSL_SE050_NO_TRNG` it includes the seed, so a child cannot reseed or draw -from a `WC_RNG` in those builds either. +`WC_HW_E`) and send nothing. The parent's session is not affected. Without +`WOLFSSL_SE050_NO_TRNG` this includes the seed, so a child cannot reseed or +draw from a `WC_RNG` in those builds either. The DRBG's own hash runs in +software, also with `WOLFSSL_SE050_HASH`, so it does not stop a child. A child that needs the SE05x must set up its own session, and only once the parent no longer uses its session (for example after the parent of a diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index 463ee25e363..c28f73c82f8 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -1013,6 +1013,30 @@ static WARN_UNUSED_RESULT int wc_RNG_HealthTest_SHA512_ex_internal( * lives below in its own #ifdef WOLFSSL_DRBG_SHA512 section. */ #ifndef NO_SHA256 +/* Initialize one of the DRBG's SHA-256 objects. */ +static WARN_UNUSED_RESULT int Hash_DRBG_InitSha256(DRBG_internal* drbg, + wc_Sha256* sha) +{ + int ret; + +#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) + ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); +#else + (void)drbg; + ret = wc_InitSha256(sha); +#endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Hash on the host, not the SE05x. On the SE05x, V, C and the seed + * material would cross the bus (in clear without SCP03), every generate + * would cost APDUs, and a fork() child could not reseed: the port + * refuses it the parent's session. */ + if (ret == 0) { + sha->useSWCrypt = 1; + } +#endif + return ret; +} + /* Hash Derivation Function */ /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ static WARN_UNUSED_RESULT int Hash_df(DRBG_internal* drbg, byte* out, @@ -1072,11 +1096,7 @@ static WARN_UNUSED_RESULT int Hash_df(DRBG_internal* drbg, byte* out, ctr = 1; for (i = 0; i < len; i++) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha256(sha); - #endif + ret = Hash_DRBG_InitSha256(drbg, sha); if (ret != 0) break; #endif @@ -1953,11 +1973,7 @@ static WARN_UNUSED_RESULT int Hash_gen(DRBG_internal* drbg, byte* out, #endif for (i = 0; i < len; i++) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha256(sha); - #endif + ret = Hash_DRBG_InitSha256(drbg, sha); if (ret == 0) #endif ret = wc_Sha256Update(sha, data, DRBG_SEED_LEN); @@ -2115,11 +2131,7 @@ static WARN_UNUSED_RESULT int Hash_DRBG_Generate(DRBG_internal* drbg, DYNAMIC_TYPE_TMP_BUFFER, ret = MEMORY_E); if (ret == 0) { thisV = shadowV; - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha256(sha); - #endif + ret = Hash_DRBG_InitSha256(drbg, sha); } if (ret != 0) { @@ -2182,11 +2194,7 @@ static WARN_UNUSED_RESULT int Hash_DRBG_Generate(DRBG_internal* drbg, ret = Hash_gen(drbg, out, outSz, thisV); if (ret == DRBG_SUCCESS) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha256(sha); - #endif + ret = Hash_DRBG_InitSha256(drbg, sha); if (ret == 0) #endif ret = wc_Sha256Update(sha, &type, sizeof(type)); @@ -2312,11 +2320,7 @@ static WARN_UNUSED_RESULT int Hash_DRBG_Instantiate(DRBG_internal* drbg, #endif #ifdef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha256_ex(&drbg->sha256, drbg->heap, drbg->devId); - #else - ret = wc_InitSha256(&drbg->sha256); - #endif + ret = Hash_DRBG_InitSha256(drbg, &drbg->sha256); if (ret != 0) return ret; #endif @@ -2365,6 +2369,27 @@ static int Hash_DRBG_Uninstantiate(DRBG_internal* drbg) #define OUTPUT_BLOCK_LEN_SHA512 (WC_SHA512_DIGEST_SIZE) /* 64 bytes */ +/* Initialize one of the SHA-512 DRBG's SHA-512 objects. */ +static WARN_UNUSED_RESULT int Hash512_DRBG_InitSha512( + DRBG_SHA512_internal* drbg, wc_Sha512* sha) +{ + int ret; + +#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) + ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); +#else + (void)drbg; + ret = wc_InitSha512(sha); +#endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Hash on the host, as Hash_DRBG_InitSha256() does. */ + if (ret == 0) { + sha->useSWCrypt = 1; + } +#endif + return ret; +} + /* Hash Derivation Function using SHA-512 */ /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ static WARN_UNUSED_RESULT int Hash512_df(DRBG_SHA512_internal* drbg, byte* out, @@ -2431,11 +2456,7 @@ static WARN_UNUSED_RESULT int Hash512_df(DRBG_SHA512_internal* drbg, byte* out, ctr = 1; for (i = 0; i < len; i++) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha512(sha); - #endif + ret = Hash512_DRBG_InitSha512(drbg, sha); if (ret != 0) break; #endif @@ -2624,11 +2645,7 @@ static WARN_UNUSED_RESULT int Hash512_gen(DRBG_SHA512_internal* drbg, #endif for (i = 0; i < len; i++) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha512(sha); - #endif + ret = Hash512_DRBG_InitSha512(drbg, sha); if (ret == 0) #endif ret = wc_Sha512Update(sha, data, DRBG_SHA512_SEED_LEN); @@ -2740,11 +2757,7 @@ static WARN_UNUSED_RESULT int Hash512_DRBG_Generate(DRBG_SHA512_internal* drbg, DYNAMIC_TYPE_TMP_BUFFER, ret = MEMORY_E); if (ret == 0) { thisV = shadowV; - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha512(sha); - #endif + ret = Hash512_DRBG_InitSha512(drbg, sha); } if (ret != 0) { @@ -2808,11 +2821,7 @@ static WARN_UNUSED_RESULT int Hash512_DRBG_Generate(DRBG_SHA512_internal* drbg, ret = Hash512_gen(drbg, out, outSz, thisV); if (ret == DRBG_SUCCESS) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha512(sha); - #endif + ret = Hash512_DRBG_InitSha512(drbg, sha); if (ret == 0) #endif ret = wc_Sha512Update(sha, &type, sizeof(type)); @@ -2921,11 +2930,7 @@ static WARN_UNUSED_RESULT int Hash512_DRBG_Instantiate( #endif #ifdef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha512_ex(&drbg->sha512, drbg->heap, drbg->devId); - #else - ret = wc_InitSha512(&drbg->sha512); - #endif + ret = Hash512_DRBG_InitSha512(drbg, &drbg->sha512); if (ret != 0) return ret; #endif diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 89f12c97b19..9ab9014e9fd 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -170,6 +170,18 @@ on the specific device platform. #endif #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) #include + + /* The software implementation stays compiled in: wc_Sha256Update() and + * wc_Sha256Final() send an object to the SE05x unless its useSWCrypt is + * set. Each software wc_InitSha256_ex() below starts the object on the + * SE05x with this. Call it AFTER the NULL check. */ + #define SHA256_SE050_INIT(sha256, heap) \ + do { \ + (sha256)->useSWCrypt = 0; \ + (void)se050_hash_init(&(sha256)->se050Ctx, (heap)); \ + } while (0) +#else + #define SHA256_SE050_INIT(sha256, heap) WC_DO_NOTHING #endif #if FIPS_VERSION3_GE(6,0,0) @@ -292,7 +304,7 @@ on the specific device platform. defined(NO_WOLFSSL_RENESAS_TSIP_CRYPT_HASH)) && \ !defined(PSOC6_HASH_SHA2) && !defined(WOLFSSL_IMXRT_DCP) && !defined(WOLFSSL_SILABS_SE_ACCEL) && \ !defined(WOLFSSL_NXP_HASHCRYPT_SHA) && \ - !defined(WOLFSSL_KCAPI_HASH) && !defined(WOLFSSL_SE050_HASH) && \ + !defined(WOLFSSL_KCAPI_HASH) && \ ((!defined(WOLFSSL_RENESAS_SCEPROTECT) && \ !defined(WOLFSSL_RENESAS_RSIP)) \ || defined(NO_WOLFSSL_RENESAS_FSPSM_HASH)) && \ @@ -375,8 +387,17 @@ int wc_Sha256Reset(wc_Sha256* sha256) { { void* heap = sha256->heap; int devId = sha256->devId; + int ret; + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Init_ex starts the object on the SE05x: keep where it hashes. */ + byte useSWCrypt = sha256->useSWCrypt; + #endif wc_Sha256Free(sha256); - return wc_InitSha256_ex(sha256, heap, devId); + ret = wc_InitSha256_ex(sha256, heap, devId); + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + sha256->useSWCrypt = useSWCrypt; + #endif + return ret; } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA256) && \ @@ -387,6 +408,10 @@ int wc_Sha256Reset(wc_Sha256* sha256) { if (ret != 0) return ret; } +#endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Drop the message an SE05x object buffered; useSWCrypt stays. */ + se050_hash_free(&sha256->se050Ctx); #endif return InitSha256(sha256); } @@ -928,6 +953,7 @@ wc_static_assert(sizeof(Sha256TScratch) == WC_SHA256_TSCRATCH_SIZE); #endif WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); sha256->heap = heap; #ifdef WOLF_CRYPTO_CB sha256->devId = devId; @@ -1131,51 +1157,6 @@ wc_static_assert(sizeof(Sha256TScratch) == WC_SHA256_TSCRATCH_SIZE); !defined(WOLFSSL_QNX_CAAM) /* functions defined in wolfcrypt/src/port/caam/caam_sha256.c */ -#elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - - int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) - { - if (sha256 == NULL) { - return BAD_FUNC_ARG; - } - #ifdef WC_CTX_IS_ALIGNED - if (!WC_CTX_IS_ALIGNED(sha256, wc_Sha256)) { - return BAD_ALIGN_E; - } - #endif - WC_SILABS_CLEAR_HASH_CTX(sha256); - (void)devId; - - return se050_hash_init(&sha256->se050Ctx, heap); - } - - int wc_Sha256Update(wc_Sha256* sha256, const byte* data, word32 len) - { - if (sha256 == NULL) { - return BAD_FUNC_ARG; - } - if (data == NULL && len == 0) { - /* valid, but do nothing */ - return 0; - } - if (data == NULL) { - return BAD_FUNC_ARG; - } - - return se050_hash_update(&sha256->se050Ctx, data, len); - } - - int wc_Sha256Final(wc_Sha256* sha256, byte* hash) - { - int ret = 0; - if (sha256 == NULL || hash == NULL) { - return BAD_FUNC_ARG; - } - ret = se050_hash_final(&sha256->se050Ctx, hash, WC_SHA256_DIGEST_SIZE, - kAlgorithm_SSS_SHA256); - return ret; - } - #elif defined(WOLFSSL_AFALG_HASH) /* implemented in wolfcrypt/src/port/af_alg/afalg_hash.c */ @@ -1390,6 +1371,7 @@ int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) if (sha256 == NULL) return BAD_FUNC_ARG; WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); ret = InitSha256(sha256); if (ret != 0) return ret; @@ -1555,6 +1537,7 @@ int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) if (sha256 == NULL) return BAD_FUNC_ARG; WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); ret = InitSha256(sha256); if (ret != 0) return ret; @@ -1707,6 +1690,7 @@ int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) if (sha256 == NULL) return BAD_FUNC_ARG; WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); ret = InitSha256(sha256); if (ret != 0) return ret; @@ -1773,6 +1757,7 @@ int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) if (sha256 == NULL) return BAD_FUNC_ARG; WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); ret = InitSha256(sha256); if (ret != 0) return ret; @@ -1852,6 +1837,7 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, return BAD_ALIGN_E; #endif WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); ret = InitSha256(sha256); if (ret != 0) return ret; @@ -2302,6 +2288,11 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, return BAD_FUNC_ARG; } + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + if (!sha256->useSWCrypt) { + return se050_hash_update(&sha256->se050Ctx, data, len); + } + #endif #ifdef WOLF_CRYPTO_CB #ifndef WOLF_CRYPTO_CB_FIND if (sha256->devId != INVALID_DEVID) @@ -2527,6 +2518,12 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, if (sha256 == NULL || hash == NULL) { return BAD_FUNC_ARG; } + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE05x hash only buffers the message: no state to read out. */ + if (!sha256->useSWCrypt) { + return NOT_COMPILED_IN; + } + #endif #if defined(WOLFSSL_CHECK_MEM_ZERO) && defined(LITTLE_ENDIAN_ORDER) && \ !defined(WOLFSSL_WIDE_BYTE) wc_MemZero_Add("wc_Sha256FinalRaw digest", digest, sizeof(digest)); @@ -2561,6 +2558,15 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, return BAD_FUNC_ARG; } + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + if (!sha256->useSWCrypt) { + /* Resets the context on success. On failure the buffered + * message stays for wc_Sha256Free() to wipe and release. */ + return se050_hash_final(&sha256->se050Ctx, hash, + WC_SHA256_DIGEST_SIZE, + kAlgorithm_SSS_SHA256); + } + #endif #ifdef WOLF_CRYPTO_CB #ifndef WOLF_CRYPTO_CB_FIND if (sha256->devId != INVALID_DEVID) @@ -2613,6 +2619,12 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, if (sha256 == NULL || data == NULL) { return BAD_FUNC_ARG; } + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE05x hash keeps no digest state to transform. */ + if (!sha256->useSWCrypt) { + return NOT_COMPILED_IN; + } + #endif #if defined(WOLFSSL_ARMASM) || defined(WOLFSSL_RISCV_ASM) || \ (defined(WOLFSSL_PPC64_ASM) && defined(LITTLE_ENDIAN_ORDER)) diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index 1fcfaef790b..85e7ba59b7b 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -292,77 +292,6 @@ wc_static_assert(sizeof(Sha512TScratch) == WC_SHA512_TSCRATCH_SIZE); #elif defined(MAX3266X_SHA) /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ -#elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - int wc_InitSha512(wc_Sha512* sha512) - { - int ret; - if (sha512 == NULL) - return BAD_FUNC_ARG; - ret = se050_hash_init(&sha512->se050Ctx, NULL); -#if defined(WOLFSSL_SHA512_HASHTYPE) - if (ret == 0) { - sha512->hashType = WC_HASH_TYPE_SHA512; - } -#endif - return ret; - } - int wc_InitSha512_ex(wc_Sha512* sha512, void* heap, int devId) - { - int ret; - if (sha512 == NULL) { - return BAD_FUNC_ARG; - } - (void)devId; - ret = se050_hash_init(&sha512->se050Ctx, heap); -#if defined(WOLFSSL_SHA512_HASHTYPE) - if (ret == 0) { - sha512->hashType = WC_HASH_TYPE_SHA512; - } -#endif - return ret; - } - int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) - { - if (sha512 == NULL) { - return BAD_FUNC_ARG; - } - if (data == NULL && len == 0) { - /* valid, but do nothing */ - return 0; - } - if (data == NULL) { - return BAD_FUNC_ARG; - } - - return se050_hash_update(&sha512->se050Ctx, data, len); - } - int wc_Sha512Final(wc_Sha512* sha512, byte* hash) - { - int ret = 0; - if (sha512 == NULL || hash == NULL) { - return BAD_FUNC_ARG; - } - ret = se050_hash_final(&sha512->se050Ctx, hash, WC_SHA512_DIGEST_SIZE, - kAlgorithm_SSS_SHA512); - return ret; - } - int wc_Sha512FinalRaw(wc_Sha512* sha512, byte* hash) - { - int ret = 0; - if (sha512 == NULL || hash == NULL) { - return BAD_FUNC_ARG; - } - ret = se050_hash_final(&sha512->se050Ctx, hash, WC_SHA512_DIGEST_SIZE, - kAlgorithm_SSS_SHA512); - return ret; - } - void wc_Sha512Free(wc_Sha512* sha512) - { - if (sha512 == NULL) { - return; - } - se050_hash_free(&sha512->se050Ctx); - } #elif defined(STM32_HASH_SHA512) /* Supports CubeMX HAL or Standard Peripheral Library */ @@ -1038,8 +967,17 @@ int wc_Sha512Reset(wc_Sha512* sha512) { { void* heap = sha512->heap; int devId = sha512->devId; + int ret; + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Init_ex starts the object on the SE05x: keep where it hashes. */ + byte useSWCrypt = sha512->useSWCrypt; + #endif wc_Sha512Free(sha512); - return wc_InitSha512_ex(sha512, heap, devId); + ret = wc_InitSha512_ex(sha512, heap, devId); + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + sha512->useSWCrypt = useSWCrypt; + #endif + return ret; } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA512) && \ @@ -1050,6 +988,10 @@ int wc_Sha512Reset(wc_Sha512* sha512) { if (ret != 0) return ret; } +#endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Drop the message an SE05x object buffered; useSWCrypt stays. */ + se050_hash_free(&sha512->se050Ctx); #endif return InitSha512(sha512); } @@ -1968,6 +1910,12 @@ static int InitSha512_Family(wc_Sha512* sha512, void* heap, int devId, XMEMSET(sha512, 0, sizeof(*sha512)); sha512->heap = heap; +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The software implementation stays compiled in: wc_Sha512Update() and + * wc_Sha512Final() send the object to the SE05x unless useSWCrypt (zero + * here) gets set. */ + (void)se050_hash_init(&sha512->se050Ctx, heap); +#endif #ifdef WOLFSSL_SMALL_STACK_CACHE /* This allocation combines the customary W buffer used by * _Transform_Sha512() with additional buffer space used by @@ -2435,6 +2383,11 @@ int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) return BAD_FUNC_ARG; } +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + if (!sha512->useSWCrypt) { + return se050_hash_update(&sha512->se050Ctx, data, len); + } +#endif #ifdef WOLF_CRYPTO_CB #ifndef WOLF_CRYPTO_CB_FIND if (sha512->devId != INVALID_DEVID) @@ -2468,8 +2421,6 @@ int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) #elif defined(WOLFSSL_RENESAS_RSIP) && \ !defined(NO_WOLFSSL_RENESAS_FSPSM_HASH) /* functions defined in wolfcrypt/src/port/renesas/renesas_fspsm_sha.c */ -#elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - #elif defined(MAX3266X_SHA) /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ #elif defined(STM32_HASH_SHA512) @@ -2695,8 +2646,6 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) #if defined(WOLFSSL_KCAPI_HASH) /* functions defined in wolfcrypt/src/port/kcapi/kcapi_hash.c */ -#elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - #elif defined(WOLFSSL_RENESAS_RSIP) && \ !defined(NO_WOLFSSL_RENESAS_FSPSM_HASH) /* functions defined in wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c */ @@ -2742,6 +2691,13 @@ static int Sha512FinalRaw(wc_Sha512* sha512, byte* hash, word32 digestSz) int wc_Sha512FinalRaw(wc_Sha512* sha512, byte* hash) { +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* An SE05x object has no raw state: unchanged, it finishes the hash. */ + if ((sha512 != NULL) && (hash != NULL) && !sha512->useSWCrypt) { + return se050_hash_final(&sha512->se050Ctx, hash, WC_SHA512_DIGEST_SIZE, + kAlgorithm_SSS_SHA512); + } +#endif return Sha512FinalRaw(sha512, hash, WC_SHA512_DIGEST_SIZE); } @@ -2791,6 +2747,14 @@ static int Sha512_Family_Final(wc_Sha512* sha512, byte* hash, size_t digestSz, #ifndef STM32_HASH_SHA512 int wc_Sha512Final(wc_Sha512* sha512, byte* hash) { +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + if ((sha512 != NULL) && (hash != NULL) && !sha512->useSWCrypt) { + /* Resets the context on success. On failure the buffered message + * stays for wc_Sha512Free() to wipe and release. */ + return se050_hash_final(&sha512->se050Ctx, hash, WC_SHA512_DIGEST_SIZE, + kAlgorithm_SSS_SHA512); + } +#endif return Sha512_Family_Final(sha512, hash, WC_SHA512_DIGEST_SIZE, InitSha512); } #endif @@ -2801,7 +2765,6 @@ int wc_Sha512Final(wc_Sha512* sha512, byte* hash) /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ #else -#if !defined(WOLFSSL_SE050) || !defined(WOLFSSL_SE050_HASH) int wc_InitSha512(wc_Sha512* sha512) { int devId = INVALID_DEVID; @@ -2876,10 +2839,12 @@ void wc_Sha512Free(wc_Sha512* sha512) #if defined(PSOC6_HASH_SHA2) wc_Psoc6_Sha_Free(); #endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&sha512->se050Ctx); +#endif ForceZero(sha512, sizeof(*sha512)); } -#endif #if (defined(OPENSSL_EXTRA) || defined(HAVE_CURL)) \ && !defined(WOLFSSL_KCAPI_HASH) @@ -2898,6 +2863,12 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) if (sha == NULL || data == NULL) { return BAD_FUNC_ARG; } +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE05x hash keeps no digest state to transform. */ + if (!sha->useSWCrypt) { + return NOT_COMPILED_IN; + } +#endif #if defined(WOLFSSL_SMALL_STACK_CACHE) @@ -2963,8 +2934,8 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) return ret; } #endif /* OPENSSL_EXTRA */ +#endif /* !MAX3266X_SHA */ #endif /* WOLFSSL_SHA512 */ -#endif /* !WOLFSSL_SE050 || !WOLFSSL_SE050_HASH */ /* -------------------------------------------------------------------------- */ diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 704f013e826..cf9b95ed6f1 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -33506,7 +33506,7 @@ WOLFSSL_TEST_SUBROUTINE wc_test_ret_t se050_fork_test(void) else if (rc == WC_NO_ERR_TRACE(BAD_STATE_E)) res = 0; #if defined(WOLFSSL_SE050_HASH) && !defined(NO_SHA256) - /* the DRBG's hash, which hung the RNG fork test */ + /* a SHA-256 on the SE05x must be refused as well */ if ((res == 0) && (wc_Sha256Hash((const byte*)"abc", 3, digest) == 0)) res = 2; #endif diff --git a/wolfcrypt/test/test.h b/wolfcrypt/test/test.h index b2093e0a080..3d2521b0a86 100644 --- a/wolfcrypt/test/test.h +++ b/wolfcrypt/test/test.h @@ -62,10 +62,10 @@ #define WC_TEST_RNG_HOLD #endif /* The SE05x port refuses a fork() child the parent's session, so a child - * whose DRBG hashes or seeds on the SE05x cannot reseed and draw. The fork - * tests below need a child that can. */ -#if defined(WOLFSSL_SE050) && \ - (defined(WOLFSSL_SE050_HASH) || !defined(WOLFSSL_SE050_NO_TRNG)) + * whose DRBG seeds on the SE05x cannot reseed and draw. The fork tests below + * need a child that can. (The DRBG hashes in software, also with + * WOLFSSL_SE050_HASH.) */ +#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_TRNG) #define WC_TEST_RNG_NO_FORK_CHILD #endif /* The fork test needs a real process model on top of the handlers. */ diff --git a/wolfssl/wolfcrypt/sha256.h b/wolfssl/wolfcrypt/sha256.h index c3190d32d07..89b33e38ea5 100644 --- a/wolfssl/wolfcrypt/sha256.h +++ b/wolfssl/wolfcrypt/sha256.h @@ -220,8 +220,6 @@ struct wc_Sha256 { #ifdef FREESCALE_LTC_SHA ltc_hash_ctx_t ctx; -#elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - SE050_HASH_Context se050Ctx; #elif defined(STM32_HASH_SHA2) STM32_HASH_Context stmCtx; #elif defined(WOLFSSL_SILABS_SE_ACCEL) @@ -255,6 +253,13 @@ struct wc_Sha256 { #if defined(WOLFSSL_SILABS_CRYPTOCB) wc_silabs_sha_t silabsCtx; #endif /* WOLFSSL_SILABS_CRYPTOCB */ +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Also alongside the software members: a SHA-256 object hashes on the + * SE05x unless useSWCrypt is set, which the Hash DRBG does to keep its + * state off the bus. SHA-224 always uses the SE05x. */ + SE050_HASH_Context se050Ctx; + byte useSWCrypt; /* Use SW hash instead of SE050 */ +#endif void* heap; #ifdef WOLFSSL_PIC32MZ_HASH hashUpdCache cache; /* cache for updates */ diff --git a/wolfssl/wolfcrypt/sha512.h b/wolfssl/wolfcrypt/sha512.h index ad7eef309ea..4225883e814 100644 --- a/wolfssl/wolfcrypt/sha512.h +++ b/wolfssl/wolfcrypt/sha512.h @@ -194,7 +194,11 @@ struct wc_Sha512 { wolfssl_KCAPI_Hash kcapi; #endif #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* SHA-512 objects hash on the SE05x unless useSWCrypt is set, which the + * Hash DRBG does to keep its state off the bus. SHA-384 always uses the + * SE05x. */ SE050_HASH_Context se050Ctx; + byte useSWCrypt; /* Use SW hash instead of SE050 */ #endif #if defined(WOLFSSL_HASH_KEEP) byte* msg; From b0640fed6076bcb7bf85fc8098ff0fc4bbcdaeb1 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 30 Nov 2026 14:31:51 +0000 Subject: [PATCH 23/23] Fix raw hash APIs and context init for SE050 hashes With WOLFSSL_SE050_HASH the SE050 buffers the whole message and keeps no intermediate digest, but: - wc_ShaFinalRaw() and wc_Sha512FinalRaw() returned the finished (padded) digest instead of raw state, so a caller such as the TLS constant-time HMAC check would compute wrong values. - wc_ShaTransform() was not defined, so an OPENSSL_EXTRA build did not link. - The SE050 wc_InitSha_ex(), wc_InitSha224_ex() and wc_InitSha384_ex() set only the SE050 context. Free and Copy also read W, heap and devId, so with WOLFSSL_SMALL_STACK_CACHE wc_Sha224Free() and wc_Sha384Free() freed an uninitialized W pointer. Define WOLFSSL_NO_HASH_RAW for WOLFSSL_SE050_HASH, so TLS, LMS and XMSS use the full hash calls. Return NOT_COMPILED_IN from wc_ShaFinalRaw(), wc_ShaTransform() and, for an object on the SE050, wc_Sha512FinalRaw(). Zero the object in the SE050 inits and set heap and devId. --- wolfcrypt/src/port/nxp/README_SE050.md | 6 ++++++ wolfcrypt/src/sha.c | 26 +++++++++++++++++++++----- wolfcrypt/src/sha256.c | 9 ++++++++- wolfcrypt/src/sha512.c | 13 ++++++++++--- wolfssl/wolfcrypt/settings.h | 8 ++++++++ 5 files changed, 53 insertions(+), 9 deletions(-) diff --git a/wolfcrypt/src/port/nxp/README_SE050.md b/wolfcrypt/src/port/nxp/README_SE050.md index 654857eae18..f05d77a2f60 100644 --- a/wolfcrypt/src/port/nxp/README_SE050.md +++ b/wolfcrypt/src/port/nxp/README_SE050.md @@ -228,6 +228,12 @@ The SHA-256 or SHA-512 inside wolfCrypt's Hash DRBG stays in software either way, so the DRBG state (V, C and seed material) never crosses the I2C bus and generating random data sends no commands to the SE050. +The SE050 keeps no intermediate digest, so the raw hash accessors +(`wc_ShaFinalRaw()`, `wc_Sha512FinalRaw()`, `wc_Sha256FinalRaw()` and the +`wc_Sha*Transform()` functions) return `NOT_COMPILED_IN` for a hash on the +SE050. This define therefore also defines `WOLFSSL_NO_HASH_RAW`, so TLS, LMS +and XMSS use the full hash calls. + **`WOLFSSL_SE050_CRYPT`** wolfSSL supports offloading symmetric crypto operations (AES-ECB/CBC) to the diff --git a/wolfcrypt/src/sha.c b/wolfcrypt/src/sha.c index 5874184c945..7536a94e3c6 100644 --- a/wolfcrypt/src/sha.c +++ b/wolfcrypt/src/sha.c @@ -403,8 +403,14 @@ if (sha == NULL) { return BAD_FUNC_ARG; } - WC_SILABS_CLEAR_HASH_CTX(sha); + /* Only se050Ctx hashes, but Free and Copy read the other fields. */ + XMEMSET(sha, 0, sizeof(*sha)); + sha->heap = heap; + #ifdef WOLF_CRYPTO_CB + sha->devId = devId; + #else (void)devId; + #endif return se050_hash_init(&sha->se050Ctx, heap); } @@ -429,14 +435,24 @@ } int wc_ShaFinalRaw(wc_Sha* sha, byte* hash) { - int ret = 0; if (sha == NULL || hash == NULL) { return BAD_FUNC_ARG; } - ret = se050_hash_final(&sha->se050Ctx, hash, WC_SHA_DIGEST_SIZE, - kAlgorithm_SSS_SHA1); - return ret; + /* The SE05x hash only buffers the message: no state to read out. + * (settings.h defines WOLFSSL_NO_HASH_RAW, so nothing in wolfSSL + * calls this.) */ + return NOT_COMPILED_IN; } +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) + int wc_ShaTransform(wc_Sha* sha, const unsigned char* data) + { + if (sha == NULL || data == NULL) { + return BAD_FUNC_ARG; + } + /* The SE05x hash keeps no digest state to transform. */ + return NOT_COMPILED_IN; + } +#endif #elif defined(WOLFSSL_HAVE_PSA) && !defined(WOLFSSL_PSA_NO_HASH) /* implemented in wolfcrypt/src/port/psa/psa_hash.c */ diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 9ab9014e9fd..cdc1073ee65 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -2892,8 +2892,15 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, return BAD_ALIGN_E; } #endif - WC_SILABS_CLEAR_HASH_CTX(sha224); + /* Only se050Ctx hashes, but Free and Copy read the other fields, + * such as the W scratch pointer. */ + XMEMSET(sha224, 0, sizeof(*sha224)); + sha224->heap = heap; + #ifdef WOLF_CRYPTO_CB + sha224->devId = devId; + #else (void)devId; + #endif return se050_hash_init(&sha224->se050Ctx, heap); } diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index 85e7ba59b7b..b61fe23c867 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -2692,10 +2692,9 @@ static int Sha512FinalRaw(wc_Sha512* sha512, byte* hash, word32 digestSz) int wc_Sha512FinalRaw(wc_Sha512* sha512, byte* hash) { #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - /* An SE05x object has no raw state: unchanged, it finishes the hash. */ + /* The SE05x hash only buffers the message: no state to read out. */ if ((sha512 != NULL) && (hash != NULL) && !sha512->useSWCrypt) { - return se050_hash_final(&sha512->se050Ctx, hash, WC_SHA512_DIGEST_SIZE, - kAlgorithm_SSS_SHA512); + return NOT_COMPILED_IN; } #endif return Sha512FinalRaw(sha512, hash, WC_SHA512_DIGEST_SIZE); @@ -2952,7 +2951,15 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) if (sha384 == NULL) { return BAD_FUNC_ARG; } + /* Only se050Ctx hashes, but Free and Copy read the other fields, + * such as the W scratch pointer. */ + XMEMSET(sha384, 0, sizeof(*sha384)); + sha384->heap = heap; + #ifdef WOLF_CRYPTO_CB + sha384->devId = devId; + #else (void)devId; + #endif return se050_hash_init(&sha384->se050Ctx, heap); } int wc_Sha384Update(wc_Sha384* sha384, const byte* data, word32 len) diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 3de85c3e59e..875c3c0ce92 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -5414,6 +5414,14 @@ blinding by defining WC_BLINDING_NO_RNG_ACKNOWLEDGE_WEAKNESS." #define WOLFSSL_NO_HASH_RAW #endif +/* The SE05x hash buffers the whole message and keeps no intermediate digest, + * so the raw accessors (wc_Sha*FinalRaw(), wc_Sha*Transform()) cannot serve + * it. TLS, LMS and XMSS then use the full hash calls instead. */ +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + #undef WOLFSSL_NO_HASH_RAW + #define WOLFSSL_NO_HASH_RAW +#endif + #if defined(HAVE_XCHACHA) && !defined(HAVE_CHACHA) /* XChacha requires ChaCha */ #undef HAVE_XCHACHA