Skip to content
XSS Write-up Advanced

Hacking the Apple Webcam (again)

A chain of flaws in iCloud Sharing (ShareBear) and Safari let a website plant a file the victim agreed to open, then silently swap its contents and launch it, bypassing Gatekeeper to open a webarchive that renders attacker JavaScript in any origin. This gave universal cross-site scripting, so the attacker could read cookies and act as the victim on any site, including turning on the camera.

Ryan Pickren Follow

Published on ryanpickren.com

Bounty$100,500 View original

Gaining unauthorized camera access via Safari UXSS: the story of how a shared iCloud document can hack every website you've ever visited.

Ryan Pickren, on ryanpickren.com

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

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

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

Context

This is a follow-up to an earlier Safari camera-hacking project. Apple had closed the previous 0day chain (CVE-2020-3852 + CVE-2020-3864 + CVE-2020-3865) by tightening multimedia permission handling: camera access is now only granted when the protocol is https: and the domain matches the saved settings. Malformed URIs no longer suffice, so the attacker has to genuinely inject code into the target origin, which means finding a Universal Cross-Site Scripting (UXSS) bug.

The researcher quotes Google Project Zero's definition of UXSS: it exploits vulnerabilities in the browser itself to achieve an XSS condition, so the attacker gets access not to a single site's session but potentially to any website. The Project Zero paper calls UXSS among the most significant threats for browser users and almost as valuable as a remote code execution exploit with a sandbox escape.

The difference from the earlier project matters: that bug targeted stored multimedia permissions and did not allow code execution on arbitrary origins. It let the attacker leverage Skype's camera permission but not steal Skype's cookies. This time the goal is arbitrary-origin code execution.

The target is Safari 15 (beta at the time of writing) on macOS, and the feature under scrutiny is Safari's handling of webarchive files, which Safari creates as an alternative to HTML when a user saves a website locally. A webarchive specifies the web origin in which its content should be rendered. As the Metasploit authors pointed out in 2013, an attacker who can modify such a file can achieve UXSS by design. Apple's position at the time was that the scenario was not realistic because webarchives must be downloaded and manually opened by the client.

Setup

The research targeted Safari v15 beta; one bonus bug was found on the latest public release, Safari v14.1.1. No accounts or special roles are described. The tools are Safari itself, the macOS Launch Services database, and the lsregister command line utility. The attack requires the victim to click open on a popup from the attacker's website once.

The general shape of a webarchive attack is two steps:

  1. Forcefully download an evil webarchive file.
  2. Forcefully open it.

Historically, step 1 was easy: before Safari 13 no warning was shown before a website downloaded arbitrary files. With Safari 13 and later, users are prompted before each download. Step 2 was historically done by navigating to the file:// URI scheme, for example through error pages living on file:// ("Errorjacking") or by setting the <base> tag to file://. By 2022, auto-downloads are prevented by default and macOS Gatekeeper treats webarchive files as malicious applications, so users cannot even manually open foreign webarchives.

Finding it

The researcher focused on custom URI schemes, the unofficial and mostly undocumented schemes used by third-party iOS and macOS apps for deep linking. Several first-party system apps also register schemes, such as Apple Help Viewer (help://), FaceTime (facetime-audio://) and Apple Feedback (applefeedback://). Modern Safari warns before launching secondary applications, except for a hardcoded set of exceptions identified in a Black Hat presentation.

All of these schemes are registered with Launch Services, so they can be listed with:

Bash
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump | grep -B6 bindings:.*: | grep -B6 apple-internal

Digging through internal Apple schemes and cross-referencing them with the ones Safari trusts produced one interesting candidate: icloud-sharing:. It is registered by an iCloud Sharing application called ShareBear. The researcher found no public documentation or research about the scheme and started probing it directly.

Exploitation

Step 1: Launching ShareBear from a web page

iCloud File Sharing can generate a public Share Link, which looks like this:

Text
https://www.icloud.com/iclouddrive/01fooriERbarZSTfikqmwQAem

Replacing https with icloud-sharing is enough for Safari to automatically open ShareBear with the file as a parameter:

HTML
<script>
location.href = 'icloud-sharing://www.icloud.com/iclouddrive/01fooriERbarZSTfikqmwQAem'
</script>

This is saved as evil.html. Simply replacing https with icloud-sharing is enough for Safari to automatically open ShareBear with the file as a parameter.

Step 2: The ShareBear open prompt and the polymorphic file

When the user has not opened the file before, ShareBear shows a prompt with the default value "Open". The user expects to open the image example.png if they agree. In reality they agree to more: once the user clicks Open, the file is downloaded to /Users/<user>/Library/Mobile Documents/com~apple~CloudDocs and automatically opened via Launch Services. The user never sees the prompt again, and from that point ShareBear, and therefore any website in Safari, can automatically launch the file.

The problematic part is that the file can be changed by anybody with write access to it. The owner can change the entire byte content and the file extension after the user agrees. ShareBear then downloads and updates the file on the victim's machine without any user interaction or notification. In effect the victim has granted permission to plant a polymorphic file and to launch it remotely at any moment.

Apple fixed this behaviour in macOS Monterey 12.0.1 as a result of the report, without a CVE, because it is more of a design flaw than a bug.

Step 3: The iframe sandbox escape (bonus bug)

While fuzzing the icloud-sharing:// scheme, the researcher found that ShareBear checks the URL path for /iclouddrive/* before performing the behaviour above. If the path is /photos/*, ShareBear tells Safari to open a new tab pointing to the iCloud web app but does not verify that the domain name is actually the iCloud web app. Normally the user sees https://photos.icloud.com, but because the domain is never validated, ShareBear can be tricked into opening a new tab to any website.

That matters where a website is not allowed to call window.open itself, for example with a popup blocker enabled or inside a sandboxed iframe. New windows opened from a sandboxed iframe should inherit the iframe's restrictions, otherwise escaping the sandbox would be as trivial as opening a popup. This bug makes Safari open a fresh tab without any sandbox restrictions:

HTML
<html>
<head>
<meta http-equiv="refresh" content="0;URL='icloud-sharing://example.com/photos/foo'" />
</head>
</html>

So the missing domain check gives an easy popup-blocker bypass and an iframe sandbox escape. It was fixed in Safari 15.2 without a CVE. A live demo was published on BugPoC with PoC ID bp-S4HH6YcO, and it only works with Safari below 15.2 on macOS before Monterey 12.1.

Step 4: Quarantine and Gatekeeper

At this point the attacker can prompt the user to open a shared PNG, and after agreement can launch the file at any future point, even after changing its content and extension. The next idea is to swap the content of puppy.png for a webarchive, rename it evil.webarchive, and launch it with the same icloud-sharing:// URL. Gatekeeper blocks that: ShareBear correctly gives downloaded files the com.apple.quarantine attribute, and according to Apple, Gatekeeper prevents quarantined executable files and similar files (shell scripts, web archives and so on) from opening or executing.

Two limitations follow:

  1. The attacker cannot run their own apps.
  2. The attacker cannot directly open webarchive files.

Launching existing, approved apps is trivial, though, by using a fileloc that points to a local app. This is sometimes called Arbitrary File Execution and is often misunderstood because it looks scary:

XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>URL</key>
<string>file:///System/Applications/Calculator.app</string>
</dict>
</plist>

This fileloc points to macOS Calculator and is launched with the icloud-sharing:// scheme. Launching an already-approved app has little impact, so the focus stays on opening webarchives.

Step 5: The Windows URL File shortcut

The fileloc technique resembles an old symlink attack: it uses a shortcut to trick software into opening something it does not expect. Shortcuts come in many forms: Unix symlinks, macOS aliases, Windows linkfiles, Safari weblocs, Edge bookmarks and so on. The idea was to use a shortcut to launch Safari, an existing approved application, and have Safari open a different file. Gatekeeper has no problem with launching Safari; it objects to opening files ending in .webarchive.

The shortcut filetype that worked is the ancient Windows URL File:

Text
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
[InternetShortcut]
URL=file:///path/to/webarchive
IDList=

Launching evil.url opens Safari and instructs it to load the webarchive without asking Gatekeeper for permission (CVE-2021-30861). The remaining problem is that the full path to the webarchive must be known. If the webarchive is downloaded via ShareBear it lives in /Users/<user>/Library/Mobile Documents/com~apple~CloudDocs, which includes the victim's username and is not scalable.

The workaround is to mount the webarchive into the known /Volumes/ directory using a DMG file, launched with the icloud-sharing:// scheme. Now the location is known, so the following evil.url works every time:

Text
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
[InternetShortcut]
URL=file:///Volumes/folder/evil.webarchive
IDList=

Launching evil.url with the icloud-sharing:// scheme opens evil.webarchive, and JavaScript executes anywhere the attacker wants. The screen recording injects alert(origin) in https://google.com.

Step 6: The full chain

Using ShareBear to download and open a webarchive has three steps:

  1. Trick the victim into giving permission to plant the polymorphic file.
  2. Turn puppies.png into evil.dmg and launch it.
  3. Turn evil.dmg into evil.url and launch it.

Turning one file into three different payloads requires server-side coordination. A less fun alternative is to have the victim agree to open a shared folder that already contains all the files. In the recorded demonstration the victim agrees to view a folder containing PNG images plus two hidden files, .evil.dmg and .evil.url. The website uses the icloud-sharing:// scheme to launch both hidden files, bypassing Gatekeeper and opening a webarchive. No additional prompts are shown after the victim agrees to view the shared folder. The example webarchive injects code into https://www.icloud.com to exfiltrate the victim's iOS camera roll. The same technique could inject JavaScript to turn on the webcam when hijacking a trusted video chat site such as https://zoom.us or https://facetime.apple.com.

Bonus: local file theft through Scripting Additions

One limitation remained: the UXSS chain cannot steal files that exist only on the victim's hard drive. UXSS can indirectly steal files by injecting into https://dropbox.com or https://drive.google.com, but local files are out of reach. Inspired by the Black Hat presentation, the researcher looked for system applications that run JavaScript in a more privileged context than Safari.

macOS Script Editor recognises an obscure filetype called Scripting Additions (.osax). These bundles contain a nested XML-based file called a Dictionary Document (.sdef), used to display developer-defined terms for an AppleScript application. These XML files are allowed to contain HTML, and the HTML renderer has a JavaScript engine that does not enforce the same-origin policy. This was fixed in macOS Big Sur 11.6.2 as CVE-2021-30975. Stealing /etc/passwd becomes easy:

XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dictionary SYSTEM "">
<dictionary>
<suite name="" code="">
<command name="" code="" description="">
</command>
<documentation>
<html>
<![CDATA[
<script>
fetch('file:///etc/passwd').then(x=>{x.text().then(y=>{document.write(y);})})
</script>
]]>
</html>
</documentation>
</suite>
</dictionary>

Gatekeeper does not mind opening Scripting Addition files, so evil.sdef is packaged in evil.osax and sent to the victim via ShareBear, and the icloud-sharing:// URI launches it in Script Editor. In addition to UXSS, the hack can circumvent sandbox restrictions and steal local files.

Root cause

The chain combines several design decisions. Safari launches the icloud-sharing:// scheme automatically. and it treats a one-time user approval as permanent permission to download and launch a file whose content and extension can change later. It also fails to validate the domain for /photos/* paths, which lets any site be opened in a fresh tab outside a sandboxed iframe. Gatekeeper's quarantine protection is bypassed because the shortcut filetype (.url) makes Safari, an approved application, open the quarantined webarchive indirectly. The webarchive format itself specifies the origin in which content is rendered, so once it opens, code runs in that origin. The .sdef renderer runs JavaScript without enforcing the same-origin policy, which allows reading local files.

Impact

With the victim's click on the popup, the attacker gains full access to every website the victim has visited, not just multimedia permission hijacking. That includes the ability to turn on the camera and to attack accounts such as iCloud, PayPal, Facebook and Gmail. The chain requires the victim to click "open" on a popup from the attacker's website. The local file theft variant additionally requires the victim to open the .osax through ShareBear. The researcher reported the chain to Apple and received $100,500 as a bounty. The research produced four 0day bugs (CVE-2021-30861, CVE-2021-30975 and two without CVEs), two of which were used in the camera hack.

Fix

Apple fixed the issues in several places. ShareBear now reveals files instead of launching them (macOS Monterey 12.0.1, no CVE). WebKit no longer opens quarantined files (Safari 15, CVE-2021-30861). The /photos/* domain validation issue was fixed in Safari 15.2 without a CVE. The .sdef JavaScript same-origin policy issue was fixed in macOS Big Sur 11.6.2 as CVE-2021-30975. The bugs were submitted in mid July 2021 and patched in early 2022.

Variants to test

  • Enumerate Launch Services schemes with the lsregister command above and cross-reference them with the schemes Safari launches without a prompt. A positive result is a scheme that opens an application from a web page with no user prompt.
  • For each such scheme, test whether it accepts a URL parameter that points to a remote resource. A positive result is the application downloading and opening the resource.
  • Test whether the application re-downloads and re-opens a previously approved file after its content and extension change. A positive result is a silent update and launch with no new prompt.
  • Test path-based behaviour such as /photos/* with an arbitrary domain. A positive result is a new tab opening to the attacker's domain, including from inside a sandboxed iframe or with a popup blocker enabled.
  • Try shortcut filetypes (.url, .webloc, aliases) that point to a quarantined file and launch them through an approved application. A positive result is the quarantined file opening without a Gatekeeper prompt.
  • Try mounting payloads into a predictable path such as /Volumes/ with a DMG so the shortcut can use a fixed path. A positive result is the payload opening from the known location.
  • Look for document or bundle formats that embed HTML or JavaScript and are rendered by a privileged application, such as .sdef in Script Editor. A positive result is JavaScript executing without same-origin policy restrictions, for example a successful fetch('file:///etc/passwd').

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 Safari, Apple's web browser, run his own code inside any website the victim had ever visited. Once his code runs inside a site like your bank, your email or a video chat service, the browser treats it as part of that site. That means the attacker can do anything you could do on that site while logged in: read your messages, move money, or switch on your webcam.

The trick starts with a small popup. You visit the attacker's website, and it asks whether you want to open a shared picture from iCloud, Apple's online storage service. If you click Open once, the attacker can later replace that harmless picture with a file of his choosing, and ShareBear will update it on your Mac without any user interaction or notification. From there he slips past Gatekeeper, the macOS feature that normally blocks dangerous downloaded files, and gets his code running inside a real website.

The researcher reported the problems to Apple and was paid $100,500. The work produced four previously unknown bugs, two of which were used in the camera attack. This article walks through the whole story from the beginning, explaining each idea as it comes up.

Background: why the old trick stopped working

This project is a sequel. In an earlier piece of research the same researcher had turned on an Apple webcam without permission by abusing how Safari stored camera permissions. Apple closed that hole with three fixes (CVE-2020-3852, CVE-2020-3864 and CVE-2020-3865).

After those fixes, camera access is only granted when two conditions hold: the address uses https: (the encrypted version of the web) and the domain matches what you saved earlier. A domain is the part of a web address that identifies the site, like example.com. So simply crafting a strange-looking web address no longer works. The attacker now has to get his own code genuinely running inside the target site. In security language, he needs a Universal Cross-Site Scripting bug.

What cross-site scripting and UXSS mean

Cross-site scripting, usually shortened to XSS, is when an attacker manages to get his JavaScript (the programming language web pages use to be interactive) to run inside someone else's website. The browser cannot tell the difference between the site's own code and the injected code, so the injected code inherits the site's powers.

Universal XSS, or UXSS, is the same idea but the weakness is in the browser itself rather than in one website. The researcher quotes Google Project Zero's paper, "Analysis of UXSS exploits and mitigations in Chromium":

"UXSS attacks exploit vulnerabilities in the browser itself [...] to achieve an XSS condition. As a result, the attacker does not just get access to user session on a single website, but may get access to any [website]."

A useful comparison: ordinary XSS is like finding a spare key to one house. UXSS is like finding a master key that opens every house on the street, because the flaw is in the lock manufacturer's design, not in any single door.

The same paper calls UXSS "among the most significant threats for users of any browser" and "almost as valuable as a Remote Code Execution (RCE) exploit with the sandbox escape." Remote code execution means running your own programs on someone else's machine; a sandbox is the restricted box a program is kept in so it cannot touch the rest of the system. Escaping the sandbox means getting out of that box.

Why does that matter in practice? Imagine a website that can jump into https://zoom.com to switch on the camera, hop into https://paypal.com to send money, and hijack https://gmail.com to read email. That is the scale of what a UXSS bug offers.

How this differs from the earlier camera hack

The earlier bug targeted stored multimedia permissions. It let the attacker use a camera permission that had already been granted to an app such as Skype, but it did not let him run code on other websites. In other words, it could borrow Skype's camera permission but could not steal Skype's cookies. A cookie is a small piece of data a website stores in your browser to remember that you are logged in; stealing one can let an attacker act as you. This time the goal is bigger: run code on any origin.

An origin is the combination of protocol, domain and port that the browser uses to decide what may talk to what. Two pages share an origin only if all three match. Running code "on an origin" means the browser believes the code belongs to that site.

The file format at the centre of it

The target is Safari 15 (still in beta when the research was done) on macOS, Apple's desktop operating system. The feature under the microscope is Safari's handling of webarchive files.

A webarchive is a file Safari creates when you save a web page to your disk, as an alternative to saving it as plain HTML. The surprising part is that a webarchive records the web origin in which its content should be displayed. That is handy for rebuilding a saved page faithfully, but it also means that whoever controls the file controls the origin the content will run in.

As the Metasploit authors pointed out back in 2013, an attacker who can modify such a file can achieve UXSS by design. Metasploit is a well-known collection of hacking tools. Apple's view at the time was that the scenario was not realistic, because "the webarchives must be downloaded and manually opened by the client." In plain terms: the user would have to go out of their way to open the file, so Apple did not consider it a serious risk.

The attack plan

The researcher read many write-ups about Safari UXSS bugs that had already been fixed, and decided to concentrate on webarchive files. The general shape of a webarchive attack has two steps:

  1. Forcefully download an evil webarchive file.
  2. Forcefully open it.

Historically, step 1 was easy. Before Safari 13, no warning was shown before a website downloaded arbitrary files, so planting the webarchive was simple. From Safari 13 onwards, users are asked for permission before each download.

Step 2 used to be done by navigating to the file:// address scheme. A URI scheme is the first part of an address, the bit before the colon, that tells the system what kind of thing the address points to: https for a secure web page, file for a file on your own disk, mailto for an email address. Back when Safari's error pages lived on file://, hackers worked out how to trigger an error page on purpose and then alter its path, a trick cheerfully named "Errorjacking." Another old approach was to set the HTML <base> tag to file://. The <base> tag tells the browser what address relative links on a page should be resolved against.

By 2022 things are much harder. Auto-downloads are blocked by default, and macOS Gatekeeper treats webarchive files as malicious applications. Gatekeeper is the macOS feature that checks downloaded software before it is allowed to run. The result is that users cannot even manually open a webarchive that came from elsewhere.

Apple appears to have changed its 2013 position on how dangerous these files can be. Still, webarchives are too tempting to abandon, so the researcher set out to see whether the old attack could still work on current Safari and macOS.

Exploring custom URI schemes

The earlier camera project had focused on official URI schemes registered with IANA, the organisation that keeps the master list of such names. This time the researcher looked at the other world: custom URL schemes. These are unofficial and mostly undocumented names that third-party apps on iOS and macOS register so that other apps can open them, a technique called deep linking. There is a whole community around discovering these schemes and using them across apps, both for fun and for security research.

Several of Apple's own system apps register schemes too, for example Apple Help Viewer (help://), FaceTime (facetime-audio://) and Apple Feedback (applefeedback://). Abusing these from a web page in Safari is not new. Past examples range from annoyingly placing phone calls, to helping social engineering (tricking people), to arbitrary file execution.

Modern Safari warns the user before launching another application, unless the scheme is one of a hardcoded set of exceptions identified in a Black Hat presentation. Black Hat is a well-known security conference.

All of these schemes are registered with Launch Services, the macOS component that keeps track of which application opens which kind of file or address. You can list them with this command:

Bash
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump | grep -B6 bindings:.*: | grep -B6 apple-internal

Line by line:

  • The long path at the start points to lsregister, a command line tool that reads the Launch Services database, the system's list of registered applications and the schemes they handle.
  • -dump asks the tool to print the whole database.
  • The vertical bar | takes that output and feeds it to the next command.
  • grep -B6 bindings:.*: searches for lines containing bindings: followed by a colon, and also prints the six lines before each match (-B6). grep is a standard tool for searching text.
  • The second grep -B6 apple-internal keeps only the matches that mention apple-internal, again with six lines of context before them.

The point of the command is to find schemes that Apple's own software registers, so they can be compared with the list of schemes Safari will launch without asking.

Digging through internal Apple schemes and cross-referencing them with the ones Safari trusts turned up one interesting candidate: icloud-sharing:. It is registered by an iCloud Sharing application called ShareBear. The researcher could find no public documentation or research about this scheme, so he started poking at it himself.

The ShareBear application

At this point we have an application that Safari will launch automatically, but we do not yet know how to make it open something useful. That part turned out to be straightforward.

iCloud File Sharing can generate a public Share Link, a web address anyone can use to reach a shared file. These links look something like this:

Text
https://www.icloud.com/iclouddrive/01fooriERbarZSTfikqmwQAem

Line by line: https is the scheme, www.icloud.com is the domain, and the long string after /iclouddrive/ is an identifier for the shared file. It works like a ticket number that points to one specific item.

Simply replacing https with icloud-sharing is enough to make Safari open ShareBear automatically with that file as a parameter. A parameter here is an extra piece of information handed to the application, telling it what to work on.

HTML
<script>
location.href = 'icloud-sharing://www.icloud.com/iclouddrive/01fooriERbarZSTfikqmwQAem'
</script>

Line by line:

  • <script> and </script> mark the start and end of a piece of JavaScript inside a web page.
  • location.href is the browser's current address. Assigning to it tells the browser to go somewhere else.
  • The string in quotes is the address to go to: the same share link as before, but with https swapped for icloud-sharing.

This snippet is saved as a file called evil.html and served from the attacker's website. The important detail is that the scheme is on Safari's trusted list, so no launch prompt appears.

The open prompt and the file that changes

When the user has not opened the file before, ShareBear shows a prompt with the default value "Open." The user reasonably expects that agreeing will open the image example.png. In reality they are agreeing to much more.

Once the user clicks Open, the file is downloaded to /Users/<user>/Library/Mobile Documents/com~apple~CloudDocs and opened automatically through Launch Services. The user never sees that prompt again. From then on, ShareBear, and therefore any website open in Safari, can launch that file automatically.

The truly problematic part is that the file can be changed by anybody who has write access to it. The owner can change the entire byte content and the file extension after the user agrees. A file extension is the part after the dot in a filename, like .png or .webarchive, which usually hints at what kind of file it is. ShareBear will then download and update the file on the victim's machine with no user interaction and no notification.

In effect, the victim has given the attacker permission to plant a polymorphic file and permission to launch it remotely at any moment. Polymorphic here means the file can change its form: what looked like a picture yesterday can be an executable program today.

Apple fixed this behaviour in macOS Monterey 12.0.1 as a result of the report, without issuing a CVE. A CVE is a public identifier for a known security flaw, so a fix without one means Apple treated it as a design flaw rather than a bug in the usual sense.

Bonus bug: escaping an iframe sandbox

While fuzzing the icloud-sharing:// scheme, the researcher stumbled on a bug unrelated to the webarchive hunt. Fuzzing means feeding a system lots of unusual inputs to see what breaks.

ShareBear checks the path of the URL for /iclouddrive/* before doing the behaviour above. The path is the part of an address after the domain, like /photos/ in https://photos.icloud.com/photos/. If the path is /photos/*, ShareBear tells Safari to open a new tab pointing at the iCloud web app, but it never checks that the domain really is the iCloud web app. Normally the user simply sees https://photos.icloud.com. Because the domain is never validated, ShareBear can be tricked into opening a new tab to any website at all.

Why does that matter? A website is normally allowed to open a new tab with window.open, so at first this looks like nothing special. But there are situations where a website is not allowed to do that. One is when a popup blocker is switched on. Another, more devious, one is when the website is inside a sandboxed iframe.

An iframe is a way to embed one web page inside another. The sandbox attribute is used when you want to show untrusted third-party content, for example an ad banner on your blog, without letting that content run JavaScript or do other powerful things. The rule is that new windows opened from a sandboxed iframe must inherit the same restrictions as the iframe itself. Otherwise escaping the sandbox would be as easy as opening a popup.

This bug makes Safari open a fresh tab with no sandbox restrictions at all:

HTML
<html>
<head>
<meta http-equiv="refresh" content="0;URL='icloud-sharing://example.com/photos/foo'" />
</head>
</html>

Line by line:

  • <html>, <head> and </html> are the basic structure tags of a web page.
  • <meta http-equiv="refresh" ...> tells the browser to reload or navigate after a delay. Here the delay is 0, meaning immediately.
  • URL='icloud-sharing://example.com/photos/foo' is where the browser is sent. The domain is example.com, an arbitrary site, and the path is /photos/foo, which triggers ShareBear's photo branch.
  • Because ShareBear does not check the domain, it asks Safari to open example.com in a new tab, and that tab is not bound by the sandbox.

So the missing domain check gives an easy popup-blocker bypass and an iframe sandbox escape. It was fixed in Safari 15.2 without a CVE. A live demo was published on BugPoC, a site for sharing proof-of-concept exploits, with PoC ID bp-S4HH6YcO. It only works with Safari below 15.2 on macOS before Monterey 12.1.

Quarantine and Gatekeeper

Quick reminder of where we are. The attacker's website can ask the user to open a shared PNG file. If the user agrees, the attacker can launch that file at any future moment, even after changing its content and extension.

The obvious next idea is to swap the content of puppy.png for a webarchive, rename it evil.webarchive, and launch it with the same icloud-sharing:// address. Gatekeeper blocks that. ShareBear correctly gives downloaded files the com.apple.quarantine attribute, a marker macOS puts on files that came from the internet. According to Apple, "Gatekeeper prevents quarantined executable files and other similar files (shell scripts, web archives, and so on) from opening or executing."

Two limitations follow from this protection:

  1. The attacker cannot run his own applications.
  2. The attacker cannot directly open webarchive files.

Launching existing, already-approved applications is trivial, though. You use a fileloc, a small file that points at a local application, and let the system open it. This is sometimes called Arbitrary File Execution, and it is often misunderstood because it sounds scarier than it is:

XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>URL</key>
<string>file:///System/Applications/Calculator.app</string>
</dict>
</plist>

Line by line:

  • The first line declares this as an XML document, a text format for structured data, using UTF-8 character encoding.
  • The DOCTYPE line says the document follows Apple's plist format, a way of writing settings and structured values.
  • <plist version="1.0"> opens the plist.
  • <dict> opens a dictionary, a list of key and value pairs.
  • <key>URL</key> names the entry, and <string>file:///System/Applications/Calculator.app</string> gives its value: the local address of the macOS Calculator app.
  • The closing tags end the dictionary and the plist.

This fileloc points at macOS Calculator and is launched with the icloud-sharing:// scheme. Launching an application that is already approved has little impact, so the focus stays on opening webarchives.

The Windows URL File shortcut

The fileloc technique resembles an old symlink attack. A symlink is a file that acts as a pointer to another file, so software can be tricked into opening something it did not expect. Shortcuts come in many forms: Unix symlinks, macOS aliases, Windows linkfiles, Safari weblocs, Edge bookmarks and so on.

The idea was to use a shortcut to launch Safari, an existing approved application, and have Safari open a different file. Gatekeeper has no problem with launching Safari; it objects to opening files ending in .webarchive.

The shortcut filetype that worked is the ancient Windows URL File:

Text
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
[InternetShortcut]
URL=file:///path/to/webarchive
IDList=

Line by line:

  • [{000214A0-0000-0000-C000-000000000046}] is a section header identifying the file as a Windows internet shortcut.
  • Prop3=19,2 is a property setting used by that format.
  • [InternetShortcut] starts the section that holds the actual target.
  • URL=file:///path/to/webarchive is the address the shortcut points at: a local webarchive file.
  • IDList= is an optional list of shell items, left empty here.

Launching evil.url opens Safari and tells it to load the webarchive without asking Gatekeeper for permission. This was tracked as CVE-2021-30861. One problem remained: the attacker needs to know the full path to the webarchive. If the webarchive is downloaded through ShareBear, it lives in /Users/<user>/Library/Mobile Documents/com~apple~CloudDocs, which includes the victim's username. That is not scalable, because the attacker would have to guess each victim's name.

The workaround is to mount the webarchive into the known /Volumes/ directory using a DMG file, launched with the icloud-sharing:// scheme. A DMG is Apple's disk image format, a single file that the system can attach as if it were a disk. Mounting means attaching it so its contents appear at a fixed location. Now the location is known, so the following evil.url works every time:

Text
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
[InternetShortcut]
URL=file:///Volumes/folder/evil.webarchive
IDList=

Line by line, this is the same shortcut format as before, with one change: URL=file:///Volumes/folder/evil.webarchive points at a fixed path under /Volumes/, where the mounted disk image puts the file. No username is needed.

Launching evil.url with the icloud-sharing:// scheme opens evil.webarchive, and JavaScript then runs wherever the attacker wants. The screen recording injects alert(origin) in https://google.com. alert shows a popup box, and origin is a built-in value holding the current origin, so the popup proves which site the code is running in.

The full chain

Using ShareBear to download and open a webarchive comes down to three steps:

  1. Trick the victim into giving permission to plant the polymorphic file.
  2. Turn puppies.png into evil.dmg and launch it.
  3. Turn evil.dmg into evil.url and launch it.

Turning one file into three different payloads requires coordination on the attacker's server. A payload is the part of an attack that actually does the damage. A less fun alternative is to have the victim agree to open a shared folder that already contains all the files.

In the recorded demonstration the victim agrees to view a folder containing PNG images plus two hidden files, .evil.dmg and .evil.url. The website uses the icloud-sharing:// scheme to launch both hidden files, bypassing Gatekeeper and opening a webarchive. No additional prompts are shown after the victim agrees to view the shared folder. The example webarchive injects code into https://www.icloud.com to exfiltrate the victim's iOS camera roll. Exfiltrate means to copy data out to the attacker's own server.

It would be just as easy to inject JavaScript to switch on the webcam when hijacking a trusted video chat site such as https://zoom.us or https://facetime.apple.com.

How Apple fixed it

Apple fixed the issues in several places:

  • ShareBear now reveals files instead of launching them. This shipped in macOS Monterey 12.0.1 without a CVE.
  • WebKit, the engine inside Safari that renders pages, no longer opens quarantined files. This shipped in Safari 15 as CVE-2021-30861.
  • The /photos/* domain validation issue was fixed in Safari 15.2 without a CVE.
  • The .sdef JavaScript same-origin policy issue was fixed in macOS Big Sur 11.6.2 as CVE-2021-30975.

The bugs were submitted in mid July 2021 and patched in early 2022.

Bonus material: stealing local files

One limitation still bothered the researcher. The UXSS chain cannot steal files that exist only on the victim's hard drive. UXSS can indirectly steal files by injecting code into https://dropbox.com or https://drive.google.com, but files that never leave the machine are out of reach.

Inspired by the Black Hat presentation mentioned earlier, he looked for system applications that run JavaScript in a more privileged context than Safari. Privileged here means with more power and fewer restrictions.

macOS Script Editor recognises an obscure filetype called Scripting Additions, with the extension .osax. These bundles, which are folders that the system treats as a single file, contain a nested XML-based file called a Dictionary Document, with the extension .sdef. That file is used to display developer-defined terms for an AppleScript application. AppleScript is Apple's own scripting language for automating apps.

The important discovery was that these XML files are allowed to contain HTML, the language web pages are written in. The HTML renderer inside Script Editor also has a JavaScript engine, and that engine does not enforce the same-origin policy. The same-origin policy is the browser rule that stops code from one site reading data from another; without it, code can read anything it can reach. This was fixed in macOS Big Sur 11.6.2 as CVE-2021-30975. Stealing /etc/passwd becomes easy. That file is a classic Unix file listing user accounts, often used in demonstrations because it is readable and harmless to show.

XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dictionary SYSTEM "">
<dictionary>
<suite name="" code="">
<command name="" code="" description="">
</command>
<documentation>
<html>
<![CDATA[
<script>
fetch('file:///etc/passwd').then(x=>{x.text().then(y=>{document.write(y);})})
</script>
]]>
</html>
</documentation>
</suite>
</dictionary>

Line by line:

  • The first line declares an XML document using UTF-8.
  • <!DOCTYPE dictionary SYSTEM ""> says this is a dictionary document, with no external definition file.
  • <dictionary>, <suite> and <command> are the structural tags of a Scripting Addition dictionary. The empty name and code attributes are left blank here.
  • <documentation> opens the section that holds human-readable documentation for the command.
  • <html> starts a block of HTML inside that documentation.
  • <![CDATA[ marks the start of raw character data, so the XML parser does not try to interpret the JavaScript as XML.
  • <script> opens the JavaScript block.
  • fetch('file:///etc/passwd') asks the system to read the local file /etc/passwd. fetch is the standard JavaScript function for retrieving a resource.
  • .then(x=>{x.text().then(y=>{document.write(y);})}) waits for the response, converts it to text, and writes that text into the page with document.write, so the file's contents appear on screen.
  • The closing tags end the script, the CDATA block, the HTML, the documentation, the suite and the dictionary.

Gatekeeper does not mind opening Scripting Addition files. So evil.sdef is packaged inside evil.osax and sent to the victim through ShareBear, and the icloud-sharing:// address launches it in Script Editor. In addition to UXSS, the hack can get around sandbox restrictions and steal local files.

Conclusion

This project shows how a design flaw in one application can make a whole range of unrelated bugs more dangerous. It is also a good example of how, even with macOS Gatekeeper switched on, an attacker can still cause a lot of trouble by tricking approved applications into doing harmful things.

The bugs were submitted to Apple in mid July 2021. Apple patched all of them in early 2022 and paid a bounty of $100,500. A bounty is a reward a company pays to someone who reports a security problem responsibly.

Glossary

  • 0day: a security flaw that the vendor does not know about yet, so there is no fix available at the time it is used.
  • AppleScript: Apple's scripting language for automating applications on macOS.
  • Arbitrary File Execution: tricking the system into launching a file or application of the attacker's choosing.
  • Black Hat: a well-known security conference where researchers present their work.
  • Bounty: a reward paid by a company to someone who reports a security flaw.
  • Bundle: a folder that macOS treats as a single file, such as an application or a Scripting Addition.
  • CDATA: a marker in XML that says the enclosed text is raw data and should not be parsed as XML.
  • Cookie: a small piece of data a website stores in your browser to remember you, often used to keep you logged in.
  • CVE: a public identifier assigned to a known security flaw.
  • Deep linking: using a special address to open a specific place inside another application.
  • DMG: Apple's disk image format, a single file the system can attach as if it were a disk.
  • Domain: the part of a web address that identifies the site, such as example.com.
  • Exfiltrate: to copy data out to an attacker's own system.
  • File extension: the part of a filename after the dot, such as .png, which usually hints at the file type.
  • fileloc: a small file that points at a local application so the system can open it.
  • Fuzzing: feeding a system lots of unusual inputs to find out what breaks.
  • Gatekeeper: the macOS feature that checks downloaded software before it is allowed to run.
  • grep: a standard command line tool for searching text.
  • HTML: the language web pages are written in.
  • https: the encrypted version of the web protocol, used for secure pages.
  • IANA: the organisation that keeps the master list of official URI schemes.
  • iCloud: Apple's online storage and sync service.
  • Iframe: a way to embed one web page inside another.
  • JavaScript: the programming language web pages use to be interactive.
  • Launch Services: the macOS component that tracks which application opens which kind of file or address.
  • lsregister: the command line tool that reads and prints the Launch Services database.
  • macOS: Apple's desktop operating system.
  • Metasploit: a well-known collection of hacking tools.
  • Mounting: attaching a disk image so its contents appear at a fixed location in the file system.
  • Origin: the combination of protocol, domain and port that the browser uses to decide what may talk to what.
  • Parameter: an extra piece of information handed to an application or address, telling it what to work on.
  • Path: the part of an address after the domain, such as /photos/.
  • Payload: the part of an attack that actually does the damage.
  • Plist: Apple's structured text format for settings and values.
  • Polymorphic file: a file that can change its form and content after it has been approved.
  • Popup blocker: a browser feature that stops websites opening new windows on their own.
  • Privileged: having more power and fewer restrictions than normal.
  • Project Zero: Google's security research team.
  • Quarantine attribute: a marker macOS puts on files downloaded from the internet.
  • Remote Code Execution (RCE): running your own programs on someone else's machine.
  • Sandbox: a restricted box a program is kept in so it cannot touch the rest of the system.
  • Sandboxed iframe: an embedded page that is not allowed to run JavaScript or do other powerful things.
  • Same-origin policy: the browser rule that stops code from one site reading data from another.
  • Script Editor: the macOS application for writing and running AppleScript.
  • Scripting Additions (.osax): a bundle format that Script Editor recognises and that can contain a Dictionary Document.
  • Dictionary Document (.sdef): an XML file inside a Scripting Addition that describes an application's scripting terms and may contain HTML.
  • ShareBear: the iCloud Sharing application that registers the icloud-sharing: scheme.
  • Share Link: a public web address that gives access to a shared iCloud file.
  • Symlink: a file that acts as a pointer to another file.
  • URI scheme: the first part of an address, before the colon, that says what kind of thing the address points to.
  • UXSS (Universal Cross-Site Scripting): a browser flaw that lets an attacker run code in any website, not just one.
  • Webarchive: a file Safari creates when saving a web page, which records the origin the content should be displayed in.
  • WebKit: the engine inside Safari that renders web pages.
  • window.open: the JavaScript function a website uses to open a new window or tab.
  • XSS (Cross-Site Scripting): getting an attacker's JavaScript to run inside someone else's website.
  • XML: a text format for structured data.

More by Ryan Pickren

View all

1 more disclosed report, 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.

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.