Closed Bug 2024364 Opened 8 months ago Closed 7 months ago

OOB read/type confusion in [@ js::CreateRegExpMatchResult] via RegExpShared desync after CheckForInterrupt runs JS

Categories

(Core :: JavaScript Engine, defect, P3)

defect

Tracking

()

RESOLVED DUPLICATE of bug 2027272

People

(Reporter: bugmon, Unassigned)

References

Details

(4 keywords, Whiteboard: [bugmon:bisected,confirmed][prefs-checked])

Attachments

(2 files)

Summary

Type confusion via out-of-bounds heap read in js::CreateRegExpMatchResult caused by RegExpShared desynchronization. RegExpShared::execute() in /firefox/js/src/vm/RegExpObject.cpp at line 790 calls CheckForInterrupt(cx) inside its retry loop, which can run arbitrary JS that swaps the RegExpObject's SHARED_SLOT. After execution succeeds with the old shared, callers at /firefox/js/src/builtin/RegExp.cpp:1809 re-read SHARED_SLOT and obtain the new shared, then pass it to CreateRegExpMatchResult alongside the old match results — causing OOB dense-element reads whose bytes are reinterpreted as JS::Value and stored into a JS-visible groups object.

Affected Code

Root cause — /firefox/js/src/vm/RegExpObject.cpp, lines 758–812 (RegExpShared::execute):

uint32_t interruptRetries = 0;
const uint32_t maxInterruptRetries = 4;
do {
  RegExpRunStatus result = irregexp::Execute(cx, re, input, start, matches);
  ...
  if (result == RegExpRunStatus::Error) {
    ...
    if (cx->hasAnyPendingInterrupt()) {
      if (!CheckForInterrupt(cx)) {          // <-- RUNS ARBITRARY JS
        return RegExpRunStatus::Error;
      }
      if (interruptRetries++ < maxInterruptRetries) {
        if (!compileIfNecessary(cx, re, input,
                                RegExpShared::CodeKind::Jitcode)) {
          return RegExpRunStatus::Error;
        }
        continue;                            // <-- retry with OLD `re`
      }
    }
    ...
  }
  return result;                             // <-- Success, matches filled by OLD `re`
} while (true);

re is a MutableHandleRegExpShared rooted in ExecuteRegExp (RegExp.cpp:1580). It stays pointing at the old shared after re.compile() swaps the RegExpObject slot. The bug is in the caller.

Desync point — /firefox/js/src/builtin/RegExp.cpp, lines 1799–1811 (RegExpBuiltinExecMatchRaw):

VectorMatchPairs matches;
RegExpRunStatus status =
    ExecuteRegExp(cx, regexp, input, lastIndex, &matches);  // matches ← 22 pairs (OLD shared)
...
} else {
  RootedRegExpShared shared(cx, regexp->as<RegExpObject>().getShared()); // <-- RE-READ: NEW shared (60 groups)
  if (!CreateRegExpMatchResult(cx, shared, input, matches, output)) {    // <-- MISMATCH
    return false;
  }

OOB sink — /firefox/js/src/builtin/RegExp.cpp, lines 121–126 + 250–261:

size_t numPairs = matches.length();                          // = 22
Rooted<ArrayObject*> arr(
    cx, NewDenseFullyAllocatedArrayWithShape(cx, numPairs, shape));  // 22 dense elements

// ... arr filled with 22 elements ...

for (uint32_t i = 0; i < re->numDistinctNamedCaptures(); i++) {  // 60 iterations (NEW shared)
  getValueAndIndex(re, i, arr, &val, valueIndex);
  //   valueIndex = re->getNamedCaptureIndex(i);             // up to 60
  //   val.set(arr->getDenseElement(valueIndex));            // OOB READ for valueIndex >= 22
  groups->initSlot(i, val);   // <-- garbage heap bytes stored as JS::Value
  //   HeapSlot::post -> cell->storeBuffer() -> (addr & ~ChunkMask)->storeBuffer
  //   CRASH: wild pointer dereference at 0x7f6161600000
}

getDenseElement at /firefox/js/src/vm/NativeObject.h:725 is guarded only by MOZ_ASSERT (debug-only). The OOB read lands in adjacent GC-arena memory (inline elements are contiguous with other cells), which frequently has tag-pattern bits that parse as object Values. Cell::storeBuffer() at /firefox/js/src/gc/Cell.h:372 computes (payload & ~ChunkMask)->storeBuffer, dereferencing the wild chunk-aligned address in rdi=0x7f6161600000. r13=0x17 (23) is the loop counter: getNamedCaptureIndex(23)=24 > 22.

Correct Pattern

ExecuteRegExpLegacy at /firefox/js/src/builtin/RegExp.cpp:370–403 already does this correctly — it passes the same RootedRegExpShared to both ExecuteRegExpImpl and CreateRegExpMatchResult:

RootedRegExpShared shared(cx, RegExpObject::getShared(cx, reobj));
...
RegExpRunStatus status =
    ExecuteRegExpImpl(cx, res, &shared, input, *lastIndex, &matches, reobj);
...
return CreateRegExpMatchResult(cx, shared, input, matches, rval);  // same `shared`

Exploit Chain

  1. Create regex re = /^(a+)*a{25}(b)...(u)$/ (catastrophic backtracking, 21 capture groups, pairCount()=22).
  2. Raise InterruptReason::CallbackUrgent via interruptIf(true); set setInterruptCallback("true") so the shell interrupt handler creates a new global.
  3. Register Debugger.onNewGlobalObject in a separate non-debuggee compartment (avoids DebuggeeWouldRun). The hook uses unsafeDereference() to reach the main global and calls re.compile(patternWith60NamedGroups) + re.exec(...), swapping SHARED_SLOT to a new RegExpShared with 60 named captures and a populated groups template.
  4. re.exec(input) → RegExpShared::execute allocates 22-pair matches, irregexp interpreter hits backtracking, checks InterruptRequested(), returns Error.
  5. CheckForInterrupt(cx) → shell callback → new global → onNewGlobalObject fires → slot swapped.
  6. Retry loop continues with old rooted re, JIT-compiles it, executes, fills 22 pairs, returns Success.
  7. RegExpBuiltinExecMatchRaw:1809 re-reads slot → new shared.
  8. CreateRegExpMatchResult: arr has 22 elements, loop runs 60 times, getDenseElement(24..60) reads adjacent GC cells as Values, initSlot post-barrier dereferences garbage → SEGV.

Security Impact

Severity: High (sec-high).

  • Primitive: OOB heap read (adjacent GC cells) reinterpreted as JS::Value, stored into JS-visible groups object.
  • Info leak: Double-tagged OOB bytes expose heap pointer bits to JS.
  • Fake object: Object-tagged OOB bytes whose barrier survives become a forged JSObject* reachable from script — arbitrary R/W with heap grooming.
  • The SEGV is the most common outcome, not the only one.
  • Preconditions: Interrupt callback that synchronously runs JS during regex execution (shell: setInterruptCallback + Debugger hooks). The engine-level invariant violation (re-reading SHARED_SLOT after execute() may run JS) is the bug regardless of browser reachability.
  • Also affected: RegExpMatcherImpl at /firefox/js/src/builtin/RegExp.cpp:1635 (identical pattern).

Suggested Fix

Add a MutableHandleRegExpShared out-param to ExecuteRegExp so callers use the shared that actually performed the match:

// /firefox/js/src/builtin/RegExp.cpp
static RegExpRunStatus ExecuteRegExp(JSContext* cx, HandleObject regexp,
                                     HandleString string, int32_t lastIndex,
                                     VectorMatchPairs* matches,
                                     MutableHandleRegExpShared reOut) {
  Handle<RegExpObject*> reobj = regexp.as<RegExpObject>();
  reOut.set(RegExpObject::getShared(cx, reobj));
  if (!reOut) return RegExpRunStatus::Error;
  ...
  return ExecuteRegExpImpl(cx, res, reOut, input, lastIndex, matches, reobj);
}

// RegExpBuiltinExecMatchRaw ~1799:
VectorMatchPairs matches;
RootedRegExpShared shared(cx);
RegExpRunStatus status =
    ExecuteRegExp(cx, regexp, input, lastIndex, &matches, &shared);
...
} else {
  // DO NOT re-read regexp->getShared()
  if (!CreateRegExpMatchResult(cx, shared, input, matches, output)) {
    return false;
  }

Apply the same fix to RegExpMatcherImpl at line 1635. Defense-in-depth: add MOZ_RELEASE_ASSERT(valueIndex < arr->getDenseInitializedLength()) in the named-capture loop.

Attached file Crash stack trace —
Group: core-security → javascript-core-security
Attachment #9554335 - Attachment mime type: application/javascript → text/plain
Keywords: bugmon

Verified bug as reproducible on mozilla-central 20260318213336-e52ef55079f7.
Unable to bisect testcase (Testcase reproduces on start build!):

Start: 0a488da1e966f05a7c1b0c71c594e9a8e28204a3 (20251220202405)
End: e52ef55079f792c6f0cb79aa121a119866637e1f (20260318213336)
BuildFlags: BuildFlags(asan=False, tsan=False, debug=True, fuzzing=True, coverage=False, valgrind=False, no_opt=False, fuzzilli=False, nyx=False, searchfox=False, afl=False)

Whiteboard: [bugmon:bisected,confirmed]

We should double check but if this really requires debugger onNewGlobalObject trickery this isn't sec-high. Using the hook is a clever loophole Claude found; we should fix that.

Yes, this is bogus for similar reasons to bug 2023006. In shell fuzzing builds, we try to sandbox interrupt handlers by evaluating a string in a new global, in an attempt to prevent fuzzers from writing interrupt handlers that modify arbitrary data in the interrupted realm (since that doesn't happen in real interrupt handlers in the browser.) In bug 2023006, Claude used the debugger inside the interrupt handler to gain access to the original global. In this bug, it's taking advantage of the implementation details of our sandbox to trigger arbitrary behaviour in the onNewGlobalObject hook. Neither of these cases is relevant to the browser; they just circumvent our attempts to make fuzzing the shell more relevant to the real world.

We could consider making the sandboxed global not fire the onNewGlobalObject hook to prevent this from arising in the future, but more realistically I think we should just teach Claude (either from in-tree comments or something in the prompt) that shell interrupt handlers are not an interesting attack surface.

Keywords: sec-high → sec-other
Duplicate of this bug: 2024828

Bug 2024828 is similar but uses a different debugger loophole (addAllGlobalsAsDebuggees). It also says "and the embedding may spin nested event loops". We should double check that can't happen here.

Severity: -- → S4
Priority: -- → P3
Keywords: csectype-bounds
Whiteboard: [bugmon:bisected,confirmed] → [bugmon:bisected,confirmed][prefs-checked]

Triage notes:

  • No prefs are required to reproduce (only shell-only APIs like setInterruptCallback / Debugger), so the configuration is supported — adding [prefs-checked].
  • Bug is already sec-other and comments 5/6 explain it's a shell-only fuzzing-harness artifact not reachable from the browser. Removing csectype-bounds since it only applies to actual sec bugs. Not producing a fix patch given the shell-only nature.

This is an automated analysis result. If this result is incorrect please add a needinfo and feel free to correct the error.

Testcase crashes using the initial build (mozilla-central 20260318213336-e52ef55079f7) but not with tip (mozilla-central 20260411091926-496be9d3e8d5.)

The bug appears to have been fixed in the following build range:

Start: bc10d899b08ed38923bab88e333b4f968d4faa40 (20260407161548)
End: 5d29050b2516bfea2e8f3533fd451525529201c4 (20260407162108)
Pushlog: https://hg.mozilla.org/integration/autoland/pushloghtml?fromchange=bc10d899b08ed38923bab88e333b4f968d4faa40&tochange=5d29050b2516bfea2e8f3533fd451525529201c4

bugmon, can you confirm that the above bisection range is responsible for fixing this issue?
Removing bugmon keyword as no further action possible. Please review the bug and re-add the keyword for further analysis.

Flags: needinfo?(bugmon)
Keywords: bugmon
Flags: needinfo?(jdemooij)
Flags: needinfo?(bugmon)

Fixed by bug 2027272. Leaving open for :jandem to resolve the thread in comment 8.

See Also: → 2027272

I looked at the code in nsGlobalWindowInner::ShowSlowScriptDialog. The e10s content process code path is a lot cleaner than the old slow script dialog code. The main interesting case that's left is the debugger code (the next interrupt after the user clicks "debug" in the slow script banner) because we do spin a nested event loop there while starting the debugger, but here we also suppress all events through SuppressEventHandling.

Status: UNCONFIRMED → RESOLVED
Closed: 7 months ago
Duplicate of bug: 2027272
Flags: needinfo?(jdemooij)
Resolution: --- → DUPLICATE
Group: javascript-core-security
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: