Skip to content

Fix SE050/SE051 port bugs in hashing, AES, RSA-OAEP, Ed25519 and fork handling - #12318

Open
LinuxJedi wants to merge 23 commits into
wolfSSL:masterfrom
LinuxJedi:fenrir-se05x-fixes
Open

LinuxJedi wants to merge 23 commits into
wolfSSL:masterfrom
LinuxJedi:fenrir-se05x-fixes

Conversation

@LinuxJedi

@LinuxJedi LinuxJedi commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Description

Fixes for the NXP SE050/SE051 port. Most are Fenrir findings (the F-ID is
in the commit subject); the rest are bugs found while testing those fixes
on a real SE051. One commit per fix, and each commit message has the
details.

Hashing (WOLFSSL_SE050_HASH):

  • F-1970: a zero-length hash update is a no-op instead of BAD_FUNC_ARG.
  • F-11174, F-11175: NULL context and digest checks in the SHA-1/224/256/384/512
    wrappers and in the port. wc_Sha512Free(NULL) no longer crashes.
  • The SHA-2 Copy functions deep-copy the buffered message. Before, the copy
    shared the original's buffer, so wc_Sha256GetHash() and friends left the
    original pointing at freed memory (use after free, then double free). This
    also replaces the undefined PRINTF() in se050_hash_copy().
  • F-12323: the buffered message, which includes the HMAC ipad/opad blocks, is
    wiped before it is freed.
  • wc_Sha224Free() frees and wipes the SE050 message buffer, and the SHA-2
    Copy functions clean up the destination when a copy step fails.
  • The Hash DRBG's SHA-256 and SHA-512 run in software. Before, with
    WOLFSSL_SE050_HASH, the DRBG state crossed the I2C bus (in clear without
    SCP03), every generate cost APDUs, and the DRBG hashed before an SCP03
    session existed. All other hashes still go to the SE050.
  • WOLFSSL_SE050_HASH defines WOLFSSL_NO_HASH_RAW. The SE050 keeps no
    intermediate state, so wc_ShaFinalRaw() and wc_Sha512FinalRaw() returned
    the padded digest; they now return NOT_COMPILED_IN, and TLS, LMS and XMSS
    use the full hash calls. wc_ShaTransform() is defined, so OPENSSL_EXTRA
    builds link, and the SE050 SHA-1/224/384 inits zero the object.

AES (WOLFSSL_SE050_CRYPT):

  • F-11245, F-12324: the SE key object is released when storing the key fails
    and when the Aes is freed. Before, every wc_AesSetKey()/wc_AesFree()
    cycle left an object allocated on the SE.
  • Each AES call is a stateless CipherOneShot. The SE05x keeps one crypto object
    per cipher mode for the whole session, so the per-Aes cipher contexts were
    shared: two Aes objects in use at once, such as the read and write keys of
    a TLS connection, gave wrong output with no error. aes_ctx and
    ctxInitDone are removed from struct Aes (SE050 builds only).
  • wc_AesEcbEncrypt()/wc_AesEcbDecrypt() go to the SE. They ran software AES
    with an empty key schedule, which also broke AES-GCM and AES-CTR.
  • The per-call key lookup APDUs are gone. A single block is 1 APDU instead of
    3, and the wolfCrypt AES-GCM test on the SE051 takes 244 s instead of 436 s.
    A new AES key skips object IDs that are already in use, so it never
    overwrites or deletes an existing object.

RSA:

  • F-15216: the SE050 no longer silently swaps other OAEP parameters for
    OAEP-SHA1 with an empty label. Other parameters are padded on the host and
    the SE does the raw RSA operation. SE050 keys larger than RSA_MAX_SIZE are
    refused on that path.

EdDSA:

  • F-9983: WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN returned a positive 27 on a
    detected key change and left the signature in place. It now returns
    SIG_VERIFY_E and wipes the signature, in ed25519.c and ed448.c, and
    --enable-faultharden and CMake WOLFSSL_FAULTHARDEN turn it on. This one
    is not SE050 specific.
  • Ed25519 sign and verify of an empty message work on the SE051. Plug&Trust
    leaves out the empty input TLV, which the applet rejects with 0x6A80. This
    failed the first RFC 8032 test vector in ed25519_test and cryptocb_test.

Port:

  • A fork() child is refused the parent's SE05x session: wc_se050_lock()
    returns BAD_STATE_E instead of waiting on a mutex the parent's threads may
    hold or interleaving APDUs on the parent's session. The child can open a
    session of its own. The RNG fork test hung on this with WOLFSSL_SE050_HASH.
    A new test forks while another thread holds the port lock.
  • se050_port.c no longer picks up wolfssl/options.h through the SDK's
    ex_sss_boot.h. It changed ecc_point's layout in that file only (for
    example with WOLFSSL_SMALL_STACK_CACHE), so ECDH with an SE050 key failed
    with ECC_INF_E.

CMAC:

  • F-15132: the Rust wrapper and the C one-shots zero the Cmac before init, so
    useSWCrypt is not read from uninitialized memory.

Testing

  • Real SE051 (applet 7.2) on an STM32U585 board, with WOLFSSL_SE050_HASH and
    WOLFSSL_SE050_CRYPT. The wolfCrypt tests for hashing, HMAC, RSA, ECC, AES
    (all modes), GMAC, key wrap, CMAC, PKCS#7, Ed25519 and crypto callbacks pass
    and leave no objects on the SE. Extra checks compare SE AES against software
    AES: interleaved Aes objects, re-keying, CBC chaining across calls, inputs
    over 448 bytes, and GCM.
    The same checks also pass over a platform SCP03 session.
  • SE050 simulator: default flags, -DWOLFSSL_NO_RSA_SW -DWOLFSSL_NO_ECC_SW,
    -DWOLFSSL_SE050_ONLY_KEY_ID, and the full wolfCrypt test with
    WOLFSSL_SE050_HASH and WOLFSSL_SE050_CRYPT, with and without
    WOLFSSL_SMALL_STACK_CACHE, including the RNG fork tests.
  • Host default build: testwolfcrypt passes.

The SE050 hash tests send TLVs with the 0x81 length form, which the SE050
simulator rejects until wolfSSL/simulators#28 is merged.

Checklist

  • added tests
  • updated/added doxygen
  • updated appropriate READMEs
  • Updated manual and documentation

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.
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.
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.
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.
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.
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.
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.
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.
…ltharden

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.
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.
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.
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.
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.
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.
Copilot AI balanced review requested due to automatic review settings November 30, 2026 08:39
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical issues can cause an RSA stack-buffer overflow and unintended deletion of pre-existing secure-element objects.

4 open issues
What changed in this PR

This PR fixes cryptographic correctness and resource-management issues in wolfCrypt’s NXP SE050/SE051 integration, and strengthens software EdDSA signing checks.

Changes:

  • Adds hash argument checks, independent message-buffer copies, and sensitive-data cleanup.
  • Reworks hardware AES operations and key cleanup, preserves RSA-OAEP parameters, and supports empty-message Ed25519 operations.
  • Enables EdDSA key-change checks through fault-hardening options and initializes CMAC backend selection safely.
File Description
wrapper/​rust/​wolfssl-wolfcrypt/​src/​cmac.rs Zero-initializes the native CMAC context.
wolfssl/​wolfcrypt/​aes.h Removes shared SE050 cipher-context fields.
wolfcrypt/​test/​test.c Updates OAEP parameter and invalid-label tests.
wolfcrypt/​src/​sha512.c Adds argument checks and SE050 deep copies for SHA-384/512.
wolfcrypt/​src/​sha256.c Adds argument checks and SE050 deep copies for SHA-224/256.
wolfcrypt/​src/​sha.c Validates SHA-1 context and output pointers.
wolfcrypt/​src/​rsa.c Adds host OAEP padding for non-native SE050 parameters.
wolfcrypt/​src/​port/​nxp/​se050_port.c Revises hash cleanup, AES operations, OAEP validation, and empty-message Ed25519 handling.
wolfcrypt/​src/​ed448.c Corrects key-change errors and wipes rejected signatures.
wolfcrypt/​src/​ed25519.c Corrects key-change errors and wipes rejected signatures.
wolfcrypt/​src/​cmac.c Initializes backend selection in CMAC one-shot helpers.
wolfcrypt/​src/​aes.c Routes SE050 ECB operations to hardware.
configure.ac Enables EdDSA checks with Autotools fault hardening.
CMakeLists.txt Enables EdDSA checks with CMake fault hardening.
cmake/​options.h.in Exports the EdDSA checking feature macro.

Review effort: Balanced

Comment thread wolfcrypt/src/port/nxp/se050_port.c Resolved
Comment thread wolfcrypt/src/rsa.c Resolved
Comment thread wolfcrypt/src/sha256.c Resolved
Comment thread wolfcrypt/src/sha256.c Resolved
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.
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.
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.
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.

@wolfSSL-Fenrir-bot wolfSSL-Fenrir-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fenrir Automated Review — PR #12318

Scan targets checked: wolfcrypt-src, wolfcrypt-bugs, wolfcrypt-port-bugs, wolfcrypt-rs-src, wolfcrypt-rs-bugs, wolfssl-src, wolfssl-bugs
Not reviewed (no scan target covers them): CMakeLists.txt, cmake/options.h.in, configure.ac
Coverage: 12 of 12 in-scope changed file(s) opened by the reviewer

Findings: 2
2 finding(s) posted as inline comments (see file-level comments below)

This review was generated automatically by Fenrir. Reported findings require changes before merge.

Review tier: Max

Comment thread wolfcrypt/src/sha256.c Resolved
Comment thread wolfcrypt/src/port/nxp/se050_port.c Resolved
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.

@wolfSSL-Fenrir-bot wolfSSL-Fenrir-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fenrir Automated Review — PR #12318

Scan targets checked: wolfcrypt-src, wolfcrypt-bugs, wolfcrypt-port-bugs
Unchanged since last review (not re-run): wolfcrypt-rs-src, wolfcrypt-rs-bugs, wolfssl-src, wolfssl-bugs
Not reviewed (no scan target covers them): CMakeLists.txt, cmake/options.h.in, configure.ac
Coverage: 4 of 4 in-scope changed file(s) opened by the reviewer

Fenrir result: Approved ✅

No new issues found in the changed files.

Advisory only — this automated result does not count as a GitHub approval.

Review tier: Lite

@wolfSSL-Fenrir-bot
wolfSSL-Fenrir-bot dismissed their stale review November 30, 2026 14:18

Fenrir's latest completed scan found no issues; clearing the prior automated change request.

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.
With the wolfSSL host crypto, ex_sss_boot.h pulls in the middleware's
fsl_sss_wolfssl_types.h, which includes <wolfssl/options.h> 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.
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.
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.
@LinuxJedi LinuxJedi changed the title Fix SE050/SE051 port bugs in hashing, AES, RSA-OAEP and Ed25519 Fix SE050/SE051 port bugs in hashing, AES, RSA-OAEP, Ed25519 and fork handling Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants