Closed Bug 2023006 Opened 8 months ago Closed 8 months ago

Reentrancy vulnerability in RegExpStatics::executeLazy

Categories

(Core :: JavaScript Engine, defect)

defect

Tracking

()

RESOLVED INVALID
Tracking Status
firefox150 --- affected

People

(Reporter: tsmith, Unassigned)

Details

(Keywords: ai-involved, testcase)

Attachments

(2 files)

Attached file crash_stack.txt —

Summary

Reentrancy vulnerability in RegExpStatics::executeLazy (/firefox/js/src/vm/RegExpStatics.cpp:19-61). The function passes a stack-rooted snapshot of matchesInput and a raw pointer to this->matches into RegExpShared::execute, which can reentrantly invoke JS via CheckForInterrupt during the regex interrupt-retry loop. Reentrant JS can overwrite this->matchesInput with a tiny string while the retry writes large match offsets derived from the old, rooted input. The resulting matches / matchesInput desync causes an out-of-bounds read in NewDependentString when RegExp.lastMatch materializes the match string.

Affected Code

File: /firefox/js/src/vm/RegExpStatics.cpp, lines 42–44

/* Execute the full regular expression. */
Rooted<JSLinearString*> input(cx, matchesInput);
RegExpRunStatus status =
    RegExpShared::execute(cx, &shared, input, lazyIndex, &this->matches);

File: /firefox/js/src/vm/RegExpObject.cpp, lines 789–803

if (cx->hasAnyPendingInterrupt()) {
  if (!CheckForInterrupt(cx)) {          // ← runs JS; can mutate RegExpStatics
    return RegExpRunStatus::Error;
  }
  if (interruptRetries++ < maxInterruptRetries) {
    ...
    continue;   // ← re-runs Execute with the OLD `input`, writes into &this->matches
  }
}

File: /firefox/js/src/vm/RegExpStatics.h, lines 155–157

MOZ_ASSERT(start <= end);
MOZ_ASSERT(end <= matchesInput->length());   // ← stripped in release
JSString* str = NewDependentString(cx, matchesInput, start, end - start);

The invariant "matches offsets are valid indices into matchesInput" is only guarded by a debug-only assertion. executeLazy is the only caller of RegExpShared::execute that passes a non-stack-local VectorMatchPairs* — every other caller passes a fresh stack buffer, so this reentrancy hazard is unique to the lazy-evaluation path.

Correct Pattern

bool RegExpStatics::executeLazy(JSContext* cx) {
  if (!pendingLazyEvaluation) {
    return true;
  }
  ...
  Rooted<JSLinearString*> input(cx, matchesInput);

  // Use a stack-local buffer; don't let execute() write directly into
  // this->matches, because CheckForInterrupt inside execute() can
  // reentrantly mutate *this via updateFromMatchPairs.
  VectorMatchPairs localMatches;
  RegExpRunStatus status =
      RegExpShared::execute(cx, &shared, input, lazyIndex, &localMatches);
  if (status == RegExpRunStatus::Error) {
    return false;
  }
  MOZ_ASSERT(status == RegExpRunStatus::Success);

  // Restore invariant atomically: matches and matchesInput must agree.
  matchesInput = input;             // reentrant JS may have clobbered this
  if (!matches.initArrayFrom(localMatches)) {
    ReportOutOfMemory(cx);
    return false;
  }

  pendingLazyEvaluation = false;
  lazySource = nullptr;
  lazyIndex = size_t(-1);
  return true;
}

Exploit Chain

  1. Attacker runs /(a*)b\1c/.exec("Q".repeat(500000) + "aaabac") — the backreference \1 forces a backtracking loop whose Backtrack() checks cx->interruptBits_ for CallbackUrgent on each iteration. This sets up RegExpStatics with pendingLazyEvaluation = true, matchesInput = the 500006-char string, and lazyIndex/lazySource for replay.
  2. Attacker registers an interrupt callback (setInterruptCallback) and arms it (interruptIf(true)).
  3. Attacker reads RegExp.lastMatch. This invokes static_lastMatch_getter → createLastMatch → executeLazy.
  4. executeLazy roots input = matchesInput (500006 chars) and calls RegExpShared::execute(..., input, ..., &this->matches).
  5. Inside execute, the jitted regex runs, hits Backtrack(), sees the pending urgent interrupt, returns RegExpRunStatus::Error.
  6. execute calls CheckForInterrupt(cx) (RegExpObject.cpp:790). The interrupt callback runs.
  7. The callback uses new Debugger().findAllGlobals()[i].executeInGlobal("/AB/.exec('AB'+String.fromCharCode(67))") to run a regex exec in the main global. (Running in a fresh global would target a different RegExpStatics; executeInGlobal targets the victim's.)
  8. That exec calls RegExpStatics::updateFromMatchPairs, which sets this->matchesInput = "ABC" (3 chars) and this->matches = {[0,2]}, and clears pendingLazyEvaluation.
  9. Callback returns true. execute does continue and retries irregexp::Execute(cx, re, input, start, matches). input is still the rooted 500006-char string.
  10. The retry succeeds (no interrupt pending), writing matches[0] = {500002, 500006} into this->matches. execute returns Success.
  11. executeLazy returns. createLastMatch calls makeMatch(cx, 0) → reads matches[0] = {500002, 500006} → calls createDependent(cx, 500002, 500006).
  12. createDependent calls NewDependentString(cx, matchesInput, 500002, 4). matchesInput is "ABC" (length 3).
  13. NewDependentStringHelper sees length=4 fits inline, calls NewInlineString<Latin1Char>(cx, base, 500002, 4).
  14. PodCopy(chars, base->latin1Chars(nogc) + 500002, 4) reads 4 bytes at ~500KB past the end of "ABC"'s inline storage → OOB read into GC heap.

Security Impact

Severity: High (sec-high). Out-of-bounds read of attacker-controlled offset and length into the GC heap, returned to JS as a string. The attacker fully controls the desync delta (choose the large string's length and the tiny string's length), giving an arbitrary-offset heap read relative to the tiny string's chars. In a release build (no ASAN poisoning), the 4 leaked bytes become the contents of RegExp.lastMatch — a direct information disclosure primitive suitable for defeating ASLR or leaking adjacent object contents. If the length (end - start) exceeds the inline-string threshold, the engine creates a JSDependentString whose chars_ pointer lies far outside its base — a persistent wild-pointer string usable for repeated, sliceable heap reads.

Preconditions: The testcase uses Debugger.findAllGlobals + executeInGlobal to achieve cross-global reentrancy from the interrupt callback. This is a privileged (devtools) API in the browser. However, the underlying engine invariant violation — executeLazy is not reentrancy-safe against CheckForInterrupt — is real regardless of the specific callback vector; any code path that can synchronously run a regex exec in the same global during CheckForInterrupt triggers it. In the shell, it reproduces with --fuzzing-safe.

ASAN Report

==712175==ERROR: AddressSanitizer: use-after-poison on address 0x2e8954ad696a at pc 0x56047276c132 bp 0x7ffd360ea510 sp 0x7ffd360ea508
READ of size 1 at 0x2e8954ad696a thread T0
    #0 0x56047276c131 in void mozilla::PodCopy<unsigned char>(unsigned char*, unsigned char const*, unsigned long) /firefox/obj-x86_64-pc-linux-gnu/dist/include/mozilla/PodOperations.h:115:15
    #1 0x56047276c131 in JSInlineString* js::NewInlineString<unsigned char>(JSContext*, JS::Handle<JSLinearString*>, unsigned long, unsigned long, js::gc::Heap) /firefox/js/src/vm/StringType-inl.h:142:3
    #2 0x56047276c131 in JSLinearString* NewDependentStringHelper<(JS::ContractBaseChain)1>(JSContext*, JSString*, unsigned long, unsigned long, js::gc::Heap) /firefox/js/src/vm/StringType.cpp:1957:12
    #3 0x560470c01afe in js::RegExpStatics::createDependent(JSContext*, unsigned long, unsigned long, JS::MutableHandle<JS::Value>) /firefox/js/src/vm/RegExpStatics.h:157:19
    #4 0x560470c01afe in js::RegExpStatics::makeMatch(JSContext*, unsigned long, JS::MutableHandle<JS::Value>) /firefox/js/src/vm/RegExpStatics.h:185:10
    #5 0x560470c01afe in js::RegExpStatics::createLastMatch(JSContext*, JS::MutableHandle<JS::Value>) /firefox/js/src/vm/RegExpStatics.h:199:10
    #6 0x560470c01afe in static_lastMatch_getter(JSContext*, unsigned int, JS::Value*) /firefox/js/src/builtin/RegExp.cpp:1434:1
    #7 0x5604725768fa in CallJSNative(...) /firefox/js/src/vm/Interpreter.cpp:490:13
    #8 0x5604725768fa in js::InternalCallOrConstruct(...) /firefox/js/src/vm/Interpreter.cpp:586:12
    #9 0x560472578324 in InternalCall(...) /firefox/js/src/vm/Interpreter.cpp:653:10
    #10 0x560472578324 in js::Call(...) /firefox/js/src/vm/Interpreter.cpp:685:8
    #11 0x560472579e4b in js::CallGetter(...) /firefox/js/src/vm/Interpreter.cpp:807:10
    #12 0x560472af6f26 in CallGetter(...) /firefox/js/src/vm/NativeObject.cpp:2157:12
    #13 0x560472ae3aa6 in bool GetExistingProperty<(js::AllowGC)1>(...) /firefox/js/src/vm/NativeObject.cpp:2185:12
    #14 0x560472ae3aa6 in bool NativeGetPropertyInline<(js::AllowGC)1>(...) /firefox/js/src/vm/NativeObject.cpp:2328:14
    #15 0x560472ae3aa6 in js::NativeGetProperty(...) /firefox/js/src/vm/NativeObject.cpp:2358:10
    #16 0x5604725a477a in js::GetProperty(...) /firefox/js/src/vm/ObjectOperations-inl.h:113:10
    #17 0x5604725a477a in js::GetProperty(...) /firefox/js/src/vm/ObjectOperations-inl.h:120:10
    #18 0x5604725a477a in js::GetProperty(...) /firefox/js/src/vm/Interpreter.cpp:4630:10
    #19 0x56047181b7eb in js::jit::DoGetPropFallback(...) /firefox/js/src/jit/BaselineIC.cpp:1318:8
    #20 0x7a0ab4801baf  ([anon:js-executable-memory]+0x2baf)

Address 0x2e8954ad696a is a wild pointer inside of access range of size 0x000000000001.
SUMMARY: AddressSanitizer: use-after-poison /firefox/obj-x86_64-pc-linux-gnu/dist/include/mozilla/PodOperations.h:115:15
Shadow bytes around the buggy address:
=>0x2e8954ad6900: f7 f7 f7 f7 f7 f7 f7 f7 f7 f7 f7 f7 f7[f7]f7 f7
  Poisoned by user:        f7
==712175==ABORTING

Suggested Fix

Use a stack-local VectorMatchPairs and restore matchesInput atomically after execute returns, so that reentrant mutation during CheckForInterrupt cannot desynchronize the two fields:

bool RegExpStatics::executeLazy(JSContext* cx) {
  if (!pendingLazyEvaluation) {
    return true;
  }

  MOZ_ASSERT(lazySource);
  MOZ_ASSERT(matchesInput);
  MOZ_ASSERT(lazyIndex != size_t(-1));

  Rooted<JSAtom*> source(cx, lazySource);
  RootedRegExpShared shared(cx,
                            cx->zone()->regExps().get(cx, source, lazyFlags));
  if (!shared) {
    return false;
  }

  Rooted<JSLinearString*> input(cx, matchesInput);

  // RegExpShared::execute can run JS via CheckForInterrupt during the
  // interrupt-retry loop, which may reentrantly call updateFromMatchPairs
  // and overwrite |this->matchesInput| and |this->matches|. Use a
  // stack-local buffer and commit both fields atomically on success.
  VectorMatchPairs localMatches;
  RegExpRunStatus status =
      RegExpShared::execute(cx, &shared, input, lazyIndex, &localMatches);
  if (status == RegExpRunStatus::Error) {
    return false;
  }

  MOZ_ASSERT(status == RegExpRunStatus::Success);

  // Restore the invariant: matches offsets are valid for matchesInput.
  matchesInput = input;
  if (!matches.initArrayFrom(localMatches)) {
    ReportOutOfMemory(cx);
    return false;
  }

  pendingLazyEvaluation = false;
  lazySource = nullptr;
  lazyIndex = size_t(-1);

  return true;
}

Additionally, consider upgrading the debug-only assertion in createDependent (RegExpStatics.h:156) to MOZ_RELEASE_ASSERT(end <= matchesInput->length()) as defense-in-depth.

Attached file testcase.js —
Attachment #9552480 - Attachment mime type: application/x-javascript → text/plain

This is bogus. In the actual browser, interrupt handlers are not adversarial, and they don't go around executing arbitrary code in the interrupted realm. In bug 1881130, to limit the number of bogus fuzz bugs, we rewrote setInterruptCallback so that in --fuzzing-safe mode it would only accept a string to run in a fresh global, in an attempt to prevent it from mutating the interrupted code. It's somewhat clever of Claude to use the debugger API to work around this restriction, but that doesn't make this a real problem.

Status: NEW → RESOLVED
Closed: 8 months ago
Resolution: --- → INVALID
Group: javascript-core-security

I don't think it's helpful to label this as slop; our non-AI fuzzers also reported bugs like this regularly. It might be useful to figure out what we can do to make it more obvious in the future that this kind of bug is not interesting.

You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: