diff --git a/internal/tools/command/hardline.go b/internal/tools/command/hardline.go new file mode 100644 index 000000000..2ceb416eb --- /dev/null +++ b/internal/tools/command/hardline.go @@ -0,0 +1,481 @@ +package command + +import ( + "fmt" + "os" + "strings" +) + +// Blocked reports a command line that must not run. It carries the +// offending segment so the refusal can name what was actually objected to +// rather than the whole line. +type Blocked struct { + // Rule is a short identifier for the rule that fired. + Rule string + // Reason explains the refusal in one line, shown to the model and the + // user. + Reason string + // Segment is the offending command as it appeared. + Segment string +} + +func (b *Blocked) Error() string { + if b.Segment == "" { + return fmt.Sprintf("refused (%s): %s", b.Rule, b.Reason) + } + return fmt.Sprintf("refused (%s): %s: %q", b.Rule, b.Reason, b.Segment) +} + +// Hardline checks a command line against the rules that hold regardless of +// configuration, approval, or operator instruction. +// +// This is deliberately a floor and not a security boundary. Anything with a +// shell has countless ways around a pattern list, and pretending otherwise +// would be worse than not having one. What it does buy is that the failure +// modes with no recovery -- the ones where you cannot intervene afterwards +// because the machine, the filesystem, or the gateway itself is gone -- are +// not reachable by an ordinary mistake. +// +// Two rules exist specifically to keep intervention possible: an agent must +// not be able to stop the daemon that hosts /stop, nor start a second one +// outside the supervisor's control. +func Hardline(line string) error { + return hardline(line, 0) +} + +// maxNesting bounds how far the rules follow a command into the commands it +// wraps. Real command lines nest once or twice; the limit only stops a +// pathological input from recursing without end. +const maxNesting = 8 + +func hardline(line string, depth int) error { + if line = strings.TrimSpace(line); line == "" { + return nil + } + + // The fork bomb is checked against the whole line because its + // definition spans the separators everything else is split on. + if isForkBomb(line) { + return &Blocked{ + Rule: "fork-bomb", + Reason: "exhausts the process table and requires a reboot to clear", + Segment: line, + } + } + + for _, seg := range Split(line) { + if err := checkSegment(seg, depth); err != nil { + return err + } + } + return nil +} + +// checkSegment applies every rule to one command invocation, then follows +// the segment into any command it merely wraps. +// +// Without that second step the rules are trivially defeated, and not only +// by someone trying: `bash -c "rm -rf /"` is a shape models produce +// unprompted, and `xargs rm -rf /` reads as ordinary shell. In both cases +// the dangerous command is an argument, so nothing above sees it. +func checkSegment(seg Segment, depth int) error { + for _, rule := range rules { + if reason, hit := rule.check(seg); hit { + return &Blocked{Rule: rule.name, Reason: reason, Segment: seg.Raw} + } + } + + if depth >= maxNesting { + return nil + } + + // A shell's -c argument is a whole command line of its own, quoting + // and separators included, so it goes back through the front door. + if payload, ok := shellPayload(seg); ok { + return hardline(payload, depth+1) + } + + // A wrapper's remaining words are one command, already tokenised. + if inner, ok := unwrap(seg); ok { + return checkSegment(inner, depth+1) + } + + return nil +} + +// shells run a command line supplied as an argument. +var shells = map[string]bool{ + "sh": true, "bash": true, "zsh": true, "dash": true, + "ksh": true, "ash": true, +} + +// shellPayload returns the command line a segment asks another shell to +// run, whether via `sh -c` or `eval`. +func shellPayload(seg Segment) (string, bool) { + base := baseName(seg.Name) + + if shells[base] { + for i, arg := range seg.Args { + if arg == "-c" && i+1 < len(seg.Args) { + return seg.Args[i+1], true + } + } + return "", false + } + + if base == "eval" && len(seg.Args) > 0 { + return strings.Join(seg.Args, " "), true + } + + return "", false +} + +// wrappers run another command rather than doing the work themselves, so +// the command that matters is further along the line. +var wrappers = map[string]bool{ + "xargs": true, "env": true, "nice": true, "ionice": true, + "timeout": true, "stdbuf": true, "time": true, "nohup": true, + "setsid": true, "unbuffer": true, "script": true, +} + +// unwrap returns the command a wrapper invokes. +// +// Flags, environment assignments, and bare numbers are skipped, the last +// because several wrappers take a leading value -- `timeout 30 rm -rf /` +// and `nice -n 10 rm -rf /` both have to resolve to the rm. +func unwrap(seg Segment) (Segment, bool) { + if !wrappers[baseName(seg.Name)] { + return Segment{}, false + } + for i, arg := range seg.Args { + if strings.HasPrefix(arg, "-") || isAssignment(arg) || isBareNumber(arg) { + continue + } + return segmentFromWords(strings.Join(seg.Args[i:], " "), seg.Args[i:]) + } + return Segment{}, false +} + +// isBareNumber reports whether a word is a plain count or duration, such +// as timeout's 30 or 1m. +func isBareNumber(word string) bool { + if word == "" { + return false + } + trimmed := strings.TrimRight(word, "smhd") + if trimmed == "" { + return false + } + for _, r := range trimmed { + if (r < '0' || r > '9') && r != '.' { + return false + } + } + return true +} + +type rule struct { + name string + check func(Segment) (string, bool) +} + +var rules = []rule{ + {"recursive-root-delete", checkRecursiveDelete}, + {"filesystem-format", checkMkfs}, + {"block-device-write", checkBlockDeviceWrite}, + {"kill-all-processes", checkKillAll}, + {"system-power", checkSystemPower}, + {"sudo-stdin-password", checkSudoStdin}, + {"daemon-self-termination", checkSelfTermination}, + {"daemon-launch", checkDaemonLaunch}, +} + +// criticalPaths are the delete targets with no recovery path. Anything +// outside this set is the operator's business, including recursive deletes +// inside the workspace. +var criticalPaths = map[string]bool{ + "/": true, "//": true, "/.": true, "/..": true, + "~": true, "$HOME": true, "${HOME}": true, + "/home": true, "/root": true, "/etc": true, "/usr": true, + "/var": true, "/bin": true, "/sbin": true, "/boot": true, + "/lib": true, "/lib64": true, "/opt": true, "/srv": true, + "/proc": true, "/sys": true, "/dev": true, +} + +// checkRecursiveDelete refuses a recursive rm whose target is a critical +// path. A recursive delete elsewhere is ordinary work and is allowed. +func checkRecursiveDelete(seg Segment) (string, bool) { + if seg.Name != "rm" { + return "", false + } + if !hasRecursiveFlag(seg.Args) { + return "", false + } + for _, arg := range seg.Args { + if strings.HasPrefix(arg, "-") { + continue + } + if isCriticalPath(arg) { + return "recursive delete of " + arg + ", which is not recoverable", true + } + } + return "", false +} + +// hasRecursiveFlag reports whether rm was asked to recurse, covering both +// the long form and bundled short flags such as -rf and -fr. +func hasRecursiveFlag(args []string) bool { + for _, arg := range args { + if arg == "--recursive" { + return true + } + if !strings.HasPrefix(arg, "-") || strings.HasPrefix(arg, "--") { + continue + } + if strings.ContainsAny(arg[1:], "rR") { + return true + } + } + return false +} + +// isCriticalPath reports whether a delete target names the filesystem root, +// a home directory, or a system directory -- with or without a trailing +// slash or glob. +func isCriticalPath(arg string) bool { + trimmed := strings.TrimSuffix(arg, "*") + trimmed = strings.TrimSuffix(trimmed, "/") + if trimmed == "" { + // The argument was "/" or "/*". + return true + } + return criticalPaths[trimmed] || criticalPaths[arg] +} + +// checkMkfs refuses any filesystem format. The tool name carries the type, +// so mkfs.ext4 and mkfs alike are matched on the prefix. +func checkMkfs(seg Segment) (string, bool) { + base := baseName(seg.Name) + if base == "mkfs" || strings.HasPrefix(base, "mkfs.") { + return "formats a filesystem, destroying everything on it", true + } + return "", false +} + +// checkBlockDeviceWrite refuses writes straight to a block device, whether +// through dd's of= or a shell redirect. /dev/null and /dev/zero are +// excluded: writing to them is routine and harmless. +func checkBlockDeviceWrite(seg Segment) (string, bool) { + if baseName(seg.Name) == "dd" { + for _, arg := range seg.Args { + target, ok := strings.CutPrefix(arg, "of=") + if ok && isBlockDevice(target) { + return "writes raw data to " + target + ", destroying the device's contents", true + } + } + } + for i, word := range seg.Words { + if word != ">" && word != ">>" { + continue + } + if i+1 < len(seg.Words) && isBlockDevice(seg.Words[i+1]) { + return "redirects output to the block device " + seg.Words[i+1], true + } + } + return "", false +} + +// isBlockDevice reports whether a path names a disk device rather than one +// of the harmless character devices. +func isBlockDevice(path string) bool { + if !strings.HasPrefix(path, "/dev/") { + return false + } + switch path { + case "/dev/null", "/dev/zero", "/dev/random", "/dev/urandom", "/dev/stdout", "/dev/stderr": + return false + } + name := strings.TrimPrefix(path, "/dev/") + for _, prefix := range []string{"sd", "nvme", "hd", "vd", "xvd", "mmcblk", "loop", "md", "dm-"} { + if strings.HasPrefix(name, prefix) { + return true + } + } + return false +} + +// checkKillAll refuses signalling every process, which takes down the +// daemon and anything else on the machine. +func checkKillAll(seg Segment) (string, bool) { + if baseName(seg.Name) != "kill" { + return "", false + } + for _, arg := range seg.Args { + if arg == "-1" { + return "signals every process on the system", true + } + } + return "", false +} + +// powerCommands halt or restart the machine outright. +var powerCommands = map[string]bool{ + "shutdown": true, "reboot": true, "halt": true, "poweroff": true, +} + +// checkSystemPower refuses anything that powers the machine down or +// restarts it. Matching is on the command position only, so a commit +// message or a log line mentioning reboot is unaffected. +func checkSystemPower(seg Segment) (string, bool) { + base := baseName(seg.Name) + if powerCommands[base] { + return "shuts down or restarts the machine", true + } + if base == "init" || base == "telinit" { + for _, arg := range seg.Args { + if arg == "0" || arg == "6" { + return "changes runlevel to shut down or reboot", true + } + } + } + if base == "systemctl" { + for _, arg := range seg.Args { + switch arg { + case "poweroff", "reboot", "halt", "kexec": + return "shuts down or restarts the machine", true + } + } + } + return "", false +} + +// checkSudoStdin refuses feeding sudo a password on stdin unless one has +// been configured deliberately. Without SUDO_PASSWORD set there is nothing +// legitimate to supply, so the flag only appears when something is trying +// passwords. +func checkSudoStdin(seg Segment) (string, bool) { + if !seg.Elevated || os.Getenv("SUDO_PASSWORD") != "" { + return "", false + } + for _, flag := range seg.ElevationArgs { + if flag == "-S" || flag == "--stdin" { + return "supplies a sudo password on stdin and no SUDO_PASSWORD is configured", true + } + if strings.HasPrefix(flag, "-") && !strings.HasPrefix(flag, "--") && strings.Contains(flag[1:], "S") { + return "supplies a sudo password on stdin and no SUDO_PASSWORD is configured", true + } + } + return "", false +} + +// daemonNames are the processes whose death removes the operator's ability +// to intervene. +var daemonNames = map[string]bool{"archied": true, "archie-agent": true} + +// checkSelfTermination refuses killing the daemon that hosts the gateway. +// +// /stop, approvals, and every other control run inside archied. An agent +// that can stop it can put itself beyond reach, and the only remaining +// recourse is physical access to the host. +func checkSelfTermination(seg Segment) (string, bool) { + base := baseName(seg.Name) + + if base == "pkill" || base == "killall" { + for _, arg := range seg.Args { + if strings.HasPrefix(arg, "-") { + continue + } + if namesDaemon(arg) { + return "kills the archie daemon, which is what /stop runs in", true + } + } + } + + if base == "systemctl" || base == "service" { + if hasAny(seg.Args, "stop", "kill", "disable", "mask", "restart") && anyNamesDaemon(seg.Args) { + return "stops the archie daemon, which is what /stop runs in", true + } + } + + // The docker socket is mounted, so the container is reachable from + // inside itself. + if base == "docker" || base == "podman" { + if hasAny(seg.Args, "stop", "kill", "rm", "restart", "down") && anyNamesDaemon(seg.Args) { + return "stops the archie daemon's container, which is what /stop runs in", true + } + } + + return "", false +} + +// checkDaemonLaunch refuses starting another daemon. +// +// A second archied outside the supervisor competes for the same Telegram +// updates and the same queues, and nothing is tracking it -- so it cannot +// be restarted, reconfigured, or stopped through any of the usual paths. +func checkDaemonLaunch(seg Segment) (string, bool) { + name := baseName(seg.Name) + if name == "nohup" || name == "setsid" { + if len(seg.Args) > 0 && namesDaemon(baseName(seg.Args[0])) { + return "starts a second archie daemon detached from the supervisor", true + } + return "", false + } + if daemonNames[name] { + return "starts a second archie daemon outside the supervisor", true + } + return "", false +} + +// namesDaemon reports whether an argument refers to an archie process or +// container. Container names carry a compose prefix and suffix, so this is +// a substring test rather than an exact one. +func namesDaemon(arg string) bool { + if daemonNames[arg] { + return true + } + return strings.Contains(arg, "archied") || strings.Contains(arg, "archie-agent") +} + +func anyNamesDaemon(args []string) bool { + for _, arg := range args { + if namesDaemon(arg) { + return true + } + } + return false +} + +func hasAny(args []string, wanted ...string) bool { + for _, arg := range args { + for _, w := range wanted { + if arg == w { + return true + } + } + } + return false +} + +// baseName strips any directory from a command, so that /sbin/reboot and +// reboot are judged the same. +func baseName(name string) string { + if i := strings.LastIndexAny(name, "/\\"); i >= 0 { + return name[i+1:] + } + return name +} + +// isForkBomb reports whether the line defines and invokes a +// self-replicating function. Whitespace is removed first because it is +// optional throughout the construct. +func isForkBomb(line string) bool { + compact := strings.Map(func(r rune) rune { + if r == ' ' || r == '\t' || r == '\n' || r == '\r' { + return -1 + } + return r + }, line) + return strings.Contains(compact, ":(){:|:&};:") || + strings.Contains(compact, ":(){:|:&};:&") +} diff --git a/internal/tools/command/hardline_test.go b/internal/tools/command/hardline_test.go new file mode 100644 index 000000000..ca575c147 --- /dev/null +++ b/internal/tools/command/hardline_test.go @@ -0,0 +1,188 @@ +package command_test + +import ( + "errors" + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/tools/command" +) + +// TestHardlineBlocks covers the commands that must never run. +func TestHardlineBlocks(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + line string + rule string + }{ + {"root delete", "rm -rf /", "recursive-root-delete"}, + {"root delete glob", "rm -rf /*", "recursive-root-delete"}, + {"root delete dot", "rm -rf /.", "recursive-root-delete"}, + {"root delete long flag", "rm --recursive --force /", "recursive-root-delete"}, + {"root delete bundled reverse", "rm -fr /", "recursive-root-delete"}, + {"home delete", "rm -rf ~", "recursive-root-delete"}, + {"home var delete", "rm -rf $HOME", "recursive-root-delete"}, + {"home brace delete", "rm -rf ${HOME}/", "recursive-root-delete"}, + {"etc delete", "rm -rf /etc", "recursive-root-delete"}, + {"usr glob delete", "rm -rf /usr/*", "recursive-root-delete"}, + {"quoted root delete", `rm -rf "/"`, "recursive-root-delete"}, + {"env prefixed delete", "FOO=bar rm -rf /", "recursive-root-delete"}, + {"sudo delete", "sudo rm -rf /", "recursive-root-delete"}, + + {"mkfs", "mkfs.ext4 /dev/sda1", "filesystem-format"}, + {"bare mkfs", "mkfs /dev/sdb", "filesystem-format"}, + + {"dd to disk", "dd if=/dev/zero of=/dev/sda bs=1M", "block-device-write"}, + {"dd to nvme", "dd if=x.img of=/dev/nvme0n1", "block-device-write"}, + {"redirect to disk", "echo x > /dev/sda", "block-device-write"}, + + {"fork bomb", ":(){ :|:& };:", "fork-bomb"}, + {"fork bomb compact", ":(){:|:&};:", "fork-bomb"}, + + {"kill all", "kill -9 -1", "kill-all-processes"}, + + {"shutdown", "shutdown -h now", "system-power"}, + {"reboot", "reboot", "system-power"}, + {"poweroff path", "/sbin/poweroff", "system-power"}, + {"init 0", "init 0", "system-power"}, + {"telinit 6", "telinit 6", "system-power"}, + {"systemctl reboot", "systemctl reboot", "system-power"}, + + {"sudo stdin", "sudo -S ls", "sudo-stdin-password"}, + + {"pkill daemon", "pkill archied", "daemon-self-termination"}, + {"killall daemon", "killall -9 archied", "daemon-self-termination"}, + {"systemctl stop daemon", "systemctl stop archied", "daemon-self-termination"}, + {"docker stop daemon", "docker stop archie-core-archied-1", "daemon-self-termination"}, + {"docker rm daemon", "docker rm -f archie-core-archied-1", "daemon-self-termination"}, + + {"launch daemon", "archied -config /etc/archie/config.toml", "daemon-launch"}, + {"nohup daemon", "nohup archied &", "daemon-launch"}, + + {"hidden after separator", "echo hello; rm -rf /", "recursive-root-delete"}, + {"hidden after and", "cd /tmp && rm -rf /", "recursive-root-delete"}, + {"hidden after pipe", "cat x | rm -rf /", "recursive-root-delete"}, + {"hidden in substitution", "echo $(rm -rf /)", "recursive-root-delete"}, + {"hidden in backticks", "echo `rm -rf /`", "recursive-root-delete"}, + {"hidden in subshell", "(rm -rf /)", "recursive-root-delete"}, + {"hidden after newline", "echo hi\nrm -rf /", "recursive-root-delete"}, + + // Wrapped forms. These are not exotic: `bash -c` is a shape + // models produce unprompted, and without unwrapping every rule + // above is one quotation mark away from being bypassed. + {"bash -c", `bash -c "rm -rf /"`, "recursive-root-delete"}, + {"sh -c single quoted", `sh -c 'rm -rf /'`, "recursive-root-delete"}, + {"eval", `eval "rm -rf /"`, "recursive-root-delete"}, + {"nested shells", `bash -c "sh -c 'rm -rf /'"`, "recursive-root-delete"}, + {"xargs", "xargs rm -rf /", "recursive-root-delete"}, + {"timeout with duration", "timeout 30 rm -rf /", "recursive-root-delete"}, + {"nice with flag value", "nice -n 10 rm -rf /", "recursive-root-delete"}, + {"env assignment", "env FOO=bar rm -rf /", "recursive-root-delete"}, + {"nohup wrapping delete", "nohup rm -rf / &", "recursive-root-delete"}, + {"wrapped power command", `bash -c "reboot"`, "system-power"}, + {"wrapped daemon kill", `sh -c "pkill archied"`, "daemon-self-termination"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + err := command.Hardline(tc.line) + if err == nil { + t.Fatalf("Hardline(%q) allowed the command", tc.line) + } + var blocked *command.Blocked + if !errors.As(err, &blocked) { + t.Fatalf("error type = %T, want *command.Blocked", err) + } + if blocked.Rule != tc.rule { + t.Errorf("rule = %q, want %q (reason: %s)", blocked.Rule, tc.rule, blocked.Reason) + } + if blocked.Reason == "" { + t.Error("refusal carries no reason, so the model cannot tell why") + } + }) + } +} + +// TestHardlineAllows is the half that decides whether this is usable. A +// blocklist that fires on commit messages and ordinary work would be +// turned off within a day, so the quoting and command-position analysis +// matters as much as the patterns. +func TestHardlineAllows(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + line string + }{ + {"echoing the string", `echo "rm -rf /"`}, + {"commit message", `git commit -m "revert the rm -rf / change"`}, + {"commit message single quotes", `git commit -m 'stop using rm -rf / in scripts'`}, + {"pr title", `gh pr create --title "guard against rm -rf /"`}, + {"grep for the pattern", `grep -r "rm -rf /" .`}, + {"writing a doc that mentions reboot", `echo "reboot the machine" > notes.txt`}, + + {"ordinary recursive delete", "rm -rf ./build"}, + {"recursive delete in workspace", "rm -rf /workspace/tmp"}, + {"recursive delete of subdir", "rm -rf /var/lib/archie/work/tmp"}, + {"non-recursive root file", "rm /tmp/x"}, + + {"dd to a file", "dd if=/dev/zero of=disk.img bs=1M count=10"}, + {"redirect to null", "echo x > /dev/null"}, + {"redirect to a file", "go test ./... > out.txt"}, + + {"killing a pid", "kill -9 12345"}, + {"pkill something else", "pkill node"}, + {"systemctl status", "systemctl status archied"}, + {"systemctl restart something else", "systemctl restart nginx"}, + {"docker ps", "docker ps -a"}, + {"docker stop another container", "docker stop nats"}, + + {"sudo without stdin", "sudo apt-get update"}, + {"ordinary build", "go build ./..."}, + {"chained ordinary commands", "cd /workspace && go test ./... && git status"}, + {"empty", ""}, + {"whitespace", " "}, + + // The unwrapping must not turn ordinary wrapped commands into + // refusals. + {"bash -c ordinary", `bash -c "go test ./..."`}, + {"bash -c mentioning the string", `bash -c 'echo "rm -rf /"'`}, + {"xargs ordinary", "find . -name '*.tmp' | xargs rm -f"}, + {"timeout ordinary", "timeout 30 go test ./..."}, + {"env ordinary", "env GOFLAGS=-mod=mod go build ./..."}, + {"nohup ordinary", "nohup ./long-running-job &"}, + {"deeply nested ordinary", `bash -c "sh -c 'echo hello'"`}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + if err := command.Hardline(tc.line); err != nil { + t.Errorf("Hardline(%q) blocked an ordinary command: %v", tc.line, err) + } + }) + } +} + +// TestBlockedErrorNamesTheSegment keeps the refusal actionable: the model +// has to be able to tell which part of a chained command was objected to. +func TestBlockedErrorNamesTheSegment(t *testing.T) { + t.Parallel() + + err := command.Hardline("go build ./... && rm -rf /etc") + if err == nil { + t.Fatal("Hardline allowed a recursive delete of /etc") + } + msg := err.Error() + if !strings.Contains(msg, "rm -rf /etc") { + t.Errorf("error %q does not name the offending segment", msg) + } + if strings.Contains(msg, "go build") { + t.Errorf("error %q blames the wrong segment", msg) + } +} diff --git a/internal/tools/command/parse.go b/internal/tools/command/parse.go new file mode 100644 index 000000000..766648488 --- /dev/null +++ b/internal/tools/command/parse.go @@ -0,0 +1,270 @@ +// Package command inspects shell command lines before they are executed. +// +// It exists because a substring search over a command line is wrong in both +// directions. `git commit -m "revert the rm -rf change"` is harmless and +// would be blocked; `echo x; rm -rf /` is not and, with a naive anchor on +// the start of the line, would be allowed. Deciding either way requires +// knowing where a command actually begins, which means parsing quoting and +// separators rather than pattern-matching the raw text. +// +// Tool execution owns command constraints (see docs/architecture/policy.md). +// When internal/policy's evaluation API lands, [Hardline] becomes an +// evaluator registered there; the rules themselves stay here. +package command + +import "strings" + +// Segment is one command invocation found within a command line, already +// split from its neighbours and stripped of quoting. +type Segment struct { + // Raw is the segment's original text, for reporting. + Raw string + // Words are the segment's tokens with quoting removed, including any + // privilege wrapper such as sudo. + Words []string + // Name is the command being invoked: the first word after leading + // environment assignments and privilege wrappers have been skipped. + // Empty when the segment invokes nothing. + Name string + // Args are the words following Name. + Args []string + // Elevated reports whether the segment runs through sudo or doas. + Elevated bool + // ElevationArgs are the flags given to that privilege wrapper. + ElevationArgs []string +} + +// Split breaks a command line into the individual commands within it. +// +// Separators are only honoured outside quotes, which is what keeps a +// quoted argument from being read as a new command: in +// `echo "a; rm -rf /"` the semicolon is data, so the whole line is one +// segment whose command is echo. Command substitutions and subshells do +// start new commands, so `$(rm -rf /)` and `(rm -rf /)` are seen. +func Split(line string) []Segment { + var ( + segments []Segment + current strings.Builder + quote rune + escaped bool + prev rune + // varBraces counts open ${...} expansions. Their braces are part + // of a word, unlike the braces of a { cmd; } group, so they must + // not split the line -- otherwise ${HOME} parses as the separate + // pieces "$", "HOME" and the rest. + varBraces int + ) + + flush := func() { + if seg, ok := newSegment(current.String()); ok { + segments = append(segments, seg) + } + current.Reset() + } + + runes := []rune(line) + for i := 0; i < len(runes); i++ { + r := runes[i] + + if escaped { + current.WriteRune(r) + escaped = false + prev = r + continue + } + // Inside single quotes a backslash is literal, so escaping only + // applies elsewhere. + if r == '\\' && quote != '\'' { + current.WriteRune(r) + escaped = true + prev = r + continue + } + + if quote != 0 { + current.WriteRune(r) + if r == quote { + quote = 0 + } + prev = r + continue + } + if r == '\'' || r == '"' { + current.WriteRune(r) + quote = r + prev = r + continue + } + + // ${...} is one word, not a brace group. + if r == '{' && prev == '$' { + varBraces++ + current.WriteRune(r) + prev = r + continue + } + if r == '}' && varBraces > 0 { + varBraces-- + current.WriteRune(r) + prev = r + continue + } + + // Unquoted from here: these end the current command and begin + // another. Backtick and the bracket forms are included because a + // substitution, subshell, or brace group contains commands of its + // own -- `echo $(rm -rf /)` must be seen as an rm. + if strings.ContainsRune(";&|\n()`{}", r) { + flush() + prev = r + continue + } + current.WriteRune(r) + prev = r + } + flush() + + return segments +} + +// newSegment tokenises one segment, reporting false when it invokes +// nothing. +func newSegment(raw string) (Segment, bool) { + return segmentFromWords(strings.TrimSpace(raw), tokenise(raw)) +} + +// segmentFromWords builds a segment from already-tokenised words. It is +// shared with wrapper unwrapping, where the inner command is a slice of an +// outer segment's words and re-parsing text would lose the original +// quoting. +func segmentFromWords(raw string, words []string) (Segment, bool) { + if len(words) == 0 { + return Segment{}, false + } + + seg := Segment{Raw: raw, Words: words} + + // Leading NAME=value pairs set the environment for the command that + // follows rather than being the command, so `FOO=bar rm -rf /` is an + // rm invocation. + i := 0 + for i < len(words) && isAssignment(words[i]) { + i++ + } + + // A privilege wrapper likewise fronts the real command. Its own flags + // are kept, because some of them are the thing worth refusing. + if i < len(words) && (words[i] == "sudo" || words[i] == "doas") { + seg.Elevated = true + i++ + for i < len(words) && strings.HasPrefix(words[i], "-") { + seg.ElevationArgs = append(seg.ElevationArgs, words[i]) + i++ + } + // sudo VAR=value cmd is accepted by sudo too. + for i < len(words) && isAssignment(words[i]) { + i++ + } + } + + if i >= len(words) { + // Nothing but assignments or a bare sudo: no command to judge, + // but the elevation flags may still matter. + return seg, seg.Elevated + } + + seg.Name = words[i] + seg.Args = words[i+1:] + return seg, true +} + +// tokenise splits a segment into words, removing quotes and treating +// redirection operators as words of their own so that a redirect target +// can be examined. +func tokenise(raw string) []string { + var ( + words []string + current strings.Builder + quote rune + escaped bool + filled bool + ) + + end := func() { + if filled { + words = append(words, current.String()) + current.Reset() + filled = false + } + } + + for _, r := range raw { + if escaped { + current.WriteRune(r) + filled = true + escaped = false + continue + } + if r == '\\' && quote != '\'' { + escaped = true + continue + } + + if consumed := consumeQuote(r, "e, ¤t, &filled); consumed { + continue + } + + switch r { + case ' ', '\t', '\r': + end() + case '>', '<': + end() + words = append(words, string(r)) + default: + current.WriteRune(r) + filled = true + } + } + end() + + return words +} + +// consumeQuote handles one rune's interaction with quoting, reporting +// whether it was consumed. Quote characters themselves are dropped: the +// caller wants an argument's value, so that "/" and / compare equal. +func consumeQuote(r rune, quote *rune, current *strings.Builder, filled *bool) bool { + if *quote != 0 { + if r == *quote { + *quote = 0 + return true + } + current.WriteRune(r) + *filled = true + return true + } + if r == '\'' || r == '"' { + *quote = r + // An empty quoted string is still a word. + *filled = true + return true + } + return false +} + +// isAssignment reports whether a word is a NAME=value environment +// assignment rather than a command. +func isAssignment(word string) bool { + eq := strings.Index(word, "=") + if eq <= 0 { + return false + } + for i, r := range word[:eq] { + isLetter := (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || r == '_' + isDigit := r >= '0' && r <= '9' + if !isLetter && (!isDigit || i == 0) { + return false + } + } + return true +} diff --git a/internal/tools/provider/builtin/provider.go b/internal/tools/provider/builtin/provider.go index ef5863a6e..aa780b7bc 100644 --- a/internal/tools/provider/builtin/provider.go +++ b/internal/tools/provider/builtin/provider.go @@ -17,6 +17,7 @@ import ( "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/tools" toolsbuiltin "github.com/samcharles93/archie-core/internal/tools/builtin" + "github.com/samcharles93/archie-core/internal/tools/command" ) // toolset groups these tools for progressive disclosure and guardrails. @@ -137,6 +138,10 @@ func toEntry(tool toolsbuiltin.Tool) (tools.ToolEntry, error) { // and the guardrail engine both see it. func handlerFor(tool toolsbuiltin.Tool) tools.Handler { return func(ctx context.Context, input map[string]any) (any, error) { + if err := screen(tool.Schema.Name, input); err != nil { + return nil, err + } + params := json.RawMessage("{}") if len(input) > 0 { encoded, err := json.Marshal(input) @@ -163,6 +168,24 @@ func handlerFor(tool toolsbuiltin.Tool) tools.Handler { } } +// screen applies the always-on command rules before a tool runs. +// +// This lives in the adapter rather than in the lifted shell tool so that +// the copied files stay diffable against tau, and so the rules are archie's +// to change. It is a floor, not a sandbox: anything with a shell has ways +// around a rule list, and the point is only that the failures with no +// recovery are not reachable by an ordinary mistake. +func screen(name string, input map[string]any) error { + if name != "shell" { + return nil + } + line, _ := input["command"].(string) + if err := command.Hardline(line); err != nil { + return fmt.Errorf("tool shell: %w", err) + } + return nil +} + // classify tags each tool so the guardrail engine and budget enforcement // can reason about it. This is categorisation, not a jail: it describes // what a tool does and does not gate whether it may run. diff --git a/internal/tools/provider/builtin/provider_test.go b/internal/tools/provider/builtin/provider_test.go index 6c1d96e3d..4ce9ac5a7 100644 --- a/internal/tools/provider/builtin/provider_test.go +++ b/internal/tools/provider/builtin/provider_test.go @@ -101,6 +101,55 @@ func TestHandlerSurfacesToolFailureAsError(t *testing.T) { t.Fatal("no read tool discovered") } +// TestShellHandlerEnforcesHardlineRules checks the rules are actually +// wired into the executing handler. The rules are tested in +// internal/tools/command; what matters here is that a call cannot reach +// tau's executor without passing through them. +func TestShellHandlerEnforcesHardlineRules(t *testing.T) { + t.Parallel() + + shell := shellHandler(t, t.TempDir()) + + if _, err := shell(context.Background(), map[string]any{"command": "rm -rf /"}); err == nil { + t.Error("the shell tool accepted a recursive delete of /") + } else if !strings.Contains(err.Error(), "refused") { + t.Errorf("error = %v, want a refusal naming the rule", err) + } +} + +// TestShellHandlerAllowsOrdinaryCommands guards the other direction: the +// screen must not stand between the model and normal work. +func TestShellHandlerAllowsOrdinaryCommands(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + out, err := shellHandler(t, dir)(context.Background(), map[string]any{ + "command": `echo "rm -rf / is only mentioned here"`, + }) + if err != nil { + t.Fatalf("an ordinary echo was refused: %v", err) + } + if text, ok := out.(string); !ok || !strings.Contains(text, "only mentioned here") { + t.Errorf("shell returned %#v, want the echoed text", out) + } +} + +func shellHandler(t *testing.T, workspace string) func(context.Context, map[string]any) (any, error) { + t.Helper() + + entries, err := startedProvider(t, workspace).Discover(context.Background()) + if err != nil { + t.Fatalf("Discover: %v", err) + } + for _, e := range entries { + if e.Name == "shell" { + return e.Handler + } + } + t.Fatal("no shell tool discovered") + return nil +} + // TestUnconfiguredWorkspaceIsRejected keeps the tools from silently rooting // at the daemon's own working directory, which in the container is /. func TestUnconfiguredWorkspaceIsRejected(t *testing.T) {