Sub topic 6
Blocking Dangerous Shell Commands
Shell commands are the riskiest tool call most agents can make. A single string can delete a directory, rewrite remote history, or drop a database table. This chapter builds a pre-action hook that inspects a proposed shell command and blocks it with exit code 2.
Prerequisites
This chapter assumes you know three things:
- The hook contract from earlier chapters: the agent sends the tool-call event as JSON on stdin, and the hook answers with an exit code and a stderr message.
- Basic Python, including
reandjson. - Shell syntax: pipes,
&&,;, quoting, andbash -c.
Field names such as tool_input.command follow the convention used by Claude Code and Kiro CLI. Check your agent's documentation for the exact names.
The simplest version: regex on the raw string
A first guard matches a list of deny patterns against the command text.
#!/usr/bin/env python3
import json
import re
import sys
BLOCKED_PATTERNS = [
r"\brm\s+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+/(\s|$)",
r"\bgit\s+push\b.*--force",
r"\bdrop\s+table\b",
]
event = json.load(sys.stdin)
command = event.get("tool_input", {}).get("command", "")
for pattern in BLOCKED_PATTERNS:
if re.search(pattern, command, re.IGNORECASE):
print(f"Blocked: command matches risky pattern {pattern!r}. Use a safer alternative.", file=sys.stderr)
sys.exit(2)
sys.exit(0)This works for the exact strings it was written for. It is also easy to get around by accident, and an agent that has just been blocked will often retry with a slightly different spelling. The pattern for rm requires the letters r then f inside one flag group, so each of these slips through:
rm -fr /(letters in the other order)rm -r -f /(separate flags)rm --recursive --force /bash -c 'rm -rf /'(this one is caught, but only by luck of the substring)echo hi; sudo rm -rf /*(the/*target does not match/(\s|$))
The cause is that the regex looks at characters, not at commands. A shell command is a small language, so the hook should parse it before judging it.
Normalize first, then judge
Normalizing means turning the raw string into a structure that is the same however the user or agent spelled the command. Three steps cover most cases:
- Split the string into individual commands at
;,&&,||,|, and newlines. - Tokenize each command the way a shell would, respecting quotes.
- Strip wrappers such as
sudo, then look at the program name and its arguments.
Python's shlex module can do the splitting and tokenizing in one pass. With punctuation_chars=True, it emits operators like && and ; as their own tokens, and it leaves operators inside quotes alone. Setting commenters to an empty string means text after # is still inspected.
A fuller guard
#!/usr/bin/env python3
import json
import os
import re
import shlex
import sys
WRAPPERS = {"sudo", "command", "nohup", "time"}
SHELLS = {"sh", "bash", "zsh"}
DANGEROUS_TARGETS = {"/", "/*", "~", "~/", "$HOME", "$HOME/"}
MAX_DEPTH = 3
def split_commands(command):
lexer = shlex.shlex(command.replace("\n", " ; "), posix=True, punctuation_chars=True)
lexer.whitespace_split = True
lexer.commenters = ""
commands, current = [], []
for token in lexer:
if set(token) <= set(";&|()"):
if current:
commands.append(current)
current = []
else:
current.append(token)
if current:
commands.append(current)
return commands
def check_tokens(tokens, depth):
while tokens and os.path.basename(tokens[0]) in WRAPPERS:
tokens = tokens[1:]
if not tokens:
return None
name = os.path.basename(tokens[0])
args = tokens[1:]
if name in SHELLS and "-c" in args:
index = args.index("-c")
if index + 1 < len(args):
if depth >= MAX_DEPTH:
return "shell nesting is too deep to inspect"
return check(args[index + 1], depth + 1)
if name == "rm":
flags, targets = set(), []
for arg in args:
if arg.startswith("--"):
flags.add(arg)
elif arg.startswith("-") and len(arg) > 1:
flags.update(arg[1:])
else:
targets.append(arg)
recursive = {"r", "R", "--recursive"} & flags
if recursive and any(t in DANGEROUS_TARGETS for t in targets):
return "recursive rm on the filesystem root or home directory"
if name == "git" and "push" in args and ("--force" in args or "-f" in args):
return "git push --force can overwrite shared history"
return None
def check(command, depth=0):
if re.search(r"\bdrop\s+table\b", command, re.IGNORECASE):
return "SQL DROP TABLE"
for tokens in split_commands(command):
reason = check_tokens(tokens, depth)
if reason:
return reason
return None
def main():
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
if not isinstance(command, str):
raise TypeError("command is not a string")
reason = check(command)
except (KeyError, TypeError, ValueError) as exc:
print(f"Blocked: hook could not analyze this call ({type(exc).__name__}).", file=sys.stderr)
return 2
if reason:
print(f"Blocked: {reason}. Name the exact directory or branch you mean.", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
sys.exit(main())Save it as guard.py. Several choices in it matter beyond the code itself.
Flags are sets, not strings
The rm branch collects every short flag into a set, so -rf, -fr, -r -f, and -Rf all produce the same result. Long flags such as --recursive are kept whole. The rule then asks a question about meaning: is the delete recursive, and is the target the root or home directory?
Only the dangerous combination is blocked
The rule fires on rm -r aimed at /, ~, or $HOME, not on rm -rf in general. Agents routinely run rm -rf node_modules or rm -rf ./build. A rule that blocks them teaches the agent to work around the hook and teaches you to disable it.
Force-push rules stay narrow
--force-with-lease is a separate token from --force, so it passes. It refuses to overwrite commits you have not seen, which makes it a reasonable alternative to suggest in the feedback message.
Nested shells are re-checked
When the program is bash -c "...", the hook feeds the inner string back through check. The depth cap stops an adversarial or confused chain of nested shells from recursing forever, and it blocks when it cannot finish inspecting.
Failing closed
The main function catches KeyError, TypeError, and ValueError and exits with code 2. ValueError covers json.JSONDecodeError and the No closing quotation error from shlex. This is failing closed: if the hook cannot tell what the command is, it does not let it through.
import json
import sys
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: hook could not read the tool call, so it was not allowed.", file=sys.stderr)
sys.exit(2)Be aware of the exit-code convention here. In most hook systems, exit 2 blocks and shows stderr to the agent. Other nonzero codes are often treated as a non-blocking hook error, and the tool call still runs. An uncaught Python exception exits with code 1, which can mean a crashed guard silently allows everything. That is why main catches errors explicitly and returns 2.
Testing without an agent
A hook is a plain program, so you can test it by piping events into it. This loop runs a batch of commands and prints the exit code for each.
run() {
printf '{"tool_name":"shell","tool_input":{"command":"%s"}}' "$1" | python3 guard.py 2>/dev/null
echo "exit code: $? <- $1"
}
run "rm -rf /"
run "rm -fr /"
run "ls && rm -rf ~"
run "bash -c 'rm -rf /'"
run "git push --force origin main"
run "git push --force-with-lease origin main"
run "rm -rf ./build"
run "echo 'a; b'"
run "echo 'oops"Expected exit codes are 2 for the first five, 0 for the next three, and 2 for the last. The last case is an unterminated quote, which the hook cannot parse. The hook treats echo 'a; b' as one harmless command, because the semicolon is inside quotes. Drop the 2>/dev/null while debugging so you can read the stderr messages, since those are the text the agent will see.
Keep this list as a regression suite. Every time the agent finds a way around your guard, add that command to the list before you fix the rule.
What this guard still misses
Parsing closes the common spelling gaps, but a command-string check has hard limits:
- Variable expansion:
T=/; rm -rf $Tdoes not contain a literal dangerous target. - Encoded payloads:
echo cm0gLXJmIC8= | base64 -d | shhides the command. - Scripts:
python cleanup.pycan do anything, and the hook never sees the script's contents. - Global git options:
git -C repo push --forcestill matches here, but more exotic option placement may not. - Other tools:
find / -delete,dd, andchmod -R 777 /need their own rules.
Exercise
The guard allows rm -rf ./build but blocks rm -rf ~. Write the test lines you would add to the bash loop for rm -R --force /* and sudo rm -r -f $HOME, and say what exit code each should return and why.
Show answer
Both should return 2. In rm -R --force /*, the flag set contains R and --force, so the delete is recursive, and the target /* is in DANGEROUSTARGETS. In sudo rm -r -f $HOME, the sudo wrapper is stripped, the flags r and f are collected separately, and $HOME is in DANGEROUSTARGETS (the hook sees the literal text, because nothing expands it). The test lines are run "rm -R --force /*" and run "sudo rm -r -f \$HOME", with the dollar sign escaped so the test shell does not expand it before the text reaches the hook.
Exercise
Why does main exit with code 2 when shlex raises an error, even though the command might be harmless?
Show answer
The hook cannot tell what the command does, so allowing it would mean running unchecked input. Failing closed trades a few false positives for the guarantee that anything the hook cannot analyze is blocked. Exit code 2 is also required, because other nonzero codes are often treated as a non-blocking hook failure and the command would still run.