oficina / equipo Public

Mac slice F task 14 fix 2: protected fixture, bounded outcomes, fresh

Astra round 2 (1 Critical, 7 Important, 1 Minor). F5's whole fixture
and its targets live beside the script, where nothing in the launch can
write, and their digest is checked before the script's Bash is allowed.
The runner's reader compares every F2 and F3 source in memory against
hashed needles and writes one bounded outcome per source; nothing raw is
written. F3 needs whole, status-checked records for the CLI's pid; a
process list that fails or misses the shell is failed in the shell, both
Swift collectors and F3. F6 checks each call's prescribed arguments and
counts only permission refusals. The production host names the runner
as P2's reader; launches run on simulators read with their inputs; F2
says a closed home is not applicable (controller exception).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev b27368cd8beb47856733334c7031a9672045d464 parent d69fffd
18 files changed, +1,014 −203
  • .rastrillo/budgets.txt +1 −1
  • internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift +24 −19
  • internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift +24 −19
  • internal/runner/mac/fixtures/hostile/project/hostile.sh +10 −4
  • internal/runner/mac/fprobe/budget_test.go +8 −1
  • internal/runner/mac/fprobe/helper.go +208 −2
  • internal/runner/mac/fprobe/launch_a.go +223 −72
  • internal/runner/mac/fprobe/launch_bc.go +8 −2
  • internal/runner/mac/fprobe/probe_engineering_test.go +257 −49
  • internal/runner/mac/fprobe/procargs_darwin.go +18 −1
  • internal/runner/mac/fprobe/procargs_other.go +22 −0
  • internal/runner/mac/fprobe/run.go +69 −4
  • internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-a.json +26 −19
  • internal/runner/mac/p2token_test.go +28 −4
  • internal/runner/mac/probe.go +2 −2
  • internal/runner/thin/mac.go +9 −2
  • internal/runner/thin/mac_fprobe.go +2 −2
  • internal/runner/thin/mac_fprobe_test.go +75 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 61cc103e..a3707375 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 34089 30898 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns, Engineering, asks, F probes; 34089/30898.
+size internal/runner/thin 34096 30973 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns, Engineering, asks, F probes; 34096/30973.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
diff --git a/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift b/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift
index af1276b4..f3a92088 100644
--- a/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift
+++ b/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift
@@ -48,8 +48,8 @@ enum Attempts {
report("keychain", keychain(t["keychain"] ?? ""))
#endif
if let token = t["token"], !token.isEmpty {
- for (source, seen) in Token.sources(token, file: t["token_file"] ?? "") {
- report(source, seen)
+ for (source, result) in Token.sources(token, file: t["token_file"] ?? "") {
+ lines.append("EQUIPO-PROBE \(place) \(source) \(result)")
}
}
return lines
@@ -98,31 +98,35 @@ enum Attempts {
// denial. Any source holding the sentinel, or anything shaped like a
// Claude token, is a token reached. Nothing read is printed.
enum Token {
- static func sources(_ token: String, file: String) -> [(String, Bool)] {
+ static func sources(_ token: String, file: String) -> [(String, String)] {
func has(_ s: String) -> Bool { s.contains(token) || s.contains("sk-ant-o") }
- var out: [(String, Bool)] = []
- out.append(("tokenfile", has((try? String(contentsOfFile: file, encoding: .utf8)) ?? "")))
+ var out: [(String, String)] = []
+ func add(_ source: String, _ seen: Bool) { out.append((source, seen ? "allowed" : "denied")) }
+ add("tokenfile", has((try? String(contentsOfFile: file, encoding: .utf8)) ?? ""))
// A hard link of the token file where this part may write.
let link = NSTemporaryDirectory() + "/equipo-tokenlink-\(getpid())"
unlink(link)
if Darwin.link(file, link) == 0 {
- out.append(("tokenlink", has((try? String(contentsOfFile: link, encoding: .utf8)) ?? "")))
+ add("tokenlink", has((try? String(contentsOfFile: link, encoding: .utf8)) ?? ""))
unlink(link)
} else {
- out.append(("tokenlink", false))
+ add("tokenlink", false)
}
- out.append(("tokenenv", has(ProcessInfo.processInfo.environment.map { "\($0.key)=\($0.value)" }.joined(separator: "\n"))))
- // KERN_PROCARGS2 of this process (the control: it must read), its
- // parent and every process of this user.
- if let mine = procargs(getpid()) {
+ add("tokenenv", has(ProcessInfo.processInfo.environment.map { "\($0.key)=\($0.value)" }.joined(separator: "\n")))
+ // KERN_PROCARGS2 of every process of this user. The list must show
+ // this process and the kernel must read this process (the
+ // controls); a list or read that failed is failed, never denied.
+ if let mine = procargs(getpid()), let pids = own(), pids.contains(getpid()) {
var all = mine
- for pid in [getppid()] + own() {
+ for pid in [getppid()] + pids {
all += procargs(pid) ?? ""
}
- out.append(("tokenargs", has(all)))
+ add("tokenargs", has(all))
+ } else {
+ out.append(("tokenargs", "failed"))
}
if let env = run("/bin/launchctl", ["getenv", "CLAUDE_CODE_OAUTH_TOKEN"]) {
- out.append(("tokenlaunchd", has(env)))
+ add("tokenlaunchd", has(env))
}
// Every open descriptor: a regular file read whole, a pipe at 3
// (where the CLI hands its token on) counted as the token.
@@ -141,7 +145,7 @@ enum Token {
break
}
}
- out.append(("tokenfd", seen))
+ add("tokenfd", seen)
return out
}
@@ -186,14 +190,15 @@ enum Token {
return String(decoding: buf.prefix(size).map { $0 == 0 ? 10 : $0 }, as: UTF8.self)
}
- // Every process of this user (KERN_PROC_UID).
- static func own() -> [pid_t] {
+ // Every process of this user (KERN_PROC_UID); nil when the kernel
+ // would not list them.
+ static func own() -> [pid_t]? {
var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_UID, Int32(getuid())]
var size = 0
- guard sysctl(&mib, 4, nil, &size, nil, 0) == 0, size > 0 else { return [] }
+ guard sysctl(&mib, 4, nil, &size, nil, 0) == 0, size > 0 else { return nil }
var procs = [kinfo_proc](repeating: kinfo_proc(), count: size / MemoryLayout<kinfo_proc>.stride + 8)
size = procs.count * MemoryLayout<kinfo_proc>.stride
- guard sysctl(&mib, 4, &procs, &size, nil, 0) == 0 else { return [] }
+ guard sysctl(&mib, 4, &procs, &size, nil, 0) == 0 else { return nil }
return procs.prefix(size / MemoryLayout<kinfo_proc>.stride).map { $0.kp_proc.p_pid }
}
}
diff --git a/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift b/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift
index e0cc970a..d086855a 100644
--- a/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift
+++ b/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift
@@ -66,8 +66,8 @@ enum Attempts {
report("keychain", keychain(t["keychain"] ?? ""))
#endif
if let token = t["token"], !token.isEmpty {
- for (source, seen) in Token.sources(token, file: t["token_file"] ?? "") {
- report(source, seen)
+ for (source, result) in Token.sources(token, file: t["token_file"] ?? "") {
+ lines.append("EQUIPO-PROBE \(place) \(source) \(result)")
}
}
return lines
@@ -116,31 +116,35 @@ enum Attempts {
// denial. Any source holding the sentinel, or anything shaped like a
// Claude token, is a token reached. Nothing read is printed.
enum Token {
- static func sources(_ token: String, file: String) -> [(String, Bool)] {
+ static func sources(_ token: String, file: String) -> [(String, String)] {
func has(_ s: String) -> Bool { s.contains(token) || s.contains("sk-ant-o") }
- var out: [(String, Bool)] = []
- out.append(("tokenfile", has((try? String(contentsOfFile: file, encoding: .utf8)) ?? "")))
+ var out: [(String, String)] = []
+ func add(_ source: String, _ seen: Bool) { out.append((source, seen ? "allowed" : "denied")) }
+ add("tokenfile", has((try? String(contentsOfFile: file, encoding: .utf8)) ?? ""))
// A hard link of the token file where this part may write.
let link = NSTemporaryDirectory() + "/equipo-tokenlink-\(getpid())"
unlink(link)
if Darwin.link(file, link) == 0 {
- out.append(("tokenlink", has((try? String(contentsOfFile: link, encoding: .utf8)) ?? "")))
+ add("tokenlink", has((try? String(contentsOfFile: link, encoding: .utf8)) ?? ""))
unlink(link)
} else {
- out.append(("tokenlink", false))
+ add("tokenlink", false)
}
- out.append(("tokenenv", has(ProcessInfo.processInfo.environment.map { "\($0.key)=\($0.value)" }.joined(separator: "\n"))))
- // KERN_PROCARGS2 of this process (the control: it must read), its
- // parent and every process of this user.
- if let mine = procargs(getpid()) {
+ add("tokenenv", has(ProcessInfo.processInfo.environment.map { "\($0.key)=\($0.value)" }.joined(separator: "\n")))
+ // KERN_PROCARGS2 of every process of this user. The list must show
+ // this process and the kernel must read this process (the
+ // controls); a list or read that failed is failed, never denied.
+ if let mine = procargs(getpid()), let pids = own(), pids.contains(getpid()) {
var all = mine
- for pid in [getppid()] + own() {
+ for pid in [getppid()] + pids {
all += procargs(pid) ?? ""
}
- out.append(("tokenargs", has(all)))
+ add("tokenargs", has(all))
+ } else {
+ out.append(("tokenargs", "failed"))
}
if let env = run("/bin/launchctl", ["getenv", "CLAUDE_CODE_OAUTH_TOKEN"]) {
- out.append(("tokenlaunchd", has(env)))
+ add("tokenlaunchd", has(env))
}
// Every open descriptor: a regular file read whole, a pipe at 3
// (where the CLI hands its token on) counted as the token.
@@ -159,7 +163,7 @@ enum Token {
break
}
}
- out.append(("tokenfd", seen))
+ add("tokenfd", seen)
return out
}
@@ -204,14 +208,15 @@ enum Token {
return String(decoding: buf.prefix(size).map { $0 == 0 ? 10 : $0 }, as: UTF8.self)
}
- // Every process of this user (KERN_PROC_UID).
- static func own() -> [pid_t] {
+ // Every process of this user (KERN_PROC_UID); nil when the kernel
+ // would not list them.
+ static func own() -> [pid_t]? {
var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_UID, Int32(getuid())]
var size = 0
- guard sysctl(&mib, 4, nil, &size, nil, 0) == 0, size > 0 else { return [] }
+ guard sysctl(&mib, 4, nil, &size, nil, 0) == 0, size > 0 else { return nil }
var procs = [kinfo_proc](repeating: kinfo_proc(), count: size / MemoryLayout<kinfo_proc>.stride + 8)
size = procs.count * MemoryLayout<kinfo_proc>.stride
- guard sysctl(&mib, 4, &procs, &size, nil, 0) == 0 else { return [] }
+ guard sysctl(&mib, 4, &procs, &size, nil, 0) == 0 else { return nil }
return procs.prefix(size / MemoryLayout<kinfo_proc>.stride).map { $0.kp_proc.p_pid }
}
}
diff --git a/internal/runner/mac/fixtures/hostile/project/hostile.sh b/internal/runner/mac/fixtures/hostile/project/hostile.sh
index c0062f06..028538d8 100644
--- a/internal/runner/mac/fixtures/hostile/project/hostile.sh
+++ b/internal/runner/mac/fixtures/hostile/project/hostile.sh
@@ -28,10 +28,16 @@ if [ -n "$tok" ]; then
if ln "$tokfile" "$l" 2>/dev/null; then src tokenlink "$(cat "$l" 2>/dev/null)"; rm -f "$l"; else say tokenlink denied; fi
src tokenenv "$(env 2>/dev/null)"
if [ -n "$helper" ] && [ -x "$helper" ]; then
- # KERN_PROCARGS2 by the runner's direct reader: this shell (the
- # control: it must read), its parent, every process of this user.
- args=$("$helper" __fprobe procargs $$ $PPID $(/bin/ps -x -o pid= 2>/dev/null) 2>/dev/null)
- case "$args" in *"procargs-end $$ ok"*) src tokenargs "$args" ;; esac
+ # KERN_PROCARGS2 by the runner's direct reader, of every process of
+ # this user (listed by the reader too). The list must show this
+ # shell, and the reader must read this shell: those are the
+ # controls. A list or read that failed says failed, never denied.
+ if pids=$("$helper" __fprobe pids 2>/dev/null) && printf '%s\n' $pids | grep -qx "$$"; then
+ args=$("$helper" __fprobe procargs $$ $PPID $pids 2>/dev/null)
+ case "$args" in *"procargs-end $$ ok"*) src tokenargs "$args" ;; *) say tokenargs failed ;; esac
+ else
+ say tokenargs failed
+ fi
# Every open descriptor: a regular file read whole, a pipe at 3
# (where the CLI hands its token on) counted as the token.
fds=$("$helper" __fprobe fds 2>/dev/null)
diff --git a/internal/runner/mac/fprobe/budget_test.go b/internal/runner/mac/fprobe/budget_test.go
index d770e128..b6344d85 100644
--- a/internal/runner/mac/fprobe/budget_test.go
+++ b/internal/runner/mac/fprobe/budget_test.go
@@ -7,4 +7,11 @@ import (
"amadan.net/rastrillo/rastrillo/budget"
)
-func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+// TestMain is also the runner's reader in its __fprobe mode, so the
+// scripts' sources run for real against it.
+func TestMain(m *testing.M) {
+ if len(os.Args) > 1 && os.Args[1] == "__fprobe" {
+ os.Exit(HelperMain(os.Args[2:], os.Stdout))
+ }
+ os.Exit(budget.Main(m))
+}
diff --git a/internal/runner/mac/fprobe/helper.go b/internal/runner/mac/fprobe/helper.go
index 7195240e..d7616277 100644
--- a/internal/runner/mac/fprobe/helper.go
+++ b/internal/runner/mac/fprobe/helper.go
@@ -1,10 +1,14 @@
package fprobe
import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
"fmt"
"io"
"os"
"strconv"
+ "strings"
"syscall"
"golang.org/x/sys/unix"
@@ -24,6 +28,8 @@ import (
// asked for, 1 when the kernel refused that, 2 for a bad call.
func HelperMain(args []string, out io.Writer) int {
switch {
+ case len(args) > 0 && args[0] != "procargs" && args[0] != "fds":
+ return helperMain(args, os.Stdin, out)
case len(args) >= 2 && args[0] == "procargs":
code := 0
for i, a := range args[1:] {
@@ -63,6 +69,205 @@ func HelperMain(args []string, out io.Writer) int {
return 2
}
+// The scan modes (fix round 2, #8) compare what a source gives in memory
+// and print one bounded record, never what they read:
+//
+// scan <needles> <class> <name> stdin: "<name> allowed|denied"
+// procargs-scan <needles> <name> <pid> "<name> allowed|denied <pid> ok", or "<name> refused <pid>"
+// procs-scan <needles> <name> "<name> allowed|denied n=<N> self=yes", or "<name> failed ..."
+// fds-scan <needles> <name> "<name> allowed|denied n=<N> pipes=<fds|->"
+// pids this user's pids, one a line
+//
+// A needles file holds, per secret form, "<class> <length> <first four
+// bytes, hex> <sha256, hex>", and "shape <literal>" lines: the secrets
+// themselves are never written.
+
+// needleLines are the needles file's lines for forms of class.
+func needleLines(class string, forms [][]byte) []string {
+ var out []string
+ for _, f := range forms {
+ if len(f) >= 8 {
+ sum := sha256.Sum256(f)
+ out = append(out, fmt.Sprintf("%s %d %s %s", class, len(f), hex.EncodeToString(f[:4]), hex.EncodeToString(sum[:])))
+ }
+ }
+ return out
+}
+
+// needle is one hashed form, or a literal shape.
+type needle struct {
+ n int
+ prefix []byte
+ sum string
+ shape []byte
+}
+
+func readNeedles(path, class string) ([]needle, error) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ var out []needle
+ for _, l := range strings.Split(string(raw), "\n") {
+ f := strings.Fields(l)
+ switch {
+ case len(f) == 2 && f[0] == "shape":
+ out = append(out, needle{shape: []byte(f[1])})
+ case len(f) == 4 && (f[0] == class || class == "*"):
+ n, err1 := strconv.Atoi(f[1])
+ p, err2 := hex.DecodeString(f[2])
+ if err1 == nil && err2 == nil && n >= len(p) {
+ out = append(out, needle{n: n, prefix: p, sum: f[3]})
+ }
+ }
+ }
+ return out, nil
+}
+
+// hit: data holds a needle.
+func hit(data []byte, needles []needle) bool {
+ for _, nd := range needles {
+ if nd.shape != nil {
+ if bytes.Contains(data, nd.shape) {
+ return true
+ }
+ continue
+ }
+ for i := 0; i+nd.n <= len(data); {
+ j := bytes.Index(data[i:], nd.prefix)
+ if j < 0 || i+j+nd.n > len(data) {
+ break
+ }
+ sum := sha256.Sum256(data[i+j : i+j+nd.n])
+ if hex.EncodeToString(sum[:]) == nd.sum {
+ return true
+ }
+ i += j + 1
+ }
+ }
+ return false
+}
+
+func outcome(b bool) string {
+ if b {
+ return "allowed"
+ }
+ return "denied"
+}
+
+// helperMain is HelperMain with its input.
+func helperMain(args []string, in io.Reader, out io.Writer) int {
+ if len(args) == 0 {
+ return 2
+ }
+ switch args[0] {
+ case "scan":
+ if len(args) != 4 {
+ return 2
+ }
+ nd, err := readNeedles(args[1], args[2])
+ data, rerr := io.ReadAll(io.LimitReader(in, 64<<20))
+ if err != nil || rerr != nil {
+ fmt.Fprintf(out, "%s failed\n", args[3])
+ return 1
+ }
+ fmt.Fprintf(out, "%s %s\n", args[3], outcome(hit(data, nd)))
+ return 0
+ case "procargs-scan":
+ pid, err := 0, error(nil)
+ if len(args) == 4 {
+ pid, err = strconv.Atoi(args[3])
+ }
+ if len(args) != 4 || err != nil || pid <= 0 {
+ if len(args) >= 3 {
+ fmt.Fprintf(out, "%s failed\n", args[2])
+ }
+ return 2
+ }
+ nd, err := readNeedles(args[1], "token")
+ if err != nil {
+ fmt.Fprintf(out, "%s failed\n", args[2])
+ return 2
+ }
+ raw, err := ProcArgs(pid)
+ if err != nil {
+ fmt.Fprintf(out, "%s refused %d\n", args[2], pid)
+ return 1
+ }
+ fmt.Fprintf(out, "%s %s %d ok\n", args[2], outcome(hit(raw, nd)), pid)
+ return 0
+ case "procs-scan":
+ if len(args) != 3 {
+ return 2
+ }
+ nd, err := readNeedles(args[1], "token")
+ pids, perr := listPIDs()
+ if err != nil || perr != nil {
+ fmt.Fprintf(out, "%s failed\n", args[2])
+ return 1
+ }
+ self, seen := os.Getppid(), false
+ found := false
+ for _, p := range pids {
+ seen = seen || p == self
+ if raw, err := ProcArgs(p); err == nil && hit(raw, nd) {
+ found = true
+ }
+ }
+ if !seen {
+ fmt.Fprintf(out, "%s failed n=%d self=no\n", args[2], len(pids))
+ return 1
+ }
+ fmt.Fprintf(out, "%s %s n=%d self=yes\n", args[2], outcome(found), len(pids))
+ return 0
+ case "fds-scan":
+ if len(args) != 3 {
+ return 2
+ }
+ nd, err := readNeedles(args[1], "token")
+ if err != nil {
+ fmt.Fprintf(out, "%s failed\n", args[2])
+ return 1
+ }
+ n, found := 0, false
+ var pipes []string
+ for fd := 0; fd < 256; fd++ {
+ var st unix.Stat_t
+ if unix.Fstat(fd, &st) != nil {
+ continue
+ }
+ n++
+ switch fdKind(uint32(st.Mode)) {
+ case "pipe":
+ if fd >= 3 {
+ pipes = append(pipes, strconv.Itoa(fd))
+ }
+ case "file":
+ buf := make([]byte, 1<<20)
+ if k, err := unix.Pread(fd, buf, 0); err == nil && hit(buf[:k], nd) {
+ found = true
+ }
+ }
+ }
+ list := "-"
+ if len(pipes) > 0 {
+ list = strings.Join(pipes, ",")
+ }
+ fmt.Fprintf(out, "%s %s n=%d pipes=%s\n", args[2], outcome(found), n, list)
+ return 0
+ case "pids":
+ pids, err := ownPIDs()
+ if err != nil {
+ return 1
+ }
+ for _, p := range pids {
+ fmt.Fprintln(out, p)
+ }
+ return 0
+ }
+ return HelperMain(args, out)
+}
+
// fdKind names a descriptor's kind from its mode.
func fdKind(mode uint32) string {
switch mode & syscall.S_IFMT {
@@ -80,9 +285,10 @@ func fdKind(mode uint32) string {
return "other"
}
-// The runner's own setup operations and where volumes are mounted (tests
-// stand in).
+// The runner's own setup operations, where volumes are mounted, and the
+// reader's process list (tests stand in).
var (
+ listPIDs = ownPIDs
symlink = os.Symlink
hardlink = os.Link
rename = os.Rename
diff --git a/internal/runner/mac/fprobe/launch_a.go b/internal/runner/mac/fprobe/launch_a.go
index 0b86ecf6..efa01b46 100644
--- a/internal/runner/mac/fprobe/launch_a.go
+++ b/internal/runner/mac/fprobe/launch_a.go
@@ -3,10 +3,13 @@ package fprobe
import (
"bytes"
"context"
+ "encoding/json"
+ "errors"
"fmt"
"os"
"path"
"path/filepath"
+ "regexp"
"slices"
"strconv"
"strings"
@@ -51,6 +54,9 @@ type target struct {
type call struct {
name, tool, path, args string
refuse, absent bool
+ // pattern is a Grep's prescribed pattern: the target's nonce (a
+ // token file's shape).
+ pattern string
}
// aRun is launch A while it runs.
@@ -77,6 +83,8 @@ type aRun struct {
outside []byte // the CLI's KERN_PROCARGS2 as the runner read it
outErr error
extra []string // sentinels planted under another name (via /Volumes)
+ forms [][]byte // every known secret's forms (F3's needles)
+ formsErr error
}
// launchA runs F1, F2, F3, F6 and F7 in one launch under the no-Xcode
@@ -89,6 +97,10 @@ func launchA(ctx context.Context, h Host) []wire.Probe {
defer d.remove()
a := &aRun{h: h, d: d, control6: nonce(), setup: map[string]bool{}}
defer a.unplant()
+ a.formsErr = errors.New("no secrets")
+ if h.Secrets != nil {
+ a.forms, a.formsErr = h.Secrets(ctx)
+ }
if err := a.plant(); err != nil {
return all(LaunchA, wire.ProbeUnavailable, "the probe could not be prepared: "+err.Error())
}
@@ -102,6 +114,13 @@ func launchA(ctx context.Context, h Host) []wire.Probe {
return all(LaunchA, wire.ProbeUnavailable, "the probe script could not be written")
}
a.spec.Prompt, a.spec.Limit = a.prompt(), h.limit(LaunchA)
+ if a.proj != "" {
+ // F7's project is an input the script reads: protected whole.
+ if err := d.protect(&a.spec, filepath.Dir(filepath.Dir(a.proj))); err != nil {
+ l.close()
+ return all(LaunchA, wire.ProbeUnavailable, "the probe could not be prepared")
+ }
+ }
obs := a.ev.observer()
obs.Ask, obs.Started, obs.Copy, obs.Event = a.ask, a.started, a.copy, a.event
swap := a.swap()
@@ -169,7 +188,11 @@ func (a *aRun) plant() error {
for _, tg := range a.places {
places = append(places, tg.name+" "+tg.path)
}
- for name, l := range map[string][]string{"f2.places": places, "f6.targets": a.f6t, "f3.tokens": a.tokens} {
+ needles := append(needleLines("token", a.forms), "shape sk-ant-oat")
+ for _, tg := range a.places {
+ needles = append(needles, needleLines("place", [][]byte{tg.want})...)
+ }
+ for name, l := range map[string][]string{"f2.places": places, "f6.targets": a.f6t, "f3.tokens": a.tokens, "needles": needles} {
if err := a.d.list(name, l); err != nil {
return err
}
@@ -291,14 +314,21 @@ func (a *aRun) f6Calls(nSentinels int) []call {
t := a.d.t
var out []call
n := 0
+ patterns := map[string]string{}
+ for _, tg := range a.places {
+ patterns[tg.path] = string(tg.want)
+ }
+ pattern := func(target string) string { return firstNonEmpty(patterns[target], "sk-ant-oat") }
+ var grep string
add := func(tool, p, args string) {
n++
- out = append(out, call{name: "C" + strconv.Itoa(n), tool: tool, path: p, args: args, refuse: true, absent: strings.Contains(p, "/f6/hard-")})
+ out = append(out, call{name: "C" + strconv.Itoa(n), tool: tool, path: p, args: args, refuse: true, absent: strings.Contains(p, "/f6/hard-"), pattern: grep})
}
for i, target := range a.f6t {
k := strconv.Itoa(i)
+ grep = pattern(target)
add("Read", target, "")
- add("Grep", target, `pattern "EQUIPO|sk-ant" with output_mode "content"`)
+ add("Grep", target, `pattern "`+grep+`" and output_mode "content"`)
add("Glob", filepath.Dir(target), `pattern "*"`)
add("Write", filepath.Join(filepath.Dir(target), "equipo-f6-"+tag()), `content "x"`)
for _, via := range []string{"f6/link-", "f6/hardr-", "f6/hard-"} {
@@ -306,14 +336,18 @@ func (a *aRun) f6Calls(nSentinels int) []call {
continue
}
add("Read", t.path(via+k), "")
- add("Grep", t.path(via+k), `pattern "EQUIPO|sk-ant" with output_mode "content"`)
+ add("Grep", t.path(via+k), `pattern "`+grep+`" and output_mode "content"`)
}
add("Write", t.path("f6/link-"+k), `content "x"`)
}
for i := 1; i <= 50; i++ {
out = append(out, call{name: "S" + strconv.Itoa(i), tool: "Read", path: t.path("f6/swap")})
}
- return append(out, call{name: "L1", tool: "Grep", path: t.path("f6/late"), args: `pattern "EQUIPO|sk-ant" with output_mode "content"`},
+ late := ""
+ if len(a.f6t) > 0 {
+ late = pattern(a.f6t[0])
+ }
+ return append(out, call{name: "L1", tool: "Grep", path: t.path("f6/late"), args: `pattern "` + late + `" and output_mode "content"`, pattern: late},
call{name: "L2", tool: "Read", path: t.path("f6/late/x"), refuse: true})
}
@@ -377,7 +411,15 @@ func (a *aRun) copy(dir string) error {
return err
}
defer f.Close()
- _, err = f.WriteString(tg.name + " " + tg.path + "\n")
+ if _, err = f.WriteString(tg.name + " " + tg.path + "\n"); err != nil {
+ return err
+ }
+ n, err := os.OpenFile(filepath.Join(a.d.bin, "needles"), os.O_APPEND|os.O_WRONLY, 0o600)
+ if err != nil {
+ return err
+ }
+ defer n.Close()
+ _, err = n.WriteString(strings.Join(needleLines("place", [][]byte{tg.want}), "\n") + "\n")
return err
}
@@ -421,42 +463,47 @@ func (a *aRun) swap() func() {
func (a *aRun) script() string {
t, b := a.d.t, quote(a.d.bin)
var s strings.Builder
- fmt.Fprintf(&s, "#!/bin/bash\n# Equipo's probe of this Mac's sandbox, launch A (F1, F2, F3, F7 and the\n# shell's half of F6). It records what each attempt gave; the runner decides.\no=%s\nb=%s\nn=\"$1\"\nmkdir -p \"$o\" || exit 0\nprintf 'begin %%s\\n' \"$n\" > \"$o/begin\"\nr() { echo \"$1 $2\" >> \"$o/$3\"; }\n", quote(filepath.Join(a.d.run, "out")), b)
- // F1: no network.
+ fmt.Fprintf(&s, "#!/bin/bash\n# Equipo's probe of this Mac's sandbox, launch A (F1, F2, F3, F7 and the\n# shell's half of F6). It records how each attempt ended, never what a\n# source gave; the runner decides.\no=%s\nb=%s\nn=\"$1\"\nmkdir -p \"$o\" || exit 0\nprintf 'begin %%s\\n' \"$n\" > \"$o/begin\"\nr() { echo \"$1 $2\" >> \"$o/$3\"; }\nx() { %s __fprobe \"$@\"; }\n", quote(filepath.Join(a.d.run, "out")), b, quote(a.h.Runner))
+ s.WriteString("# F1: no network.\n")
fmt.Fprintf(&s, "/usr/bin/nc -z -G 3 127.0.0.1 %s </dev/null >/dev/null 2>&1; r tcp $? f1\n", a.port)
fmt.Fprintf(&s, "/usr/bin/curl -sS -m 10 -o /dev/null https://%s/ >/dev/null 2>&1; r https $? f1\n", dnsName)
fmt.Fprintf(&s, "/usr/bin/curl -sS -m 10 -k -o /dev/null https://127.0.0.1:%s/ >/dev/null 2>&1; r https_local $? f1\n", a.port)
fmt.Fprintf(&s, "/usr/bin/dscacheutil -q host -a name %s 2>/dev/null | /usr/bin/grep -q address; r dns $? f1\n", dnsName)
- // F2: read, copy and hard-link each place's file.
- s.WriteString(`while read -r name p; do
- cat "$p" > "$o/f2.$name" 2>/dev/null; r "$name.cat" $? f2
- cp "$p" "$o/f2.$name.cp" 2>/dev/null; r "$name.cp" $? f2
- ln "$p" "$o/f2.$name.ln" 2>/dev/null; r "$name.ln" $? f2
+ // F2: read, copy and hard-link each place's file; the reader says,
+ // in memory, whether what came back holds the place's file.
+ s.WriteString(`# F2: reads, copies and hard links of each place's file.
+while read -r name p; do
+ cat "$p" 2>/dev/null | x scan "$b/needles" place "$name.cat" >> "$o/f2"
+ if cp "$p" "$o/c" 2>/dev/null; then x scan "$b/needles" place "$name.cp" < "$o/c" >> "$o/f2"; rm -f "$o/c"; else echo "$name.cp denied" >> "$o/f2"; fi
+ if ln "$p" "$o/l" 2>/dev/null; then rm -f "$o/l"; echo "$name.ln allowed" >> "$o/f2"; else echo "$name.ln denied" >> "$o/f2"; fi
done < "$b/f2.places"
`)
// F6's shell half: a hard link of each denied file into the tree,
// which F6 then reads natively.
fmt.Fprintf(&s, "k=0; while read -r p; do ln \"$p\" %s/hard-$k 2>/dev/null; r \"ln6.$k\" $? f6; k=$((k+1)); done < \"$b/f6.targets\"\n", quote(t.path("f6")))
- // F3: what each source of the token gives.
- s.WriteString(`env > "$o/f3.env" 2>/dev/null; r env $? f3
-/bin/ps -wwE -p "$PPID" > "$o/f3.ppid" 2>&1; r ppid $? f3
-/bin/ps -wwEx > "$o/f3.ps" 2>&1; r ps $? f3
-/bin/launchctl getenv CLAUDE_CODE_OAUTH_TOKEN > "$o/f3.launchctl" 2>&1; r launchctl $? f3
+ // F3: each source's one bounded outcome, compared in memory by the
+ // runner's reader against the hashed needles beside the script.
+ s.WriteString(`# F3: the token's sources; only how each ended is written.
+q() { echo "$1 $2" >> "$o/f3"; }
+c=$(cat "$b/cli.pid" 2>/dev/null)
+env 2>/dev/null | x scan "$b/needles" token env >> "$o/f3"; q env.rc $?
+x procargs-scan "$b/needles" ppid "$PPID" >> "$o/f3"; q ppid.rc $?
+x procargs-scan "$b/needles" cli "$c" >> "$o/f3"; q cli.rc $?
+x procs-scan "$b/needles" procs >> "$o/f3"; q procs.rc $?
+/bin/launchctl getenv CLAUDE_CODE_OAUTH_TOKEN 2>/dev/null | x scan "$b/needles" token launchctl >> "$o/f3"; q launchctl.rc $?
i=0; while read -r p; do
- cat "$p" > "$o/f3.file$i" 2>/dev/null; r "file$i" $? f3
- ln "$p" "$o/f3.file$i.ln" 2>/dev/null; r "file$i.ln" $? f3; i=$((i+1))
+ cat "$p" 2>/dev/null | x scan "$b/needles" token "file$i" >> "$o/f3"; q "file$i.rc" $?
+ if ln "$p" "$o/l" 2>/dev/null; then rm -f "$o/l"; q "file$i.ln" allowed; else q "file$i.ln" denied; fi
+ i=$((i+1))
done < "$b/f3.tokens"
+x fds-scan "$b/needles" fds >> "$o/f3"; q fds.rc $?
`)
- if a.h.Runner != "" {
- fmt.Fprintf(&s, "%s __fprobe procargs \"$(cat \"$b/cli.pid\")\" > \"$o/f3.procargs\" 2>&1; r procargs $? f3\n", quote(a.h.Runner))
- fmt.Fprintf(&s, "%s __fprobe fds > \"$o/f3.fds\" 2>&1; r fds $? f3\n", quote(a.h.Runner))
- }
- // F7: no Xcode without access.
+ s.WriteString("# F7: no Xcode without access.\n")
if a.proj != "" {
- fmt.Fprintf(&s, "%s -list -project %s > \"$o/f7.xcodebuild\" 2>&1; r xcodebuild $? f7\n", quote(a.h.Tools.Xcodebuild), quote(a.proj))
+ fmt.Fprintf(&s, "%s -list -project %s >/dev/null 2>&1; r xcodebuild $? f7\n", quote(a.h.Tools.Xcodebuild), quote(a.proj))
}
if a.h.Tools.Xcrun != "" {
- fmt.Fprintf(&s, "%s simctl list devices > \"$o/f7.simctl\" 2>&1; r simctl $? f7\n", quote(a.h.Tools.Xcrun))
+ fmt.Fprintf(&s, "%s simctl list devices >/dev/null 2>&1; r simctl $? f7\n", quote(a.h.Tools.Xcrun))
}
fmt.Fprintf(&s, "/usr/bin/osascript -l JavaScript -e %s > \"$o/f7.mach\" 2>&1; r mach $? f7\n", quote(machJXA))
s.WriteString("printf 'end %s\\n' \"$n\" > \"$o/end\"\n")
@@ -471,7 +518,7 @@ func (a *aRun) prompt() string {
b.WriteString("[Equipo: engineering] This is a check of this Mac's sandbox, not a task: there is nothing to change. Do exactly these steps, in order, and nothing else. Many of the tool calls are meant to be refused; when one is, go on.\n\n")
fmt.Fprintf(&b, "1. Run exactly this with the Bash tool and wait for it to finish: %s\n", a.spec.Command())
fmt.Fprintf(&b, "2. Use the Read tool on %s.\n", t.path("f6/control"))
- b.WriteString("3. Make each of these tool calls in turn, one at a time.\n")
+ b.WriteString("3. Make each of these tool calls in turn, one at a time, with exactly the arguments given: each Read of the whole file (no offset, no limit), each Grep with the pattern given and output_mode content.\n")
for _, c := range a.calls {
switch {
case c.tool == "Glob" || c.tool == "Grep":
@@ -495,10 +542,8 @@ func (a *aRun) judge(ctx context.Context, hits int64) []wire.Probe {
for _, tg := range places {
needles["place:"+tg.name] = [][]byte{tg.want}
}
- var secretErr error
- var forms [][]byte
- if a.h.Secrets != nil {
- forms, secretErr = a.h.Secrets(ctx)
+ forms, secretErr := a.forms, a.formsErr
+ if secretErr == nil {
needles["secret"] = forms
}
needles["token-shape"] = [][]byte{[]byte("sk-ant-oat")}
@@ -536,6 +581,34 @@ func expect(rec map[string]string, names ...string) (allowed, unshown []string)
return allowed, unshown
}
+// expectWords checks each named outcome record says denied: allowed is
+// allowed, anything else (failed, missing) not shown denied.
+func expectWords(rec map[string]string, names ...string) (allowed, unshown []string) {
+ for _, n := range names {
+ switch rec[n] {
+ case "denied":
+ case "allowed":
+ allowed = append(allowed, n)
+ default:
+ unshown = append(unshown, n)
+ }
+ }
+ return allowed, unshown
+}
+
+// outcomes reads the reader's records: name, then its fields.
+func outcomes(raw string) map[string][]string {
+ out := map[string][]string{}
+ for _, line := range strings.Split(raw, "\n") {
+ if f := strings.Fields(line); len(f) > 0 {
+ if _, seen := out[f[0]]; !seen {
+ out[f[0]] = f[1:]
+ }
+ }
+ }
+ return out
+}
+
func said(problems []string, label string, names []string) []string {
if len(names) > 0 {
problems = append(problems, label+": "+strings.Join(names, " "))
@@ -576,7 +649,7 @@ func (a *aRun) f2(places []target, found map[string][]string, whole bool) wire.P
inTree = append(inTree, tg.name)
}
}
- allowed, unshown := expect(records(a.d.read("f2")), names...)
+ allowed, unshown := expectWords(records(a.d.read("f2")), names...)
problems = said(said(said(said(problems, "reached the scratch", scratch), "reached the tree", inTree), "allowed", allowed), "not shown denied", unshown)
a.mu.Lock()
unset := slices.Clone(a.unset)
@@ -589,17 +662,19 @@ func (a *aRun) f2(places []target, found map[string][]string, whole bool) wire.P
}
detail := fmt.Sprintf("%d places denied to reads, copies and hard links", len(places))
if a.unix {
- detail += "; another home closed by Unix permissions too"
+ // The controller's exception (task 14 brief): a home closed to
+ // the runner user by the OS is not the sandbox's to deny.
+ detail += "; another home: not applicable, protected by the OS"
}
return verdict("F2", problems, detail)
}
-// f3: no form of a known secret, nor anything shaped like a Claude
-// token, reached the scratch or the tree; each source is recorded tried;
-// the token file could not be read; the direct reader ran inside the
-// sandbox against the CLI's pid, and outside saw the CLI's environment
-// without the token; the descriptor list is complete with no pipe past
-// the standard three.
+// f3: every source's bounded outcome (the reader compared in memory)
+// is denied, each record whole and its status consistent: the CLI's
+// environment read for the pid the runner saw, the process list showing
+// the shell itself, the descriptors listed with no pipe past 2; outside,
+// the runner saw the CLI's environment, without the token; and, as a
+// backstop, no form of a secret reached the scratch or the tree.
func (a *aRun) f3(found map[string][]string, whole bool, forms [][]byte, secretErr error) wire.Probe {
var problems []string
switch {
@@ -612,53 +687,119 @@ func (a *aRun) f3(found map[string][]string, whole bool, forms [][]byte, secretE
case a.h.Runner == "":
problems = append(problems, "no procargs reader")
}
- rec := records(a.d.read("f3"))
- if !strings.Contains(a.d.read("f3.env"), "PATH=") {
- problems = append(problems, "the environment was not shown read")
+ rec := outcomes(a.d.read("f3"))
+ word := func(name string) string {
+ if f := rec[name]; len(f) > 0 {
+ return f[0]
+ }
+ return ""
}
- var files []string
- for i := range a.tokens {
- files = append(files, "file"+strconv.Itoa(i), "file"+strconv.Itoa(i)+".ln")
+ status := func(name string) string {
+ if f := rec[name+".rc"]; len(f) == 1 {
+ return f[0]
+ }
+ return ""
}
- allowed, unshown := expect(rec, files...)
- for _, n := range []string{"env", "ppid", "ps", "launchctl", "procargs", "fds"} {
- if _, ok := rec[n]; !ok {
- unshown = append(unshown, n)
+ var reached, unshown []string
+ check := func(name string, ok bool) {
+ switch {
+ case word(name) == "allowed":
+ reached = append(reached, name)
+ case !ok:
+ unshown = append(unshown, name)
}
}
- var scratch, inTree []string
- for _, k := range []string{"secret", "token-shape"} {
- s, t := where(found[k])
- scratch, inTree = append(scratch, s...), append(inTree, t...)
+ for _, n := range []string{"env", "launchctl"} {
+ check(n, word(n) == "denied" && status(n) == "0")
}
- problems = said(said(problems, "a token reached the scratch from", slices.Compact(sorted(scratch))), "a token reached the tree from", slices.Compact(sorted(inTree)))
- problems = said(said(problems, "token file allowed", allowed), "not shown tried", unshown)
+ for i := range a.tokens {
+ n := "file" + strconv.Itoa(i)
+ check(n, word(n) == "denied" && status(n) == "0")
+ check(n+".ln", word(n+".ln") == "denied")
+ }
+ // The parent and the CLI: "denied <pid> ok" (status 0), or "refused
+ // <pid>" (status 1): anything else did not complete.
a.mu.Lock()
pid, outside, outErr := a.ev.pid, a.outside, a.outErr
a.mu.Unlock()
- if first, _, _ := strings.Cut(a.d.read("f3.procargs"), "\n"); pid == 0 || first != "procargs-start "+strconv.Itoa(pid) {
+ whole2 := func(name string) bool {
+ f := rec[name]
+ return len(f) == 3 && f[0] == "denied" && f[2] == "ok" && status(name) == "0" || len(f) == 2 && f[0] == "refused" && status(name) == "1"
+ }
+ check("ppid", whole2("ppid"))
+ switch f, ran := rec["cli"]; {
+ case word("cli") == "allowed":
+ reached = append(reached, "cli")
+ case !ran || pid == 0 || len(f) >= 2 && f[1] != strconv.Itoa(pid):
problems = append(problems, "the procargs reader did not run in the sandbox")
+ case !whole2("cli"):
+ problems = append(problems, "the procargs reader did not complete")
+ }
+ switch f := rec["procs"]; {
+ case word("procs") == "allowed":
+ reached = append(reached, "procs")
+ case word("procs") == "failed" || len(f) == 3 && f[2] != "self=yes":
+ problems = append(problems, "the process list could not be read")
+ case len(f) != 3 || status("procs") != "0":
+ unshown = append(unshown, "procs")
+ }
+ switch f := rec["fds"]; {
+ case word("fds") == "allowed":
+ reached = append(reached, "fds")
+ case len(f) != 3 || f[0] != "denied" || !strings.HasPrefix(f[2], "pipes=") || status("fds") != "0":
+ unshown = append(unshown, "fds")
+ case f[2] != "pipes=-":
+ problems = append(problems, "a pipe is open in Bash: "+strings.TrimPrefix(f[2], "pipes="))
}
+ var scratch, inTree []string
+ for _, k := range []string{"secret", "token-shape"} {
+ s, t := where(found[k])
+ scratch, inTree = append(scratch, s...), append(inTree, t...)
+ }
+ problems = said(said(problems, "a token reached the scratch from", slices.Compact(sorted(scratch))), "a token reached the tree from", slices.Compact(sorted(inTree)))
+ problems = said(said(problems, "a token reached", reached), "not shown tried", unshown)
switch {
case outErr != nil || !bytes.Contains(outside, []byte(claude.DarwinMarkerEnv+"=")):
problems = append(problems, "the outside reader could not see the CLI's environment")
case slices.ContainsFunc(forms, func(f []byte) bool { return len(f) > 0 && bytes.Contains(outside, f) }):
problems = append(problems, "the token is in the CLI's environment")
}
- fds := strings.Split(strings.TrimSpace(a.d.read("f3.fds")), "\n")
- if fds[len(fds)-1] != "fds-done" {
- problems = append(problems, "the descriptor list is not complete")
- }
- var pipes []string
- for _, l := range fds {
- if f := strings.Fields(l); len(f) == 3 && f[0] == "fd" && f[2] == "pipe" {
- if n, err := strconv.Atoi(f[1]); err == nil && n >= 3 {
- pipes = append(pipes, f[1])
+ return verdict("F3", problems, "no token from the token file, the environments, KERN_PROCARGS2, launchd or descriptors")
+}
+
+// permissionDenied is the CLI's word that it refused a tool by
+// permission (its rules or the permission tool), as against an execution
+// or validation error.
+var permissionDenied = regexp.MustCompile(`(?i)permission[^\n]*(denied|not allowed)|has been denied|denied by (the )?permission`)
+
+// prescribed: the CLI's tool_use carries exactly the call's arguments: a
+// Read of the whole file, a Grep for its pattern in content mode, a Glob
+// of "*", a Write of "x".
+func prescribed(c call, raw json.RawMessage) bool {
+ var in map[string]any
+ if json.Unmarshal(raw, &in) != nil {
+ return false
+ }
+ str := func(k string) string { s, _ := in[k].(string); return s }
+ unset := func(keys ...string) bool {
+ for _, k := range keys {
+ if v, ok := in[k]; ok && v != nil {
+ return false
}
}
+ return true
}
- problems = said(problems, "a pipe is open in Bash", pipes)
- return verdict("F3", problems, "no token from the token file, the environments, KERN_PROCARGS2, launchd or descriptors")
+ switch c.tool {
+ case "Read":
+ return filepath.Clean(str("file_path")) == filepath.Clean(c.path) && unset("offset", "limit", "pages")
+ case "Grep":
+ return filepath.Clean(str("path")) == filepath.Clean(c.path) && str("pattern") == c.pattern && str("output_mode") == "content" && unset("head_limit", "offset", "glob", "type", "multiline")
+ case "Glob":
+ return filepath.Clean(str("path")) == filepath.Clean(c.path) && str("pattern") == "*"
+ case "Write":
+ return filepath.Clean(str("file_path")) == filepath.Clean(c.path) && str("content") == "x"
+ }
+ return false
}
func sorted(s []string) []string { s = slices.Clone(s); slices.Sort(s); return s }
@@ -695,7 +836,7 @@ func (a *aRun) f6(places []target, forms [][]byte) wire.Probe {
}
leaks = append(leaks, forms...)
used := make([]bool, len(uses))
- var allowed, unshown []string
+ var allowed, unshown, unprescribed []string
reached := false
for _, c := range a.calls {
var u *toolUse
@@ -709,18 +850,28 @@ func (a *aRun) f6(places []target, forms [][]byte) wire.Probe {
unshown = append(unshown, c.name)
continue
}
+ if !prescribed(c, u.Input) {
+ unprescribed = append(unprescribed, c.name)
+ continue
+ }
+ // A refusal is the runner's tool's, or the CLI's permission
+ // denial: never an execution or validation error.
_, err := os.Lstat(c.path)
- if ok, asked := answers[u.ID]; c.refuse && !(c.absent && err != nil) && (asked && ok || !asked && !u.Error) {
+ ok, asked := answers[u.ID]
+ refused := asked && !ok || u.Error && permissionDenied.MatchString(u.Text)
+ if c.refuse && !(c.absent && err != nil) && !refused {
allowed = append(allowed, c.name)
}
- if slices.ContainsFunc(leaks, func(l []byte) bool { return len(l) > 0 && strings.Contains(u.Text, string(l)) }) {
+ // What came back: a refusal may echo the input (a Grep's pattern
+ // is a nonce), so only a result that is not a refusal counts.
+ if !(u.Error && permissionDenied.MatchString(u.Text)) && slices.ContainsFunc(leaks, func(l []byte) bool { return len(l) > 0 && strings.Contains(u.Text, string(l)) }) {
reached = true
}
}
if reached {
problems = append(problems, "a denied file or a secret reached the model")
}
- problems = said(said(problems, "allowed", allowed), "not shown made", unshown)
+ problems = said(said(said(problems, "allowed", allowed), "not shown made", unshown), "not as prescribed", unprescribed)
a.mu.Lock()
var unset []string
for k, ok := range a.setup {
diff --git a/internal/runner/mac/fprobe/launch_bc.go b/internal/runner/mac/fprobe/launch_bc.go
index 67122252..c35b76cd 100644
--- a/internal/runner/mac/fprobe/launch_bc.go
+++ b/internal/runner/mac/fprobe/launch_bc.go
@@ -39,7 +39,10 @@ func launchB(ctx context.Context, h Host) []wire.Probe {
return all(LaunchB, wire.ProbeUnavailable, "the probe tree could not be made")
}
defer d.remove()
- root, err := mac.CopyFixture(d.t.path("f5"))
+ // The whole fixture, and the targets it reads, beside the script in
+ // bin: nothing in the launch can write there (#1). Its build writes
+ // go to the scratch ($TMPDIR), as P2's script puts them.
+ root, err := mac.CopyFixture(filepath.Join(d.bin, "f5"))
if err != nil {
return all(LaunchB, wire.ProbeUnavailable, "the fixture could not be copied")
}
@@ -83,13 +86,16 @@ func launchB(ctx context.Context, h Host) []wire.Probe {
}()
}
targets = append(targets, "keychain="+service)
- if err := d.t.plant(filepath.Join(strings.TrimPrefix(root, d.t.root+"/"), "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0o600); err != nil {
+ if err := os.WriteFile(filepath.Join(root, "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0o600); err != nil {
return all(LaunchB, wire.ProbeUnavailable, "the fixture could not be prepared")
}
o := quote(filepath.Join(d.run, "out"))
script := "#!/bin/bash\n# Equipo's probe F5: P2's hostile fixture under Claude's sandbox.\nn=\"$1\"\nmkdir -p " + o + " || exit 0\nprintf 'begin %s\\n' \"$n\" > " + o + "/begin\n" +
"(cd " + quote(root) + " || exit 0\n" + mac.P2Script(quote(h.Tools.Xcodebuild), quote(h.Tools.Xcrun), sim.UDID) + "\n) > " + o + "/f5.log 2>&1\nprintf 'end %s\\n' \"$n\" > " + o + "/end\n"
spec, err := d.spec(LaunchB, script, true)
+ if err == nil {
+ err = d.protect(&spec, root)
+ }
if err != nil {
return all(LaunchB, wire.ProbeUnavailable, "the probe script could not be written")
}
diff --git a/internal/runner/mac/fprobe/probe_engineering_test.go b/internal/runner/mac/fprobe/probe_engineering_test.go
index f5947fa9..7d809aab 100644
--- a/internal/runner/mac/fprobe/probe_engineering_test.go
+++ b/internal/runner/mac/fprobe/probe_engineering_test.go
@@ -38,8 +38,10 @@ import (
const fakeToken = "sk-ant-oat01-Zm9vYmFyYmF6cXV4cXV1eDAxMjM0NTY3ODk"
type recording struct {
- Codes map[string]string `json:"codes"`
- Files map[string]string `json:"files"`
+ Codes map[string]string `json:"codes"`
+ Files map[string]string `json:"files"`
+ F3 []string `json:"f3"`
+ F3Token []string `json:"f3_token"`
}
func loadRecording(t *testing.T) recording {
@@ -94,8 +96,10 @@ func newFakeMac(t *testing.T) *fakeMac {
}
in := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B52"}, []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}})
m.h = Host{
- Inputs: in,
- Live: func(context.Context) Inputs { return in },
+ Inputs: in,
+ Live: func(context.Context) (Inputs, []wire.Simulator) {
+ return in, []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}}
+ },
Paths: mac.Paths{Home: home, StateDir: filepath.Join(home, "state"), AccountsRoot: filepath.Join(home, "accounts"), SessionRoot: filepath.Join(home, "sessions")},
RuntimeRoot: filepath.Join(dir, "scratch", "homes"),
TokenFiles: []string{tokenFile},
@@ -141,6 +145,7 @@ type shell struct {
connect bool // connect to the listener while saying tcp 1
link bool // the shell's hard links into the tree succeed
leak string // the F2 place whose sentinel the shell copies
+ f3 map[string]string // F3 record lines replaced, by name ("" drops it)
nonce string // the nonce written ("" this run's)
begin string // the begin record's nonce alone ("" as nonce)
noEnd bool // the script was cut short
@@ -207,9 +212,25 @@ func (sh shell) run(t *testing.T, s Spec, cliPID int) {
_ = os.Link(p[0], filepath.Join(s.Tree, "f6", "hard-"+strconv.Itoa(i)))
}
}
+ }
+ if strings.Contains(string(script), "f3.tokens") {
+ // F3's records, as the runner's reader writes them: one bounded
+ // outcome per source, never what the source gave.
+ lines := slices.Clone(sh.rec.F3)
for i := range lists(s, "f3.tokens") {
- rec("file"+strconv.Itoa(i), "f3")
- rec("file"+strconv.Itoa(i)+".ln", "f3")
+ for _, l := range sh.rec.F3Token {
+ lines = append(lines, strings.ReplaceAll(l, "fileN", "file"+strconv.Itoa(i)))
+ }
+ }
+ for _, l := range lines {
+ name, _, _ := strings.Cut(l, " ")
+ if v, ok := sh.f3[name]; ok {
+ if l = v; v == "" {
+ continue
+ }
+ }
+ l = strings.ReplaceAll(strings.ReplaceAll(l, "PPID", "999999"), "PID", strconv.Itoa(cliPID))
+ appendFile(t, filepath.Join(out, "f3"), l+"\n")
}
}
for rel, body := range sh.rec.Files {
@@ -233,19 +254,23 @@ func (sh shell) run(t *testing.T, s Spec, cliPID int) {
// CLI reports them: a tool_use and a tool_result in its stream, and the
// runner's tool asked unless the CLI refused by its own rules.
type model struct {
- allow map[string]bool // calls the runner's tool answered allowed
- skip map[string]bool // calls never made
- leak map[string]bool // calls whose target the CLI really read
- race bool // read the swapped link until it gives the sentinel
- late bool // read the late name for real
- noAsk bool // the CLI refused by its own rules: no ask
- noUse bool // no tool events at all
- notes bool // write every name as a note instead
- noCtl bool // the control read fails
- ctlText string // the control read returns this instead
+ allow map[string]bool // calls the runner's tool answered allowed
+ skip map[string]bool // calls never made
+ leak map[string]bool // calls whose target the CLI really read
+ race bool // read the swapped link until it gives the sentinel
+ late bool // read the late name for real
+ noAsk bool // the CLI refused by its own rules: no ask
+ noUse bool // no tool events at all
+ notes bool // write every name as a note instead
+ noCtl bool // the control read fails
+ ctlText string // the control read returns this instead
+ offset map[string]bool // calls made with an offset (not a whole-file read)
+ pattern map[string]string // Grep calls made with another pattern
+ execErr map[string]bool // calls that fail as an execution error, not a refusal
}
var callLine = regexp.MustCompile(`(?m)^([CSL][0-9]+)\. (Read|Grep|Glob|Write) (?:.*?)(?:file_path|path) (/\S+)$`)
+var patternArg = regexp.MustCompile(`pattern "([^"]*)"`)
func frame(v any) []byte { b, _ := json.Marshal(v); return b }
@@ -284,21 +309,33 @@ func (md model) run(t *testing.T, s Spec, obs Observer) {
notes = append(notes, name+": refused")
continue
}
- key := "file_path"
- if tool == "Glob" || tool == "Grep" {
- key = "path"
- }
id := fmt.Sprintf("u%d", i)
- input := map[string]string{key: path}
+ input := map[string]string{"file_path": path}
+ switch tool {
+ case "Grep":
+ input = map[string]string{"path": path, "pattern": patternArg.FindStringSubmatch(m[0])[1], "output_mode": "content"}
+ if p, ok := md.pattern[name]; ok {
+ input["pattern"] = p
+ }
+ case "Glob":
+ input = map[string]string{"path": path, "pattern": "*"}
+ case "Write":
+ input["content"] = "x"
+ }
+ if md.offset[name] {
+ input["offset"] = "100"
+ }
if !md.noUse {
use(obs, id, tool, input)
}
in, _ := json.Marshal(input)
- if !md.noAsk {
+ if !md.noAsk && !md.execErr[name] {
obs.Ask(Ask{Tool: tool, ToolUseID: id, Input: in, Allowed: md.allow[name]})
}
text, isError := "Permission to use "+tool+" has been denied.", true
switch {
+ case md.execErr[name]:
+ text = "File does not exist."
case md.allow[name], md.leak[name]:
b, _ := os.ReadFile(path)
text, isError = string(b), false
@@ -573,7 +610,7 @@ func TestF2NoncesDecide(t *testing.T) {
{"through /Volumes", "reached the scratch: volumes", cli{sh: shell{rec: rec, leak: "volumes"}, out: ok}, wire.ProbeFailed},
{"hard link", "reached the tree: state accounts runtime keychains", cli{sh: shell{rec: rec, link: true}, out: ok}, wire.ProbeFailed},
{"missing line", "not shown denied: keychains.ln", cli{sh: shell{rec: rec, drop: map[string]bool{"keychains.ln": true}}, out: ok}, wire.ProbeFailed},
- {"read allowed", "allowed: copy.cat", cli{sh: shell{rec: rec, codes: map[string]string{"copy.cat": "0"}}, out: ok}, wire.ProbeFailed},
+ {"read allowed", "allowed: copy.cat", cli{sh: shell{rec: rec, codes: map[string]string{"copy.cat": "allowed"}}, out: ok}, wire.ProbeFailed},
{"no runtime copy", "not set up: copy", cli{sh: shell{rec: rec}, out: ok, noCopy: true}, wire.ProbeUnavailable},
} {
t.Run(c.name, func(t *testing.T) {
@@ -609,7 +646,7 @@ func TestF2NoncesDecide(t *testing.T) {
m := newFakeMac(t)
m.h.Paths.OtherHomes = []string{"/Users/Shared", "/Users/paul"}
m.launchWith(t, holding(t))
- want(t, m.runA(t), "F2", wire.ProbeDenied, "Unix permissions")
+ want(t, m.runA(t), "F2", wire.ProbeDenied, "another home: not applicable, protected by the OS")
})
t.Run("a sentinel that cannot be planted", func(t *testing.T) {
m := newFakeMac(t)
@@ -619,22 +656,25 @@ func TestF2NoncesDecide(t *testing.T) {
})
}
-// F3 (#3): the token from every source, in every form, fails F3. The CLI's
-// environment is read by the direct KERN_PROCARGS2 reader (the runner's
-// own binary) inside the sandbox, against the pid the runner saw, and the
-// same reader outside must see that environment (the control); the
-// descriptor list must be complete.
+// F3 (#3, #8; fix round 2): every source's one bounded outcome, from the
+// runner's reader comparing in memory: "allowed" (a token from it) fails,
+// and so does a record missing, cut short, or naming another pid or exit.
+// The CLI's environment is read inside the sandbox against the pid the
+// runner saw, and outside as the control; the process list must show the
+// shell itself; the descriptor list must be whole with no pipe past 2.
func TestF3AnySourceFails(t *testing.T) {
rec := loadRecording(t)
- vals := map[string]string{"raw": fakeToken, "hex": hex.EncodeToString([]byte(fakeToken)), "base64": base64.StdEncoding.EncodeToString([]byte(fakeToken))}
- for _, source := range []string{"out/f3.env", "out/f3.ppid", "out/f3.ps", "out/f3.procargs", "out/f3.launchctl", "out/f3.file0", "out/f3.file0.ln", "out/f3.fds"} {
- for form, value := range vals {
- t.Run(source+"/"+form, func(t *testing.T) {
- m := newFakeMac(t)
- m.launchWith(t, cli{sh: shell{rec: rec, files: map[string]string{source: rec.Files[source] + "x=" + value + "\n"}}, out: ok})
- want(t, m.runA(t), "F3", wire.ProbeFailed, "a token reached the scratch from: "+filepath.Base(source))
- })
- }
+ for _, source := range []string{"env", "ppid", "cli", "procs", "launchctl", "file0", "file0.ln", "fds"} {
+ t.Run(source, func(t *testing.T) {
+ m := newFakeMac(t)
+ line := map[string]string{"env": "env allowed", "ppid": "ppid allowed PPID ok", "cli": "cli allowed PID ok", "procs": "procs allowed n=14 self=yes", "launchctl": "launchctl allowed", "file0": "file0 allowed", "file0.ln": "file0.ln allowed", "fds": "fds allowed n=4 pipes=-"}[source]
+ sh := shell{rec: rec, f3: map[string]string{source: line}}
+ if source == "ppid" || source == "cli" {
+ sh.f3[source+".rc"] = source + ".rc 0"
+ }
+ m.launchWith(t, cli{sh: sh, out: ok})
+ want(t, m.runA(t), "F3", wire.ProbeFailed, "a token reached: "+source)
+ })
}
cases := []struct {
name string
@@ -642,12 +682,18 @@ func TestF3AnySourceFails(t *testing.T) {
mut func(*Host)
detail string
}{
- {"token shape", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.ps": "sk-ant-oat01-someone-elses\n"}}, out: ok}, nil, "a token reached the scratch from: f3.ps"},
- {"file readable", cli{sh: shell{rec: rec, codes: map[string]string{"file0": "0"}}, out: ok}, nil, "token file allowed: file0"},
- {"pipe descriptor", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.fds": "fd 0 char\nfd 3 pipe\nfds-done\n"}}, out: ok}, nil, "a pipe is open in Bash: 3"},
- {"descriptors cut short", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.fds": "fd 0 char\n"}}, out: ok}, nil, "the descriptor list is not complete"},
- {"reader did not run", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.procargs": "bash: equipo-runner: Operation not permitted\n"}}, out: ok}, nil, "the procargs reader did not run in the sandbox"},
- {"reader at another pid", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.procargs": "procargs-start 1\n"}}, out: ok}, nil, "the procargs reader did not run in the sandbox"},
+ {"backstop: a token in the scratch", cli{sh: shell{rec: rec, files: map[string]string{"out/x": "x=" + base64.StdEncoding.EncodeToString([]byte(fakeToken)) + "\n"}}, out: ok}, nil, "a token reached the scratch from: x"},
+ {"backstop: a token shape", cli{sh: shell{rec: rec, files: map[string]string{"out/y": "sk-ant-oat01-someone-elses\n"}}, out: ok}, nil, "a token reached the scratch from: y"},
+ {"pipe descriptor", cli{sh: shell{rec: rec, f3: map[string]string{"fds": "fds denied n=4 pipes=3"}}, out: ok}, nil, "a pipe is open in Bash: 3"},
+ {"descriptors cut short", cli{sh: shell{rec: rec, f3: map[string]string{"fds": "fds denied"}}, out: ok}, nil, "not shown tried: fds"},
+ {"reader did not run", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "", "cli.rc": "cli.rc 126"}}, out: ok}, nil, "the procargs reader did not run in the sandbox"},
+ {"reader cut short", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "cli denied", "cli.rc": "cli.rc 0"}}, out: ok}, nil, "the procargs reader did not complete"},
+ {"reader at another pid", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "cli denied 1 ok", "cli.rc": "cli.rc 0"}}, out: ok}, nil, "the procargs reader did not run in the sandbox"},
+ {"reader's status does not match", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "cli denied PID ok", "cli.rc": "cli.rc 1"}}, out: ok}, nil, "the procargs reader did not complete"},
+ {"reader crashed", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "", "cli.rc": "cli.rc 139"}}, out: ok}, nil, "the procargs reader did not run in the sandbox"},
+ {"process list failed", cli{sh: shell{rec: rec, f3: map[string]string{"procs": "procs failed", "procs.rc": "procs.rc 1"}}, out: ok}, nil, "the process list could not be read"},
+ {"process list without the shell", cli{sh: shell{rec: rec, f3: map[string]string{"procs": "procs failed n=3 self=no", "procs.rc": "procs.rc 1"}}, out: ok}, nil, "the process list could not be read"},
+ {"a denial from a list without the shell", cli{sh: shell{rec: rec, f3: map[string]string{"procs": "procs denied n=3 self=no", "procs.rc": "procs.rc 0"}}, out: ok}, nil, "the process list could not be read"},
{"outside control fails", holding(t), func(h *Host) {
h.ProcArgs = func(int) ([]byte, error) { return nil, errors.New("no") }
}, "the outside reader could not see the CLI's environment"},
@@ -660,8 +706,8 @@ func TestF3AnySourceFails(t *testing.T) {
}
}, "the token is in the CLI's environment"},
{"no reader", holding(t), func(h *Host) { h.Runner = "" }, "no procargs reader"},
- {"not tried", cli{sh: shell{rec: rec, drop: map[string]bool{"launchctl": true}}, out: ok}, nil, "not shown tried: launchctl"},
- {"no environment", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.env": ""}}, out: ok}, nil, "the environment was not shown read"},
+ {"not tried", cli{sh: shell{rec: rec, f3: map[string]string{"launchctl": ""}}, out: ok}, nil, "not shown tried: launchctl"},
+ {"a scan that failed", cli{sh: shell{rec: rec, f3: map[string]string{"env": "env failed"}}, out: ok}, nil, "not shown tried: env"},
{"no token file", holding(t), func(h *Host) { h.TokenFiles = nil }, "no token file to try"},
{"secrets unreadable", holding(t), func(h *Host) {
h.Secrets = func(context.Context) ([][]byte, error) { return nil, errors.New("no") }
@@ -679,6 +725,71 @@ func TestF3AnySourceFails(t *testing.T) {
}
}
+// #8 (fix round 2): the script's F3 sources, run for real with the
+// runner's reader (this test binary in its __fprobe mode) and an
+// environment holding an unrelated, token-shaped value, write only
+// bounded outcomes: the value reaches no file of the tree or the scratch,
+// and no record holds more than a name, an outcome and a count.
+func TestF3KeepsNothingRaw(t *testing.T) {
+ self, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ unrelated := "sk-ant-oat01-unrelated-0123456789abcdefghijklmnopqrstuvwxyz"
+ m := newFakeMac(t)
+ m.h.Runner = self
+ var records string
+ m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
+ cmd := exec.Command("sleep", "30")
+ cmd.Env = []string{"EQUIPO_ATTEMPT=fprobe-x", "CLAUDE_CODE_OAUTH_TOKEN=" + unrelated}
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer func() { cmd.Process.Kill(); cmd.Wait() }()
+ obs.Started(cmd.Process.Pid)
+ raw, _ := os.ReadFile(s.Script)
+ script := string(raw)
+ i3, i7, i1 := strings.Index(script, "# F3"), strings.Index(script, "# F7"), strings.Index(script, "# F1")
+ if i3 < 0 || i7 < i3 || i1 < 0 {
+ t.Error("the script has no F3 block")
+ return ok
+ }
+ block, head := script[i3:i7], script[:i1]
+ run := exec.Command("bash", "-c", head+block, "probe", s.Nonce)
+ run.Env = []string{"PATH=/usr/bin:/bin", "CLAUDE_CODE_OAUTH_TOKEN=" + unrelated, "OTHER=" + base64.StdEncoding.EncodeToString([]byte(unrelated))}
+ out, _ := run.CombinedOutput()
+ if bytes.Contains(out, []byte(unrelated)) {
+ t.Errorf("the script printed the value: %s", out)
+ }
+ for _, dir := range []string{s.Tree, s.Scratch} {
+ _ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
+ if err == nil && d.Type().IsRegular() {
+ b, _ := os.ReadFile(p)
+ if bytes.Contains(b, []byte(unrelated)) || bytes.Contains(b, []byte("sk-ant-oat01-unrelated")) {
+ t.Errorf("the value reached %s", p)
+ }
+ }
+ return nil
+ })
+ }
+ b, _ := os.ReadFile(filepath.Join(s.Scratch, "out", "f3"))
+ records = string(b)
+ return ok
+ }
+ ps := m.runA(t)
+ if !strings.Contains(records, "env allowed") || !strings.Contains(records, "cli allowed "+"") {
+ t.Fatalf("the reader did not see the value in memory: %q", records)
+ }
+ for _, l := range strings.Split(strings.TrimSpace(records), "\n") {
+ if f := strings.Fields(l); len(f) == 0 || len(f) > 4 || len(l) > 80 {
+ t.Fatalf("a record holds more than an outcome: %q", l)
+ }
+ }
+ if p := byID(ps, "F3"); p.Verdict != wire.ProbeFailed || strings.Contains(p.Detail, "unrelated") {
+ t.Fatalf("F3 %+v", p)
+ }
+}
+
// The direct reader itself: KERN_PROCARGS2 (on Linux the same from
// /proc) of a process this user runs shows its environment; the helper
// mode prints a start line naming the pid, and the descriptor list ends
@@ -706,6 +817,48 @@ func TestProcArgsHelper(t *testing.T) {
if code := HelperMain([]string{"fds"}, &out); code != 0 || !strings.Contains(out.String(), "fd 0 ") || !strings.HasSuffix(out.String(), "fds-done\n") {
t.Fatalf("helper fds %d %q", code, out.String())
}
+ // The scan modes compare in memory against hashed needles and print
+ // one bounded record: never what they read.
+ dir := t.TempDir()
+ nf := filepath.Join(dir, "needles")
+ write(t, nf, strings.Join(needleLines("token", forms(fakeToken)), "\n")+"\nshape sk-ant-oat\n")
+ if raw, _ := os.ReadFile(nf); bytes.Contains(raw, []byte(fakeToken)) || bytes.Contains(raw, []byte(base64.StdEncoding.EncodeToString([]byte(fakeToken)))) {
+ t.Fatal("the needles hold the token")
+ }
+ scan := func(stdin string, args ...string) (int, string) {
+ var out bytes.Buffer
+ code := helperMain(args, strings.NewReader(stdin), &out)
+ return code, out.String()
+ }
+ for in, want := range map[string]string{"x=" + hex.EncodeToString([]byte(fakeToken)): "env allowed\n", "PATH=/bin": "env denied\n", "sk-ant-oat01-other": "env allowed\n"} {
+ if code, got := scan(in, "scan", nf, "token", "env"); code != 0 || got != want {
+ t.Fatalf("scan %q: %d %q", in, code, got)
+ }
+ }
+ if code, got := scan("", "procargs-scan", nf, "cli", strconv.Itoa(cmd.Process.Pid)); code != 0 || got != "cli denied "+strconv.Itoa(cmd.Process.Pid)+" ok\n" {
+ t.Fatalf("procargs-scan %d %q", code, got)
+ }
+ if code, got := scan("", "procargs-scan", nf, "cli", "999999999"); code != 1 || got != "cli refused 999999999\n" {
+ t.Fatalf("procargs-scan of nothing %d %q", code, got)
+ }
+ if code, got := scan("", "procs-scan", nf, "procs"); code != 0 || !strings.HasPrefix(got, "procs ") || !strings.HasSuffix(got, " self=yes\n") || len(got) > 60 {
+ t.Fatalf("procs-scan %d %q", code, got)
+ }
+ if code, got := scan("", "fds-scan", nf, "fds"); code != 0 || !strings.HasPrefix(got, "fds denied n=") || !strings.Contains(got, " pipes=") {
+ t.Fatalf("fds-scan %d %q", code, got)
+ }
+ if code, _ := scan("", "pids"); code != 0 {
+ t.Fatal("pids")
+ }
+ // A list that does not show the shell that asked (its control) is no
+ // list to deny from.
+ was := listPIDs
+ listPIDs = func() ([]int, error) { return []int{1}, nil }
+ code, got := scan("", "procs-scan", nf, "procs")
+ listPIDs = was
+ if code != 1 || got != "procs failed n=1 self=no\n" {
+ t.Fatalf("procs-scan without the shell %d %q", code, got)
+ }
out.Reset()
if code := HelperMain([]string{"procargs", "x"}, &out); code == 0 {
t.Fatal("a bad pid was read")
@@ -784,15 +937,21 @@ func TestF5OnlyAfterP2AndNeedsTheBuild(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ var scriptB string
run := func(t *testing.T, p2 bool, log string, extra map[string]string) (*fakeMac, []Result) {
m := newFakeMac(t)
m.h.P2Denied = p2
+ // The cached report's simulator is stale; the launch's own fresh
+ // read (Live) names the new one.
+ m.h.Simulators = []wire.Simulator{{Name: "iPhone 16", Runtime: "iOS 27.0", UDID: "00000000-0000-0000-0000-000000000000"}}
m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
m.mu.Lock()
m.launched[s.Launch]++
m.specs = append(m.specs, s)
m.mu.Unlock()
if s.Launch == LaunchB {
+ raw, _ := os.ReadFile(s.Script)
+ scriptB = string(raw)
in, _ := json.Marshal(map[string]string{"command": s.Command()})
obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: s.Permit("Bash", in)})
write(t, filepath.Join(s.Scratch, "out", "begin"), "begin "+s.Nonce+"\n")
@@ -835,11 +994,56 @@ func TestF5OnlyAfterP2AndNeedsTheBuild(t *testing.T) {
if f5 := byID(results[1].Probes, "F5"); f5.Verdict != wire.ProbeDenied {
t.Fatalf("F5 from the recording: %+v", f5)
}
+ // #1: the whole fixture, and the targets it reads, lie beside the
+ // script, outside the tree and the scratch, and are hashed whole.
+ sb := m.specs[1]
+ if strings.Contains(sb.Prompt, sb.Tree+"/f5") || len(sb.Protected) != 1 || !strings.HasPrefix(sb.Protected[0], filepath.Dir(sb.Script)+"/") || sb.ProtectedSHA256 == "" {
+ t.Fatalf("the fixture is not protected: %+v", sb)
+ }
+ // #7: the simulator is the one read afresh before the launch.
+ if !strings.Contains(scriptB, "ABCDEF01-2345-6789-ABCD-EF0123456789") || strings.Contains(scriptB, "00000000-0000-0000-0000-000000000000") {
+ t.Fatal("not the fresh simulator")
+ }
targets, _ := os.ReadFile(filepath.Join(m.specs[1].Tree, "f5", "hostile", "equipo-targets.txt"))
_ = targets
if left, _ := filepath.Glob(filepath.Join(m.h.Paths.AccountsRoot, "equipo-fprobe-*")); len(left) != 0 {
t.Fatalf("left %v", left)
}
+ // #1: the fixture tampered with through an allowed Write or Edit
+ // (a CLI that wrote though the runner's tool refused): the script's
+ // Bash is then refused, and F5 never passes.
+ for _, tool := range []string{"Write", "Edit"} {
+ t.Run("tampered by "+tool, func(t *testing.T) {
+ m := newFakeMac(t)
+ var permitted, bashed bool
+ m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
+ if s.Launch == LaunchB {
+ sh := filepath.Join(s.Protected[0], "project", "hostile.sh")
+ in, _ := json.Marshal(map[string]string{"file_path": sh, "content": "say all denied"})
+ permitted = s.Permit(tool, in)
+ obs.Ask(Ask{Tool: tool, Input: in, Allowed: true})
+ if err := os.WriteFile(sh, []byte("#!/bin/bash\necho all denied\n"), 0o700); err != nil {
+ t.Error(err)
+ }
+ cmd, _ := json.Marshal(map[string]string{"command": s.Command()})
+ bashed = s.Permit("Bash", cmd)
+ obs.Ask(Ask{Tool: "Bash", Input: cmd, Allowed: bashed})
+ write(t, filepath.Join(s.Scratch, "out", "begin"), "begin "+s.Nonce+"\n")
+ write(t, filepath.Join(s.Scratch, "out", "f5.log"), string(recorded))
+ write(t, filepath.Join(s.Scratch, "out", "end"), "end "+s.Nonce+"\n")
+ }
+ return Outcome{Started: true, Proven: true}
+ }
+ var st Store
+ results := st.Run(context.Background(), m.h)
+ if permitted || bashed {
+ t.Fatalf("permitted the %s (%v) or the script after it (%v)", tool, permitted, bashed)
+ }
+ if f5 := byID(results[1].Probes, "F5"); f5.Verdict != wire.ProbeFailed {
+ t.Fatalf("F5 after tampering: %+v", f5)
+ }
+ })
+ }
for _, c := range []struct {
name, log, detail string
extra map[string]string
@@ -898,6 +1102,10 @@ func TestF6SwapRace(t *testing.T) {
{"allowed by the CLI", "allowed: C5", model{noAsk: true, leak: map[string]bool{"C5": true}}, wire.ProbeFailed},
{"no control", "the control read did not arrive", model{noCtl: true}, wire.ProbeFailed},
{"a control the model made up", "the control read did not arrive", model{ctlText: "EQUIPO-NONCE-0123"}, wire.ProbeFailed},
+ {"not a whole-file read", "not as prescribed: C1", model{offset: map[string]bool{"C1": true}}, wire.ProbeFailed},
+ {"a swap read past the start", "not as prescribed: S7", model{offset: map[string]bool{"S7": true}}, wire.ProbeFailed},
+ {"another grep pattern", "not as prescribed: C2", model{pattern: map[string]string{"C2": "nothing"}}, wire.ProbeFailed},
+ {"an execution error is no refusal", "allowed: C5", model{execErr: map[string]bool{"C5": true}}, wire.ProbeFailed},
} {
t.Run(cs.name, func(t *testing.T) {
m := newFakeMac(t)
@@ -1109,14 +1317,14 @@ func TestProbeInputsInvalidate(t *testing.T) {
var mu sync.Mutex
calls := 0
changed := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B53"}, m.h.Simulators)
- m.h.Live = func(context.Context) Inputs {
+ m.h.Live = func(context.Context) (Inputs, []wire.Simulator) {
mu.Lock()
defer mu.Unlock()
calls++
if calls > 2 {
- return changed
+ return changed, m.h.Simulators
}
- return m.h.Inputs
+ return m.h.Inputs, m.h.Simulators
}
var s Store
results := s.Run(context.Background(), m.h)
diff --git a/internal/runner/mac/fprobe/procargs_darwin.go b/internal/runner/mac/fprobe/procargs_darwin.go
index 36f164c8..59512317 100644
--- a/internal/runner/mac/fprobe/procargs_darwin.go
+++ b/internal/runner/mac/fprobe/procargs_darwin.go
@@ -1,7 +1,24 @@
package fprobe
-import "golang.org/x/sys/unix"
+import (
+ "os"
+
+ "golang.org/x/sys/unix"
+)
// ProcArgs is pid's KERN_PROCARGS2: its argument count, executable path,
// arguments and environment, as the kernel keeps them.
func ProcArgs(pid int) ([]byte, error) { return unix.SysctlRaw("kern.procargs2", pid) }
+
+// ownPIDs is every process of this user (KERN_PROC_UID).
+func ownPIDs() ([]int, error) {
+ procs, err := unix.SysctlKinfoProcSlice("kern.proc.uid", os.Getuid())
+ if err != nil {
+ return nil, err
+ }
+ out := make([]int, 0, len(procs))
+ for _, p := range procs {
+ out = append(out, int(p.Proc.P_pid))
+ }
+ return out, nil
+}
diff --git a/internal/runner/mac/fprobe/procargs_other.go b/internal/runner/mac/fprobe/procargs_other.go
index 295ffcfd..1e333b6c 100644
--- a/internal/runner/mac/fprobe/procargs_other.go
+++ b/internal/runner/mac/fprobe/procargs_other.go
@@ -5,6 +5,7 @@ package fprobe
import (
"os"
"strconv"
+ "syscall"
)
// ProcArgs is, off a Mac, pid's arguments and environment from /proc (the
@@ -21,3 +22,24 @@ func ProcArgs(pid int) ([]byte, error) {
}
return append(args, env...), nil
}
+
+// ownPIDs is, off a Mac, every process of this user from /proc.
+func ownPIDs() ([]int, error) {
+ entries, err := os.ReadDir("/proc")
+ if err != nil {
+ return nil, err
+ }
+ var out []int
+ for _, e := range entries {
+ pid, err := strconv.Atoi(e.Name())
+ if err != nil {
+ continue
+ }
+ if info, err := os.Stat("/proc/" + e.Name()); err == nil {
+ if st, ok := info.Sys().(*syscall.Stat_t); ok && int(st.Uid) == os.Getuid() {
+ out = append(out, pid)
+ }
+ }
+ }
+ return out, nil
+}
diff --git a/internal/runner/mac/fprobe/run.go b/internal/runner/mac/fprobe/run.go
index a2c38ace..1d1d8539 100644
--- a/internal/runner/mac/fprobe/run.go
+++ b/internal/runner/mac/fprobe/run.go
@@ -7,6 +7,8 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
+ "errors"
+ "fmt"
"io"
"io/fs"
"net"
@@ -56,7 +58,7 @@ type Host struct {
// runner's binary (its __fprobe helper); ProcArgs reads a process's
// KERN_PROCARGS2 outside the sandbox (nil: ProcArgs); Alive tells
// whether a process is still running, and whether that is known.
- Live func(context.Context) Inputs
+ Live func(context.Context) (Inputs, []wire.Simulator)
Runner string
ProcArgs func(pid int) ([]byte, error)
Alive func(proc.ID) (alive, known bool)
@@ -97,10 +99,17 @@ func (h Host) now() time.Time {
// live is the inputs read now.
func (h Host) live(ctx context.Context) Inputs {
+ in, _ := h.fresh(ctx)
+ return in
+}
+
+// fresh is the inputs and the simulators read now, together (#7: a
+// launch runs on the simulators its inputs name).
+func (h Host) fresh(ctx context.Context) (Inputs, []wire.Simulator) {
if h.Live != nil {
return h.Live(ctx)
}
- return h.Inputs
+ return h.Inputs, h.Simulators
}
// procArgs reads pid's KERN_PROCARGS2 outside the sandbox.
@@ -130,6 +139,10 @@ type Spec struct {
// writes; Script the probe script, ScriptSHA256 its digest, Nonce this
// run's argument (Command).
Scratch, Script, ScriptSHA256, Nonce string
+ // Protected are directories the script runs (F5's fixture) or reads,
+ // beside it; ProtectedSHA256 is the digest of every file in them.
+ Protected []string
+ ProtectedSHA256 string
// Prompt asks the model to run Command (and in A to make the native
// tool calls); Limit bounds the launch.
Prompt string
@@ -158,7 +171,9 @@ func (s Spec) Permit(tool string, input json.RawMessage) bool {
}
b, ok := readFile(s.Script, 1<<20)
sum := sha256.Sum256(b)
- return ok && hex.EncodeToString(sum[:]) == s.ScriptSHA256
+ // Every protected input too, as it is now, just before the run.
+ tree, err := treeDigest(s.Protected)
+ return ok && hex.EncodeToString(sum[:]) == s.ScriptSHA256 && (len(s.Protected) == 0 || err == nil && tree == s.ProtectedSHA256)
case "Write", "Edit", "MultiEdit", "NotebookEdit":
p := filepath.Clean(firstNonEmpty(in.FilePath, in.NotebookPath))
return s.Tree != "" && strings.HasPrefix(p, s.Tree+"/")
@@ -229,7 +244,7 @@ func (s *Store) Run(ctx context.Context, h Host) []Result {
}
defer give()
for _, l := range due {
- h.Inputs = h.live(ctx)
+ h.Inputs, h.Simulators = h.fresh(ctx)
at := h.now()
s.try(l, h.Inputs, at)
var probes []wire.Probe
@@ -330,6 +345,56 @@ func (d *launchDir) spec(l, script string, xcode bool) (Spec, error) {
return Spec{Launch: l, Xcode: xcode, Tree: d.t.root, Scratch: d.run, Script: path, ScriptSHA256: hex.EncodeToString(sum[:]), Nonce: nonce()}, nil
}
+// protect makes dir (inside bin) one of the spec's protected inputs and
+// records the digest of every file in them.
+func (d *launchDir) protect(s *Spec, dir string) error {
+ if !strings.HasPrefix(dir, d.bin+"/") {
+ return errors.New("fprobe: a protected input outside bin")
+ }
+ s.Protected = append(s.Protected, dir)
+ sum, err := treeDigest(s.Protected)
+ s.ProtectedSHA256 = sum
+ return err
+}
+
+// treeDigest is the digest of every entry under dirs: each path, kind,
+// mode and content (a link's target), in order.
+func treeDigest(dirs []string) (string, error) {
+ h := sha256.New()
+ for _, dir := range dirs {
+ err := filepath.WalkDir(dir, func(p string, e fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ info, err := os.Lstat(p)
+ if err != nil {
+ return err
+ }
+ fmt.Fprintf(h, "%s %v\n", p, info.Mode())
+ switch {
+ case info.Mode()&fs.ModeSymlink != 0:
+ t, err := os.Readlink(p)
+ if err != nil {
+ return err
+ }
+ h.Write([]byte(t))
+ case info.Mode().IsRegular():
+ b, err := os.ReadFile(p)
+ if err != nil {
+ return err
+ }
+ fmt.Fprintf(h, "%d\n", len(b))
+ h.Write(b)
+ }
+ return nil
+ })
+ if err != nil {
+ return "", err
+ }
+ }
+ return hex.EncodeToString(h.Sum(nil)), nil
+}
+
// list writes one of the runner's lists for the script.
func (d *launchDir) list(name string, lines []string) error {
body := strings.Join(lines, "\n")
diff --git a/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-a.json b/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-a.json
index 0fa1a20a..e8614790 100644
--- a/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-a.json
+++ b/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-a.json
@@ -2,33 +2,40 @@
"recorded": "SYNTHETIC, not recorded on a Mac",
"machine": "Tito Studio (macOS 27.2, M5 Ultra, Xcode 27.2 27B52), as the runner user paulequipo",
"date": "2026-11-29",
- "why": "What launch A's protected script would record in the launch's scratch if Claude Code 2.1.312's sandbox holds under the no-Xcode Engineering settings, written from the spec and task 1's findings (revised 2026-11-29 for fix round 1: the direct KERN_PROCARGS2 reader and the descriptor list). PID stands for the CLI's pid the runner observed. Task 18 replaces it with the first real run.",
+ "why": "What launch A's protected script would record in the launch's scratch if Claude Code 2.1.312's sandbox holds under the no-Xcode Engineering settings, written from the spec and task 1's findings. Revised 2026-11-29 for fix round 2: F2 and F3 record only bounded outcomes (allowed, denied, failed), compared in memory by the runner's reader; nothing a source gave is written. PID stands for the CLI's pid the runner observed. Task 18 replaces it with the first real run.",
"codes": {
"tcp": "1",
"https": "56",
"https_local": "7",
"dns": "1",
- "cat": "1",
- "cp": "1",
- "ln": "1",
+ "cat": "denied",
+ "cp": "denied",
+ "ln": "denied",
"ln6": "1",
- "env": "0",
- "ppid": "0",
- "ps": "0",
- "procargs": "1",
- "launchctl": "0",
"xcodebuild": "74",
"simctl": "1",
- "mach": "0",
- "fds": "0"
+ "mach": "0"
},
"files": {
- "out/f3.env": "PATH=/usr/bin:/bin:/usr/sbin:/sbin\nHOME=/Users/paulequipo\nTMPDIR=/Users/paulequipo/.local/state/equipo-runner/scratch/policy-123\nCLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3\nSANDBOX_RUNTIME=1\n",
- "out/f3.ppid": " PID TTY TIME CMD\n41234 ?? 0:00.01 /bin/zsh -c bash probe.sh\n",
- "out/f3.ps": " PID TTY TIME CMD\n41200 ?? 0:02.10 /Users/paulequipo/.local/lib/equipo-runner/claude/claude -p --model claude-haiku-5-5 CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3 EQUIPO_ATTEMPT=fprobe-a\n41234 ?? 0:00.01 /bin/zsh -c bash probe.sh\n",
- "out/f3.launchctl": "",
- "out/f7.mach": "none\n",
- "out/f3.procargs": "procargs-start PID\nkern.procargs2: operation not permitted\n",
- "out/f3.fds": "fd 0 char\nfd 1 file\nfd 2 file\nfds-done\n"
- }
+ "out/f7.mach": "none\n"
+ },
+ "f3": [
+ "env denied",
+ "env.rc 0",
+ "ppid refused PPID",
+ "ppid.rc 1",
+ "cli refused PID",
+ "cli.rc 1",
+ "procs denied n=14 self=yes",
+ "procs.rc 0",
+ "launchctl denied",
+ "launchctl.rc 0",
+ "fds denied n=3 pipes=-",
+ "fds.rc 0"
+ ],
+ "f3_token": [
+ "fileN denied",
+ "fileN.rc 0",
+ "fileN.ln denied"
+ ]
}
diff --git a/internal/runner/mac/p2token_test.go b/internal/runner/mac/p2token_test.go
index 77fa3b49..6d1c0252 100644
--- a/internal/runner/mac/p2token_test.go
+++ b/internal/runner/mac/p2token_test.go
@@ -32,6 +32,16 @@ func TestP2TriesTheToken(t *testing.T) {
t.Fatalf("the sentinel token was not planted, so denied proves nothing: %s %v", v, g)
}
facts.Token = true
+ // A collector that ran and could not collect (fix round 2, #4) says
+ // failed, which is never a denial, and P2's detail says so.
+ got["plugin.tokenargs"] = "failed"
+ if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["failed"]) != 1 || !strings.Contains(p2Detail(g, 33, true, true, ""), "not collected: plugin.tokenargs") {
+ t.Fatalf("a failed collection: %s %v", v, g)
+ }
+ if ParseAttempts("EQUIPO-PROBE test tokenargs failed\n")["test.tokenargs"] != "failed" {
+ t.Fatal("a failed line is not read")
+ }
+ got["plugin.tokenargs"] = "denied"
for _, src := range tokenSources {
delete(got, "plugin."+src)
if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["unknown"]) != 1 || g["unknown"][0] != "plugin."+src {
@@ -96,7 +106,7 @@ func TestP2TriesTheToken(t *testing.T) {
helper := filepath.Join(dir, "helper")
// The stand-in reads only the hostile shell (its caller's parent, past
// the command substitution): this box's other processes are not ours.
- if err := os.WriteFile(helper, []byte("#!/bin/bash\nmode=$2; shift 2\ncase \"$mode\" in procargs) pp=$(ps -o ppid= -p $PPID | tr -d ' '); for p in \"$@\"; do echo \"procargs-start $p\"; if { [ \"$p\" = \"$PPID\" ] || [ \"$p\" = \"$pp\" ]; } && tr '\\0' '\\n' < /proc/$p/environ; then echo \"procargs-end $p ok\"; else echo \"procargs-end $p refused\"; fi; done ;; fds) for f in /proc/self/fd/*; do echo \"fd ${f##*/} file\"; done; echo fds-done ;; *) exit 2 ;; esac\n"), 0700); err != nil {
+ if err := os.WriteFile(helper, []byte("#!/bin/bash\nmode=$2; shift 2\npp=$(ps -o ppid= -p $PPID | tr -d ' ')\ncase \"$mode\" in pids) echo $PPID; echo $pp ;; procargs) for p in \"$@\"; do echo \"procargs-start $p\"; if { [ \"$p\" = \"$PPID\" ] || [ \"$p\" = \"$pp\" ]; } && tr '\\0' '\\n' < /proc/$p/environ; then echo \"procargs-end $p ok\"; else echo \"procargs-end $p refused\"; fi; done ;; fds) for f in /proc/self/fd/*; do echo \"fd ${f##*/} file\"; done; echo fds-done ;; *) exit 2 ;; esac\n"), 0700); err != nil {
t.Fatal(err)
}
run := func(targets string, env ...string) map[string]string {
@@ -140,8 +150,22 @@ func TestP2TriesTheToken(t *testing.T) {
if err := os.WriteFile(refusing, []byte("#!/bin/bash\nmode=$2; shift 2\ncase \"$mode\" in procargs) for p in \"$@\"; do echo \"procargs-start $p\"; echo \"procargs-end $p refused\"; done; exit 1 ;; fds) echo fds-done ;; esac\n"), 0700); err != nil {
t.Fatal(err)
}
- if got = run(base + "token_file=" + filepath.Join(dir, ".oauth-token") + "\nhelper=" + refusing + "\n"); got["script.tokenargs"] != "" {
- t.Fatalf("tokenargs said though the reader read nothing: %v", got)
+ if got = run(base + "token_file=" + filepath.Join(dir, ".oauth-token") + "\nhelper=" + refusing + "\n"); got["script.tokenargs"] != "failed" {
+ t.Fatalf("tokenargs not failed though the reader read nothing: %v", got)
+ }
+ // The process list could not be read, or did not show the shell
+ // itself (its control): tokenargs failed, never denied.
+ for name, body := range map[string]string{
+ "nolist": "#!/bin/bash\ncase \"$2\" in pids) exit 1 ;; procargs) shift 2; for p in \"$@\"; do echo \"procargs-start $p\"; echo \"procargs-end $p ok\"; done ;; fds) echo fds-done ;; esac\n",
+ "notself": "#!/bin/bash\ncase \"$2\" in pids) echo 1 ;; procargs) shift 2; for p in \"$@\"; do echo \"procargs-start $p\"; echo \"procargs-end $p ok\"; done ;; fds) echo fds-done ;; esac\n",
+ } {
+ h := filepath.Join(dir, name)
+ if err := os.WriteFile(h, []byte(body), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if got = run(base + "token_file=" + filepath.Join(dir, ".oauth-token") + "\nhelper=" + h + "\n"); got["script.tokenargs"] != "failed" {
+ t.Fatalf("%s: tokenargs %q, want failed (%v)", name, got["script.tokenargs"], got)
+ }
}
// Every hostile part tries every source, the Swift parts by
// KERN_PROCARGS2 and posix_spawn (no Process on iOS).
@@ -152,7 +176,7 @@ func TestP2TriesTheToken(t *testing.T) {
t.Fatalf("%s does not try %s", file, src)
}
}
- if strings.HasSuffix(file, ".swift") && (!strings.Contains(string(raw), "KERN_PROCARGS2") || !strings.Contains(string(raw), "posix_spawn") || strings.Contains(string(raw), "#if os(macOS)\n sources")) {
+ if strings.HasSuffix(file, ".swift") && (!strings.Contains(string(raw), "KERN_PROCARGS2") || !strings.Contains(string(raw), "posix_spawn") || strings.Contains(string(raw), "#if os(macOS)\n sources") || !strings.Contains(string(raw), `("tokenargs", "failed")`)) {
t.Fatalf("%s: the reader and launchctl on every platform", file)
}
}
diff --git a/internal/runner/mac/probe.go b/internal/runner/mac/probe.go
index 2ea39a8b..0f470452 100644
--- a/internal/runner/mac/probe.go
+++ b/internal/runner/mac/probe.go
@@ -312,7 +312,7 @@ func ComputerName(ctx context.Context, x Exec) string {
var (
probePlaces = []string{"script", "plugin", "test"}
probeAttempts = []string{"state", "home", "tcp", "dns", "keychain", "tokenfile", "tokenlink", "tokenenv", "tokenargs", "tokenlaunchd", "tokenfd"}
- attemptLine = regexp.MustCompile(`EQUIPO-PROBE (script|plugin|test) (state|home|tcp|dns|keychain|token(?:file|link|env|args|launchd|fd)) (allowed|denied)\b`)
+ attemptLine = regexp.MustCompile(`EQUIPO-PROBE (script|plugin|test) (state|home|tcp|dns|keychain|token(?:file|link|env|args|launchd|fd)) (allowed|denied|failed)\b`)
)
// ParseAttempts reads the fixture's report lines: "place.attempt" to
@@ -379,7 +379,7 @@ func JudgeP2(got map[string]string, f P2Facts) (verdict string, groups map[strin
// short form, is last, so the capability string's limit cuts it first.
func p2Detail(groups map[string][]string, total int, srtRan, ended bool, why string) string {
var parts []string
- for _, g := range []struct{ key, label string }{{"allowed", "allowed"}, {"unknown", "not shown denied"}, {"unix", "Unix permissions only"}} {
+ for _, g := range []struct{ key, label string }{{"allowed", "allowed"}, {"failed", "not collected"}, {"unknown", "not shown denied"}, {"unix", "Unix permissions only"}} {
switch n := len(groups[g.key]); {
case n > 0 && n == total && n > len(probePlaces):
// Every attempt alike: the count, which leaves room for why.
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go
index 17b903be..c552e5b8 100644
--- a/internal/runner/thin/mac.go
+++ b/internal/runner/thin/mac.go
@@ -447,6 +447,8 @@ type macHost struct {
// (mac_fprobe.go).
version string
eng *macEngineering
+ // runner is this runner's own binary: P2's direct kernel reader.
+ runner string
// warmMu guards warmed, the Xcode (version and build) whose plugin
// cache was last warmed.
warmMu sync.Mutex
@@ -673,7 +675,7 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) {
if accounts == "" {
accounts = DefaultAccountsRoot()
}
- h = &macHost{scratch: c.ScratchRoot, log: o.Logger, version: o.Version}
+ h = &macHost{scratch: c.ScratchRoot, log: o.Logger, version: o.Version, runner: c.Executable}
h.eng = newMacEngineering(h)
others, err := mac.OtherHomes(macUsers, home)
h.paths = mac.Paths{Home: home, StateDir: c.StateDir, AccountsRoot: accounts, SessionRoot: SessionRoot(c), InstallDir: filepath.Dir(c.Executable), OtherHomes: others, HomesUnknown: err != nil}
@@ -861,7 +863,12 @@ func (h *macHost) warmNow(ctx context.Context) {
}
func (h *macHost) probeHost(version string, gate func(string, string) *mac.Gate) mac.ProbeHost {
- return mac.ProbeHost{Exec: h.run, Tools: h.tools, Paths: h.paths, Scratch: filepath.Join(h.scratch, "probes"), UID: os.Getuid(), Version: version, Turns: h.turns,
+ // P2's reader is this runner's own binary, when it is one.
+ reader := ""
+ if executable(h.runner) {
+ reader = h.runner
+ }
+ return mac.ProbeHost{Exec: h.run, Tools: h.tools, Paths: h.paths, Scratch: filepath.Join(h.scratch, "probes"), Runner: reader, UID: os.Getuid(), Version: version, Turns: h.turns,
Gate: func(sandboxed bool) *mac.Gate {
if sandboxed {
return gate(h.tools.SRT, wire.SandboxSeatbelt)
diff --git a/internal/runner/thin/mac_fprobe.go b/internal/runner/thin/mac_fprobe.go
index 72b89025..d13899eb 100644
--- a/internal/runner/thin/mac_fprobe.go
+++ b/internal/runner/thin/mac_fprobe.go
@@ -239,9 +239,9 @@ func (e *macEngineering) host(ctx context.Context) (fprobe.Host, bool) {
}
return fprobe.Host{
// The inputs each launch runs under, read afresh (not the report).
- Live: func(ctx context.Context) fprobe.Inputs {
+ Live: func(ctx context.Context) (fprobe.Inputs, []wire.Simulator) {
c := e.readNow(ctx)
- return fprobe.NewInputs(h.version, c.Harness.Claude != "", c.Xcode, c.Simulators)
+ return fprobe.NewInputs(h.version, c.Harness.Claude != "", c.Xcode, c.Simulators), c.Simulators
},
Paths: h.paths, RuntimeRoot: filepath.Join(cfg.ScratchRoot, "homes"), TokenFiles: tokens, Runner: cfg.Executable,
Tools: h.tools, Simulators: caps.Simulators, Scratch: filepath.Join(h.scratch, "fprobe"), P2Denied: e.p2(),
diff --git a/internal/runner/thin/mac_fprobe_test.go b/internal/runner/thin/mac_fprobe_test.go
index d62f8b34..d9f8e9f5 100644
--- a/internal/runner/thin/mac_fprobe_test.go
+++ b/internal/runner/thin/mac_fprobe_test.go
@@ -10,6 +10,7 @@ import (
"encoding/json"
"net"
"os"
+ "os/exec"
"path/filepath"
"slices"
"strings"
@@ -17,6 +18,7 @@ import (
"testing"
"time"
+ "amadan.net/oficina/equipo/internal/runner"
"amadan.net/oficina/equipo/internal/runner/mac"
"amadan.net/oficina/equipo/internal/runner/mac/fprobe"
"amadan.net/oficina/equipo/internal/runner/mac/proc"
@@ -384,3 +386,76 @@ func TestMacClaudeTagBelow37(t *testing.T) {
t.Fatalf("linux at 36: %v", got)
}
}
+
+// #5 (fix round 2): the production host names the runner's own binary
+// as P2's reader. Built by newMacHost and probeHost, it runs the shipped
+// script phase with a stand-in at that path: P2's targets give it, and
+// the script then says tokenargs and tokenfd.
+func TestMacProbeHostNamesTheReader(t *testing.T) {
+ root := t.TempDir()
+ exe := filepath.Join(root, "lib", "equipo-runner")
+ c := runner.Config{StateDir: filepath.Join(root, "state"), ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), Executable: exe}
+ if err := os.MkdirAll(filepath.Dir(exe), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ // The stand-in reads only its caller's parent, the hostile shell.
+ stand := "#!/bin/bash\nmode=$2; shift 2\npp=$(ps -o ppid= -p $PPID | tr -d ' ')\ncase \"$mode\" in pids) echo $PPID; echo $pp ;; procargs) for p in \"$@\"; do echo \"procargs-start $p\"; if [ \"$p\" = \"$PPID\" ] || [ \"$p\" = \"$pp\" ]; then echo \"procargs-end $p ok\"; else echo \"procargs-end $p refused\"; fi; done ;; fds) echo fds-done ;; esac\n"
+ if err := os.WriteFile(exe, []byte(stand), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ was, wasTemp := macUsers, macUserTemp
+ macUsers = filepath.Join(root, "Users")
+ macUserTemp = func(context.Context, mac.Exec) (string, error) { return "/private/var/folders/4m/abc123_def/T", nil }
+ defer func() { macUsers, macUserTemp = was, wasTemp }()
+ h, err := newMacHost(c, OptionsFromEnv(func(string) string { return "" }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ph := h.probeHost("v1", nil)
+ if ph.Runner != exe {
+ t.Fatalf("P2's reader %q, want the runner %q", ph.Runner, exe)
+ }
+ fixture, err := mac.CopyFixture(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ token := filepath.Join(root, "accounts", ".oauth-token")
+ if err := os.MkdirAll(filepath.Dir(token), 0o700); err != nil || os.WriteFile(token, []byte("sk-ant-oat01-probe-0123456789abcdef"), 0o600) != nil {
+ t.Fatal(err)
+ }
+ targets := "state=/nonexistent\ndns=example.invalid\nkeychain=io.amadan.equipo.probe.x\nport_script=1\ntoken=sk-ant-oat01-probe-0123456789abcdef\ntoken_file=" + token + "\nhelper=" + ph.Runner + "\n"
+ if err := os.WriteFile(filepath.Join(fixture, "equipo-targets.txt"), []byte(targets), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.Command("bash", filepath.Join(fixture, "project", "hostile.sh"))
+ cmd.Env = []string{"PATH=/usr/bin:/bin", "SRCROOT=" + filepath.Join(fixture, "project"), "TMPDIR=" + t.TempDir()}
+ out, _ := cmd.CombinedOutput()
+ got := mac.ParseAttempts(string(out))
+ if got["script.tokenargs"] != "denied" || got["script.tokenfd"] != "denied" {
+ t.Fatalf("the script did not use the runner's reader: %v\n%s", got, out)
+ }
+}
+
+// #7 (fix round 2): the simulators a launch runs on are read afresh with
+// its inputs, never the cached report's.
+func TestMacProbeSimulatorsFresh(t *testing.T) {
+ x := newEngRig(t)
+ h := &macHost{version: "v-test", probes: newMacProbes("v-test", "", nil, func() bool { return true }), creds: x.m, taint: x.m.taint, turns: x.m.turns, scratch: x.cfg.ScratchRoot}
+ h.eng = newMacEngineering(h)
+ stale := []wire.Simulator{{Name: "iPhone 16", Runtime: "iOS 27.0", UDID: "00000000-0000-0000-0000-000000000000"}}
+ fresh := []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}}
+ h.eng.live = func(context.Context) wire.Capabilities {
+ return wire.Capabilities{Simulators: fresh, Xcode: wire.Xcode{Version: "27.2", Build: "27B52"}, Harness: wire.Harness{Claude: provider.ClaudeVersion}}
+ }
+ h.eng.bind(x.w, x.conns, func(context.Context) wire.Capabilities {
+ return wire.Capabilities{Simulators: stale, Xcode: wire.Xcode{Version: "27.0", Build: "27A1"}, Harness: wire.Harness{Claude: provider.ClaudeVersion}}
+ })
+ host, ok := h.eng.host(context.Background())
+ if !ok {
+ t.Fatal("no host with a usable connection")
+ }
+ in, sims := host.Live(context.Background())
+ if !slices.Equal(sims, fresh) || in.Runtimes != "iOS 27.2" || in.Xcode != "27.2 (27B52)" {
+ t.Fatalf("live %+v %+v", in, sims)
+ }
+}