All writing

Fixing Sentry's Mach exception handler for Xcode's Enhanced Security

This is a follow-up to the post about adopting Xcode’s Enhanced Security in an app with a Rust core, and it’s about one entitlement from that bundle, platform restrictions, and what it does to crash reporters that catch Mach exceptions. With that key on, the app was killed as soon as the Sentry Cocoa SDK started, and the fix (which went upstream as getsentry/sentry-cocoa#9705 and shipped in Sentry Cocoa 9.36.0) is mostly about registering the exception handler differently and reading the different message the kernel then sends, plus a fallback for Rosetta, which doesn’t accept the new registration.

What the kernel is enforcing

A Mach exception handler is how crash reporters on Apple platforms catch a crash before it turns into a signal. The SDK creates a port, asks the kernel to send exceptions like EXC_BAD_ACCESS for the whole task to it, and a dedicated thread waits on that port, writes the report, and replies “not handled” so that the kernel goes on to deliver the usual SIGSEGV. The registration is one call:

task_set_exception_ports(task, mask, port,
    (int)(EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES), THREAD_STATE_NONE);

The behavior argument decides what the exception message carries, and EXCEPTION_DEFAULT sends the thread and task control ports of whoever crashed, which is convenient for the handler (it can read the thread’s registers right away) but is also a lot of power to hand to whoever holds the port. That’s what platform restrictions take away. In the Mac build the kill came about 0.6 seconds after launch, and re-signing the same build with different sets of the Enhanced Security keys pointed at com.apple.security.hardened-process.platform-restrictions-string = 2 as the one that causes it. The kernel log line for the kill looked like this:

EXC_GUARD AST: type=0x1 flavor=0x6 target=0x80000001 ... subcode=0x6e

Flavor 6 is kGUARD_EXC_EXCEPTION_BEHAVIOR_ENFORCE, the target is the behavior that was asked for (0x80000000 is MACH_EXCEPTION_CODES and 1 is EXCEPTION_DEFAULT), and the subcode is the exception mask the SDK registers (bad access, bad instruction, arithmetic, software and breakpoint). The rule itself is in xnu, in exception_is_identity_protected in osfmk/kern/ipc_tt.c, and it says that a task under the enhanced IPC policy may only register EXCEPTION_IDENTITY_PROTECTED, EXCEPTION_STATE or EXCEPTION_STATE_IDENTITY_PROTECTED. Anything else gets the task killed on the spot.

This is easy to miss during development, since the simulator doesn’t enforce the restriction at all, and the SDK skips the Mach monitor while a debugger is attached, so a build run from Xcode is fine too. That matches the report in getsentry/sentry-cocoa#5412, where the crash only showed up in a TestFlight build.

Registering the identity-protected behavior

EXCEPTION_IDENTITY_PROTECTED exists since macOS 12 and iOS 15, which is the SDK’s minimum anyway, and with it the exception message no longer carries control ports. It carries an identity token for the task and the crashed thread’s ID instead, and the message has a different layout, so the handler needs a second struct for it:

typedef struct {
    mach_msg_header_t header;
    mach_msg_body_t body;
    mach_msg_port_descriptor_t taskIdentityToken;
    NDR_record_t NDR;
    uint64_t threadID;
    exception_type_t exception;
    mach_msg_type_number_t codeCount;
    mach_exception_data_type_t code[0];
    char padding[512];
} MachExceptionIdentityProtectedMessage;

The receive buffer becomes a union of the old message, the new one and a bare header, and the handler tells them apart by the header’s msgh_id. The MIG definitions in the macOS SDK’s mach/mach_exc.defs number the routines from 2405, which is mach_exception_raise, and mach_exception_raise_identity_protected is the fourth one, so 2408. Reading it from the message means the handler doesn’t need to remember how it registered, which my first version did with a global.

The bigger change is that the handler needs a thread port to read the crashed thread’s registers and walk its stack, and now it only has an ID. Since the crash happened in our own task, we can list our threads and match the ID with THREAD_IDENTIFIER_INFO. Every port task_threads returns is a send right we own, so the ones that don’t match are deallocated as we go, and the array itself is freed with vm_deallocate:

static thread_t
threadWithID(uint64_t threadID)
{
    const task_t thisTask = mach_task_self();
    thread_act_array_t threads = NULL;
    mach_msg_type_number_t numThreads = 0;
    if (task_threads(thisTask, &threads, &numThreads) != KERN_SUCCESS) {
        return THREAD_NULL;
    }

    thread_t match = THREAD_NULL;
    for (mach_msg_type_number_t i = 0; i < numThreads; i++) {
        thread_identifier_info_data_t info;
        mach_msg_type_number_t infoCount = THREAD_IDENTIFIER_INFO_COUNT;
        if (match == THREAD_NULL
            && thread_info(threads[i], THREAD_IDENTIFIER_INFO, (thread_info_t)&info, &infoCount)
                == KERN_SUCCESS
            && info.thread_id == threadID) {
            match = threads[i];
        } else {
            mach_port_deallocate(thisTask, threads[i]);
        }
    }
    vm_deallocate(thisTask, (vm_address_t)threads, sizeof(thread_t) * numThreads);
    return match;
}

Nothing matches when the exception came from another task, like a forked child that inherited our exception ports. The handler then skips reading a machine context and marks the report’s registers as not valid, instead of sending zeros as if they were real, but the child’s crash is still recorded as a crash of our process (that part is a separate fix). The rest of the handler stays the same, it just reads the exception type, codes and NDR from whichever layout arrived.

Firebase Crashlytics does the same thing in FIRCLSMachException.c, and KSCrash has a PR for the same bug, kstenerud/KSCrash#956.

Rosetta rejects the behavior

The KSCrash PR falls back to the old behavior under Rosetta, which my first version didn’t do (I assumed that a behavior the headers declare is one the kernel accepts), so it’s worth checking with a small program built for both architectures:

#include <mach/mach.h>
#include <stdio.h>

int main(void) {
    mach_port_t port;
    mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port);
    mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND);
    kern_return_t kr = task_set_exception_ports(mach_task_self(), EXC_MASK_BAD_ACCESS, port,
        (int)(EXCEPTION_IDENTITY_PROTECTED | MACH_EXCEPTION_CODES), THREAD_STATE_NONE);
    printf("%s\n", mach_error_string(kr));
}
clang -arch x86_64 identity.c -o identity-x86 && ./identity-x86   # (os/kern) invalid argument
clang -arch arm64 identity.c -o identity-arm && ./identity-arm    # (os/kern) successful

Under Rosetta the call returns KERN_INVALID_ARGUMENT, and natively it succeeds. Nothing crashes either way, the install just fails, and the SDK treats a failed install as “no Mach monitor” and carries on with the signal handler only, so an x86_64 build of an app on Apple silicon would lose its Mach crash reports with nothing more than an error line in the SDK’s debug log. Rosetta also doesn’t enforce the restriction on translated processes, so the old behavior is safe there, and since there’s no public way to ask whether the restrictions apply to the current process, the registration tries the protected behavior first and falls back only on that one error:

static kern_return_t
setExceptionPort(const task_t task, const exception_mask_t mask)
{
    kern_return_t kr = task_set_exception_ports(task, mask, g_exceptionPort,
        (int)(EXCEPTION_IDENTITY_PROTECTED | MACH_EXCEPTION_CODES), THREAD_STATE_NONE);
    if (kr != KERN_INVALID_ARGUMENT) {
        return kr;
    }

    return task_set_exception_ports(task, mask, g_exceptionPort,
        (int)(EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES), THREAD_STATE_NONE);
}

You might also come across task_register_hardened_exception_handler, which sounds like it should be part of this, but it’s only required with a different entitlement, com.apple.security.only-one-exception-port, and a plain port registered with the identity-protected behavior survives under platform-restrictions-string = 2.

Testing a handler that can’t run under XCTest

The handler is the awkward part to test. A real kernel exception kills the test runner, and the simulator doesn’t enforce the restriction, so a unit test can’t show the kill or the handler running under it. What a unit test can check is the registration, by enabling the monitor and reading the behavior back from the kernel:

kern_return_t kr = task_get_exception_ports(
    mach_task_self(), EXC_MASK_BAD_ACCESS, masks, &count, ports, behaviors, flavors);
XCTAssertEqual(behaviors[0] & ~MACH_EXCEPTION_MASK, expectedBehavior);

expectedBehavior is EXCEPTION_IDENTITY_PROTECTED natively and EXCEPTION_DEFAULT when sysctl.proc_translated says the process runs under Rosetta. The test skips under a debugger, since installing would replace the debugger’s ports, and it fails if the registration is switched back to EXCEPTION_DEFAULT.

For the handler itself, we need a process that is signed with the entitlement and can crash for real. A small command-line probe that links the built Sentry.framework does the job, ad-hoc signed with only the one entitlement:

codesign --force --sign - --entitlements platform-restrictions.entitlements probe

The probe runs in a few modes, one launch each. A control mode registers an EXCEPTION_DEFAULT port by hand and has to exit with 137, killed by SIGKILL, which proves the restriction is in force on that machine (if the control survives, or dies some other way, the rest of the run says nothing about the fix). Then one launch starts the SDK and exits, one starts it and writes to address 0x10 so it crashes, and the last one starts it again and prints the crash report from the previous run in beforeSend, returning nil so nothing gets sent. With the fix, the start returns, the crash exits with SIGSEGV (exit status 139, so the handler declined the exception the way it should), and the replayed report has mechanism mach, EXC_BAD_ACCESS with code 1 and subcode 16, and the main thread as the crashed thread with a non-empty stack. The same checks, done from a small SwiftUI app with the entitlement, passed on an iPad and in Mac Catalyst too.

Rosetta needs its own run, from an x86_64 build of the probe, and there the control is expected to survive, since translated processes aren’t restricted. What that run checks is that the fallback keeps the Mach monitor installed, and with it the report is still mechanism mach.

To be sure the probe can tell a broken fix from a working one, it’s worth breaking the fix on purpose and running it again. Forcing EXCEPTION_DEFAULT got the start killed, removing the Rosetta fallback made the Rosetta report fall back to mechanism signal, and checking for the wrong msgh_id produced a report saying EXC_BAD_INSTRUCTION with code 0, blaming the wrong thread, which is a report that still arrives and looks plausible.

Summary

If your app enables Enhanced Security with platform restrictions, every crash reporter in it has to register its Mach exception ports with EXCEPTION_IDENTITY_PROTECTED (or one of the state behaviors) and read the crashed thread from the ID in the message. Sentry Cocoa does both since 9.36.0, so with an older version (or another crash reporter that doesn’t), leaving platform-restrictions-string out of the entitlements is what keeps the app from being killed at start. The new message format reaches every app, not only the hardened ones, so a crash handler installed after Sentry that builds its own Mach exception messages and forwards them to Sentry has to support mach_exception_raise_identity_protected as well, or Sentry falls back to reporting the crash through its signal handler. Check this on a device or a signed Mac build, since the simulator and a debug run from Xcode both hide the crash. A fix like this also needs the fallback to EXCEPTION_DEFAULT on KERN_INVALID_ARGUMENT, or x86_64 builds under Rosetta lose their Mach reports without crashing. For code that only runs when the kernel delivers a real exception, a small signed probe with a control mode, plus a few deliberately broken builds, shows much more than a unit test can.

Email address copied [email protected]