SPB Git

Repository Public

ShellTool.swift 13.3 KB 201 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatAgents/Sources/ShellTool.swift3// Description: Optional macOS shell tool: always human-approved, hard denylist, confined working directory, scrubbed environment, timeout, output cap, process-group kill.4import Foundation5import LocalChatCore67/// Command screening is available on every platform (it is pure text analysis and shown in approval sheets).8public enum ShellPolicy {9    /// Patterns that are refused even when the user approves: they destroy data or systems, or escalate privileges.10    static let hardDeny: [(pattern: String, reason: String)] = [11        (#"(^|[;&|`(\s])sudo(\s|$)"#, "sudo is not allowed"),12        (#"(^|[;&|`(\s])(su|doas)\s"#, "switching user is not allowed"),13        (#"\brm\s+.*--no-preserve-root"#, "recursive deletion of the root"),14        (#"\bmkfs(\.|\s|$)|\bnewfs(_|\s)|\bdiskutil\s+(erase|partition|zero|secureErase|reformat|apfs\s+delete)"#, "formatting or erasing disks"),15        (#"\bdd\b[^|;&]*\bof=/dev/"#, "raw writes to a device"),16        (#">\s*/dev/(r?disk|sd|nvme)"#, "raw writes to a device"),17        (#"(^|[;&|`(\s])(shutdown|reboot|halt|poweroff)(\s|$)"#, "shutting down the machine"),18        (#":\s*\(\s*\)\s*\{[^}]*:\s*\|\s*:"#, "fork bomb"),19        (#"\b(curl|wget|fetch)\b[^|;&]*\|\s*(sudo\s+)?(ba|z|k|da|fi)?sh\b"#, "piping a download into a shell"),20        (#"\b(ba|z)?sh\s+<\s*\(\s*(curl|wget)"#, "executing a download"),21        (#"\bchmod\s+(-[a-zA-Z]+\s+)*(777|a\+rwx)\s+/(\s|$)|\bchown\s+-R\b[^;&|]*\s/(\s|$)"#, "changing permissions of the root"),22        (#"\b(launchctl\s+(unload|bootout|remove|disable)|csrutil|spctl\s+--master-disable|nvram|kextload|kextunload)\b"#, "changing system security or services"),23        (#"\b(killall|pkill)\b"#, "killing processes by name"),24        (#"\bkill\s+(-[0-9A-Z]+\s+)*-?1(\s|$)"#, "killing every process"),25        (#"\bsecurity\s+(dump-keychain|find-(generic|internet)-password|delete-keychain|export)\b"#, "reading or deleting Keychain secrets"),26        (#"(\.ssh/|id_(rsa|ed25519|ecdsa)|\.aws/credentials|\.netrc|\.gnupg/)"#, "touching credentials"),27        (#"\bgit\s+push\b[^;&|]*(--force|-f)\b"#, "force-pushing"),28        (#"\b(base64\s+(-d|--decode)|xxd\s+-r)\b[^|;&]*\|\s*(ba|z)?sh\b"#, "executing obfuscated code"),29        (#"\beval\b|\bexec\s"#, "eval/exec are not allowed"),30        (#">\s*/(etc|System|Library|usr|bin|sbin)/"#, "writing to system directories"),31        (#"\bcrontab\b|\bosascript\b"#, "scheduling or scripting other apps"),32    ]3334    static let protectedTargets: Set<String> = ["/", "/*", "~", "~/", "~/*", "$HOME", "$HOME/", "$HOME/*", "${HOME}", "${HOME}/", "${HOME}/*", ".", "..", "*",35                                                "/Users", "/System", "/Library", "/Applications", "/bin", "/sbin", "/usr", "/etc", "/var", "/private", "/opt", "/Volumes"]3637    /// True when the command contains a recursive `rm` aimed at the root, the home folder or a top-level system directory.38    static func isDestructiveRemoval(_ command: String) -> Bool {39        for segment in command.components(separatedBy: CharacterSet(charactersIn: "|;&\n(){}`")) {40            let tokens = segment.split(whereSeparator: { $0 == " " || $0 == "\t" }).map(String.init)41            guard let index = tokens.firstIndex(where: { $0 == "rm" || $0.hasSuffix("/rm") }) else { continue }42            let arguments = tokens[(index + 1)...]43            let recursive = arguments.contains { $0 == "--recursive" || ($0.hasPrefix("-") && !$0.hasPrefix("--") && $0.contains(where: { $0 == "r" || $0 == "R" })) }44            guard recursive else { continue }45            for raw in arguments where !raw.hasPrefix("-") {46                var target = raw.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))47                while target.count > 1, target.hasSuffix("/") { target.removeLast() }48                if protectedTargets.contains(target) || protectedTargets.contains(raw) { return true }49                let home = NSHomeDirectory()50                if target == home || target == home + "/*" { return true }51            }52        }53        return false54    }5556    /// Nil when the command may be proposed for approval; otherwise why it is refused.57    public static func refusal(for command: String, permissions: ToolPermissions) -> String? {58        let trimmed = command.trimmingCharacters(in: .whitespacesAndNewlines)59        guard !trimmed.isEmpty else { return "The command is empty." }60        guard trimmed.count <= 4000 else { return "The command is too long." }61        guard !trimmed.contains("\0") else { return "Invalid characters in the command." }62        // collapse quoting tricks used to hide words (s"u"do, su\do)63        let normalized = trimmed.replacingOccurrences(of: "\\\n", with: " ").replacingOccurrences(of: #"\\(?=[a-zA-Z])"#, with: "", options: .regularExpression)64            .replacingOccurrences(of: #"(?<=[a-zA-Z])(""|'')(?=[a-zA-Z])"#, with: "", options: .regularExpression)65        for candidate in Set([trimmed, normalized]) {66            if isDestructiveRemoval(candidate) { return "Refused: recursive deletion of a system or home directory. This rule cannot be overridden." }67            for rule in hardDeny where candidate.range(of: rule.pattern, options: [.regularExpression, .caseInsensitive]) != nil {68                return "Refused: \(rule.reason). This rule cannot be overridden."69            }70            for extra in permissions.shellDenylist where !extra.isEmpty && candidate.localizedCaseInsensitiveContains(extra) {71                return "Refused: the command contains \"\(extra)\", which the user blocked."72            }73        }74        if !permissions.shellAllowlist.isEmpty {75            // every command of a pipeline / sequence must start with an allowed program76            let segments = normalized.components(separatedBy: CharacterSet(charactersIn: "|;&\n")).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }77            if normalized.contains("$(") || normalized.contains("`") { return "Refused: command substitution is not allowed when an allowlist is set." }78            for segment in segments {79                let program = segment.split(separator: " ").first(where: { !$0.contains("=") }).map { ($0 as Substring).split(separator: "/").last.map(String.init) ?? String($0) } ?? ""80                guard permissions.shellAllowlist.contains(program) else { return "Refused: \"\(program)\" is not in the allowed commands (\(permissions.shellAllowlist.joined(separator: ", ")))." }81            }82        }83        return nil84    }85}8687#if os(macOS)88public struct ShellTool: AgentTool {89    public let risk: ToolRisk = .execute90    public let platforms: Set<ToolPlatform> = [.macOS]91    public let alwaysRequiresApproval = true92    public let definition = ToolDefinition(93        name: "run_shell", summary: "Runs a zsh command on this Mac inside a granted folder. The user must approve every command. Destructive commands are refused.",94        parameters: ["type": "object", "properties": [95            "command": ["type": "string"],96            "working_directory": ["type": "string", "description": "inside a granted folder; default: the first granted folder"],97            "timeout_seconds": ["type": "integer", "description": "1 to 120, default 30"]], "required": ["command"]])98    static let outputCap = 60_00099100    public init() {}101102    /// A sandboxed app cannot spawn arbitrary processes: the tool only exists when the app is not sandboxed and says shell is permitted.103    public static func isShellAvailable(appPermitsShell: Bool) -> Bool {104        appPermitsShell && ProcessInfo.processInfo.environment["APP_SANDBOX_CONTAINER_ID"] == nil105    }106107    public func run(arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {108        guard context.permissions.allowShell else { throw ToolError("Shell execution is turned off for this agent.") }109        let command = arguments["command"]?.stringValue ?? ""110        if let reason = ShellPolicy.refusal(for: command, permissions: context.permissions) { throw ToolError(reason) }111        let directory = try context.jail.resolve(arguments["working_directory"]?.stringValue ?? ".")112        var isDir: ObjCBool = false113        guard FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDir), isDir.boolValue else { throw ToolError("The working directory does not exist.") }114        let timeout = TimeInterval(max(1, min(120, arguments["timeout_seconds"]?.intValue ?? 30)))115        let result = try await ShellProcess.run(command: command, directory: directory, timeout: timeout, outputCap: Self.outputCap)116        var text = result.output.isEmpty ? "(no output)" : result.output117        if result.truncated { text += "\n[… output truncated]" }118        if result.timedOut { return ToolOutput(text + "\n[killed: exceeded \(Int(timeout)) s]", isError: true) }119        return ToolOutput(text + "\n[exit code \(result.exitCode)]", isError: result.exitCode != 0)120    }121}122123enum ShellProcess {124    struct Result: Sendable { var output: String; var exitCode: Int32; var timedOut: Bool; var truncated: Bool }125126    final class State: @unchecked Sendable {127        private let lock = NSLock(); private var pid: pid_t = 0; private var timedOutFlag = false128        func set(_ p: pid_t) { lock.withLock { pid = p } }129        var timedOut: Bool { lock.withLock { timedOutFlag } }130        /// Kills the whole process group (the child is its own group leader).131        func kill(timeout: Bool = false) {132            let p: pid_t = lock.withLock { if timeout { timedOutFlag = true }; return pid }133            if p > 0 { Darwin.kill(-p, SIGKILL) }134        }135    }136137    static func run(command: String, directory: URL, timeout: TimeInterval, outputCap: Int) async throws -> Result {138        let state = State()139        return try await withTaskCancellationHandler {140            try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Result, Error>) in141                DispatchQueue.global(qos: .userInitiated).async {142                    do { continuation.resume(returning: try spawn(command: command, directory: directory, timeout: timeout, outputCap: outputCap, state: state)) }143                    catch { continuation.resume(throwing: error) }144                }145            }146        } onCancel: { state.kill() }147    }148149    static func spawn(command: String, directory: URL, timeout: TimeInterval, outputCap: Int, state: State) throws -> Result {150        var fds: [Int32] = [0, 0]151        guard pipe(&fds) == 0 else { throw ToolError("Could not create a pipe.") }152        var actions: posix_spawn_file_actions_t?153        posix_spawn_file_actions_init(&actions); defer { posix_spawn_file_actions_destroy(&actions) }154        posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0)155        posix_spawn_file_actions_adddup2(&actions, fds[1], 1)156        posix_spawn_file_actions_adddup2(&actions, fds[1], 2)157        posix_spawn_file_actions_addclose(&actions, fds[0])158        posix_spawn_file_actions_addclose(&actions, fds[1])159        posix_spawn_file_actions_addchdir_np(&actions, directory.path)160        var attr: posix_spawnattr_t?161        posix_spawnattr_init(&attr); defer { posix_spawnattr_destroy(&attr) }162        posix_spawnattr_setpgroup(&attr, 0)   // new process group led by the child163        posix_spawnattr_setflags(&attr, Int16(POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_CLOEXEC_DEFAULT))164165        // scrubbed environment: nothing from the app (tokens, keys) leaks into the command166        let env = ["PATH=/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin:/usr/local/bin", "HOME=\(NSHomeDirectory())", "LANG=en_US.UTF-8",167                   "TERM=dumb", "PWD=\(directory.path)", "TMPDIR=\(NSTemporaryDirectory())"]168        let argv: [UnsafeMutablePointer<CChar>?] = ["/bin/zsh", "-f", "-c", command].map { strdup($0) } + [nil]169        let envp: [UnsafeMutablePointer<CChar>?] = env.map { strdup($0) } + [nil]170        defer { argv.forEach { free($0) }; envp.forEach { free($0) } }171        var pid: pid_t = 0172        let status = posix_spawn(&pid, "/bin/zsh", &actions, &attr, argv, envp)173        close(fds[1])174        guard status == 0 else { close(fds[0]); throw ToolError("Could not start the command (\(String(cString: strerror(status)))).") }175        state.set(pid)176177        let timer = DispatchSource.makeTimerSource(queue: .global())178        timer.schedule(deadline: .now() + timeout); timer.setEventHandler { state.kill(timeout: true) }; timer.resume()179        defer { timer.cancel() }180181        // drain until EOF, keeping at most `outputCap` bytes (keeps the child from blocking on a full pipe)182        var data = Data(); var truncated = false183        var buffer = [UInt8](repeating: 0, count: 16384)184        while true {185            let n = read(fds[0], &buffer, buffer.count)186            if n > 0 {187                if data.count < outputCap { data.append(contentsOf: buffer[0..<min(n, outputCap - data.count)]) }188                if data.count >= outputCap { truncated = true }189            } else if n == 0 || errno != EINTR { break }190        }191        close(fds[0])192        var raw: Int32 = 0193        while waitpid(pid, &raw, 0) == -1 && errno == EINTR {}194        Darwin.kill(-pid, SIGKILL)   // leftovers of the group (background children)195        let exit: Int32 = (raw & 0x7F) == 0 ? (raw >> 8) & 0xFF : 128 + (raw & 0x7F)196        return Result(output: String(decoding: data, as: UTF8.self).trimmingCharacters(in: .newlines), exitCode: exit,197                      timedOut: state.timedOut, truncated: truncated)198    }199}200#endif201
Files main
Menu

Theme