Closed Bug 2042727 Opened 5 months ago Closed 5 months ago

FutexThread state-machine invariant violation: re-entrant Atomics.wait during interrupt handler enters wait() with state_ == Woken [@ js::FutexThread::wait]

Categories

(Core :: JavaScript: Standard Library, defect)

defect

Tracking

()

RESOLVED FIXED
153 Branch
Tracking Status
firefox-esr115 --- unaffected
firefox-esr140 --- unaffected
firefox151 --- wontfix
firefox152 --- wontfix
firefox153 --- fixed

People

(Reporter: bugmon, Assigned: jandem)

References

(Regression)

Details

(5 keywords)

Attachments

(3 files, 1 external file)

js::FutexThread::wait (js/src/builtin/AtomicsObject.cpp:1697) begins with the precondition MOZ_ASSERT(state_ == Idle || state_ == WaitingInterrupted) at line 1702. The per-JSContext futex state machine assumes wait() is only ever entered when state_ is Idle (a fresh wait) or WaitingInterrupted (which is immediately rejected with JSMSG_ATOMICS_WAIT_NOT_ALLOWED at lines 1707-1712). This guard is incomplete with respect to interrupt-driven re-entrancy: a blocked main-thread Atomics.wait can be interrupted, and the interrupt callback runs attacker-controlled script on the same JSContext. If that script calls Atomics.notify on the same location it drives state_ to Woken (via FutexThread::notify's first branch, line 1830), and a subsequent re-entrant Atomics.wait then enters FutexThread::wait with state_ == Woken, violating the assertion.

The testcase reproduces deterministically in the SpiderMonkey debug shell under --fuzzing-safe. The shell's timeout() watchdog delivers an urgent interrupt that wakes a blocked Atomics.wait; the interrupt-callback string performs Atomics.notify(t,0) followed by Atomics.wait(t,0,0,50) on the same shared buffer (obtained via getSharedArrayBuffer), triggering the crash.

In debug builds this is a JS-reachable engine-invariant violation (assertion abort). In release builds the assert is compiled out and the synchronization state machine becomes inconsistent: the re-entrant wait clobbers the shared per-context state_/cond_ and its scope-exit handler (MakeScopeExit at line 1715) resets state_ = Idle on return, destroying the outer wait's Woken signal and producing lost-wakeup / hang behavior for a thread that other agents are concurrently notifying.

Build Info

Affected Code

File: js/src/builtin/AtomicsObject.cpp, line 1697-1715

FutexThread::WaitResult js::FutexThread::wait(
    JSContext* cx, js::UniqueLock<js::Mutex>& locked,
    const mozilla::Maybe<mozilla::TimeDuration>& timeout) {
  MOZ_ASSERT(&cx->fx == this);
  MOZ_ASSERT(cx->fx.canWait());
  MOZ_ASSERT(state_ == Idle || state_ == WaitingInterrupted);  // <-- violated: state_ == Woken

  // Disallow waiting when a runtime is processing an interrupt.
  if (state_ == WaitingInterrupted) {
    UnlockGuard unlock(locked);
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_ATOMICS_WAIT_NOT_ALLOWED);
    return WaitResult::Error;
  }

  // Go back to Idle after returning.
  auto onFinish = mozilla::MakeScopeExit([&] { state_ = Idle; });

File: js/src/builtin/AtomicsObject.cpp, line 1807-1817

        state_ = WaitingInterrupted;
        {
          UnlockGuard unlock(locked);
          if (!cx->handleInterrupt()) {   // <-- runs attacker script while state_ == WaitingInterrupted
            return WaitResult::Error;
          }
        }
        if (state_ == Woken) {
          return WaitResult::OK;
        }
        break;

File: js/src/builtin/AtomicsObject.cpp, line 1825-1846

void js::FutexThread::notify(NotifyReason reason) {
  MOZ_ASSERT(isWaiting());

  if ((state_ == WaitingInterrupted || state_ == WaitingNotifiedForInterrupt) &&
      reason == NotifyExplicit) {
    state_ = Woken;   // <-- Atomics.notify during the interrupt sets state_ = Woken
    return;
  }
  switch (reason) {
    case NotifyExplicit:
      state_ = Woken;
      break;
    ...
  }
  cond_->notify_all();
}

The precondition assertion that is violated, and the two source sites that drive the illegal state transition (notify NotifyExplicit -> Woken, and the interrupt-handling re-entry point).

Exploit Chain

  1. Main thread creates a SharedArrayBuffer + Int32Array and registers the shared buffer with setSharedArrayBuffer so the interrupt handler (which runs in a different global) can re-obtain the same raw buffer.
  2. Main thread calls Atomics.wait(ta, 0, 0) which enters FutexThread::wait; state_ transitions Idle -> Waiting and the thread blocks in cond_->wait (AtomicsObject.cpp:1738/1754).
  3. The shell watchdog scheduled by timeout(0.3, <string>) fires and calls JS_RequestInterruptCallback -> JSContext::requestInterrupt(CallbackUrgent) (Runtime.cpp:464); because fx.isWaiting() is true it calls fx.notify(NotifyForJSInterrupt) (Runtime.cpp:474), setting state_ = WaitingNotifiedForInterrupt and signalling cond_.
  4. The wait loop wakes, sets state_ = WaitingInterrupted, releases the futex lock via UnlockGuard, and calls cx->handleInterrupt() (AtomicsObject.cpp:1807-1810), which runs the interrupt-callback script string.
  5. The interrupt script calls Atomics.notify(t, 0): atomics_notify_impl finds the still-listed sync waiter (isWaiting() true) and calls waiter->cx()->fx.notify(NotifyExplicit); FutexThread::notify's first branch sets state_ = Woken (AtomicsObject.cpp:1830).
  6. The interrupt script then calls Atomics.wait(t, 0, 0, 50), re-entering FutexThread::wait with state_ == Woken, which is neither Idle nor WaitingInterrupted, triggering the MOZ_ASSERT at line 1702 (debug abort). In release the assert is gone and the shared state_/cond_ are corrupted, causing the outer wait's Woken signal to be lost.
  7. All operations run on the same thread/JSContext, so cx->fx is the same FutexThread and state_ is the same field across the outer and re-entrant wait calls.

Steps to Reproduce

  1. Build/obtain the SpiderMonkey debug shell with assertions: /firefox/obj-js-debug/dist/bin/js
  2. Save the testcase as atomics_wait_reentry.js
  3. Run: /firefox/obj-js-debug/dist/bin/js atomics_wait_reentry.js (the watchdog fires at ~0.3s; allow a few seconds)
  4. Observe the abort: 'Assertion failure: state_ == Idle || state_ == WaitingInterrupted, at js/src/builtin/AtomicsObject.cpp:1702'
  5. Note: the runtime always passes --fuzzing-safe; all primitives used (timeout, setSharedArrayBuffer/getSharedArrayBuffer, SharedArrayBuffer, Atomics.wait/notify) are available under --fuzzing-safe. The ASAN build compiles the assert out and instead hangs (lost wakeup), so verify with the debug build.

Security Impact

  • Severity: Low
  • Attacker capability: Script reachable from a single thread (no workers needed) can drive the per-JSContext FutexThread synchronization state machine into an illegal state. In assertions/debug builds this is a guaranteed abort (DoS). In release builds the assert is elided and the shared state_/cond_ are left inconsistent across the nested wait() frames: the re-entrant wait's scope-exit resets state_ = Idle, so the outer wait loses a delivered Woken notification, yielding lost-wakeup / hang behavior of Atomics.wait while other agents are notifying. No memory corruption was demonstrated; the impact is a synchronization-primitive invariant violation / potential denial-of-service.
  • Preconditions: Reachable from ordinary (untrusted) JavaScript that can perform a blocking Atomics.wait and run code from an interrupt callback. In the JS shell this uses timeout()'s watchdog; in Firefox the analogous slow-script watchdog interrupt can interrupt a blocked main-thread Atomics.wait and run page script via the interrupt path. No special prefs or shell-only flags are required (reproduces under --fuzzing-safe).

ASAN Report

Assertion failure: state_ == Idle || state_ == WaitingInterrupted, at js/src/builtin/AtomicsObject.cpp:1702

==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x000000000000 (pc ... MOZ_CrashSequence; WRITE memory access; address points to the zero page)
    #0 MOZ_CrashSequence(void*, long) mozilla/Assertions.h:261:3
    #1 js::FutexThread::wait(JSContext*, js::LockGuard<js::Mutex>&, mozilla::Maybe<...> const&) js/src/builtin/AtomicsObject.cpp:1702:3
    #2 AtomicsWait<int>(...) js/src/builtin/AtomicsObject.cpp:1260:43
    #3 js::atomics_wait_impl(...) js/src/builtin/AtomicsObject.cpp:1270:10
    #4 DoAtomicsWait<int>(...) js/src/builtin/AtomicsObject.cpp:1350:11
    #5 DoWait(...) js/src/builtin/AtomicsObject.cpp:1402:12
    #6 atomics_wait(JSContext*, unsigned int, JS::Value*) js/src/builtin/AtomicsObject.cpp:1429:10
    ...
    #17 EvaluateInner(...) js/src/shell/js.cpp:3173:32
    #18 ShellInterruptCallback(JSContext*) js/src/shell/js.cpp:1236:12
    #19 InvokeInterruptCallbacks(JSContext*) js/src/vm/Runtime.cpp:386:10
    #20 HandleInterrupt(JSContext*, bool, bool) js/src/vm/Runtime.cpp:425:8
    #21 js::FutexThread::wait(...) js/src/builtin/AtomicsObject.cpp:1810:20
    #22 AtomicsWait<int>(...) js/src/builtin/AtomicsObject.cpp:1260:43
    #26 atomics_wait(JSContext*, unsigned int, JS::Value*) js/src/builtin/AtomicsObject.cpp:1429:10
    ...
SUMMARY: UndefinedBehaviorSanitizer: SEGV mozilla/Assertions.h:261:3 in MOZ_CrashSequence(void*, long)
Attached patch fix.patch — — Splinter Review
Attached file crash_stack.txt —
Group: core-security → javascript-core-security
See Also: → 2042730
Duplicate of this bug: 2042730

This uses getSharedArrayBuffer() from the interrupt callback and bug 2042730 uses getSharedObject(). NI myself to see if we can fix these + bug 2042991 with a single patch.

Flags: needinfo?(jdemooij)
Attached file (secure) —

LLMs keep finding clever ways to mutate the interrupted code. It seems better to
create the global with a small set of allowlisted testing functions to prevent this.
The functions to trigger GC seem most useful because that's what interrupt callbacks
can do in the browser.

Assignee: nobody → jdemooij
Status: UNCONFIRMED → ASSIGNED
Ever confirmed: true
Flags: needinfo?(jdemooij)
Pushed by jdemooij@mozilla.com: https://github.com/mozilla-firefox/firefox/commit/2c175d4c7761 https://hg.mozilla.org/integration/autoland/rev/a26b84731a28 Expose minimal set of testing functions to interrupt callback-string globals. r=iain
Group: javascript-core-security → core-security-release
Status: ASSIGNED → RESOLVED
Closed: 5 months ago
Resolution: --- → FIXED
Target Milestone: --- → 153 Branch
Group: core-security-release
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: