Closed Bug 2054832 Opened 4 months ago Closed 4 months ago

OOB heap read in streaming wasm custom-section skip via `size_t`→`uint32_t` module-offset truncation

Categories

(Core :: JavaScript: WebAssembly, defect, P1)

defect

Tracking

()

RESOLVED FIXED
155 Branch
Tracking Status
firefox-esr115 154+ fixed
firefox-esr140 154+ fixed
firefox-esr153 154+ fixed
firefox153 --- wontfix
firefox154 + fixed
firefox155 + fixed

People

(Reporter: jandem, Assigned: rhunt)

Details

(Keywords: ai-involved, csectype-bounds, sec-high, Whiteboard: [adv-main154+r][adv-esr153.1+r][adv-esr140.14+r][adv-esr115.39+r])

Attachments

(5 external files)

This was found by Clauditor but rejected by its verifier because it doesn't reproduce in the JS shell. Brian Grinstead noticed this and I had Claude write the summary below.

Summary

Streaming WebAssembly compilation places no cap on the total module size: after
the code section, the Tail state of CompileStreamTask::consumeChunk
(js/src/wasm/WasmJS.cpp:5443) appends attacker bytes to tailBytes_
indefinitely. As a result the absolute offset of a section within the module
can exceed 2^32.

The decoder tracks that absolute offset in a size_t
(Decoder::offsetInModule_, WasmBinary.h:305) but stores section ranges in a
uint32_t-based BytecodeRange (WasmBinaryTypes.h:49-50). When a custom
section header is parsed past the 2^32 boundary,
BytecodeRange::fromStartAndSize(currentOffset(), size, range) silently narrows
the size_t offset to uint32_t (WasmBinaryTypes.h:37, called from
Decoder::readSectionHeader WasmBinary.cpp:76 and Decoder::startSection
WasmBinary.cpp:132).

The skip step then recomputes the decode cursor as

// js/src/wasm/WasmBinary.cpp:258
void Decoder::skipAndFinishCustomSection(const BytecodeRange& range) {
  MOZ_ASSERT(cur_ >= beg_);
  MOZ_ASSERT(cur_ <= end_);
  cur_ = beg_ + (range.end - offsetInModule_);   // truncated end - real size_t offset
  MOZ_ASSERT(cur_ <= end_);                       // DEBUG-ONLY guard
  clearError();
}

Here range.end is a truncated (mod 2^32) value while offsetInModule_ is
the real size_t tail-start offset. The subtraction mixes the two spaces:
when the truncated end is smaller than the offset, the unsigned result wraps and
cur_ is moved below beg_. The only bounds check is a debug-only
MOZ_ASSERT, so in a release build the next readFixedU8 dereferences a wild
pointer — an out-of-bounds heap read whose bytes are then parsed as
attacker-visible wasm section structure.

Root cause

The invariant that module offsets fit in uint32_t is enforced everywhere
except on the streaming tail:

  • Non-streaming decode is capped at MaxModuleBytes = 1 GiB
    (WasmConstants.h:1206) by if (d.bytesRemain() > MaxModuleBytes)
    (WasmValidate.cpp:2550).

  • The streamed code section is capped at MaxCodeSectionBytes (== 1 GiB)
    (WasmJS.cpp:5393).

  • The env span before the code section and the tail span after it are not
    capped at all
    . CompileStreamTask::consumeChunk Tail state:

    // js/src/wasm/WasmJS.cpp:5443
    case Tail: {
      if (!tailBytes_->append(begin, length)) {          // no size limit
        return rejectAndDestroyAfterHelperThreadStarted(StreamOOMCode);
      }
      return true;
    }
    

Because the tail is uncapped, the tail decoder can be constructed with a real
tail-start offset, and section headers within it can cross 2^32:

// js/src/wasm/WasmValidate.cpp:6785
Decoder tailDecoder(bytecode.tailSpan(), bytecode.tailRange().start, error);

offsetInModule_ holds the true offset, currentOffset() (WasmBinary.h:449,
offsetInModule_ + (cur_ - beg_)) is a size_t, and the moment it is fed into
fromStartAndSize's uint32_t start parameter the high bits are lost.

Exploitation path

Tracing the PoC (below), the tail decoder is built with offsetInModule_ = 4124
(the real tail start — this value is small and not truncated). The tail
contains two custom sections:

  1. Custom section 1 spans [4130, 2^32-1). Its range is computed entirely
    below 2^32, so fromStartAndSize does not overflow; the skip advances
    cur_ correctly to near the end of the tail buffer.

  2. Custom section 2 header starts at module offset 2^32-1. After reading
    its id byte + 5-byte LEB size, currentOffset() is 2^32 + 5. This is
    narrowed:

    • start: 2^32 + 5 → 5
    • end: 5 + 1119 → 1124

    skipAndFinishCustomSection then computes
    cur_ = beg_ + (1124 - 4124) = beg_ - 3000 — a pointer 3000 bytes below
    the tail buffer. The subsequent read is OOB.

The below-buffer displacement equals offsetInModule_ - range.end and is
attacker-tunable: enlarging the code section (up to MaxCodeSectionBytes = 1
GiB) raises offsetInModule_ and pushes cur_ up to ~1 GiB below beg_. The
OOB bytes are subsequently interpreted as wasm section headers, making their
contents observable to the page (e.g. via Module.customSections / decode
behavior), i.e. a heap information leak.

Sibling parameterization: helper-thread infinite loop

If instead the truncated range.end is chosen greater than
offsetInModule_, cur_ is rewound to an in-bounds position without advancing
past the section. DecodeModuleTail's skip loop

// js/src/wasm/WasmValidate.cpp:4753
while (!d.done()) {
  if (!d.skipCustomSection(codeMeta)) {
    return false;
  }
}

then re-parses the same giant section forever — a wasm helper-thread infinite
loop (DoS).

Reproduction

Reproduced 2026-07-13 on an ASan+UBSan build
(obj-firefox-asan/dist/bin/firefox), default prefs, from a plain web-content
page. UBSan aborted with:

WasmBinary.cpp:261:15: runtime error: addition of unsigned offset to
0x78b9e4fae800 overflowed to 0x78b9e4fadc48

The delta 0xae800 - 0xadc48 = 0xBB8 = 3000 matches the constructed
below-buffer displacement exactly. Stack:

skipAndFinishCustomSection
  <- skipCustomSection
  <- startSection
  <- DecodeDataSection
  <- DecodeModuleTail
  <- CompileStreaming
  <- CompileStreamTask::execute

The page streams a 4,294,968,420-byte module through
WebAssembly.compileStreaming(new Response(readableStream)).

Test case

<!DOCTYPE html>
<script>
function varu32_5(v){return [(v&0x7f)|0x80,((v>>>7)&0x7f)|0x80,
  ((v>>>14)&0x7f)|0x80,((v>>>21)&0x7f)|0x80,(v>>>28)&0x0f];}
const prefix=[];function push(...a){for(const x of a)prefix.push(x);}
push(0x00,0x61,0x73,0x6d,0x01,0x00,0x00,0x00);   // magic + version
push(0x01,0x04,0x01,0x60,0x00,0x00);             // type section
push(0x03,0x02,0x01,0x00);                       // function section
push(0x0a,0x87,0x20); push(0x01,0x84,0x20,0x00); // code section header
for(let i=0;i<4098;i++)push(0x01); push(0x0b);   // code body
const E=prefix.length;               // 4124 (tail starts here)
const A=4294967295-E-6;              // custom sec 1 ends at 2^32-1
push(0x00,...varu32_5(A)); push(0x00);
const prefixU8=new Uint8Array(prefix);
const SEC2_AT=4294967295, A2=1119;
const sec2=[0x00,...varu32_5(A2),0x00];          // custom sec 2 straddles 2^32
const TOTAL=SEC2_AT+1+5+A2;          // 4294968420
const tail2=new Uint8Array(TOTAL-SEC2_AT); tail2.set(sec2,0);
let sent=0; const CHUNK=1<<26;
const rs=new ReadableStream({pull(c){
  if(sent===0){c.enqueue(prefixU8);sent=prefixU8.length;return;}
  if(sent>=TOTAL){c.close();return;}
  if(sent>=SEC2_AT){c.enqueue(tail2.subarray(sent-SEC2_AT));sent=TOTAL;return;}
  const n=Math.min(CHUNK,SEC2_AT-sent); c.enqueue(new Uint8Array(n)); sent+=n;}});
WebAssembly.compileStreaming(new Response(rs,
  {headers:{'Content-Type':'application/wasm'}})).then(
  m=>console.log('unexpectedly compiled'), e=>console.log('error '+e));
</script>

Why shell-only reproduction fails

The precondition (>4 GiB streamed) is not deliverable from the fuzzing-safe JS
shell used by the standard shell reproduction gate:

  • The shell stream harness BufferStreamMain (js/src/shell/js.cpp:8515)
    defaults to 10-byte chunks with a 1 ms delay
    (BufferStreamState() ctor, js.cpp:8508), i.e. ~10 KB/s → several days to
    deliver >4 GiB.
  • The knob to change that, setBufferStreamParams, lives in
    fuzzing_unsafe_functions[] (js.cpp:10623-10682), so it is undefined in the
    fuzzing-safe shell.
  • Non-streaming compiles are capped at MaxModuleBytes = 1 GiB, and every other
    Decoder construction takes uint32_t offsets over <= 1 GiB buffers.

No shell-reachable variant exists; this should be filed and triaged as a
browser (fetch/streaming) wasm memory-safety bug.

Suggested fixes

  • Cap the streaming env and tail spans so total module size cannot exceed
    MaxModuleBytes (mirror the existing bytesRemain() > MaxModuleBytes /
    MaxCodeSectionBytes checks in the Env/Tail states of consumeChunk).
  • Make the size_t→uint32_t narrowing explicit and checked: have
    readSectionHeader/startSection fail if currentOffset() does not fit in
    uint32_t, or promote BytecodeRange offsets / the arithmetic in
    skipAndFinishCustomSection to size_t.
  • Promote the release-relevant MOZ_ASSERT(cur_ <= end_) in
    skipAndFinishCustomSection to a release check (MOZ_RELEASE_ASSERT /
    explicit error return).

Secondary: resource-exhaustion enabler (excluded class)

Independently of the OOB, streaming compilation buffers attacker bytes without a
total-size cap (envBytes_ grows unbounded until a code section is found;
tailBytes_ grows unbounded afterward — consumeChunk Env/Tail states).
This permits multi-GB content-process memory growth from a streamed response and
is the enabling precondition for the OOB above. Verified implicitly by the OOB
repro (which streamed 4.29 GB through consumeChunk without rejection).

(In reply to Jan de Mooij [:jandem] from comment #0)

  • The shell stream harness BufferStreamMain (js/src/shell/js.cpp:8515)
    defaults to 10-byte chunks with a 1 ms delay
    (BufferStreamState() ctor, js.cpp:8508), i.e. ~10 KB/s → several days to
    deliver >4 GiB.
  • The knob to change that, setBufferStreamParams, lives in
    fuzzing_unsafe_functions[] (js.cpp:10623-10682), so it is undefined in the
    fuzzing-safe shell.

We should check if this knob is really fuzzing-unsafe.

The rating assigned by our bug rating tool (currently under development) is:

Rating: sec-high

Explanation: Verified against source: offsetInModule_ is size_t (WasmBinary.h:305) but is fed via currentOffset() into BytecodeRange::fromStartAndSize's uint32_t 'start' parameter (WasmBinary.cpp:76/132), silently truncating module offsets that cross 2^32. skipAndFinishCustomSection then does cur_ = beg_ + (range.end - offsetInModule_) with only debug-only MOZ_ASSERT bounds checks (WasmBinary.cpp:261), so a truncated end < the real tail offset wraps cur_ below beg_, yielding a wild pointer that is then dereferenced/parsed. The streaming Tail state (WasmJS.cpp:5443) buffers attacker bytes with no total-size cap, so absolute section offsets can exceed 2^32 — the invariant enforced everywhere else (MaxModuleBytes/MaxCodeSectionBytes, 1 GiB). This is a memory-safety out-of-bounds heap read reachable from plain web content via WebAssembly.compileStreaming, with precise/deterministic triggering (displacement tunable up to ~1 GiB below the buffer) and OOB bytes reinterpreted as wasm section structure (potential heap info leak). Memory-safety, web-reachable, no unusual user action, precise triggering demonstrated -> sec-high. Main mitigation is the multi-GB memory precondition (~4-5 GiB buffered in the content process, so it fails on low-memory/mobile devices), which constrains scope but does not make it OOM-triggered; a reasonable argument for sec-moderate exists on that basis, but deterministic memory-safety OOB reads from content are treated as sec-high.

Please ni? me if you disagree with this rating.

Attached file (secure) —
Assignee: nobody → rhunt
Status: NEW → ASSIGNED
Severity: -- → S2
Priority: -- → P1
Group: javascript-core-security → core-security-release
Status: ASSIGNED → RESOLVED
Closed: 4 months ago
Resolution: --- → FIXED
Target Milestone: --- → 155 Branch

Please add uplift requests for beta, esr115, esr140, and esr153

firefox-beta Uplift Approval Request

  • User impact if declined/Reason for urgency: Potentially exploitable security issue
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: yes
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing:
  • Risk associated with taking this patch: low
  • Explanation of risk level: Adds a simple length check earlier in the compile pipeline. Well tested code.
  • String changes made/needed?: N/A
  • Is Android affected?: yes
Attachment #9615333 - Flags: approval-mozilla-beta?
Attached file (secure) —

firefox-esr115 Uplift Approval Request

  • User impact if declined/Reason for urgency: Potentially exploitable security issue
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: yes
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing:
  • Risk associated with taking this patch: low
  • Explanation of risk level: Adds a simple length check earlier in the compile pipeline. Well tested code.
  • String changes made/needed?: N/A
  • Is Android affected?: yes
Attachment #9615334 - Flags: approval-mozilla-esr115?
Attached file (secure) —

firefox-esr140 Uplift Approval Request

  • User impact if declined/Reason for urgency: Potentially exploitable security issue
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: yes
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing:
  • Risk associated with taking this patch: low
  • Explanation of risk level: Adds a simple length check earlier in the compile pipeline. Well tested code.
  • String changes made/needed?: N/A
  • Is Android affected?: yes
Attachment #9615335 - Flags: approval-mozilla-esr140?
Attached file (secure) —

firefox-esr153 Uplift Approval Request

  • User impact if declined/Reason for urgency: Potentially exploitable security issue
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: yes
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing:
  • Risk associated with taking this patch: low
  • Explanation of risk level: Adds a simple length check earlier in the compile pipeline. Well tested code.
  • String changes made/needed?: N/A
  • Is Android affected?: yes
Attachment #9615336 - Flags: approval-mozilla-esr153?
Attached file (secure) —
Attachment #9615333 - Flags: approval-mozilla-beta? → approval-mozilla-beta+
Attachment #9615336 - Flags: approval-mozilla-esr153? → approval-mozilla-esr153+
Attachment #9615334 - Flags: approval-mozilla-esr115? → approval-mozilla-esr115+
Attachment #9615335 - Flags: approval-mozilla-esr140? → approval-mozilla-esr140+
QA Whiteboard: [sec] [uplift] [qa-triage-done-c155/b154]
Flags: needinfo?(rhunt)
Whiteboard: [adv-main151+r][adv-esr115.36+r][adv-esr140.11+r][adv-esr115.39+]
Whiteboard: [adv-main151+r][adv-esr115.36+r][adv-esr140.11+r][adv-esr115.39+] → [adv-main154+r][adv-esr53.1+r][adv-esr140.14+r][adv-esr115.39+]
Whiteboard: [adv-main154+r][adv-esr53.1+r][adv-esr140.14+r][adv-esr115.39+] → [adv-main154+r][adv-esr153.1+r][adv-esr140.14+r][adv-esr115.39+r]
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: