From 8f0b73f5145ed012a9ae808613fa79643ccae6a8 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:15:53 +0100 Subject: [PATCH 1/4] fix(intercept): match argv deny and ask rules across compound and wrapped Bash commands --- intercept/argv_compound.go | 576 ++++++++++++++++++++++++++++++++ intercept/argv_compound_test.go | 238 +++++++++++++ intercept/intercept.go | 18 +- 3 files changed, 827 insertions(+), 5 deletions(-) create mode 100644 intercept/argv_compound.go create mode 100644 intercept/argv_compound_test.go diff --git a/intercept/argv_compound.go b/intercept/argv_compound.go new file mode 100644 index 0000000..e4a021b --- /dev/null +++ b/intercept/argv_compound.go @@ -0,0 +1,576 @@ +package intercept + +import ( + "encoding/json" + "path" + "strings" + + "mvdan.cc/sh/v3/syntax" +) + +// argvMaxNestedPayloads bounds how deeply nested shell/eval payloads +// (for example, bash -c "bash -c ...") are re-parsed and walked. +const argvMaxNestedPayloads = 3 + +// callWord is one argument word of a *syntax.CallExpr for deny/ask matching. +// Literal is true when the word contains no runtime expansion; Value holds the +// unquoted text. AssignLike is true when the word begins with a literal +// NAME= prefix (for example FOO=1 or FOO=$(id)), so wrappers like env and sudo +// can skip environment assignments without skipping arbitrary opaque tokens. +type callWord struct { + Value string + Literal bool + AssignLike bool +} + +// argvCompoundMatches reports whether any command executed within a Bash tool +// call matches the deny/ask prefix rule tokens. It parses the entire Bash line, +// walks every *syntax.CallExpr in the AST, strips known wrapper programs, and +// recurses into eval and shell -c payloads up to argvMaxNestedPayloads deep. +// +// Parse errors never panic and always return false (no match). +func argvCompoundMatches(tokens []string, toolName string, input []byte) bool { + if toolName != "Bash" || len(tokens) == 0 { + return false + } + var in struct { + Command string `json:"command"` + } + if json.Unmarshal(input, &in) != nil { + return false + } + if strings.TrimSpace(in.Command) == "" { + return false + } + return bashCommandMatchesArgv(tokens, in.Command, 0) +} + +func bashCommandMatchesArgv(rule []string, command string, depth int) bool { + f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(command), "") + if err != nil { + return false + } + matched := false + syntax.Walk(f, func(n syntax.Node) bool { + if matched { + return false + } + call, ok := n.(*syntax.CallExpr) + if !ok || len(call.Args) == 0 { + return true + } + words := make([]callWord, len(call.Args)) + for i, w := range call.Args { + words[i] = callWordOf(w) + } + if callMatchesArgv(rule, words, depth) { + matched = true + return false + } + return true + }) + return matched +} + +// callMatchesArgv checks a single call's argv against rule, stripping known +// wrappers repeatedly and recursing into eval / shell -c payloads up to +// argvMaxNestedPayloads deep. +func callMatchesArgv(rule []string, argv []callWord, depth int) bool { + cur := argv + for len(cur) > 0 { + if argvMatchesRulePrefix(rule, cur) { + return true + } + if !cur[0].Literal || cur[0].Value == "" { + return false + } + prog := path.Base(cur[0].Value) + + // Nested Bash payload wrappers: eval and shells with -c. + if prog == "eval" { + if depth >= argvMaxNestedPayloads { + return false + } + payload, ok := evalPayload(cur[1:]) + if !ok { + return false + } + return bashCommandMatchesArgv(rule, payload, depth+1) + } + if isShellWrapper(prog) { + if depth >= argvMaxNestedPayloads { + return false + } + payload, ok := shellDashCPayload(cur[1:]) + if !ok { + return false + } + return bashCommandMatchesArgv(rule, payload, depth+1) + } + + // Direct command-wrapping programs. + next, ok := stripOneWrapper(prog, cur[1:]) + if !ok || len(next) == 0 || len(next) >= len(cur) { + return false + } + cur = next + } + return false +} + +// argvMatchesRulePrefix compares rule against the first len(rule) tokens of +// argv. For token 0, a rule token without a path separator matches the basename +// of the actual program; a rule token with a separator must match verbatim. +func argvMatchesRulePrefix(rule []string, argv []callWord) bool { + if len(rule) == 0 || len(argv) < len(rule) { + return false + } + for i, want := range rule { + if !argv[i].Literal { + return false + } + got := argv[i].Value + if i == 0 { + if got == "" { + return false + } + if !strings.ContainsAny(want, "/\\") { + got = path.Base(got) + } + } + if got != want { + return false + } + } + return true +} + +// callWordOf converts a Bash AST word into a callWord. Words containing any +// expansion (parameter, command/process substitution, arithmetic, glob, brace, +// tilde, ANSI-C/locale quoting) become opaque (Literal: false) rather than +// failing the whole call. +func callWordOf(w *syntax.Word) callWord { + if w == nil || len(w.Parts) == 0 { + return callWord{} + } + assignLike := false + if firstLit, ok := w.Parts[0].(*syntax.Lit); ok && hasAssignPrefix(firstLit.Value) { + assignLike = true + } + + var sb strings.Builder + literal := true + for _, part := range w.Parts { + switch p := part.(type) { + case *syntax.Lit: + s, ok := unescapeBareLit(p.Value) + if !ok { + literal = false + continue + } + sb.WriteString(s) + case *syntax.SglQuoted: + if p.Dollar { + literal = false + continue + } + sb.WriteString(p.Value) + case *syntax.DblQuoted: + if p.Dollar { + literal = false + continue + } + for _, q := range p.Parts { + lit, ok := q.(*syntax.Lit) + if !ok { + literal = false + break + } + sb.WriteString(unescapeDblQuotedLit(lit.Value)) + } + default: + literal = false + } + } + if !literal { + return callWord{Literal: false, AssignLike: assignLike} + } + val := sb.String() + if !assignLike && hasAssignPrefix(val) { + assignLike = true + } + return callWord{Value: val, Literal: true, AssignLike: assignLike} +} + +func unescapeBareLit(s string) (string, bool) { + var sb strings.Builder + sb.Grow(len(s)) + hasOpenBrace := false + hasCloseBrace := false + for i := 0; i < len(s); i++ { + c := s[i] + if c == '\\' { + if i+1 >= len(s) { + return "", false + } + i++ + if s[i] == '\n' { + continue + } + sb.WriteByte(s[i]) + continue + } + switch c { + case '*', '?', '[', ']', '~': + return "", false + case '{': + hasOpenBrace = true + case '}': + hasCloseBrace = true + } + sb.WriteByte(c) + } + if hasOpenBrace && hasCloseBrace && (strings.Contains(s, ",") || strings.Contains(s, "..")) { + return "", false + } + return sb.String(), true +} + +func unescapeDblQuotedLit(s string) string { + var sb strings.Builder + sb.Grow(len(s)) + for i := 0; i < len(s); i++ { + if s[i] == '\\' && i+1 < len(s) { + switch s[i+1] { + case '\n': + i++ + continue + case '"', '$', '`', '\\': + i++ + sb.WriteByte(s[i]) + continue + } + } + sb.WriteByte(s[i]) + } + return sb.String() +} + +func hasAssignPrefix(s string) bool { + eq := strings.IndexByte(s, '=') + if eq <= 0 { + return false + } + for i := 0; i < eq; i++ { + c := s[i] + isLetter := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' + isDigit := c >= '0' && c <= '9' + if i == 0 && !isLetter { + return false + } + if !isLetter && !isDigit { + return false + } + } + return true +} + +func isShellWrapper(prog string) bool { + switch prog { + case "sh", "bash", "zsh", "dash", "ksh", "fish": + return true + } + return false +} + +// shellDashCPayload extracts the literal command string following a leading +// "-c" option. Other shell options are intentionally not interpreted. +func shellDashCPayload(args []callWord) (string, bool) { + if len(args) < 2 { + return "", false + } + if !args[0].Literal || args[0].Value != "-c" { + return "", false + } + if !args[1].Literal { + return "", false + } + return args[1].Value, true +} + +// evalPayload joins eval's arguments with spaces for re-parsing as Bash. +// A leading "--" is stripped. Opaque arguments are substituted with an +// unexpanded placeholder ($__opaque) so they never shift a later literal word +// into command position, while trailing opaque args still let a leading literal +// command match. +func evalPayload(args []callWord) (string, bool) { + if len(args) > 0 && args[0].Literal && args[0].Value == "--" { + args = args[1:] + } + if len(args) == 0 { + return "", false + } + parts := make([]string, 0, len(args)) + hasLiteral := false + for _, a := range args { + if a.Literal { + parts = append(parts, a.Value) + hasLiteral = true + } else { + parts = append(parts, "$__opaque") + } + } + if !hasLiteral { + return "", false + } + return strings.Join(parts, " "), true +} + +// wrapperSpec describes the handled leading-option layout for a wrapper +// program. Any flag not listed in shortNoArg, shortArg, longNoArg, longArg, +// or longOptVal causes stripping to skip the call rather than guess. +type wrapperSpec struct { + shortNoArg string // short flags that take no argument + shortArg string // short flags that take one argument (attached or next token) + shortOptAtt string // short flags that accept only an optional attached argument (never next token) + longNoArg map[string]bool // --flag (no value) + longArg map[string]bool // --flag VAL or --flag=VAL + longOptVal map[string]bool // --flag or --flag=VAL (never consumes next token) + allowBareMin bool // treat bare "-" as a no-arg option (env -) + allowNumFlag bool // treat - as a no-arg option (nice -10) + skipAssigns bool // skip NAME=VALUE tokens after options (env, sudo) + posBeforeCmd int // required positional arguments before the wrapped command +} + +func strSet(names ...string) map[string]bool { + m := make(map[string]bool, len(names)) + for _, n := range names { + m[n] = true + } + return m +} + +var wrapperSpecs = map[string]wrapperSpec{ + "env": { + shortNoArg: "i0v", + shortArg: "uCSa", + longNoArg: strSet("ignore-environment", "null", "debug"), + longArg: strSet("unset", "chdir", "split-string", "argv0"), + longOptVal: strSet("block-signal", "default-signal", "ignore-signal"), + allowBareMin: true, + skipAssigns: true, + }, + "command": { + shortNoArg: "p", + }, + "builtin": {}, + "exec": { + shortNoArg: "cl", + shortArg: "a", + }, + "nohup": {}, + "setsid": { + shortNoArg: "cfw", + longNoArg: strSet("ctty", "fork", "wait"), + }, + "stdbuf": { + shortArg: "ioe", + longArg: strSet("input", "output", "error"), + }, + "nice": { + shortArg: "n", + longArg: strSet("adjustment"), + allowNumFlag: true, + }, + "ionice": { + shortNoArg: "t", + shortArg: "cn", + longNoArg: strSet("ignore"), + longArg: strSet("class", "classdata"), + }, + "timeout": { + shortNoArg: "fpv", + shortArg: "ks", + longNoArg: strSet("foreground", "preserve-status", "verbose"), + longArg: strSet("kill-after", "signal"), + posBeforeCmd: 1, // DURATION + }, + "taskset": { + shortNoArg: "ca", + longNoArg: strSet("cpu-list", "all-tasks"), + posBeforeCmd: 1, // MASK / CPU-LIST + }, + "chrt": { + shortNoArg: "abdforiRv", + shortArg: "TPD", + longNoArg: strSet("all-tasks", "batch", "deadline", "fifo", "idle", "other", "rr", "reset-on-fork", "verbose"), + longArg: strSet("sched-runtime", "sched-period", "sched-deadline"), + posBeforeCmd: 1, // PRIORITY + }, + "sudo": { + shortNoArg: "AbBEHikKnPsSv", + shortArg: "CDgprRtTuU", + longNoArg: strSet("askpass", "background", "bell", "set-home", "login", "reset-timestamp", "remove-timestamp", "non-interactive", "preserve-groups", "shell", "stdin", "validate"), + longArg: strSet("close-from", "chdir", "group", "host", "prompt", "role", "chroot", "type", "command-timeout", "user", "other-user"), + longOptVal: strSet("preserve-env"), + skipAssigns: true, + }, + "doas": { + shortNoArg: "Lns", + shortArg: "au", + }, + "watch": { + shortNoArg: "bcCdegprtwx", + shortArg: "nq", + longNoArg: strSet("beep", "color", "no-color", "errexit", "chgexit", "precise", "no-rerun", "no-title", "no-wrap", "exec"), + longArg: strSet("interval", "equexit"), + longOptVal: strSet("differences"), + }, + "flock": { + shortNoArg: "sxeunFo", + shortArg: "wE", + longNoArg: strSet("shared", "exclusive", "unlock", "nb", "nonblock", "no-fork", "close", "verbose"), + longArg: strSet("timeout", "wait", "conflict-exit-code"), + posBeforeCmd: 1, // LOCKFILE + }, + "strace": { + shortNoArg: "cCdfFikqrtTvwxyYzZ", + shortArg: "abeEIoOpPsSuUX", + longNoArg: strSet("summary-only", "summary", "debug", "follow-forks", "instruction-pointer", "stack-traces", "quiet", "relative-timestamps", "absolute-timestamps", "syscall-times", "no-abbrev", "summary-wall-clock", "hex", "decode-fds", "decode-pids", "successful-only", "failed-only"), + longArg: strSet("columns", "detach-on", "trace", "env", "interruptible", "output", "output-separately", "attach", "trace-path", "string-limit", "summary-sort-by", "user", "signal", "status", "inject", "fault", "raw", "read", "write", "abbrev", "verbose", "silence", "strings-in-hex", "const-print-style"), + }, + "ltrace": { + shortNoArg: "bcCfiLrStT", + shortArg: "aADeFlnopsuwx", + longNoArg: strSet("no-signals", "demangle", "syscalls"), + longArg: strSet("align", "arraylen", "config", "debug", "library", "indent", "output", "attach", "strsize", "username", "where"), + }, + "xargs": { + shortNoArg: "0oprtx", + shortArg: "adEILnPsR", + shortOptAtt: "ei", + longNoArg: strSet("null", "open-tty", "interactive", "no-run-if-empty", "verbose", "exit", "show-limits"), + longArg: strSet("arg-file", "delimiter", "eof", "replace", "max-lines", "max-args", "max-procs", "max-chars", "process-slot-var"), + }, +} + +func stripOneWrapper(prog string, args []callWord) ([]callWord, bool) { + spec, ok := wrapperSpecs[prog] + if !ok { + return nil, false + } + i := 0 + for i < len(args) { + if !args[i].Literal { + if spec.skipAssigns && args[i].AssignLike { + break + } + // Do not guess past an opaque token in option position. + return nil, false + } + tok := args[i].Value + if tok == "--" { + i++ + break + } + if tok == "-" { + if spec.allowBareMin { + i++ + continue + } + break + } + if !strings.HasPrefix(tok, "-") { + break + } + if strings.HasPrefix(tok, "--") { + name := tok[2:] + if eq := strings.IndexByte(name, '='); eq >= 0 { + flagName := name[:eq] + if spec.longArg[flagName] || spec.longOptVal[flagName] { + i++ + continue + } + return nil, false + } + if spec.longNoArg[name] || spec.longOptVal[name] { + i++ + continue + } + if spec.longArg[name] { + if i+1 >= len(args) { + return nil, false + } + i += 2 + continue + } + return nil, false + } + + // Short flag or combined short-flag cluster (e.g. -nu root, -uFOO). + flags := tok[1:] + if spec.allowNumFlag && isAllDigits(flags) { + i++ + continue + } + consumedNext := false + for j := 0; j < len(flags); j++ { + ch := flags[j] + switch { + case strings.IndexByte(spec.shortNoArg, ch) >= 0: + continue + case strings.IndexByte(spec.shortOptAtt, ch) >= 0: + // Optional value only when attached in the same token; never consumes next token. + j = len(flags) + case strings.IndexByte(spec.shortArg, ch) >= 0: + if j+1 < len(flags) { + // Attached value consumes the rest of this token. + j = len(flags) + } else { + if i+1 >= len(args) { + return nil, false + } + consumedNext = true + } + default: + // Unhandled flag: skip this call rather than guessing whether it takes a value. + return nil, false + } + } + if consumedNext { + i += 2 + } else { + i++ + } + } + + if spec.skipAssigns { + for i < len(args) && args[i].AssignLike { + i++ + } + } + + if spec.posBeforeCmd > 0 { + if i+spec.posBeforeCmd > len(args) { + return nil, false + } + i += spec.posBeforeCmd + } + + if i >= len(args) { + return nil, false + } + return args[i:], true +} + +func isAllDigits(s string) bool { + if s == "" { + return false + } + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return false + } + } + return true +} diff --git a/intercept/argv_compound_test.go b/intercept/argv_compound_test.go new file mode 100644 index 0000000..a02ba21 --- /dev/null +++ b/intercept/argv_compound_test.go @@ -0,0 +1,238 @@ +package intercept + +import ( + "encoding/json" + "testing" + + "github.com/Autumn-27/artex/db" +) + +func bashInput(cmd string) []byte { + b, _ := json.Marshal(map[string]string{"command": cmd}) + return b +} + +func matchSingleArgvRule(action, pattern, toolName string, input []byte) (Decision, bool) { + ic := New(nil) + ic.SetRulesForTest([]db.InterceptRule{{ + ID: 1, + Name: action + " " + pattern, + Enabled: true, + Priority: 100, + MatchTarget: "tool_input", + MatchType: "argv", + Pattern: pattern, + Action: action, + }}) + return ic.Match(toolName, input) +} + +func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { + nmapShouldMatch := []struct { + name string + cmd string + }{ + {"plain", "nmap -p 80 x"}, + {"command wrapper", "command nmap -p 80 x"}, + {"command double dash", "command -- nmap -p 80 x"}, + {"command -p", "command -p nmap -p 80 x"}, + {"path qualified", "/usr/bin/nmap -p 80 x"}, + {"sudo", "sudo nmap -p 80 x"}, + {"sudo with flags and assign", "sudo -u root -n FOO=1 nmap -p 80 x"}, + {"doas", "doas -u root nmap -p 80 x"}, + {"env with assign", "env FOO=1 nmap -p 80 x"}, + {"env with flags", "env -i -u HOME -C /tmp -S arg FOO=1 nmap -p 80 x"}, + {"env with expansion in assign", "env FOO=$(id) nmap -p 80 x"}, + {"timeout", "timeout 30 nmap -p 80 x"}, + {"timeout with flags", "timeout -k 5 -s KILL 30 nmap -p 80 x"}, + {"nohup", "nohup nmap -p 80 x"}, + {"setsid", "setsid -f nmap -p 80 x"}, + {"stdbuf", "stdbuf -oL -eL nmap -p 80 x"}, + {"nice -n", "nice -n 10 nmap -p 80 x"}, + {"nice numeric flag", "nice -10 nmap -p 80 x"}, + {"ionice", "ionice -c 3 nmap -p 80 x"}, + {"taskset", "taskset -c 0-1 nmap -p 80 x"}, + {"chrt", "chrt -f 50 nmap -p 80 x"}, + {"watch", "watch -n 5 nmap -p 80 x"}, + {"flock", "flock -n /tmp/lock nmap -p 80 x"}, + {"strace", "strace -f -o /tmp/trace nmap -p 80 x"}, + {"ltrace", "ltrace -f -o /tmp/ltrace nmap -p 80 x"}, + {"xargs", "echo 10.0.0.1 | xargs -n 1 nmap -p 80"}, + {"xargs -I", "xargs -I{} nmap -p 80 {}"}, + {"exec", "exec -- nmap -p 80 x"}, + {"exec -a", "exec -a fake nmap -p 80 x"}, + {"semicolon list", "nmap -p 80 x; true"}, + {"and list", "true && nmap -p 80 x"}, + {"or list", "false || nmap -p 80 x"}, + {"pipeline", "nmap -p 80 x | tee out"}, + {"subshell", "(nmap -p 80 x)"}, + {"redirect", "nmap -p 80 x > out"}, + {"background", "nmap -p 80 x &"}, + {"prefix assign", "FOO=1 nmap -p 80 x"}, + {"expansion in later arg", "nmap $(id)"}, + {"param expansion in later arg", "nmap $TARGET"}, + {"command subst inside echo", "echo $(nmap -p 80 x)"}, + {"bash -c single quoted", "bash -c 'nmap -p 80 x'"}, + {"sh -c double quoted", `sh -c "nmap -p 80 x"`}, + {"zsh -c", "zsh -c 'nmap -p 80 x'"}, + {"dash -c", "dash -c 'nmap -p 80 x'"}, + {"ksh -c", "ksh -c 'nmap -p 80 x'"}, + {"fish -c", "fish -c 'nmap -p 80 x'"}, + {"path qualified bash -c", "/bin/bash -c 'nmap -p 80 x'"}, + {"eval quoted", "eval 'nmap -p 80 x'"}, + {"eval separate args", "eval nmap -p 80 x"}, + {"eval with trailing subst", "eval nmap $(id)"}, + {"stacked wrappers", "sudo env FOO=1 timeout 30 nohup command /usr/bin/nmap -p 80 x"}, + {"nested payload depth 2", `bash -c "sh -c 'nmap -p 80 x'"`}, + {"nested payload depth 3", `bash -c "sh -c \"eval 'nmap -p 80 x'\""`}, + {"bad nested payload does not block later call", `bash -c "if then"; nmap -p 80 x`}, + } + + for _, action := range []string{"deny", "ask"} { + for _, tc := range nmapShouldMatch { + t.Run(action+"/match/"+tc.name, func(t *testing.T) { + dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(tc.cmd)) + if !ok || dec.Action != action { + t.Errorf("%s [\"nmap\"] on %q: got (%+v, %v), want match with action %q", action, tc.cmd, dec, ok, action) + } + }) + } + } + + nmapShouldNotMatch := []struct { + name string + cmd string + }{ + {"argument to echo", "echo nmap"}, + {"prefix of other binary", "nmapx"}, + {"argument in pipeline", "echo x | grep nmap"}, + {"command -v lookup", "command -v nmap"}, + {"command -V lookup", "command -V nmap"}, + {"sudo -l list", "sudo -l nmap"}, + {"sudo -e edit", "sudo -e nmap"}, + {"sudo unknown flag", "sudo --unknown-flag nmap -p 80 x"}, + {"env unknown flag", "env -Z nmap -p 80 x"}, + {"env no command", "env FOO=1"}, + {"ionice pid mode", "ionice -p 1234"}, + {"taskset pid mode", "taskset -p 1234"}, + {"chrt pid mode", "chrt -p 1234"}, + {"xargs ambiguous -l", "xargs -l nmap"}, + {"shell with non-c option", "bash -x -c 'nmap -p 80 x'"}, + {"shell script file", "bash nmap"}, + {"eval opaque leading arg", "eval $CMD nmap"}, + {"opaque command token", "$CMD -p 80 x"}, + {"nested payload depth 4 exceeds limit", `bash -c "sh -c \"bash -c 'eval \\\"nmap -p 80 x\\\"'\""`}, + {"unparsable single quote", "nmap 'unterminated"}, + {"unparsable subst", "nmap $("}, + {"empty command", ""}, + } + + for _, action := range []string{"deny", "ask"} { + for _, tc := range nmapShouldNotMatch { + t.Run(action+"/nomatch/"+tc.name, func(t *testing.T) { + if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(tc.cmd)); ok { + t.Errorf("%s [\"nmap\"] on %q unexpectedly matched: %+v", action, tc.cmd, dec) + } + }) + } + } + + // Non-Bash tool never matches argv rules. + if dec, ok := matchSingleArgvRule("deny", `["nmap"]`, "shell_open", bashInput("nmap -p 80 x")); ok { + t.Errorf("non-Bash tool matched deny rule: %+v", dec) + } +} + +func TestArgvDenyMultiTokenAndPathRules(t *testing.T) { + cases := []struct { + name string + pattern string + cmd string + want bool + }{ + {"git config path qualified with flag", `["git","config"]`, "/usr/bin/git config --list", true}, + {"git config via command", `["git","config"]`, "command git config --list", true}, + {"git config via sudo", `["git","config"]`, "sudo git config user.name foo", true}, + {"git config opaque subcommand", `["git","config"]`, "git $SUB --list", false}, + {"git status does not match git config", `["git","config"]`, "git status", false}, + {"exact path rule matches exact path", `["/usr/bin/nmap"]`, "/usr/bin/nmap -p 80 x", true}, + {"exact path rule does not match bare name", `["/usr/bin/nmap"]`, "nmap -p 80 x", false}, + {"exact path rule does not match other path", `["/usr/bin/nmap"]`, "/opt/bin/nmap -p 80 x", false}, + {"builtin wrapper matches echo", `["echo"]`, "builtin -- echo hi", true}, + {"xargs with no command does not invent echo", `["echo"]`, "xargs -n 1", false}, + {"wrapper itself can still be denied", `["sudo"]`, "sudo nmap -p 80 x", true}, + {"shell itself can still be denied", `["bash"]`, "bash -c 'echo hi'", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, got := matchSingleArgvRule("deny", tc.pattern, "Bash", bashInput(tc.cmd)) + if got != tc.want { + t.Errorf("deny %s on %q = %v, want %v", tc.pattern, tc.cmd, got, tc.want) + } + }) + } +} + +func TestArgvAllowRemainsStrict(t *testing.T) { + cases := []struct { + cmd string + want bool + }{ + {"nmap -p 80 x", true}, + {"command nmap x", false}, + {"nmap x; true", false}, + {"bash -c 'nmap x'", false}, + {"/usr/bin/nmap x", false}, + {"sudo nmap x", false}, + {"env FOO=1 nmap x", false}, + {"nmap $(id)", false}, + } + for _, tc := range cases { + t.Run(tc.cmd, func(t *testing.T) { + _, got := matchSingleArgvRule("allow", `["nmap"]`, "Bash", bashInput(tc.cmd)) + if got != tc.want { + t.Errorf("allow [\"nmap\"] on %q = %v, want %v", tc.cmd, got, tc.want) + } + }) + } +} + +func TestArgvCompoundMalformedInputDoesNotPanic(t *testing.T) { + inputs := [][]byte{ + nil, + []byte(``), + []byte(`not json`), + []byte(`{}`), + bashInput(`nmap 'unterminated`), + bashInput(`nmap $(`), + bashInput(`if then fi; (( (`), + bashInput(`bash -c "unterminated`), + bashInput(`eval "((("`), + } + for _, action := range []string{"deny", "ask", "allow"} { + for _, in := range inputs { + if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", in); ok { + t.Errorf("%s matched malformed input %q: %+v", action, string(in), dec) + } + } + } +} + +func TestArgvPriorityPreservedWithCompoundDeny(t *testing.T) { + ic := New(nil) + ic.SetRulesForTest([]db.InterceptRule{ + {ID: 1, Name: "allow simple nmap", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"}, + {ID: 2, Name: "deny compound nmap", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "deny"}, + }) + + // Simple command hits the higher-priority allow rule. + dec, ok := ic.Match("Bash", bashInput("nmap -p 80 x")) + if !ok || dec.Action != "allow" || dec.RuleID != 1 { + t.Fatalf("simple nmap: got (%+v, %v), want allow rule 1", dec, ok) + } + // Compound command fails the strict allow rule and falls through to the deny rule. + dec, ok = ic.Match("Bash", bashInput("nmap -p 80 x; true")) + if !ok || dec.Action != "deny" || dec.RuleID != 2 { + t.Fatalf("compound nmap: got (%+v, %v), want deny rule 2", dec, ok) + } +} diff --git a/intercept/intercept.go b/intercept/intercept.go index c765f02..a41a383 100644 --- a/intercept/intercept.go +++ b/intercept/intercept.go @@ -765,12 +765,20 @@ func (i *Interceptor) SetRulesForTest(rules []db.InterceptRule) { func ruleMatches(r compiledRule, toolName string, input []byte) bool { if r.MatchType == "argv" { // Bash only, on the parsed command; match_target is always tool_input. - // The denylist neutralises allow rules only: an argv deny or ask rule - // for a denylisted program still matches. - if r.Action == "allow" && CheckArgvAllow(r.argv) != nil { - return false + // Allow rules stay strictly limited to a single simple command with + // exact derived prefix and denylist enforcement. Deny and ask rules + // walk every call in a compound Bash command, stripping known wrappers + // and recursing into eval / shell -c payloads. + if r.Action == "allow" { + if CheckArgvAllow(r.argv) != nil { + return false + } + return r.MatchTarget == "tool_input" && argvRuleMatches(r.argv, toolName, input) } - return r.MatchTarget == "tool_input" && argvRuleMatches(r.argv, toolName, input) + if r.Action == "deny" || r.Action == "ask" { + return r.MatchTarget == "tool_input" && argvCompoundMatches(r.argv, toolName, input) + } + return false } var subject string switch r.MatchTarget { From da00bf7c8af0c37fe76035e5d8c8bdef22022f72 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:57:59 +0100 Subject: [PATCH 2/4] fix(intercept): close shell-option, env -S, xargs -l and find -exec argv bypasses --- intercept/argv_compound.go | 784 ++++++++++++++++++++++++++------ intercept/argv_compound_test.go | 44 +- 2 files changed, 681 insertions(+), 147 deletions(-) diff --git a/intercept/argv_compound.go b/intercept/argv_compound.go index e4a021b..0d85d30 100644 --- a/intercept/argv_compound.go +++ b/intercept/argv_compound.go @@ -8,10 +8,15 @@ import ( "mvdan.cc/sh/v3/syntax" ) -// argvMaxNestedPayloads bounds how deeply nested shell/eval payloads +// argvMaxNestedPayloads bounds how deeply nested shell/eval/env -S payloads // (for example, bash -c "bash -c ...") are re-parsed and walked. const argvMaxNestedPayloads = 3 +// argvMaxWrapperCandidates bounds option-disambiguation branching (for example +// repeated ambiguous optional-value flags like xargs -l) so pathological input +// cannot cause exponential work. +const argvMaxWrapperCandidates = 8 + // callWord is one argument word of a *syntax.CallExpr for deny/ask matching. // Literal is true when the word contains no runtime expansion; Value holds the // unquoted text. AssignLike is true when the word begins with a literal @@ -26,7 +31,8 @@ type callWord struct { // argvCompoundMatches reports whether any command executed within a Bash tool // call matches the deny/ask prefix rule tokens. It parses the entire Bash line, // walks every *syntax.CallExpr in the AST, strips known wrapper programs, and -// recurses into eval and shell -c payloads up to argvMaxNestedPayloads deep. +// recurses into eval, shell -c, env -S, flock -c, and parallel command-string +// payloads up to argvMaxNestedPayloads deep. // // Parse errors never panic and always return false (no match). func argvCompoundMatches(tokens []string, toolName string, input []byte) bool { @@ -73,47 +79,61 @@ func bashCommandMatchesArgv(rule []string, command string, depth int) bool { } // callMatchesArgv checks a single call's argv against rule, stripping known -// wrappers repeatedly and recursing into eval / shell -c payloads up to +// wrappers repeatedly and recursing into nested Bash payloads up to // argvMaxNestedPayloads deep. func callMatchesArgv(rule []string, argv []callWord, depth int) bool { - cur := argv - for len(cur) > 0 { - if argvMatchesRulePrefix(rule, cur) { - return true - } - if !cur[0].Literal || cur[0].Value == "" { + if len(argv) == 0 { + return false + } + if argvMatchesRulePrefix(rule, argv) { + return true + } + if !argv[0].Literal || argv[0].Value == "" { + return false + } + prog := path.Base(argv[0].Value) + rest := argv[1:] + + switch { + case prog == "eval": + if depth >= argvMaxNestedPayloads { return false } - prog := path.Base(cur[0].Value) - - // Nested Bash payload wrappers: eval and shells with -c. - if prog == "eval" { - if depth >= argvMaxNestedPayloads { - return false - } - payload, ok := evalPayload(cur[1:]) - if !ok { - return false - } - return bashCommandMatchesArgv(rule, payload, depth+1) - } - if isShellWrapper(prog) { - if depth >= argvMaxNestedPayloads { - return false - } - payload, ok := shellDashCPayload(cur[1:]) - if !ok { - return false - } - return bashCommandMatchesArgv(rule, payload, depth+1) - } - - // Direct command-wrapping programs. - next, ok := stripOneWrapper(prog, cur[1:]) - if !ok || len(next) == 0 || len(next) >= len(cur) { + payload, ok := evalPayload(rest) + if !ok { return false } - cur = next + return bashCommandMatchesArgv(rule, payload, depth+1) + + case isShellWrapper(prog): + if depth >= argvMaxNestedPayloads { + return false + } + payload, ok := shellDashCPayload(rest) + if !ok { + return false + } + return bashCommandMatchesArgv(rule, payload, depth+1) + + case prog == "env": + return envMatchesArgv(rule, rest, depth) + + case prog == "find": + return findExecMatches(rule, rest, depth) + + case prog == "flock": + return flockMatchesArgv(rule, rest, depth) + + case prog == "parallel": + return parallelMatchesArgv(rule, rest, depth) + } + + for _, next := range stripOneWrapperCandidates(prog, rest) { + if len(next) > 0 && len(next) < len(argv) { + if callMatchesArgv(rule, next, depth) { + return true + } + } } return false } @@ -146,9 +166,9 @@ func argvMatchesRulePrefix(rule []string, argv []callWord) bool { } // callWordOf converts a Bash AST word into a callWord. Words containing any -// expansion (parameter, command/process substitution, arithmetic, glob, brace, -// tilde, ANSI-C/locale quoting) become opaque (Literal: false) rather than -// failing the whole call. +// expansion (parameter, command/process substitution, arithmetic, glob, brace +// expansion, tilde, ANSI-C/locale quoting) become opaque (Literal: false) +// rather than failing the whole call. func callWordOf(w *syntax.Word) callWord { if w == nil || len(w.Parts) == 0 { return callWord{} @@ -283,19 +303,110 @@ func isShellWrapper(prog string) bool { return false } -// shellDashCPayload extracts the literal command string following a leading -// "-c" option. Other shell options are intentionally not interpreted. +// Known leading options of POSIX/Bash/Zsh/Dash/Ksh/Fish shells. +// Short flags may appear with '-' or '+' (only '-c' enables command mode); +// -o/+o and -O/+O take a single option-name value. +const shellShortNoArg = "abBCdefhHiklmnpPrstuvxETLN" + +var ( + shellLongNoArg = strSet( + "debugger", "dump-po-strings", "dump-strings", "interactive", "login", + "no-config", "noediting", "noprofile", "norc", "posix", "pretty-print", + "private", "restricted", "verbose", + ) + shellLongArg = strSet("init-file", "rcfile") +) + +// shellDashCPayload parses a shell's leading options (combined short clusters +// containing c, -o/+o and -O/+O with a value, known long options, and --) and +// returns the literal command string if -c (or --command) was given. +// No -c (script/stdin mode), unknown options, or opaque options before -c +// return ("", false). func shellDashCPayload(args []callWord) (string, bool) { - if len(args) < 2 { + hasC := false + i := 0 + for i < len(args) { + if !args[i].Literal { + return "", false + } + tok := args[i].Value + if tok == "--" || tok == "-" { + i++ + break + } + if !strings.HasPrefix(tok, "-") && !strings.HasPrefix(tok, "+") { + break + } + if strings.HasPrefix(tok, "--") { + name := tok[2:] + if eq := strings.IndexByte(name, '='); eq >= 0 { + flagName, val := name[:eq], name[eq+1:] + if flagName == "command" { + return val, true + } + if shellLongArg[flagName] { + i++ + continue + } + return "", false + } + if name == "command" { + if i+1 >= len(args) || !args[i+1].Literal { + return "", false + } + return args[i+1].Value, true + } + if shellLongNoArg[name] { + i++ + continue + } + if shellLongArg[name] { + if i+1 >= len(args) { + return "", false + } + i += 2 + continue + } + return "", false + } + + // Short option or combined short-option cluster starting with '-' or '+'. + sign := tok[0] + flags := tok[1:] + if flags == "" { + break + } + consumedNext := false + for j := 0; j < len(flags); j++ { + ch := flags[j] + switch { + case ch == 'c' && sign == '-': + hasC = true + case ch == 'o' || ch == 'O': + if j+1 < len(flags) { + j = len(flags) + } else { + if i+1 >= len(args) { + return "", false + } + consumedNext = true + } + case strings.IndexByte(shellShortNoArg, ch) >= 0: + continue + default: + return "", false + } + } + if consumedNext { + i += 2 + } else { + i++ + } + } + if !hasC || i >= len(args) || !args[i].Literal { return "", false } - if !args[0].Literal || args[0].Value != "-c" { - return "", false - } - if !args[1].Literal { - return "", false - } - return args[1].Value, true + return args[i].Value, true } // evalPayload joins eval's arguments with spaces for re-parsing as Bash. @@ -326,17 +437,344 @@ func evalPayload(args []callWord) (string, bool) { return strings.Join(parts, " "), true } +// envMatchesArgv handles env's options (including -S/--split-string, whose +// value is re-parsed as a Bash line at depth+1), NAME=VALUE assignments, and +// any trailing wrapped command. +func envMatchesArgv(rule []string, args []callWord, depth int) bool { + spec := wrapperSpecs["env"] + i := 0 + checkSplitString := func(val string) bool { + if depth >= argvMaxNestedPayloads || strings.TrimSpace(val) == "" { + return false + } + if bashCommandMatchesArgv(rule, val, depth+1) { + return true + } + // If the split-string payload starts with env options (e.g. -i or -u), + // also evaluate it as an env invocation. + if strings.HasPrefix(strings.TrimSpace(val), "-") { + return bashCommandMatchesArgv(rule, "env "+val, depth+1) + } + return false + } + + for i < len(args) { + if !args[i].Literal { + if args[i].AssignLike { + break + } + return false + } + tok := args[i].Value + if tok == "--" { + i++ + break + } + if tok == "-" { + i++ + continue + } + if !strings.HasPrefix(tok, "-") { + break + } + if strings.HasPrefix(tok, "--") { + name := tok[2:] + if eq := strings.IndexByte(name, '='); eq >= 0 { + flagName, val := name[:eq], name[eq+1:] + if flagName == "split-string" { + if checkSplitString(val) { + return true + } + i++ + continue + } + if spec.longArg[flagName] || spec.longOptVal[flagName] { + i++ + continue + } + return false + } + if name == "split-string" { + if i+1 >= len(args) { + return false + } + if args[i+1].Literal && checkSplitString(args[i+1].Value) { + return true + } + i += 2 + continue + } + if spec.longNoArg[name] || spec.longOptVal[name] { + i++ + continue + } + if spec.longArg[name] { + if i+1 >= len(args) { + return false + } + i += 2 + continue + } + return false + } + + flags := tok[1:] + consumedNext := false + for j := 0; j < len(flags); j++ { + ch := flags[j] + switch { + case ch == 'S': + if j+1 < len(flags) { + if checkSplitString(flags[j+1:]) { + return true + } + j = len(flags) + } else { + if i+1 >= len(args) { + return false + } + if args[i+1].Literal && checkSplitString(args[i+1].Value) { + return true + } + consumedNext = true + } + case strings.IndexByte(spec.shortNoArg, ch) >= 0: + continue + case strings.IndexByte(spec.shortArg, ch) >= 0: + if j+1 < len(flags) { + j = len(flags) + } else { + if i+1 >= len(args) { + return false + } + consumedNext = true + } + default: + return false + } + } + if consumedNext { + i += 2 + } else { + i++ + } + } + + for i < len(args) && args[i].AssignLike { + i++ + } + if i >= len(args) { + return false + } + return callMatchesArgv(rule, args[i:], depth) +} + +// findExecMatches walks every -exec, -execdir, -ok, and -okdir clause inside a +// find invocation (terminated by literal ";" or "+") and runs callMatchesArgv +// on each wrapped command. +func findExecMatches(rule []string, args []callWord, depth int) bool { + for i := 0; i < len(args); i++ { + if !args[i].Literal { + continue + } + switch args[i].Value { + case "-exec", "-execdir", "-ok", "-okdir": + start := i + 1 + end := start + terminated := false + for end < len(args) { + if args[end].Literal && (args[end].Value == ";" || args[end].Value == "+") { + terminated = true + break + } + end++ + } + if terminated && end > start { + if callMatchesArgv(rule, args[start:end], depth) { + return true + } + i = end + } + } + } + return false +} + +// flockMatchesArgv handles both "flock [opts] " and +// "flock [opts] -c " / "flock [opts] -c ". +func flockMatchesArgv(rule []string, args []callWord, depth int) bool { + spec := wrapperSpecs["flock"] + i := 0 + for i < len(args) { + if !args[i].Literal { + return false + } + tok := args[i].Value + if tok == "--" { + i++ + break + } + if !strings.HasPrefix(tok, "-") || tok == "-" { + break + } + if strings.HasPrefix(tok, "--") { + name := tok[2:] + if eq := strings.IndexByte(name, '='); eq >= 0 { + flagName, val := name[:eq], name[eq+1:] + if flagName == "command" { + if depth < argvMaxNestedPayloads && bashCommandMatchesArgv(rule, val, depth+1) { + return true + } + i++ + continue + } + if spec.longArg[flagName] { + i++ + continue + } + return false + } + if name == "command" { + if i+1 >= len(args) { + return false + } + if depth < argvMaxNestedPayloads && args[i+1].Literal && bashCommandMatchesArgv(rule, args[i+1].Value, depth+1) { + return true + } + i += 2 + continue + } + if spec.longNoArg[name] { + i++ + continue + } + if spec.longArg[name] { + if i+1 >= len(args) { + return false + } + i += 2 + continue + } + return false + } + + flags := tok[1:] + consumedNext := false + for j := 0; j < len(flags); j++ { + ch := flags[j] + switch { + case ch == 'c': + if j+1 < len(flags) { + if depth < argvMaxNestedPayloads && bashCommandMatchesArgv(rule, flags[j+1:], depth+1) { + return true + } + j = len(flags) + } else { + if i+1 >= len(args) { + return false + } + if depth < argvMaxNestedPayloads && args[i+1].Literal && bashCommandMatchesArgv(rule, args[i+1].Value, depth+1) { + return true + } + consumedNext = true + } + case strings.IndexByte(spec.shortNoArg, ch) >= 0: + continue + case strings.IndexByte(spec.shortArg, ch) >= 0: + if j+1 < len(flags) { + j = len(flags) + } else { + if i+1 >= len(args) { + return false + } + consumedNext = true + } + default: + return false + } + } + if consumedNext { + i += 2 + } else { + i++ + } + } + + // Skip positional . + if i >= len(args) { + return false + } + i++ + if i >= len(args) { + return false + } + // Handle "flock -c " / "flock --command ". + if args[i].Literal { + tok := args[i].Value + if tok == "-c" || tok == "--command" { + if i+1 < len(args) && args[i+1].Literal && depth < argvMaxNestedPayloads { + return bashCommandMatchesArgv(rule, args[i+1].Value, depth+1) + } + return false + } + if strings.HasPrefix(tok, "--command=") { + if depth < argvMaxNestedPayloads { + return bashCommandMatchesArgv(rule, strings.TrimPrefix(tok, "--command="), depth+1) + } + return false + } + if strings.HasPrefix(tok, "-c") && len(tok) > 2 { + if depth < argvMaxNestedPayloads { + return bashCommandMatchesArgv(rule, tok[2:], depth+1) + } + return false + } + } + return callMatchesArgv(rule, args[i:], depth) +} + +// parallelMatchesArgv strips parallel's leading options, stops before GNU +// parallel's input separators (:::, :::+, ::::, ::::+), and matches the +// wrapped command (including single-string shell commands like +// "parallel 'nmap -p 80 {}' ::: target"). +func parallelMatchesArgv(rule []string, args []callWord, depth int) bool { + for _, cand := range stripOneWrapperCandidates("parallel", args) { + end := len(cand) + for idx, w := range cand { + if w.Literal && (w.Value == ":::" || w.Value == ":::+" || w.Value == "::::" || w.Value == "::::+") { + end = idx + break + } + } + cmd := cand[:end] + if len(cmd) == 0 { + continue + } + if callMatchesArgv(rule, cmd, depth) { + return true + } + if len(cmd) == 1 && cmd[0].Literal && depth < argvMaxNestedPayloads { + if bashCommandMatchesArgv(rule, cmd[0].Value, depth+1) { + return true + } + } + } + return false +} + // wrapperSpec describes the handled leading-option layout for a wrapper -// program. Any flag not listed in shortNoArg, shortArg, longNoArg, longArg, -// or longOptVal causes stripping to skip the call rather than guess. +// program. Any flag not listed here causes stripping to skip the call rather +// than guess, except for optional-argument flags in shortOptAmb / longOptAmb +// where both 0-arg and 1-arg interpretations are considered. type wrapperSpec struct { shortNoArg string // short flags that take no argument shortArg string // short flags that take one argument (attached or next token) shortOptAtt string // short flags that accept only an optional attached argument (never next token) + shortOptAmb string // short flags with optional attached OR separate next-token value (try both) longNoArg map[string]bool // --flag (no value) longArg map[string]bool // --flag VAL or --flag=VAL longOptVal map[string]bool // --flag or --flag=VAL (never consumes next token) - allowBareMin bool // treat bare "-" as a no-arg option (env -) + allowBareMin bool // treat bare "-" as a no-arg option allowNumFlag bool // treat - as a no-arg option (nice -10) skipAssigns bool // skip NAME=VALUE tokens after options (env, sudo) posBeforeCmd int // required positional arguments before the wrapped command @@ -353,9 +791,9 @@ func strSet(names ...string) map[string]bool { var wrapperSpecs = map[string]wrapperSpec{ "env": { shortNoArg: "i0v", - shortArg: "uCSa", + shortArg: "uCa", longNoArg: strSet("ignore-environment", "null", "debug"), - longArg: strSet("unset", "chdir", "split-string", "argv0"), + longArg: strSet("unset", "chdir", "argv0"), longOptVal: strSet("block-signal", "default-signal", "ignore-signal"), allowBareMin: true, skipAssigns: true, @@ -409,7 +847,7 @@ var wrapperSpecs = map[string]wrapperSpec{ }, "sudo": { shortNoArg: "AbBEHikKnPsSv", - shortArg: "CDgprRtTuU", + shortArg: "CDghprRtTuU", longNoArg: strSet("askpass", "background", "bell", "set-home", "login", "reset-timestamp", "remove-timestamp", "non-interactive", "preserve-groups", "shell", "stdin", "validate"), longArg: strSet("close-from", "chdir", "group", "host", "prompt", "role", "chroot", "type", "command-timeout", "user", "other-user"), longOptVal: strSet("preserve-env"), @@ -420,11 +858,12 @@ var wrapperSpecs = map[string]wrapperSpec{ shortArg: "au", }, "watch": { - shortNoArg: "bcCdegprtwx", - shortArg: "nq", - longNoArg: strSet("beep", "color", "no-color", "errexit", "chgexit", "precise", "no-rerun", "no-title", "no-wrap", "exec"), - longArg: strSet("interval", "equexit"), - longOptVal: strSet("differences"), + shortNoArg: "bcCegprtwx", + shortArg: "nq", + shortOptAmb: "d", + longNoArg: strSet("beep", "color", "no-color", "errexit", "chgexit", "precise", "no-rerun", "no-title", "no-wrap", "exec"), + longArg: strSet("interval", "equexit"), + longOptVal: strSet("differences"), }, "flock": { shortNoArg: "sxeunFo", @@ -449,118 +888,173 @@ var wrapperSpecs = map[string]wrapperSpec{ shortNoArg: "0oprtx", shortArg: "adEILnPsR", shortOptAtt: "ei", + shortOptAmb: "l", longNoArg: strSet("null", "open-tty", "interactive", "no-run-if-empty", "verbose", "exit", "show-limits"), longArg: strSet("arg-file", "delimiter", "eof", "replace", "max-lines", "max-args", "max-procs", "max-chars", "process-slot-var"), }, + "busybox": {}, + "chroot": { + longNoArg: strSet("skip-chdir"), + longArg: strSet("userspec", "groups"), + posBeforeCmd: 1, // NEWROOT + }, + "parallel": { + shortNoArg: "0kmquvXi", + shortArg: "jnNPILSadEC", + longNoArg: strSet("null", "keep-order", "quote", "ungroup", "verbose", "bar", "eta", "progress", "no-notice", "will-cite", "plain", "pipe", "pipepart", "line-buffer", "group", "dry-run", "shuf"), + longArg: strSet("jobs", "max-args", "max-procs", "max-lines", "sshlogin", "arg-file", "delimiter", "colsep", "tagstring", "timeout", "delay", "retries", "results", "joblog", "workdir", "wd", "env", "halt", "memfree", "load"), + longOptVal: strSet("tag"), + }, } -func stripOneWrapper(prog string, args []callWord) ([]callWord, bool) { +// stripOneWrapperCandidates returns the possible wrapped-command slices after +// stripping prog's options, assignments, and required positional arguments. +// For unambiguous options it returns at most one slice; for optional-argument +// flags (such as xargs -l) it returns both the 0-arg and 1-arg interpretations. +func stripOneWrapperCandidates(prog string, args []callWord) [][]callWord { spec, ok := wrapperSpecs[prog] if !ok { - return nil, false + return nil } - i := 0 - for i < len(args) { - if !args[i].Literal { - if spec.skipAssigns && args[i].AssignLike { + var out [][]callWord + seenIdx := map[int]bool{} + var walk func(i int) + walk = func(i int) { + if len(out) >= argvMaxWrapperCandidates { + return + } + for i < len(args) { + if !args[i].Literal { + if spec.skipAssigns && args[i].AssignLike { + break + } + return + } + tok := args[i].Value + if tok == "--" { + i++ break } - // Do not guess past an opaque token in option position. - return nil, false - } - tok := args[i].Value - if tok == "--" { - i++ - break - } - if tok == "-" { - if spec.allowBareMin { - i++ - continue - } - break - } - if !strings.HasPrefix(tok, "-") { - break - } - if strings.HasPrefix(tok, "--") { - name := tok[2:] - if eq := strings.IndexByte(name, '='); eq >= 0 { - flagName := name[:eq] - if spec.longArg[flagName] || spec.longOptVal[flagName] { + if tok == "-" { + if spec.allowBareMin { i++ continue } - return nil, false + break } - if spec.longNoArg[name] || spec.longOptVal[name] { + if !strings.HasPrefix(tok, "-") { + break + } + if strings.HasPrefix(tok, "--") { + name := tok[2:] + if eq := strings.IndexByte(name, '='); eq >= 0 { + flagName := name[:eq] + if spec.longArg[flagName] || spec.longOptVal[flagName] { + i++ + continue + } + return + } + if spec.longNoArg[name] || spec.longOptVal[name] { + i++ + continue + } + if spec.longArg[name] { + if i+1 >= len(args) { + return + } + i += 2 + continue + } + return + } + + flags := tok[1:] + if spec.allowNumFlag && isAllDigits(flags) { i++ continue } - if spec.longArg[name] { - if i+1 >= len(args) { - return nil, false - } - i += 2 - continue - } - return nil, false - } - - // Short flag or combined short-flag cluster (e.g. -nu root, -uFOO). - flags := tok[1:] - if spec.allowNumFlag && isAllDigits(flags) { - i++ - continue - } - consumedNext := false - for j := 0; j < len(flags); j++ { - ch := flags[j] - switch { - case strings.IndexByte(spec.shortNoArg, ch) >= 0: - continue - case strings.IndexByte(spec.shortOptAtt, ch) >= 0: - // Optional value only when attached in the same token; never consumes next token. - j = len(flags) - case strings.IndexByte(spec.shortArg, ch) >= 0: - if j+1 < len(flags) { - // Attached value consumes the rest of this token. + consumedNext := false + ambiguousNext := false + for j := 0; j < len(flags); j++ { + ch := flags[j] + switch { + case strings.IndexByte(spec.shortNoArg, ch) >= 0: + continue + case strings.IndexByte(spec.shortOptAtt, ch) >= 0: j = len(flags) - } else { - if i+1 >= len(args) { - return nil, false + case strings.IndexByte(spec.shortOptAmb, ch) >= 0: + if j+1 < len(flags) { + // Attached value (e.g. -l5) consumes the rest of this token. + j = len(flags) + } else { + // Bare flag: try treating as no-arg AND (if a next token + // could be its optional argument) consuming the next token. + ambiguousNext = true } - consumedNext = true + case strings.IndexByte(spec.shortArg, ch) >= 0: + if j+1 < len(flags) { + j = len(flags) + } else { + if i+1 >= len(args) { + return + } + consumedNext = true + } + default: + return } - default: - // Unhandled flag: skip this call rather than guessing whether it takes a value. - return nil, false + } + if ambiguousNext && !consumedNext { + // Interpretation 1: no-arg. + walk(i + 1) + // Interpretation 2: consumes next token as optional value + // (e.g. xargs -l 5 nmap, watch -d permanent nmap). + if i+1 < len(args) && optAmbMayConsume(prog, args[i+1]) { + walk(i + 2) + } + return + } + if consumedNext { + i += 2 + } else { + i++ } } - if consumedNext { - i += 2 - } else { - i++ - } - } - if spec.skipAssigns { - for i < len(args) && args[i].AssignLike { - i++ + if spec.skipAssigns { + for i < len(args) && args[i].AssignLike { + i++ + } } - } - - if spec.posBeforeCmd > 0 { - if i+spec.posBeforeCmd > len(args) { - return nil, false + if spec.posBeforeCmd > 0 { + if i+spec.posBeforeCmd > len(args) { + return + } + i += spec.posBeforeCmd } - i += spec.posBeforeCmd + if i >= len(args) || seenIdx[i] { + return + } + seenIdx[i] = true + out = append(out, args[i:]) } + walk(0) + return out +} - if i >= len(args) { - return nil, false +func optAmbMayConsume(prog string, next callWord) bool { + if !next.Literal { + return true + } + switch prog { + case "xargs": + return isAllDigits(next.Value) + case "watch": + return next.Value == "permanent" || next.Value == "cumulative" + default: + return !strings.HasPrefix(next.Value, "-") } - return args[i:], true } func isAllDigits(s string) bool { diff --git a/intercept/argv_compound_test.go b/intercept/argv_compound_test.go index a02ba21..4a4fb0a 100644 --- a/intercept/argv_compound_test.go +++ b/intercept/argv_compound_test.go @@ -43,6 +43,11 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { {"env with assign", "env FOO=1 nmap -p 80 x"}, {"env with flags", "env -i -u HOME -C /tmp -S arg FOO=1 nmap -p 80 x"}, {"env with expansion in assign", "env FOO=$(id) nmap -p 80 x"}, + {"env -S separate", "env -S 'nmap -p 80 x'"}, + {"env -S attached", "env -S'nmap -p 80 x'"}, + {"env --split-string equals", "env --split-string='nmap -p 80 x'"}, + {"env --split-string separate", "env --split-string 'nmap -p 80 x'"}, + {"env -S with env flags", "env -S '-i FOO=1 nmap -p 80 x'"}, {"timeout", "timeout 30 nmap -p 80 x"}, {"timeout with flags", "timeout -k 5 -s KILL 30 nmap -p 80 x"}, {"nohup", "nohup nmap -p 80 x"}, @@ -54,11 +59,30 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { {"taskset", "taskset -c 0-1 nmap -p 80 x"}, {"chrt", "chrt -f 50 nmap -p 80 x"}, {"watch", "watch -n 5 nmap -p 80 x"}, + {"watch -d permanent", "watch -d permanent nmap -p 80 x"}, {"flock", "flock -n /tmp/lock nmap -p 80 x"}, + {"flock -c after lockfile", "flock /tmp/lock -c 'nmap -p 80 x'"}, + {"flock -c before lockfile", "flock -n -c 'nmap -p 80 x' /tmp/lock"}, {"strace", "strace -f -o /tmp/trace nmap -p 80 x"}, {"ltrace", "ltrace -f -o /tmp/ltrace nmap -p 80 x"}, {"xargs", "echo 10.0.0.1 | xargs -n 1 nmap -p 80"}, {"xargs -I", "xargs -I{} nmap -p 80 {}"}, + {"xargs -l bare", "xargs -l nmap"}, + {"xargs -l5 attached", "xargs -l5 nmap"}, + {"xargs -l 5 separate", "xargs -l 5 nmap"}, + {"find -exec", `find . -maxdepth 0 -exec nmap -p 80 x \;`}, + {"find -execdir", `find . -execdir nmap -p 80 x \;`}, + {"find -ok", `find . -ok nmap -p 80 x \;`}, + {"find -okdir plus", `find . -okdir nmap -p 80 x +`}, + {"find multiple -exec clauses", `find . -exec echo {} \; -exec nmap -p 80 {} \;`}, + {"find -exec shell wrapper", `find . -exec sh -ec 'nmap -p 80 x' \;`}, + {"parallel bare", "parallel nmap"}, + {"parallel with jobs and :::", "parallel -j 4 nmap -p 80 {} ::: 10.0.0.1"}, + {"parallel quoted shell string", "parallel -j 4 'nmap -p 80 {}' ::: 10.0.0.1"}, + {"busybox", "busybox nmap -p 80 x"}, + {"busybox sh -c", "busybox sh -c 'nmap -p 80 x'"}, + {"chroot", "chroot / nmap -p 80 x"}, + {"chroot with userspec", "chroot --userspec=0:0 /mnt nmap -p 80 x"}, {"exec", "exec -- nmap -p 80 x"}, {"exec -a", "exec -a fake nmap -p 80 x"}, {"semicolon list", "nmap -p 80 x; true"}, @@ -73,11 +97,20 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { {"param expansion in later arg", "nmap $TARGET"}, {"command subst inside echo", "echo $(nmap -p 80 x)"}, {"bash -c single quoted", "bash -c 'nmap -p 80 x'"}, + {"bash -x -c", "bash -x -c 'nmap -p 80 x'"}, + {"bash -lc", "bash -lc 'nmap -p 80 x'"}, + {"bash -ec", "bash -ec 'nmap -p 80 x'"}, + {"bash -o pipefail -c", "bash -o pipefail -c 'nmap -p 80 x'"}, + {"bash +o pipefail -c", "bash +o pipefail -c 'nmap -p 80 x'"}, + {"bash -O extglob -c", "bash -O extglob -c 'nmap -p 80 x'"}, + {"bash --norc -c", "bash --norc -c 'nmap -p 80 x'"}, + {"bash --noprofile --rcfile /dev/null -c --", "bash --noprofile --rcfile /dev/null -c -- 'nmap -p 80 x'"}, {"sh -c double quoted", `sh -c "nmap -p 80 x"`}, {"zsh -c", "zsh -c 'nmap -p 80 x'"}, {"dash -c", "dash -c 'nmap -p 80 x'"}, {"ksh -c", "ksh -c 'nmap -p 80 x'"}, {"fish -c", "fish -c 'nmap -p 80 x'"}, + {"fish --command", "fish --command='nmap -p 80 x'"}, {"path qualified bash -c", "/bin/bash -c 'nmap -p 80 x'"}, {"eval quoted", "eval 'nmap -p 80 x'"}, {"eval separate args", "eval nmap -p 80 x"}, @@ -116,9 +149,16 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { {"ionice pid mode", "ionice -p 1234"}, {"taskset pid mode", "taskset -p 1234"}, {"chrt pid mode", "chrt -p 1234"}, - {"xargs ambiguous -l", "xargs -l nmap"}, - {"shell with non-c option", "bash -x -c 'nmap -p 80 x'"}, + {"xargs -l echo nmap does not match nmap", "xargs -l echo nmap"}, + {"shell unknown option before -c", "bash --unknown-opt -c 'nmap -p 80 x'"}, + {"shell opaque option before -c", "bash $OPT -c 'nmap -p 80 x'"}, + {"shell script mode with -x", "bash -x nmap"}, {"shell script file", "bash nmap"}, + {"shell -- before -c treats -c as script", "bash -- -c 'nmap -p 80 x'"}, + {"find -exec echo nmap", `find . -exec echo nmap \;`}, + {"parallel echo with nmap input", "parallel echo ::: nmap"}, + {"chroot without command", "chroot /"}, + {"busybox list mode", "busybox --list"}, {"eval opaque leading arg", "eval $CMD nmap"}, {"opaque command token", "$CMD -p 80 x"}, {"nested payload depth 4 exceeds limit", `bash -c "sh -c \"bash -c 'eval \\\"nmap -p 80 x\\\"'\""`}, From 0258a0570bb615164ab13442d081b6e27e5d903e Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:18:18 +0100 Subject: [PATCH 3/4] fix(intercept): parse command lines after parallel ::: when no command precedes it --- intercept/argv_compound.go | 25 ++++++++++++++++++++++++- intercept/argv_compound_test.go | 8 ++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/intercept/argv_compound.go b/intercept/argv_compound.go index 0d85d30..f640b40 100644 --- a/intercept/argv_compound.go +++ b/intercept/argv_compound.go @@ -737,17 +737,40 @@ func flockMatchesArgv(rule []string, args []callWord, depth int) bool { // parallel's input separators (:::, :::+, ::::, ::::+), and matches the // wrapped command (including single-string shell commands like // "parallel 'nmap -p 80 {}' ::: target"). +// +// When no command precedes ":::", GNU parallel executes each argument after +// ":::" as a command line, so each literal argument up to the next separator +// is parsed as a Bash line at depth+1. +// +// Note: "parallel -a FILE" / "--arg-file FILE" and "parallel :::: FILE" read +// command lines from a file that the matcher does not read. func parallelMatchesArgv(rule []string, args []callWord, depth int) bool { + isParallelSep := func(w callWord) bool { + return w.Literal && (w.Value == ":::" || w.Value == ":::+" || w.Value == "::::" || w.Value == "::::+") + } for _, cand := range stripOneWrapperCandidates("parallel", args) { end := len(cand) for idx, w := range cand { - if w.Literal && (w.Value == ":::" || w.Value == ":::+" || w.Value == "::::" || w.Value == "::::+") { + if isParallelSep(w) { end = idx break } } cmd := cand[:end] if len(cmd) == 0 { + // No command before separator: for ":::" each following literal + // argument (until any subsequent separator) runs as a command line. + // For ":::+", "::::", and "::::+", do not guess. + if end < len(cand) && cand[end].Literal && cand[end].Value == ":::" && depth < argvMaxNestedPayloads { + for _, arg := range cand[end+1:] { + if isParallelSep(arg) { + break + } + if arg.Literal && bashCommandMatchesArgv(rule, arg.Value, depth+1) { + return true + } + } + } continue } if callMatchesArgv(rule, cmd, depth) { diff --git a/intercept/argv_compound_test.go b/intercept/argv_compound_test.go index 4a4fb0a..4e18d93 100644 --- a/intercept/argv_compound_test.go +++ b/intercept/argv_compound_test.go @@ -79,6 +79,10 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { {"parallel bare", "parallel nmap"}, {"parallel with jobs and :::", "parallel -j 4 nmap -p 80 {} ::: 10.0.0.1"}, {"parallel quoted shell string", "parallel -j 4 'nmap -p 80 {}' ::: 10.0.0.1"}, + {"parallel no command ::: bare", "parallel ::: nmap"}, + {"parallel no command ::: quoted line", `parallel ::: "nmap -p 80 x"`}, + {"parallel no command -j2 ::: bare", "parallel -j2 ::: nmap"}, + {"parallel no command ::: multiple lines", "parallel ::: echo nmap"}, {"busybox", "busybox nmap -p 80 x"}, {"busybox sh -c", "busybox sh -c 'nmap -p 80 x'"}, {"chroot", "chroot / nmap -p 80 x"}, @@ -157,6 +161,10 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { {"shell -- before -c treats -c as script", "bash -- -c 'nmap -p 80 x'"}, {"find -exec echo nmap", `find . -exec echo nmap \;`}, {"parallel echo with nmap input", "parallel echo ::: nmap"}, + {"parallel no command ::: echo nmap quoted", `parallel ::: "echo nmap"`}, + {"parallel echo nmap ::: x", "parallel echo nmap ::: x"}, + {"parallel :::: file input", "parallel :::: nmap"}, + {"parallel :::+ separator", "parallel :::+ nmap"}, {"chroot without command", "chroot /"}, {"busybox list mode", "busybox --list"}, {"eval opaque leading arg", "eval $CMD nmap"}, From bbdb064afc17dfdaf20f1b1d84cbbdad87ce7788 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:56:42 +0100 Subject: [PATCH 4/4] fix(intercept): over-approximate unknown options on known wrappers and expand parallel flags --- intercept/argv_compound.go | 253 ++++++++++++++++++++------------ intercept/argv_compound_test.go | 9 +- 2 files changed, 165 insertions(+), 97 deletions(-) diff --git a/intercept/argv_compound.go b/intercept/argv_compound.go index f640b40..1ff824f 100644 --- a/intercept/argv_compound.go +++ b/intercept/argv_compound.go @@ -439,10 +439,10 @@ func evalPayload(args []callWord) (string, bool) { // envMatchesArgv handles env's options (including -S/--split-string, whose // value is re-parsed as a Bash line at depth+1), NAME=VALUE assignments, and -// any trailing wrapped command. +// any trailing wrapped command. Unknown options are over-approximated (tried +// as 0-arg and, when applicable, 1-arg) up to argvMaxWrapperCandidates. func envMatchesArgv(rule []string, args []callWord, depth int) bool { spec := wrapperSpecs["env"] - i := 0 checkSplitString := func(val string) bool { if depth >= argvMaxNestedPayloads || strings.TrimSpace(val) == "" { return false @@ -458,115 +458,141 @@ func envMatchesArgv(rule []string, args []callWord, depth int) bool { return false } - for i < len(args) { - if !args[i].Literal { - if args[i].AssignLike { - break - } + candidates := 0 + seenIdx := map[int]bool{} + var walk func(i int) bool + walk = func(i int) bool { + if candidates >= argvMaxWrapperCandidates { return false } - tok := args[i].Value - if tok == "--" { - i++ - break - } - if tok == "-" { - i++ - continue - } - if !strings.HasPrefix(tok, "-") { - break - } - if strings.HasPrefix(tok, "--") { - name := tok[2:] - if eq := strings.IndexByte(name, '='); eq >= 0 { - flagName, val := name[:eq], name[eq+1:] - if flagName == "split-string" { - if checkSplitString(val) { - return true - } - i++ - continue - } - if spec.longArg[flagName] || spec.longOptVal[flagName] { - i++ - continue + for i < len(args) { + if !args[i].Literal { + if args[i].AssignLike { + break } return false } - if name == "split-string" { - if i+1 >= len(args) { - return false - } - if args[i+1].Literal && checkSplitString(args[i+1].Value) { - return true - } - i += 2 - continue + tok := args[i].Value + if tok == "--" { + i++ + break } - if spec.longNoArg[name] || spec.longOptVal[name] { + if tok == "-" { i++ continue } - if spec.longArg[name] { - if i+1 >= len(args) { - return false - } - i += 2 - continue + if !strings.HasPrefix(tok, "-") { + break } - return false - } - - flags := tok[1:] - consumedNext := false - for j := 0; j < len(flags); j++ { - ch := flags[j] - switch { - case ch == 'S': - if j+1 < len(flags) { - if checkSplitString(flags[j+1:]) { + if strings.HasPrefix(tok, "--") { + name := tok[2:] + if eq := strings.IndexByte(name, '='); eq >= 0 { + flagName, val := name[:eq], name[eq+1:] + if flagName == "split-string" && checkSplitString(val) { return true } - j = len(flags) - } else { + // Known or unknown --flag=val skips one token. + i++ + continue + } + if name == "help" || name == "version" { + return false + } + if name == "split-string" { if i+1 >= len(args) { return false } if args[i+1].Literal && checkSplitString(args[i+1].Value) { return true } - consumedNext = true + i += 2 + continue } - case strings.IndexByte(spec.shortNoArg, ch) >= 0: - continue - case strings.IndexByte(spec.shortArg, ch) >= 0: - if j+1 < len(flags) { - j = len(flags) - } else { + if spec.longNoArg[name] || spec.longOptVal[name] { + i++ + continue + } + if spec.longArg[name] { if i+1 >= len(args) { return false } - consumedNext = true + i += 2 + continue + } + // Unknown long option without "=": try 0-arg and 1-arg. + if walk(i + 1) { + return true + } + if i+1 < len(args) && walk(i+2) { + return true } - default: return false } + + flags := tok[1:] + consumedNext := false + unknownOpt := false + for j := 0; j < len(flags); j++ { + ch := flags[j] + switch { + case ch == 'S': + if j+1 < len(flags) { + if checkSplitString(flags[j+1:]) { + return true + } + j = len(flags) + } else { + if i+1 >= len(args) { + return false + } + if args[i+1].Literal && checkSplitString(args[i+1].Value) { + return true + } + consumedNext = true + } + case strings.IndexByte(spec.shortNoArg, ch) >= 0: + continue + case strings.IndexByte(spec.shortArg, ch) >= 0: + if j+1 < len(flags) { + j = len(flags) + } else { + if i+1 >= len(args) { + return false + } + consumedNext = true + } + default: + unknownOpt = true + j = len(flags) + } + } + if unknownOpt { + if walk(i + 1) { + return true + } + if i+1 < len(args) && walk(i+2) { + return true + } + return false + } + if consumedNext { + i += 2 + } else { + i++ + } } - if consumedNext { - i += 2 - } else { + + for i < len(args) && args[i].AssignLike { i++ } + if i >= len(args) || seenIdx[i] { + return false + } + seenIdx[i] = true + candidates++ + return callMatchesArgv(rule, args[i:], depth) } - - for i < len(args) && args[i].AssignLike { - i++ - } - if i >= len(args) { - return false - } - return callMatchesArgv(rule, args[i:], depth) + return walk(0) } // findExecMatches walks every -exec, -execdir, -ok, and -okdir clause inside a @@ -785,18 +811,21 @@ func parallelMatchesArgv(rule []string, args []callWord, depth int) bool { return false } -// wrapperSpec describes the handled leading-option layout for a wrapper -// program. Any flag not listed here causes stripping to skip the call rather -// than guess, except for optional-argument flags in shortOptAmb / longOptAmb -// where both 0-arg and 1-arg interpretations are considered. +// wrapperSpec describes the leading-option layout for a known wrapper program. +// Explicit non-executing modes (stopShort / stopLong, plus --help / --version) +// skip unwrapping. Unknown options on a known wrapper are over-approximated +// (trying both 0-arg and 1-arg interpretations, capped by +// argvMaxWrapperCandidates) rather than returning no match. type wrapperSpec struct { shortNoArg string // short flags that take no argument shortArg string // short flags that take one argument (attached or next token) shortOptAtt string // short flags that accept only an optional attached argument (never next token) shortOptAmb string // short flags with optional attached OR separate next-token value (try both) + stopShort string // short flags indicating a non-executing mode (skip unwrapping) longNoArg map[string]bool // --flag (no value) longArg map[string]bool // --flag VAL or --flag=VAL longOptVal map[string]bool // --flag or --flag=VAL (never consumes next token) + stopLong map[string]bool // --flag indicating a non-executing mode (skip unwrapping) allowBareMin bool // treat bare "-" as a no-arg option allowNumFlag bool // treat - as a no-arg option (nice -10) skipAssigns bool // skip NAME=VALUE tokens after options (env, sudo) @@ -823,6 +852,7 @@ var wrapperSpecs = map[string]wrapperSpec{ }, "command": { shortNoArg: "p", + stopShort: "vV", }, "builtin": {}, "exec": { @@ -846,8 +876,10 @@ var wrapperSpecs = map[string]wrapperSpec{ "ionice": { shortNoArg: "t", shortArg: "cn", + stopShort: "pPu", longNoArg: strSet("ignore"), longArg: strSet("class", "classdata"), + stopLong: strSet("pid", "pgid", "uid"), }, "timeout": { shortNoArg: "fpv", @@ -858,27 +890,34 @@ var wrapperSpecs = map[string]wrapperSpec{ }, "taskset": { shortNoArg: "ca", + stopShort: "p", longNoArg: strSet("cpu-list", "all-tasks"), + stopLong: strSet("pid"), posBeforeCmd: 1, // MASK / CPU-LIST }, "chrt": { shortNoArg: "abdforiRv", shortArg: "TPD", + stopShort: "pm", longNoArg: strSet("all-tasks", "batch", "deadline", "fifo", "idle", "other", "rr", "reset-on-fork", "verbose"), longArg: strSet("sched-runtime", "sched-period", "sched-deadline"), + stopLong: strSet("pid", "max"), posBeforeCmd: 1, // PRIORITY }, "sudo": { shortNoArg: "AbBEHikKnPsSv", shortArg: "CDghprRtTuU", + stopShort: "elV", longNoArg: strSet("askpass", "background", "bell", "set-home", "login", "reset-timestamp", "remove-timestamp", "non-interactive", "preserve-groups", "shell", "stdin", "validate"), longArg: strSet("close-from", "chdir", "group", "host", "prompt", "role", "chroot", "type", "command-timeout", "user", "other-user"), longOptVal: strSet("preserve-env"), + stopLong: strSet("edit", "list"), skipAssigns: true, }, "doas": { shortNoArg: "Lns", shortArg: "au", + stopShort: "C", }, "watch": { shortNoArg: "bcCegprtwx", @@ -915,7 +954,9 @@ var wrapperSpecs = map[string]wrapperSpec{ longNoArg: strSet("null", "open-tty", "interactive", "no-run-if-empty", "verbose", "exit", "show-limits"), longArg: strSet("arg-file", "delimiter", "eof", "replace", "max-lines", "max-args", "max-procs", "max-chars", "process-slot-var"), }, - "busybox": {}, + "busybox": { + stopLong: strSet("list", "list-full", "list-modules", "install"), + }, "chroot": { longNoArg: strSet("skip-chdir"), longArg: strSet("userspec", "groups"), @@ -924,16 +965,17 @@ var wrapperSpecs = map[string]wrapperSpec{ "parallel": { shortNoArg: "0kmquvXi", shortArg: "jnNPILSadEC", - longNoArg: strSet("null", "keep-order", "quote", "ungroup", "verbose", "bar", "eta", "progress", "no-notice", "will-cite", "plain", "pipe", "pipepart", "line-buffer", "group", "dry-run", "shuf"), - longArg: strSet("jobs", "max-args", "max-procs", "max-lines", "sshlogin", "arg-file", "delimiter", "colsep", "tagstring", "timeout", "delay", "retries", "results", "joblog", "workdir", "wd", "env", "halt", "memfree", "load"), + longNoArg: strSet("null", "keep-order", "quote", "ungroup", "verbose", "bar", "eta", "progress", "no-notice", "will-cite", "plain", "pipe", "pipepart", "line-buffer", "group", "dry-run", "shuf", "link", "xargs"), + longArg: strSet("jobs", "max-args", "max-procs", "max-lines", "sshlogin", "sshloginfile", "basefile", "transferfile", "total-jobs", "block", "recstart", "recend", "compress-program", "use-compress-program", "nice", "sshdelay", "arg-file", "delimiter", "colsep", "tagstring", "timeout", "delay", "retries", "results", "joblog", "workdir", "wd", "env", "halt", "memfree", "load"), longOptVal: strSet("tag"), }, } // stripOneWrapperCandidates returns the possible wrapped-command slices after // stripping prog's options, assignments, and required positional arguments. -// For unambiguous options it returns at most one slice; for optional-argument -// flags (such as xargs -l) it returns both the 0-arg and 1-arg interpretations. +// For unambiguous known options it returns one slice; for optional-argument +// flags (such as xargs -l) or unknown options on a known wrapper it tries both +// 0-arg and 1-arg interpretations up to argvMaxWrapperCandidates. func stripOneWrapperCandidates(prog string, args []callWord) [][]callWord { spec, ok := wrapperSpecs[prog] if !ok { @@ -972,10 +1014,14 @@ func stripOneWrapperCandidates(prog string, args []callWord) [][]callWord { name := tok[2:] if eq := strings.IndexByte(name, '='); eq >= 0 { flagName := name[:eq] - if spec.longArg[flagName] || spec.longOptVal[flagName] { - i++ - continue + if spec.stopLong[flagName] { + return } + // Known or unknown --flag=val consumes one token. + i++ + continue + } + if name == "help" || name == "version" || spec.stopLong[name] { return } if spec.longNoArg[name] || spec.longOptVal[name] { @@ -989,6 +1035,11 @@ func stripOneWrapperCandidates(prog string, args []callWord) [][]callWord { i += 2 continue } + // Unknown long option without "=": try both 0-arg and 1-arg. + walk(i + 1) + if i+1 < len(args) { + walk(i + 2) + } return } @@ -999,9 +1050,12 @@ func stripOneWrapperCandidates(prog string, args []callWord) [][]callWord { } consumedNext := false ambiguousNext := false + unknownNext := false for j := 0; j < len(flags); j++ { ch := flags[j] switch { + case strings.IndexByte(spec.stopShort, ch) >= 0: + return case strings.IndexByte(spec.shortNoArg, ch) >= 0: continue case strings.IndexByte(spec.shortOptAtt, ch) >= 0: @@ -1025,9 +1079,18 @@ func stripOneWrapperCandidates(prog string, args []callWord) [][]callWord { consumedNext = true } default: - return + // Unknown short flag on a known wrapper: try both 0-arg and 1-arg. + unknownNext = true + j = len(flags) } } + if unknownNext { + walk(i + 1) + if i+1 < len(args) { + walk(i + 2) + } + return + } if ambiguousNext && !consumedNext { // Interpretation 1: no-arg. walk(i + 1) diff --git a/intercept/argv_compound_test.go b/intercept/argv_compound_test.go index 4e18d93..2ee2110 100644 --- a/intercept/argv_compound_test.go +++ b/intercept/argv_compound_test.go @@ -83,6 +83,12 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { {"parallel no command ::: quoted line", `parallel ::: "nmap -p 80 x"`}, {"parallel no command -j2 ::: bare", "parallel -j2 ::: nmap"}, {"parallel no command ::: multiple lines", "parallel ::: echo nmap"}, + {"parallel --link ::: nmap", "parallel --link ::: nmap"}, + {"parallel --xargs ::: nmap", "parallel --xargs ::: nmap"}, + {"parallel unknown no-arg long opt", "parallel --future-flag ::: nmap"}, + {"parallel unknown value long opt", "parallel --future-val 42 nmap -p 80 x"}, + {"sudo unknown flag over-approximated", "sudo --unknown-flag nmap -p 80 x"}, + {"env unknown flag over-approximated", "env -Z nmap -p 80 x"}, {"busybox", "busybox nmap -p 80 x"}, {"busybox sh -c", "busybox sh -c 'nmap -p 80 x'"}, {"chroot", "chroot / nmap -p 80 x"}, @@ -147,8 +153,6 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { {"command -V lookup", "command -V nmap"}, {"sudo -l list", "sudo -l nmap"}, {"sudo -e edit", "sudo -e nmap"}, - {"sudo unknown flag", "sudo --unknown-flag nmap -p 80 x"}, - {"env unknown flag", "env -Z nmap -p 80 x"}, {"env no command", "env FOO=1"}, {"ionice pid mode", "ionice -p 1234"}, {"taskset pid mode", "taskset -p 1234"}, @@ -163,6 +167,7 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { {"parallel echo with nmap input", "parallel echo ::: nmap"}, {"parallel no command ::: echo nmap quoted", `parallel ::: "echo nmap"`}, {"parallel echo nmap ::: x", "parallel echo nmap ::: x"}, + {"parallel --link echo nmap ::: x", "parallel --link echo nmap ::: x"}, {"parallel :::: file input", "parallel :::: nmap"}, {"parallel :::+ separator", "parallel :::+ nmap"}, {"chroot without command", "chroot /"},