Skip to content
RCE Write-up Advanced

Unauthd - Logic bugs FTW

A logic flaw in authd allowed a local user to forge code signatures with arbitrary entitlements, and a race condition in kextutil allowed loading an unsigned kernel extension. Chained together, these bugs let an attacker gain root and kernel code execution with SIP bypass.

Ilias Morad Follow

Published on a2nkf.github.io

This blog post is about a MacOS LPE chain I wrote and reported back in February. It features three logic bugs to go from user to root with System Integrity Protection (SIP) bypass to kernel.

A2nkF's Blog, on a2nkf.github.io

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

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

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

Context

This is a local privilege escalation chain for macOS that goes from an unprivileged user to root, bypasses System Integrity Protection (SIP) and ends in kernel code execution. It was written and reported by Ilias Morad (A2nkF) in February 2020 and disclosed on 31 July 2020. The chain uses three logic bugs and no memory corruption, so it is fully deterministic and reliable. It runs on macOS versions below 10.15.5.

The central component of the first bug is authd(8), part of the mostly open-source Security.framework. That framework manages security-related functionality: Keychain access through securityd(1), code signing through trustd(8), and authorisation, authentication and spawning of privileged processes through authd. Third-party applications can talk to authd through the public authorisation services APIs, and many of Apple's own private and public frameworks use the same APIs to perform privileged actions from inside an unprivileged process.

_config.yml
_config.yml From the original on a2nkf.github.io

The set of supported rules and some preregistered rights live in authorization.plist. Rules give granular control over which privilege a client needs to qualify for a right: the client's group, the client's user, whether it runs as GUI or console, and the client's entitlements. Some rights additionally or alternatively require the user to type their password into a pop-up dialog.

_config.yml
_config.yml From the original on a2nkf.github.io

Setup

Finding it

While auditing the authd source, the researcher looked at process.c, specifically the code that fetches code signing information from a client:

C
    // ...

    status = SecCodeCopySigningInformation(codeRef, kSecCSRequirementInformation, &code_info); // [1]
    require_noerr_action(status, done, os_log_debug(AUTHD_LOG, "process: PID %d SecCodeCopySigningInformation failed with %d", proc->auditInfo.pid, (int)status));

    // ...

    if (CFDictionaryGetValueIfPresent(code_info, kSecCodeInfoEntitlementsDict, &value)) {
        if (CFGetTypeID(value) == CFDictionaryGetTypeID()) {
            proc->code_entitlements = CFDictionaryCreateCopy(kCFAllocatorDefault, value); // [2]
        }
        value = NULL;
    }

The code calls SecCodeCopySigningInformation to retrieve data from the client [1] and, if entitlements are present, copies them into a dictionary [2]. At first glance it looks fine, but Apple's developer documentation for SecCodeCopySigningInformation states:

Text
 If the signing data for the code is corrupt or invalid, this function may fail or it
 may return partial data. To ensure that only valid data is returned (and errors are
 raised for invalid data), you must successfully call the SecCodeCheckValidity or
 SecCodeCheckValidityWithErrors function before calling SecCodeCopySigningInformation.

Neither function is called before SecCodeCopySigningInformation. The copyright on the file dates to 2012-2013. SecCodeCheckValidity[WithErrors] would compare the client's binary on disk against its CDHash and verify its integrity. Because that never happens, a client can be codesigned with arbitrary entitlements without authd ever complaining.

The next question is which entitlements authd cares about. The internal check is process_has_entitlement_for_right:

C
bool
process_has_entitlement_for_right(process_t proc, const char * right)
{
    bool entitled = false;
    require(right != NULL, done);

    CFTypeRef rights = NULL;
    if (proc->code_entitlements && CFDictionaryGetValueIfPresent(proc->code_entitlements, CFSTR("com.apple.private.AuthorizationServices"), &rights)) { // [3]
        if (CFGetTypeID(rights) == CFArrayGetTypeID()) {
            CFStringRef key = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, right, kCFStringEncodingUTF8, kCFAllocatorNull);
            require(key != NULL, done);

            CFIndex count = CFArrayGetCount(rights);
            for (CFIndex i = 0; i < count; i++) {
                if (CFEqual(CFArrayGetValueAtIndex(rights, i), key)) {
                    entitled = true;
                    break;
                }
            }
            CFReleaseSafe(key);
        }
    }

done:
    return entitled;
}

It looks for the com.apple.private.AuthorizationServices entitlement [3], an array of strings where each entry is the name of a desired right.

Exploitation

Step 1: forge the entitlement and request the right

With the check understood, triggering the bug is straightforward:

  1. Create an entitlement file with the right(s) you want. The researcher uses system.install.apple-software for demonstration:
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>com.apple.private.AuthorizationServices</key>
    <array>
        <string>system.install.apple-software</string>
    </array>
</dict>
</plist>
  1. Write a program that waits for some time, then creates an AuthorizationRef and requests the desired right from authd.
  2. While the program is waiting, sign it:
Bash
codesign -f -s - --entitlements entitlements.xml ./test

Here ./test is the path to your program. 4. Observe the authd logs. They look similar to this:

_config.yml
_config.yml From the original on a2nkf.github.io

The signing has to happen after the program starts, not before. The reason is AppleMobileFileIntegretyDaemon, or amfid(8), the daemon that fetches and verifies entitlements and signatures of signed binaries. amfid would refuse to run a non-Apple-signed program that carries restricted entitlements.

Step 2: pick a useful right

Holding the proper entitlement is not enough to get any right you want. A process still has to satisfy the rules in authorization.plist. One rule, mostly used by Apple's private frameworks, checks entitlements, but many rules do not care about entitlements at all: they require the client to run as a specific user or the user to enter a password. So system.privilege.admin and AuthorizationExecuteWithPrivileges are not reachable this way.

After analysing authorization.plist, the researcher found the following rights obtainable by the default user just by holding the corresponding entitlements:

Text
Right                                        Private Framework implementing API

system.install.apple-software               // PackageKit.framework/InstallKit.framework
system.preferences.nvram                    // SystemAdministrator.framework
com.apple.uninstalld.uninstall              // Uninstall.framework
com.apple.opendirectoryd.linkidentity
com.apple.ServiceManagement.daemons.modify  // ServiceManagement.framework
system.services.directory.configure
com.apple.trust-settings.user
system.install.apple-config-data            // PackageKit.framework/InstallKit.framework
system.services.networkextension.filtering
system.install.software.iap                 // PackageKit.framework/InstallKit.framework
system.install.software.mdm-provided        // PackageKit.framework/InstallKit.framework
system.install.apple-software.standard-user // PackageKit.framework/InstallKit.framework
system.services.systemconfiguration.network
com.apple.activitymonitor.kill              // Activicymonitor?
com.apple.XType.fontmover.restore
com.apple.security.assessment.update
system.services.networkextension.vpn
com.apple.SoftwareUpdate.scan               // SoftwareUpdate.framework/InstallKit.framework
com.apple.SoftwareUpdate.modify-settings    // SoftwareUpdate.framework/InstallKit.framework
system.preferences.security.remotepair

Three rights stood out: system.install.apple-software, system.preferences.nvram and com.apple.ServiceManagement.daemons.modify. SystemAdministrator.framework performs additional checks on the client, so nvram cannot be written. com.apple.ServiceManagement.daemons.modify is less useful than it sounds: it allows starting and stopping existing daemons, not registering new ones. Honourable mentions are com.apple.activitymonitor.kill, which can kill arbitrary processes, and com.apple.uninstalld.uninstall, which can remove files and applications without a password prompt. Both could crash the system, but the goal is kernel code execution.

That leaves the system.install.* rights. Reversing the private PackageKit.framework showed APIs that install Apple-signed packages to any non-SIP-protected location, which is what the next step needs.

Step 3: install an Apple-signed package to a chosen location

At this point the password prompt normally shown when installing packages is bypassed, but only Apple-signed packages can be installed. PKG files are archives containing the files to install, an optional code signature and pre/post-install scripts, and pkgutil(1) can reveal their contents. Normally installd(8) runs pre/post-install scripts as root, but a package cannot simply be built with malicious scripts because it would not be Apple signed.

The better route is to find an Apple-signed package whose script can be hijacked. A package signed by Apple has its scripts executed not by installd but by system_installd(8), which holds the com.apple.rootless.install.heritable entitlement. That means system_installd and all its child processes run without SIP restrictions, which makes sense because they may need to install or update files at SIP-protected locations.

Downloading the packages from Apple's developer website and reading most of their scripts did not turn up anything. The researcher then looked for alternative downloads and found macOSPublicBetaAccessUtility.pkg, downloadable at beta.apple.com. Its post-install script, where $3 holds the disk the package is being installed onto, is shown here:

_config.yml
_config.yml From the original on a2nkf.github.io

The report states that this lets an executable with elevated rights be forged as long as the path matches, giving root code execution and a SIP bypass.

Step 4: load a kernel extension

With root and a SIP bypass, the obvious target for kernel code execution is kextutil(8), the utility that loads and unloads kernel extensions. On systems without SIP, root is enough to load a kernel extension. With SIP, only Apple-signed kernel extensions can be loaded, and the signature validation happens in kextutil itself rather than in the kernel. SIP prevents root from debugging system processes such as kextutil, so the signature check cannot simply be skipped.

When told to load a kernel extension, kextutil first copies it to a SIP-protected directory, /Library/StagedExtensions/private/<path to kext>. For example, a kext at /tmp/test.kext is copied to /Library/StagedExtensions/private/tmp/test.kext, so that nobody can tamper with it while it is verified. It then verifies the signature and loads and starts the kext. This would be fine if kextutil opened the kext once, loaded all files, performed the checks and then loaded the files from memory, and file descriptors could mitigate the issue. In reality there is a race between verification and loading into the kernel.

The chain is meant to be 100% reliable, and most races can be lost. The -interactive flag removes the uncertainty: it stops kextutil at each of these steps, so the race is won every time. After bypassing SIP:

  1. Copy an Apple-signed kernel extension (for example acfs.kext) to a non-SIP-protected location such as /tmp.
  2. Run kextutil -interactive /tmp/acfs.kext. kextutil verifies the signature automatically and waits for interaction before loading the kext.
  3. Overwrite the binary with your own:
Bash
mv kernelHax /Library/StagedExtensions/private/tmp/acfs.kext/Contents/MacOS/acfs
  1. Tell kextutil to continue. It loads the kext, including the malicious code, into the kernel.
  2. Tell kextutil to continue again. This starts the kernel extension.

Demo

A video of the full chain in action:

Watch the video on Vimeo
vimeo-player From the original on a2nkf.github.io

Root cause

The first bug is a missing validity check. authd calls SecCodeCopySigningInformation without first calling SecCodeCheckValidity or SecCodeCheckValidityWithErrors, although Apple's documentation requires it. The validity functions compare the binary on disk with its CDHash, so without them the entitlements authd reads are not bound to a verified binary. amfid blocks running a non-Apple-signed binary with restricted entitlements, but it does not stop the binary being re-signed after it has started, which is why the signing happens while the program waits.

The second bug is in an Apple-signed package's post-install script, which lets an executable with elevated rights be forged when the path matches. Because the package is Apple signed, the script runs under system_installd, which carries com.apple.rootless.install.heritable, so the forged executable runs without SIP restrictions.

The third bug is a race in kextutil between verifying the kext and loading it into the kernel, leaving a window in which the binary can be replaced. The -interactive flag makes that window deterministic rather than racy.

Impact

An unprivileged local user can obtain root, bypass SIP and execute code in the kernel, on macOS versions below 10.15.5. The chain is deterministic because it relies on logic bugs rather than memory corruption. The rights reachable through the first bug are limited to those whose rules accept entitlements alone; rights that require a specific user or a password prompt are not reachable this way.

Fix

Apple's mitigation for the first bug was to implement the code validity checks inside SecCodeCopySigningInformation, removing the need to call SecCodeCheckValidity[WithErrors] beforehand. The updated developer documentation states:

Text
This function obtains and verifies the signature on the code specified by the code object.
It checks the validity of all sealed components, including resources (if any). It validates the code against
a code requirement if one is specified. The call succeeds if all these conditions are satisfactory.

The report does not describe fixes for the package script or for kextutil.

Variants to test

  • A positive result is a privileged daemon that reads entitlements from a client whose binary can be re-signed after launch.
  • Enumerate rights in authorization.plist whose rules accept entitlements alone, then reverse the private frameworks implementing them. A positive result is a right that leads to code execution or file writes at a useful location.
  • A positive result is a script that runs an attacker-controlled executable under system_installd.
  • A positive result is a deterministic window in which the verified file can be replaced before use.

Timeline

  • January 1st 2020: Initial Discovery
  • February 24th 2020: First working Exploit
  • February 28th 2020: Reported Vulnerabilities to Apple
  • July 24th 2020: Apple released public patch for macOS (10.15.6)
  • July 28th 2020: Apple released public patch for tvOS (13.4.5)
  • July 31st 2020: Public Disclosure

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

What happened, in plain words

Imagine you have a normal user account on a Mac. You can browse the web, write documents, install apps into your own folder. You cannot change the system itself, and you certainly cannot take over the deepest part of the operating system, the kernel. This article is about a chain of three mistakes in macOS that let a normal user do exactly that: become the all-powerful root user, get around a protection called System Integrity Protection (SIP), and finally run code inside the kernel.

The researcher, Ilias Morad (A2nkF), wrote and reported this chain in February 2020 and published it on 31 July 2020. It works on macOS versions below 10.15.5. The important thing about it is that it uses no memory corruption, only logic bugs. A logic bug is a mistake in how a program decides things, not a mistake in how it stores data. Because of that, the chain is fully deterministic: it works every time, not just sometimes.

A few words before we start, because they come up constantly:

  • Privilege escalation means going from a less powerful account to a more powerful one. Here it means going from a normal user to root, the account that can do anything on the machine.
  • Local privilege escalation (LPE) means the attacker already has a foothold on the machine (a normal login) and wants more power. It is not about breaking in from the internet.
  • The kernel is the core of the operating system. It sits between programs and the hardware. Code running in the kernel can do anything, so getting code there is the strongest position an attacker can reach on a machine.
  • SIP (System Integrity Protection) is a macOS feature that stops even root from modifying certain protected files and folders. It is a seatbelt on top of the normal permission system.
  • An entitlement is a small labelled permission baked into a program's signature. Think of it as a badge printed on an ID card: the program presents the card, and the system reads the badge to decide what the program is allowed to do.
  • Code signing is the process of attaching a cryptographic signature to a program so the system can tell who made it and whether it has been changed since.
  • An API is a defined way for one program to ask another program to do something. Think of a restaurant menu: you do not walk into the kitchen, you order from the menu, and the kitchen does the work.

The first bug: authd trusts what it is told

The central character of the first bug is a background program called authd(8). The (8) is just a convention meaning it is a system administration program. authd is part of Apple's Security.framework, which is mostly open source. That framework handles security-related jobs: Keychain access through securityd(1), code signing through trustd(8), and authorisation, authentication and the spawning of privileged processes through authd.

In plain words: when a program wants to do something that needs special permission, it asks authd. authd checks whether the program is allowed, and if so, it helps carry the action out. Third-party applications can talk to authd through the public authorisation services APIs, and many of Apple's own private and public frameworks use the same APIs to perform privileged actions from inside an unprivileged process.

_config.yml
_config.yml From the original on a2nkf.github.io

The picture above illustrates the functionality that authd provides.

The set of supported rules, and some preregistered rights, live in a file called authorization.plist. A right here is a named permission, like system.install.apple-software. A rule decides who qualifies for a right. Rules give granular control: they can look at the client's group, the client's user, whether it runs as GUI or console, and the client's entitlements. Some rights additionally or alternatively require the user to type their password into a pop-up dialog.

_config.yml
_config.yml From the original on a2nkf.github.io

The picture above shows one of those password pop-ups, the kind any Mac user has seen.

The suspicious code

While auditing the authd source, the researcher looked at process.c, specifically the code that fetches code signing information from a client:

C
    // ...

    status = SecCodeCopySigningInformation(codeRef, kSecCSRequirementInformation, &code_info); // [1]
    require_noerr_action(status, done, os_log_debug(AUTHD_LOG, "process: PID %d SecCodeCopySigningInformation failed with %d", proc->auditInfo.pid, (int)status));

    // ...

    if (CFDictionaryGetValueIfPresent(code_info, kSecCodeInfoEntitlementsDict, &value)) {
        if (CFGetTypeID(value) == CFDictionaryGetTypeID()) {
            proc->code_entitlements = CFDictionaryCreateCopy(kCFAllocatorDefault, value); // [2]
        }
        value = NULL;
    }

Line by line, in plain words:

  • The // ... lines are just places where other code was cut out to keep the example short.
  • SecCodeCopySigningInformation(...) is the call marked [1]. It asks the system for information about the signature of the program that is talking to authd. The result is stored in code_info.
  • The require_noerr_action(...) line checks whether that call succeeded. If it failed, it writes a debug log line containing the process ID and the error code, then jumps to the done label.
  • The if (CFDictionaryGetValueIfPresent(...)) line looks inside code_info for a piece called kSecCodeInfoEntitlementsDict, which is where entitlements are stored. If it is there, the value is put into value.
  • The inner if (CFGetTypeID(value) == CFDictionaryGetTypeID()) checks that the value really is a dictionary (a key/value container, like a small table).
  • The line marked [2], proc->code_entitlements = CFDictionaryCreateCopy(...), makes a copy of those entitlements and attaches it to the record of the calling process.

So the code asks for the client's signing information [1] and, if entitlements are present, copies them into a dictionary [2]. At first glance it looks fine. But Apple's developer documentation for SecCodeCopySigningInformation says something important:

Text
 If the signing data for the code is corrupt or invalid, this function may fail or it
 may return partial data. To ensure that only valid data is returned (and errors are
 raised for invalid data), you must successfully call the SecCodeCheckValidity or
 SecCodeCheckValidityWithErrors function before calling SecCodeCopySigningInformation.

In plain words: this function is not a validator. If the signature data is broken or fake, it may still hand back partial data. To be sure the data is genuine, you must first call SecCodeCheckValidity or SecCodeCheckValidityWithErrors.

Neither of those functions is called before SecCodeCopySigningInformation. The copyright on the file dates to 2012-2013. What would the missing check have done? SecCodeCheckValidity[WithErrors] compares the program's binary on disk against its CDHash, a fingerprint of the binary, and verifies its integrity. Because that never happens, a program can be codesigned with arbitrary entitlements without authd ever complaining.

Think of it like a bouncer who reads the name badge on your jacket but never checks that the jacket is really yours. You can sew any badge you like onto your own jacket, and the bouncer will believe it.

Which entitlements does authd care about?

The next question is which entitlements authd actually looks at. The internal check is a function called process_has_entitlement_for_right:

C
bool
process_has_entitlement_for_right(process_t proc, const char * right)
{
    bool entitled = false;
    require(right != NULL, done);

    CFTypeRef rights = NULL;
    if (proc->code_entitlements && CFDictionaryGetValueIfPresent(proc->code_entitlements, CFSTR("com.apple.private.AuthorizationServices"), &rights)) { // [3]
        if (CFGetTypeID(rights) == CFArrayGetTypeID()) {
            CFStringRef key = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, right, kCFStringEncodingUTF8, kCFAllocatorNull);
            require(key != NULL, done);

            CFIndex count = CFArrayGetCount(rights);
            for (CFIndex i = 0; i < count; i++) {
                if (CFEqual(CFArrayGetValueAtIndex(rights, i), key)) {
                    entitled = true;
                    break;
                }
            }
            CFReleaseSafe(key);
        }
    }

done:
    return entitled;
}

Line by line:

  • bool entitled = false; starts with the answer "no, this process is not entitled".
  • require(right != NULL, done); makes sure a right name was actually passed in. If not, it jumps to done.
  • The if (proc->code_entitlements && CFDictionaryGetValueIfPresent(...)) line, marked [3], checks whether the process has entitlements at all, and whether they contain an entry named com.apple.private.AuthorizationServices. If so, that entry is put into rights.
  • The inner if (CFGetTypeID(rights) == CFArrayGetTypeID()) checks that the entry is an array, that is, a list of strings.
  • CFStringCreateWithCStringNoCopy(...) turns the requested right name into a string object called key.
  • CFIndex count = CFArrayGetCount(rights); counts how many entries the list has.
  • The for loop walks through the list one entry at a time.
  • if (CFEqual(CFArrayGetValueAtIndex(rights, i), key)) compares each entry with the requested right. If they match, entitled = true; and break; stops the loop.
  • CFReleaseSafe(key); frees the temporary string.
  • done: is the label jumped to on early exit, and return entitled; hands back the answer.

So authd looks for the com.apple.private.AuthorizationServices entitlement [3], which is supposed to be an array of strings where each entry is the name of a desired right. Nothing in this function checks whether the entitlement itself is genuine. That check was supposed to happen earlier, and it does not.

Exploiting the first bug

Step 1: forge the entitlement and request the right

With the check understood, triggering the bug is straightforward:

  1. Create an entitlement file with the right(s) you want. The researcher uses system.install.apple-software for demonstration:
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>com.apple.private.AuthorizationServices</key>
    <array>
        <string>system.install.apple-software</string>
    </array>
</dict>
</plist>

This is a property list, or plist, a simple text format Apple uses for configuration. Line by line:

  • The first line declares the file as XML in UTF-8 encoding.
  • The DOCTYPE line points at Apple's standard definition for plist files.
  • <plist version="1.0"> opens the plist.
  • <dict> opens a dictionary, a set of key/value pairs.
  • <key>com.apple.private.AuthorizationServices</key> names the entitlement that authd looks for.
  • <array> opens a list, and <string>system.install.apple-software</string> puts one right name in it. This is the right that lets a program install Apple software packages.
  • The closing tags close the array, the dictionary and the plist.
  1. Write a program that waits for some time, then creates an AuthorizationRef and requests the desired right from authd. An AuthorizationRef is just a handle, a reference the program uses to talk to the authorisation system, like a ticket you show at a counter.
  2. While the program is waiting, sign it:
Bash
codesign -f -s - --entitlements entitlements.xml ./test

Line by line:

  • codesign is Apple's command-line tool for signing programs.
  • -f means force: replace any existing signature.
  • -s - means sign with an ad-hoc identity, that is, without a real developer certificate.
  • --entitlements entitlements.xml attaches the entitlements from the file we just wrote.
  • ./test is the path to your program.
  1. Observe the authd logs. They look similar to this:
_config.yml
_config.yml From the original on a2nkf.github.io

The screenshot above shows the authd log output after the program has been re-signed while it waits.

Why does the signing have to happen after the program starts, and not before? Because of AppleMobileFileIntegretyDaemon, or amfid(8), the daemon that fetches and verifies entitlements and signatures of signed binaries. amfid would refuse to run a non-Apple-signed program that carries restricted entitlements. So the program starts as an ordinary, allowed program, and only then gets re-signed with the forged entitlements.

Step 2: pick a useful right

Holding the proper entitlement is not enough to get any right you want. A process still has to satisfy the rules in authorization.plist. One rule, mostly used by Apple's private frameworks, checks entitlements, but many rules do not care about entitlements at all: they require the client to run as a specific user or the user to enter a password. So system.privilege.admin and AuthorizationExecuteWithPrivileges are not reachable this way. In plain words: you cannot simply ask for the master key and get it, because the master key's rule wants a password, not a badge.

After analysing authorization.plist, the researcher found the following rights obtainable by the default user just by holding the corresponding entitlements:

Text
Right                                        Private Framework implementing API

system.install.apple-software               // PackageKit.framework/InstallKit.framework
system.preferences.nvram                    // SystemAdministrator.framework
com.apple.uninstalld.uninstall              // Uninstall.framework
com.apple.opendirectoryd.linkidentity
com.apple.ServiceManagement.daemons.modify  // ServiceManagement.framework
system.services.directory.configure
com.apple.trust-settings.user
system.install.apple-config-data            // PackageKit.framework/InstallKit.framework
system.services.networkextension.filtering
system.install.software.iap                 // PackageKit.framework/InstallKit.framework
system.install.software.mdm-provided        // PackageKit.framework/InstallKit.framework
system.install.apple-software.standard-user // PackageKit.framework/InstallKit.framework
system.services.systemconfiguration.network
com.apple.activitymonitor.kill              // Activicymonitor?
com.apple.XType.fontmover.restore
com.apple.security.assessment.update
system.services.networkextension.vpn
com.apple.SoftwareUpdate.scan               // SoftwareUpdate.framework/InstallKit.framework
com.apple.SoftwareUpdate.modify-settings    // SoftwareUpdate.framework/InstallKit.framework
system.preferences.security.remotepair

This is a table with two columns. The left column is the name of a right. The right column, where present, names the private framework that implements the API for that right. A framework is a bundle of code that programs can use, like a toolbox.

Three rights stood out: system.install.apple-software, system.preferences.nvram and com.apple.ServiceManagement.daemons.modify. Each turned out to be less useful than it looked:

  • SystemAdministrator.framework performs additional checks on the client, so nvram cannot be written.
  • com.apple.ServiceManagement.daemons.modify is less useful than it sounds: it allows starting and stopping existing daemons, not registering new ones. A daemon is a background program that runs without a user watching it.

Honourable mentions are com.apple.activitymonitor.kill, which can kill arbitrary processes, and com.apple.uninstalld.uninstall, which can remove files and applications without a password prompt. Both could crash the system, but the goal is kernel code execution.

That leaves the system.install.* rights. Reversing the private PackageKit.framework showed APIs that install Apple-signed packages to any non-SIP-protected location, which is what the next step needs. Reversing here means reading compiled code to understand what it does, the way you might take apart a machine to see how it works.

Step 3: install an Apple-signed package to a chosen location

At this point the password prompt normally shown when installing packages is bypassed, but only Apple-signed packages can be installed. A PKG file is an archive containing the files to install, an optional code signature and pre/post-install scripts. A script is a small program that runs automatically at a certain moment. pkgutil(1) can reveal the contents of such an archive.

Normally installd(8) runs pre/post-install scripts as root, but a package cannot simply be built with malicious scripts because it would not be Apple signed. So the researcher looked for an Apple-signed package whose script could be hijacked.

Why is an Apple-signed package better than a homemade one? Because a package signed by Apple has its scripts executed not by installd but by system_installd(8), which holds the com.apple.rootless.install.heritable entitlement. That means system_installd and all its child processes run without SIP restrictions. This makes sense, because they may need to install or update files at SIP-protected locations. In other words: the installer for Apple's own packages is allowed to ignore the seatbelt, and so is anything it starts.

Downloading the packages from Apple's developer website and reading most of their scripts did not turn up anything. The researcher then looked for alternative downloads and found macOSPublicBetaAccessUtility.pkg, downloadable at beta.apple.com. Its post-install script, where $3 holds the disk the package is being installed onto, is shown here:

_config.yml
_config.yml From the original on a2nkf.github.io

The screenshot above shows the post-install script of that package. The report states that this lets an executable with elevated rights be forged as long as the path matches, giving root code execution and a SIP bypass.

Step 4: load a kernel extension

With root and a SIP bypass, the obvious target for kernel code execution is kextutil(8), the utility that loads and unloads kernel extensions. A kernel extension, or kext, is a bundle of code that runs inside the kernel. Drivers are a common example.

On systems without SIP, root is enough to load a kernel extension. With SIP, only Apple-signed kernel extensions can be loaded, and the signature validation happens in kextutil itself rather than in the kernel. SIP prevents root from debugging system processes such as kextutil, so the signature check cannot simply be skipped.

When told to load a kernel extension, kextutil does the following:

  1. It copies the kext to a SIP-protected directory, /Library/StagedExtensions/private/<path to kext>. For example, a kext at /tmp/test.kext is copied to /Library/StagedExtensions/private/tmp/test.kext, so that nobody can tamper with it while it is verified.
  2. It verifies the signature.
  3. It loads and starts the kext.

This would be fine if kextutil opened the kext once, loaded all files, performed the checks and then loaded the files from memory. File descriptors, the handles a program uses to keep a file open, could mitigate the issue. In reality there is a race between verification and loading into the kernel. A race condition is when a program checks something and later uses it, and an attacker can change it in between. The general name for this class is time-of-check to time-of-use, or TOCTOU.

The chain is meant to be 100% reliable, and most races can be lost. The -interactive flag removes the uncertainty: it stops kextutil at each of these steps, so the race is won every time. Think of it as a video game that pauses between levels and waits for you to press a key. You get to rearrange the board before the next level starts.

After bypassing SIP:

  1. Copy an Apple-signed kernel extension (for example acfs.kext) to a non-SIP-protected location such as /tmp.
  2. Run kextutil -interactive /tmp/acfs.kext. kextutil verifies the signature automatically and waits for interaction before loading the kext.
  3. Overwrite the binary with your own:
Bash
mv kernelHax /Library/StagedExtensions/private/tmp/acfs.kext/Contents/MacOS/acfs

Line by line:

  • mv is the standard command to move or rename a file.
  • kernelHax is the attacker's own binary, sitting in the current directory.
  • /Library/StagedExtensions/private/tmp/acfs.kext/Contents/MacOS/acfs is the path inside the staged copy of the kext where the original binary lives. Replacing it means the verified kext now contains the attacker's code.
  1. Tell kextutil to continue. It loads the kext, including the malicious code, into the kernel.
  2. Tell kextutil to continue again. This starts the kernel extension.

Demo

A video of the full chain in action:

Watch the video on Vimeo
vimeo-player From the original on a2nkf.github.io

The video above shows the whole chain running end to end.

Root cause

The first bug is a missing validity check. authd calls SecCodeCopySigningInformation without first calling SecCodeCheckValidity or SecCodeCheckValidityWithErrors, although Apple's documentation requires it. The validity functions compare the binary on disk with its CDHash, so without them the entitlements authd reads are not bound to a verified binary. amfid blocks running a non-Apple-signed binary with restricted entitlements, but it does not stop the binary being re-signed after it has started, which is why the signing happens while the program waits.

The second bug is in an Apple-signed package's post-install script, which lets an executable with elevated rights be forged when the path matches. Because the package is Apple signed, the script runs under system_installd, which carries com.apple.rootless.install.heritable, so the forged executable runs without SIP restrictions.

The third bug is a race in kextutil between verifying the kext and loading it into the kernel, leaving a window in which the binary can be replaced. The -interactive flag makes that window deterministic rather than racy.

Impact

An unprivileged local user can obtain root, bypass SIP and execute code in the kernel, on macOS versions below 10.15.5. The chain is deterministic because it relies on logic bugs rather than memory corruption. The rights reachable through the first bug are limited to those whose rules accept entitlements alone; rights that require a specific user or a password prompt are not reachable this way.

Fix

Apple's mitigation for the first bug was to implement the code validity checks inside SecCodeCopySigningInformation, removing the need to call SecCodeCheckValidity[WithErrors] beforehand. The updated developer documentation states:

Text
This function obtains and verifies the signature on the code specified by the code object.
It checks the validity of all sealed components, including resources (if any). It validates the code against
a code requirement if one is specified. The call succeeds if all these conditions are satisfactory.

In plain words: the function now does the checking itself, so a caller cannot forget to do it first. The report does not describe fixes for the package script or for kextutil.

Variants to test

  • A positive result is a privileged daemon that reads entitlements from a client whose binary can be re-signed after launch.
  • Enumerate rights in authorization.plist whose rules accept entitlements alone, then reverse the private frameworks implementing them. A positive result is a right that leads to code execution or file writes at a useful location.
  • A positive result is a script that runs an attacker-controlled executable under system_installd.
  • A positive result is a deterministic window in which the verified file can be replaced before use.

Timeline

  • January 1st 2020: Initial Discovery
  • February 24th 2020: First working Exploit
  • February 28th 2020: Reported Vulnerabilities to Apple
  • July 24th 2020: Apple released public patch for macOS (10.15.6)
  • July 28th 2020: Apple released public patch for tvOS (13.4.5)
  • July 31st 2020: Public Disclosure

Glossary

  • API: a defined way for one program to ask another program to do something, like ordering from a menu instead of walking into the kitchen.
  • authd: a macOS background program that handles authorisation, authentication and the spawning of privileged processes.
  • amfid (AppleMobileFileIntegretyDaemon): the macOS daemon that fetches and verifies entitlements and signatures of signed binaries.
  • AuthorizationRef: a handle a program uses to talk to the authorisation system.
  • AuthorizationExecuteWithPrivileges: an API mentioned in the report as a way to get root privileges, which the first bug does not reach.
  • authorization.plist: the file that defines the supported rules and some preregistered rights for authd.
  • CDHash: a fingerprint of a binary, used to check that the binary on disk matches what was signed.
  • Code signing: attaching a cryptographic signature to a program so the system can tell who made it and whether it has changed.
  • codesign: Apple's command-line tool for signing programs.
  • Daemon: a background program that runs without a user watching it.
  • Deterministic: works the same way every time, with no chance of failure.
  • Entitlement: a small labelled permission baked into a program's signature, like a badge printed on an ID card.
  • File descriptor: a handle a program uses to keep a file open.
  • Framework: a bundle of code that programs can use, like a toolbox.
  • installd: the macOS program that runs package pre/post-install scripts as root.
  • Kernel: the core of the operating system, sitting between programs and the hardware; code running there can do anything.
  • Kernel extension (kext): a bundle of code that runs inside the kernel, such as a driver.
  • kextutil: the macOS utility that loads and unloads kernel extensions.
  • Local privilege escalation (LPE): going from a less powerful account on a machine to a more powerful one, starting from an existing foothold.
  • Logic bug: a mistake in how a program decides things, rather than in how it stores data.
  • Memory corruption: a class of bug where a program writes to memory it should not, often leading to crashes or code execution; this chain uses none.
  • PKG: an archive containing files to install, an optional code signature and pre/post-install scripts.
  • pkgutil: the macOS utility that reveals the contents of a PKG archive.
  • Plist (property list): a simple text format Apple uses for configuration.
  • Privilege escalation: going from a less powerful account to a more powerful one.
  • Race condition: when a program checks something and later uses it, and an attacker can change it in between.
  • Reversing: reading compiled code to understand what it does.
  • Right: a named permission in the authorisation system, such as system.install.apple-software.
  • root: the account that can do anything on the machine.
  • Rule: the condition that decides who qualifies for a right.
  • Script: a small program that runs automatically at a certain moment.
  • SecCodeCheckValidity / SecCodeCheckValidityWithErrors: functions that compare a binary on disk with its CDHash and verify its integrity.
  • SecCodeCopySigningInformation: a function that retrieves signing information about a program; it does not validate it by itself.
  • securityd: the macOS program that handles Keychain access.
  • SIP (System Integrity Protection): a macOS feature that stops even root from modifying certain protected files and folders.
  • system_installd: the macOS program that runs scripts of Apple-signed packages, holding the com.apple.rootless.install.heritable entitlement so it and its children run without SIP restrictions.
  • Time-of-check to time-of-use (TOCTOU): the general name for a race where something is checked and later used, with a window in between.
  • trustd: the macOS program that handles code signing checks.

More by Ilias Morad

View all

2 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.