Use after free in V8 (CVE-2024-3169)
A use-after-free in V8's WebAssembly graph builder: when multiple memories exist, the reload logic only checked memory 0's growability, so a cached non-zero memory could be grown and its backing store replaced while compiled code kept a stale pointer. An attacker could trigger a crash, and the author believes it may be exploitable in 32-bit Chrome.
- Fix shipped in 17 days
TITLE
use-after-free of wasm memory buffer due to mismatch of cached memory in ReloadInstanceCacheIntoSsa
VULNERABILITY DETAILS
After the wasm multi-memory feature has landed, I find that the wasm graph-builder-interface has a bug in function 'ReloadInstanceCacheIntoSsa'.
This bug will cause the ptr of wasm memory used in compiled wasm code not updated while executing. If the wasm memory backingstore buffer gets replaced during 'memory.grow', then a used-after-free crash will occur. Likely https://bugs.chromium.org/p/chromium/issues/detail?id=1377816
Looking at the code:
void ReloadInstanceCacheIntoSsa(SsaEnv* ssa_env, const WasmModule* module) {
if (module->memories.empty()) return;
const WasmMemory* memory0 = &module->memories[0];
if (memory0->initial_pages == memory0->maximum_pages) return;
LoadInstanceCacheIntoSsa(ssa_env);
}
In function 'ReloadInstanceCacheIntoSsa', only memory0 of the memoried vector is considered. Therefore, if memory0's initial_pages equals to its maximum_pages, 'LoadInstanceCacheIntoSsa' will not be executed.
However, with the multi-memory feature (after M120?), the other memories can also be imported to wasm instance and grew.
This function converted a bug after this commit: https://chromium-review.googlesource.com/c/v8/v8/+/4751826
commit 1137222a33cfce2e6fcc45c7395c98b496a0762f
Author: Clemens Backes <[email protected]>
Date: Fri Aug 4 15:58:54 2023 +0200
[wasm][turbofan] Determine the memory index to cache
We currently always cache memory start and size of memory 0. With
multiple memories, this needs to be adapted.
The Liftoff approach to always cache the LRU memory does not work well
for TurboFan, because we would need to load the fields when they are
first used, which might be inside of loops.
In order to avoid regressions, we thus determine one memory to cache per
function. We currently take the first memory that is being accessed
insode the function via a standard memory access operation. For the use
cases that we currently see this works perfectly fine, if we see use
cases where multiple memories are accessed inside a function then we
might need to readjust this.
R=[email protected]
Bug: v8:13918
Change-Id: Id51e9e7ecffd5bc50a9d5fd351abcbfb1f450644
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/4751826
Commit-Queue: Clemens Backes <[email protected]>
Reviewed-by: Thibaud Michaud <[email protected]>
Cr-Commit-Position: refs/heads/main@{#89434}
Before this commit, wasm-graph-builder always cache memory0. After this commit, wasm-graph-builder starts to have a 'cached_memory_index_' member, and it is determined by the following function:
size_t num_memories =
decoder->module_ == nullptr ? 0 : decoder->module_->memories.size();
if (num_memories == 1) {
builder_->set_cached_memory_index(0);
} else if (num_memories > 1) {
int first_used_mem_index = FindFirstUsedMemoryIndex(
base::VectorOf(decoder->start(), decoder->end() - decoder->start()),
decoder->zone());
if (first_used_mem_index >= 0) {
builder_->set_cached_memory_index(first_used_mem_index);
}
}
int FindFirstUsedMemoryIndex(base::Vector<const uint8_t> body, Zone* zone) {
BodyLocalDecls locals;
for (BytecodeIterator it{body.begin(), body.end(), &locals, zone};
it.has_next(); it.next()) {
WasmOpcode opcode = it.current();
constexpr bool kConservativelyAssumeMemory64 = true;
constexpr bool kConservativelyAssumeMultiMemory = true;
switch (opcode) {
default:
break;
#define CASE(name, ...) case kExpr##name:
FOREACH_LOAD_MEM_OPCODE(CASE)
FOREACH_STORE_MEM_OPCODE(CASE)
#undef CASE
MemoryAccessImmediate imm(
&it, it.pc() + 1, UINT32_MAX, kConservativelyAssumeMemory64,
kConservativelyAssumeMultiMemory, Decoder::kNoValidation);
return imm.mem_index;
}
}
return -1;
}
Briefly, the first used memory will be used as 'cached_memory_index_' while traversing the wasm opcodes.
Therefore, as an example, if memory[1] is cached and memory[0].initial_pages==memory[0].maximum_pages, 'LoadInstanceCacheIntoSsa' will never be executed in 'ReloadInstanceCacheIntoSsa'.
I construct a POC on windows11 under the latest version of d8, commit bc34b7bc5ad745437882c89cea199c264f762540, using 'python3 .\tools\dev\gm.py x64.release' to build.
run:
out\x64.release\d8.exe poc.js
And the uaf crash log (16GB win11 vm):
success_grow_amount: 1
fail_grow_amount: 1
success_grow_amount: 2
==== C stack trace ===============================
(No symbol) [0x000002127D441B93]
(No symbol) [0x000002C880000000]
(No symbol) [0x000001E7000027E1]
(No symbol) [0x0000000000000008]
(No symbol) [0x00000020871FEB90]
Builtins_JSToWasmWrapperAsm [0x00007FF67C31E50A+138]
Builtins_JSToWasmWrapperAsm [0x00007FF67C31E50A+138]
Builtins_JSToWasmWrapper [0x00007FF67C3F5F93+2771]
Builtins_InterpreterEntryTrampoline [0x00007FF67C290FEA+298]
Builtins_InterpreterEntryTrampoline [0x00007FF67C290FEA+298]
Builtins_JSEntryTrampoline [0x00007FF67C28EA5C+92]
Builtins_JSEntry [0x00007FF67C28E65B+219]
v8::internal::`anonymous namespace'::Invoke [0x00007FF67B2784DE+2190]
v8::internal::Execution::CallScript [0x00007FF67B278D98+232]
v8::Script::Run [0x00007FF67B0CDA7D+1021]
v8::Script::Run [0x00007FF67B0CD66D+13]
v8::Shell::ExecuteString [0x00007FF67B0A50E6+1606]
v8::SourceGroup::Execute [0x00007FF67B0B836D+637]
v8::Shell::RunMainIsolate [0x00007FF67B0BB55F+319]
v8::Shell::RunMain [0x00007FF67B0BB203+307]
v8::Shell::Main [0x00007FF67B0BCF09+3113]
__scrt_common_main_seh [0x00007FF67C452988+268]
BaseThreadInitThunk [0x00007FFE5A77257D+29]
RtlUserThreadStart [0x00007FFE5BB8AA58+40]
Note:
In the POC, I initially arranged several big wasm memory with 65536 initial pages, so I recommend to reproduce it with a host/vm win11 with 16GB/32GB physical memory machine (I have successfully tested). Some 8GB machines with big virtual memory may be also ok. (And >=128GB memory may have side effects, not sure)
I believe this uaf can be exploited in 32bit chrome, in the same way as issuse 1377816 used (https://bugs.chromium.org/p/chromium/issues/detail?id=1377816). I will try and update if success.
BISECT:
https://chromium-review.googlesource.com/c/v8/v8/+/4751826
commit 1137222a33cfce2e6fcc45c7395c98b496a0762f
Author: Clemens Backes <[email protected]>
Date: Fri Aug 4 15:58:54 2023 +0200
[wasm][turbofan] Determine the memory index to cache
FIX PATCH:
Get the right cached memory index:
--- a/src/wasm/graph-builder-interface.cc +++ b/src/wasm/graph-builder-interface.cc @@ -270,8 +270,10 @@ class WasmGraphBuildingInterface { // actually grow. void ReloadInstanceCacheIntoSsa(SsaEnv* ssa_env, const WasmModule* module) { if (module->memories.empty()) return;
- const WasmMemory* memory0 = &module->memories[0];
- if (memory0->initial_pages == memory0->maximum_pages) return;
- const WasmMemory* cached_memory = &module->memories[builder_->cached_memory_index()];
- if (cached_memory->initial_pages == cached_memory->maximum_pages) return; LoadInstanceCacheIntoSsa(ssa_env); }
VERSION
Chrome Version: Tested on v8 12.1.0 - 12.2.0 Operating System: Tested on Windows 11
CREDIT:
johnshoop
Context
V8 is the JavaScript and WebAssembly engine used by Chrome. TurboFan is its optimising compiler, and the wasm graph builder is the component that turns a decoded wasm function body into TurboFan's sea-of-nodes intermediate representation (SSA). To make memory accesses fast, the graph builder caches the start pointer and size of a wasm linear memory in the instance cache, so compiled code can load them from a fixed slot instead of re-reading the memory object each time.
When a wasm memory grows via memory.grow, the backing store can be replaced. The cached start pointer then becomes stale, so the graph builder has to reload the instance cache before the next access. The function responsible for that is ReloadInstanceCacheIntoSsa. With the multi-memory feature, a module can import and grow more than one memory, and the graph builder caches only one of them per function, chosen as the first memory the function accesses.
The bug is a use-after-free: the cached pointer for a memory that is not memory 0 is not refreshed after a grow, and compiled code keeps using the freed backing store.
Setup
The researcher tested on Windows 11 with a d8 build from V8 commit [redacted], built with:
python3 .\tools\dev\gm.py x64.release
The proof of concept was run as:
out\x64.release\d8.exe poc.js
The PoC allocates several large wasm memories with 65536 initial pages, so the researcher recommends a Windows 11 host or VM with 16GB or 32GB of physical memory. Some 8GB machines with large virtual memory may also work. Machines with 128GB or more may behave differently, though the researcher was not sure. The researcher tested on V8 12.1.0 to 12.2.0.
Finding it
After the wasm multi-memory feature landed, the researcher found a bug in ReloadInstanceCacheIntoSsa in the wasm graph-builder interface. The cached pointer of a wasm memory used by compiled code is not updated while executing. If the backing store of that memory is replaced during memory.grow, a use-after-free crash occurs. The researcher notes it is likely the same issue as Chromium issue 1377816.
The suspicious code:
void ReloadInstanceCacheIntoSsa(SsaEnv* ssa_env, const WasmModule* module) {
if (module->memories.empty()) return;
const WasmMemory* memory0 = &module->memories[0];
if (memory0->initial_pages == memory0->maximum_pages) return;
LoadInstanceCacheIntoSsa(ssa_env);
}
Only memory0 of the memories vector is considered. If memory 0 has initial_pages equal to maximum_pages, it cannot grow, so the function returns early and LoadInstanceCacheIntoSsa is never executed. With multi-memory (after M120, per the researcher), other memories can also be imported into a wasm instance and grown, so the early return is wrong for them.
The behaviour changed with this commit:
commit [redacted]
Author: Clemens Backes <[redacted]>
Date: Fri Aug 4 15:58:54 2023 +0200
[wasm][turbofan] Determine the memory index to cache
We currently always cache memory start and size of memory 0. With
multiple memories, this needs to be adapted.
The Liftoff approach to always cache the LRU memory does not work well
for TurboFan, because we would need to load the fields when they are
first used, which might be inside of loops.
In order to avoid regressions, we thus determine one memory to cache per
function. We currently take the first memory that is being accessed
insode the function via a standard memory access operation. For the use
cases that we currently see this works perfectly fine, if we see use
cases where multiple memories are accessed inside a function then we
might need to readjust this.
R=[redacted]
Bug: v8:13918
Change-Id: [redacted]
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/4751826
Commit-Queue: Clemens Backes <[redacted]>
Reviewed-by: Thibaud Michaud <[redacted]>
Cr-Commit-Position: refs/heads/main@{#89434}
Before this commit, the graph builder always cached memory 0. After it, the builder has a cached_memory_index_ member, set by this code:
size_t num_memories =
decoder->module_ == nullptr ? 0 : decoder->module_->memories.size();
if (num_memories == 1) {
builder_->set_cached_memory_index(0);
} else if (num_memories > 1) {
int first_used_mem_index = FindFirstUsedMemoryIndex(
base::VectorOf(decoder->start(), decoder->end() - decoder->start()),
decoder->zone());
if (first_used_mem_index >= 0) {
builder_->set_cached_memory_index(first_used_mem_index);
}
}
and the index is found by walking the wasm opcodes:
int FindFirstUsedMemoryIndex(base::Vector<const uint8_t> body, Zone* zone) {
BodyLocalDecls locals;
for (BytecodeIterator it{body.begin(), body.end(), &locals, zone};
it.has_next(); it.next()) {
WasmOpcode opcode = it.current();
constexpr bool kConservativelyAssumeMemory64 = true;
constexpr bool kConservativelyAssumeMultiMemory = true;
switch (opcode) {
default:
break;
#define CASE(name, ...) case kExpr##name:
FOREACH_LOAD_MEM_OPCODE(CASE)
FOREACH_STORE_MEM_OPCODE(CASE)
#undef CASE
MemoryAccessImmediate imm(
&it, it.pc() + 1, UINT32_MAX, kConservativelyAssumeMemory64,
kConservativelyAssumeMultiMemory, Decoder::kNoValidation);
return imm.mem_index;
}
}
return -1;
}
In short, the first memory used while traversing the wasm opcodes becomes cached_memory_index_. So if memory 1 is the cached one and memory 0 has initial_pages == maximum_pages, LoadInstanceCacheIntoSsa is never executed inside ReloadInstanceCacheIntoSsa, and the cached pointer for memory 1 is never refreshed.
Exploitation
Step 1: Build a d8 with the affected V8
Use the commit and build command above. The PoC is a JavaScript file run under d8.
Step 2: Arrange the memories
Create a wasm module with multiple memories where memory 0 has initial_pages equal to maximum_pages (so it cannot grow) and a later memory is the first one accessed by the function, making it the cached memory. Allocate several large memories with 65536 initial pages, as the researcher did.
Step 3: Grow the cached memory
Call memory.grow on the cached memory so its backing store is replaced. Because ReloadInstanceCacheIntoSsa returns early on memory 0, the cached start pointer is not reloaded.
Step 4: Access the memory again
The compiled code uses the stale pointer into the freed backing store, producing a use-after-free crash. The run output showed the grow attempts and then the crash:
success_grow_amount: 1
fail_grow_amount: 1
success_grow_amount: 2
==== C stack trace ===============================
(No symbol) [0x000002127D441B93]
(No symbol) [0x000002C880000000]
(No symbol) [0x000001E7000027E1]
(No symbol) [0x0000000000000008]
(No symbol) [0x00000020871FEB90]
Builtins_JSToWasmWrapperAsm [0x00007FF67C31E50A+138]
Builtins_JSToWasmWrapperAsm [0x00007FF67C31E50A+138]
Builtins_JSToWasmWrapper [0x00007FF67C3F5F93+2771]
Builtins_InterpreterEntryTrampoline [0x00007FF67C290FEA+298]
Builtins_InterpreterEntryTrampoline [0x00007FF67C290FEA+298]
Builtins_JSEntryTrampoline [0x00007FF67C28EA5C+92]
Builtins_JSEntry [0x00007FF67C28E65B+219]
v8::internal::`anonymous namespace'::Invoke [0x00007FF67B2784DE+2190]
v8::internal::Execution::CallScript [0x00007FF67B278D98+232]
v8::Script::Run [0x00007FF67B0CDA7D+1021]
v8::Script::Run [0x00007FF67B0CD66D+13]
v8::Shell::ExecuteString [0x00007FF67B0A50E6+1606]
v8::SourceGroup::Execute [0x00007FF67B0B836D+637]
v8::Shell::RunMainIsolate [0x00007FF67B0BB55F+319]
v8::Shell::RunMain [0x00007FF67B0BB203+307]
v8::Shell::Main [0x00007FF67B0BCF09+3113]
__scrt_common_main_seh [0x00007FF67C452988+268]
BaseThreadInitThunk [0x00007FFE5A77257D+29]
RtlUserThreadStart [0x00007FFE5BB8AA58+40]
The stack trace shows the crash occurring under the JS-to-wasm wrapper.
Root cause
ReloadInstanceCacheIntoSsa decides whether to reload the instance cache by looking only at module->memories[0]. The commit that introduced cached_memory_index_ made the graph builder cache whichever memory the function first accesses, but the reload check was not updated to use that index. When memory 0 is fixed-size and the cached memory is a different one, the early return skips LoadInstanceCacheIntoSsa, so the cached start pointer and size are not refreshed after a grow. The backing store is freed and replaced, and compiled code keeps using the old pointer.
The bisect points at the same commit, [redacted].
Impact
The result is a use-after-free in V8 reachable from wasm code that uses multiple memories. The researcher believes the bug can be exploited in 32-bit Chrome in the same way as Chromium issue 1377816, and planned to try it and update if successful. The report does not show a working exploit, only the crash. Exploitation requires a module where memory 0 cannot grow and a later memory is the cached one, plus a grow of that cached memory while compiled code holds the stale pointer.
Fix
The fix makes the reload check use the cached memory index instead of memory 0:
--- a/src/wasm/graph-builder-interface.cc
+++ b/src/wasm/graph-builder-interface.cc
@@ -270,8 +270,10 @@ class WasmGraphBuildingInterface {
// actually grow.
void ReloadInstanceCacheIntoSsa(SsaEnv* ssa_env, const WasmModule* module) {
if (module->memories.empty()) return;
- const WasmMemory* memory0 = &module->memories[0];
- if (memory0->initial_pages == memory0->maximum_pages) return;
+ const WasmMemory* cached_memory = &module->memories[builder_->cached_memory_index()];
+ if (cached_memory->initial_pages == cached_memory->maximum_pages) return;
LoadInstanceCacheIntoSsa(ssa_env);
}
The patch makes the reload check use the cached memory index instead of memory 0.
Variants to test
- Other cached-memory selection paths. Build modules where the first accessed memory is not memory 0 and memory 0 is fixed-size, then grow the cached memory. A positive result is a crash under the JS-to-wasm wrapper or a stale pointer observed after the grow.
- Different memory counts. Try modules with exactly one memory and with several, to confirm the single-memory path still caches memory 0 and reloads correctly. A positive result is a crash only in the multi-memory case.
- Other engines or versions. Check V8 versions around 12.1.0 to 12.2.0 and any engine that adopted the same per-function cached memory index. A positive result is the same early-return pattern in the reload check.
- 32-bit builds. The researcher expected exploitability in 32-bit Chrome following issue 1377816. A positive result would be controlled reuse of the freed backing store rather than a plain crash.
What happened, in plain words
A security researcher found a bug in V8, the part of Google Chrome that runs JavaScript and WebAssembly. The bug is a use-after-free: the browser keeps using a piece of memory after it has been handed back to the system, a bit like continuing to read from a library book you have already returned, when someone else may now have it. The researcher showed that a specially crafted WebAssembly program makes d8 crash, and believed the flaw could be exploited in 32-bit Chrome. The report includes a fix patch that changes one check so that it looks at the right memory. The researcher was credited as johnshoop, and the report was disclosed on 30 January 2024.
Background: the pieces involved
Before the details, here are the main parts, explained from scratch.
- V8 is the engine inside Chrome that reads and runs the code on web pages. JavaScript is the language most web pages use; WebAssembly (often shortened to wasm) is a second language that browsers can run, designed to be fast, and often produced by compiling code written in languages such as C or C++.
- TurboFan is V8's optimising compiler. When a piece of code runs often, TurboFan translates it into a faster, lower-level form so it runs quicker.
- The wasm graph builder is the part of TurboFan that takes a decoded wasm function and turns it into TurboFan's internal representation, called SSA (static single assignment, a way of writing a program where each value is assigned only once). You can think of it as a translator that rewrites a recipe into a more efficient kitchen workflow.
- Linear memory is the block of memory a wasm program uses for its data. It behaves like one long array of bytes. A wasm program can ask for it to grow with an instruction called
memory.grow. - Backing store is the actual chunk of memory the browser has reserved behind that linear memory. When the memory grows, the browser may allocate a new, larger chunk and free the old one.
- Instance cache is a small set of saved values the compiled code keeps, including the start address and size of the linear memory. Saving them means the fast code does not have to look them up every time, like keeping a phone number on a sticky note instead of searching for it in a directory each call.
- Multi-memory is a wasm feature that lets one module use more than one linear memory at once, instead of just one.
- Use-after-free is a class of bug where a program keeps a reference to memory that has already been freed. If the program then reads or writes through that reference, it may see garbage, crash, or, in the worst case, let an attacker influence what happens.
How the caching works
To make memory accesses fast, the graph builder saves the start pointer and the size of a wasm linear memory in the instance cache. Compiled code can then load them from a fixed slot instead of re-reading the memory object each time.
When a wasm memory grows via memory.grow, the backing store can be replaced. The saved start pointer then points at the old, freed chunk, so the graph builder has to reload the instance cache before the next access. The function responsible for that is ReloadInstanceCacheIntoSsa.
With the multi-memory feature, a module can import and grow more than one memory. The graph builder caches only one of them per function, chosen as the first memory the function accesses.
The bug is a use-after-free: the cached pointer for a memory that is not memory 0 is not refreshed after a grow, and compiled code keeps using the freed backing store.
Finding it
After the wasm multi-memory feature landed, the researcher found a bug in ReloadInstanceCacheIntoSsa in the wasm graph-builder interface. The cached pointer of a wasm memory used by compiled code is not updated while executing. If the backing store of that memory is replaced during memory.grow, a use-after-free crash occurs. The researcher notes it is likely the same issue as Chromium issue 1377816.
The suspicious code:
void ReloadInstanceCacheIntoSsa(SsaEnv* ssa_env, const WasmModule* module) {
if (module->memories.empty()) return;
const WasmMemory* memory0 = &module->memories[0];
if (memory0->initial_pages == memory0->maximum_pages) return;
LoadInstanceCacheIntoSsa(ssa_env);
}
Line by line:
void ReloadInstanceCacheIntoSsa(SsaEnv* ssa_env, const WasmModule* module)declares the function that is supposed to refresh the saved memory information. It receives the module being compiled.if (module->memories.empty()) return;says: if the module has no memories at all, there is nothing to refresh, so stop.const WasmMemory* memory0 = &module->memories[0];picks the first memory in the module's list. This is the key line: it always looks at memory number 0.if (memory0->initial_pages == memory0->maximum_pages) return;says: if memory 0 starts at its maximum size, it can never grow, so there is no need to refresh anything, and the function stops here.LoadInstanceCacheIntoSsa(ssa_env);is the actual refresh. It only runs if the earlier check did not stop the function.
Only memory0 of the memories vector is considered. If memory 0 has initial_pages equal to maximum_pages, it cannot grow, so the function returns early and LoadInstanceCacheIntoSsa is never executed. With multi-memory (after M120, per the researcher), other memories can also be imported into a wasm instance and grown, so the early return is wrong for them.
The behaviour changed with this commit:
commit [redacted]
Author: Clemens Backes <[redacted]>
Date: Fri Aug 4 15:58:54 2023 +0200
[wasm][turbofan] Determine the memory index to cache
We currently always cache memory start and size of memory 0. With
multiple memories, this needs to be adapted.
The Liftoff approach to always cache the LRU memory does not work well
for TurboFan, because we would need to load the fields when they are
first used, which might be inside of loops.
In order to avoid regressions, we thus determine one memory to cache per
function. We currently take the first memory that is being accessed
insode the function via a standard memory access operation. For the use
cases that we currently see this works perfectly fine, if we see use
cases where multiple memories are accessed inside a function then we
might need to readjust this.
R=[redacted]
Bug: v8:13918
Change-Id: [redacted]
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/4751826
Commit-Queue: Clemens Backes <[redacted]>
Reviewed-by: Thibaud Michaud <[redacted]>
Cr-Commit-Position: refs/heads/main@{#89434}
This is a commit message from the V8 source code repository. It records a change made on 4 August 2023. The title says the change is about deciding which memory index to cache. The body explains that the code used to always cache memory 0, and that with multiple memories this had to change. It also explains why the approach used by Liftoff (another V8 compiler) of always caching the least recently used memory did not suit TurboFan: TurboFan would have to load the fields when they are first used, which might be inside loops. So the change picks one memory per function, namely the first memory the function accesses with a standard memory access operation. The rest of the message is metadata: the reviewer, the bug number, the change identifier, the review link and the commit position.
Before this commit, the graph builder always cached memory 0. After it, the builder has a cached_memory_index_ member, set by this code:
size_t num_memories =
decoder->module_ == nullptr ? 0 : decoder->module_->memories.size();
if (num_memories == 1) {
builder_->set_cached_memory_index(0);
} else if (num_memories > 1) {
int first_used_mem_index = FindFirstUsedMemoryIndex(
base::VectorOf(decoder->start(), decoder->end() - decoder->start()),
decoder->zone());
if (first_used_mem_index >= 0) {
builder_->set_cached_memory_index(first_used_mem_index);
}
}
Line by line:
size_t num_memories = decoder->module_ == nullptr ? 0 : decoder->module_->memories.size();counts how many memories the module has. If there is no module, the count is 0; otherwise it is the size of the module's memory list.if (num_memories == 1) {handles the simple case of exactly one memory.builder_->set_cached_memory_index(0);in that case, caches memory 0, which is the only one.} else if (num_memories > 1) {handles the multi-memory case.int first_used_mem_index = FindFirstUsedMemoryIndex(starts a call to a helper that finds the first memory the function actually uses.base::VectorOf(decoder->start(), decoder->end() - decoder->start()),passes the bytes of the function body to that helper.decoder->zone());passes a memory area (a zone) the helper can use for temporary work.if (first_used_mem_index >= 0) {checks that a memory was found (a negative value means none).builder_->set_cached_memory_index(first_used_mem_index);records that memory as the one to cache.
And the index is found by walking the wasm opcodes:
int FindFirstUsedMemoryIndex(base::Vector<const uint8_t> body, Zone* zone) {
BodyLocalDecls locals;
for (BytecodeIterator it{body.begin(), body.end(), &locals, zone};
it.has_next(); it.next()) {
WasmOpcode opcode = it.current();
constexpr bool kConservativelyAssumeMemory64 = true;
constexpr bool kConservativelyAssumeMultiMemory = true;
switch (opcode) {
default:
break;
#define CASE(name, ...) case kExpr##name:
FOREACH_LOAD_MEM_OPCODE(CASE)
FOREACH_STORE_MEM_OPCODE(CASE)
#undef CASE
MemoryAccessImmediate imm(
&it, it.pc() + 1, UINT32_MAX, kConservativelyAssumeMemory64,
kConservativelyAssumeMultiMemory, Decoder::kNoValidation);
return imm.mem_index;
}
}
return -1;
}
Line by line:
int FindFirstUsedMemoryIndex(base::Vector<const uint8_t> body, Zone* zone)declares a helper that takes the function body as bytes and returns the index of the first memory used, or a negative number if none is found.BodyLocalDecls locals;prepares a place to hold the function's local variable declarations.for (BytecodeIterator it{body.begin(), body.end(), &locals, zone};starts a loop that walks through the function's instructions one by one.it.has_next(); it.next()) {keeps the loop going while there are instructions left.WasmOpcode opcode = it.current();reads the current instruction.constexpr bool kConservativelyAssumeMemory64 = true;andconstexpr bool kConservativelyAssumeMultiMemory = true;set two flags that tell the decoder to assume the most general case, so it does not miss a memory reference.switch (opcode) {starts a decision on the instruction type.default: break;ignores instructions that are not memory loads or stores.- The
#define CASE(name, ...) case kExpr##name:and the twoFOREACH_LOAD_MEM_OPCODE(CASE)/FOREACH_STORE_MEM_OPCODE(CASE)lines generate a case for every load and store instruction, so the code below runs only for those. MemoryAccessImmediate imm(...)decodes the instruction's memory index, using the flags set above and skipping validation.return imm.mem_index;returns that index as soon as the first memory access is found.return -1;at the end means no memory access was found in the whole function.
In short, the first memory used while traversing the wasm opcodes becomes cached_memory_index_. So if memory 1 is the cached one and memory 0 has initial_pages == maximum_pages, LoadInstanceCacheIntoSsa is never executed inside ReloadInstanceCacheIntoSsa, and the cached pointer for memory 1 is never refreshed.
Exploitation
Step 1: Build a d8 with the affected V8
d8 is V8's own command-line shell for running JavaScript outside a browser, useful for testing. The researcher tested on Windows 11 with a d8 build from V8 commit [redacted], built with:
python3 .\tools\dev\gm.py x64.release
This command runs a Python helper script that comes with the V8 source tree. It builds a 64-bit release version of d8. The proof of concept was then run as:
out\x64.release\d8.exe poc.js
This runs the built d8 program on a JavaScript file called poc.js, which contains the proof of concept.
The PoC allocates several large wasm memories with 65536 initial pages, so the researcher recommends a Windows 11 host or VM with 16GB or 32GB of physical memory. Some 8GB machines with large virtual memory may also work. Machines with 128GB or more may behave differently, though the researcher was not sure. The researcher tested on V8 12.1.0 to 12.2.0.
Step 2: Arrange the memories
Create a wasm module with multiple memories where memory 0 has initial_pages equal to maximum_pages (so it cannot grow) and a later memory is the first one accessed by the function, making it the cached memory. Allocate several large memories with 65536 initial pages, as the researcher did.
Step 3: Grow the cached memory
Call memory.grow on the cached memory so its backing store is replaced. Because ReloadInstanceCacheIntoSsa returns early on memory 0, the cached start pointer is not reloaded.
Step 4: Access the memory again
The compiled code uses the stale pointer into the freed backing store, producing a use-after-free crash. The run output showed the grow attempts and then the crash:
success_grow_amount: 1
fail_grow_amount: 1
success_grow_amount: 2
==== C stack trace ===============================
(No symbol) [0x000002127D441B93]
(No symbol) [0x000002C880000000]
(No symbol) [0x000001E7000027E1]
(No symbol) [0x0000000000000008]
(No symbol) [0x00000020871FEB90]
Builtins_JSToWasmWrapperAsm [0x00007FF67C31E50A+138]
Builtins_JSToWasmWrapperAsm [0x00007FF67C31E50A+138]
Builtins_JSToWasmWrapper [0x00007FF67C3F5F93+2771]
Builtins_InterpreterEntryTrampoline [0x00007FF67C290FEA+298]
Builtins_InterpreterEntryTrampoline [0x00007FF67C290FEA+298]
Builtins_JSEntryTrampoline [0x00007FF67C28EA5C+92]
Builtins_JSEntry [0x00007FF67C28E65B+219]
v8::internal::`anonymous namespace'::Invoke [0x00007FF67B2784DE+2190]
v8::internal::Execution::CallScript [0x00007FF67B278D98+232]
v8::Script::Run [0x00007FF67B0CDA7D+1021]
v8::Script::Run [0x00007FF67B0CD66D+13]
v8::Shell::ExecuteString [0x00007FF67B0A50E6+1606]
v8::SourceGroup::Execute [0x00007FF67B0B836D+637]
v8::Shell::RunMainIsolate [0x00007FF67B0BB55F+319]
v8::Shell::RunMain [0x00007FF67B0BB203+307]
v8::Shell::Main [0x00007FF67B0BCF09+3113]
__scrt_common_main_seh [0x00007FF67C452988+268]
BaseThreadInitThunk [0x00007FFE5A77257D+29]
RtlUserThreadStart [0x00007FFE5BB8AA58+40]
The first three lines are the program's own output, showing how many grow attempts succeeded and failed. Then comes a C stack trace: a list of the function calls that were active when the crash happened, from the innermost call at the top to the outermost at the bottom. The addresses are memory locations; (No symbol) means the tool could not match that address to a named function. The names that do appear show the path through V8: the JS-to-wasm wrapper (the code that lets JavaScript call a wasm function), the interpreter entry trampoline, the script execution functions, and finally the shell's main function. The stack trace shows the crash occurring under the JS-to-wasm wrapper.
Root cause
ReloadInstanceCacheIntoSsa decides whether to reload the instance cache by looking only at module->memories[0]. The commit that introduced cached_memory_index_ made the graph builder cache whichever memory the function first accesses, but the reload check was not updated to use that index. When memory 0 is fixed-size and the cached memory is a different one, the early return skips LoadInstanceCacheIntoSsa, so the cached start pointer and size are not refreshed after a grow. The backing store is freed and replaced, and compiled code keeps using the old pointer.
The bisect points at the same commit, [redacted]. A bisect is a way of finding which change introduced a bug by testing versions in the middle of a range and narrowing down until the culprit is found.
Impact
The result is a use-after-free in V8 reachable from wasm code that uses multiple memories. The researcher believes the bug can be exploited in 32-bit Chrome in the same way as Chromium issue 1377816, and planned to try it and update if successful. The report does not show a working exploit, only the crash. Exploitation requires a module where memory 0 cannot grow and a later memory is the cached one, plus a grow of that cached memory while compiled code holds the stale pointer.
Fix
The fix makes the reload check use the cached memory index instead of memory 0:
--- a/src/wasm/graph-builder-interface.cc
+++ b/src/wasm/graph-builder-interface.cc
@@ -270,8 +270,10 @@ class WasmGraphBuildingInterface {
// actually grow.
void ReloadInstanceCacheIntoSsa(SsaEnv* ssa_env, const WasmModule* module) {
if (module->memories.empty()) return;
- const WasmMemory* memory0 = &module->memories[0];
- if (memory0->initial_pages == memory0->maximum_pages) return;
+ const WasmMemory* cached_memory = &module->memories[builder_->cached_memory_index()];
+ if (cached_memory->initial_pages == cached_memory->maximum_pages) return;
LoadInstanceCacheIntoSsa(ssa_env);
}
This is a diff, a format that shows what changed in a file. Lines starting with - are removed and lines starting with + are added. The two removed lines looked at memory 0. The two added lines look at the memory the builder actually cached, using cached_memory_index(). The patch makes the reload check use the cached memory index instead of memory 0.
Variants to test
- Other cached-memory selection paths. Build modules where the first accessed memory is not memory 0 and memory 0 is fixed-size, then grow the cached memory. A positive result is a crash under the JS-to-wasm wrapper or a stale pointer observed after the grow.
- Different memory counts. Try modules with exactly one memory and with several, to confirm the single-memory path still caches memory 0 and reloads correctly. A positive result is a crash only in the multi-memory case.
- Other engines or versions. Check V8 versions around 12.1.0 to 12.2.0 and any engine that adopted the same per-function cached memory index. A positive result is the same early-return pattern in the reload check.
- 32-bit builds. The researcher expected exploitability in 32-bit Chrome following issue 1377816. A positive result would be controlled reuse of the freed backing store rather than a plain crash.
Glossary
- V8: the JavaScript and WebAssembly engine inside Chrome and other products.
- WebAssembly (wasm): a fast, low-level language that browsers can run, often produced by compiling other languages.
- TurboFan: V8's optimising compiler, which turns hot code into faster machine-level code.
- Graph builder: the part of TurboFan that translates a decoded wasm function into TurboFan's internal representation.
- SSA (static single assignment): a way of writing a program internally where each value is assigned only once.
- Linear memory: the block of memory a wasm program uses for its data, behaving like one long array of bytes.
- Backing store: the actual chunk of memory reserved behind a linear memory.
- Instance cache: saved values, such as a memory's start pointer and size, that compiled code can read quickly.
memory.grow: the wasm instruction that asks a linear memory to become larger.- Multi-memory: a wasm feature allowing one module to use more than one linear memory.
- Use-after-free: a bug where a program keeps using memory after it has been freed.
- Pointer: a value that records where something lives in memory.
- Stale pointer: a pointer that still refers to an old location after the data has moved or been freed.
- Commit: a recorded change in a source code repository.
- Bisect: a method of finding the change that introduced a bug by testing versions in the middle of a range and narrowing down.
- d8: V8's command-line shell for running JavaScript outside a browser.
- Proof of concept (PoC): a small program that demonstrates a bug.
- Stack trace: a list of the function calls active when a program crashed, from innermost to outermost.
- JS-to-wasm wrapper: the code that lets JavaScript call a wasm function.
- Diff: a format showing lines removed from and added to a file.
- 32-bit / 64-bit: ways of describing how much memory a program can address at once; 32-bit programs have a smaller address space.
- CVE: a public identifier given to a known security vulnerability.
- Chrome VRP: Google Chrome's Vulnerability Reward Program, which pays researchers for reporting bugs.