Files
MyAiConfiguration/shared/hooks/scripts/command-safety.py
T
Julian Lechner c3e22eb902
CI / CI configuration security checks (push) Successful in 6s
CI / Python tests and compilation (push) Failing after 12s
CI / QMD unit tests (push) Skipped
CI / Capabilities and shell quality (push) Successful in 1m50s
CI / Build and inspect generated packages (push) Skipped
CI / Bash integration and installation guards (push) Skipped
CI / Installed client configuration smoke tests (push) Skipped
CI / PowerShell tests on Ubuntu (push) Failing after 7m24s
corrections
2026-11-19 10:30:43 +01:00

300 lines
12 KiB
Python

"""Block clearly destructive shell commands.
Hook mode (--hook) reads a Claude or Codex PreToolUse event from stdin and exits 2 with a
reason on stderr to block the tool call; anything it cannot parse is allowed (fail open).
CLI mode (--command) checks one command and additionally rejects absolute paths outside the
workspace. Both modes are guard rails against accidents, not a security boundary: they parse
command text and cannot see what scripts, aliases, or variables expand to at run time.
"""
import argparse
import importlib.util
import json
import ntpath
import os
import posixpath
import re
import shlex
import sys
WRAPPERS = {'sudo', 'doas', 'command', 'builtin', 'exec', 'nohup', 'time', 'env', 'xargs', 'timeout', 'nice'}
# Shell keywords that can precede a command in the same segment.
KEYWORDS = {'if', 'then', 'else', 'elif', 'do', 'while', 'until', '!'}
LINE_CONTINUATION = re.compile(r'[\\`]\r?\n')
HEREDOC = re.compile(r'<<(-?)\s*([\'"]?)([A-Za-z_][A-Za-z0-9_]*)\2')
POSIX_SHELLS = {'bash', 'sh', 'zsh', 'dash', 'ksh'}
POWERSHELL_HOSTS = {'pwsh', 'powershell'}
POWERSHELL_REMOVE = {'remove-item', 'ri'}
# In PowerShell these aliases mean Remove-Item; in Bash, rm follows the POSIX rules instead.
POWERSHELL_REMOVE_ALIASES = {'rm', 'del', 'erase', 'rd', 'rmdir'}
CMD_REMOVE = {'del', 'erase', 'rd', 'rmdir'}
RECURSE_PARAMETER = re.compile(r'-r(?:e(?:c(?:u(?:r(?:s(?:e)?)?)?)?)?)?(?::\$true)?')
MAX_DEPTH = 3
def split_segments(command):
"""Split on ;, &, |, &&, ||, newlines, and braces outside quotes; drop # comments and heredoc bodies; join continued lines."""
command = LINE_CONTINUATION.sub(' ', command)
segments, current, quote, index, heredocs = [], [], None, 0, []
while index < len(command):
character = command[index]
if not quote and command.startswith('<<', index) and not command.startswith('<<<', index):
match = HEREDOC.match(command, index)
if match:
heredocs.append((match.group(1) == '-', match.group(3)))
current.append(match.group(0))
index = match.end()
continue
if not quote and character == '\n' and heredocs:
# The body is text for the command, not commands: skip to each delimiter line.
segments.append(''.join(current))
current = []
lines = command[index + 1:].split('\n')
consumed = 0
for strip_tabs, word in heredocs:
while consumed < len(lines):
line = lines[consumed].rstrip('\r')
consumed += 1
if (line.lstrip('\t') if strip_tabs else line) == word:
break
heredocs = []
index += 1 + sum(len(line) + 1 for line in lines[:consumed])
continue
if character == '\\' and quote != "'" and index + 1 < len(command):
current.append(command[index:index + 2])
index += 2
continue
if quote:
current.append(character)
if character == quote:
quote = None
elif character in '\'"':
quote = character
current.append(character)
elif character == '#' and (index == 0 or command[index - 1].isspace()):
newline = command.find('\n', index)
index = len(command) if newline < 0 else newline
continue
elif character in ';&|\n{}':
segments.append(''.join(current))
current = []
else:
current.append(character)
index += 1
segments.append(''.join(current))
return [segment.strip() for segment in segments if segment.strip()]
def tokenize(segment):
try:
return shlex.split(segment, posix=True)
except ValueError:
return segment.split()
def program_name(token):
name = re.split(r'[\\/]', token)[-1].lower()
return re.sub(r'\.(exe|cmd|bat)$', '', name)
def strip_wrappers(tokens):
"""Drop leading keywords, subshell parentheses, and variable assignments; stop at the first program or wrapper."""
tokens = list(tokens)
while tokens:
first = tokens[0].lstrip('(')
if not first or first in KEYWORDS or re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=.*', first):
tokens.pop(0)
continue
tokens[0] = first
break
return tokens
def short_flags(tokens):
flags = set()
for token in tokens:
if re.fullmatch(r'-[A-Za-z]+', token):
flags.update(token[1:])
return flags
def git_subcommand(arguments):
index = 0
while index < len(arguments):
token = arguments[index]
if token in ('-C', '-c', '--git-dir', '--work-tree', '--namespace'):
index += 2
elif token.startswith('-'):
index += 1
else:
return token.lower(), [item.lower() for item in arguments[index + 1:]]
return '', []
def check_tokens(tokens, shell=None):
"""Return why the command is blocked; shell is 'bash', 'powershell', or None when unknown."""
tokens = strip_wrappers(tokens)
if not tokens:
return None
program = program_name(tokens[0])
if program in WRAPPERS:
# Wrapper options and values (xargs -0, sudo -u bob, timeout 30) come before the wrapped command.
for start in range(1, len(tokens)):
reason = check_tokens(tokens[start:], shell)
if reason:
return reason
return None
arguments = tokens[1:]
lowered = [argument.lower() for argument in arguments]
if program == 'rm' and shell != 'powershell':
flags = short_flags(arguments)
recursive = bool(flags & {'r', 'R'}) or '--recursive' in lowered
force = 'f' in flags or '--force' in lowered
if recursive and force:
return 'recursive forced deletion (rm -rf)'
if program == 'git':
subcommand, rest = git_subcommand(arguments)
if subcommand == 'reset' and '--hard' in rest:
return 'discarding work tree changes (git reset --hard)'
if subcommand == 'clean' and ('f' in short_flags(rest) or '--force' in rest):
return 'deleting untracked files (git clean -f)'
if subcommand == 'checkout' and ('--' in rest or '.' in rest):
return 'discarding file changes (git checkout -- <path>)'
if subcommand == 'restore' and rest and ('--staged' not in rest or '--worktree' in rest):
return 'discarding file changes (git restore)'
if subcommand == 'push' and ('f' in short_flags(rest) or any(item.startswith(('--force', '+')) for item in rest)):
return 'overwriting remote history (git push --force)'
if subcommand == 'stash' and rest[:1] == ['clear']:
return 'deleting all stashes (git stash clear)'
if program == 'find' and '-delete' in lowered:
return 'deleting found files (find -delete)'
powershell_remove = program in POWERSHELL_REMOVE or (shell != 'bash' and program in POWERSHELL_REMOVE_ALIASES)
if powershell_remove and any(RECURSE_PARAMETER.fullmatch(item) for item in lowered):
return 'recursive deletion (Remove-Item -Recurse)'
if program in CMD_REMOVE and '/s' in lowered and '/q' in lowered:
return 'quiet recursive deletion (del /s /q)'
if program == 'format' and any(re.fullmatch(r'[a-z]:', item) for item in lowered):
return 'formatting a drive'
return None
def nested_command(tokens):
"""Return (command, shell) for bash -c, pwsh -Command, cmd /c, and eval; otherwise None."""
tokens = strip_wrappers(tokens)
if not tokens:
return None
program = program_name(tokens[0])
if program in WRAPPERS:
return next((found for start in range(1, len(tokens)) if (found := nested_command(tokens[start:]))), None)
if program == 'eval':
return ' '.join(tokens[1:]), 'bash'
for index, token in enumerate(tokens[1:], start=1):
lowered = token.lower()
nested = ' '.join(tokens[index + 1:])
if program in POSIX_SHELLS and re.fullmatch(r'-[a-z]*c', lowered):
return nested, 'bash'
if program in POWERSHELL_HOSTS and lowered in ('-c', '-command'):
return nested, 'powershell'
if program == 'cmd' and lowered in ('/c', '/k'):
return nested, None
return None
def find_violation(command, shell=None, depth=0):
if depth > MAX_DEPTH:
return None
for segment in split_segments(command):
tokens = tokenize(segment)
reason = check_tokens(tokens, shell)
if reason:
return reason
nested = nested_command(tokens)
if nested:
reason = find_violation(nested[0], nested[1], depth + 1)
if reason:
return reason
return None
def outside_workspace(command, workspace):
workspace = os.path.normcase(os.path.realpath(workspace))
for token in tokenize(command):
candidate = token.split('=', 1)[-1] if token.startswith('-') else token
if re.fullmatch(r'/[A-Za-z?]', candidate):
continue # cmd.exe switches such as /c or /s are not paths.
if not (posixpath.isabs(candidate) or ntpath.isabs(candidate)):
continue
resolved = os.path.normcase(os.path.realpath(candidate))
try:
inside = os.path.commonpath([resolved, workspace]) == workspace
except ValueError:
inside = False
if not inside:
return candidate
return None
def run_hook(data, shell_override=None):
try:
event = json.loads(data.decode('utf-8', errors='replace'))
command = event.get('tool_input', {}).get('command')
tool = str(event.get('tool_name', '')).lower()
except (ValueError, AttributeError):
return 0
if not isinstance(command, str):
return 0
shell = tool if tool in ('bash', 'powershell') else None
if shell_override:
# Codex reports every shell command as Bash, even PowerShell script text on Windows.
shell = None if shell_override == 'unknown' else shell_override
reason = find_violation(command, shell)
if reason:
print(f'Blocked by command-safety hook: {reason}. Ask the user to run this command themselves if it is intended.', file=sys.stderr)
return 2
remind_search(event)
return 0
def remind_search(event):
# Runs the search reminder in this process so shell calls start one hook process, not two.
# Best effort like agent-guards.py itself: a reminder failure never blocks or fails the command.
try:
spec = importlib.util.spec_from_file_location('agent_guards', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'agent-guards.py'))
guards = importlib.util.module_from_spec(spec)
spec.loader.exec_module(guards)
guards.remind_search(event)
except Exception:
pass
def run_check(command, workspace):
reason = find_violation(command)
if reason:
print(f'Blocked potentially destructive command: {reason}', file=sys.stderr)
return 1
path = outside_workspace(command, workspace)
if path:
print(f'Blocked command containing an absolute path outside the workspace: {path}', file=sys.stderr)
return 1
print('PASS command safety')
return 0
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument('--hook', action='store_true', help='read a PreToolUse event from stdin')
mode.add_argument('--command', help="command text to check, or '-' to read it from stdin")
parser.add_argument('--workspace', default=os.getcwd())
parser.add_argument('--shell', choices=('bash', 'powershell', 'unknown'), help='hook mode: dialect to assume instead of the tool name')
args = parser.parse_args()
if args.hook:
return run_hook(sys.stdin.buffer.read(), args.shell)
# Windows PowerShell 5.1 prefixes piped stdin with a UTF-8 byte order mark.
command = sys.stdin.buffer.read().decode('utf-8-sig', errors='replace') if args.command == '-' else args.command
return run_check(command, args.workspace)
if __name__ == '__main__':
sys.exit(main())