Closed Bug 2052059 Opened 4 months ago Closed 4 months ago

SpiderMonkey Parallel WeakMap Ephemeron OOM Use-After-Free Enables Browser Native Code Execution

Categories

(Core :: JavaScript: GC, defect)

Firefox 154
defect

Tracking

()

RESOLVED DUPLICATE of bug 2046917

People

(Reporter: amyb, Unassigned)

Details

(Keywords: ai-involved, csectype-uaf, reporter-external)

Attachments

(5 files)

User Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36

Steps to reproduce:

Security Report: SpiderMonkey Parallel WeakMap Ephemeron OOM Use-After-Free Enables Browser Native Code Execution

Reporter: OpenAI Codex Security
Organization: OpenAI
Component: Mozilla Firefox / SpiderMonkey (parallel garbage collection and WeakMap ephemeron marking)
Affected Area: ParallelMarkTask::markDeferredWeakmaps, GCMarker::abortLinearWeakMarking, WeakMapBase::addEphemeronEdge, weak-reference sweeping
Bug Class: Per-worker GC failure-state desynchronization -> incomplete ephemeron marking -> use-after-free -> cross-kind type confusion -> arbitrary read/write -> native code execution


Summary

SpiderMonkey contains a use-after-free in parallel WeakMap marking that has
been present since parallel marking was implemented in December 2022 and has
been enabled by default in stable desktop Firefox since Firefox 124.

The linear-time WeakMap marking algorithm records key-to-value ephemeron edges
in a zone-wide table. Adding an edge is fallible. If an allocation fails, the
collector must stop trusting the incomplete table and use iterative WeakMap
marking for the remainder of the collection.

Parallel marking uses multiple GCMarker instances, one for each mark task.
The state that records whether every ephemeron edge was added,
haveAllImplicitEdges, is stored separately in each marker. Deferred WeakMaps
can be drained by a helper task using that task's marker. If growing the
ephemeron table fails on the helper, abortLinearWeakMarking() clears only the
helper marker's flag. The main marker's copy remains true.

Weak-reference processing later calls enterWeakMarkingMode() on the main
marker. Because its local flag still says the ephemeron table is complete, it
enters linear weak marking and skips the iterative fallback. Values reachable
through the omitted edges remain white even though their WeakMaps and keys are
black. Release Firefox then finalizes the values while retaining the live
WeakMap entries, and WeakMap.prototype.get() returns dangling GC pointers.

The attached browser exploit demonstrates the use-after-free and native code
execution on Firefox 154.0a1. It uses a reliable trigger path added in June
2026: ordinary JavaScript reserves and fragments virtual address space with
zero-length resizable ArrayBuffer objects, then forces an existing ephemeron
table to grow while a parallel helper drains deferred WeakMaps. The omitted
values are rope strings. After sweeping, an Array spray reuses their 24-byte
cells. The stale WeakMap values retain String tags, so SpiderMonkey interprets
controlled Array fields as rope metadata and string-child pointers.

The June 2026 deferred-WeakMap path is not the vulnerability. It is the helper
allocation-failure trigger used by the attached exploit. Firefox 124 through
Firefox 152 contain the same use-after-free through the older parallel
WeakMap::trace() path: a helper marker can call markEntries(), fail while
adding an ephemeron edge, and clear only its own validity flag. Reaching that
failure with a stable-specific allocation strategy produces the same omitted
live value and the same dangling WeakMap entry. The cell-reuse, arbitrary
read/write, and native code execution stages operate after the use-after-free
and do not depend on deferred WeakMap processing.

Two stale strings provide the exploit primitives:

first stale string:
    discloses exact addresses of controlled typed arrays and a Wasm function

second stale string:
    overwrites one typed array's data pointer with an attacker-selected address

The resulting typed-array alias provides 64-bit arbitrary read/write in the
Firefox content process. The exploit uses it to locate attacker-selected bytes
in executable Wasm JIT code, replace a Wasm function's native entry fields with
that address, and invoke the function. The native payload executes:

execve("/bin/sh", ["/bin/sh", "-c", "id > /tmp/i"], NULL)

No SpiderMonkey shell API, JavaScript engine flag, experimental preference,
profile mutation, cache mutation, or modified Firefox binary is required for
the demonstrated Firefox 154.0a1 chain. The page uses standard JavaScript and
WebAssembly APIs. The content sandbox is disabled only for the shell-command
demonstration; the memory corruption, arbitrary read/write, and native
instruction-pointer redirection occur in the Firefox content process before
that boundary.

Impact

A malicious web page can cause the parallel collector to finalize live
WeakMap values, reclaim the cells as attacker-controlled objects, and continue
using the dangling values under their original String tags.

The browser exploit performs the following operations:

1. Causes a real ephemeron-table allocation failure on a parallel helper.
2. Leaves live WeakMap string values white and allows them to be finalized.
3. Reclaims the string cells with Array objects of the same GC allocation size.
4. Uses the stale String view to disclose exact GC heap addresses.
5. Uses a second stale String view to corrupt a typed-array data pointer.
6. Reads and writes arbitrary 64-bit values in the content process.
7. Locates attacker-selected bytes in an executable Wasm JIT mapping.
8. Replaces a Wasm function's native entry fields with the payload address.
9. Calls the function and executes native x86-64 instructions.
10. Invokes /bin/sh -c "id > /tmp/i" when the content sandbox is disabled.

The arbitrary read/write proof reads the live BigUint64Array length field,
changes it from 16 to 1, observes the JavaScript object's length become
1, restores the field, and observes the length return to 16:

browser-targets-209bb73e4088-209bb73e30e8-209bb73e3078-two-byte
write-candidate-8347-two-byte
write-configured-8347-two-byte
write-returned-8347-two-byte
controller-target-a7c5603c00
arbitrary-read-10
arbitrary-write-observed-length-1
arbitrary-write-restored-length-16
browser-arbitrary-read-write-true

The final native payload creates /tmp/i. A successful run produces content
equivalent to:

uid=0(root) gid=0(root) groups=0(root)

Root Cause (High Level)

The collector maintains one logical invariant using independent per-worker
state:

global invariant:
    every required WeakMap ephemeron edge was added successfully

actual representation:
    each GCMarker has a separate haveAllImplicitEdges flag

failure path:
    helper marker observes allocation failure and clears only its own flag

later decision:
    main marker consults only its still-true flag and trusts the shared table

The ephemeron-edge table itself is zone-wide, but the validity bit governing
that table is marker-local. A failure in any worker invalidates the shared
table for the entire collection, so the validity state cannot safely be local
to the worker that encountered the failure.

The iterative fallback is present and correct. It is skipped only because the
main marker is never told that a helper failed to populate the table.

Affected Versions

Affected build:

Firefox source revision: 9b76a2f882af6691de21dfe290f8175c9bedce7b
Firefox milestone: 154.0a1
Build: unmodified release Firefox
Architecture: Linux x86-64
Trigger: ordinary HTTP page, standard JavaScript and WebAssembly APIs

The underlying failure-state bug was introduced by:

5bf9244ab9a20bc0dce43346be847580d91b1f32
Bug 1802897 - Part 9: Implement parallel marking
Commit date: 2022-12-07

https://github.com/mozilla-firefox/firefox/commit/5bf9244ab9a20bc0dce43346be847580d91b1f32

That commit added ParallelMarker and ParallelMarkTask, gave each task a
different GCMarker, and allowed helpers to trace GC objects and their WeakMap
entries. haveAllImplicitEdges remained a member of each marker. An ephemeron
allocation failure encountered while a helper traced a WeakMap therefore
invalidated only the helper marker even though every worker populated the same
zone-wide ephemeron table.

Parallel marking was initially pref-gated. It became enabled by default in
desktop Firefox in:

129bcbde9046e55c88bf6671ece8466156c6daa5
Bug 1875117 - Ship GC parallel marking
Commit date: 2024-01-22

https://github.com/mozilla-firefox/firefox/commit/129bcbde9046e55c88bf6671ece8466156c6daa5

Firefox 124 is the first stable desktop release whose release tag contains the
shipping commit.

The trigger path used by the attached exploit was added by:

96e25e0bbc490a8311e580fdf9c1de42790b4f9a
Bug 1991980 - Reorder marking to delay tracing a WeakMap's entries until
everything else has been marked
Commit date: 2026-06-11

https://github.com/mozilla-firefox/firefox/commit/96e25e0bbc490a8311e580fdf9c1de42790b4f9a

That commit added the shared deferred-WeakMap lists and
ParallelMarkTask::markDeferredWeakmaps(). Any task can become the task that
drains a deferred list, and it processes the list with its own marker. The
reordering therefore provides the direct helper-thread edge-table growth path
used by the browser proof-of-concept, but it is not the origin of the
per-marker validity-state defect.

Release-tag containment gives the following channel status as of 2026-07-01:

Firefox 123 and earlier: parallel marking not shipped by default
Firefox 124 through Firefox 152.0.4: affected
Firefox 153.0 beta: affected beginning with 153.0b1
Firefox 154.0a1 Nightly: affected with working exploit POC
Current stable Firefox 152: affected

Here, "affected" refers to the underlying helper-marker failure-state bug and
resulting WeakMap use-after-free. The complete browser native-code-execution
proof was validated on the Firefox 154.0a1 revision listed above and uses the
newer deferred-WeakMap trigger. The supplied HTML does not claim to be a
stable-release exploit without replacing that first-stage trigger.

The latest upstream main revision checked for this report is:

Firefox main: 0a7f146ccac85b8f413264042dcd764028d419ec
Firefox milestone: 154.0a1
Commit date: 2026-07-01 19:25:44 UTC

Current main still stores haveAllImplicitEdges in each GCMarker, still
processes deferred WeakMaps with the current parallel task's marker, and still
uses only marker() (marker zero) to select linear or iterative weak marking:

https://github.com/mozilla-firefox/firefox/blob/0a7f146ccac85b8f413264042dcd764028d419ec/js/src/gc/GCMarker.h#L707-L712

https://github.com/mozilla-firefox/firefox/blob/0a7f146ccac85b8f413264042dcd764028d419ec/js/src/gc/ParallelMarking.cpp#L213-L223

https://github.com/mozilla-firefox/firefox/blob/0a7f146ccac85b8f413264042dcd764028d419ec/js/src/gc/Marking.cpp#L2848-L2853

https://github.com/mozilla-firefox/firefox/blob/0a7f146ccac85b8f413264042dcd764028d419ec/js/src/gc/Sweeping.cpp#L645-L674

No upstream fix is present at that revision.


Detailed Analysis

Each Parallel Task Uses a Different GCMarker

GCRuntime stores all markers in a vector but defines marker() as marker
zero, the marker used by the main thread:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/GCRuntime.h#L559-L567

// Get the marking tracer used on the main thread.
GCMarker& marker() { return *markers[0]; }
const GCMarker& marker() const { return *markers[0]; }

// Get the marking tracer used for concurrent marking.
GCMarker& concurrentMarker() {
  MOZ_ASSERT(isConcurrentMarkingEnabled());
  return *markers[1];
}

Parallel marking creates one task for each marker. Task zero runs on the main
thread, while the remaining tasks run on helpers:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/ParallelMarking.cpp#L62-L105

size_t ParallelMarker::workerCount() const { return gc->markers.length(); }

bool ParallelMarker::mark(const SliceBudget& sliceBudget) {
  ...
  for (size_t i = 0; i < workerCount(); i++) {
    GCMarker* marker = gc->markers[i].get();
    tasks[i].emplace(this, marker, color, i, sliceBudget);
    ...
  }
  ...
  // Run the parallel tasks, using the main thread for the first one.
  for (size_t i = 1; i < workerCount(); i++) {
    gc->startTask(*tasks[i], lock);
  }
  tasks[0]->runFromMainThread(lock);

The validity state for the shared ephemeron-edge table is a field of
GCMarker, not GCRuntime or Zone:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/GCMarker.h#L707-L712

/* Track the state of marking. */
MainThreadOrGCTaskData<MarkingState> state;

/* Whether we successfully added all edges to the implicit edges table. */
MainThreadOrGCTaskData<bool> haveAllImplicitEdges;

Every marker starts with its own flag set to true:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/Marking.cpp#L2548-L2554

void GCMarker::start() {
  MOZ_ASSERT(state == NotActive);
  MOZ_ASSERT(stack.isEmpty());
  state = RegularMarking;
  haveAllImplicitEdges = true;
  setMarkColor(MarkColor::Black);
}

Stable Releases Populate Ephemeron Edges With Helper Markers

Before deferred WeakMap processing was added, tracing a WeakMap during normal
parallel marking immediately called markEntries() with the marker recovered
from the current task's tracer. This is the path present in Firefox 124 through
Firefox 152:

https://github.com/mozilla-firefox/firefox/blob/d4faced9e237d6431856c0873cb035cbbc25817b/js/src/gc/WeakMap-inl.h#L298-L327

void WeakMap<K, V, AP>::trace(JSTracer* trc) {
  ...
  if (trc->isMarkingTracer()) {
    GCMarker* marker = GCMarker::fromTracer(trc);
    mozilla::Maybe<gc::CellColor> markResult = markMap(marker->markColor());
    if (markResult.isSome()) {
      mozilla::Maybe<AutoLockGC> lock;
      if (marker->isParallelMarking()) {
        lock.emplace(marker->runtime());
      }
      ...
      (void)markEntries(marker);
    }
    return;
  }

Incremental WeakMap marking causes that call to populate the shared ephemeron
table:

https://github.com/mozilla-firefox/firefox/blob/d4faced9e237d6431856c0873cb035cbbc25817b/js/src/gc/WeakMap-inl.h#L358-L384

bool populateWeakKeysTable =
    marker->incrementalWeakMapMarkingEnabled || marker->isWeakMarking();

...
for (auto iter = modIter(); !iter.done(); iter.next()) {
  if (markEntry(marker, mapColor, iter, populateWeakKeysTable)) {
    markedAny = true;
  }
}

When a helper owns the tracer, an edge-allocation failure therefore clears the
helper's haveAllImplicitEdges while marker zero remains true. The June 2026
reordering changed when and where WeakMap entries are processed, but the
failure-state mismatch was already reachable through this stable-release
path.

A Helper Can Drain the Shared Deferred-WeakMap List

When a task has no mark-stack work and no other task remains active, it checks
the shared deferred-WeakMap list. The task that reaches this state drains the
list:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/ParallelMarking.cpp#L159-L180

void ParallelMarkTask::run(AutoLockHelperThreadState& lock) {
  AutoUpdateMarkStackRanges updateRanges(*marker);

  for (;;) {
    if (hasWork()) {
      ...
    } else if (pm->hasActiveTasks(lock)) {
      ...
    } else if (gc->hasDeferredWeakMaps(pm->color)) {
      // All marking is done, but there are deferred weakmaps to process.
      markDeferredWeakmaps(lock);
    } else {
      break;
    }
  }

markDeferredWeakmaps() moves the global list to a local list and calls
markDeferredWeakMapChildren() with the current task's marker:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/ParallelMarking.cpp#L213-L226

void ParallelMarkTask::markDeferredWeakmaps(AutoLockHelperThreadState& lock) {
  MOZ_ASSERT(!pm->hasActiveTasks(lock));

  WeakMapList deferred(std::move(gc->deferredMapsList(pm->color)));

  {
    AutoUnlockHelperThreadState unlock(lock);
    marker->markDeferredWeakMapChildren(deferred);
  }
  ...
}

The marker then visits every entry in each deferred map:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/Marking.cpp#L1498-L1508

void GCMarker::markDeferredWeakMapChildren(WeakMapList& deferred) {
  enterSingleThreadedMode();
  while (js::WeakMapBase* map = deferred.popFirst()) {
    (void)map->markEntries(this);
    MOZ_ASSERT(!map->isSystem());
    map->zone()->gcMarkedUserWeakMaps().pushBack(map);
  }
  leaveSingleThreadedMode();
}

Nothing requires the task that drains this list to be task zero. A helper task
therefore calls markEntries() using a helper marker.

Ephemeron-Edge Construction Is Fallible

If a WeakMap key is not yet as marked as its map, SpiderMonkey records the
conditional key-to-value edge. Failure calls abortLinearWeakMarking() on the
marker currently processing the entry:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/WeakMap-inl.h#L264-L291

if (populateWeakKeysTable) {
  ...
  if (keyColor < mapColor) {
    ...
    if (!this->addEphemeronEdgesForEntry(AsMarkColor(mapColor),
                                         &keyCell->asTenured(), delegate,
                                         tenuredValue)) {
      marker->abortLinearWeakMarking();
    }
  }
}

Both creating a table entry and appending to its edge vector can fail:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/WeakMap.cpp#L128-L140

bool WeakMapBase::addEphemeronEdge(MarkColor color, gc::TenuredCell* src,
                                   gc::TenuredCell* dst) {
  auto& edgeTable = src->zone()->gcEphemeronEdges();
  auto p = edgeTable.lookupForAdd(src);
  if (!p) {
    if (!edgeTable.add(p, src, EphemeronEdgeVector())) {
      return false;
    }
  }
  return p->value().emplaceBack(color, dst);
}

This is an expected allocation-failure path. The collector already has an
iterative algorithm that does not depend on the table being complete.

The Failure Invalidates Only the Helper Marker

abortLinearWeakMarking() modifies only the current GCMarker:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/Marking.cpp#L2806-L2811

void GCMarker::abortLinearWeakMarking() {
  haveAllImplicitEdges = false;
  if (state == WeakMarking) {
    leaveWeakMarkingMode();
  }
}

When this runs on marker N, marker zero remains unchanged:

marker N: haveAllImplicitEdges = false
marker 0: haveAllImplicitEdges = true
zone ephemeron table: incomplete

The shared table and the marker-zero validity flag now disagree.

Sweeping Trusts Marker Zero's Stale Flag

Weak-reference processing uses marker(), which is marker zero. It does not
consult the marker that processed the deferred WeakMaps or aggregate validity
across all markers:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/Sweeping.cpp#L604-L670

IncrementalProgress GCRuntime::markWeakReferences(
    SliceBudget& incrementalBudget) {
  MOZ_ASSERT(!marker().isWeakMarking());
  ...
  if (marker().enterWeakMarkingMode()) {
    ...
    for (ZoneIterT zone(this); !zone.done(); zone.next()) {
      if (!marker().isWeakMarking()) {
        break;
      }
      if (zone->enterWeakMarkingMode(&marker(), budget) == NotFinished) {
        return NotFinished;
      }
    }
  }

enterWeakMarkingMode() decides whether the linear algorithm is safe by
reading only the receiving marker's flag:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/Marking.cpp#L2728-L2746

bool GCMarker::enterWeakMarkingMode() {
  MOZ_ASSERT(tracer()->weakMapAction() == JS::WeakMapTraceAction::Expand);
  if (!haveAllImplicitEdges) {
    return false;
  }
  ...
  setMarkingStateAndTracer<WeakMarkingTracer>(RegularMarking, WeakMarking);
  return true;
}

Because marker zero's flag is still true, it enters weak marking and scans the
incomplete table.

The iterative fallback runs only when marker zero is not in weak-marking mode:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/Sweeping.cpp#L678-L692

bool markedAny = true;
while (markedAny) {
  ...
  markedAny = false;

  if (!marker().isWeakMarking()) {
    for (ZoneIterT zone(this); !zone.done(); zone.next()) {
      markedAny |= WeakMapBase::markZoneIteratively(zone, &marker());
    }
  }
}

The stale true flag therefore suppresses the exact fallback intended to make
allocation failure safe.

The Consistency Check Is Absent From Release Firefox

SpiderMonkey has a check that detects a marked WeakMap and marked key whose
value is less marked:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/WeakMap.cpp#L142-L155

#if defined(JS_GC_ZEAL) || defined(DEBUG)
bool WeakMapBase::checkMarkingForZone(JS::Zone* zone) {
  bool ok = true;
  ForAllWeakMapsInZone(zone, [&ok](WeakMapBase* map) {
    if (map->isMarked() && !map->checkMarking()) {
      ok = false;
    }
  });
  return ok;
}
#endif

Sweeping invokes it through a MOZ_RELEASE_ASSERT, but the entire function is
compiled only for Debug or GC-zeal builds:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/gc/Sweeping.cpp#L1251-L1267

static inline void MaybeCheckWeakMapMarking(GCRuntime* gc) {
#if defined(JS_GC_ZEAL) || defined(DEBUG)
  ...
  if (shouldCheck) {
    for (SweepGroupZonesIter zone(gc); !zone.done(); zone.next()) {
      MOZ_RELEASE_ASSERT(WeakMapBase::checkMarkingForZone(zone));
    }
  }
#endif
}

Debug builds stop before sweeping with a diagnostic that the value is white.
Release Firefox has no equivalent release-effective guard. It finalizes the
white value while the black-keyed entry remains in the WeakMap.

Reclaiming the Finalized String as an Array

The exploit makes the omitted WeakMap values rope strings and arranges for the
surrounding string cells to be finalized in the same collection. It then
sprays tenured Array objects whose allocation size matches JSString.

The WeakMap entry retains the original String value tag. When its finalized
cell is reused as an Array, string operations interpret the Array object's
fields using the rope layout. The relevant string union stores rope children
in the same two pointer fields used by other string representations:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/vm/StringType.h#L295-L332

struct Data {
  ...
  struct {
    union {
      const JS::Latin1Char* nonInlineCharsLatin1;
      const char16_t* nonInlineCharsTwoByte;
      JSString* left;  /* JSRope */
      JSRope* parent;
    } u2;
    union {
      JSLinearString* base;
      JSAtom* atom;
      JSString* right; /* JSRope */
      size_t capacity;
      ...
    } u3;
  } s;
};

JSRope consumes those fields directly:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/vm/StringType.h#L874-L907

JSString* leftChild() const {
  MOZ_ASSERT(isRope());
  MOZ_ASSERT(!isBeingFlattened());
  return d.s.u2.left;
}

JSString* rightChild() const {
  MOZ_ASSERT(isRope());
  return d.s.u3.right;
}

static_assert(sizeof(JSRope) == sizeof(JSString),
              "string subclasses must be binary-compatible with JSString");

The reclaimed Array supplies controlled dynamic slots and dense elements at
the locations interpreted as the rope's child strings. The exploit places
valid inline-string headers in those buffers. Flattening the stale rope then
copies raw controlled JS::Value words into a readable string, disclosing the
tagged addresses of scratch, rw1, rw2, and a warmed Wasm function.

Converting the Stale String Into Arbitrary Read/Write

The first stale string is used only for disclosure. The second stale string is
configured as an extensible string containing a nested rope. During
flattening, the forged child and capacity fields make SpiderMonkey write the
address of rw2's data-pointer field into the first element of rw1.

After that write:

rw1[0] controls the pointer stored in rw2's data-pointer field
rw2[0] reads or writes eight bytes through that pointer

The exploit defines the primitives as:

function arbRead64(address) {
  rw1[0] = address;
  return rw2[0];
}

function arbWrite64(address, value) {
  rw1[0] = address;
  rw2[0] = value;
}

Reading the address of rw2's length field returns 0x10. Writing 1 to the
same address changes the live typed array's JavaScript-visible length to one,
and restoring 0x10 changes it back to sixteen.

Redirecting a Wasm Function to Attacker-Selected Native Code

The exploit creates and warms a small exported Wasm function before triggering
the GC bug. Its function body materializes attacker-selected f64 constants,
causing the exact constant bytes to appear in the function's executable JIT
code.

For native functions, JSFunction stores both the native method pointer and a
native JIT entry in fixed slots:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/vm/JSFunction.h#L68-L99

/*
 * For native functions, the native method pointer stored as a private
 * value, or undefined.
 */
NativeFuncOrInterpretedEnvSlot,

/*
 * For native functions this is one of:
 * ...
 *  - a native JIT entry (used for Wasm and TrampolineNative functions)
 */
NativeJitInfoOrInterpretedScriptSlot,

Wasm functions expose the JIT-entry cell through this slot:

https://github.com/mozilla-firefox/firefox/blob/9b76a2f882af6691de21dfe290f8175c9bedce7b/js/src/vm/JSFunction.h#L665-L695

void** nativeJitEntry() const {
  MOZ_ASSERT(isNativeWithJitEntry());
  return static_cast<void**>(nativeJitInfoOrInterpretedScript());
}

void initWasmWithJitEntry(void** entry, js::wasm::Instance* instance,
                          const js::wasm::SuperTypeVector* superTypeVector,
                          void* uncheckedCallEntry);

void** wasmJitEntry() const {
  MOZ_ASSERT(isWasmWithJitEntry());
  return nativeJitEntry();
}

The exploit uses arbitrary read to obtain both fields and the code pointer in
the JIT-entry cell. It aligns that pointer to the executable page, scans the
page for the first eight payload bytes, and verifies every payload byte before
changing control flow.

It then writes the payload address to both the native entry field and the
JIT-entry cell. Calling the ordinary JavaScript WebAssembly export transfers
execution to the verified payload address.

Native Payload

The x86-64 payload performs:

1. Construct "/bin/sh", "-c", "id > /tmp/i", and argv[] on the native stack.
2. Invoke execve through the Linux x86-64 system-call interface.
3. Execute the command in the Firefox content process when its sandbox is
   disabled for the demonstration.

The payload does not require a fixed JIT address. The exploit obtains the live
Wasm function and JIT-entry addresses through the arbitrary-read primitive,
then finds and verifies the payload inside that exact executable mapping.

Exploitation Strategy

The browser exploit uses two WeakMaps to build mutually dependent ephemeron
chains. Each map is first populated to its final capacity while only half of
the conditional edges remain active. This establishes the WeakMap storage
without requiring the large ephemeron table during the preparatory
collections.

The exploit then reinserts the second half of the entries without growing the
WeakMaps themselves. Zero-length resizable ArrayBuffer objects reserve the
remaining virtual-address ranges from large to small. Because the buffers have
zero current length, the reservations fragment address space without
committing an equivalent amount of physical memory.

The next parallel major collection must grow the zone's ephemeron-edge table
for the newly active entries. A helper task drains the deferred maps and
encounters the allocation failure. The helper abandons linear weak marking
only in its own GCMarker; marker zero proceeds with the incomplete table.

The exploit proceeds in this order:

1. Create mutually dependent WeakMap entries and tenure the graph.
2. Reinsert the deferred half of the graph without growing the WeakMaps.
3. Fragment virtual address space with zero-length resizable ArrayBuffers.
4. Trigger a parallel major GC and fail ephemeron-table growth on a helper.
5. Allow release sweeping to finalize omitted rope-string values.
6. Spray Arrays to reclaim the finalized 24-byte string cells.
7. Read reclaimed Array fields through a stale rope to disclose GC addresses.
8. Flatten a second stale rope to corrupt a typed-array data pointer.
9. Use the typed arrays for 64-bit arbitrary read/write.
10. Locate and verify the native payload in warmed Wasm JIT code.
11. Replace the Wasm function's native entry fields with the payload address.
12. Invoke the export and execute id > /tmp/i through /bin/sh.

The exploit is stochastic because it depends on parallel task scheduling,
allocation failure placement, and exact GC-cell reuse. Each attempt uses a
fresh Firefox content process. A successful attempt completes the full chain
from an ordinary page.

Stable-Release Exploitation

Firefox 124 through Firefox 152 do not contain the deferred-WeakMap processing
used by the demonstrated first stage. They do contain the same vulnerable
state transition through direct parallel WeakMap tracing:

helper traces a WeakMap
    -> WeakMap::trace() calls markEntries() with the helper marker
    -> ephemeron-edge allocation fails
    -> helper marker clears only its local haveAllImplicitEdges
    -> marker zero enters linear weak marking with an incomplete table
    -> live WeakMap value is finalized
    -> WeakMap.get() returns the dangling value

A stable-specific exploit therefore needs a different allocation and
scheduling strategy to make the ephemeron allocation fail during direct
WeakMap::trace() rather than during deferred-list draining. Once the stale
WeakMap value exists, the Array reclaim, typed-array arbitrary read/write,
and Wasm entry redirection stages are independent of which helper-marking path
omitted the edge. This makes exploitation of the stable-release use-after-free
likely, although the supplied end-to-end HTML validates the complete chain on
the newer deferred-list path.

Proof of Concept

The primary browser proof-of-concept is:

parallel-ephemeron-oom-browser-native-code-execution.html

The standalone arbitrary read/write proof is:

parallel-ephemeron-oom-browser-arw.html

Serve the exploit directory over HTTP:

python3 -m http.server 8000 --bind 127.0.0.1

For the native shell-command demonstration, remove any prior result and launch
the affected Firefox build with its content sandbox disabled:

rm -f /tmp/i
MOZ_DISABLE_CONTENT_SANDBOX=1 /path/to/firefox \
  http://127.0.0.1:8000/parallel-ephemeron-oom-browser-native-code-execution.html

The HTML file contains the WeakMap graph, virtual-address pressure, GC-cell
spray, stale-string primitives, WebAssembly function, native payload, and the
JavaScript needed to complete the chain.

A successful run reaches these milestones:

browser-arbitrary-read-write-true
wasm-entry-<native-entry>-<jit-entry-cell>-<wasm-code>
native-payload-<payload-address>
native-code-execution-ready-<payload-address>

The final call to the WebAssembly export executes the native payload. Success
is shown by /tmp/i:

cat /tmp/i

Expected content:

uid=0(root) gid=0(root) groups=0(root)

The arbitrary read/write PoC can be opened under the ordinary Firefox sandbox
because it does not spawn a process. Its success indicator is:

browser-arbitrary-read-write-true

No command-line JavaScript preference, privileged browser API, shell-only
function, debugger injection, fault-injection framework, modified profile, or
modified Firefox binary is used.

Suggested Fix

Ephemeron-table completeness must be collection-wide. An allocation failure
in any marker must force the main weak-reference pass to use iterative WeakMap
marking.

The targeted fix should:

  1. Move the haveAllImplicitEdges validity state to GCRuntime, the active GC
    session, or another object shared by all parallel markers.
  2. Make failure propagation synchronized and monotonic: once any worker
    reports an omitted edge, the shared state remains false for the rest of the
    collection.
  3. Make enterWeakMarkingMode() consult the shared state before scanning
    gcEphemeronEdges.
  4. Preserve the existing iterative WeakMapBase::markZoneIteratively() path
    as the allocation-failure fallback.
  5. Ensure deferred-WeakMap processing returns or records allocation failure
    explicitly instead of relying on worker-local side effects.
  6. Add a release-effective invariant before sweeping that prevents a marked
    WeakMap and marked key from retaining a white value.

One suitable design is a collection-wide failure latch:

void GCRuntime::abortLinearWeakMarking() {
  allEphemeronEdgesPresent = false;
}

bool GCRuntime::canUseLinearWeakMarking() const {
  return allEphemeronEdgesPresent;
}

The latch must be accessed under the GC lock or with synchronization suitable
for parallel marking. It must be reset once at the start of the collection,
not independently for every marker.

A regression test should force addEphemeronEdge() or its vector growth to
fail while a nonzero ParallelMarkTask processes deferred WeakMaps. The test
must verify all of the following in both Debug and optimized builds:

1. The failure becomes visible to marker zero.
2. Linear weak marking is not entered with an incomplete table.
3. Iterative WeakMap marking runs to a fixed point.
4. A black WeakMap and black key retain a marked value.
5. WeakMap.get() returns the original live object after collection.
6. Sweeping cannot reclaim the value's GC cell.

The regression should cover failures in both HashMap::add() and
EphemeronEdgeVector::emplaceBack(), because either allocation can leave the
zone-wide table incomplete.

I have added a POC that triggers the UAF on 152's latest stable release, including an ASAN trigger showing bad reads of freed-cell poison 0xffff4b4b4b4b4b48 in WeakMap::trace() during compacting sweep.

Group: firefox-core-security → javascript-core-security
Component: Untriaged → JavaScript: GC
Product: Firefox → Core
Attachment #9603629 - Attachment mime type: application/octet-stream → text/html

I can reproduce the MOZ_CRASH_UNSAFE_PRINTF() on a Mac Release 152.0.3: bp-3877cc91-d0c0-4aa2-be90-ca89b0260701

I could not reproduce on 153.0b7 or nightly, but I don't know if that's because we fixed something or because the magic numbers in the test are not as generic as they look.

Status: UNCONFIRMED → NEW
Ever confirmed: true

The trigger changes a bit, here is a path that triggers the UAF on linux asan nightly-154.0a1-20260701192917

This looks like bug 2046917?

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

Attachment

General

Creator:
Created:
Updated:
Size: