Skip to content

Fix entropy_mutex ownership tracking & re-init race - #11645

Open
stenslae wants to merge 2 commits into
wolfSSL:masterfrom
stenslae:audit-entropy-mutex
Open

stenslae wants to merge 2 commits into
wolfSSL:masterfrom
stenslae:audit-entropy-mutex

Conversation

@stenslae

@stenslae stenslae commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Description

Fixes a re-initialization race in Entropy_Init().

  • Swapped wc_InitMutex() for wc_local_InitMutexOnce(), so an active mutex is never re-initialized.
  • Added Entropy_SetupAndLock(), which creates the mutex, takes the lock and sets up SHA-3 under it. wc_Entropy_Get(), wc_Entropy_GetRawEntropy(), wc_Entropy_OnDemandTest() and Entropy_Init() all call it. This replaces the old FIPS-only lazy init in wc_Entropy_Get(), which checked entropy_memuse_initialized without the lock.
  • Entropy_Init() reruns the startup health test until one passes.
  • Entropy_Final() frees the mutex whenever it was created, even if init failed. It then resets entropy_mutex_init so a later Entropy_Init() creates the mutex again.
  • Added WC_MUTEX_READY_ONCE to wc_port.h and used it in place of the hard-coded 2 in wc_local_InitMutexOnce().

The mutex-ownership tracking from F-7091, F-7419 and F-8169 was originally part of this PR and is now in master via #11707.

Checklist

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

@stenslae stenslae self-assigned this Oct 5, 2026
Copilot AI balanced review requested due to automatic review settings October 5, 2026 18:35
@github-actions

github-actions Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

zephyr-frdm_rw612

  • FLASH: datas +16 B, log_const_area -8 B, rodata +108 B, text +13,496 B (+4.8%, 296,076 B / 67,108,864 B, total: 0% used)
  • RAM: bss +49 B, datas +16 B (+0.1%, 58,423 B / 983,040 B, total: 6% used)

No memory changes detected for:


Catch memory regressions in CI with MemBrowse. Free for open source.

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.

Copilot review overview

🔵 Needs a closer look

Entropy-source synchronization changes need platform-aware human review and stronger concurrency regression coverage.

Review effort: Balanced
Findings: 2 Medium severity

Open (2)
What changed in this PR

Hardens wolfCrypt’s memory-based entropy source against mutex ownership and re-initialization errors.

Changes:

  • Guards mutex release and counter-thread shutdown with ownership tracking.
  • Uses one-time mutex initialization and resets its flag during finalization.
  • Adds whitebox lifecycle and failure-path tests.
File Description
wolfcrypt/​src/​wolfentropy.c Updates mutex ownership, initialization, and cleanup handling.
tests/​unit-mcdc/​test_wolfentropy_whitebox.c Adds re-initialization, lock-refusal, and held-mutex cleanup checks.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@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 #11645

Scan targets checked: wolfcrypt-src, wolfcrypt-bugs, wolfssl-bugs
Coverage: 2 of 2 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

@stenslae
stenslae force-pushed the audit-entropy-mutex branch from 3479616 to 9c11a59 Compare October 5, 2026 19:39
@stenslae
stenslae requested review from wolfSSL-Fenrir-bot and a balanced review from Copilot October 5, 2026 19:39

@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 #11645

Scan targets checked: wolfssl-bugs
Unchanged since last review (not re-run): wolfcrypt-src, wolfcrypt-bugs
Coverage: 1 of 1 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

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.

Copilot review overview

🟡 Changes recommended

The new on-demand test baseline can falsely report a regression when the threaded entropy counter is stopped.

Review effort: Balanced
Findings: 1 Medium severity

Open (1)
Resolved since last review (2)

@stenslae
stenslae force-pushed the audit-entropy-mutex branch from 9c11a59 to 1b65c7a Compare October 5, 2026 20:02
@stenslae
stenslae requested review from wolfSSL-Fenrir-bot and a balanced review from Copilot October 5, 2026 20:02

@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 #11645

Scan targets checked: wolfssl-bugs
Unchanged since last review (not re-run): wolfcrypt-src, wolfcrypt-bugs
Coverage: 1 of 1 in-scope changed file(s) opened by the reviewer

Findings: 1
1 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: Lite

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.

@stenslae
stenslae force-pushed the audit-entropy-mutex branch from 1b65c7a to eb4b2dd Compare October 7, 2026 21:32
@stenslae
stenslae requested review from wolfSSL-Fenrir-bot and a balanced review from Copilot October 7, 2026 21:35

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.

@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 #11645

Scan targets checked: wolfssl-bugs
Unchanged since last review (not re-run): wolfcrypt-src, wolfcrypt-bugs
Coverage: 1 of 1 in-scope changed file(s) opened by the reviewer

Findings: 1
1 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: Lite

@stenslae
stenslae force-pushed the audit-entropy-mutex branch from eb4b2dd to 52173d9 Compare October 9, 2026 19:59
@stenslae
stenslae requested review from wolfSSL-Fenrir-bot and a balanced review from Copilot October 9, 2026 20:00

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

Initialization readiness can be published before startup completes, allowing a concurrent caller to return success prematurely.

2 open findings

🧠 Review effort: Balanced

Comment thread wolfcrypt/src/wolfentropy.c Resolved

@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 #11645

Scan targets checked: wolfcrypt-src, wolfcrypt-bugs, wolfssl-bugs
Coverage: 2 of 2 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 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 #11645

Scan targets checked: wolfcrypt-src, wolfcrypt-bugs
Unchanged since last review (not re-run): wolfssl-bugs
Not reviewed (no scan target covers them): doc/dox_comments/header_files/wolfentropy.h
Coverage: 1 of 1 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 October 28, 2026 22:51

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

@claude claude 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.

Code review found no issues

No high-confidence issues detected in this change.

@stenslae stenslae assigned lealem47 and unassigned stenslae Oct 28, 2026
@stenslae
stenslae force-pushed the audit-entropy-mutex branch from d374b41 to 47ab7a6 Compare October 30, 2026 18:48
@stenslae
stenslae requested review from wolfSSL-Fenrir-bot and a balanced review from Copilot October 30, 2026 18:48

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.

🔵 Needs a closer look

Entropy bootstrap changes require maintainer validation with a FIPS source bundle and dynamic-mutex/counter-thread configurations to verify pre-init KATs and concurrent first use beyond this source-only review.

No open issues 🎉

Review effort: Balanced

@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 #11645

Scan targets checked: wolfcrypt-src, wolfcrypt-bugs, wolfssl-src, wolfssl-bugs
Not reviewed (no scan target covers them): doc/dox_comments/header_files/wolfentropy.h
Coverage: 3 of 3 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

Comment thread wolfcrypt/src/wolfentropy.c Resolved
Comment thread wolfcrypt/src/wolfentropy.c Resolved
@lealem47 lealem47 assigned stenslae and unassigned lealem47 Oct 30, 2026
@stenslae
stenslae force-pushed the audit-entropy-mutex branch from 47ab7a6 to e031465 Compare November 2, 2026 19:56
@stenslae

stenslae commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

Rebased onto master. #11707 already merged part of this PR:

  • Tracking entropy_mutex ownership before stopping the counter thread or unlocking (F-7091, F-7419, F-8169)
  • Starting the counter thread in wc_Entropy_OnDemandTest()

I've dropped both, so the only commit left is Fix Entropy_Init() re-init race. It moves mutex setup, locking and SHA-3 init into Entropy_SetupAndLock(). wc_Entropy_Get(), wc_Entropy_OnDemandTest() and Entropy_Init() all call it, and Entropy_Init() reruns the startup health test until one passes.

@stenslae
stenslae requested review from wolfSSL-Fenrir-bot and a balanced review from Copilot November 2, 2026 20:00
@stenslae

stenslae commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

@claude review

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.

🟢 Approval recommended

No active review issues are recorded for the wolfEntropy initialization and mutex-cleanup changes.

No open issues 🎉

Review effort: Balanced

@claude claude 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.

Code review found no issues

No high-confidence issues detected in this change.

@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 #11645

Scan targets checked: wolfcrypt-src, wolfcrypt-bugs, wolfssl-src, wolfssl-bugs
Not reviewed (no scan target covers them): doc/dox_comments/header_files/wolfentropy.h
Coverage: 2 of 2 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

and returns its error on failure rather than retrying.
\return 0 On success
\return BAD_FUNC_ARG If entropy is NULL

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.

Can we add the bits range check to the BAD_FUNC_ARG line in the docs for completeness? This is a minor item and I wouldn't hold up the PR over it, just noticed the bits range check wasn't documented.

Also I think we should mention/call out that a NULL buffer is accepted when the length is zero and why we opted to allow that case instead of rejecting it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Sure, added comments/docs for it.

Comment thread wolfcrypt/src/wolfentropy.c Outdated
/* Free the mutex if created, even if SHA-3 setup failed. */
if (WOLFSSL_ATOMIC_LOAD(entropy_mutex_init) == WC_MUTEX_READY_ONCE) {
wc_FreeMutex(&entropy_mutex);
WOLFSSL_ATOMIC_STORE(entropy_mutex_init, 0);

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.

Can we name this 0 something like the ready-state got a name? WC_MUTEX_UNINITIALIZED or something similar? Not a blocker for merging, just a nice-to-have.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added WC_MUTEX_UNINIT_ONCE (0) next to WC_MUTEX_READY_ONCE in wc_port.h. Entropy_Final() and the entropy_mutex_init initializer use it now.

Comment thread wolfcrypt/src/wc_port.c
WC_ATOMIC_UINT_ARG expected;

if (WOLFSSL_ATOMIC_LOAD(*flag) == 2) {
if (WOLFSSL_ATOMIC_LOAD(*flag) == WC_MUTEX_READY_ONCE) {

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.

I love that we gave this ready-state a name instead of using 2, a magic number that has no meaning! Can we do the same for the uninitialized-state in wolfentropy.c too around line 1136 of this PR? (I'll leave a comment there also). NOTE: Not a blocker to PR merge, just a nice-to-have.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks! Added the state above, and I also named the in-progress state (WC_MUTEX_BUSY_ONCE, 1), so wc_local_InitMutexOnce() has no bare numbers left. ecc.c and iotsafe.c still initialize their flags with a literal 0. It's the same value, but I left them out to keep this PR on entropy and can follow up separately.

Comment thread wolfcrypt/src/wolfentropy.c Outdated
#if !defined(SINGLE_THREADED) && !defined(WOLFSSL_MUTEX_INITIALIZER)
/* Free the mutex if created, even if SHA-3 setup failed. */
if (WOLFSSL_ATOMIC_LOAD(entropy_mutex_init) == WC_MUTEX_READY_ONCE) {
wc_FreeMutex(&entropy_mutex);

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.

There are multiple implementations for wc_FreeMutex() and most of them are capable of returning errors when the mutex is actively held or busy. I'm not sure that's possible here but I should ask the question: Should we check the return code here to make sure the wc_FreeMutex call succeeded before assuming we are good to reset the flag to the uninitialized-state so we don't end up re-initializing a live mutex later?

Something like:

    if (WOLFSSL_ATOMIC_LOAD(entropy_mutex_init) == WC_MUTEX_READY_ONCE) {
        int ret; /* could put at the top of the Entropy_Final function but since it's only used here, local scope to the if condition is fine too */
        ret = wc_FreeMutex(&entropy_mutex);
        if (ret == 0) {
            WOLFSSL_ATOMIC_STORE(entropy_mutex_init, 0);
        } else {
            WOLFSSL_MSG("Entropy_Final: Failed to free mutex, flag left initialized");
        }
    }

@stenslae can you see if this is a realistic scenario (could the mutex at this point ever be held by another thread to where the free COULD fail)? If it's not then don't bother checking the return code.

If a code path exists where we could set this flag to uninitialized and then later try to re-initialize it after a failed wc_FreeMutex() call then perhaps we should consider checking the return code here and logging a failure with WOLFSSL_MSG().

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I originally followed the existing teardown pattern for lazily created global mutexes, like the cache locks in ecc.c.

No thread that holds a wolfCrypt_Init() reference can be inside an entropy call when wolfCrypt_Cleanup() calls Entropy_Final(). But in cases of misuse, since the entropy source sets itself up lazily, a thread can be seeding an RNG through wc_Entropy_Get() while another thread's wolfCrypt_Cleanup() hits zero. Ports whose free can fail on a held mutex (ThreadX, VxWorks, etc.) can then refuse the free. Since the flag was reset anyway, wc_InitMutex() could get called on a live mutex.

It's not a likely path, but since it does exist, I think it makes more sense to change to the format you suggested. It matches gRandMethodMutex in ssl_crypto.c now: on a failed free the flag stays WC_MUTEX_READY_ONCE, so the existing mutex is reused, and the failure is logged.

lealem47
lealem47 previously approved these changes Nov 18, 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.

7 participants