Closed Bug 2030104 Opened 7 months ago Closed 7 months ago

Missing type validation in [@ JSStructuredCloneReader::readSharedWasmMemory] allows attacker-controlled isHuge flag

Categories

(Core :: JavaScript Engine, defect, P1)

defect

Tracking

()

RESOLVED DUPLICATE of bug 2026869

People

(Reporter: bugmon, Unassigned)

References

(Blocks 2 open bugs)

Details

(5 keywords, Whiteboard: [pp3])

Attachments

(3 files)

JSStructuredCloneReader::readSharedWasmMemory reads the isHuge field of a serialized WebAssembly.Memory using startRead() — which can produce any JS::Value type — but then calls isHuge.toBoolean() without first checking isHuge.isBoolean(). Upstream Mozilla has this guard at lines 3030-3035; it has been removed from this build.

In debug builds this fires MOZ_ASSERT(isBoolean()) in Value.h:955. In release builds, toBoolean() returns bool(asBits_ & 0x1) — the low bit of the raw tagged value. By replacing the serialized boolean with an Int32 (tag 0xffff0003), an attacker controls this bit and thus the isHuge argument to WasmMemoryObject::create(). The isHuge flag determines whether wasm linear memory uses guard-page-based bounds checking (no explicit checks emitted) or explicit bounds checks against boundsCheckLimit(). Constructing a WasmMemoryObject where isHuge() disagrees with the underlying SharedArrayBuffer's actual reservation layout violates a core JIT safety invariant — caught by MOZ_RELEASE_ASSERT at WasmModule.cpp:578 when the memory is bound to a module instance, but other consumers of WasmMemoryObject::isHuge() may not be similarly guarded.

The shell trigger uses a TOCTOU in Deserialize() (TestingFunctions.cpp): the SharedArrayBuffer option getter runs after the synthetic-buffer check but before obj->data() is dereferenced, letting JS swap in crafted bytes via the clonebuffer setter. In a browser context the equivalent surface is any path where structured-clone bytes can be tampered (e.g. compromised content process feeding IPC to a privileged deserializer, or IndexedDB blob corruption).

Note: The task pointed to js/src/irregexp/imported/special-case.cc, but exhaustive byte-for-byte comparison against upstream Mozilla confirmed that file is identical. The actual injected vulnerability was located in StructuredClone.cpp via comprehensive diff scanning of the entire js/src tree.

Build Info

Affected Code

File: js/src/vm/StructuredClone.cpp, line 3027-3058

  // Read the isHuge flag
  RootedValue isHuge(cx);
  if (!startRead(&isHuge)) {
    return false;
  }
  // <-- MISSING: upstream checks `if (!isHuge.isBoolean()) { ...error...; return false; }`

  // Read the SharedArrayBuffer object.
  RootedValue payload(cx);
  if (!startRead(&payload)) {
    return false;
  }
  if (!payload.isObject() ||
      !payload.toObject().is<SharedArrayBufferObject>() ||
      payload.toObject().as<SharedArrayBufferObject>().isGrowable()) {
    JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
                              JSMSG_SC_BAD_SERIALIZED_DATA,
                              "shared wasm memory must be backed by a "
                              "non-growable SharedArrayBuffer");
    return false;
  }

  Rooted<ArrayBufferObjectMaybeShared*> sab(
      cx, &payload.toObject().as<SharedArrayBufferObject>());

  // Construct the memory.
  RootedObject proto(
      cx, GlobalObject::getOrCreatePrototype(cx, JSProto_WasmMemory));
  if (!proto) {
    return false;
  }
  RootedObject memory(
      cx, WasmMemoryObject::create(cx, sab, isHuge.toBoolean(), proto));  // <-- unchecked toBoolean()

File: js/public/Value.h, line 954-960

  bool toBoolean() const {
    MOZ_ASSERT(isBoolean());          // debug-only, fires here
#if defined(JS_NUNBOX32)
    return bool(toNunboxPayload());
#elif defined(JS_PUNBOX64)
    return bool(asBits_ & 0x1);       // release: attacker controls low bit
#endif

File: js/src/wasm/WasmJS.cpp, line 2638-2667

size_t WasmMemoryObject::boundsCheckLimit() const {
  if (!buffer().isWasm() || isHuge()) {     // <-- corrupted flag read here
    return buffer().byteLength();
  }
  ...
  size_t mappedSize = buffer().wasmMappedSize();
  ...
  size_t limit = mappedSize - wasm::GuardSize;  // <-- if isHuge wrongly false on a huge SAB,
  ...                                           //     limit becomes ~6GB instead of byteLength
  return limit;
}

File: js/src/wasm/WasmModule.cpp, line 578-582

    MOZ_RELEASE_ASSERT(
        codeMeta().isAsmJS() ||
        memory->isHuge() ==
            IsHugeMemoryEnabled(desc.addressType(), desc.pageSize()));
    // ^ catches the corruption at module instantiation, proving the invariant is violated

startRead() deserializes whatever tag appears next in the byte stream — boolean, int32, double, object, etc. The payload field (SharedArrayBuffer) is correctly type-checked immediately after read, but the isHuge field is not. Note the asymmetry: payload gets isObject() && is<SharedArrayBufferObject>() validation, isHuge gets nothing. Upstream Mozilla has the missing guard at js/src/vm/StructuredClone.cpp:3030-3035.

Exploit Chain

  1. Serialize a shared WebAssembly.Memory with serialize(mem, undefined, {scope: 'SameProcess', SharedArrayBuffer: 'allow'}) — produces a buffer with header (8 bytes), SCTAG_SHARED_WASM_MEMORY (8 bytes), then SCTAG_BOOLEAN for isHuge at offset 16, then the SAB payload.
  2. Copy the serialized bytes into a fresh ArrayBuffer and overwrite the upper 32 bits at offset 16 (Uint32 index 5) with 0xffff0003 (JSVAL_TAG_INT32). The lower 32 bits (index 4) become the integer payload — its low bit becomes the corrupted boolean in release builds.
  3. Call deserialize(s, opts) where opts has a getter for SharedArrayBuffer. Deserialize() reads obj->isSynthetic() (false, since the buffer came from real serialize) and computes scope=SameProcess BEFORE invoking JS_GetProperty on the options object — the getter runs after the scope decision but before obj->data() is dereferenced (TestingFunctions.cpp:6418).
  4. Inside the getter, assign s.clonebuffer = craft. CloneBufferObject's clonebuffer setter replaces the internal JSStructuredCloneData with attacker bytes. The buffer is now synthetic, but the local scope variable already holds SameProcess.
  5. JS_ReadStructuredClone parses the crafted buffer with SameProcess scope and shared-memory policy enabled. SCTAG_SHARED_WASM_MEMORY_OBJECT dispatches to readSharedWasmMemory. startRead(&isHuge) reads the Int32 tag and produces an Int32Value.
  6. isHuge.toBoolean() is called with no type check. Debug: MOZ_ASSERT(isBoolean()) fires at Value.h:955. Release: bool(asBits_ & 0x1) returns the low bit of the attacker's integer.
  7. WasmMemoryObject::create() stores the corrupted flag in the ISHUGE_SLOT. The object now has isHuge() inconsistent with its SharedArrayBuffer's actual reservation layout.
  8. When the corrupted memory is imported into a wasm module instance, WasmModule.cpp:578 MOZ_RELEASE_ASSERT detects the mismatch and crashes (verified in ASAN build). If any code path consumes isHuge() without this assertion, bounds-check elision would proceed with a flag that doesn't match the guard-page layout, enabling out-of-bounds wasm memory access.

Steps to Reproduce

  1. Build SpiderMonkey shell from this tree (debug recommended for the assertion).
  2. Save the testcase as testcase.js.
  3. Run: /firefox/obj-js-debug/dist/bin/js --fuzzing-safe testcase.js
  4. Observe Assertion failure: isBoolean(), at .../js/Value.h:955 with frame #3 in JSStructuredCloneReader::readSharedWasmMemory at StructuredClone.cpp:3058.
  5. For the release-build invariant proof, additionally set v[4] = 0 (forcing isHuge=false on a huge-mode SAB) and import the deserialized memory into a wasm module — observe MOZ_RELEASE_ASSERT at WasmModule.cpp:578 in the ASAN build.

Security Impact

  • Severity: High
  • Attacker capability: An attacker who can supply tampered structured-clone bytes can construct a WasmMemoryObject whose isHuge() flag disagrees with the underlying SharedArrayBuffer's reservation layout. isHuge governs whether the JIT emits explicit bounds checks or relies on guard-page faults; an inconsistency between the flag and the actual memory mapping is a memory-safety invariant violation. The instantiation path is protected by MOZ_RELEASE_ASSERT (resulting in a controlled crash / DoS at minimum), but the corrupted object exists and is reachable from JS before instantiation — any consumer of isHuge() not behind that assert is a potential out-of-bounds primitive.
  • Preconditions: Requires the ability to feed attacker-controlled bytes into JS_ReadStructuredClone with shared-memory clone policy enabled. In the JS shell this is achieved via the clonebuffer setter TOCTOU. In a browser context this requires either a compromised content process talking to a more-privileged deserializer over IPC, persisted-storage tampering (IndexedDB), or a separate serialization bug. Cross-origin isolation (COOP+COEP) must be enabled for the SharedArrayBuffer policy gate to pass.

ASAN Report

[27392] Assertion failure: isBoolean(), at /firefox/obj-js-debug/dist/include/js/Value.h:955
#01: ???[/firefox/obj-js-debug/dist/bin/js +0x271fa62]
#02: ???[/firefox/obj-js-debug/dist/bin/js +0x3b4b406]
#03: ???[/firefox/obj-js-debug/dist/bin/js +0x3b4c369]
#04: ???[/firefox/obj-js-debug/dist/bin/js +0x3b48648]
#05: ???[/firefox/obj-js-debug/dist/bin/js +0x3b36edb]
#06: ???[/firefox/obj-js-debug/dist/bin/js +0x3b36db5]
#07: JS_ReadStructuredClone(JSContext*, JSStructuredCloneData const&, unsigned int, JS::StructuredCloneScope, JS::MutableHandle<JS::Value>, JS::CloneDataPolicy const&, JSStructuredCloneCallbacks const*, void*)[/firefox/obj-js-debug/dist/bin/js +0x3b5138b]
#08: ???[/firefox/obj-js-debug/dist/bin/js +0x29e6f72]
#09: ???[/firefox/obj-js-debug/dist/bin/js +0x3b2d095]
#10: ???[/firefox/obj-js-debug/dist/bin/js +0x3b08446]
#11: ???[/firefox/obj-js-debug/dist/bin/js +0x30dd454]
#12: ??? (???:???)
UndefinedBehaviorSanitizer:DEADLYSIGNAL
==27392==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x000000000000 (pc 0x56f68b34ba7a bp 0x7ffed0df1bd0 sp 0x7ffed0df1bd0 T27392)
==27392==The signal is caused by a WRITE memory access.
==27392==Hint: address points to the zero page.
    #0 0x56f68b34ba7a in MOZ_CrashSequence(void*, long) /firefox/obj-js-debug/dist/include/mozilla/Assertions.h:235:3
    #1 0x56f68b34ba7a in JS::Value::toBoolean() const /firefox/obj-js-debug/dist/include/js/Value.h:955:5
    #2 0x56f68b34ba7a in js::WrappedPtrOperations<JS::Value, JS::Rooted<JS::Value>, void>::toBoolean() const /firefox/obj-js-debug/dist/include/js/Value.h:1309:43
    #3 0x56f68c777405 in JSStructuredCloneReader::readSharedWasmMemory(unsigned int, JS::MutableHandle<JS::Value>) /firefox/js/src/vm/StructuredClone.cpp:3058:52
    #4 0x56f68c778368 in JSStructuredCloneReader::startReadUnchecked(JS::MutableHandle<JS::Value>, JSStructuredCloneReader::ShouldAtomizeStrings, bool*) /firefox/js/src/vm/StructuredClone.cpp:3313:14
    #5 0x56f68c774647 in JSStructuredCloneReader::startRead(JS::MutableHandle<JS::Value>, JSStructuredCloneReader::ShouldAtomizeStrings) /firefox/js/src/vm/StructuredClone.cpp:3451:8
    #6 0x56f68c762eda in JSStructuredCloneReader::read(JS::MutableHandle<JS::Value>, unsigned long) /firefox/js/src/vm/StructuredClone.cpp:4078:8
    #7 0x56f68c762db4 in ReadStructuredClone(JSContext*, JSStructuredCloneData const&, JS::StructuredCloneScope, JS::MutableHandle<JS::Value>, JS::CloneDataPolicy const&, JSStructuredCloneCallbacks const*, void*) /firefox/js/src/vm/StructuredClone.cpp:803:12
    #8 0x56f68c77d38a in JS_ReadStructuredClone(JSContext*, JSStructuredCloneData const&, unsigned int, JS::StructuredCloneScope, JS::MutableHandle<JS::Value>, JS::CloneDataPolicy const&, JSStructuredCloneCallbacks const*, void*) /firefox/js/src/vm/StructuredClone.cpp:4223:10
    #9 0x56f68b612f71 in Deserialize(JSContext*, unsigned int, JS::Value*) /firefox/js/src/builtin/TestingFunctions.cpp:6418:8
    #10 0x56f68c759094 in CallJSNative(JSContext*, bool (*)(JSContext*, unsigned int, JS::Value*), js::CallReason, JS::CallArgs const&) /firefox/js/src/vm/Interpreter.cpp:490:13
    #11 0x56f68c734445 in js::InternalCallOrConstruct(JSContext*, JS::CallArgs const&, js::MaybeConstruct, js::CallReason) /firefox/js/src/vm/Interpreter.cpp:586:12
    #12 0x56f68bd09453 in js::jit::DoCallFallback(JSContext*, js::jit::BaselineFrame*, js::jit::ICFallbackStub*, unsigned int, JS::Value*, JS::MutableHandle<JS::Value>) /firefox/js/src/jit/BaselineIC.cpp:1701:10
    #13 0x1a3a6105ec9e  (<unknown module>)

==27392==Register values:
rax = 0x0000000000000000  rbx = 0x00007ffed0df1c68  rcx = 0x00000000000003bb  rdx = 0x0000786a9ac5d563  
rdi = 0x0000786a9ac5e700  rsi = 0x0000000000000000  rbp = 0x00007ffed0df1bd0  rsp = 0x00007ffed0df1bd0  
 r8 = 0x0000000000000000   r9 = 0x0000000000000003  r10 = 0x0000000000000002  r11 = 0x0000000000000293  
r12 = 0x000056f6adf36630  r13 = 0xaaaaaaaaaaaaaaaa  r14 = 0x00007ffed0df1ed8  r15 = 0x00007ffed0df1c50  
UndefinedBehaviorSanitizer can not provide additional info.
SUMMARY: UndefinedBehaviorSanitizer: SEGV /firefox/obj-js-debug/dist/include/mozilla/Assertions.h:235:3 in MOZ_CrashSequence(void*, long)
==27392==ABORTING
Attached file testcase.js —
Attached patch fix.patch — — Splinter Review
Attached file crash_stack.txt —
Group: core-security → javascript-core-security

Ryan, would you know who would be the best person to look at this issue?

Severity: -- → S2
Flags: needinfo?(rhunt)
Priority: -- → P1

This was fixed in bug 2026869. Also the test takes advantage of an issue with the deserialize testing function that I'm fixing in bug 2029299.

Status: UNCONFIRMED → RESOLVED
Closed: 7 months ago
Duplicate of bug: 2026869
Resolution: --- → DUPLICATE
Flags: needinfo?(rhunt)
Whiteboard: [pp3]
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: