SPB Git

Repository Public MIT

SandboxEscapeTests.swift 24.0 KB 394 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraAgentsTests/SandboxEscapeTests.swift10// Module           : AstraAgentsTests11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================87888990import Foundation91import Testing92import AstraCore93@testable import AstraAgents9495#if os(macOS)9697// SR-1 of docs/security/SECURITY_REVIEW_3.0.md: what a program started for an agent can do besides writing files and98// opening sockets. Every test runs the real attack under the real profile (`/usr/bin/sandbox-exec`) in a temporary99// workspace, and checks the operating system's own answer. Nothing here opens a window or asks the person anything:100// when the profile holds, the request never leaves the sandbox.101102/// Runs a program for the test's own set-up, outside any sandbox, and returns what it printed and its exit status.103@discardableResult func hostRun(_ executable: String, _ arguments: [String]) throws -> (status: Int32, output: String) {104    let process = Process()105    process.executableURL = URL(fileURLWithPath: executable)106    process.arguments = arguments107    let pipe = Pipe()108    process.standardOutput = pipe; process.standardError = pipe109    try process.run()110    let data = pipe.fileHandleForReading.readDataToEndOfFile()111    process.waitUntilExit()112    return (process.terminationStatus, String(decoding: data, as: UTF8.self))113}114115/// A listener on 127.0.0.1 that only counts who connects.116final class LocalListener {117    let descriptor: Int32118    let port: Int119    init() throws {120        descriptor = socket(AF_INET, SOCK_STREAM, 0)121        var address = sockaddr_in()122        address.sin_family = sa_family_t(AF_INET); address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)123        address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = 0124        let fd = descriptor125        let bound = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size)) } }126        guard bound == 0, listen(descriptor, 4) == 0 else { throw ToolError("no local listener") }127        var length = socklen_t(MemoryLayout<sockaddr_in>.size)128        _ = withUnsafeMutablePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(fd, $0, &length) } }129        port = Int(UInt16(bigEndian: address.sin_port))130        _ = fcntl(descriptor, F_SETFL, fcntl(descriptor, F_GETFL) | O_NONBLOCK)131    }132    deinit { close(descriptor) }133    func accepted() -> Bool { let client = accept(descriptor, nil, nil); if client >= 0 { close(client); return true }; return false }134}135136@Suite struct SandboxEscapeTests {137    private func runner(_ ws: TemporaryWorkspace, network: Bool = false) throws -> SandboxedProcessRunner {138        try SandboxedProcessRunner(root: ws.url, ref: ws.access.workspace, supervisor: ProcessSupervisor(), allowsNetwork: network,139                                   temporaryRoot: ws.outside.appendingPathComponent("tmp", isDirectory: true))140    }141142    private func run(_ runner: SandboxedProcessRunner, _ argv: [String], cwd: String? = nil, timeout: TimeInterval = 30) async throws -> ProcessResult {143        try await runner.run(try runner.prepare(argv: argv, workingDirectory: cwd, timeout: timeout), runID: UUID(), onOutput: nil)144    }145146    /// A faceless application bundle inside the workspace whose executable writes a marker outside it and connects to a147    /// local listener: exactly what the reviewer's attacker builds.148    private func plantApplication(_ ws: TemporaryWorkspace, marker: URL, port: Int) throws {149        let identifier = "ai.spboucher.astra.tests.escape." + UUID().uuidString150        try ws.put("X.app/Contents/Info.plist", """151        <?xml version="1.0" encoding="UTF-8"?>152        <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">153        <plist version="1.0"><dict>154        <key>CFBundleExecutable</key><string>x</string>155        <key>CFBundleIdentifier</key><string>\(identifier)</string>156        <key>CFBundleName</key><string>X</string>157        <key>CFBundlePackageType</key><string>APPL</string>158        <key>LSUIElement</key><true/>159        <key>LSBackgroundOnly</key><true/>160        </dict></plist>161        """)162        try ws.put("X.app/Contents/MacOS/x", "#!/bin/sh\necho ran > '\(marker.path)'\n/usr/bin/nc -z -w 2 127.0.0.1 \(port)\nexit 0\n")163        #expect(chmod(ws.url.appendingPathComponent("X.app/Contents/MacOS/x").path, 0o755) == 0)164    }165166    /// The finding itself. Before the fix `open -g -j X.app` exited 0 and LaunchServices started the script outside the167    /// profile: the marker appeared outside the workspace and the listener received a connection with the network off.168    @Test func aProgramCannotLaunchAnAppItBuiltInTheWorkspace() async throws {169        let ws = try TemporaryWorkspace()170        let runner = try runner(ws)171        let listener = try LocalListener()172        let marker = ws.outside.appendingPathComponent("launched-" + UUID().uuidString)173        try plantApplication(ws, marker: marker, port: listener.port)174        for argv in [["open", "-g", "-j", "./X.app"], ["open", "-g", "-j", "-n", "-a", "./X.app"], ["/bin/sh", "-c", "open -g -j \"$PWD/X.app\""],175                     ["open", "-g", "-j", "./X.app/Contents/MacOS/x"]] {176            let result = try await run(runner, argv)177            #expect(result.exitCode != 0, "\(argv): \(result.stdout)\(result.stderr)")178        }179        // LaunchServices starts things asynchronously: give a launch that got through the time to show itself.180        var connected = false181        for _ in 0..<50 {182            if listener.accepted() { connected = true }183            if connected || FileManager.default.fileExists(atPath: marker.path) { break }184            try await Task.sleep(nanoseconds: 100_000_000)185        }186        #expect(!FileManager.default.fileExists(atPath: marker.path))                  // nothing was written outside the workspace…187        #expect(!connected)                                                           // …and nothing reached the network188        // the bundle itself is sound: run directly (inside the sandbox) the same executable is confined like any program189        let direct = try await run(runner, ["./X.app/Contents/MacOS/x"])190        #expect(direct.exitCode == 0 && !FileManager.default.fileExists(atPath: marker.path) && !listener.accepted())191    }192193    /// Apple events to another app are refused. With the profile in force the request never reaches the other app, so194    /// macOS shows no automation prompt.195    @Test func aProgramCannotSendAppleEvents() async throws {196        let ws = try TemporaryWorkspace()197        let runner = try runner(ws)198        let finder = try await run(runner, ["osascript", "-e", "tell application \"Finder\" to get name of startup disk"])199        #expect(finder.exitCode != 0 && finder.stdout.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, "\(finder.stdout)\(finder.stderr)")200        let events = try await run(runner, ["osascript", "-e", "tell application \"System Events\" to get name of every process"])201        #expect(events.exitCode != 0 && events.stdout.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)202    }203204    /// No background job: `launchctl submit` is refused and the job never runs.205    @Test func aProgramCannotCreateALaunchdJob() async throws {206        let ws = try TemporaryWorkspace()207        let runner = try runner(ws)208        let label = "ai.spboucher.astra.tests.job." + UUID().uuidString209        let marker = ws.outside.appendingPathComponent("job-" + UUID().uuidString)210        defer { _ = try? hostRun("/bin/launchctl", ["remove", label]) }            // should it ever be created, it is not left behind211        let result = try await run(runner, ["launchctl", "submit", "-l", label, "--", "/bin/sh", "-c", "echo ran > '\(marker.path)'"])212        #expect(result.exitCode != 0, "\(result.stdout)\(result.stderr)")213        try await Task.sleep(nanoseconds: 1_500_000_000)214        #expect(!FileManager.default.fileExists(atPath: marker.path))215        #expect(try hostRun("/bin/launchctl", ["list", label]).status != 0)            // launchd does not know the job216    }217218    /// The keychain daemons are out of reach. A throw-away keychain file (never the login keychain, never added to the219    /// search list) holds one item that any program may read without a prompt: outside the sandbox `security` prints its220    /// secret, inside it cannot.221    @Test func aProgramCannotReadAKeychainSecret() async throws {222        let ws = try TemporaryWorkspace()223        let keychain = ws.outside.appendingPathComponent("secfix-\(UUID().uuidString).keychain-db").path224        let secret = "s3cret-" + UUID().uuidString225        guard try hostRun("/usr/bin/security", ["create-keychain", "-p", "test-password", keychain]).status == 0 else {226            // No keychain can be created here (a headless builder): the claim cannot be checked on this machine.227            return228        }229        defer { _ = try? hostRun("/usr/bin/security", ["delete-keychain", keychain]) }230        #expect(try hostRun("/usr/bin/security", ["unlock-keychain", "-p", "test-password", keychain]).status == 0)231        #expect(try hostRun("/usr/bin/security", ["add-generic-password", "-s", "astra-secfix-item", "-a", "tester", "-w", secret, "-A", keychain]).status == 0)232        let outside = try hostRun("/usr/bin/security", ["find-generic-password", "-s", "astra-secfix-item", "-w", keychain])233        #expect(outside.status == 0 && outside.output.contains(secret))                // readable without the sandbox: the set-up is real234        for network in [false, true] {235            let confined = try runner(ws, network: network)236            let inside = try await run(confined, ["security", "find-generic-password", "-s", "astra-secfix-item", "-w", keychain])237            #expect(inside.exitCode != 0 && !inside.stdout.contains(secret) && !inside.stderr.contains(secret), "network \(network): \(inside.stdout)")238        }239    }240241    /// A confined program can end what it started, and nothing else.242    @Test func aProgramCannotSignalProcessesOutsideItsSandbox() async throws {243        let ws = try TemporaryWorkspace()244        let runner = try runner(ws)245        let victim = Process()246        victim.executableURL = URL(fileURLWithPath: "/bin/sleep"); victim.arguments = ["120"]247        try victim.run()248        defer { victim.terminate() }249        for signal in ["-0", "-TERM", "-KILL"] {250            let result = try await run(runner, ["/bin/sh", "-c", "kill \(signal) \(victim.processIdentifier)"])251            #expect(result.exitCode != 0, "kill \(signal)")252        }253        try await Task.sleep(nanoseconds: 300_000_000)254        #expect(victim.isRunning)255        let own = try await run(runner, ["/bin/sh", "-c", "/bin/sleep 60 & child=$!; kill -TERM $child; wait $child; echo ended $?"])256        #expect(own.stdout == "ended 143\n")257        let python = try await run(runner, ["python3", "-c", "import subprocess\np = subprocess.Popen(['/bin/sleep', '60'])\np.terminate()\nprint('ended', p.wait())"])258        #expect(python.stdout == "ended -15\n", "\(python.stderr)")259    }260261    /// The other half of the decision: the allowed tools still work under the tightened profile. Tools that are not262    /// installed on the machine are skipped, not assumed.263    @Test func theUsualToolsStillRunUnderTheProfile() async throws {264        let ws = try TemporaryWorkspace()265        let runner = try runner(ws)266        try ws.put("tests/test_sum.py", "import unittest\n\nclass T(unittest.TestCase):\n    def test_sum(self):\n        self.assertEqual(1 + 1, 2)\n")267        try ws.put("tool.py", "import json, hashlib, sqlite3, ssl, subprocess, getpass, tempfile, os\nopen(os.path.join(tempfile.gettempdir(), 'scratch'), 'w').write('t')\n"268            + "print(json.dumps({'user': bool(getpass.getuser()), 'child': subprocess.run(['/bin/echo', 'sub'], capture_output=True, text=True).stdout.strip()}))\n")269        try ws.put("Makefile", "all:\n\t@echo made > made.txt && cat made.txt\n")270        try ws.put("hello.swift", "print(\"hello from swift\")\n")271        try ws.put("hello.c", "#include <stdio.h>\nint main(void) { puts(\"hello from c\"); return 0; }\n")272273        let unittest = try await run(runner, ["python3", "-m", "unittest", "discover", "-s", "tests"])274        #expect(unittest.exitCode == 0 && unittest.stderr.contains("OK"), "\(unittest.stderr)")275        let tool = try await run(runner, ["python3", "tool.py"])276        #expect(tool.exitCode == 0 && tool.stdout == "{\"user\": true, \"child\": \"sub\"}\n", "\(tool.stderr)")277        let shell = try await run(runner, ["/bin/sh", "-c", "ls | wc -l && id -un"])278        #expect(shell.exitCode == 0 && shell.stdout.contains(NSUserName()))            // user names resolve (opendirectoryd is reachable)279280        if (try? runner.gitExecutable()) != nil {281            #expect(try await run(runner, ["git", "init", "-q", "repo"]).exitCode == 0)282            try ws.put("repo/a.txt", "a\n")283            #expect(try await run(runner, ["git", "add", "a.txt"], cwd: "repo").exitCode == 0)284            let commit = try await run(runner, ["git", "-c", "user.name=T", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false", "commit", "-q", "-m", "first"], cwd: "repo")285            #expect(commit.exitCode == 0, "\(commit.stderr)")286            #expect(try await run(runner, ["git", "log", "--oneline"], cwd: "repo").stdout.contains("first"))287            let make = try await run(runner, ["make"])288            #expect(make.exitCode == 0 && make.stdout == "made\n", "\(make.stderr)")289            let version = try await run(runner, ["swift", "--version"])290            #expect(version.exitCode == 0 && version.stdout.contains("Swift version"), "\(version.stderr)")291            let compiled = try await run(runner, ["swiftc", "hello.swift", "-o", "hello"], timeout: 120)292            #expect(compiled.exitCode == 0, "\(compiled.stderr)")293            #expect(try await run(runner, ["./hello"]).stdout == "hello from swift\n")294            #expect(try await run(runner, ["clang", "hello.c", "-o", "hello-c"], timeout: 120).exitCode == 0)295            #expect(try await run(runner, ["./hello-c"]).stdout == "hello from c\n")296        }297        if ProcessPolicy.searchPath.contains(where: { FileManager.default.isExecutableFile(atPath: $0 + "/node") }) {298            try ws.put("index.js", "const os = require('os'); const fs = require('fs'); fs.writeFileSync('node.txt', 'n'); console.log('node ' + (os.userInfo().username.length > 0));\n")299            let node = try await run(runner, ["node", "index.js"])300            #expect(node.exitCode == 0 && node.stdout == "node true\n", "\(node.stderr)")301        }302        // with the network allowed, names resolve and a local service answers303        let listener = try LocalListener()304        let open = try self.runner(ws, network: true)305        let reached = try await run(open, ["python3", "-c", "import socket\ns = socket.create_connection(('localhost', \(listener.port)), 3)\nprint('connected')"])306        #expect(reached.stdout == "connected\n", "\(reached.stderr)")307    }308309    @Test func theProfileAndTheSentenceSayWhatIsEnforced() throws {310        let closed = ProcessConfinement.profile(networkAllowed: false), open = ProcessConfinement.profile(networkAllowed: true)311        for rule in ["(deny file-write*)", "(deny lsopen)", "(deny appleevent-send)", "(deny job-creation)", "(deny mach-lookup)", "(deny signal)",312                     "(allow signal (target same-sandbox))"] {313            #expect(closed.contains(rule) && open.contains(rule), "\(rule)")314        }315        #expect(closed.hasSuffix("(deny network*)") && !open.contains("(deny network"))316        // the allow-list is short and names no service that launches, automates or holds secrets317        #expect(ProcessConfinement.allowedMachServices.count == 10)318        for forbidden in ["launchservices", "lsd", "SecurityServer", "securityd", "secd", "pasteboard", "windowserver", "tccd", "appleevents", "coreservices"] {319            #expect(!ProcessConfinement.allowedMachServices.contains { $0.lowercased().contains(forbidden.lowercased()) }, "\(forbidden)")320        }321        let sentence = ProcessConfinement.summary(workspaceName: "project", networkAllowed: false)322        for word in ["write only inside “project”", "launch apps", "Apple events", "background jobs", "keychain", "no network access", "Not enforced: reads", "detaches itself", "still confined"] {323            #expect(sentence.contains(word), "\(word)")324        }325        #expect(ProcessConfinement.summary(workspaceName: "project", networkAllowed: true).contains("can use the network"))326        let ws = try TemporaryWorkspace()327        #expect(try runner(ws).confinementSummary == sentence)328        #expect(ProcessConfinement.facts.contains { $0.holds && $0.text.contains("LaunchServices") })329        #expect(ProcessConfinement.facts.contains { !$0.holds && $0.text.contains("Reads are not restricted") })330        #expect(ProcessConfinement.facts.contains { !$0.holds && $0.text.contains("detaches itself") })331    }332}333334#endif335336#if os(macOS)337338/// Limits of the confinement that are documented, not fixed (docs/agents/WORKSPACE_TOOLS.md, "What it does not give").339/// These tests state the present behaviour, so that a change in it is noticed and the documents are corrected.340@Suite struct SandboxKnownLimitTests {341    private func runner(_ ws: TemporaryWorkspace) throws -> SandboxedProcessRunner {342        try SandboxedProcessRunner(root: ws.url, ref: ws.access.workspace, supervisor: ProcessSupervisor(), temporaryRoot: ws.outside.appendingPathComponent("tmp", isDirectory: true))343    }344    private func sh(_ runner: SandboxedProcessRunner, _ script: String) async throws -> ProcessResult {345        try await runner.run(try runner.prepare(argv: ["/bin/sh", "-c", script], workingDirectory: nil, timeout: 20), runID: UUID(), onOutput: nil)346    }347348    /// SR-10: the profile allows writes by path. A file of the workspace that is a second name (a hard link) of a file349    /// elsewhere on the same volume is the same file: writing through it changes the file outside. A program cannot make350    /// such a link itself; it has to be there already. The file tools are not affected: they replace by rename.351    @Test func aHardLinkAlreadyInTheWorkspaceReachesTheFileItNames() async throws {352        let ws = try TemporaryWorkspace()353        let outside = ws.outside.appendingPathComponent("outside.txt")354        try Data("original\n".utf8).write(to: outside)355        let runner = try runner(ws)356        // a confined program cannot create the link357        let made = try await sh(runner, "ln '\(outside.path)' made-inside.txt")358        #expect(made.exitCode != 0 && !ws.exists("made-inside.txt"))359        // one that is already there (made by the person or by another program) is a way out for writes360        #expect(link(outside.path, ws.url.appendingPathComponent("already.txt").path) == 0)361        let appended = try await sh(runner, "echo appended >> already.txt")362        #expect(appended.exitCode == 0)363        #expect(try String(contentsOf: outside, encoding: .utf8) == "original\nappended\n")       // the documented limit364        // the file tools replace the name and never write through the old file365        _ = try await ws.access.write("already.txt", text: "replaced by the file tool\n")366        #expect(try String(contentsOf: outside, encoding: .utf8) == "original\nappended\n" && ws.text("already.txt") == "replaced by the file tool\n")367    }368369    /// A program that moves itself to another session is not reached by the signal sent to its group, and stays confined.370    @Test func aDetachedDescendantKeepsTheProfile() async throws {371        let ws = try TemporaryWorkspace()372        let runner = try runner(ws)373        let marker = ws.outside.appendingPathComponent("detached-" + UUID().uuidString)374        try ws.put("detach.py", """375        import os, sys, time376        if os.fork() == 0:377            os.setsid()378            for stream in (sys.stdin, sys.stdout, sys.stderr): stream.close()379            time.sleep(0.6)380            open('detached-pid', 'w').write(str(os.getpid()))381            try: open(r'\(marker.path)', 'w').write('escaped')382            except OSError as error: open('detached-refused', 'w').write(str(error.errno))383            os._exit(0)384        """)385        let result = try await runner.run(try runner.prepare(argv: ["python3", "detach.py"], workingDirectory: nil, timeout: 20), runID: UUID(), onOutput: nil)386        #expect(result.exitCode == 0 && result.duration < 5)                              // the call returned without waiting for the descendant387        #expect(await waitUntil(5) { ws.exists("detached-refused") || FileManager.default.fileExists(atPath: marker.path) })388        #expect(ws.exists("detached-pid"))                                                 // it outlived the command (the limit)…389        #expect(!FileManager.default.fileExists(atPath: marker.path) && ws.text("detached-refused") == "1")   // …and could still write only inside the workspace390    }391}392393#endif394
Files main
Menu

Theme