Type Confusion in V8 (CVE-2025-13229)
V8 incorrectly types the result of the WebAssembly ref.func instruction as an exact function type, even though imported functions may be subtypes of the declared type. An attacker could exploit this to cause a type confusion and achieve an arbitrary write within the sandbox, potentially leading to remote code execution.
Originally disclosed on Chrome VRP
- Fix shipped in 40 days
README
This is potentially a Wasm spec-level unsoundness issue. However, there seem to be no public spec documenting how ref.func and other operations that yield references work in conjunction with custom descriptors. I am reporting this privately to Google Chrome/V8 as Google seems to be leading the spec work and implementation of custom descriptors the first and practically has the most affected users in the wild.
As this might be a spec-level unsoundness which the Wasm community needs to know, I believe that the issue necessitates a quicker disclosure deadline than what is enforced by default by Chrome's disclosure policies. It would be great if we can coordinate the disclosure within a week from the reported date - please contact me through email or through the comments. Unless otherwise coordinated, the spec unsoundness issue is subject to a 14-day disclosure deadline after which the issue, without any specific mentions of Chrome/V8, will be disclosed publicly on https://github.com/WebAssembly/custom-descriptors/issues. The Chrome/V8 security team is allowed to responsibly disclose this to other vendors and personnel involved in WebAssembly work (at CG meetings or whatnot) under the conditions that 1. the reporter is credited, and 2. is given at least a day's advance notice.
VULNERABILITY DETAILS
Summary
Wasm type confusion due to invalidly typing ref.func function types as exact. Imported functions are allowed to be subtypes of the declared function type, and ref.func returns the original reference for equivalence with the original import. However, ref.func is typed as exact based on its declared function type which is unsound. By abusing WasmGCTypeAnalyzer reachability analysis, this may be pivoted into arbitrary Wasm type confusion.
Custom descriptors feature is exposed in the wild by default through Origin Trials from M141, which is currently at Beta and very soon reaches (Early) Stable. This bug is not caused by a recent code change and has existed from the very first feature implementation (approx. 6 months) due to a likely inherent spec unsoundness.
This bug is notable in that
ref.funcoperation itself is completely unrelated to custom descriptors, yet the addition of exactness introduces unsoundness.
Details
WebAssembly Custom Descriptors proposal introduces exactness as part of heaptype. An object may only be typed as exact if it is exactly an instance of that type, but not for its subtypes. Most importantly, this is not only valid for struct types but for all indexed types including function types.
Currently, V8 types ref.func as exact types of its declared function type:
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/function-body-decoder-impl.h;drc=43df3221d3b0c1ea8f7d54394a00cb8656204085;l=4240
DECODE(RefFunc) {
this->detected_->add_reftypes();
IndexImmediate imm(this, this->pc_ + 1, "function index", validate);
if (!this->ValidateFunction(this->pc_ + 1, imm)) return 0;
ModuleTypeIndex index = this->module_->functions[imm.index].sig_index;
const TypeDefinition& type_def = this->module_->type(index);
Value* value =
Push(ValueType::Ref(index, type_def.is_shared, RefTypeKind::kFunction)
.AsExactIfEnabled(this->enabled_)); // [!] typed as exact based on declared function type
CALL_INTERFACE_IF_OK_AND_REACHABLE(RefFunc, imm.index, value);
return 1 + imm.length;
}
Other decoders, e.g. ModuleDecoderImpl::consume_init_expr(), ConstantExpressionInterface::RefFunc(), also does the same and types it as exact.
However, imported functions may very well be subtypes of the declared type based on Wasm spec. Importing a subtyped function does not violate any JS-Wasm boundary type checks and is perfectly legal:
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/module-instantiate.cc;drc=e75b1ba2a99aa352048745d44754c5de8be273d8;l=733
ImportCallKind ResolvedWasmImport::ComputeKind(
DirectHandle<WasmTrustedInstanceData> trusted_instance_data, int func_index,
const wasm::CanonicalSig* expected_sig, CanonicalTypeIndex expected_sig_id,
WellKnownImport preknown_import) {
// ...
if (!trusted_function_data_.is_null()) {
if (Tagged<WasmExportedFunctionData> data;
TryCast(*trusted_function_data_, &data)) {
if (!data->MatchesSignature(expected_sig_id)) { // [!] allows subtype
return ImportCallKind::kLinkError;
}
uint32_t function_index = static_cast<uint32_t>(data->function_index());
if (function_index >=
data->instance_data()->module()->num_imported_functions) {
return ImportCallKind::kWasmToWasm;
}
// ...
}
}
// ...
}
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-objects.cc;drc=e75b1ba2a99aa352048745d44754c5de8be273d8;l=3085
bool WasmExportedFunctionData::MatchesSignature(
wasm::CanonicalTypeIndex other_canonical_type_index) {
return wasm::GetTypeCanonicalizer()->IsCanonicalSubtype( // [!] allows subtype
sig_index(), other_canonical_type_index);
}
Plus, imported functions preserve their reference for equivalence.
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/module-instantiate.cc;drc=e75b1ba2a99aa352048745d44754c5de8be273d8;l=2335
bool InstanceBuilder::ProcessImportedFunction(
DirectHandle<WasmTrustedInstanceData> trusted_instance_data,
int import_index, int func_index, DirectHandle<Object> value,
WellKnownImport preknown_import) {
// ...
// Store any {WasmExternalFunction} callable in the instance before the call
// is resolved to preserve its identity. This handles exported functions as
// well as functions constructed via other means (e.g. WebAssembly.Function).
if (WasmExternalFunction::IsWasmExternalFunction(*value)) {
trusted_instance_data->func_refs()->set( // [!] stores imported function, later returned for ref.func
func_index, Cast<WasmExternalFunction>(*value)->func_ref());
}
// ...
}
This indicates that ref.func must NOT be typed as an exact type, at the very least for imported functions, as its actual type may be a subtype. However, it is statically typed as an exact (super)type. Consider the following case:
- We have function types
f2 <: f1 - Module 1 exports
fn : f2. - Module 2 imports it as
fn : f1. This is legal. - Module 2 executes
ref.func $fn, yielding typeref exact $f1. This is obviously wrong as its real exact type isref exact $f2, but the next line will show it even more obviously. - Module 2 executes
ref.cast $f1+ref.cast $f2on the object. This results inref exact $f1 -> ref $f1 -> ref $f2casting, which succeeds because the first is a static upcast and the second succeeds dynamically. However, the two typesref exact $f1andref $f2are unrelated in subtyping hierarchy; the cast should never have succeeded.- Note that without custom descriptors and thus without exactness, the cast should succeed!
So how is this exploitable? Enter WasmGCTypeAnalyzer again, which I have first demonstrated that it can be used to pivot seemingly unexploitable Wasm type confusions into attacker-chosen, arbitrary type confusions (b/372269618, b/373703277, b/374790906, b/377620832, ...). After a series of exploits WasmGCTypeAnalyzer has been hardened such that most operations that lead to an unreachable state are replaced to trap or otherwise conform with the statically reachable case unconditionally. But we can still run around the mitigations and exploit subtle discrepancies as shown in the below Wasm code, pulled out from the repro (replace v = f1, v2 = f2, imp = fn):
kExprBlock, kWasmVoid,
// make typer track function type as ref v2
kExprRefFunc, $imp, // decoder: ref exact v (mistyped!), typer: ref v
kExprLocalTee, 3,
kGCPrefix, kExprRefCast, $sig_v_v, // decoder: ref v (upcast), typer: ref v
kGCPrefix, kExprRefCast, $sig_v_v2, // decoder: ref v2, typer: ref v2, runtime: cast succeed
kExprDrop,
// now refine it with ref exact v
kExprLocalGet, 3, // decoder: ref exact v, typer: ref v2
kGCPrefix, kExprRefCastNull, kWasmExact, $sig_v_v, // decoder: ref null exact v (upcast), typer: ref v2
// exploit implicit type refinement w/ inconsistent types from decoder
kExprBrOnNonNull, 0, // typer: (ref exact v) & (ref v2) = bot on branch taken, runtime: branch taken
kExprUnreachable,
kExprEnd,
kExprBrOnNonNull leads to RefineTypeKnowledge(is_null.object(), is_null.type.AsNonNull(), branch), where is_null.type is taken from the decoder's static typing information. The typer already tracks the object's type as ref v2, and as (ref exact v) & (ref v2) = bot following code is marked as statically unreachable while it is in fact reached dynamically. Note that both sides of the branch is typed as unreachable, and that there is no statically "reachability compliant" result of IsNull that the operation should get reduced into (aside from replacing it with an unconditional trap).
Exploiting such reachability analysis bug has been shown to be possible in prior reports via loop reprocessing bypass, and thus is omitted.
Although I cannot find a spec that describes how ref.func should be typed with custom descriptors, it seems that there is enough brokenness across other implementations potentially indicating a spec issue (again, if a spec even exists). Binaryen also documents that they implement this exactness typing rule in PR #7600.
Bisect
Bug introduced by WebAssembly Custom Descriptors, on Origin Trials from M141 and onwards. More specifically, it is introduced in commit 25a0fc85 and dc8cec44 which makes ref.func exact.
VERSION
Chrome Version: M141~
Operating System: All
REPRODUCTION CASE
Attached as poc.js which exploits this issue to alias two unrelated struct types, then uses this type confusion to trigger an arbitrary caged write within the sandbox.
Also attached is rce.html which exploits this issue, together with the wrapper-wasmcpt-uaf v8sbx bypass, to gain RCE and print out /flag/flag to stdout.
You might want to pass --experimental-wasm-custom-descriptors on d8 or --enable-blink-features=WebAssemblyCustomDescriptors on Chrome to simulate Origin Trials behavior.
FOR CRASHES, PLEASE INCLUDE THE FOLLOWING ADDITIONAL INFORMATION
Type of crash: Renderer
Crash State: Crashes on arbitrary caged write attempt from JIT-compiled Wasm function with poc.js / RCE with rce.html
CREDIT INFORMATION
Reporter credit: Seunghyun Lee (@0x10n) of CMU CSD / CyLab
Context
This report concerns V8, the JavaScript and WebAssembly engine used by Google Chrome, and specifically the WebAssembly Custom Descriptors proposal. Custom Descriptors introduces exactness as part of a heap type. An object may only be typed as exact if it is exactly an instance of that type, not an instance of a subtype. The proposal applies this to all indexed types, including function types, not only struct types.
The feature was exposed in the wild by default through Origin Trials from M141, which at the time of reporting was at Beta and about to reach (Early) Stable. The bug was not caused by a recent code change: according to the report it had existed from the very first implementation of the feature, roughly six months, and the reporter describes it as a likely inherent spec unsoundness.
The reporter frames the issue as potentially a Wasm spec-level unsoundness. There appeared to be no public spec documenting how ref.func and other operations that yield references behave together with custom descriptors, so the report was filed privately with Google Chrome/V8 on the basis that Google leads the spec work and implementation and has the most affected users in the wild.
Because the Wasm community might need to know about a spec-level problem, the reporter asked for a faster deadline than Chrome's default policy: coordination within a week of the reported date, and otherwise a 14-day disclosure deadline after which the issue would be published, without specific mentions of Chrome/V8, at https://github.com/WebAssembly/custom-descriptors/issues. The Chrome/V8 security team was permitted to disclose responsibly to other vendors and to people involved in WebAssembly work, such as at CG meetings, provided the reporter is credited and is given at least a day's advance notice.
A notable point the reporter makes is that ref.func itself is completely unrelated to custom descriptors, yet the addition of exactness introduces unsoundness into it.
Setup
No accounts, roles or special tooling are described beyond the engine itself. The relevant preconditions are:
- A V8 build with the custom descriptors feature enabled. To simulate Origin Trials behaviour, the report suggests
--experimental-wasm-custom-descriptorson d8 or--enable-blink-features=WebAssemblyCustomDescriptorson Chrome. - The affected versions are Chrome M141 and later, on all operating systems.
- Two attached files are referenced:
poc.js, which exploits the issue to alias two unrelated struct types and then trigger an arbitrary caged write within the sandbox, andrce.html, which combines the issue with thewrapper-wasmcpt-uafv8sbx bypass to gain RCE and print/flag/flagto stdout.
Finding it
The starting observation is in the decoder. V8 types ref.func as the exact type of its declared function type:
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/function-body-decoder-impl.h;drc=[redacted];l=4240
DECODE(RefFunc) {
this->detected_->add_reftypes();
IndexImmediate imm(this, this->pc_ + 1, "function index", validate);
if (!this->ValidateFunction(this->pc_ + 1, imm)) return 0;
ModuleTypeIndex index = this->module_->functions[imm.index].sig_index;
const TypeDefinition& type_def = this->module_->type(index);
Value* value =
Push(ValueType::Ref(index, type_def.is_shared, RefTypeKind::kFunction)
.AsExactIfEnabled(this->enabled_)); // [!] typed as exact based on declared function type
CALL_INTERFACE_IF_OK_AND_REACHABLE(RefFunc, imm.index, value);
return 1 + imm.length;
}
Other decoders, such as ModuleDecoderImpl::consume_init_expr() and ConstantExpressionInterface::RefFunc(), do the same and also type the result as exact.
The problem is that imported functions may legally be subtypes of the declared function type. Importing a subtyped function does not violate any JS-Wasm boundary type checks. The report shows where the import path allows a subtype:
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/module-instantiate.cc;drc=[redacted];l=733
ImportCallKind ResolvedWasmImport::ComputeKind(
DirectHandle<WasmTrustedInstanceData> trusted_instance_data, int func_index,
const wasm::CanonicalSig* expected_sig, CanonicalTypeIndex expected_sig_id,
WellKnownImport preknown_import) {
// ...
if (!trusted_function_data_.is_null()) {
if (Tagged<WasmExportedFunctionData> data;
TryCast(*trusted_function_data_, &data)) {
if (!data->MatchesSignature(expected_sig_id)) { // [!] allows subtype
return ImportCallKind::kLinkError;
}
uint32_t function_index = static_cast<uint32_t>(data->function_index());
if (function_index >=
data->instance_data()->module()->num_imported_functions) {
return ImportCallKind::kWasmToWasm;
}
// ...
}
}
// ...
}
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-objects.cc;drc=[redacted];l=3085
bool WasmExportedFunctionData::MatchesSignature(
wasm::CanonicalTypeIndex other_canonical_type_index) {
return wasm::GetTypeCanonicalizer()->IsCanonicalSubtype( // [!] allows subtype
sig_index(), other_canonical_type_index);
}
Imported functions also preserve their reference, for equivalence:
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/module-instantiate.cc;drc=[redacted];l=2335
bool InstanceBuilder::ProcessImportedFunction(
DirectHandle<WasmTrustedInstanceData> trusted_instance_data,
int import_index, int func_index, DirectHandle<Object> value,
WellKnownImport preknown_import) {
// ...
// Store any {WasmExternalFunction} callable in the instance before the call
// is resolved to preserve its identity. This handles exported functions as
// well as functions constructed via other means (e.g. WebAssembly.Function).
if (WasmExternalFunction::IsWasmExternalFunction(*value)) {
trusted_instance_data->func_refs()->set( // [!] stores imported function, later returned for ref.func
func_index, Cast<WasmExternalFunction>(*value)->func_ref());
}
// ...
}
Taken together, these show that ref.func must not be typed as an exact type, at least for imported functions, because its actual type may be a subtype. Yet it is statically typed as an exact supertype.
The reporter illustrates the consequence with a concrete scenario:
- We have function types
f2 <: f1. - Module 1 exports
fn : f2. - Module 2 imports it as
fn : f1. This is legal. - Module 2 executes
ref.func $fn, yielding typeref exact $f1. This is wrong, since its real exact type isref exact $f2. - Module 2 executes
ref.cast $f1followed byref.cast $f2on the object. This results inref exact $f1 -> ref $f1 -> ref $f2casting, which succeeds because the first is a static upcast and the second succeeds dynamically. However,ref exact $f1andref $f2are unrelated in the subtyping hierarchy, so the cast should never have succeeded. Without custom descriptors, and therefore without exactness, the cast should succeed.
Exploitation
Step 1: turn the mistyping into a reachability discrepancy
The pivot uses WasmGCTypeAnalyzer, which the reporter had previously demonstrated can turn seemingly unexploitable Wasm type confusions into attacker-chosen arbitrary type confusions (referencing b/372269618, b/373703277, b/374790906, b/377620832 and others). After those exploits the analyser was hardened so that most operations leading to an unreachable state are replaced with a trap or otherwise made to conform unconditionally with the statically reachable case. The report states that subtle discrepancies can still be exploited, as in the following Wasm code pulled from the repro, with v = f1, v2 = f2 and imp = fn:
kExprBlock, kWasmVoid,
// make typer track function type as ref v2
kExprRefFunc, $imp, // decoder: ref exact v (mistyped!), typer: ref v
kExprLocalTee, 3,
kGCPrefix, kExprRefCast, $sig_v_v, // decoder: ref v (upcast), typer: ref v
kGCPrefix, kExprRefCast, $sig_v_v2, // decoder: ref v2, typer: ref v2, runtime: cast succeed
kExprDrop,
// now refine it with ref exact v
kExprLocalGet, 3, // decoder: ref exact v, typer: ref v2
kGCPrefix, kExprRefCastNull, kWasmExact, $sig_v_v, // decoder: ref null exact v (upcast), typer: ref v2
// exploit implicit type refinement w/ inconsistent types from decoder
kExprBrOnNonNull, 0, // typer: (ref exact v) & (ref v2) = bot on branch taken, runtime: branch taken
kExprUnreachable,
kExprEnd,
The sequence works as follows. ref.func $imp is typed by the decoder as ref exact v (the mistyping) while the typer tracks it as ref v. The value is stored in local 3 with local.tee. Two ref.cast operations then bring the decoder and typer to ref v2, and at runtime the cast succeeds. The value is dropped from the stack but remains in local 3.
local.get 3 then reads it back: the decoder sees ref exact v, the typer sees ref v2. A ref.cast null with kWasmExact to $sig_v_v is an upcast for the decoder, giving ref null exact v, while the typer still tracks ref v2.
Step 2: make the branch statically unreachable but dynamically taken
kExprBrOnNonNull calls RefineTypeKnowledge(is_null.object(), is_null.type.AsNonNull(), branch), where is_null.type comes from the decoder's static typing information. The typer already tracks the object as ref v2, and since (ref exact v) & (ref v2) = bot, the code after the branch is marked statically unreachable while it is in fact reached dynamically. Both sides of the branch are typed as unreachable, and there is no statically reachability-compliant result of IsNull the operation could be reduced to, other than replacing it with an unconditional trap.
The report notes that exploiting such a reachability analysis bug has been shown to be possible in prior reports via loop reprocessing bypass, and omits the details here.
Step 3: from type confusion to a caged write and RCE
The attached poc.js exploits the issue to alias two unrelated struct types and then uses the resulting type confusion to trigger an arbitrary caged write within the sandbox. The attached rce.html combines the issue with the wrapper-wasmcpt-uaf v8sbx bypass to gain RCE and print /flag/flag to stdout.
The crash information in the report states the crash type as Renderer, with the crash state being a crash on an arbitrary caged write attempt from a JIT-compiled Wasm function with poc.js, or RCE with rce.html.
Root cause
The mistake is the exactness annotation on ref.func. The decoder types the result as ref exact of the declared function type, but an imported function is allowed to be a subtype of that declared type, and ref.func returns the original reference so that it stays equivalent to the import. The static type is therefore an exact supertype while the runtime object may be an exact subtype, and the two are unrelated in the subtyping hierarchy. The same exactness typing appears in other decoders, including ModuleDecoderImpl::consume_init_expr() and ConstantExpressionInterface::RefFunc().
The hardening of WasmGCTypeAnalyzer replaces most operations that lead to an unreachable state with a trap or makes them conform with the statically reachable case, yet the report shows subtle discrepancies can still be exploited. Here the two disagree, and the intersection of ref exact v and ref v2 is bottom, so the analyser concludes the branch target is unreachable while the branch is taken at runtime. The report also points out that Binaryen documents implementing the same exactness typing rule in PR #7600, which it says may indicate a spec issue.
According to the bisect, the bug was introduced by the WebAssembly Custom Descriptors work, on Origin Trials from M141 onwards, specifically in commits 25a0fc85 and dc8cec44, which make ref.func exact.
Impact
With poc.js, the issue aliases two unrelated struct types and triggers an arbitrary caged write within the sandbox from a JIT-compiled Wasm function. With rce.html, combined with the wrapper-wasmcpt-uaf v8sbx bypass, it yields RCE and reads /flag/flag. The report describes the feature as exposed in the wild by default through Origin Trials from M141, at Beta and about to reach (Early) Stable, on all operating systems. The reporter characterises the underlying problem as potentially spec-level, since no public spec appears to document how ref.func should be typed with custom descriptors, and other implementations may share it.
Fix
The report does not describe a fix. The reporter's position is that ref.func must not be typed as an exact type, at least for imported functions, because its actual type may be a subtype. The report also raises the possibility that the correct behaviour needs to be settled at the specification level, given the absence of a public spec and the indication that Binaryen implements the same rule.
Variants to test
- Other reference-producing operations. The report names
ModuleDecoderImpl::consume_init_expr()andConstantExpressionInterface::RefFunc()as also typingref.funcas exact. Test constant expressions and global initialisers that produce function references through imports, and check whether aref.castchain can move an exact supertype to an unrelated subtype. A positive result is a cast succeeding between types that are unrelated in the subtyping hierarchy. - Imported subtypes across modules. Build a pair of modules where one exports a function of a subtype and the other imports it at the supertype, then use
ref.funcon the import. A positive result is the imported reference being statically typed as exact at the supertype. - Reachability refinement operations. Any operation that refines type knowledge from decoder-supplied types, such as
br_on_non_null, is a candidate for the same bottom-intersection trick. A positive result is a branch that the analyser marks unreachable but that is taken at runtime. - Other engines and toolchains. Since Binaryen documents the same exactness rule in PR #7600, test engines and toolchains that implement custom descriptors for the same
ref.functyping. A positive result is the same mismatch between the declared exact type and the runtime exact subtype of an imported function. - Loop reprocessing. The report refers to prior work using loop reprocessing to bypass reachability mitigations. Re-test the hardened analyser with loops around the refined branch to see whether the unreachable marking can be carried into code that executes.
What happened, in plain words
A security researcher found a bug in Google Chrome. The bug is not in the part of Chrome you see, like tabs or the address bar. It is in V8, the engine inside Chrome that runs JavaScript and WebAssembly. WebAssembly (often shortened to Wasm) is a way to run programs written in other languages inside a browser at near-native speed. V8 is the software that reads those programs and turns them into instructions the computer can run.
A new WebAssembly feature called Custom Descriptors was being tested in Chrome. It adds a concept called exactness: a label on a type saying "this value is exactly this type, not a more specific version of it". The researcher found that V8 was putting that "exactly this type" label on the result of a WebAssembly instruction called ref.func, even though the value could legally be a more specific type. That mismatch let a crafted WebAssembly program confuse the engine about what type a value has. The researcher then used that confusion to trigger an arbitrary caged write within the sandbox, and, combined with the wrapper-wasmcpt-uaf v8sbx bypass, to gain RCE and print /flag/flag to stdout.
The reporter believed the mistake might be a flaw at the WebAssembly specification level, though no public spec documenting this behaviour was found. Because of that, they asked Google for a faster-than-usual public disclosure, so the wider WebAssembly community could learn about it.
Context
The product: V8 and WebAssembly
When you open a web page, Chrome downloads the page's code and hands it to V8. V8 reads JavaScript, and also WebAssembly, and executes it. WebAssembly is a compact binary format designed so that programs written in C, C++, Rust and similar languages can run in a browser safely and quickly. A WebAssembly program is shipped as a module: a self-contained bundle of functions and data, a bit like a sealed box with a list of things it offers to the outside and a list of things it needs from the outside.
The feature: Custom Descriptors and exactness
Custom Descriptors is a proposed addition to WebAssembly. It introduces the idea of an exact type. To understand it, think of animal classifications. "Dog" is a subtype of "Animal": every dog is an animal, but not every animal is a dog. Normally, if a box is labelled "Animal", it may contain a dog. If a box is labelled "exactly Animal", it must contain something that is an animal and nothing more specific, so a dog would not qualify.
In WebAssembly's type system, the same idea applies to heap types, which describe things stored in memory, including functions. The report stresses that exactness applies to all indexed types, including function types, not only to struct types (structs are bundles of named fields, like a record in a database).
The timeline
The feature was being rolled out to real users by default through Origin Trials from Chrome version M141. An Origin Trial is a way for Chrome to switch a new feature on for a portion of real websites before it becomes permanent, so the Chrome team can see how it behaves in the wild. At the time of the report, M141 was at the Beta stage and about to reach (Early) Stable. The bug was not caused by a recent code change: according to the report it had existed since the very first implementation of the feature, roughly six months, and the reporter describes it as a likely inherent flaw in the specification.
Why it was reported privately, and the disclosure request
The reporter frames the issue as potentially a problem at the level of the WebAssembly specification. There appeared to be no public specification documenting how ref.func and other operations that produce references behave together with custom descriptors. A reference here is a value that points at something, such as a function, rather than containing the data itself, like a name card that tells you which person to talk to instead of being the person.
Because Google leads the specification work and the implementation, and has the most affected users in the wild, the report was filed privately with Google Chrome/V8. Because the wider WebAssembly community might need to know about a specification-level problem, the reporter asked for a faster deadline than Chrome's default policy: coordination within a week of the reported date, and otherwise a 14-day disclosure deadline. After that deadline the issue would be published, without specific mentions of Chrome/V8, at https://github.com/WebAssembly/custom-descriptors/issues. The Chrome/V8 security team was permitted to disclose responsibly to other vendors and to people involved in WebAssembly work, such as at CG meetings, provided the reporter is credited and is given at least a day's advance notice.
One point the reporter highlights: ref.func itself is completely unrelated to custom descriptors, yet the addition of exactness introduces the flaw into it.
Setup
No accounts, roles or special tooling are described beyond the engine itself. The relevant preconditions are:
- A V8 build with the custom descriptors feature enabled. To simulate Origin Trials behaviour, the report suggests
--experimental-wasm-custom-descriptorson d8 or--enable-blink-features=WebAssemblyCustomDescriptorson Chrome. d8 is V8's own small command-line program for running JavaScript and WebAssembly, used by developers to test the engine without a full browser. The two strings are command-line flags: switches you add when starting a program to change its behaviour. - The affected versions are Chrome M141 and later, on all operating systems.
- Two attached files are referenced:
poc.js, which exploits the issue to alias two unrelated struct types and then trigger an arbitrary caged write within the sandbox, andrce.html, which combines the issue with thewrapper-wasmcpt-uafv8sbx bypass to gain RCE and print/flag/flagto stdout. A few of those terms deserve a plain explanation now:- Alias means to make two things that should be separate be treated as the same thing. If the engine thinks a box of apples is a box of oranges, it will read and write it using the wrong rules.
- The sandbox is a boundary Chrome builds around the part of itself that processes web content, so that a bug there does not automatically give control of the whole computer. A caged write is a write to memory inside that boundary, at an address the attacker chooses.
- RCE stands for remote code execution: making the target computer run code the attacker supplied.
- v8sbx is the name of the sandbox around V8; a bypass is a way around a protection.
wrapper-wasmcpt-uafis the name of the v8sbx bypass used together with this issue. UAF stands for use-after-free, a bug where memory is used after it has been released. - stdout is the standard output stream, the place where a program prints its normal text output.
Finding it
The decoder labels ref.func as exact
The starting observation is in the decoder. When V8 loads a WebAssembly module, the decoder reads the binary instructions one by one and checks that they make sense, a bit like a proofreader checking a manuscript before it is printed. The decoder also assigns a static type to each value: a label saying what kind of thing the value is, decided before the program runs.
V8 types ref.func as the exact type of its declared function type. ref.func is the WebAssembly instruction that produces a reference to a function. The declared function type is the type written in the module's own list of types, the label the module itself puts on the function.
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/function-body-decoder-impl.h;drc=[redacted];l=4240
DECODE(RefFunc) {
this->detected_->add_reftypes();
IndexImmediate imm(this, this->pc_ + 1, "function index", validate);
if (!this->ValidateFunction(this->pc_ + 1, imm)) return 0;
ModuleTypeIndex index = this->module_->functions[imm.index].sig_index;
const TypeDefinition& type_def = this->module_->type(index);
Value* value =
Push(ValueType::Ref(index, type_def.is_shared, RefTypeKind::kFunction)
.AsExactIfEnabled(this->enabled_)); // [!] typed as exact based on declared function type
CALL_INTERFACE_IF_OK_AND_REACHABLE(RefFunc, imm.index, value);
return 1 + imm.length;
}
Line by line, in plain words:
DECODE(RefFunc) {starts the handler that runs when the decoder meets theref.funcinstruction.this->detected_->add_reftypes();records that the module uses reference types, so the rest of the engine knows to expect them.IndexImmediate imm(this, this->pc_ + 1, "function index", validate);reads the number that follows the instruction in the binary. That number is the index of the function being referred to, like a row number in the module's function table.if (!this->ValidateFunction(this->pc_ + 1, imm)) return 0;checks that the function index is valid. If it is not, decoding stops with an error.ModuleTypeIndex index = this->module_->functions[imm.index].sig_index;looks up the declared type (the signature) of that function.const TypeDefinition& type_def = this->module_->type(index);fetches the full definition of that type.Value* value =begins building the static type label for the value thatref.funcwill produce.Push(ValueType::Ref(index, type_def.is_shared, RefTypeKind::kFunction)creates a reference type pointing at that function type..AsExactIfEnabled(this->enabled_));is the crucial part: if the feature is enabled, it marks the type as exact. The comment on that line,// [!] typed as exact based on declared function type, flags it as the suspect step.CALL_INTERFACE_IF_OK_AND_REACHABLE(RefFunc, imm.index, value);passes the value on to the next stage, but only if decoding succeeded and the code is considered reachable.return 1 + imm.length;tells the decoder how many bytes the instruction occupied, so it can move on to the next one.
Other decoders, such as ModuleDecoderImpl::consume_init_expr() and ConstantExpressionInterface::RefFunc(), do the same and also type the result as exact. A constant expression is a small expression evaluated at load time, for example to set up a global variable, a named storage slot shared across the module.
The problem: imports may be subtypes
The problem is that imported functions may legally be subtypes of the declared function type. An import is something a module asks for from the outside, like a restaurant ordering ingredients from a supplier. The module says what type it expects; the supplier may deliver something more specific that still fits. Importing a subtyped function does not violate any JS-Wasm boundary type checks, the checks that guard the border between JavaScript and WebAssembly.
The report shows where the import path allows a subtype:
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/module-instantiate.cc;drc=[redacted];l=733
ImportCallKind ResolvedWasmImport::ComputeKind(
DirectHandle<WasmTrustedInstanceData> trusted_instance_data, int func_index,
const wasm::CanonicalSig* expected_sig, CanonicalTypeIndex expected_sig_id,
WellKnownImport preknown_import) {
// ...
if (!trusted_function_data_.is_null()) {
if (Tagged<WasmExportedFunctionData> data;
TryCast(*trusted_function_data_, &data)) {
if (!data->MatchesSignature(expected_sig_id)) { // [!] allows subtype
return ImportCallKind::kLinkError;
}
uint32_t function_index = static_cast<uint32_t>(data->function_index());
if (function_index >=
data->instance_data()->module()->num_imported_functions) {
return ImportCallKind::kWasmToWasm;
}
// ...
}
}
// ...
}
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-objects.cc;drc=[redacted];l=3085
bool WasmExportedFunctionData::MatchesSignature(
wasm::CanonicalTypeIndex other_canonical_type_index) {
return wasm::GetTypeCanonicalizer()->IsCanonicalSubtype( // [!] allows subtype
sig_index(), other_canonical_type_index);
}
Line by line, in plain words:
ImportCallKind ResolvedWasmImport::ComputeKind(starts a function that decides how a call to an imported function should be carried out. The parameters include the data of the instance doing the importing, the index of the function, the expected signature (the type the importer expects) and its identifier.if (!trusted_function_data_.is_null()) {checks that there is actual function data to inspect.if (Tagged<WasmExportedFunctionData> data; TryCast(*trusted_function_data_, &data)) {tries to view the data as an exported WebAssembly function.TryCastsucceeds only if the object really is that kind of thing.if (!data->MatchesSignature(expected_sig_id)) {asks whether the function's signature matches the expected one. The comment// [!] allows subtypemarks the key point: the check is not strict equality, it accepts a subtype.return ImportCallKind::kLinkError;if the signature does not match at all, the import fails with a link error, the WebAssembly equivalent of a broken reference at load time.uint32_t function_index = static_cast<uint32_t>(data->function_index());reads the function's index.if (function_index >= data->instance_data()->module()->num_imported_functions) {checks whether the function is defined in the module itself rather than being another import.return ImportCallKind::kWasmToWasm;if so, the call is a direct WebAssembly-to-WebAssembly call.- The second function,
WasmExportedFunctionData::MatchesSignature, is the actual comparison.return wasm::GetTypeCanonicalizer()->IsCanonicalSubtype(asks the type canonicaliser, the component that gives every type a single shared identity, whether the function's own signature is a subtype of the expected one. The comment// [!] allows subtypeagain flags that a subtype is accepted.
Imports keep their identity
Imported functions also preserve their reference, for equivalence. In other words, if you ask for a reference to an imported function, you get back the very same reference that was imported, not a copy. This matters because WebAssembly requires that the same function always compares equal to itself.
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/module-instantiate.cc;drc=[redacted];l=2335
bool InstanceBuilder::ProcessImportedFunction(
DirectHandle<WasmTrustedInstanceData> trusted_instance_data,
int import_index, int func_index, DirectHandle<Object> value,
WellKnownImport preknown_import) {
// ...
// Store any {WasmExternalFunction} callable in the instance before the call
// is resolved to preserve its identity. This handles exported functions as
// well as functions constructed via other means (e.g. WebAssembly.Function).
if (WasmExternalFunction::IsWasmExternalFunction(*value)) {
trusted_instance_data->func_refs()->set( // [!] stores imported function, later returned for ref.func
func_index, Cast<WasmExternalFunction>(*value)->func_ref());
}
// ...
}
Line by line, in plain words:
bool InstanceBuilder::ProcessImportedFunction(starts the routine that wires an imported function into a module instance. An instance is a module that has been loaded and given its imports, ready to run.- The parameters carry the instance's data, the import's position, the function's position, the value being imported and any well-known import information.
- The comment explains the intent: store the callable in the instance before the call is resolved, to preserve its identity. It notes this covers exported functions and functions made by other means, such as
WebAssembly.Function. if (WasmExternalFunction::IsWasmExternalFunction(*value)) {checks whether the imported value is a WebAssembly function object.trusted_instance_data->func_refs()->set(stores it in the instance's table of function references. The comment// [!] stores imported function, later returned for ref.funcmarks that this stored reference is whatref.funcwill later hand back.func_index, Cast<WasmExternalFunction>(*value)->func_ref());records it under the function's index, taking the reference from the imported function object.
What this means
Taken together, these show that ref.func must not be typed as an exact type, at least for imported functions, because its actual type may be a subtype. Yet it is statically typed as an exact supertype. The static label says "exactly this broad type", while the real object is "exactly a narrower type".
The reporter illustrates the consequence with a concrete scenario:
- We have function types
f2 <: f1. The symbol<:means "is a subtype of", so everyf2is also anf1, but not the other way round. - Module 1 exports
fn : f2. It offers a function whose type is the narrower one. - Module 2 imports it as
fn : f1. This is legal, because a narrower type fits where a broader one is expected. - Module 2 executes
ref.func $fn, yielding typeref exact $f1. This is wrong, since its real exact type isref exact $f2. - Module 2 executes
ref.cast $f1followed byref.cast $f2on the object. A cast is an instruction that checks at runtime whether a value really has a given type, and traps if it does not. This results inref exact $f1 -> ref $f1 -> ref $f2casting, which succeeds because the first is a static upcast and the second succeeds dynamically. An upcast is a cast towards a broader type, which is always safe. However,ref exact $f1andref $f2are unrelated in the subtyping hierarchy, so the cast should never have succeeded. Without custom descriptors, and therefore without exactness, the cast should succeed.
Exploitation
Step 1: turn the mistyping into a reachability discrepancy
The pivot uses WasmGCTypeAnalyzer. This is a component inside V8 that analyses WebAssembly GC code (GC stands for garbage collection, automatic memory cleanup) to work out which parts of a program can actually be reached at runtime. The reporter had previously demonstrated that it can turn seemingly unexploitable Wasm type confusions into attacker-chosen arbitrary type confusions, referencing b/372269618, b/373703277, b/374790906, b/377620832 and others. Those identifiers are internal bug numbers.
After those exploits the analyser was hardened so that most operations leading to an unreachable state are replaced with a trap or otherwise made to conform unconditionally with the statically reachable case. A trap is WebAssembly's way of aborting execution immediately when something illegal happens, like a referee blowing the whistle. The report states that subtle discrepancies can still be exploited, as in the following Wasm code pulled from the repro, with v = f1, v2 = f2 and imp = fn:
kExprBlock, kWasmVoid,
// make typer track function type as ref v2
kExprRefFunc, $imp, // decoder: ref exact v (mistyped!), typer: ref v
kExprLocalTee, 3,
kGCPrefix, kExprRefCast, $sig_v_v, // decoder: ref v (upcast), typer: ref v
kGCPrefix, kExprRefCast, $sig_v_v2, // decoder: ref v2, typer: ref v2, runtime: cast succeed
kExprDrop,
// now refine it with ref exact v
kExprLocalGet, 3, // decoder: ref exact v, typer: ref v2
kGCPrefix, kExprRefCastNull, kWasmExact, $sig_v_v, // decoder: ref null exact v (upcast), typer: ref v2
// exploit implicit type refinement w/ inconsistent types from decoder
kExprBrOnNonNull, 0, // typer: (ref exact v) & (ref v2) = bot on branch taken, runtime: branch taken
kExprUnreachable,
kExprEnd,
This is a list of WebAssembly instructions as V8 names them internally. The comments show what the decoder and the typer each believe at that point. The typer is the part that tracks types as the program runs through the analyser. Line by line:
kExprBlock, kWasmVoid,opens a block of code that produces no value. A block is a labelled section, like a paragraph with a heading you can jump to.kExprRefFunc, $imp,is theref.funcinstruction on the imported function. The comment notes the decoder saysref exact v(the mistyping) while the typer saysref v.kExprLocalTee, 3,stores the value in local slot 3 while also leaving it on the stack. A local is a named storage slot inside a function, like a drawer in a desk.teemeans "store and keep a copy".kGCPrefix, kExprRefCast, $sig_v_v,performs a cast to the broader type. The comment says the decoder now seesref v(an upcast) and the typer also seesref v.kGCPrefix, kExprRefCast, $sig_v_v2,performs a cast to the narrower type. The comment says both decoder and typer now seeref v2, and the cast succeeds at runtime.kExprDrop,throws away the value on top of the stack. The stack is the working area where instructions leave their results, like a pile of plates. The value is gone from the stack but still sits in local 3.kExprLocalGet, 3,reads the value back from local 3. The comment says the decoder seesref exact vwhile the typer seesref v2.kGCPrefix, kExprRefCastNull, kWasmExact, $sig_v_v,casts to the exact broader type, allowing null. For the decoder this is an upcast, givingref null exact v, while the typer still tracksref v2.kExprBrOnNonNull, 0,branches to the block's end if the value is not null. The comment says the typer computes(ref exact v) & (ref v2) = boton the branch taken, while at runtime the branch is taken.botmeans bottom, the empty type that no value can have, so the typer concludes the branch cannot happen.kExprUnreachable,is an instruction that traps if it is ever executed. It is placed where the analyser believes execution can never arrive.kExprEnd,closes the block.
The sequence works as follows. ref.func $imp is typed by the decoder as ref exact v (the mistyping) while the typer tracks it as ref v. The value is stored in local 3 with local.tee. Two ref.cast operations then bring the decoder and typer to ref v2, and at runtime the cast succeeds. The value is dropped from the stack but remains in local 3.
local.get 3 then reads it back: the decoder sees ref exact v, the typer sees ref v2. A ref.cast null with kWasmExact to $sig_v_v is an upcast for the decoder, giving ref null exact v, while the typer still tracks ref v2.
Step 2: make the branch statically unreachable but dynamically taken
kExprBrOnNonNull calls RefineTypeKnowledge(is_null.object(), is_null.type.AsNonNull(), branch), where is_null.type comes from the decoder's static typing information. In plain words, the branch instruction asks the analyser to narrow down what it knows about the value, using the type the decoder assigned. The typer already tracks the object as ref v2, and since (ref exact v) & (ref v2) = bot, the code after the branch is marked statically unreachable while it is in fact reached dynamically. Both sides of the branch are typed as unreachable, and there is no statically reachability-compliant result of IsNull the operation could be reduced to, other than replacing it with an unconditional trap.
The report notes that exploiting such a reachability analysis bug has been shown to be possible in prior reports via loop reprocessing bypass, and omits the details here. A loop is a section of code that repeats; reprocessing means the analyser goes over that section again, and a bypass is a way to slip past a protection.
Step 3: from type confusion to a caged write and RCE
The attached poc.js exploits the issue to alias two unrelated struct types and then uses the resulting type confusion to trigger an arbitrary caged write within the sandbox. The attached rce.html combines the issue with the wrapper-wasmcpt-uaf v8sbx bypass to gain RCE and print /flag/flag to stdout. /flag/flag is the file path that rce.html prints to stdout.
The crash information in the report states the crash type as Renderer, with the crash state being a crash on an arbitrary caged write attempt from a JIT-compiled Wasm function with poc.js, or RCE with rce.html. The renderer is the Chrome process that handles a page's content. JIT stands for just-in-time compilation: turning code into machine instructions while the program runs, for speed.
Root cause
The mistake is the exactness annotation on ref.func. The decoder types the result as ref exact of the declared function type, but an imported function is allowed to be a subtype of that declared type, and ref.func returns the original reference so that it stays equivalent to the import. The static type is therefore an exact supertype while the runtime object may be an exact subtype, and the two are unrelated in the subtyping hierarchy. The same exactness typing appears in other decoders, including ModuleDecoderImpl::consume_init_expr() and ConstantExpressionInterface::RefFunc().
The existing defences did not stop it because the hardening of WasmGCTypeAnalyzer addresses operations that lead to an unreachable state by trapping or conforming with the statically reachable case, but it relies on the decoder's static typing being consistent with the typer's knowledge. Here the two disagree, and the intersection of ref exact v and ref v2 is bottom, so the analyser concludes the branch target is unreachable while the branch is taken at runtime. The report also points out that Binaryen documents implementing the same exactness typing rule in PR #7600, which it says may indicate a spec issue. Binaryen is a separate compiler toolchain for WebAssembly.
According to the bisect, the bug was introduced by the WebAssembly Custom Descriptors work, on Origin Trials from M141 onwards, specifically in commits 25a0fc85 and dc8cec44, which make ref.func exact. A bisect is a search through the history of code changes to find the exact change that introduced a bug, like halving a list of suspects until one remains.
Impact
With poc.js, the issue aliases two unrelated struct types and triggers an arbitrary caged write within the sandbox from a JIT-compiled Wasm function. With rce.html, combined with the wrapper-wasmcpt-uaf v8sbx bypass, it yields RCE and reads /flag/flag. The report describes the feature as exposed in the wild by default through Origin Trials from M141, at Beta and about to reach (Early) Stable, on all operating systems. The reporter characterises the underlying problem as potentially specification-level, since no public specification appears to document how ref.func should be typed with custom descriptors, and other implementations may share it.
Fix
The report does not describe a fix. The reporter's position is that ref.func must not be typed as an exact type, at least for imported functions, because its actual type may be a subtype. The report also raises the possibility that the correct behaviour needs to be settled at the specification level, given the absence of a public specification and the indication that Binaryen implements the same rule.
Variants to test
- Other reference-producing operations. The report names
ModuleDecoderImpl::consume_init_expr()andConstantExpressionInterface::RefFunc()as also typingref.funcas exact. Test constant expressions and global initialisers that produce function references through imports, and check whether aref.castchain can move an exact supertype to an unrelated subtype. A positive result is a cast succeeding between types that are unrelated in the subtyping hierarchy. - Imported subtypes across modules. Build a pair of modules where one exports a function of a subtype and the other imports it at the supertype, then use
ref.funcon the import. A positive result is the imported reference being statically typed as exact at the supertype. - Reachability refinement operations. Any operation that refines type knowledge from decoder-supplied types, such as
br_on_non_null, is a candidate for the same bottom-intersection trick. A positive result is a branch that the analyser marks unreachable but that is taken at runtime. - Other engines and toolchains. Since Binaryen documents the same exactness rule in PR #7600, test engines and toolchains that implement custom descriptors for the same
ref.functyping. A positive result is the same mismatch between the declared exact type and the runtime exact subtype of an imported function. - Loop reprocessing. The report refers to prior work using loop reprocessing to bypass reachability mitigations. Re-test the hardened analyser with loops around the refined branch to see whether the unreachable marking can be carried into code that executes.
Glossary
- V8: the JavaScript and WebAssembly engine inside Google Chrome that reads and runs web code.
- WebAssembly (Wasm): a compact binary format for running programs written in other languages inside a browser at near-native speed.
- Module: a self-contained WebAssembly program bundle with its own functions, data, imports and exports.
- Instance: a module that has been loaded and given its imports, ready to run.
- Custom Descriptors: a proposed WebAssembly feature that adds exactness to types.
- Exactness / exact type: a label saying a value is exactly a given type, not a more specific subtype of it.
- Subtype: a narrower type that fits wherever a broader type is expected, like dog within animal.
- Supertype: a broader type that a subtype fits into.
- Heap type: a type describing something stored in memory, such as a function or a struct.
- Struct: a bundle of named fields, like a record in a database.
- Indexed type: a type identified by a number in the module's type table.
- Reference: a value that points at something, such as a function, rather than containing the data itself.
ref.func: the WebAssembly instruction that produces a reference to a function.- Signature: the declared type of a function, describing its parameters and results.
- Decoder: the part of V8 that reads a WebAssembly module's binary instructions and checks them.
- Static type: a type label assigned before the program runs.
- Typer: the part of the analyser that tracks types as it processes code.
- Cast: an instruction that checks at runtime whether a value really has a given type, and traps if not.
- Upcast: a cast towards a broader type, always safe.
- Trap: WebAssembly's way of aborting execution immediately when something illegal happens.
- Import: something a module asks for from the outside.
- Export: something a module offers to the outside.
- Constant expression: a small expression evaluated at load time, for example to set up a global.
- Global: a named storage slot shared across a module.
- Local: a named storage slot inside a function.
- Stack: the working area where instructions leave their results.
WasmGCTypeAnalyzer: the V8 component that analyses WebAssembly GC code to work out which parts can be reached at runtime.- Reachability: whether a piece of code can actually be executed at runtime.
- Bottom (
bot): the empty type that no value can have. - Type confusion: a bug where the engine treats a value as a type it is not.
- Alias: making two things that should be separate be treated as the same.
- Sandbox: a boundary Chrome builds around the part of itself that processes web content.
- Caged write: a write to memory inside the sandbox, at an address the attacker chooses.
- RCE (remote code execution): making the target computer run code the attacker supplied.
- v8sbx: the name of the sandbox around V8.
- Bypass: a way around a protection.
- UAF (use-after-free): a bug where memory is used after it has been released.
wrapper-wasmcpt-uaf: the name given to a separate, previously known weakness used together with this one.- stdout: the standard output stream, where a program prints its normal text output.
- Renderer: the Chrome process that handles a page's content.
- JIT (just-in-time compilation): turning code into machine instructions while the program runs, for speed.
- Origin Trial: a way for Chrome to switch a new feature on for a portion of real websites before it becomes permanent.
- d8: V8's own small command-line program for running JavaScript and WebAssembly.
- Command-line flag: a switch you add when starting a program to change its behaviour.
- Binaryen: a separate compiler toolchain for WebAssembly.
- Bisect: a search through the history of code changes to find the exact change that introduced a bug.
- Loop: a section of code that repeats.
- Reprocessing: the analyser going over a section of code again.
- Link error: the WebAssembly equivalent of a broken reference at load time.
- Type canonicaliser: the component that gives every type a single shared identity.
- GC (garbage collection): automatic memory cleanup.