mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-20 07:00:58 +08:00
fix(intercept): match argv deny and ask rules across compound and wrapped Bash commands
This commit is contained in:
@@ -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 -<digits> 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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+13
-5
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user