diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index f0467d2..e156eb9 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -59,7 +59,7 @@ { "name": "delivery", "description": "Agents and skills for taking a change from spec to a verified merge through tracker-gated stages.", - "version": "0.1.0", + "version": "0.2.0", "category": "Developer Tools", "source": "./plugins/delivery" }, diff --git a/apm.yml b/apm.yml index 6e816f7..9bf54fb 100644 --- a/apm.yml +++ b/apm.yml @@ -73,7 +73,7 @@ executables: bin: true # delivery ships the guard hook (ADR-0032 enforcement layer 2). Same # version-in-key convention as above, kept by the same sync check. - delivery#0.1.0: + delivery#0.2.0: hooks: true marketplace: diff --git a/docs/adr/0032-credentials-not-hooks-are-the-agent-safety-boundary.md b/docs/adr/0032-credentials-not-hooks-are-the-agent-safety-boundary.md index 8de2d6b..23f3296 100644 --- a/docs/adr/0032-credentials-not-hooks-are-the-agent-safety-boundary.md +++ b/docs/adr/0032-credentials-not-hooks-are-the-agent-safety-boundary.md @@ -96,9 +96,10 @@ running it in CI on a bot PR hands the bot those credentials. Decided in since v1.0.53), so on Copilot an odd-job ask may run without a human answer. The owner kept ask on Copilot rather than deny; Copilot is untested in v1 and the credential boundary still holds. - The guard hook (`plugins/delivery/.apm/hooks/guard.py`) also checks file-tool paths (Read, Grep, - Edit, Copilot's `view`, Codex's `apply_patch`) against the secret-path globs, not only shell - commands. `kubectl`, `helm`, `flux` and `tofu` are allowlists of read verbs: anything not on - the list is denied, so an unlisted mutating verb fails safe. Codex cannot ask, so odd jobs are + Edit, Write, Copilot's `view`, Codex's `apply_patch`) against the secret-path globs, not only + shell commands. `kubectl`, `helm`, `flux` and `tofu` are allowlists of subcommands that change no + cluster or state and print no secret: anything not on the list is denied, so an unlisted mutating + subcommand fails safe. Codex cannot ask, so odd jobs are denied there; an unrecognised runtime is treated the same way. - *Amended 2026-11-23 ([delivery guard hook](https://git.rkdr.net/Mortis/Holocron/issues/190)): Copilot ask kept as an accepted risk; the guard covers file tools and uses read-verb allowlists.* diff --git a/plugins/delivery/.apm/hooks/guard.py b/plugins/delivery/.apm/hooks/guard.py index 6acf914..0c8a188 100755 --- a/plugins/delivery/.apm/hooks/guard.py +++ b/plugins/delivery/.apm/hooks/guard.py @@ -19,7 +19,8 @@ Runtime detection is by where apm deployed this file: .github/hooks/scripts/... Copilot CLI ask honoured (see ADR-0032 risks) .codex/hooks/... Codex ask unsupported, so deny anywhere else unknown deny -A camelCase payload (`toolName`) is also taken as Copilot. +The payload's shape (camelCase `toolName` or snake_case `tool_name`) picks only +how the payload is read, never the runtime. """ import fnmatch @@ -64,25 +65,57 @@ OK = Verdict() HOOK_BYPASS = "never bypass the repo's gates." +# Copilot lets a timed-out hook's call through, so the guard refuses input too +# big to read quickly instead of trying. +MAX_COMMAND = 256 * 1024 +# Bounds that keep the guard linear on pathological input: words in one simple +# command, and wrappers unwrapped inside one another (`sudo sudo sudo …`). +MAX_WORDS = 2000 +MAX_COMMANDS = 5000 +MAX_UNWRAP = 32 + # -------------------------------------------------------------------------- # Secret material: paths an agent never reads # -------------------------------------------------------------------------- SECRET_BASENAME_GLOBS = ( - ".vault_pass*", ".vault-pass*", "vault_pass*", "vault-pass*", - "*vault_password*", "*vault-password*", + ".vault_pass*", ".vault-pass*", "*.tfstate", "*.tfstate.*", - "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "id_ecdsa_sk", "id_ed25519_sk", + "id_rsa*", "id_dsa*", "id_ecdsa*", "id_ed25519*", "*.key", "key.pem", "*-key.pem", "*_key.pem", "*.key.pem", "privkey*.pem", - "*private*.pem", "*.p12", "*.pfx", + "*private*.pem", "*.p12", "*.pfx", ".git-credentials*", ) +# Names that also fit source and docs about the secret (`vault_password.yml`, +# `test_vault_password.py`). A doc or data suffix exempts them. A code suffix +# exempts only a test file: `vault_pass.py` / `vault-pass.sh` is the usual name +# of an Ansible vault-password script, and running it prints the password. +SECRET_NAME_GLOBS = ("vault_pass*", "vault-pass*", "*vault_password*", + "*vault-password*", "*deploy_key*") +DOC_SUFFIXES = (".yml", ".yaml", ".md", ".rst", ".j2", ".adoc", ".html") +CODE_SUFFIXES = (".py", ".sh", ".go", ".rs", ".js", ".ts") + + +def _is_doc_or_test(base): + if base.endswith(DOC_SUFFIXES): + return True + if base.endswith(CODE_SUFFIXES): + stem = base.rsplit(".", 1)[0] + return stem.startswith(("test_", "test-")) or stem.endswith(("_test", "-test")) + return False +# Secret files whose basename alone is too common to match on. +SECRET_PATH_SUFFIXES = ("/sops/age/keys.txt", "/rancher/k3s/k3s.yaml", + "/kubernetes/admin.conf") +# Directories whose contents are secret as a whole: naming the directory, or +# any glob inside it, counts. +SECRET_DIRS = (".kube", ".ssh") # Representative secret names, used to decide whether a shell glob the agent # wrote (`cat .vault_pa*`) could expand to secret material. SECRET_SAMPLES = ( ".vault_pass", ".vault-pass", "vault_pass.txt", "vault_password", ".vault_password_file", "terraform.tfstate", "terraform.tfstate.backup", "id_rsa", "id_ed25519", "id_ecdsa", "server.key", "privkey.pem", - "tls-key.pem", "sealed-secrets-key.pem", "cert.p12", + "tls-key.pem", "sealed-secrets-key.pem", "cert.p12", ".git-credentials", + "deploy_key", ) GLOB_CHARS = set("*?[") @@ -100,227 +133,410 @@ def is_secret_path(word): candidates.add(word.rsplit("=", 1)[1]) if word.startswith("@"): candidates.add(word[1:]) + # git's REV:path (`git show HEAD:.vault_pass`) + if ":" in word: + candidates.add(word.split(":", 1)[1]) for cand in candidates: - cand = cand.strip().rstrip("/") - if not cand: + norm = cand.strip().replace("\\", "/").rstrip("/") + if not norm: continue - norm = cand.replace("\\", "/") - # the admin kubeconfig, its backups, and the directory holding them - if norm == ".kube" or norm.endswith("/.kube") or "/.kube/config" in "/" + norm: + parts = norm.split("/") + base = parts[-1].lower() + parent = parts[-2].lower() if len(parts) > 1 else "" + if base in SECRET_DIRS: + return True + if parent in SECRET_DIRS and GLOB_CHARS & set(base): + return True + # the admin kubeconfig and its backups; other kubeconfigs are fine + if parent == ".kube" and (base == "config" or base.startswith("config.") + or base == "config~"): + return True + if ("/" + norm.lower()).endswith(SECRET_PATH_SUFFIXES): return True - base = os.path.basename(norm).lower() if base.endswith(".pub"): continue if any(fnmatch.fnmatchcase(base, g) for g in SECRET_BASENAME_GLOBS): return True - if GLOB_CHARS & set(base) and _literal_count(base) >= 3: + if not _is_doc_or_test(base) and \ + any(fnmatch.fnmatchcase(base, g) for g in SECRET_NAME_GLOBS): + return True + if GLOB_CHARS & set(base) and len(base) < 256 and _literal_count(base) >= 3: if any(fnmatch.fnmatchcase(s, base) for s in SECRET_SAMPLES): return True - parent = os.path.basename(os.path.dirname(norm)) - if parent == ".kube" and fnmatch.fnmatchcase("config", base): - return True return False +HOOKS_DIR = re.compile(r"(?:^|/)\.git/hooks(?:/|$)") + + +def is_hooks_path(word): + return bool(HOOKS_DIR.search(word.replace("\\", "/"))) + + # -------------------------------------------------------------------------- # Shell tokenising # -------------------------------------------------------------------------- -OPERATORS = ("&&", "||", ";;", "|&", ";", "|", "&", "\n", "(", ")") -REDIRECTS = ("<<<", "<<-", "<<", ">>", "&>", ">&", "<&", "<>", ">|", "<", ">") +# Longest first, so `&&` wins over `&` and `<<<` over `<<`. +OPERATORS = re.compile(r"&&|\|\||;;|\|&|[;|&\n()]") +REDIRECTS = re.compile(r"<<<|<<-|<<|&>>|>>|&>|>&|<&|<>|>\||[<>]") +WORD_END = set(" \t\r\n;&|()<>") +# Runs of characters with no special meaning inside a word. +PLAIN = re.compile(r"[^\s;&|()<>\\'\"`$@{]+") +PS_PLAIN = re.compile(r"[^\s;&|()<>`'\"$@{]+") +FD_PREFIX = re.compile(r"[0-9]+(?=[<>])") +PS_FD_PREFIX = re.compile(r"(?:[0-9]+|\*)(?=>)") +VAR_START = re.compile(r"[A-Za-z_{0-9@*#?!$-]") +MAX_NESTING = 40 + + +class TooComplex(Exception): + pass + + +class Word(str): + """A shell word after unquoting. + + dynamic: it still holds an expansion, so its value is only known at run + time. brace: its unquoted text has a brace expansion (`{a,b}`, `{1..3}`). + """ + dynamic = False + brace = False + + def __new__(cls, text, dynamic=False, brace=False): + word = str.__new__(cls, text) + word.dynamic = dynamic + word.brace = brace + return word + + +def _has_brace(text): + # Linear: an opening brace, then a comma or `..`, then the closing brace, + # with no other brace between. + if "{" not in text: + return False + open_, list_, prev = False, False, "" + for ch in text: + if ch == "{": + open_, list_ = True, False + elif ch == "}": + if open_ and list_: + return True + open_ = False + elif open_ and (ch == "," or (ch == "." and prev == ".")): + list_ = True + prev = ch + return False + + +class Command: + """One simple command: its words, its redirections, and what it reads on + stdin from here-documents and here-strings.""" + + def __init__(self): + self.words = [] + self.redirects = [] # (operator, target word) + self.stdin = [] class Shell: - """Splits a command line into simple commands (lists of unquoted words). + """Splits a command line into simple commands. Not a full shell parser. It understands quoting, escapes, the control - operators, redirections, here-documents (whose bodies are data, not - commands), and command / process substitution, whose inner text is - analysed as further commands. A word that still holds a parameter - expansion after unquoting is marked dynamic, because its value is unknown. + operators, redirections, here-documents, arithmetic and command / process + substitution. A substitution's body is parsed by a nested Shell over the + same text, so the end of `$(...)` is found by the same rules as the rest + of the line, here-documents included. Here-document bodies are data, + except that an unquoted delimiter's body still runs its substitutions. + `ps` switches to PowerShell quoting: backtick escapes, backslash does not. """ - def __init__(self, text): + def __init__(self, text, ps=False, depth=0, arith=False, start=0): + if depth > MAX_NESTING: + raise TooComplex() self.text = text - self.i = 0 - self.commands = [] # list of list of (word, dynamic) - self.nested = [] # inner texts of $(...), `...`, <(...), >(...) - self.pending = [] # (delimiter, strip_tabs) of here-docs to skip + self.ps = ps + self.depth = depth + self.arith = arith # inside (( )) or $(( )): no commands, no here-docs + self.i = start + self.commands = [] + self.nested = [] # Shells of substitutions and here-doc bodies + self.pending = [] # here-docs whose bodies start at the next newline - def parse(self): - current = [] - n = len(self.text) + def _child(self, start, arith=False): + return Shell(self.text, self.ps, self.depth + 1, arith, start) + + def parse(self, closer=False): + """Parse to the end, or with closer=True to the first unmatched ')'.""" + text, n = self.text, len(self.text) + cur = Command() + parens = 0 while self.i < n: - c = self.text[self.i] - if c in " \t": + c = text[self.i] + if c in " \t\r": self.i += 1 continue - if self.text.startswith("\\\n", self.i): + if text.startswith("`\n" if self.ps else "\\\n", self.i): self.i += 2 continue if c == "#" and self._at_word_start(): - while self.i < n and self.text[self.i] != "\n": - self.i += 1 + end = text.find("\n", self.i) + self.i = n if end == -1 else end + continue + if self.ps and text.startswith("<#", self.i): + end = text.find("#>", self.i) + self.i = n if end == -1 else end + 2 + continue + if text.startswith("((", self.i) and not (cur.words or self.ps or self.arith): + self._arith(self.i + 2) continue op = self._match(OPERATORS) if op: self.i += len(op) - if op == "\n" and self.pending: - self._skip_heredocs() - if current: - self.commands.append(current) - current = [] + if op == "(": + parens += 1 + elif op == ")": + if parens == 0 and closer: + break + parens = max(0, parens - 1) + elif op == "\n" and self.pending: + self._read_heredocs() + self._end(cur) + cur = Command() continue - if self.text.startswith(("<(", ">("), self.i): - self.i += 1 - self.nested.append(self._balanced("(", ")")) + if not self.ps and text.startswith(("<(", ">("), self.i): + self._nest(self.i + 2) + cur.words.append(Word("/dev/fd/63", dynamic=True)) continue + fd = (PS_FD_PREFIX if self.ps else FD_PREFIX).match(text, self.i) + if fd: + self.i = fd.end() red = self._match(REDIRECTS) if red: self.i += len(red) - if red in ("<<", "<<-"): - while self.i < n and self.text[self.i] in " \t": - self.i += 1 - delim, _ = self._word() - self.pending.append((delim, red == "<<-")) - # any other redirect target stays a word of this command, so a - # `< .vault_pass` is caught by the secret-path check + self._redirect(red, cur) continue - word, dynamic = self._word() - current.append((word, dynamic)) - if current: - self.commands.append(current) + cur.words.append(self._word()) + if len(cur.words) > MAX_WORDS: + raise TooComplex() + self._end(cur) return self - def _skip_heredocs(self): - n = len(self.text) - for delim, strip_tabs in self.pending: + def _end(self, cmd): + if cmd.words or cmd.redirects or cmd.stdin: + self.commands.append(cmd) + if len(self.commands) > MAX_COMMANDS: + raise TooComplex() + + def _nest(self, start, arith=False): + sub = self._child(start, arith).parse(closer=True) + self.nested.append(sub) + self.i = sub.i + return sub + + def _arith(self, start): + # (( ... )) / $(( ... )): `<<` is a shift, not a here-doc + self._nest(start, arith=True) + if self.text.startswith(")", self.i): + self.i += 1 + + def _redirect(self, red, cmd): + if self.arith: + return + while self.i < len(self.text) and self.text[self.i] in " \t": + self.i += 1 + start = self.i + target = self._word() + if red in ("<<", "<<-") and not self.ps: + raw = self.text[start:self.i] + expands = not any(q in raw for q in "'\"\\") + self.pending.append((str(target), red == "<<-", expands, cmd)) + elif red == "<<<": + cmd.stdin.append(target) + else: + cmd.redirects.append((red, target)) + + def _read_heredocs(self): + text, n = self.text, len(self.text) + for delim, strip_tabs, expands, cmd in self.pending: + lines = [] while self.i < n: - end = self.text.find("\n", self.i) + end = text.find("\n", self.i) end = n if end == -1 else end - line = self.text[self.i:end] + line = text[self.i:end] self.i = min(end + 1, n) if (line.lstrip("\t") if strip_tabs else line) == delim: break + lines.append(line) + body = "\n".join(lines) + cmd.stdin.append(body) + if expands: + sub = Shell(body, self.ps, self.depth + 1) + sub._dquote(None) + self.nested.append(sub) self.pending = [] def _at_word_start(self): return self.i == 0 or self.text[self.i - 1] in " \t\n;&|()" def _match(self, ops): - for op in ops: - if self.text.startswith(op, self.i): - return op - return None + m = ops.match(self.text, self.i) + return m.group() if m else None - def _balanced(self, open_c, close_c): - # self.i is at open_c - depth, start = 0, self.i + 1 - n = len(self.text) - quote = None - while self.i < n: - c = self.text[self.i] - if quote: - if c == "\\" and quote == '"': - self.i += 2 - continue - if c == quote: - quote = None - elif c in "'\"": - quote = c - elif c == "\\": - self.i += 2 - continue - elif c == open_c: - depth += 1 - elif c == close_c: - depth -= 1 - if depth == 0: - inner = self.text[start:self.i] - self.i += 1 - return inner - self.i += 1 - return self.text[start:] + def _substitution(self): + # self.i is at "$(" (bash or PowerShell) + if not self.ps and self.text.startswith("$((", self.i): + self._arith(self.i + 3) + else: + self._nest(self.i + 2) def _backtick(self): - start = self.i + 1 - self.i += 1 - n = len(self.text) - while self.i < n and self.text[self.i] != "`": - if self.text[self.i] == "\\": - self.i += 1 - self.i += 1 - inner = self.text[start:self.i] - self.i += 1 - return inner + text, n = self.text, len(self.text) + j = self.i + 1 + out = [] + while j < n and text[j] != "`": + if text[j] == "\\" and j + 1 < n: + out.append(text[j + 1] if text[j + 1] in "$`\\" else text[j:j + 2]) + j += 2 + continue + out.append(text[j]) + j += 1 + self.i = j + 1 + self.nested.append(Shell("".join(out), self.ps, self.depth + 1).parse()) - def _word(self): + def _dquote(self, stop): + """Read double-quoted text (or a here-doc body, stop=None) up to stop. + + Returns (text, dynamic). Substitutions inside are parsed as nested. + """ + text, n = self.text, len(self.text) + esc = "`" if self.ps else "\\" out = [] dynamic = False - n = len(self.text) while self.i < n: - c = self.text[self.i] - if c in " \t\n;&|()<>": + d = text[self.i] + if stop and d == stop: + if self.ps and text.startswith(stop * 2, self.i): + out.append(stop) + self.i += 2 + continue + self.i += 1 break - if c == "\\": - if self.i + 1 < n and self.text[self.i + 1] != "\n": - out.append(self.text[self.i + 1]) - self.i += 2 # a backslash-newline is a line continuation - elif c == "'": - end = self.text.find("'", self.i + 1) - end = n if end == -1 else end - out.append(self.text[self.i + 1:end]) - self.i = end + 1 - elif c == '"': - self.i += 1 - while self.i < n and self.text[self.i] != '"': - d = self.text[self.i] - if d == "\\" and self.i + 1 < n and self.text[self.i + 1] in '"\\$`\n': - if self.text[self.i + 1] != "\n": - out.append(self.text[self.i + 1]) - self.i += 2 - elif d == "$" and self.text.startswith("$(", self.i): - self.i += 1 - self.nested.append(self._balanced("(", ")")) - dynamic = True - elif d == "`": - self.nested.append(self._backtick()) - dynamic = True - elif d == "$" and self.i + 1 < n and re.match(r"[A-Za-z_{0-9@*#?!$-]", self.text[self.i + 1]): - out.append(d) - dynamic = True - self.i += 1 - else: - out.append(d) - self.i += 1 - self.i += 1 - elif c == "$" and self.text.startswith("$'", self.i): - self.i += 1 - end = self.text.find("'", self.i + 1) - end = n if end == -1 else end - raw = self.text[self.i + 1:end] - try: - raw = raw.encode("latin-1", "backslashreplace").decode("unicode_escape") - except Exception: - pass - out.append(raw) - self.i = end + 1 - elif c == "$" and self.text.startswith("$(", self.i): - self.i += 1 - self.nested.append(self._balanced("(", ")")) + if d == esc and self.i + 1 < n: + nxt = text[self.i + 1] + if self.ps or nxt in '"\\$`\n': + if nxt != "\n": + out.append(nxt) + self.i += 2 + continue + if text.startswith("$(", self.i): + self._substitution() dynamic = True - elif c == "`": - self.nested.append(self._backtick()) + continue + if d == "`" and not self.ps: + self._backtick() dynamic = True - elif c == "$" and self.i + 1 < n and re.match(r"[A-Za-z_{0-9@*#?!$-]", self.text[self.i + 1]): - out.append(c) + continue + if d == "$" and self.i + 1 < n and VAR_START.match(text[self.i + 1]): dynamic = True - self.i += 1 - else: - out.append(c) - self.i += 1 + out.append(d) + self.i += 1 return "".join(out), dynamic + def _single(self): + # self.i is at the opening quote; PowerShell doubles a quote to escape it + text, n = self.text, len(self.text) + out = [] + j = self.i + 1 + while True: + end = text.find("'", j) + if end == -1: + out.append(text[j:]) + self.i = n + return "".join(out) + out.append(text[j:end]) + if self.ps and text.startswith("''", end): + out.append("'") + j = end + 2 + continue + self.i = end + 1 + return "".join(out) + + def _ansi_c(self): + # $'...': backslash escapes, including \' + text, n = self.text, len(self.text) + j = self.i + 2 + while j < n and text[j] != "'": + j += 2 if text[j] == "\\" else 1 + raw = text[self.i + 2:min(j, n)] + self.i = j + 1 + try: + return raw.encode("latin-1", "backslashreplace").decode("unicode_escape") + except Exception: + return raw + + def _ps_herestring(self): + # @' ... '@ and @" ... "@: the terminator sits at the start of a line + quote = self.text[self.i + 1] + start = self.i + 2 + end = self.text.find("\n" + quote + "@", start) + end = len(self.text) if end == -1 else end + body = self.text[start:end] + self.i = end + 3 + if quote == "'": + return body, False + sub = Shell(body, True, self.depth + 1) + out, dynamic = sub._dquote(None) + self.nested.append(sub) + return out, dynamic + + def _word(self): + text, n = self.text, len(self.text) + out = [] + unquoted = [] + dynamic = False + plain = PS_PLAIN if self.ps else PLAIN + while self.i < n: + run = plain.match(text, self.i) + if run: + out.append(run.group()) + unquoted.append(run.group()) + self.i = run.end() + continue + c = text[self.i] + if c in WORD_END: + break + if self.ps and c == "`" or not self.ps and c == "\\": + if self.i + 1 < n and text[self.i + 1] != "\n": + out.append(text[self.i + 1]) + self.i += 2 # an escaped newline is a line continuation + elif c == "'": + out.append(self._single()) + elif c == '"' or (not self.ps and text.startswith('$"', self.i)): + self.i += 1 if c == '"' else 2 + part, dyn = self._dquote('"') + out.append(part) + dynamic = dynamic or dyn + elif self.ps and text.startswith(("@'", '@"'), self.i): + part, dyn = self._ps_herestring() + out.append(part) + dynamic = dynamic or dyn + elif not self.ps and text.startswith("$'", self.i): + out.append(self._ansi_c()) + elif text.startswith("$(", self.i): + self._substitution() + dynamic = True + elif c == "`" and not self.ps: + self._backtick() + dynamic = True + else: + if c == "$" and self.i + 1 < n and VAR_START.match(text[self.i + 1]): + dynamic = True + out.append(c) + unquoted.append(c) + self.i += 1 + return Word("".join(out), dynamic, _has_brace("".join(unquoted))) + # -------------------------------------------------------------------------- # Unwrapping: find the program a simple command really runs @@ -328,11 +544,17 @@ class Shell: SHELLS = {"sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "fish"} SHELL_VALUE_OPTS = {"-o", "+o", "-O", "+O", "--rcfile", "--init-file"} +PWSH = {"powershell", "pwsh"} +PWSH_VALUE_OPTS = {"-executionpolicy", "-ep", "-ex", "-workingdirectory", "-wd", + "-windowstyle", "-w", "-outputformat", "-of", "-o", + "-inputformat", "-if", "-i", "-configurationname", "-version", + "-v", "-settingsfile", "-psconsolefile"} +EVALS = {"eval", "iex", "invoke-expression"} # Words that only prefix the real command. Matched on the basename, so # /usr/bin/time and /usr/bin/nohup count. -KEYWORDS = {"!", "{", "}", "then", "do", "else", "elif", "if", "while", "until", - "time", "coproc", "exec", "command", "builtin", "nohup", "setsid", - "chronic", "unbuffer", "caffeinate"} +KEYWORDS = {"!", "{", "}", "then", "do", "done", "else", "elif", "if", "while", + "until", "time", "coproc", "exec", "command", "builtin", "nohup", + "setsid", "chronic", "unbuffer", "caffeinate"} KEYWORD_VALUE_OPTS = {("exec", "-a"), ("time", "-f"), ("time", "-o"), ("time", "--format"), ("time", "--output")} # wrapper -> options that consume the next word @@ -363,50 +585,125 @@ WRAPPERS = { "--arg-file", "--delay", "--timeout", "-I", "--colsep"}, "ssh": {"-B", "-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-p", "-Q", "-R", "-S", "-W", "-w"}, + "chroot": {"--userspec", "--groups"}, } -ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\+?=") -GUARDED = re.compile( - r"\b(kubectl|kubecolor|helm|helm3|tofu|terraform|terragrunt|ansible-playbook|" - r"ansible-vault|ansible|ansible-pull|ansible-console|kubeseal|flux|sops|" - r"pre-commit)\b" - r"|--no-verif|hookspath|\bSKIP\+?=|vault.pass|\.tfstate|id_rsa|id_ed25519|\.kube", - re.I, -) -BRACE = re.compile(r"\{[^{}]*,[^{}]*\}") -# Options whose value a tool reads itself on the agent's behalf, as Ansible -# does with the vault password file and the SSH key. Such a run is an Odd job. -SECRET_ARG_EXEMPT = ("--vault-password-file", "--vault-pass-file", "--vault-id", - "--private-key", "--key-file") -SEARCHERS = {"grep", "egrep", "fgrep", "rg", "ag", "ack"} -SEARCH_VALUE_OPTS = {"-A", "-B", "-C", "-m", "-d", "-D", "-g", "-t", "-T", - "--include", "--exclude", "--exclude-dir", "--glob", - "--type", "--max-count", "--context", "--after-context", - "--before-context"} -# Programs that only print their arguments or look at file metadata. -NEUTRAL = {"echo", "printf", "ls", "stat", "test", "[", "[[", "true", ":"} -# Tool runners: args. Ansible repos commonly -# run their tools through a project venv this way. +# Tool runners: ... args. The program is the +# first word the guard knows, or whatever follows `--`. RUNNERS = { "uv": {"run", "tool"}, "poetry": {"run"}, "pipenv": {"run"}, "pdm": {"run"}, "hatch": {"run"}, "pipx": {"run"}, "direnv": {"exec"}, "mise": {"exec", "x"}, - "devbox": {"run"}, "uvx": None, + "devbox": {"run"}, "uvx": None, "aws-vault": {"exec"}, "op": {"run"}, + "doppler": {"run"}, } +# Distributions that bundle a tool as a subcommand: `k3s kubectl ...`. +BUNDLES = {"busybox", "k3s", "microk8s"} +TMUX_RUN = {"new-session", "new", "new-window", "neww", "split-window", "splitw", + "respawn-pane", "respawnp", "respawn-window", "respawnw"} +TMUX_VALUE_OPTS = {"-s", "-n", "-c", "-x", "-y", "-t", "-e", "-F", "-l", "-f"} +ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\+?=") +# Assignments whose value is a command line git runs. +COMMAND_VARS = {"GIT_SSH_COMMAND"} +GUARDED = re.compile( + r"(? 1: + idx += 1 + elif prog == "yq" and a in YQ_SUBS: + idx += 1 + else: + return {idx} + return set() -def search_pattern_indexes(args): +# Options whose value is prose: a title, a body, release notes. +MESSAGE_OPTS = { + "gh": {"-t", "--title", "-b", "--body", "-n", "--notes", "--subject"}, + "tea": {"-t", "--title", "-d", "--description", "--body"}, +} +# Programs that only print their arguments or look at file metadata. +NEUTRAL = {"echo", "printf", "ls", "stat", "test", "[", "[[", "true", ":"} +# Programs that hand a key to ssh rather than print it. +SSH_KEY_USERS = {"scp", "sftp"} +# Programs that change the files they name. Copiers change only the last one. +HOOK_WRITERS = {"rm", "rmdir", "unlink", "shred", "mv", "chmod", "chown", + "chgrp", "truncate", "tee", "sed"} +HOOK_COPIERS = {"cp", "ln", "install", "rsync"} + + +def _takes_value(word, takes_value): + """True when the option word consumes the next word: it is a value option, + or a short cluster (`-iu`) whose last letter is one.""" + if word in takes_value: + return True + return (len(word) > 2 and word[0] == "-" and word[1] != "-" + and "-" + word[-1] in takes_value) + + +def prog_name(word, ps=False): + base = os.path.basename(word.replace("\\", "/")) + low = base.lower() + if low.endswith(".exe"): + return low[:-4] + return low if ps else base + + +def option_values(args, opts): + """Indexes of the values of `opts`: the next word, or an inline value.""" + found = set() + for idx, a in enumerate(args): + if a in opts: + found.add(idx + 1) + elif "=" in a and a.split("=", 1)[0] in opts: + found.add(idx) + elif len(a) > 2 and a[:2] in opts and not a.startswith("--"): + found.add(idx) + return found + + +def search_pattern_indexes(args, value_opts): """Indexes of args that are a search pattern rather than a file.""" explicit = any(a in ("-e", "--regexp", "-f", "--file") or a.startswith(("--regexp=", "--file=")) for a in args) @@ -418,7 +715,7 @@ def search_pattern_indexes(args): skip.add(idx + 1) idx += 2 continue - if a in SEARCH_VALUE_OPTS: + if a in value_opts: skip.add(idx + 1) idx += 2 continue @@ -434,33 +731,63 @@ def search_pattern_indexes(args): return skip +def exempt_indexes(prog, args): + """Indexes of args that name no file (patterns, prose, values a tool reads + itself), or None when the program's arguments are never read as files.""" + if prog == "git": + sub_idx = _git_sub_index(args) + if sub_idx is None: + return option_values(args, {"-c"}) + sub = args[sub_idx] + if sub in ("rm", "check-ignore", "ls-files", "status"): + return None + skip = option_values(args[:sub_idx], {"-c"}) + rest = args[sub_idx + 1:] + inner = set() + if sub == "grep": + inner = search_pattern_indexes(rest, SEARCH_VALUE_OPTS) + elif sub in GIT_MESSAGE_SUBS: + inner = _git_message_indexes(rest) + return skip | {i + sub_idx + 1 for i in inner} + if prog in SEARCHERS: + value_opts = SEARCH_VALUE_OPTS | ({"-T"} if prog == "rg" else set()) + return search_pattern_indexes(args, value_opts) | option_values(args, SEARCH_GLOB_OPTS) + if prog in MESSAGE_OPTS: + return option_values(args, MESSAGE_OPTS[prog]) + if prog == "find": + if _find_acts(args): + return set() # it deletes or runs something: every name counts + return option_values(args, FIND_PATTERN_OPTS) + if prog in ANSIBLE_RUNS: + return option_values(args, SECRET_ARG_EXEMPT) + if prog in JQ_LIKE: + return _jq_filter_index(prog, args) + if prog in ("pytest", "py.test") or (prog.startswith("python") and + args[:2] == ["-m", "pytest"]): + return option_values(args, {"-k", "-m"}) + if prog in SSH_KEY_USERS: + return option_values(args, {"-i"}) + if prog == "ssh-add": + return None + return set() + + def secret_words(prog_word, prog, args): if prog in NEUTRAL: return OK - if prog == "git": - sub_idx = _git_sub_index(args) - sub = args[sub_idx] if sub_idx is not None else "" - if sub in ("rm", "check-ignore", "ls-files", "status"): - return OK - skip = set() - if prog in SEARCHERS: - skip = search_pattern_indexes(args) - elif prog == "git" and sub == "grep": - skip = {i + sub_idx + 1 for i in search_pattern_indexes(args[sub_idx + 1:])} if is_secret_path(prog_word): return deny("'%s' is secret material; agents never run or read it." % prog_word) - skip_next = False + skip = exempt_indexes(prog, args) + if skip is None: + return OK for idx, w in enumerate(args): - if skip_next: - skip_next = False - continue if idx in skip: continue - if w in SECRET_ARG_EXEMPT: - skip_next = True - continue - if w.startswith(tuple(e + "=" for e in SECRET_ARG_EXEMPT)): - continue + if w.startswith("-"): + # an option name is never a path; only an inline value can be + if "=" not in w: + continue + w = w.split("=", 1)[1] if is_secret_path(w): return deny("'%s' is secret material (vault password, private key, " "admin kubeconfig or tofu state); agents never read, copy " @@ -468,100 +795,241 @@ def secret_words(prog_word, prog, args): return OK +def _find_acts(args): + return any(a in FIND_ACTIONS for a in args) + + +def hook_writes(prog, args): + if prog == "find" and _find_acts(args): + targets = args + elif prog in HOOK_WRITERS: + if prog == "sed" and not any(a.startswith(("-i", "--in-place")) for a in args): + return OK + targets = [a for a in args if not a.startswith("-")] + elif prog in HOOK_COPIERS: + targets = [a for a in args if not a.startswith("-")][-1:] + else: + return OK + for t in targets: + if is_hooks_path(t): + return deny("Changing '%s' turns the repo's git hooks off; %s" % (t, HOOK_BYPASS)) + return OK + + +def redirect_verdict(redirects): + for op, target in redirects: + if op in (">&", "<&") and (target.isdigit() or target == "-"): + continue + if op != "<" and is_hooks_path(target): + return deny("Writing '%s' changes the repo's git hooks; %s" % (target, HOOK_BYPASS)) + if is_secret_path(target): + return deny("'%s' is secret material; agents never read or write it." % target) + return OK + + +class Ctx: + """What a simple command carries besides its words. + + guarded: the line it came from mentions a guarded tool or secret, so a + part the guard cannot read is denied rather than allowed. + stdin: here-doc bodies and here-strings the command reads. + """ + + def __init__(self, guarded=True, stdin=(), ps=False): + self.guarded = guarded + self.stdin = stdin + self.ps = ps + + class Analyzer: def __init__(self): self.depth = 0 + self.unwraps = 0 - def text(self, command): + def text(self, command, ps=False, guarded=False): """Verdict for a whole command line.""" + if len(command) > MAX_COMMAND: + return deny("The command is longer than %d KB, too long for the guard " + "to read; split it up." % (MAX_COMMAND // 1024)) if self.depth > 8: return deny("Command nesting too deep for the guard to read; simplify it.") self.depth += 1 try: - sh = Shell(command).parse() - verdict = OK - for words in sh.commands: - verdict = verdict.merge(self.simple(words, command)) - for inner in sh.nested: - verdict = verdict.merge(self.text(inner)) - return verdict + try: + sh = Shell(command, ps).parse() + except (TooComplex, RecursionError): + return deny("The command is too long or nested too deep for the guard " + "to read (over %d words in one command, %d commands, or %d " + "levels); simplify it." % (MAX_WORDS, MAX_COMMANDS, MAX_NESTING)) + return self.tree(sh, guarded or bool(GUARDED.search(command))) finally: self.depth -= 1 - def simple(self, words, whole): - joined = " ".join(w for w, _ in words) - if any(BRACE.search(w) for w, _ in words) and GUARDED.search(joined): + def tree(self, sh, guarded): + verdict = OK + if not sh.arith: + for cmd in sh.commands: + verdict = verdict.merge(self.simple(cmd, Ctx(guarded, cmd.stdin, sh.ps))) + if verdict.decision == DENY: + return verdict + for sub in sh.nested: + verdict = verdict.merge(self.tree(sub, guarded)) + if verdict.decision == DENY: + return verdict + return verdict + + def simple(self, cmd, ctx): + if any(w.brace for w in cmd.words) and GUARDED.search(" ".join(cmd.words)): return deny("Brace expansion hides what this command runs; write it " "out literally.") - return self.program(list(words), whole) + verdict = redirect_verdict(cmd.redirects) + if verdict.decision == DENY: + return verdict + return verdict.merge(self.program(cmd.words, ctx)) - def program(self, words, whole): + def assignment(self, word, ctx): + name, value = word.split("=", 1) + name = name.rstrip("+") + low = value.lower() + if name == "SKIP": + return deny("SKIP= skips pre-commit hooks; " + HOOK_BYPASS) + if name in ("HUSKY", "LEFTHOOK") and value in ("0", "false"): + return deny("%s=0 skips the repo's git hooks; %s" % (name, HOOK_BYPASS)) + if "hookspath" in low or (name.startswith("GIT_CONFIG") and "no-verify" in low): + return deny("Overriding core.hooksPath skips the repo's git hooks; " + HOOK_BYPASS) + if name in COMMAND_VARS: + return self.text(value, guarded=ctx.guarded) + if is_secret_path(value): + return deny("'%s' is secret material; agents never read it." % value) + return OK + + def program(self, words, ctx): + if len(words) > MAX_WORDS: + return deny("The command has more than %d words, too many for the guard " + "to read; split it up." % MAX_WORDS) + if self.unwraps >= MAX_UNWRAP: + return deny("Too many wrappers inside one another for the guard to read; " + "simplify the command.") + self.unwraps += 1 + try: + return self._program(words, ctx) + finally: + self.unwraps -= 1 + + def _program(self, words, ctx): verdict = OK - # leading assignments: NAME=value cmd ... - while words and ASSIGNMENT.match(words[0][0]): - verdict = verdict.merge(assignment_verdict(words[0][0])) - words = words[1:] - while words and os.path.basename(words[0][0]) in KEYWORDS: - head = os.path.basename(words[0][0]) - words = words[1:] - if head == "command" and words and words[0][0] in ("-v", "-V"): + # Walk past assignments and keywords by index: slicing at each step + # is quadratic on a long run of `! ! ! …`. + i, n = 0, len(words) + while i < n: + if ASSIGNMENT.match(words[i]): + verdict = verdict.merge(self.assignment(words[i], ctx)) + i += 1 + continue + head = prog_name(words[i], ctx.ps) + if head == "function" and i + 1 < n: + i += 2 # function NAME { ... + continue + if head not in KEYWORDS: + break + i += 1 + if head == "command" and i < n and words[i] in ("-v", "-V"): return verdict - if head == "coproc" and len(words) >= 2 and words[1][0] == "{": - words = words[1:] - while words and words[0][0].startswith("-") and len(words[0][0]) > 1: - opt = words[0][0] - words = words[1:] + if head == "coproc" and i + 1 < n and words[i + 1] == "{": + i += 1 + while i < n and words[i].startswith("-") and len(words[i]) > 1: + opt = words[i] + i += 1 if opt == "--": break if (head, opt) in KEYWORD_VALUE_OPTS: - words = words[1:] - while words and ASSIGNMENT.match(words[0][0]): - verdict = verdict.merge(assignment_verdict(words[0][0])) - words = words[1:] + i += 1 + if verdict.decision == DENY: + return verdict + words = words[i:] if not words or verdict.decision == DENY: return verdict - prog_word, prog_dynamic = words[0] - if prog_dynamic: + prog_word = words[0] + if prog_word.dynamic: # The program name is only known at run time. Fail safe when the # line mentions a guarded tool at all. - if GUARDED.search(whole): + if ctx.guarded: return deny("The program name is built at run time ('%s'), so the guard " "cannot classify this command. Write the command out literally." % prog_word) return verdict if GLOB_CHARS & set(prog_word): return deny("The program name '%s' is a glob; write it out literally." % prog_word) - prog = os.path.basename(prog_word) - args = [w for w, _ in words[1:]] + prog = prog_name(prog_word, ctx.ps) + args = words[1:] if prog in ("export", "declare", "typeset", "local", "readonly"): for a in args: if ASSIGNMENT.match(a): - verdict = verdict.merge(assignment_verdict(a)) + verdict = verdict.merge(self.assignment(a, ctx)) return verdict if prog in SHELLS: - return verdict.merge(self.shell(args, whole)) - if prog == "eval": - return verdict.merge(self.text(" ".join(args))) + return verdict.merge(self.shell(args, ctx)) + if prog in PWSH: + return verdict.merge(self.powershell(args, ctx)) + if prog == "cmd": + for idx, a in enumerate(args): + if a.lower() in ("/c", "/k", "/r"): + return verdict.merge(self.text(" ".join(args[idx + 1:]), + guarded=ctx.guarded)) + return verdict + if prog in EVALS: + if any(a.dynamic for a in args) and ctx.guarded: + return deny("'%s' runs a string built at run time; write the command " + "out literally." % prog) + return verdict.merge(self.text(" ".join(args), ctx.ps, ctx.guarded)) + if prog in ("source", "."): + if any(a.dynamic for a in args) and ctx.guarded: + return deny("'%s' runs a script built at run time; run the command " + "directly." % prog) + if prog == "trap": + rest = [a for a in args if not a.startswith("-")] + return verdict.merge(self.text(rest[0], guarded=ctx.guarded) if rest else OK) if prog in WRAPPERS: - return verdict.merge(self.wrapper(prog, words[1:], whole)) - if prog == "busybox" and args: - return verdict.merge(self.program(words[1:], whole)) + return verdict.merge(self.wrapper(prog, args, ctx)) + if prog in BUNDLES and args: + return verdict.merge(self.program(args, ctx)) if prog == "find": verdict = verdict.merge(self.find_exec(args)) + if verdict.decision == DENY: + return verdict if prog == "rtk": - return verdict.merge(self.rtk(words[1:], whole)) + return verdict.merge(self.rtk(args, ctx)) if prog in RUNNERS: - return verdict.merge(self.runner(prog, words[1:], whole)) + return verdict.merge(self.runner(prog, args, ctx)) + if prog in ("nix-shell", "nix", "tmux"): + return verdict.merge(self.launcher(prog, args, ctx)) verdict = verdict.merge(secret_words(prog_word, prog, args)) + verdict = verdict.merge(hook_writes(prog, args)) rule = RULES.get(prog) if rule: verdict = verdict.merge(rule(args, self)) return verdict - def shell(self, args, whole): + def stdin_script(self, ctx, who): + """A program that reads its commands from stdin.""" + if ctx.stdin: + verdict = OK + for doc in ctx.stdin: + verdict = verdict.merge(self.text(doc, guarded=ctx.guarded)) + return verdict + if ctx.guarded: + return deny("%s reading commands from stdin hides what it runs; run the " + "command directly." % who) + return OK + + def shell(self, args, ctx): + # Options come first. In a cluster (`-euo pipefail`), a last letter + # that takes a value consumes the next word. With -c, the command + # string is the first word after the options. idx = 0 + from_stdin = has_c = False while idx < len(args): a = args[idx] if a in SHELL_VALUE_OPTS: @@ -574,59 +1042,102 @@ class Analyzer: idx += 1 continue if a[:1] in "-+" and len(a) > 1: - if "c" in a[1:]: - j = idx + 1 - while j < len(args) and args[j] in SHELL_VALUE_OPTS: - j += 2 - return self.text(args[j]) if j < len(args) else OK + has_c = has_c or "c" in a[1:] + from_stdin = from_stdin or "s" in a[1:] + idx += 2 if a[-1] in "oO" else 1 + continue + break + rest = args[idx:] + if has_c: + if not rest: + return OK + if rest[0].dynamic and ctx.guarded: + return deny("The shell runs a string built at run time; write " + "the command out literally.") + return self.text(rest[0], guarded=ctx.guarded) + if from_stdin or not rest or rest[0] == "-": + return self.stdin_script(ctx, "A shell") + if rest[0].dynamic and ctx.guarded: + return deny("The shell runs a script built at run time; run the command " + "directly.") + if is_secret_path(rest[0]): + return deny("'%s' is secret material; agents never run or read it." % rest[0]) + return OK + + def powershell(self, args, ctx): + idx = 0 + while idx < len(args): + a = args[idx].lower() + if a in PWSH_VALUE_OPTS: + idx += 2 + continue + if a in ("-e", "-ec") or (len(a) > 2 and "-encodedcommand".startswith(a)): + return deny("An encoded PowerShell command hides what it runs; write " + "it out literally.") + if a == "-c" or (len(a) > 3 and "-command".startswith(a)): + idx += 1 + break + if a.startswith("-"): idx += 1 continue break rest = args[idx:] - if not rest: - # The shell reads its commands from stdin: a pipe or here-doc the - # guard cannot follow. - if GUARDED.search(whole): - return deny("A shell reading commands from stdin hides what it runs; " - "run the command directly.") - return OK - # bash script.sh, or a here-string (`bash <<< 'cmd'`), whose word lands here - verdict = OK - for r in rest: - verdict = verdict.merge(self.text(r)) - return verdict + if not rest or rest == ["-"]: + return self.stdin_script(ctx, "PowerShell") + return self.text(" ".join(rest), ps=True, guarded=ctx.guarded) - def rtk(self, words, whole): + def rtk(self, words, ctx): # rtk args passes through to ; rtk run is sh -c; proxy, # err, test and summary run the rest as a command. - while words and words[0][0].startswith("-"): + while words and words[0].startswith("-"): words = words[1:] if not words: return OK - sub = words[0][0] + sub = words[0] if sub == "run": - return self.text(" ".join(w for w, _ in words[1:])) + return self.text(" ".join(words[1:]), guarded=ctx.guarded) if sub in ("proxy", "err", "test", "summary"): - return self.program(words[1:], whole) - return self.program(words, whole) + return self.program(words[1:], ctx) + return self.program(words, ctx) - def runner(self, prog, words, whole): + def runner(self, prog, words, ctx): subs = RUNNERS[prog] start = 0 if subs is not None: - while start < len(words) and words[start][0].startswith("-"): + while start < len(words) and words[start].startswith("-"): start += 1 - if start >= len(words) or words[start][0] not in subs: + if start >= len(words) or words[start] not in subs: return OK start += 1 + rest = words[start:] # Runner options take values (`uv run --with x …`), so rather than # model each runner's options, start at the first word that names a - # program the guard knows. - for idx in range(start, len(words)): - base = os.path.basename(words[idx][0]) + # program the guard knows, or else after `--`. + for idx, w in enumerate(rest): + base = prog_name(w, ctx.ps) if base in RULES or base in SHELLS or base in WRAPPERS or \ - base in ("eval", "rtk") or base in RUNNERS: - return self.program(words[idx:], whole) + base in EVALS or base in RUNNERS or base in BUNDLES or base == "rtk": + return self.program(rest[idx:], ctx) + if "--" in rest: + return self.program(rest[rest.index("--") + 1:], ctx) + return OK + + def launcher(self, prog, args, ctx): + if prog == "nix-shell": + for idx, a in enumerate(args): + if a in ("--run", "--command") and idx + 1 < len(args): + return self.text(args[idx + 1], guarded=ctx.guarded) + return OK + if prog == "nix": + for idx, a in enumerate(args): + if a in ("-c", "--command"): + return self.program(args[idx + 1:], ctx) + return OK + # tmux: the shell command is what follows a command-running subcommand + for idx, a in enumerate(args): + if a in TMUX_RUN: + rest = self._skip_opts(args[idx + 1:], TMUX_VALUE_OPTS) + return self.text(" ".join(rest), guarded=ctx.guarded) if rest else OK return OK def find_exec(self, args): @@ -637,89 +1148,85 @@ class Analyzer: end = idx + 1 while end < len(args) and args[end] not in (";", "+"): end += 1 - inner = [(w, False) for w in args[idx + 1:end]] - verdict = verdict.merge(self.program(inner, " ".join(args))) + verdict = verdict.merge(self.program(args[idx + 1:end], Ctx())) idx = end idx += 1 return verdict - def wrapper(self, prog, words, whole): + def wrapper(self, prog, words, ctx): takes_value = WRAPPERS[prog] if prog in ("su", "script"): # su -c / su -lc / script -qc carry a command string - for idx, (w, _) in enumerate(words): + for idx, w in enumerate(words): is_c = w in ("-c", "--command") or ( w.startswith("-") and not w.startswith("--") and "c" in w[1:]) if is_c and idx + 1 < len(words): - return self.text(words[idx + 1][0]) + return self.text(words[idx + 1], guarded=ctx.guarded) if w.startswith("--command="): - return self.text(w.split("=", 1)[1]) + return self.text(w.split("=", 1)[1], guarded=ctx.guarded) return OK - if prog == "watch": - rest = self._skip_opts(words, takes_value) - return self.text(" ".join(w for w, _ in rest)) - if prog == "ssh": - rest = self._skip_opts(words, takes_value) - if len(rest) > 1: - return self.text(" ".join(w for w, _ in rest[1:])) - return OK - if prog == "parallel": + if prog in ("watch", "parallel"): + # both join their command words and hand them to a shell rest = self._skip_opts(words, takes_value) cmd = [] for w in rest: - if w[0] in (":::", "::::", ":::+", "::::+"): + if w in (":::", "::::", ":::+", "::::+"): break cmd.append(w) - return self.program(cmd, whole) + return self.text(" ".join(cmd), guarded=ctx.guarded) + if prog == "ssh": + rest = self._skip_opts(words, takes_value) + if len(rest) > 1: + return self.text(" ".join(rest[1:]), guarded=ctx.guarded) + if rest: # a host and no command: the remote shell reads stdin + return self.stdin_script(ctx, "ssh") + return OK # no host: git's GIT_SSH_COMMAND, which git completes if prog == "xargs": - for idx, (w, _) in enumerate(words): + for idx, w in enumerate(words): if w in ("-a", "--arg-file") and idx + 1 < len(words) and \ - is_secret_path(words[idx + 1][0]): + is_secret_path(words[idx + 1]): return deny("'%s' is secret material; agents never read it." - % words[idx + 1][0]) + % words[idx + 1]) if prog == "env": idx = 0 verdict = OK while idx < len(words): - w = words[idx][0] + w = words[idx] if w in ("-S", "--split-string") and idx + 1 < len(words): - return self.text(words[idx + 1][0] + " " + - " ".join(x for x, _ in words[idx + 2:])) + return self.text(" ".join(words[idx + 1:]), guarded=ctx.guarded) if w.startswith("--split-string="): - return self.text(w.split("=", 1)[1] + " " + - " ".join(x for x, _ in words[idx + 1:])) - if w in takes_value: + return self.text(" ".join([w.split("=", 1)[1]] + words[idx + 1:]), + guarded=ctx.guarded) + if _takes_value(w, takes_value): idx += 2 continue if w.startswith("-"): idx += 1 continue if ASSIGNMENT.match(w): - verdict = verdict.merge(assignment_verdict(w)) + verdict = verdict.merge(self.assignment(w, ctx)) idx += 1 continue break - return verdict.merge(self.program(words[idx:], whole)) + return verdict.merge(self.program(words[idx:], ctx)) rest = self._skip_opts(words, takes_value) - if prog == "timeout" and rest: - rest = rest[1:] # DURATION - if prog in ("taskset", "chrt") and rest: - rest = rest[1:] # mask / priority + if prog in ("timeout", "taskset", "chrt", "chroot") and rest: + rest = rest[1:] # duration / mask / priority / new root if prog == "flock" and rest: rest = rest[1:] # lock file - if len(rest) >= 2 and rest[0][0] in ("-c", "--command"): - return self.text(rest[1][0]) - return self.program(rest, whole) + if len(rest) >= 2 and rest[0] in ("-c", "--command"): + return self.text(rest[1], guarded=ctx.guarded) + return self.program(rest, ctx) @staticmethod def _skip_opts(words, takes_value): idx = 0 while idx < len(words): - w = words[idx][0] + w = words[idx] if w == "--": idx += 1 break - if w in takes_value: + if _takes_value(w, takes_value): idx += 2 continue if w.startswith("-") and len(w) > 1: @@ -757,6 +1264,12 @@ def wants_help(args): return any(a in ("--help", "-h", "-help") for a in args) +def _flag(args, *names): + """True when an option in `names` is given, with or without a value.""" + return any(a.lstrip("-").split("=", 1)[0] in names for a in args + if a.startswith("-")) + + KUBECTL_GLOBAL = {"-n", "--namespace", "--context", "--kubeconfig", "--cluster", "--user", "-s", "--server", "--token", "--as", "--as-group", "--as-uid", "--certificate-authority", "--client-certificate", @@ -771,7 +1284,7 @@ SECRET_RESOURCES = {"secret", "secrets"} SAFE_OUTPUTS = {"wide", "name"} -def kubectl(args, an=None): +def kubectl(args, an): idx, verb = first_positional(args, KUBECTL_GLOBAL) if verb is None or wants_help(args): return OK @@ -790,6 +1303,12 @@ def kubectl(args, an=None): if _names_secret(rest) and _secret_output(rest): return deny("'kubectl get secret -o …' prints Secret data; agents never " "read Secrets. Plain 'kubectl get secrets' lists names only.") + if _kustomize(rest) and _secret_output(rest): + return deny("'kubectl get -k … -o …' prints every object the " + "kustomization names, Secrets included.") + if _secret_manifest(rest) and _secret_output(rest): + return deny("'kubectl get -f -o …' prints the live " + "Secret's data; agents never read Secrets.") return OK if verb == "auth": sub = rest[0] if rest else "" @@ -799,9 +1318,7 @@ def kubectl(args, an=None): sub = rest[0] if rest else "" if sub in ("status", "history"): return OK - if verb == "create" and any(a == "--dry-run=client" for a in rest) or \ - verb == "create" and any(a == "--dry-run" and j + 1 < len(rest) and - rest[j + 1] == "client" for j, a in enumerate(rest)): + if verb == "create" and _dry_run(rest) == "client": # renders a manifest locally (e.g. a Secret to pipe into kubeseal) return OK if verb == "config": @@ -819,10 +1336,38 @@ def kubectl(args, an=None): return deny("Live 'kubectl diff' is a server-side dry run that needs write " "RBAC and is not used; use the offline render (kustomize build / " "flux build --dry-run).") - return deny("'kubectl %s' is not a read verb. Direct cluster changes never happen " + return deny("'kubectl %s' is not on the allowlist of subcommands that change no " + "cluster and print no secret. Direct cluster changes never happen " "from an agent; every change applies by approved merge." % verb) +def _dry_run(rest): + """The effective --dry-run mode: the last one given wins.""" + mode = None + for j, a in enumerate(rest): + if a.startswith("--dry-run="): + mode = a.split("=", 1)[1] + elif a == "--dry-run": + mode = rest[j + 1] if j + 1 < len(rest) else "unknown" + return mode + + +def _kustomize(rest): + return any(a in ("-k", "--kustomize") or a.startswith(("--kustomize=", "-k=")) + for a in rest) + + +def _secret_manifest(rest): + """A -f file whose name says it holds a Secret. A SealedSecret is + encrypted, so it does not count.""" + for j in option_values(rest, {"-f", "--filename"}): + if j < len(rest): + name = os.path.basename(rest[j].split("=", 1)[-1]).lower() + if "secret" in name and "sealed" not in name: + return True + return False + + def _names_secret(rest): for a in rest: if a.startswith("-"): @@ -859,7 +1404,7 @@ HELM_READ = {"template", "lint", "list", "ls", "status", "history", "show", "fetch", "package", "verify", "create", "completion", "help", "repo"} -def helm(args, an=None): +def helm(args, an): idx, verb = first_positional(args, HELM_GLOBAL) if verb is None or wants_help(args): return OK @@ -870,30 +1415,69 @@ def helm(args, an=None): return OK if verb == "get": sub = rest[0] if rest else "" - if sub in ("notes", "metadata", "hooks"): + if sub in ("notes", "metadata"): return OK - return deny("'helm get %s' prints release values or manifests, which can " - "hold secret material." % (sub or "")) + return deny("'helm get %s' prints release values, manifests or hooks, which " + "can hold secret material." % sub) if verb == "plugin": sub = rest[0] if rest else "" if sub in ("list", "ls"): return OK + if verb == "diff": # the helm-diff plugin: read-only, Secrets redacted + if _flag(rest, "show-secrets", "show-secrets-decoded"): + return deny("'helm diff --show-secrets' prints Secret data.") + if rest[:1] and rest[0] in HELM_DIFF_SUBS: + return OK + if verb == "secrets": # the helm-secrets plugin + return helm_secrets(rest, an) return deny("'helm %s' changes a release or the cluster. Releases change only " "by approved merge." % verb) +HELM_DIFF_SUBS = {"upgrade", "install", "revision", "rollback", "release", "version"} + + +def helm_secrets(args, an): + # every helm-secrets mode but encrypt decrypts, or deploys decrypted values + _, verb = first_positional(args, set()) + if verb in ("encrypt", "enc", "help", "version") or wants_help(args): + return OK + return deny("'helm secrets %s' decrypts secrets; agents never decrypt them. Only " + "'helm secrets encrypt' is allowed." % (verb or "")) + + +HELMFILE_GLOBAL = {"-f", "--file", "-e", "--environment", "-n", "--namespace", + "--kube-context", "-l", "--selector", "--state-values-set", + "--state-values-file", "-b", "--helm-binary", "--log-level", + "--chart", "-c"} +HELMFILE_READ = {"template", "lint", "build", "list", "deps", "repos", "version", + "help", "write-values", "show-dag", "completion"} + + +def helmfile(args, an): + idx, verb = first_positional(args, HELMFILE_GLOBAL) + if verb is None or wants_help(args) or verb in HELMFILE_READ: + return OK + return deny("'helmfile %s' is not on the allowlist of subcommands that change " + "no release and print no secret. Releases change only by approved " + "merge." % verb) + + TOFU_READ = {"init", "validate", "fmt", "plan", "providers", "version", "graph", "get", "metadata", "modules", "help"} -def tofu(args, an=None): +def tofu(args, an): # -chdir=DIR and other leading -flags are single words idx, verb = first_positional(args, set()) if verb is None or wants_help(args): return OK rest = args[idx + 1:] - if verb == "run-all": # terragrunt + if verb in ("run-all", "run"): # terragrunt: run-all , run [--all] return tofu(rest, an) + if verb == "init" and _flag(rest, "migrate-state", "force-copy"): + return deny("'tofu init -migrate-state/-force-copy' moves state between " + "backends.") if verb in TOFU_READ: return OK if verb == "workspace": @@ -902,11 +1486,11 @@ def tofu(args, an=None): return OK return deny("'tofu workspace %s' changes state." % sub) if verb == "output": - if any(a.lstrip("-").split("=")[0] in ("json", "raw") for a in rest): + if _flag(rest, "json", "raw"): return deny("'tofu output -json/-raw' prints sensitive outputs in clear.") return OK if verb == "show": - if any(a.lstrip("-").split("=")[0] == "json" for a in rest): + if _flag(rest, "json"): return deny("'tofu show -json' prints sensitive values in clear.") files = [a for a in rest if not a.startswith("-")] if not files: @@ -921,7 +1505,7 @@ def tofu(args, an=None): if verb == "destroy": return deny("'tofu destroy' is never run by an agent.") if verb == "apply": - if any(a.lstrip("-").split("=")[0] == "destroy" for a in rest): + if _flag(rest, "destroy"): return deny("'tofu apply -destroy' is a destroy; never run by an agent.") return ask("'tofu apply' changes real infrastructure.") if verb in ("import", "refresh", "test"): @@ -931,6 +1515,21 @@ def tofu(args, an=None): return deny("'tofu %s' is not in the guard's allowlist." % verb) +# terragrunt's own commands on top of tofu's; they only read or format HCL. +TERRAGRUNT_READ = {"hclfmt", "render-json", "render", "hclvalidate", + "validate-inputs", "graph-dependencies", "output-module-groups", + "info", "find", "list"} + + +def terragrunt(args, an): + idx, verb = first_positional(args, set()) + if verb in TERRAGRUNT_READ: + return OK + if verb == "hcl" and args[idx + 1:idx + 2] in (["fmt"], ["validate"], ["format"]): + return OK + return tofu(args, an) + + ANSIBLE_READ_FLAGS = {"--check", "--syntax-check", "--list-tasks", "--list-hosts", "--list-tags", "--version", "--help", "-h"} ANSIBLE_VALUE_SHORT = set("ieftuMlkKbcTPBmaJ") # options whose value may follow @@ -951,36 +1550,36 @@ def _ansible_check_mode(args): return False -def ansible_playbook(args, an=None): +def ansible_playbook(args, an): if _ansible_check_mode(args): return OK return ask("'ansible-playbook' without --check changes real hosts.") -def ansible_adhoc(args, an=None): +def ansible_adhoc(args, an): if _ansible_check_mode(args) or not args: return OK return ask("ad-hoc 'ansible' without --check runs modules on real hosts.") -def ansible_pull(args, an=None): +def ansible_pull(args, an): if _ansible_check_mode(args): return OK return ask("'ansible-pull' without --check changes real hosts.") -def ansible_console(args, an=None): +def ansible_console(args, an): return ask("'ansible-console' runs modules on real hosts.") -def ansible_vault(args, an=None): - idx, verb = first_positional(args, {"--vault-id", "--vault-password-file"}) +def ansible_vault(args, an): + _, verb = first_positional(args, {"--vault-id", "--vault-password-file"}) if verb in ("view", "decrypt", "edit", "rekey"): return deny("'ansible-vault %s' decrypts vaulted secrets; agents never do." % verb) return OK -def kubeseal(args, an=None): +def kubeseal(args, an): for a in args: if a.split("=", 1)[0] in ("--recovery-unseal", "--recovery-private-key"): return deny("kubeseal recovery decrypts Sealed Secrets; agents never do.") @@ -991,7 +1590,7 @@ SOPS_SAFE = {"-e", "--encrypt", "encrypt", "updatekeys", "filestatus", "--version", "-v", "--help", "-h", "help", "keyservice"} -def sops(args, an=None): +def sops(args, an): # A bare `sops ` opens it decrypted in $EDITOR, so only the # encrypting and metadata modes are allowed. if any(a in SOPS_SAFE for a in args): @@ -1001,6 +1600,13 @@ def sops(args, an=None): "'sops --encrypt', 'updatekeys' and 'filestatus' are allowed.") +def gpg(args, an): + # gpg takes any unambiguous prefix of a long option + if any(a.startswith("--export-secret") for a in args): + return deny("'gpg --export-secret-keys' prints private keys.") + return OK + + FLUX_GLOBAL = {"-n", "--namespace", "--context", "--kubeconfig", "--timeout", "--cluster", "--user", "--token", "--as", "--as-group", "--server", "-s", "--certificate-authority", "--client-certificate", "--client-key"} @@ -1008,17 +1614,18 @@ FLUX_READ = {"get", "logs", "events", "tree", "trace", "stats", "check", "version", "build", "completion", "help", "debug", "envsubst"} -def flux(args, an=None): +def flux(args, an): idx, verb = first_positional(args, FLUX_GLOBAL) if verb is None or wants_help(args): return OK rest = args[idx + 1:] - if verb == "debug" and any(a.split("=", 1)[0] == "--show-values" for a in rest): - return deny("'flux debug --show-values' can print values pulled from Secrets.") + if verb == "debug" and _flag(rest, "show-values", "show-vars"): + return deny("'flux debug --show-values/--show-vars' can print values pulled " + "from Secrets.") if verb in FLUX_READ: return OK if verb == "export": - if any(a.split("=", 1)[0] == "--with-credentials" for a in rest): + if _flag(rest, "with-credentials"): return deny("'flux export --with-credentials' prints source credentials.") return OK if verb in ("create", "install") and "--export" in rest: @@ -1034,7 +1641,17 @@ def flux(args, an=None): GIT_GLOBAL = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env", "--super-prefix"} -GIT_COMMIT_VALUE_SHORT = set("mFcCt") +# Subcommands that take a message with -m, and the short options whose value +# is the next word when they end a cluster (`-am msg`). +GIT_MESSAGE_SUBS = {"commit", "tag", "merge", "notes", "stash", "revert"} +GIT_VALUE_SHORT = {"commit": "mFcCt", "tag": "mFu", "merge": "mFsX", + "notes": "mFcC", "stash": "m", "revert": "mX", + "log": "SGn", "show": "SG", "whatchanged": "SG", + "rev-list": "SGn", "diff": "SG"} +GIT_VALUE_LONG = {"--message", "--file", "--reuse-message", "--reedit-message", + "--template", "--author", "--date", "--cleanup", "--fixup", + "--squash", "--trailer", "--grep", "--format", "--pretty", + "--committer"} def _git_sub_index(args): @@ -1051,6 +1668,37 @@ def _git_sub_index(args): return None +def _git_value_indexes(sub, rest): + """Indexes of option values in a git subcommand's arguments.""" + letters = GIT_VALUE_SHORT.get(sub, "") + skip = set() + for j, a in enumerate(rest): + if j in skip: + continue + if a in GIT_VALUE_LONG: + skip.add(j + 1) + elif a.startswith("-") and not a.startswith("--"): + for pos, ch in enumerate(a[1:]): + if ch in letters: + if pos == len(a) - 2: + skip.add(j + 1) + break + return skip + + +def _git_message_indexes(rest): + """Indexes of the words that are a -m / --message value.""" + found = set() + for j, a in enumerate(rest): + if a in ("-m", "--message"): + found.add(j + 1) + elif a.startswith("--message="): + found.add(j) + elif a.startswith("-") and not a.startswith("--") and "m" in a: + found.add(j + 1 if a.endswith("m") and a.index("m") == len(a) - 1 else j) + return found + + def _git_config_value(value, an): low = value.lower() if "hookspath" in low: @@ -1058,14 +1706,18 @@ def _git_config_value(value, an): if "no-verif" in low: return deny("A git alias carrying --no-verify skips the repo's git hooks; " + HOOK_BYPASS) - if "=" in value: - key, val = value.split("=", 1) - if key.lower().startswith("alias.") and val.startswith("!") and an: - return an.text(val[1:]) + key, _, val = value.partition("=") + key = key.lower() + if key == "core.sshcommand": + return an.text(val) + if key.startswith("alias.") and val.startswith("!"): + return an.text(val[1:]) + if is_secret_path(val): + return deny("'%s' is secret material; agents never read it." % val) return OK -def git(args, an=None): +def git(args, an): verdict = OK idx = 0 while idx < len(args): @@ -1089,62 +1741,59 @@ def git(args, an=None): return verdict sub = args[idx] rest = args[idx + 1:] + values = _git_value_indexes(sub, rest) + opts = [a for j, a in enumerate(rest) if j not in values] # git accepts any unambiguous prefix of a long option: --no-verif, --no-ve… - if sub != "grep" and any(len(a) >= 6 and "--no-verify".startswith(a) for a in rest): + if sub != "grep" and any(len(a) >= 6 and "--no-verify".startswith(a) for a in opts): return deny("'--no-verify' skips the repo's git hooks; " + HOOK_BYPASS) if sub == "config": + setting = not any(x in ("--get", "--get-all", "-l", "--list", "--unset", + "--unset-all", "get", "list", "unset") for x in rest) for j, a in enumerate(rest): - if a.lower() == "core.hookspath" and j + 1 < len(rest) and \ - not any(x in ("--get", "--get-all", "-l", "--list", "--unset", - "--unset-all") for x in rest): + key = a.lower() + if j + 1 >= len(rest) or not setting: + break + if key == "core.hookspath": return deny("Setting core.hooksPath skips the repo's git hooks; " + HOOK_BYPASS) - if sub == "rebase" and an: + if key.startswith("alias.") or key == "core.sshcommand": + verdict = verdict.merge(_git_config_value(a + "=" + rest[j + 1], an)) + if sub == "rebase": for j, a in enumerate(rest): if a in ("-x", "--exec") and j + 1 < len(rest): verdict = verdict.merge(an.text(rest[j + 1])) elif a.startswith("--exec="): verdict = verdict.merge(an.text(a.split("=", 1)[1])) - if sub == "bisect" and an and rest[:1] == ["run"]: - verdict = verdict.merge(an.program([(w, False) for w in rest[1:]], " ".join(rest))) - if sub == "submodule" and an and "foreach" in rest: + if sub == "bisect" and rest[:1] == ["run"]: + verdict = verdict.merge(an.program(rest[1:], Ctx())) + if sub == "submodule" and "foreach" in rest: cmd = [w for w in rest[rest.index("foreach") + 1:] if not w.startswith("--")] verdict = verdict.merge(an.text(" ".join(cmd))) if sub == "commit": - skip = False - for a in rest: - if skip: - skip = False + for j, a in enumerate(rest): + if j in values or not a.startswith("-") or a.startswith("--"): continue - if a in ("--message", "--file", "--reuse-message", "--reedit-message", - "--template", "--author", "--date", "--cleanup", "--fixup", - "--squash", "--trailer"): - skip = True - continue - if a.startswith("-") and not a.startswith("--") and len(a) > 1: - letters = a[1:] - for pos, ch in enumerate(letters): - if ch == "n": - return deny("'git commit -n' is --no-verify; it skips the " - "repo's git hooks.") - if ch in GIT_COMMIT_VALUE_SHORT: - if pos == len(letters) - 1: - skip = True - break + for ch in a[1:]: + if ch == "n": + return deny("'git commit -n' is --no-verify; it skips the " + "repo's git hooks.") + if ch in GIT_VALUE_SHORT["commit"]: + break return verdict -def pre_commit(args, an=None): - idx, verb = first_positional(args, {"-c", "--config"}) +def pre_commit(args, an): + _, verb = first_positional(args, {"-c", "--config"}) if verb == "uninstall": return deny("'pre-commit uninstall' turns the repo's gates off; " + HOOK_BYPASS) return OK RULES = { - "kubectl": kubectl, "kubectl.exe": kubectl, "kubecolor": kubectl, + "kubectl": kubectl, "kubecolor": kubectl, "microk8s.kubectl": kubectl, "helm": helm, "helm3": helm, - "tofu": tofu, "terraform": tofu, "terragrunt": tofu, + "helmfile": helmfile, "helm-secrets": helm_secrets, + "tofu": tofu, "terraform": tofu, "terragrunt": terragrunt, "ansible-playbook": ansible_playbook, "ansible": ansible_adhoc, "ansible-pull": ansible_pull, @@ -1152,6 +1801,7 @@ RULES = { "ansible-vault": ansible_vault, "kubeseal": kubeseal, "sops": sops, + "gpg": gpg, "gpg2": gpg, "flux": flux, "git": git, "pre-commit": pre_commit, @@ -1162,30 +1812,50 @@ RULES = { # -------------------------------------------------------------------------- SHELL_TOOLS = {"bash", "shell", "powershell", "local_shell", "exec_command", - "unified_exec", "run_shell_command", "container.exec", "monitor"} + "unified_exec", "run_shell_command", "container.exec", "monitor", + "write_stdin", "write_bash"} +PS_TOOLS = {"powershell"} +COMMAND_KEYS = ("command", "cmd", "input", "chars") PATH_KEYS = ("file_path", "path", "notebook_path", "filePath", "absolute_path") +WRITE_TOOLS = {"write", "edit", "multiedit", "notebookedit", "create", + "str_replace", "str_replace_editor", "insert"} +PATCH_TARGET = re.compile(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$", re.M) def analyse_tool(tool, tool_input): + if not isinstance(tool, str) or not tool: + raise ValueError("no tool name") + lname = tool.lower() + if lname in SHELL_TOOLS: + if not isinstance(tool_input, dict): + raise ValueError("tool input is not an object") + cmd = next((tool_input[k] for k in COMMAND_KEYS if k in tool_input), None) + if isinstance(cmd, list) and cmd and all(isinstance(c, str) for c in cmd): + cmd = " ".join(_quote(c) for c in cmd) + if not isinstance(cmd, str): + raise ValueError("no command string") + return Analyzer().text(cmd, ps=lname in PS_TOOLS) if not isinstance(tool_input, dict): tool_input = {} - lname = (tool or "").lower() - if lname in SHELL_TOOLS: - cmd = tool_input.get("command", "") - if isinstance(cmd, list): - cmd = " ".join(_quote(c) for c in cmd) - return Analyzer().text(str(cmd)) if lname == "apply_patch": cmd = str(tool_input.get("command", "") or tool_input.get("input", "")) - for m in re.finditer(r"^\*\*\* (?:Add|Update|Delete) File: (.+)$", cmd, re.M): - if is_secret_path(m.group(1).strip()): - return deny("'%s' is secret material; agents never touch it." % m.group(1).strip()) + for m in PATCH_TARGET.finditer(cmd): + path = m.group(1).strip() + if is_secret_path(path): + return deny("'%s' is secret material; agents never touch it." % path) + if is_hooks_path(path): + return deny("Changing '%s' changes the repo's git hooks; %s" + % (path, HOOK_BYPASS)) return OK for key in PATH_KEYS: val = tool_input.get(key) - if isinstance(val, str) and is_secret_path(val): + if not isinstance(val, str): + continue + if is_secret_path(val): return deny("'%s' is secret material (vault password, private key, " "admin kubeconfig or tofu state); agents never read it." % val) + if lname in WRITE_TOOLS and is_hooks_path(val): + return deny("Changing '%s' changes the repo's git hooks; %s" % (val, HOOK_BYPASS)) for key in ("glob", "include"): val = tool_input.get(key) if isinstance(val, str) and is_secret_path(val): @@ -1194,13 +1864,12 @@ def analyse_tool(tool, tool_input): def _quote(s): - s = str(s) if re.match(r"^[A-Za-z0-9_./=:@%+,-]+$", s): return s return "'" + s.replace("'", "'\\''") + "'" -def detect_runtime(payload=None): +def detect_runtime(): here = os.path.abspath(__file__).replace("\\", "/") if "/.claude/hooks/" in here: return "claude" @@ -1208,24 +1877,21 @@ def detect_runtime(payload=None): return "copilot" if "/.codex/hooks/" in here: return "codex" - if isinstance(payload, dict) and "toolName" in payload: - return "copilot" return "unknown" -def read_payload(raw): - payload = json.loads(raw) if raw.strip() else {} - if not isinstance(payload, dict): - raise ValueError("payload is not an object") +def read_payload(payload): + """(tool name, tool input) from either payload shape.""" if "toolName" in payload: - tool = payload.get("toolName") args = payload.get("toolArgs") if isinstance(args, str): try: args = json.loads(args) except ValueError: args = {"command": args} - return tool, args + if args is not None and not isinstance(args, dict): + raise ValueError("toolArgs is not an object") + return payload.get("toolName"), args return payload.get("tool_name"), payload.get("tool_input") @@ -1243,7 +1909,7 @@ def emit(runtime, event, verdict): return 0 if runtime == "claude": print(json.dumps({"hookSpecificOutput": { - "hookEventName": event or "PreToolUse", + "hookEventName": event, "permissionDecision": decision, "permissionDecisionReason": verdict.reason}})) return 0 @@ -1254,16 +1920,15 @@ def emit(runtime, event, verdict): def main(): - raw = sys.stdin.read() runtime = detect_runtime() event = "PreToolUse" try: - payload = json.loads(raw) if raw.strip() else {} - if isinstance(payload, dict): - runtime = detect_runtime(payload) - event = payload.get("hook_event_name") or event - tool, tool_input = read_payload(raw) - verdict = analyse_tool(tool, tool_input) + payload = json.loads(sys.stdin.read()) + if not isinstance(payload, dict): + raise ValueError("payload is not an object") + if isinstance(payload.get("hook_event_name"), str): + event = payload["hook_event_name"] + verdict = analyse_tool(*read_payload(payload)) except Exception as exc: # fail closed verdict = Verdict(DENY, "delivery guard: could not read the tool call (%s); " "denying to stay safe." % exc.__class__.__name__) @@ -1271,5 +1936,4 @@ def main(): if __name__ == "__main__": - sys.dont_write_bytecode = True sys.exit(main()) diff --git a/plugins/delivery/apm.yml b/plugins/delivery/apm.yml index 929a347..d045e4a 100644 --- a/plugins/delivery/apm.yml +++ b/plugins/delivery/apm.yml @@ -1,5 +1,5 @@ name: delivery -version: 0.1.0 +version: 0.2.0 description: Agents and skills for taking a change from spec to a verified merge through tracker-gated stages. author: name: Mortis diff --git a/plugins/delivery/docs/guard-hook.md b/plugins/delivery/docs/guard-hook.md index 4c65148..6fb3b64 100644 --- a/plugins/delivery/docs/guard-hook.md +++ b/plugins/delivery/docs/guard-hook.md @@ -8,65 +8,127 @@ in the `delivery guard hook` ticket (holocron#190) and ADR-0032's 2026-11-23 ame | Tier | Examples | Claude Code | Copilot CLI | Codex / unknown | |---|---|---|---|---| -| Never | `kubectl`/`kubecolor` verbs outside the read allowlist, `helm`/`helm3` install/upgrade/uninstall/rollback, `helm get values/manifest/all`, `flux suspend/delete/…`, `flux debug --show-values`, `tofu`/`terraform`/`terragrunt destroy`, `tofu apply -destroy`, `tofu state` (except `list`), `tofu show` without a plan file or with `-json`, `tofu output -json/-raw`, `git … --no-verify` (and its abbreviations), `git commit -n`, `SKIP=`/`SKIP+=`, `core.hooksPath` overrides (`-c`, `--config-env`, `GIT_CONFIG_*`, `git config`), git aliases carrying `--no-verify`, `pre-commit uninstall`, `ansible-vault view/decrypt/edit/rekey`, `kubeseal --recovery-*`, `sops` in any decrypting mode (including bare `sops `), `kubectl get secret -o …`/`--template`, `kubectl get --raw …secrets…`, `kubectl config view --raw`, any mention of a secret path | deny | deny | deny | +| Never | `kubectl`/`kubecolor` subcommands outside the allowlist, `helm`/`helm3` install/upgrade/uninstall/rollback, `helm get values/manifest/hooks/all`, `helm diff --show-secrets`, `helm secrets` and `helm-secrets` except `encrypt`, `helmfile` subcommands outside the allowlist, `flux suspend/delete/…`, `flux debug --show-values/--show-vars`, `tofu`/`terraform`/`terragrunt destroy`, `tofu apply -destroy`, `tofu init -migrate-state/-force-copy`, `tofu state` (except `list`), `tofu show` without a plan file or with `-json`, `tofu output -json/-raw`, `git … --no-verify` (and its abbreviations), `git commit -n`, `SKIP=`/`SKIP+=`, `HUSKY=0`, `LEFTHOOK=0`, `core.hooksPath` overrides (`-c`, `--config-env`, `GIT_CONFIG_*`, `git config`), git aliases carrying `--no-verify` or a guarded `!` command (`-c alias.…` or `git config alias.…`), `pre-commit uninstall`, writing, moving, removing or `chmod`-ing anything under `.git/hooks/`, `ansible-vault view/decrypt/edit/rekey`, `kubeseal --recovery-*`, `sops` in any decrypting mode (including bare `sops `), `gpg --export-secret-keys/-subkeys`, `kubectl get secret -o …`/`--template`, `kubectl get -k … -o …`, `kubectl get -f -o …`, `kubectl get --raw …secrets…`, `kubectl config view --raw`, any mention of a secret path | deny | deny | deny | | Odd job | `ansible-playbook` / ad-hoc `ansible` / `ansible-pull` without `--check`, `ansible-console`, `tofu apply/import/refresh/test`, `flux reconcile` | ask | ask | deny | | Read / Propose | everything else | allow | allow | allow | -`kubectl`, `helm`, `flux` and `tofu` are **allowlists**: a subcommand the guard does not list as +`kubectl`, `helm`, `helmfile`, `flux` and `tofu` are **allowlists**: a subcommand the guard does not list as allowed is denied. Widen the allowlist in `guard.py` and its test table together. The allowed sets are "no cluster or state change and no secret printed", not strictly read-only. `helm pull`, -`package`, `create` and `repo add/update`, `tofu init`, `plan` and `get`, `kubectl wait`, and +`package`, `create` and `repo add/update`, `tofu init`, `plan` and `get`, `helm diff upgrade/install/revision/rollback` (the read-only helm-diff plugin), `kubectl wait`, and `kubectl create … --dry-run=client` (which renders a Secret to pipe into `kubeseal`) all write local -files or caches. `--help` is always allowed. +files or caches. When `--dry-run` is given twice, the last one counts. `helmfile` allows `template`, +`lint`, `build`, `list`, `deps`, `repos`, `version`, `help`, `write-values` and `show-dag`. +`terragrunt` follows the `tofu` rule and also allows its own HCL commands: `hclfmt`, `hcl fmt`, +`hcl validate`, `render-json` and `render`. `--help` is always allowed. Secret paths are basename globs: `.vault_pass*`, `vault_pass*`, `*vault_password*` (and the `-` -spellings), `*.tfstate`, `*.tfstate.*`, `id_rsa`/`id_ed25519`/`id_ecdsa`/`id_dsa`, `*.key`, -`key.pem`, `*-key.pem`, `*_key.pem`, `privkey*.pem`, `*private*.pem`, `*.p12` and `*.pfx`. Also -covered: anything under `.kube/config` (backups included) and the `.kube` directory itself. A shell -glob with at least three literal characters (`.vault_pa*`) counts if it could expand to one of -these. +spellings), `*deploy_key*`, `*.tfstate`, `*.tfstate.*`, `id_rsa*`/`id_ed25519*`/`id_ecdsa*`/`id_dsa*`, +`*.key`, `key.pem`, `*-key.pem`, `*_key.pem`, `privkey*.pem`, `*private*.pem`, `*.p12`, `*.pfx` and +`.git-credentials*`. The undotted vault-password names and `*deploy_key*` also fit source and docs +about them, so a doc or data suffix (`.yml`, `.yaml`, `.md`, `.rst`, `.j2`, `.adoc`, `.html`) +exempts them. A code suffix (`.py`, `.sh`, …) exempts only a test file: `test_vault_password.py` +is fine, but `vault_pass.py` and `vault-pass.sh` are the usual names of an Ansible vault-password +script, which prints the password when run. `vault_password` and `.vault_pass.yml` are not exempt. git's `REV:path` form is checked by its path (`git show HEAD:.vault_pass`). Also covered: +- the admin kubeconfig `.kube/config` and its backups (`config.*`, `config~`). Other kubeconfigs in + `.kube`, such as `.kube/configs/stage-ro.yaml`, are fine. +- the `.kube` and `.ssh` directories as a whole, and any glob inside them (`~/.ssh/id*`, + `~/.kube/*`) +- `sops/age/keys.txt`, `/etc/rancher/k3s/k3s.yaml` and `/etc/kubernetes/admin.conf` + +Any other shell glob with at least three literal characters (`.vault_pa*`) counts if it could +expand to a secret name. Redirect targets are checked the same way for every program, so +`echo x > terraform.tfstate` and `grep < ~/.ssh/id_rsa .` are denied. + +An option name is never a path: only its `=value` is checked. So `--vault-password-file` itself +does not count, and `ansible-vault encrypt --vault-password-file ~/placeholder vars.yml` (the +placeholder-password stage workflow) is allowed, while `--vault-password-file .vault_pass` is not. Exemptions: - `.pub` files. -- The values of `--vault-password-file`, `--vault-id`, `--private-key` and `--key-file`. Ansible - reads those itself, and that run is already an Odd job. -- `ssh -i`, for the same reason. +- The values of `--vault-password-file`, `--vault-id`, `--private-key` and `--key-file`, for + `ansible-playbook`, `ansible` and `ansible-pull` only. Ansible reads those itself, and that run is + already an Odd job. Elsewhere, `ansible-inventory` and `ansible-vault` included, the value is + checked like any path. +- SSH keys handed to ssh: `ssh -i`, `scp -i`, `sftp -i`, `ssh-add`, and the command in + `GIT_SSH_COMMAND` or `core.sshCommand`, which the guard reads as a command. - The search pattern of `grep`/`rg`/`ag`/`ack`/`git grep`, wherever the program sits after unwrapping (so `rtk grep vault_pass ansible.cfg` is allowed). The exemption doesn't apply once `-e` or `-f` makes the pattern explicit. -- Programs that only print or stat their arguments: `echo`, `printf`, `ls`, `stat`, `test`. +- The filter of `jq`, `gojq` and `yq` (`jq -r '.tls.key' x.json`), unless `-f` reads it from a + file. The files they read are still checked. +- The `-k`/`-m` test selector of `pytest` and `python -m pytest`. +- File-name patterns: the values of `--include`, `--exclude`, `--exclude-dir`, `--glob`/`-g` and + `--iglob` for the search tools, and of `find -name`/`-iname`/`-path`/`-ipath`/`-regex`. A + directory `find` searches is still checked, so `find ~/.ssh -name id_rsa` is denied. A `find` + that deletes or runs something (`-delete`, `-exec`, `-execdir`, `-ok`) loses this exemption, so + `find . -name '*.tfstate' -delete` is denied, and so is any such `find` naming `.git/hooks`. +- Prose: the `-m`/`--message` value of `git commit`, `tag`, `merge`, `notes`, `stash` and + `revert`, and the title, body and notes values of `gh` and `tea`. `git commit -m x --no-verify` + is still denied: only the secret-path check skips the message. The search values of + `git log -S`/`-G`/`--grep` are skipped by the `--no-verify` check. +- Programs that only print or stat their arguments: `echo`, `printf`, `ls`, `stat`, `test`. Their + redirect targets are still checked. - `git rm`, `check-ignore`, `ls-files` and `status`. Pointing at the admin `~/.kube/config` is denied on purpose: stage sessions use the read-only kubeconfig. File tools are checked too: Read, Grep, Edit and Write paths, Copilot's `view`, and -Codex's `apply_patch` targets. +Codex's `apply_patch` targets, including `Move to`. Write and Edit under `.git/hooks/` are denied; +reading there is fine. ## How it reads a command The script tokenises the shell line itself. It handles: -- quoting and escapes, including backslash-newline -- `;`, `&&`, `||`, `|`, newlines, subshells and braces -- here-documents, whose bodies are treated as data, not commands, so commit messages and PR bodies - may name any command +- quoting and escapes, including backslash-newline and `$'…'` with escaped quotes +- `;`, `&&`, `||`, `|`, newlines, subshells, braces, `function NAME { … }` and `((…))` +- redirections, which never become words of the command. The fd number in `2>&1` is dropped, and + the target is checked for secret paths and `.git/hooks/`. +- here-documents. A body is data, so commit messages and PR bodies may name any command. Two + exceptions: an unquoted delimiter's body (`<(…)` as further commands. It also -unwraps: -- shells: `bash`/`sh`/… `-c` (including clusters such as `-lc` and `-o opt -c`), here-strings, and - a shell reading stdin, which is denied when the line mentions a guarded tool -- `eval`, and leading `NAME=value` / `NAME+=value` assignments +It parses the body of `$(…)`, `<(…)` and `>(…)` with the same rules as the rest of the line, so a +quote or bracket in a here-document inside `$(…)` cannot hide what follows. Backtick bodies are +parsed too. It also unwraps: +- shells: `bash`/`sh`/… `-c` (including clusters such as `-lc`, `-o opt -c` and + `-euo pipefail -c`), here-strings, + here-documents, and a shell reading a pipe, which is denied when the line mentions a guarded tool. + `bash <(…)`, `source <(…)`, `. <(…)` and a `-c` string holding a `$(…)` are built at run time, + so they are denied when the line mentions a guarded tool. +- `eval` (the same run-time rule), `trap 'cmd' SIG`, and leading `NAME=value` / `NAME+=value` + assignments - `env` (including `-S`), `sudo`, `doas`, `su -c`, `script -c`, `flock`, `strace`, `systemd-run`, - `busybox` + `chroot`, `busybox`, `k3s`, `microk8s` - `nohup`, `setsid`, `time`, `command` and `exec` (by basename, with their options) - `timeout`, `nice`, `xargs`, `parallel`, `watch`, `find -exec`, `ssh host ` +- `nix-shell --run`, `nix shell/develop -c`, `tmux new-session/new-window/split-window` - git's own shell-outs: `rebase --exec`, `bisect run`, `submodule foreach` and `!` aliases - `rtk` (`rtk `, `rtk run`, `rtk proxy`) - project runners: `uv`/`poetry`/`pipenv`/`pdm`/`hatch`/`pipx run`, `uv tool run`, `uvx`, - `direnv exec`, `mise exec`, `devbox run` + `direnv exec`, `mise exec`, `devbox run`, and secret injectors `aws-vault exec`, `op run` and + `doppler run` -It takes the program's basename, so `/usr/bin/kubectl` and `\kubectl` are both `kubectl`. It -denies, rather than guesses, when a program name is built at run time (`$k apply`) and the line -mentions a guarded tool, when the program name is a glob, or when brace expansion hides a guarded -command. +In an option cluster, a last letter that takes a value consumes the next word, for shells and for +every wrapper: `sudo -iu root kubectl …` runs `kubectl`, not `root`. + +It takes the program's basename and drops a `.exe` suffix, so `/usr/bin/kubectl`, `\kubectl` and +`kubectl.exe` are all `kubectl`. It denies, rather than guesses, when a program name is built at run +time (`$k apply`) and the line mentions a guarded tool, when the program name is a glob, or when an +unquoted brace expansion hides a guarded command. A guarded tool counts only as a whole name, so +`.pre-commit-config.yaml` is not `pre-commit`. + +The PowerShell tool gets a PowerShell mode of the same tokenizer, not a full PowerShell parser. The +backtick is the escape and line-continuation character, backslash is a plain path separator, `''` +escapes a single quote, and `@'…'@` here-strings are read. Program names are matched without case. +It unwraps `iex`/`Invoke-Expression`, `cmd /c` and `pwsh`/`powershell -Command`, and denies +`-EncodedCommand`. + +Copilot lets a timed-out hook's call through, so the guard refuses input it cannot read well inside +the 10-second budget. It denies outright a command longer than 256 KB, a simple command of more than +2,000 words, a line of more than 5,000 commands, substitutions nested more than 40 deep, and more +than 32 wrappers inside one another (`sudo sudo …`, `find -exec find -exec …`). Each of these +finishes well under a second. **Known gaps, by construction:** - a script the agent writes and then runs @@ -74,6 +136,9 @@ command. - MCP tools, which carry no shell command - secret files at an unusual path - `cd ~/.kube && cat config`, because the guard does not track the working directory +- file names produced at run time, such as `ls ~/.ssh/id_* | xargs cat`: `xargs` reads its + arguments from the pipe, which the guard cannot see +- a shell reading a pipe when the line mentions no guarded tool, such as `curl … | bash` - what an allowed command prints at run time, such as `ansible -C -m debug` of a vaulted variable The credential boundary covers all of these: the read-only kubeconfig, no vault password and no @@ -88,7 +153,7 @@ The script tells runtimes apart by where apm deployed it: | `.claude/hooks/` | Claude Code | Output is `hookSpecificOutput.permissionDecision`. `onFailure: block` makes a crash or timeout block the call (Claude Code ≥ 2.1.295). Verified live on 2.1.326. | | `.github/hooks/scripts/` | Copilot CLI | Output is top-level `permissionDecision` plus a reason. A non-zero exit denies, but a **timeout lets the call through**. The TUI auto-approves `ask` (ADR-0032 accepted risk). apm writes the entry in Claude's nested shape with `command`/`timeout`, and Copilot's docs accept both keys but don't document the nested group, so it is **unverified** until a Copilot account exists. | | `.codex/hooks/` | Codex | `ask` is unsupported, so the guard denies with exit 2 and the reason on stderr. apm deploys only if `.codex/` already exists, and Codex skips project hooks until a human trusts them. Codex resolves the relative command from the session cwd, so a session started in a subdirectory may not find the script. | -| anywhere else | unknown | Treated like Codex. | +| anywhere else | unknown | Treated like Codex: odd jobs are denied, with exit 2. The payload's shape (`toolName` or `tool_name`) picks only how the payload is read, never the runtime. | ## What a consuming repo needs @@ -116,5 +181,8 @@ The script tells runtimes apart by where apm deployed it: `tests/test-delivery-guard-hook.sh` copies the script to each runtime's deploy path and drives it with Claude, Copilot and Codex payloads. It covers the deny, ask and allow tables, bypass attempts (quoting, `bash -c`, `env`, `sudo`, `xargs`, `find -exec`, substitution, `eval`, dynamic program -names), the per-runtime output shape, fail-closed handling of malformed payloads, and the -`hooks.json` invariants. +names), PowerShell, the per-runtime output shape, and fail-closed handling of malformed payloads. +A malformed payload is denied: not JSON or not an object, no tool name, a shell tool whose input is +not an object or carries no command string (read from `command`, `cmd`, `input` or `chars`), and +Copilot `toolArgs` that is not an object. It also covers the time the guard takes on pathological +input and the `hooks.json` invariants. diff --git a/tests/test-delivery-guard-hook.sh b/tests/test-delivery-guard-hook.sh index e909310..579db6d 100755 --- a/tests/test-delivery-guard-hook.sh +++ b/tests/test-delivery-guard-hook.sh @@ -322,6 +322,215 @@ allow flux debug hr app # --- Kept on purpose: the admin kubeconfig is not the stage session's deny export KUBECONFIG=~/.kube/config deny kubectl --kubeconfig ~/.kube/config get pods +# --- Second review: ANSI-C quoting with an escaped quote +deny echo $'don\'t' && git push --no-verify +deny git commit -m $'fix: don\'t\n\nbody' && kubectl delete ns prod +# --- Second review: redirect operands are not words, but are checked +deny tofu show -no-color 2>&1 +deny tofu show > /tmp/state.txt +deny /dev/null git push --no-verify +deny exec 2>&1 kubectl delete ns prod +deny echo x > terraform.tfstate +deny : > ~/.kube/config +deny grep < ~/.ssh/id_rsa . +deny printf '%s' "$(<.vault_pass)" +deny while read l; do :; done < .vault_pass +allow kubectl get pods 2>&1 | tee /tmp/pods.txt +allow echo ok > /tmp/out.txt +# --- Second review: globs and whole directories under .ssh and .kube +deny cat ~/.ssh/id* +deny cat ~/.ssh/* +deny cat ~/.kube/* +deny head ~/.kube/c* +deny tar czf /tmp/k.tgz ~/.ssh +deny grep -r '' ~/.ssh +deny find ~/.ssh -name id_rsa -exec cat {} \; +allow ls -la ~/.ssh ~/.kube +allow cat ~/.ssh/known_hosts +# --- Second review: key names with suffixes +deny cat ~/.ssh/id_ed25519_work +deny cat ~/.ssh/id_rsa.bak +deny cat ~/.ssh/id_ecdsa_old +allow cat ~/.ssh/id_ed25519_work.pub +# --- Second review: more secret material +deny flux debug kustomization apps --show-vars +deny cat ~/.config/sops/age/keys.txt +deny cat /etc/rancher/k3s/k3s.yaml +deny cat /etc/kubernetes/admin.conf +deny cat ~/.git-credentials +deny gpg --export-secret-keys -a me +deny gpg --armor --export-secret-subkeys me +allow gpg --armor --export me +deny ansible-inventory -i inv --list --vault-password-file .vault_pass +deny grep -T vault_pass .vault_pass +# --- Second review: hook bypass through git config and .git/hooks +deny git config alias.c 'commit --no-verify' +deny git config --global alias.p 'push --no-verify' +deny git config alias.k '!kubectl delete ns prod' +allow git config alias.st status +deny rm -f .git/hooks/pre-commit +deny chmod -x .git/hooks/pre-push +deny mv .git/hooks/pre-commit /tmp/ +deny cp /tmp/noop .git/hooks/pre-commit +deny echo exit 0 > .git/hooks/pre-commit +allow ls .git/hooks +allow cat .git/hooks/pre-commit +# --- Second review: scripts built at run time +deny source <(echo kubectl delete pod a) +deny . <(echo kubectl delete pod a) +deny bash -c "$(echo kubectl delete pod a)" +deny eval "$(echo kubectl delete pod a)" +allow source .venv/bin/activate +# --- Second review: tokenizer and unwrapping +deny function f { kubectl delete ns prod; }; f +deny trap 'kubectl delete ns test' EXIT +deny parallel 'kubectl delete ns {}' ::: a b +deny nix-shell -p kubectl --run 'kubectl delete ns prod' +deny nix shell nixpkgs#kubectl -c kubectl delete ns prod +deny aws-vault exec prod -- kubectl delete ns prod +deny op run -- kubectl delete ns prod +deny op run -- cat ~/.kube/config +deny doppler run -- kubectl delete ns prod +deny chroot / kubectl delete ns prod +deny tmux new-session -d 'kubectl delete ns prod' +deny echo $(( $(kubectl delete ns x | wc -l) + 1 )) +deny case $x in a) kubectl delete ns x;; esac +deny k''ubectl delete ns x +deny $'\x6bubectl' delete ns x +# --- Second review: program names +deny k3s kubectl delete ns prod +deny microk8s kubectl delete ns prod +deny terraform.exe destroy +deny helm.exe uninstall x +deny git.exe commit --no-verify -m x +allow helmfile template +allow helmfile -e prod lint +allow helmfile list +allow helmfile write-values +deny helmfile apply +deny helmfile -e prod destroy +deny helmfile sync +deny helmfile delete +deny helmfile diff +# --- Second review: allowlist holes +deny helm get hooks app +deny kubectl get -k overlays/prod -o yaml +allow kubectl get -k overlays/prod +deny tofu init -migrate-state +deny tofu init -force-copy +allow tofu init -upgrade +deny kubectl create secret generic x --from-literal=a=b --dry-run=client --dry-run=none -o yaml +# --- Second review: false denies on normal work +allow git commit -m "docs: never read ~/.kube/config" +allow git commit -m "chore: ignore *.tfstate" +allow git commit -m "fix: rotate tls.key" +allow git commit -am "fix: rotate tls.key" +allow gh pr create --title "Stop tracking *.tfstate" --body x +allow gh issue create --title "Guard misses id_rsa.bak" --body "see terraform.tfstate.backup handling" +deny git commit -m x --no-verify +deny git commit -F .vault_pass +deny git commit -S --no-verify -m x +allow find . -name '*.tfstate' +allow find . -name '*.pem' -newer x +allow rg --glob='!*.tfstate' password . +allow grep -rn token . --exclude='*.key' +allow git log --oneline -S '--no-verify' +allow git log --grep --no-verify +allow GIT_SSH_COMMAND='ssh -i ~/.ssh/id_ed25519' git push origin feat/x +deny GIT_SSH_COMMAND='cat ~/.ssh/id_rsa' git fetch +allow git -c core.sshCommand='ssh -i ~/.ssh/id_ed25519' fetch +allow scp -i ~/.ssh/id_ed25519 f host: +allow sftp -i ~/.ssh/id_ed25519 host +allow ssh-add ~/.ssh/id_ed25519 +allow kubectl --kubeconfig ~/.kube/configs/stage-ro.yaml get pods +allow KUBECONFIG=~/.kube/config-readonly kubectl get pods +deny cat ~/.kube/config~ +deny cat ~/.kube/config.prod +allow kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{","}{end}' +allow helm template . --set 'hosts={a,b}' +allow tofu plan -var 'tags={env="dev",team="x"}' +allow "$VENV/bin/python" -m yamllint .pre-commit-config.yaml +allow terragrunt run --all plan +deny terragrunt run --all destroy +# --- Other hook managers' skip switches +deny HUSKY=0 git commit -m x +deny LEFTHOOK=0 git commit -m x +# --- Third review: a short-option cluster ending in a value-taking letter +deny bash -euo pipefail -c 'kubectl delete ns prod' +deny bash -eo pipefail -c "cat ~/.ssh/id_rsa" +deny sh -euo pipefail -c 'git push --no-verify' +deny bash -xeuo pipefail -c 'helm uninstall app' +deny bash -ec 'kubectl delete ns prod' +allow bash -euo pipefail -c 'kubectl get pods' +deny sudo -iu root kubectl delete ns prod +deny sudo -Eu root kubectl delete ns prod +deny sudo -nu root kubectl delete ns prod +# --- Third review: jq/yq filters are not paths; the files they read are +allow jq -r '.metadata.key' x.json +allow jq '.data.key' cm.json +allow jq -r '.private.key' x.json +allow jq --arg k v '.tls.key' x.json +allow yq '.spec.tls.key' values.yaml +allow yq e '.tls.key' values.yaml +deny jq . terraform.tfstate +deny yq e '.a' ~/.kube/config +# --- Third review: option names are not paths +allow ansible-inventory -i inventory --graph --vault-password-file ./placeholder-pass +allow ansible-vault encrypt --vault-password-file ~/placeholder vars.yml +allow ansible-vault encrypt_string --vault-password-file /dev/null 'x' +deny ansible-vault encrypt --vault-password-file .vault_pass vars.yml +deny ansible-vault view --vault-password-file /dev/null vars.yml +# --- Third review: source and docs that merely mention the vault password +allow pytest -k vault_password tests/ +allow python3 -m pytest -k vault_password tests/ +allow pytest tests/test_vault_password.py -q +allow git add roles/common/tasks/vault_password.yml +allow git diff -- docs/vault-password-handling.md +allow pytest tests/vault_password_test.py +deny ./vault_pass.py +deny cat vault-pass.sh +deny bash scripts/vault_password.sh +deny ansible-inventory --list --vault-password-file vault_pass.py +deny cat vault_password +deny cat .vault_pass.yml +# --- Third review: find that deletes or runs something loses its pattern exemption +deny find .git/hooks -type f -delete +deny find .git/hooks -name pre-commit -delete +deny find . -path ./.git/hooks -prune -o -print -exec rm {} + +deny find . -name '*.tfstate' -delete +deny find . -name '*.tfstate' -exec rm {} + +allow find .git/hooks -type f +# --- Third review: kubectl get -f on a Secret manifest +deny kubectl get -f secret.yaml -o yaml +deny kubectl get -f manifests/db-secret.yaml -o json +allow kubectl get -f sealed-secret.yaml -o yaml +allow kubectl get -f deploy.yaml -o yaml +# --- Third review: policy widenings +allow terragrunt hclfmt +allow terragrunt hcl fmt --check +allow terragrunt render-json +deny tofu hclfmt +allow helm diff upgrade x charts/x +allow helm diff revision x 1 2 +deny helm diff upgrade x charts/x --show-secrets +# --- Third review: more secret reads +deny git show HEAD:.vault_pass +deny git cat-file -p HEAD:.vault_pass +allow git show HEAD:README.md +deny cat ./deploy_key +deny cat ~/.ssh/github_deploy_key +allow cat deploy_key.pub +deny helm secrets decrypt secrets.yaml +deny helm secrets view secrets.yaml +deny helm secrets edit secrets.yaml +deny helm-secrets decrypt secrets.yaml +allow helm secrets encrypt secrets.yaml +# --- By design, kept as they are +deny kubectl apply --dry-run=client -f deploy.yaml +deny kubectl config set-context --current --namespace=dev +deny cat .vault_pass.example +ask ansible all -m ping CASES # Multi-line commands do not survive the line-per-case table above; test them @@ -338,6 +547,47 @@ expect_claude allow $'cat > notes.md <<\'EOF\'\nhelm uninstall foo\nEOF' expect_claude allow $'cat <<-EOF > x\n\tkubectl delete pod x\n\tEOF\nls' # ...but the command after the here-doc is still checked. expect_claude deny $'cat > notes.md < notes.md < notes.md <<\'EOF\'\nresult: `kubectl delete ns prod` $(helm uninstall x)\nEOF' +# No here-doc inside arithmetic. +expect_claude deny $'(( y = 1 << 2 ))\nkubectl delete ns prod' +expect_claude deny $'echo $(( 1 << 2 ))\nkubectl delete ns prod' +# A here-doc fed to a shell or ssh is a script. +expect_claude deny $'ssh node1 <<\'EOF\'\nsudo kubectl delete ns prod\nEOF' +expect_claude deny $'bash - <<\'EOF\'\nkubectl delete ns prod\nEOF' +expect_claude deny $'sh -s <<\'EOF\'\nkubectl delete ns prod\nEOF' +expect_claude allow $'bash - <<\'EOF\'\nkubectl get pods\nEOF' + +echo "== PowerShell tool" +ps_case() { + local want="$1" cmd="$2" got payload + payload="$(python3 -c 'import json,sys; print(json.dumps({"tool_name":"PowerShell","tool_input":{"command":sys.argv[1]}}))' "$cmd")" + got="$(decision "$CLAUDE" "$payload")" + if [[ "$got" == "$want" ]]; then pass; else fail "powershell: want $want, got $got: $cmd"; fi +} +ps_case deny 'Get-Content C:\Users\me\.ssh\id_rsa' +ps_case deny 'type $env:USERPROFILE\.kube\config' +ps_case deny 'Get-Content .\.vault_pass' +ps_case deny $'git push `\n --no-verify' +ps_case deny 'cmd /c kubectl delete ns prod' +ps_case deny "iex 'kubectl delete ns prod'" +ps_case deny 'Invoke-Expression "kubectl delete ns prod"' +ps_case deny "& 'C:\\tools\\kubectl.exe' delete ns prod" +ps_case deny "pwsh -Command 'kubectl delete ns prod'" +ps_case allow 'Get-ChildItem C:\repo' +ps_case allow 'kubectl get pods' +ps_case allow "git commit -m 'it''s fine'" echo "== File tools" file_case() { @@ -360,6 +610,13 @@ file_case deny "$COPILOT" '{"toolName":"view","toolArgs":"{\"path\":\"/repo/.vau file_case allow "$COPILOT" '{"toolName":"view","toolArgs":"{\"path\":\"/repo/README.md\"}"}' file_case deny "$CODEX" '{"tool_name":"apply_patch","tool_input":{"command":"*** Begin Patch\n*** Update File: infra/terraform.tfstate\n*** End Patch"}}' file_case allow "$CODEX" '{"tool_name":"apply_patch","tool_input":{"command":"*** Begin Patch\n*** Update File: README.md\n*** End Patch"}}' +file_case deny "$CODEX" '{"tool_name":"apply_patch","tool_input":{"command":"*** Begin Patch\n*** Update File: notes.txt\n*** Move to: /home/me/.ssh/id_rsa\n*** End Patch"}}' +file_case deny "$CLAUDE" '{"tool_name":"Grep","tool_input":{"pattern":".","path":"/home/me/.ssh"}}' +file_case deny "$CLAUDE" '{"tool_name":"Read","tool_input":{"file_path":"/home/me/.ssh/id_ed25519_github"}}' +file_case deny "$CLAUDE" '{"tool_name":"Read","tool_input":{"file_path":"C:\\Users\\me\\.ssh\\id_rsa"}}' +file_case deny "$CLAUDE" '{"tool_name":"Write","tool_input":{"file_path":"/repo/.git/hooks/pre-commit","content":"exit 0"}}' +file_case allow "$CLAUDE" '{"tool_name":"Read","tool_input":{"file_path":"/repo/.git/hooks/pre-commit"}}' +file_case allow "$CLAUDE" '{"tool_name":"Read","tool_input":{"file_path":"/root/.ssh/known_hosts"}}' echo "== Per-runtime output" runtime_case() { @@ -379,7 +636,11 @@ runtime_case "copilot read allows" allow "$COPILOT" "$OK_COPILOT" runtime_case "codex odd job denies (no ask)" deny "$CODEX" "$ODD_CLAUDE" runtime_case "codex never denies" deny "$CODEX" "$NEVER_CLAUDE" runtime_case "unknown runtime odd job denies" deny "$UNKNOWN" "$ODD_CLAUDE" -runtime_case "camelCase payload outside a deploy path is Copilot" ask "$UNKNOWN" "$ODD_COPILOT" +# The payload's shape picks only how it is parsed, never the runtime. +runtime_case "camelCase payload outside a deploy path is unknown" deny "$UNKNOWN" "$ODD_COPILOT" +runtime_case "unknown runtime read allows" allow "$UNKNOWN" "$OK_COPILOT" +CODEX_LIST="$(python3 -c 'import json; print(json.dumps({"tool_name":"exec_command","tool_input":{"cmd":["bash","-lc","git commit -m \"$(cat <<'"'"'EOF'"'"'\nit'"'"'s\nEOF\n)\" && git push --no-verify"]}}))')" +runtime_case "codex list-form command with a here-doc" deny "$CODEX" "$CODEX_LIST" # Shape checks: Claude needs hookSpecificOutput with hookEventName; Copilot # needs a reason with every deny; Codex needs exit 2 with the reason on stderr. @@ -406,6 +667,58 @@ echo "== Fail closed" runtime_case "malformed payload denies on claude" deny "$CLAUDE" '{not json' runtime_case "malformed payload denies on copilot" deny "$COPILOT" '{not json' runtime_case "malformed payload denies on codex" deny "$CODEX" '{not json' +runtime_case "empty stdin denies" deny "$CLAUDE" '' +runtime_case "empty object denies" deny "$CLAUDE" '{}' +runtime_case "null payload denies" deny "$CLAUDE" 'null' +runtime_case "array payload denies" deny "$CLAUDE" '[]' +runtime_case "string tool_input denies" deny "$CLAUDE" '{"tool_name":"Bash","tool_input":"kubectl delete ns prod"}' +runtime_case "missing tool_input denies" deny "$CLAUDE" '{"tool_name":"Bash"}' +runtime_case "non-string command denies" deny "$CLAUDE" '{"tool_name":"Bash","tool_input":{"command":42}}' +runtime_case "command without a tool name denies" deny "$CLAUDE" '{"tool_input":{"command":"ls"}}' +runtime_case "cmd key is read" deny "$CLAUDE" '{"tool_name":"Bash","tool_input":{"cmd":"kubectl delete ns prod"}}' +runtime_case "cmd key read allows" allow "$CLAUDE" '{"tool_name":"Bash","tool_input":{"cmd":"ls"}}' +runtime_case "codex exec_command cmd" deny "$CODEX" '{"tool_name":"exec_command","tool_input":{"cmd":"kubectl delete ns prod"}}' +runtime_case "codex write_stdin chars" deny "$CODEX" '{"tool_name":"write_stdin","tool_input":{"session_id":1,"chars":"kubectl delete ns prod\n"}}' +runtime_case "copilot list toolArgs denies" deny "$COPILOT" '{"toolName":"bash","toolArgs":["kubectl get pods"]}' +runtime_case "copilot write_bash input" deny "$COPILOT" '{"toolName":"write_bash","toolArgs":"{\"sessionId\":\"1\",\"input\":\"kubectl delete ns prod\\n\"}"}' + +echo "== Size and time" +# Copilot lets a timed-out hook's call through, so the guard must stay fast +# on pathological input and refuse oversized input outright. +if python3 - "$CLAUDE" << 'PY' +import json, subprocess, sys, time +guard = sys.argv[1] +ids = ",".join(str(i) for i in range(9000)) +cases = { + "inline JSON with many commas": ("curl -d '{\"ids\":[%s],\"m\":{\"x\":1}}' http://h" % ids, "allow"), + "many dynamic programs": (";".join(['"$a" x'] * 8000) + ";kubectl get pods", "deny"), + "deep substitution": ("echo " + "$(" * 5000 + "x" + ")" * 5000, "deny"), + "many here-docs": ("cat " + "< 3: + bad.append(name) +assert not bad, bad +PY +then pass; else fail "pathological input: wrong verdict or slower than 3s"; fi echo "== Hook definition" if python3 - "$HOOKS_JSON" << 'PY'