SPB Git

Repository Public

CommandRiskAnalyzer.swift 35.3 KB 715 lines swift

1import Foundation23/// Severity of a command line. Ordered: `.safe < .caution < .destructive`.4///5/// `.safe` means "no known risk pattern was detected", not "proven harmless".6public enum RiskLevel: Int, Sendable, Codable, Comparable, CaseIterable, Hashable {7    case safe = 08    case caution = 19    case destructive = 21011    public static func < (lhs: RiskLevel, rhs: RiskLevel) -> Bool { lhs.rawValue < rhs.rawValue }12}1314/// Machine-readable reason attached to a ``RiskAssessment``.15public enum RiskReason: String, Sendable, Codable, CaseIterable, Hashable {16    /// `sudo`, `doas`, `su`, `pkexec`.17    case privilegeEscalation18    /// `rm -r`, `rm -rf`, `find ... -delete`.19    case recursiveDelete20    /// `rm -f` without recursion, `shred`, `srm`.21    case forcedDelete22    /// Plain `rm`, `unlink`, `rmdir`.23    case fileDeletion24    /// `dd of=/dev/...`, `mkfs`, `diskutil erase*`/`partition*`, redirect to a disk device.25    case rawDiskWrite26    /// `git push --force`, `reset --hard`, `clean -fd`, `branch -D`, ...27    case destructiveGit28    /// `chmod -R`, `chown -R`, `chgrp -R`.29    case recursivePermissionChange30    /// A download or generated text piped/substituted into a shell or interpreter.31    case pipeToShell32    /// `scp`, `sftp`, remote `rsync`, `curl -T`/`-d @file`, `nc`, ...33    case networkTransfer34    /// `shutdown`, `reboot`, `halt`, `poweroff`.35    case powerControl36    /// `kill -9 -1`, `killall`, `pkill`.37    case massKill38    /// A self-replicating function such as `:(){ :|:& };:`.39    case forkBomb40    /// `>` (or `tee`, `dd of=`, `mv`/`cp`) onto a system path.41    case systemPathOverwrite42    /// `>` truncating an ordinary file.43    case fileOverwrite44    /// Reading shell history, keychain items, private SSH keys or credential files.45    case sensitiveDataAccess46    /// Sensitive data flowing into a network command.47    case sensitiveDataExfiltration48    /// The line targets several hosts at once (broadcast input).49    case multiHost50    /// Unbalanced quoting or nesting too deep to analyse reliably.51    case unparsable52}5354/// One detected risk.55public struct RiskFinding: Sendable, Equatable, Hashable {56    public let reason: RiskReason57    /// Severity contributed by this finding alone.58    public let level: RiskLevel59    /// Human-readable explanation (English) suitable for a confirmation sheet.60    public let explanation: String61}6263/// Result of analysing a command line. Only the analyzer can create one.64public struct RiskAssessment: Sendable, Equatable, Hashable {65    /// Overall level (the highest finding, raised one step for multi-host input).66    public let level: RiskLevel67    /// Findings, at most one per reason.68    public let findings: [RiskFinding]6970    /// Machine-readable reasons, in detection order.71    public var reasons: [RiskReason] { findings.map(\.reason) }72    /// Human-readable explanations, in detection order.73    public var explanations: [String] { findings.map(\.explanation) }7475    /// `true` when ``ConsentGate`` demands a reinforced confirmation: destructive76    /// level, privilege escalation, network transfer / exfiltration or multi-host.77    public var requiresReinforcedConfirmation: Bool {78        level == .destructive || findings.contains {79            switch $0.reason {80            case .privilegeEscalation, .networkTransfer, .sensitiveDataExfiltration, .multiHost: true81            default: false82            }83        }84    }8586    init(level: RiskLevel, findings: [RiskFinding]) {87        self.level = level88        self.findings = findings89    }90}9192/// Classifies shell command lines. Stateless, synchronous, no I/O: it never runs,93/// expands or resolves anything.94public struct CommandRiskAnalyzer: Sendable {95    /// Creates an analyzer.96    public init() {}9798    /// Full assessment of a (possibly compound) command line.99    /// - Parameter isMultiHost: `true` when the line will be sent to several hosts;100    ///   this adds ``RiskReason/multiHost`` and raises the level by one step.101    public func assess(_ commandLine: String, isMultiHost: Bool = false) -> RiskAssessment {102        var collector = Collector()103        analyzeLine(commandLine, depth: 0, into: &collector)104        var level = collector.findings.map(\.level).max() ?? .safe105        let blank = commandLine.allSatisfy(\.isWhitespace)106        if isMultiHost && !blank {107            collector.add(.multiHost, .caution, "The input is broadcast to several hosts at once; a mistake is repeated on each of them.")108            level = level == .safe ? .caution : .destructive109        }110        return RiskAssessment(level: level, findings: collector.findings)111    }112113    /// Cheap entry point for a single line (used by broadcast-input protection):114    /// returns only the level.115    public static func level(ofLine line: String, isMultiHost: Bool = false) -> RiskLevel {116        CommandRiskAnalyzer().assess(line, isMultiHost: isMultiHost).level117    }118119    // MARK: - Internals120121    private struct Collector {122        var findings: [RiskFinding] = []123124        mutating func add(_ reason: RiskReason, _ level: RiskLevel, _ explanation: String) {125            if let i = findings.firstIndex(where: { $0.reason == reason }) {126                if findings[i].level < level { findings[i] = RiskFinding(reason: reason, level: level, explanation: explanation) }127            } else {128                findings.append(RiskFinding(reason: reason, level: level, explanation: explanation))129            }130        }131    }132133    private struct LineState {134        var downloaderSeen = false135        var sensitiveSeen = false136    }137138    private struct CommandContext {139        var pipedInput: Bool140        var substitutions: [String]141        var redirectTargets: [String]142        var networkRedirect: Bool143    }144145    private static let maxDepth = 6146147    private func analyzeLine(_ line: String, depth: Int, into c: inout Collector) {148        guard depth <= Self.maxDepth else {149            c.add(.unparsable, .caution, "The command is nested too deeply to be analysed reliably.")150            return151        }152        if Self.looksLikeForkBomb(line) {153            c.add(.forkBomb, .destructive, "Defines a function that keeps spawning copies of itself (fork bomb); it exhausts the machine.")154        }155        let parsed = ShellLexer.parse(line)156        if parsed.unterminated {157            c.add(.unparsable, .caution, "Unbalanced quotes or parentheses: the shell may interpret this differently from what is shown.")158        }159        var state = LineState()160        for command in parsed.commands {161            let allWords = command.words + command.redirects.map(\.target)162            let substitutions = allWords.flatMap(\.substitutions)163            for inner in substitutions { analyzeLine(inner, depth: depth + 1, into: &c) }164            let networkRedirect = analyzeRedirects(command, into: &c)165            let context = CommandContext(166                pipedInput: command.pipedInput,167                substitutions: substitutions,168                redirectTargets: command.redirects.map(\.target.text),169                networkRedirect: networkRedirect170            )171            analyzeCommand(command.words.map(\.text), context: context, state: &state, depth: depth, into: &c)172        }173    }174175    /// Returns `true` when a redirection targets `/dev/tcp` or `/dev/udp`.176    private func analyzeRedirects(_ command: ShellCommand, into c: inout Collector) -> Bool {177        var network = false178        for redirect in command.redirects {179            let op = redirect.op180            let target = redirect.target.text181            guard op.hasPrefix(">") || op.hasPrefix("&>"), !target.isEmpty else { continue }182            if op == ">&", target == "-" || target.allSatisfy(\.isNumber) { continue }183            let append = op.hasSuffix(">>")184            if Self.isDiskDevice(target) {185                c.add(.rawDiskWrite, .destructive, "Writes directly to the disk device \(target), destroying its contents.")186            } else if target.hasPrefix("/dev/tcp/") || target.hasPrefix("/dev/udp/") {187                network = true188                c.add(.networkTransfer, .caution, "Sends output to a network socket (\(target)).")189            } else if Self.isHarmlessDevice(target) {190                continue191            } else if Self.isSystemPath(target) {192                c.add(.systemPathOverwrite, append ? .caution : .destructive,193                      append ? "Appends to the system file \(target)." : "Overwrites the system file \(target).")194            } else if !append {195                c.add(.fileOverwrite, .caution, "Truncates and overwrites \(target).")196            }197        }198        return network199    }200201    private func analyzeCommand(_ input: [String], context: CommandContext, state: inout LineState, depth: Int, into c: inout Collector) {202        guard depth <= Self.maxDepth + 4 else { return }203        var words = input[...]204        while let first = words.first, Self.reservedWords.contains(first) || Self.isAssignment(first) { words.removeFirst() }205        guard let first = words.first else { return }206        let name = Self.basename(first).lowercased()207        let args = Array(words.dropFirst())208209        // Sensitive data and network sinks.210        let isNetwork = context.networkRedirect211            || (Self.networkCommands.contains(name) && (name != "rsync" || args.contains(where: Self.isRemoteSpec)))212        let ownText = (Self.withoutIdentityOptions(name: name, args: args) + context.redirectTargets).joined(separator: " ")213        let ownSensitive = Self.referencesSensitivePath(ownText) || Self.isSensitiveCommand(name: name, args: args)214        if isNetwork {215            if ownSensitive || (context.pipedInput && state.sensitiveSeen) {216                c.add(.sensitiveDataExfiltration, .destructive,217                      "Sends sensitive data (shell history, keychain, private keys or credentials) to the network.")218            }219        } else if ownSensitive {220            state.sensitiveSeen = true221            c.add(.sensitiveDataAccess, .caution, "Reads sensitive data (shell history, keychain, private keys or credentials).")222        } else if Self.isEnvironmentDump(name: name, args: args) {223            state.sensitiveSeen = true224        }225        if Self.downloaders.contains(name) { state.downloaderSeen = true }226227        func recurse(_ rest: [String]) {228            analyzeCommand(rest, context: context, state: &state, depth: depth + 1, into: &c)229        }230231        switch name {232        case "sudo", "doas":233            c.add(.privilegeEscalation, .caution, "Runs with administrator privileges (\(name)).")234            recurse(Self.skipOptions(args, valueFlags: name == "sudo" ? "ughpCDRTUrt" : "uC"))235        case "pkexec":236            c.add(.privilegeEscalation, .caution, "Runs with administrator privileges (pkexec).")237            recurse(Self.skipOptions(args, valueFlags: ""))238        case "su":239            c.add(.privilegeEscalation, .caution, "Switches to another user account (su).")240            if let i = args.firstIndex(where: { $0 == "-c" || $0 == "--command" }), i + 1 < args.count {241                analyzeLine(args[i + 1], depth: depth + 1, into: &c)242            }243        case "env":244            recurse(Self.skipOptions(args, valueFlags: "uSP"))245        case "command", "builtin", "exec", "nohup", "time", "nice", "ionice", "stdbuf", "caffeinate",246             "setsid", "noglob", "nocorrect", "unbuffer", "chronic":247            var rest = Self.skipOptions(args, valueFlags: "n")248            if let f = rest.first, f.allSatisfy(\.isNumber) { rest.removeFirst() }249            recurse(rest)250        case "timeout":251            recurse(Array(Self.skipOptions(args, valueFlags: "sk").dropFirst()))252        case "watch":253            analyzeLine(Self.skipOptions(args, valueFlags: "n").joined(separator: " "), depth: depth + 1, into: &c)254        case "xargs":255            recurse(Self.skipOptions(args, valueFlags: "InPLdsEJR"))256        case "eval":257            checkSubstitutedDownload(context, into: &c)258            analyzeLine(args.joined(separator: " "), depth: depth + 1, into: &c)259        case "source", ".":260            checkSubstitutedDownload(context, into: &c)261        case "ssh":262            let rest = Self.skipOptions(args, valueFlags: "bcDEeFIiJLlmOopQRSWw")263            let remote = rest.dropFirst().joined(separator: " ")264            if !remote.isEmpty { analyzeLine(remote, depth: depth + 1, into: &c) }265            if context.pipedInput {266                c.add(.networkTransfer, .caution, "Pipes local data to a remote host over ssh.")267            }268        case "rm", "unlink", "rmdir", "srm", "shred":269            analyzeRemove(name: name, args: args, into: &c)270        case "find":271            analyzeFind(args, context: context, state: &state, depth: depth, into: &c)272        case "dd":273            for arg in args where arg.hasPrefix("of=") {274                let target = String(arg.dropFirst(3))275                if Self.isDiskDevice(target) {276                    c.add(.rawDiskWrite, .destructive, "dd writes raw data to the disk device \(target), destroying its contents.")277                } else if Self.isSystemPath(target) {278                    c.add(.systemPathOverwrite, .destructive, "dd overwrites the system file \(target).")279                } else if !Self.isHarmlessDevice(target) {280                    c.add(.fileOverwrite, .caution, "dd overwrites \(target).")281                }282            }283        case "diskutil":284            analyzeDiskutil(args, into: &c)285        case "fdisk", "gdisk", "sgdisk", "parted", "wipefs", "gpt", "newfs", "format":286            c.add(.rawDiskWrite, .destructive, "\(name) rewrites partition tables or filesystems.")287        case "git":288            analyzeGit(args, into: &c)289        case "chmod", "chown", "chgrp", "chflags":290            let recursive = args.contains { $0 == "--recursive" || ($0.hasPrefix("-") && !$0.hasPrefix("--") && $0.contains("R")) }291            if recursive {292                let broad = args.contains { !$0.hasPrefix("-") && Self.isRootLike($0) }293                c.add(.recursivePermissionChange, broad ? .destructive : .caution,294                      broad ? "Recursively changes ownership or permissions of a system or home directory."295                            : "Recursively changes ownership or permissions of a whole directory tree.")296            }297        case "sh", "bash", "zsh", "dash", "ksh", "fish", "python", "python3", "perl", "ruby", "node", "php", "osascript":298            analyzeInterpreter(name: name, args: args, context: context, state: state, depth: depth, into: &c)299        case "curl":300            if Self.curlUploads(args) {301                c.add(.networkTransfer, .caution, "curl uploads a local file to a remote server.")302            }303        case "wget":304            if args.contains(where: { $0.hasPrefix("--post-file") || $0.hasPrefix("--body-file") }) {305                c.add(.networkTransfer, .caution, "wget uploads a local file to a remote server.")306            }307        case "scp", "sftp", "ftp", "tftp":308            c.add(.networkTransfer, .caution, "\(name) transfers files to or from another machine.")309        case "rsync":310            if args.contains(where: Self.isRemoteSpec) {311                c.add(.networkTransfer, .caution, "rsync transfers files to or from another machine.")312            }313        case "nc", "ncat", "netcat", "socat", "telnet":314            c.add(.networkTransfer, .caution, "\(name) opens a raw network connection that can send or receive data.")315        case "rclone":316            if let verb = args.first(where: { !$0.hasPrefix("-") }), ["copy", "sync", "move", "copyto", "moveto"].contains(verb) {317                c.add(.networkTransfer, .caution, "rclone transfers files to or from remote storage.")318            }319        case "aws":320            if args.first == "s3", args.count > 1, ["cp", "sync", "mv"].contains(args[1]) {321                c.add(.networkTransfer, .caution, "aws s3 transfers files to or from remote storage.")322            }323        case "shutdown", "reboot", "halt", "poweroff":324            c.add(.powerControl, .destructive, "\(name) stops or restarts the machine and ends every session on it.")325        case "systemctl":326            if args.contains(where: { ["poweroff", "reboot", "halt", "kexec", "suspend", "hibernate"].contains($0) }) {327                c.add(.powerControl, .destructive, "Stops, suspends or restarts the machine.")328            }329        case "launchctl":330            if args.first == "reboot" {331                c.add(.powerControl, .destructive, "Restarts the machine or the user session.")332            }333        case "init", "telinit":334            if args.first == "0" || args.first == "6" {335                c.add(.powerControl, .destructive, "Stops or restarts the machine.")336            }337        case "kill":338            var everything = false339            for (i, arg) in args.enumerated() {340                if arg == "--" { everything = everything || args[(i + 1)...].contains("-1"); break }341                if arg == "-1" && i > 0 { everything = true }342            }343            if everything {344                c.add(.massKill, .destructive, "kill with pid -1 signals every process you are allowed to signal.")345            }346        case "killall", "pkill":347            c.add(.massKill, .caution, "\(name) terminates every process matching a name or pattern.")348        case "tee":349            let append = args.contains { $0 == "-a" || $0 == "--append" }350            for target in args where !target.hasPrefix("-") {351                if Self.isDiskDevice(target) {352                    c.add(.rawDiskWrite, .destructive, "tee writes directly to the disk device \(target).")353                } else if Self.isSystemPath(target) {354                    c.add(.systemPathOverwrite, append ? .caution : .destructive,355                          append ? "Appends to the system file \(target)." : "Overwrites the system file \(target).")356                }357            }358        case "mv", "cp":359            if let last = args.last, !last.hasPrefix("-"), args.count >= 2, Self.isSystemPath(last) {360                c.add(.systemPathOverwrite, .caution, "\(name) writes into the system location \(last).")361            }362        default:363            if name.hasPrefix("mkfs") || name.hasPrefix("newfs_") {364                c.add(.rawDiskWrite, .destructive, "\(name) creates a new filesystem, erasing the target device.")365            }366        }367    }368369    private func checkSubstitutedDownload(_ context: CommandContext, into c: inout Collector) {370        if context.substitutions.contains(where: Self.containsDownloader) {371            c.add(.pipeToShell, .destructive, "Executes code fetched from the network without any chance to review it.")372        }373    }374375    private func analyzeInterpreter(name: String, args: [String], context: CommandContext, state: LineState, depth: Int, into c: inout Collector) {376        let isShell = ["sh", "bash", "zsh", "dash", "ksh", "fish"].contains(name)377        var inline: String?378        var script: String?379        var forcedStdin = false380        var i = 0381        while i < args.count {382            let arg = args[i]383            if arg.hasPrefix("-") && arg.count > 1 {384                if isShell && !arg.hasPrefix("--") && arg.contains("s") { forcedStdin = true }385                if !arg.hasPrefix("--") && arg.contains("c") {386                    inline = i + 1 < args.count ? args[(i + 1)...].first { !$0.hasPrefix("-") } ?? "" : ""387                    break388                }389                if !arg.hasPrefix("--") && arg.contains("e") && !isShell { inline = ""; break }390                i += 1391            } else if arg == "-" {392                i += 1393            } else {394                script = arg395                break396            }397        }398        checkSubstitutedDownload(context, into: &c)399        if isShell, let inline, !inline.isEmpty {400            analyzeLine(inline, depth: depth + 1, into: &c)401        }402        let readsStdin = inline == nil && (forcedStdin || script == nil || script == "/dev/stdin")403        if context.pipedInput && readsStdin {404            if state.downloaderSeen {405                c.add(.pipeToShell, .destructive, "Pipes downloaded content straight into \(name), executing it without review.")406            } else {407                c.add(.pipeToShell, .caution, "Pipes generated text into \(name), which executes it.")408            }409        }410    }411412    private func analyzeRemove(name: String, args: [String], into c: inout Collector) {413        var recursive = false414        var forced = false415        for arg in args {416            if arg == "--" { break }417            if arg.hasPrefix("--") {418                if arg == "--recursive" { recursive = true }419                if arg == "--force" || arg == "--no-preserve-root" { forced = true }420            } else if arg.hasPrefix("-") {421                if arg.contains("r") || arg.contains("R") { recursive = true }422                if arg.contains("f") { forced = true }423            }424        }425        if name == "rm" && recursive {426            c.add(.recursiveDelete, .destructive,427                  forced ? "Recursively deletes files and directories without asking; this cannot be undone."428                         : "Recursively deletes files and directories; this cannot be undone.")429        } else if name == "shred" || name == "srm" || (name == "rm" && forced) {430            c.add(.forcedDelete, .caution, "Deletes files without confirmation; they do not go to the Trash.")431        } else {432            c.add(.fileDeletion, .caution, "Deletes files or directories; they do not go to the Trash.")433        }434    }435436    private func analyzeFind(_ args: [String], context: CommandContext, state: inout LineState, depth: Int, into c: inout Collector) {437        if args.contains("-delete") {438            c.add(.recursiveDelete, .destructive, "find -delete removes every matching file in the whole tree.")439        }440        var i = 0441        while i < args.count {442            if ["-exec", "-execdir", "-ok", "-okdir"].contains(args[i]) {443                var sub: [String] = []444                i += 1445                while i < args.count, args[i] != ";", args[i] != "+" {446                    if args[i] != "{}" { sub.append(args[i]) }447                    i += 1448                }449                if let first = sub.first, ["rm", "shred", "srm", "unlink"].contains(Self.basename(first)) {450                    c.add(.recursiveDelete, .destructive, "find runs a delete command on every matching file in the whole tree.")451                }452                analyzeCommand(sub, context: context, state: &state, depth: depth + 1, into: &c)453            }454            i += 1455        }456    }457458    private func analyzeDiskutil(_ args: [String], into c: inout Collector) {459        let verbs = args.filter { !$0.hasPrefix("-") }.map { $0.lowercased() }460        guard let verb = verbs.first else { return }461        let destructivePrefixes = ["erase", "partition", "reformat", "zerodisk", "randomdisk", "secureerase", "resetfusion"]462        var hit = destructivePrefixes.contains { verb.hasPrefix($0) }463        if ["apfs", "ap", "cs", "corestorage", "appleraid", "ar"].contains(verb), verbs.count > 1 {464            hit = hit || verbs[1].hasPrefix("delete") || verbs[1].hasPrefix("erase")465        }466        if hit {467            c.add(.rawDiskWrite, .destructive, "diskutil \(args.joined(separator: " ")) erases or repartitions a disk.")468        }469    }470471    private func analyzeGit(_ args: [String], into c: inout Collector) {472        var i = 0473        while i < args.count, args[i].hasPrefix("-") {474            i += ["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"].contains(args[i]) ? 2 : 1475        }476        guard i < args.count else { return }477        let sub = args[i]478        let rest = Array(args[(i + 1)...])479        func short(_ ch: Character) -> Bool { rest.contains { $0.hasPrefix("-") && !$0.hasPrefix("--") && $0.contains(ch) } }480        func long(_ flag: String) -> Bool { rest.contains { $0 == flag || $0.hasPrefix(flag + "=") } }481        let positional = rest.filter { !$0.hasPrefix("-") }482        var message: String?483        switch sub {484        case "push":485            if long("--force") || long("--force-with-lease") || long("--force-if-includes") || short("f") {486                message = "git push --force rewrites the remote branch; commits pushed by others can be lost."487            } else if long("--mirror") || long("--delete") || long("--prune") || short("d")488                        || positional.contains(where: { $0.hasPrefix("+") || $0.hasPrefix(":") }) {489                message = "This git push deletes or overwrites refs on the remote."490            }491        case "reset":492            if long("--hard") { message = "git reset --hard discards all uncommitted changes." }493        case "clean":494            if (short("f") || long("--force")) && !(short("n") || long("--dry-run")) {495                message = "git clean -f permanently deletes untracked files."496            }497        case "branch":498            if short("D") || ((short("d") || long("--delete")) && (short("f") || long("--force"))) {499                message = "git branch -D deletes a branch even if it is not merged."500            }501        case "checkout":502            if short("f") || long("--force") || rest.contains("--") || positional.contains(".") {503                message = "This git checkout discards uncommitted changes."504            }505        case "restore":506            if !(long("--staged") && !long("--worktree")) {507                message = "git restore discards uncommitted changes in the working tree."508            }509        case "stash":510            if let verb = positional.first, verb == "drop" || verb == "clear" {511                message = "git stash \(verb) permanently deletes stashed changes."512            }513        case "filter-branch", "filter-repo":514            message = "git \(sub) rewrites the history of the repository."515        case "reflog":516            if let verb = positional.first, verb == "expire" || verb == "delete" {517                message = "git reflog \(verb) removes the safety net used to recover lost commits."518            }519        case "gc":520            if rest.contains(where: { $0.hasPrefix("--prune") }) { message = "git gc --prune permanently removes unreachable objects." }521        case "update-ref":522            if short("d") { message = "git update-ref -d deletes a ref." }523        case "worktree":524            if positional.first == "remove", short("f") || long("--force") { message = "Force-removes a worktree with uncommitted changes." }525        default:526            break527        }528        if let message { c.add(.destructiveGit, .destructive, message) }529    }530531    // MARK: - Static helpers532533    private static let reservedWords: Set<String> = ["{", "}", "!", "if", "then", "else", "elif", "fi", "do", "done", "while", "until", "[[", "function"]534    private static let downloaders: Set<String> = ["curl", "wget", "fetch", "aria2c", "http", "https", "xh", "nc", "ncat", "netcat"]535    private static let networkCommands: Set<String> = [536        "curl", "wget", "nc", "ncat", "netcat", "socat", "telnet", "ssh", "scp", "sftp", "rsync", "ftp", "tftp",537        "mail", "mailx", "sendmail", "http", "https", "xh", "rclone", "aws", "gsutil",538    ]539540    private static func basename(_ path: String) -> String {541        guard let slash = path.lastIndex(of: "/") else { return path }542        let tail = path[path.index(after: slash)...]543        return tail.isEmpty ? path : String(tail)544    }545546    private static func isAssignment(_ word: String) -> Bool {547        guard let eq = word.firstIndex(of: "="), eq != word.startIndex else { return false }548        let name = word[..<eq]549        guard let first = name.first, first.isLetter || first == "_" else { return false }550        return name.allSatisfy { $0.isLetter || $0.isNumber || $0 == "_" }551    }552553    /// Drops leading options; a two-character option whose letter is in `valueFlags` also consumes its value.554    private static func skipOptions(_ args: [String], valueFlags: String) -> [String] {555        var i = 0556        while i < args.count {557            let arg = args[i]558            if arg == "--" { i += 1; break }559            guard arg.hasPrefix("-"), arg.count > 1 else { break }560            if arg.count == 2, let flag = arg.last, valueFlags.contains(flag) { i += 2 } else { i += 1 }561        }562        return i < args.count ? Array(args[i...]) : []563    }564565    private static func isRemoteSpec(_ arg: String) -> Bool {566        guard !arg.hasPrefix("-") else { return false }567        if arg.hasPrefix("rsync://") || arg.contains("::") { return true }568        guard let colon = arg.firstIndex(of: ":"), colon != arg.startIndex else { return false }569        return !arg[..<colon].contains("/")570    }571572    private static func withoutIdentityOptions(name: String, args: [String]) -> [String] {573        guard ["ssh", "scp", "sftp", "rsync", "ssh-copy-id"].contains(name) else { return args }574        var out: [String] = []575        var i = 0576        while i < args.count {577            let arg = args[i]578            if arg == "-i" { i += 2; continue }579            if arg == "-o", i + 1 < args.count, args[i + 1].lowercased().hasPrefix("identityfile") { i += 2; continue }580            if arg.hasPrefix("-i") && !arg.hasPrefix("--") && arg.count > 2 && arg.contains("/") { i += 1; continue }581            if arg.lowercased().hasPrefix("-oidentityfile") || arg.hasPrefix("ssh ") { i += 1; continue }582            out.append(arg)583            i += 1584        }585        return out586    }587588    private static let sensitiveSeparators = CharacterSet(charactersIn: " \t\n\"'`()<>|;&=@,")589    private static let sensitiveFragments = [590        ".aws/credentials", ".netrc", ".gnupg/", ".kube/config", ".docker/config.json", ".npmrc", ".pgpass",591        ".config/gh/hosts.yml", "/etc/shadow", "/etc/master.passwd", "/etc/sudoers", "keychain",592    ]593    private static let harmlessSSHFiles: Set<String> = ["known_hosts", "known_hosts.old", "config", "authorized_keys", ""]594595    static func referencesSensitivePath(_ text: String) -> Bool {596        for token in text.lowercased().components(separatedBy: sensitiveSeparators) where !token.isEmpty {597            if token.hasSuffix(".pub") { continue }598            let last = basename(token.hasSuffix("/") ? String(token.dropLast()) : token)599            if token.contains(".ssh/") && !harmlessSSHFiles.contains(token.hasSuffix("/") ? "" : last) { return true }600            if last.hasPrefix("id_rsa") || last.hasPrefix("id_ed25519") || last.hasPrefix("id_ecdsa") || last.hasPrefix("id_dsa") { return true }601            if last.hasPrefix(".") && (last.hasSuffix("history") || last == ".histfile") { return true }602            if last == ".env" || last.hasPrefix(".env.") { return true }603            if sensitiveFragments.contains(where: token.contains) { return true }604        }605        return false606    }607608    private static func isSensitiveCommand(name: String, args: [String]) -> Bool {609        switch name {610        case "history": return true611        case "fc": return args.contains { $0.hasPrefix("-") && $0.contains("l") }612        case "security":613            return args.contains { ["find-generic-password", "find-internet-password", "dump-keychain", "export"].contains($0) }614        case "gpg", "gpg2":615            return args.contains { $0.hasPrefix("--export-secret") }616        default: return false617        }618    }619620    private static func isEnvironmentDump(name: String, args: [String]) -> Bool {621        switch name {622        case "printenv": return true623        case "env", "set": return args.isEmpty624        case "export": return args.isEmpty || args == ["-p"]625        default: return false626        }627    }628629    private static func containsDownloader(_ source: String) -> Bool {630        let separators = CharacterSet(charactersIn: " \t\n|;&()`\"'")631        return source.components(separatedBy: separators).contains { downloaders.contains(basename($0).lowercased()) }632    }633634    private static func curlUploads(_ args: [String]) -> Bool {635        let fileData: Set<String> = ["-d", "--data", "--data-binary", "--data-ascii", "--json"]636        var i = 0637        while i < args.count {638            let arg = args[i]639            let next = i + 1 < args.count ? args[i + 1] : ""640            if arg == "--upload-file" || arg.hasPrefix("--upload-file=") { return true }641            if arg.hasPrefix("-") && !arg.hasPrefix("--") && arg.contains("T") { return true }642            if fileData.contains(arg), next.hasPrefix("@") { return true }643            if arg == "--data-urlencode", next.contains("@") { return true }644            if arg == "-F" || arg == "--form", next.contains("=@") || next.contains("=<") { return true }645            if arg.hasPrefix("--"), let eq = arg.firstIndex(of: "=") {646                let flag = String(arg[..<eq]), value = arg[arg.index(after: eq)...]647                if fileData.contains(flag), value.hasPrefix("@") { return true }648                if flag == "--data-urlencode", value.contains("@") { return true }649                if flag == "--form", value.contains("=@") || value.contains("=<") { return true }650            }651            if arg.hasPrefix("-d@") { return true }652            if arg.hasPrefix("-F"), arg.contains("=@") || arg.contains("=<") { return true }653            i += 1654        }655        return false656    }657658    static func isDiskDevice(_ path: String) -> Bool {659        let p = path.lowercased()660        guard p.hasPrefix("/dev/") else { return false }661        let node = p.dropFirst(5)662        return ["disk", "rdisk", "sd", "hd", "vd", "xvd", "nvme", "mmcblk", "dm-", "md", "loop", "mapper/", "sr"]663            .contains { node.hasPrefix($0) } && !node.hasPrefix("stdin")664    }665666    private static func isHarmlessDevice(_ path: String) -> Bool {667        let p = path.lowercased()668        return p == "/dev/null" || p == "/dev/zero" || p == "/dev/stdout" || p == "/dev/stderr"669            || p.hasPrefix("/dev/tty") || p.hasPrefix("/dev/fd/") || p == "-"670    }671672    private static let userWritablePrefixes = [673        "/tmp", "/var/tmp", "/var/folders", "/private/tmp", "/private/var/tmp", "/private/var/folders",674        "/users", "/home", "/volumes", "/opt/homebrew", "/dev",675    ]676    private static let systemPrefixes = [677        "/etc", "/usr", "/bin", "/sbin", "/system", "/library", "/var", "/boot", "/lib", "/lib64", "/opt",678        "/applications", "/root", "/proc", "/sys", "/private", "/cores",679    ]680681    static func isSystemPath(_ path: String) -> Bool {682        let p = path.lowercased()683        guard p.hasPrefix("/") else { return false }684        if p == "/" { return true }685        func under(_ prefix: String) -> Bool { p == prefix || p.hasPrefix(prefix + "/") }686        if userWritablePrefixes.contains(where: under) { return false }687        return systemPrefixes.contains(where: under)688    }689690    private static func isRootLike(_ path: String) -> Bool {691        ["/", "/*", "~", "~/", "~/*", "$HOME", "${HOME}", "$HOME/", "/Users", "/home", "/Volumes"].contains(path) || isSystemPath(path)692    }693694    static func looksLikeForkBomb(_ source: String) -> Bool {695        let compact = source.filter { !$0.isWhitespace }696        var searchStart = compact.startIndex697        while let range = compact.range(of: "(){", range: searchStart..<compact.endIndex) {698            var start = range.lowerBound699            while start > compact.startIndex {700                let previous = compact.index(before: start)701                if ";&|{}()".contains(compact[previous]) { break }702                start = previous703            }704            var name = String(compact[start..<range.lowerBound])705            if name.hasPrefix("function") { name.removeFirst("function".count) }706            if !name.isEmpty {707                let body = compact[range.upperBound...]708                if body.contains("\(name)|\(name)&") || body.contains("\(name)|\(name)|") { return true }709            }710            searchStart = range.upperBound711        }712        return false713    }714}715
Files main
Menu

Theme