bcrypt_rng: BCryptCloseAlgorithmProvider waits for a BCryptGenRandom in flight (RT-BCRYPT-GEN-CLOSE-RACE) #2529

Merged
leonida/mandy
Tyrannys merged 1 commit from rt-bcrypt-gen-close-race into main 2026-11-28 17:51:28 +00:00

Pull request successfully merged and closed

Tyrannys commented 2026-11-28 00:42:34 +00:00

Claimed in the coordination issue as: RT-BCRYPT-GEN-CLOSE-RACE (https://github.com/ProjectLeonida/mandy/issues/1608#issuecomment-7231103456)

What and why

This fixes item 3 of kevincommits' finding in #1608 (https://github.com/ProjectLeonida/mandy/issues/1608#issuecomment-7230881417), in runtime/shims/bcrypt_rng.cpp.

gen_random() looked up the handle under g_lock (shared), released the lock, and only then called the host BCryptGenRandom with the host handle. In that window, a concurrent close_algorithm_provider() could unlink the wrapper, close the host handle and free the wrapper, while the host call was still using the handle. That breaks the guarantee in the file's header comment.

The fix:

  • gen_random() keeps g_lock shared across both the lookup and the host call.
  • close_algorithm_provider() closes the host handle under the exclusive lock.

So a close waits for any call in flight, and no later call can find the closed handle. Generate calls still run side by side, because the lock is shared.

The other paths:

  • The system-preferred path (BCRYPT_USE_SYSTEM_PREFERRED_RNG) uses no handle, so it takes no lock.
  • The seeded path fills its buffer after the shared hold ends, because fill_seeded() takes the lock exclusive.

Tested

A test hook, swap_host_functions_for_test(), lets bcrypt_rng_test install fake host functions. The fake generate call blocks until the test releases it, and the fake close records whether a generate call was still running.

The new case:

  1. Starts BCryptGenRandom and waits until it is inside the host call.
  2. Calls BCryptCloseAlgorithmProvider on the same handle from another thread.
  3. Checks that the close has not returned after 200 ms.
  4. Releases the generate call, then checks that the host close ran only after the host call returned.
  5. Checks that both calls succeed and that the closed handle is refused afterwards.

With main's bcrypt_rng.cpp plus only the hook, 2 checks fail. With the fix, bcrypt_rng and bcrypt_rng_seeded pass.

GPUs tested: profile M: NVIDIA GeForce RTX 4070 SUPER, 12 GB, desktop, driver 621.01, Windows 11 (CPU-only test)

AI-assisted: yes (Claude Code)

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a: no translator change)

🤖 Generated with Claude Code

Claimed in the coordination issue as: RT-BCRYPT-GEN-CLOSE-RACE (https://github.com/ProjectLeonida/mandy/issues/1608#issuecomment-7231103456) ### What and why This fixes item 3 of kevincommits' finding in #1608 (https://github.com/ProjectLeonida/mandy/issues/1608#issuecomment-7230881417), in `runtime/shims/bcrypt_rng.cpp`. `gen_random()` looked up the handle under `g_lock` (shared), released the lock, and only then called the host `BCryptGenRandom` with the host handle. In that window, a concurrent `close_algorithm_provider()` could unlink the wrapper, close the host handle and free the wrapper, while the host call was still using the handle. That breaks the guarantee in the file's header comment. The fix: - `gen_random()` keeps `g_lock` shared across both the lookup and the host call. - `close_algorithm_provider()` closes the host handle under the exclusive lock. So a close waits for any call in flight, and no later call can find the closed handle. Generate calls still run side by side, because the lock is shared. The other paths: - The system-preferred path (`BCRYPT_USE_SYSTEM_PREFERRED_RNG`) uses no handle, so it takes no lock. - The seeded path fills its buffer after the shared hold ends, because `fill_seeded()` takes the lock exclusive. ### Tested A test hook, `swap_host_functions_for_test()`, lets `bcrypt_rng_test` install fake host functions. The fake generate call blocks until the test releases it, and the fake close records whether a generate call was still running. The new case: 1. Starts `BCryptGenRandom` and waits until it is inside the host call. 2. Calls `BCryptCloseAlgorithmProvider` on the same handle from another thread. 3. Checks that the close has not returned after 200 ms. 4. Releases the generate call, then checks that the host close ran only after the host call returned. 5. Checks that both calls succeed and that the closed handle is refused afterwards. With main's `bcrypt_rng.cpp` plus only the hook, 2 checks fail. With the fix, `bcrypt_rng` and `bcrypt_rng_seeded` pass. GPUs tested: profile M: NVIDIA GeForce RTX 4070 SUPER, 12 GB, desktop, driver 621.01, Windows 11 (CPU-only test) AI-assisted: yes (Claude Code) ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. (n/a: no translator change) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
timbot103 commented 2026-11-28 01:34:05 +00:00

Reviewed at head b5844c443 on Windows 11 (MSVC 2022 19.44).

Verification

  • Built bcrypt_rng_test and gta6rt.
  • bcrypt_rng_test (5 consecutive runs): 27/27 checks passed on all 5 runs.

Notes

  • Holding the shared lock from handle lookup through BCryptGenRandom and taking the exclusive lock in BCryptCloseAlgorithmProvider fixes the provider-close UAF race cleanly (bcrypt_rng.cpp:156-232). Seeded generation drops the shared lock before acquiring the exclusive PRNG lock and does not touch the provider handle afterwards.
  • Minor non-blocking observations: the single global shared/exclusive lock means a slow native call on one handle blocks close on an unrelated handle; the test's 200 ms sleep (bcrypt_rng_test.cpp:203-221) waits heuristically rather than signaling that the closer entered; and the test-only host-function swap assumes quiescent opens / system-preferred calls. None of these block the lifetime fix.

Approve.

AI-assisted review + local MSVC verification.

Reviewed at head `b5844c443` on Windows 11 (MSVC 2022 `19.44`). ### Verification - Built `bcrypt_rng_test` and `gta6rt`. - `bcrypt_rng_test` (5 consecutive runs): **27/27 checks passed** on all 5 runs. ### Notes - Holding the shared lock from handle lookup through `BCryptGenRandom` and taking the exclusive lock in `BCryptCloseAlgorithmProvider` fixes the provider-close UAF race cleanly (`bcrypt_rng.cpp:156-232`). Seeded generation drops the shared lock before acquiring the exclusive PRNG lock and does not touch the provider handle afterwards. - Minor non-blocking observations: the single global shared/exclusive lock means a slow native call on one handle blocks close on an unrelated handle; the test's 200 ms sleep (`bcrypt_rng_test.cpp:203-221`) waits heuristically rather than signaling that the closer entered; and the test-only host-function swap assumes quiescent opens / system-preferred calls. None of these block the lifetime fix. Approve. AI-assisted review + local MSVC verification.
zmasi commented 2026-11-28 07:05:27 +00:00

#2529 | head b5844c443f1b1323fa95f873e3d60eac9a0f7e1d (merged cleanly with main 09c153948386fd658fe2f999f6176efbaa8c8345) | ctest --test-dir runtime/build -C RelWithDebInfo -R "^bcrypt_rng" --output-on-failure | red on main: bcrypt_rng_test.cpp fails to link (LNK2019: swap_host_functions_for_test missing; on main, lookup_live_handle released g_lock before g_host_gen ran, allowing concurrent BCryptCloseAlgorithmProvider to close the host handle mid-call) | green on PR+main: 2/2 CTests pass (bcrypt_rng 27/27 checks in 0.27s and bcrypt_rng_seeded 21/21 checks in 0.03s, plus 5/5 consecutive concurrency stress runs of bcrypt_rng_test); check_no_game_data.py 0 violations | Windows 11, RTX 3090 (610.88), Vulkan SDK 1.4.363.1 | AI-assisted: yes

#2529 | head b5844c443f1b1323fa95f873e3d60eac9a0f7e1d (merged cleanly with main 09c153948386fd658fe2f999f6176efbaa8c8345) | `ctest --test-dir runtime/build -C RelWithDebInfo -R "^bcrypt_rng" --output-on-failure` | red on main: `bcrypt_rng_test.cpp` fails to link (`LNK2019`: `swap_host_functions_for_test` missing; on `main`, `lookup_live_handle` released `g_lock` before `g_host_gen` ran, allowing concurrent `BCryptCloseAlgorithmProvider` to close the host handle mid-call) | green on PR+main: `2/2` CTests pass (`bcrypt_rng` `27/27` checks in `0.27s` and `bcrypt_rng_seeded` `21/21` checks in `0.03s`, plus `5/5` consecutive concurrency stress runs of `bcrypt_rng_test`); `check_no_game_data.py` `0` violations | Windows 11, RTX 3090 (610.88), Vulkan SDK 1.4.363.1 | AI-assisted: yes
timbot103 reviewed 2026-11-28 14:36:57 +00:00
timbot103 left a comment
No description provided.
Static code audit of `b5844c443` against `ec740bcc3`. The shared lock spans the host `BCryptGenRandom` call, so the exclusive close cannot release its provider mid-call. Minor test gap in `runtime/test/bcrypt_rng_test.cpp:204–216`. The event confirms the generator entered the host, but the 200 ms sleep can expire before the closer is scheduled. If the closer runs after generation returns, both checks pass even with the original race. Gate the generator on observed lock contention or early entry into the fake host close and treat timeouts as test failures. AI-assisted.
lixonik approved these changes 2026-11-28 15:01:35 +00:00
lixonik left a comment

Reviewed b5844c443 and verified the bcrypt_rng suites on Windows 11.

Code audit:

  • runtime/shims/bcrypt_rng.cpp: holding SharedLock across both lookup_live_handle() and host_random() while close_algorithm_provider() unlinks and calls g_host_close() under AcquireSRWLockExclusive(&g_lock) cleanly closes the concurrent generate-vs-close race; fill_seeded() runs after releasing the shared hold so it cannot self-deadlock on the exclusive lock.
  • Non-blocking note: as @timbot103 noted, replacing the fixed 200 ms sleep in bcrypt_rng_test.cpp with explicit synchronization on close entry would make the race test even more deterministic, though the production fix itself is solid.

Verification (Windows 11, MSVC 19.44, Ninja Release):

  • Built bcrypt_rng_test.
  • ctest -R '^bcrypt_rng': 2/2 passed (bcrypt_rng, bcrypt_rng_seeded).
  • python -I scripts/check_no_game_data.py: passed.

AI-assisted (Antigravity, Gemini).

Reviewed `b5844c443` and verified the `bcrypt_rng` suites on Windows 11. Code audit: - `runtime/shims/bcrypt_rng.cpp`: holding `SharedLock` across both `lookup_live_handle()` and `host_random()` while `close_algorithm_provider()` unlinks and calls `g_host_close()` under `AcquireSRWLockExclusive(&g_lock)` cleanly closes the concurrent generate-vs-close race; `fill_seeded()` runs after releasing the shared hold so it cannot self-deadlock on the exclusive lock. - Non-blocking note: as `@timbot103` noted, replacing the fixed 200 ms sleep in `bcrypt_rng_test.cpp` with explicit synchronization on close entry would make the race test even more deterministic, though the production fix itself is solid. Verification (Windows 11, MSVC 19.44, Ninja Release): - Built `bcrypt_rng_test`. - `ctest -R '^bcrypt_rng'`: **2/2 passed** (`bcrypt_rng`, `bcrypt_rng_seeded`). - `python -I scripts/check_no_game_data.py`: passed. AI-assisted (Antigravity, Gemini).
MoonEyes commented 2026-11-28 17:51:23 +00:00

Red/green: On main bcrypt_rng_test does not link because the test hook swap_host_functions_for_test is missing and main releases g_lock before the host BCryptGenRandom call, and with the PR ctest -R "^bcrypt_rng$" passes, including the check that BCryptCloseAlgorithmProvider waits for an in-flight BCryptGenRandom.
Independent tester (OreoFR, RTX 4070, Windows 11): PR head merged with the other PRs of its batch on main c1ecf04ed, full ctest run (485 tests, tests that launch the game excluded): no new failure compared with main.

Red/green: On main bcrypt_rng_test does not link because the test hook swap_host_functions_for_test is missing and main releases g_lock before the host BCryptGenRandom call, and with the PR ctest -R "^bcrypt_rng$" passes, including the check that BCryptCloseAlgorithmProvider waits for an in-flight BCryptGenRandom. Independent tester (OreoFR, RTX 4070, Windows 11): PR head merged with the other PRs of its batch on main c1ecf04ed, full ctest run (485 tests, tests that launch the game excluded): no new failure compared with main.
OreoFR commented 2026-11-28 22:04:06 +00:00

Verified by OreoFR

  • Base: main c1ecf04ed + PR head b5844c443; green run in a merge package of 11 PRs, no new ctest failure vs main
  • Test: ctest -R "^bcrypt_rng$"
  • Red on main: the test does not link without the PR (rt::bcrypt_rng::swap_host_functions_for_test missing on main)
  • Green with the PR: OK
  • Verdict: READY (red by link only: the race case could not run on main)
  • Machine: RTX 4070 Laptop 8 GB, NVIDIA 621.40, Intel Core Ultra 7 155H, Windows 11

AI-assisted (Claude Code, Claude Opus 5.5).

**Verified by OreoFR** - Base: main `c1ecf04ed` + PR head `b5844c443`; green run in a merge package of 11 PRs, no new ctest failure vs main - Test: `ctest -R "^bcrypt_rng$"` - Red on main: the test does not link without the PR (rt::bcrypt_rng::swap_host_functions_for_test missing on main) - Green with the PR: OK - Verdict: READY (red by link only: the race case could not run on main) - Machine: RTX 4070 Laptop 8 GB, NVIDIA 621.40, Intel Core Ultra 7 155H, Windows 11 AI-assisted (Claude Code, Claude Opus 5.5).
Sign in to join this conversation.
No description provided.