Skip to content
Memory corruption Advisory Advanced CVE-2024-3914

Use after free in V8 (CVE-2024-3914)

A detached ArrayBuffer in V8 could still be treated as attached by Blink because Blink caches a DOMArrayBuffer that does not track V8-side detachment. An attacker could then transfer the buffer via structuredClone, causing a reallocation and a use-after-free when the stale ArrayBuffer is used.

Seunghyun Lee Follow

Originally disclosed on Chrome VRP

  • Fix shipped in 42 days

Attachments are the report pack. Description of the ArrayBuffer bug from attached paper:

blink::DOMArrayBuffer, the Blink-side data structure that represents v8::JSArrayBuffer, is shaped as the following:

C++
class CORE_EXPORT DOMArrayBuffer : public DOMArrayBufferBase {
  // ...
}

class CORE_EXPORT DOMArrayBufferBase : public ScriptWrappable {
  // ...
  ArrayBufferContents contents_;
  bool is_detached_ = false;
};

class CORE_EXPORT ArrayBufferContents {
  // ...
  std::shared_ptr<v8::BackingStore> backing_store_;
};

Note that blink::DOMArrayBuffer only holds a std::shared_ptr to v8::BackingStore but not the JSArrayBuffer itself - the object is fundamentally oblivious of any changes made from V8, including ArrayBuffer being detached. This results in a detached ArrayBuffer to reference its now-detached backing store for all Blink-side APIs that operate on ArrayBuffers, assuming that the detachment is not done from Blink but from V8.

ArrayBuffer.prototype.transfer() is one example of such, eventually reaching JSArrayBuffer::Detach():

C++
Maybe<bool> JSArrayBuffer::Detach(Handle<JSArrayBuffer> buffer,
                                  bool force_for_wasm_memory,
                                  Handle<Object> maybe_key) {
  Isolate* const isolate = buffer->GetIsolate();
  // ...
  buffer->DetachInternal(force_for_wasm_memory, isolate);
  return Just(true);
}

void JSArrayBuffer::DetachInternal(bool force_for_wasm_memory,
                                   Isolate* isolate) {
  ArrayBufferExtension* extension = this->extension();

  if (extension) {
    DisallowGarbageCollection disallow_gc;
    isolate->heap()->DetachArrayBufferExtension(*this, extension);
    std::shared_ptr<BackingStore> backing_store = RemoveExtension();
    CHECK_IMPLIES(force_for_wasm_memory, backing_store->is_wasm_memory());
  }

  if (Protectors::IsArrayBufferDetachingIntact(isolate)) {
    Protectors::InvalidateArrayBufferDetaching(isolate);
  }

  DCHECK(!is_shared());
  set_backing_store(isolate, EmptyBackingStoreBuffer());
  set_byte_length(0);
  set_was_detached(true);    // [!] All the operations are done on JSArrayBuffer, not DOMArrayBuffer - we're within V8, not Blink
}

When a V8 object is passed on to Blink, it is converted to a Blink object. Below is the code for ArrayBuffers.

C++
DOMArrayBuffer* ToDOMArrayBuffer(v8::Isolate* isolate,
                                 v8::Local<v8::Value> value) {
  if (UNLIKELY(!value->IsArrayBuffer()))
    return nullptr;

  v8::Local<v8::ArrayBuffer> v8_array_buffer = value.As<v8::ArrayBuffer>();
  if (ScriptWrappable* array_buffer = ToScriptWrappable(v8_array_buffer)) {     // [!] cached
    return array_buffer->ToImpl<DOMArrayBuffer>();
  }

  // Transfer the ownership of the allocated memory to a DOMArrayBuffer without
  // copying.
  ArrayBufferContents contents(v8_array_buffer->GetBackingStore());
  DOMArrayBuffer* array_buffer = DOMArrayBuffer::Create(contents);
  v8::Local<v8::Object> wrapper = array_buffer->AssociateWithWrapper(
      isolate, array_buffer->GetWrapperTypeInfo(), v8_array_buffer);
  DCHECK(wrapper == v8_array_buffer);
  return array_buffer;
}

inline ScriptWrappable* ToScriptWrappable(v8::Local<v8::Object> wrapper) {
  return GetInternalField<ScriptWrappable, kV8DOMWrapperObjectIndex>(wrapper);
}

Note how once an ArrayBuffer is converted to a Blink object, it is cached in an internal field which is reused later on. Thus, with the following sequence of execution we can make a detached ArrayBuffer be considered non-detached from Blink side:

  1. Create an ArrayBuffer ab
  2. Convert it once to Blink object by calling any Web APIs, e.g. new Blob([ab])
    • This is the first conversion from V8 to Blink - a new DOMArrayBuffer is created and cached
  3. Detach the ArrayBuffer from V8, e.g. ab.transfer()
  4. Use it again as a Blink object through any Web APIs, e.g. new Blob([ab]) again
    • This is the second conversion - the cached DOMArrayBuffer is reused, which is oblivious of the detachment

As blink::DOMArrayBuffer owns blink::ArrayBufferContents which in turn holds a shared pointer to the underlying BackingStore, it defers the underlying buffer's deallocation:

C++
BackingStore::~BackingStore() {
  GlobalBackingStoreRegistry::Unregister(this);
  // ...
  // JSArrayBuffer backing store. Deallocate through the embedder's allocator.
  auto allocator = get_v8_api_array_buffer_allocator();
  TRACE_BS("BS:free   bs=%p mem=%p (length=%zu, capacity=%zu)\n", this,
           buffer_start_, byte_length(), byte_capacity_);
  allocator->Free(buffer_start_, byte_length_);
}

This can still be manipulated into an exploitable state by using any APIs that transfer ArrayBuffers - notably, structuredClone(). Zero-copy transferring a DOMArrayBuffer via structuredClone() which has been detached directly from V8 results in yet another non-detached ArrayBuffer referencing the same underlying backing store buffer (ArrayBufferContents to be exact):

C++
SerializedScriptValue::TransferArrayBufferContents(
    v8::Isolate* isolate,
    const ArrayBufferArray& array_buffers,
    ExceptionState& exception_state) {
  ArrayBufferContentsArray contents;

  if (!array_buffers.size())
    return ArrayBufferContentsArray();

  for (auto* it = array_buffers.begin(); it != array_buffers.end(); ++it) {
    DOMArrayBufferBase* array_buffer = *it;
    if (array_buffer->IsDetached()) {             // [!] not detached, since we're checking DOMArrayBuffer
      // ...
    }
  }

  contents.Grow(array_buffers.size());
  // ...
  for (auto* it = array_buffers.begin(); it != array_buffers.end(); ++it) {
    DOMArrayBufferBase* array_buffer_base = *it;
    if (visited.Contains(array_buffer_base))
      continue;
    visited.insert(array_buffer_base);

    wtf_size_t index =
        static_cast<wtf_size_t>(std::distance(array_buffers.begin(), it));
    if (array_buffer_base->IsShared()) {
      // ...
    } else {
      DOMArrayBuffer* array_buffer =
          static_cast<DOMArrayBuffer*>(array_buffer_base);

      if (!array_buffer->IsDetachable(isolate)) { // [!] detachable, since this is a normal (DOM)ArrayBuffer
        // ...
      } else if (array_buffer->IsDetached()) {    // [!] not detached (again), since we're checking DOMArrayBuffer
        exception_state.ThrowDOMException(DOMExceptionCode::kDataCloneError,
                                          "ArrayBuffer at index " +
                                              String::Number(index) +
                                              " could not be transferred.");
        return ArrayBufferContentsArray();
      } else if (!array_buffer->Transfer(isolate, contents.at(index),
                                         exception_state)) {           // [!] successfully transferred
        return ArrayBufferContentsArray();
      }
    }
  }
  return contents;
}

Now, transferring one of the ArrayBuffer into a different non-zero size results in reallocation of the underlying backing store buffer:

C++
Tagged<Object> ArrayBufferTransfer(Isolate* isolate,
                                   Handle<JSArrayBuffer> array_buffer,
                                   Handle<Object> new_length,
                                   PreserveResizability preserve_resizability,
                                   const char* method_name) {
  // ...
  // 5. If IsDetachedBuffer(arrayBuffer) is true, throw a TypeError exception.
  if (array_buffer->was_detached()) {              // [!] pass, both of the duped ArrayBuffers are not detached
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kDetachedOperation,
                              isolate->factory()->NewStringFromAsciiChecked(
                                  method_name)));
  }
  // ...
  // Case 1: We don't need a BackingStore.
  if (new_byte_length == 0) {
    // 15. Perform ! DetachArrayBuffer(arrayBuffer).
    JSArrayBuffer::Detach(array_buffer).Check();   // [!] shared_ptr retained on the other ArrayBuffer preventing UAF

    // 9. Let newBuffer be ? AllocateArrayBuffer(%ArrayBuffer%, newByteLength,
    //    newMaxByteLength).
    //
    // Nothing to do for steps 10-14.
    //
    // 16. Return newBuffer.
    return *isolate->factory()
                ->NewJSArrayBufferAndBackingStore(
                    0, new_max_byte_length, InitializedFlag::kUninitialized,
                    resizable)
                .ToHandleChecked();
  }

  // Case 2: We can reuse the same BackingStore.
  auto from_backing_store = array_buffer->GetBackingStore();
  if (from_backing_store && !from_backing_store->is_resizable_by_js() &&
      resizable == ResizableFlag::kNotResizable &&
      (new_byte_length == array_buffer->GetByteLength() ||
       from_backing_store->CanReallocate())) {
    // Reallocate covers steps 10-14.
    if (new_byte_length != array_buffer->GetByteLength() &&
        !from_backing_store->Reallocate(isolate, new_byte_length)) {    // [!] reallocated, UAF on the other ArrayBuffer
      THROW_NEW_ERROR_RETURN_FAILURE(
          isolate,
          NewRangeError(MessageTemplate::kArrayBufferAllocationFailed));
    }

    // 15. Perform ! DetachArrayBuffer(arrayBuffer).
    JSArrayBuffer::Detach(array_buffer).Check();

    // 9. Let newBuffer be ? AllocateArrayBuffer(%ArrayBuffer%, newByteLength,
    //    newMaxByteLength).
    // 16. Return newBuffer.
    return *isolate->factory()->NewJSArrayBuffer(std::move(from_backing_store));
  }

  // ...
}

bool BackingStore::Reallocate(Isolate* isolate, size_t new_byte_length) {
  CHECK(CanReallocate());
  auto allocator = get_v8_api_array_buffer_allocator();
  CHECK_EQ(isolate->array_buffer_allocator(), allocator);
  CHECK_EQ(byte_length_, byte_capacity_);
  void* new_start =
      allocator->Reallocate(buffer_start_, byte_length_, new_byte_length);    // [!] reallocate buffer in place
  if (!new_start) return false;
  buffer_start_ = new_start;
  byte_capacity_ = new_byte_length;
  byte_length_ = new_byte_length;
  max_byte_length_ = new_byte_length;
  return true;
}

Using the other ArrayBuffer now results in a use-after-free as its byte_length, backing_store, was_detached, etc. still retains its old value:

C++
class JSArrayBuffer
    : public TorqueGeneratedJSArrayBuffer<JSArrayBuffer,
                                          JSObjectWithEmbedderSlots> {
  // ...
  // [byte_length]: length in bytes
  DECL_PRIMITIVE_ACCESSORS(byte_length, size_t)

  // [max_byte_length]: maximum length in bytes
  DECL_PRIMITIVE_ACCESSORS(max_byte_length, size_t)

  // [backing_store]: backing memory for this array
  // It should not be assumed that this will be nullptr for empty ArrayBuffers.
  DECL_GETTER(backing_store, void*)
  inline void set_backing_store(Isolate* isolate, void* value);
  // ...
  // [was_detached]: true => the buffer was previously detached.
  DECL_BOOLEAN_ACCESSORS(was_detached)
}

The original report as published on the Chromium issue tracker, by Seunghyun Lee (@0x10n) of KAIST Hacking Lab, via Pwn2Own 2024. Images and videos are our own copies; raw HTML is shown as text. View it on Chromium issue tracker.

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 Blink DOMArrayBuffer caches a shared pointer to the backing store but does not observe detachment performed directly in V8, so subsequent Blink operations treat the buffer as still valid.

Impact

An attacker could trigger a use-after-free in the browser, potentially leading to memory corruption or code execution, though the text does not demonstrate a full exploit.

What the attacker needed

Ability to run JavaScript in the browser

How it was found

  1. Create an ArrayBuffer.
  2. Convert it to a Blink object by calling a Web API such as new Blob([ab]), which caches a DOMArrayBuffer.
  3. Detach the ArrayBuffer from V8, for example with ab.transfer().
  4. Use the ArrayBuffer again through a Web API such as new Blob([ab]), which reuses the cached DOMArrayBuffer that is unaware of the detachment.
  5. Transfer the buffer via structuredClone to cause a reallocation of the backing store.
  6. Use the other ArrayBuffer, which now references freed memory, resulting in a use-after-free.

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.

An ArrayBuffer is a block of memory used to hold binary data in JavaScript. The browser has two views of this memory: one in the JavaScript engine (V8) and one in the rendering engine (Blink). The bug is that when the JavaScript engine marks the buffer as detached (meaning the memory is no longer valid), the rendering engine's cached copy does not notice, so it keeps using the old memory after it has been freed, which can lead to crashes or 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.

More by Seunghyun Lee

View all

1 more disclosed report, best first.

More from Google Chrome

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

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