The command-safety hook only checked the first word of each segment, so destructive commands inside if/for/while blocks, subshells, braces, PowerShell script blocks, or behind wrapper options (xargs -0, sudo -E, timeout 30) ran unchecked. A comment with an apostrophe, an escaped quote, or a line continuation also hid the following command. Skip shell keywords, split on braces, drop comments, honor backslash escapes, join continued lines, and check every suffix after a wrapper. CLI mode also strips the byte order mark that Windows PowerShell 5.1 adds to piped stdin, which let every command pass there. with-credential.ps1 returned the child's exit code from a function, so the child's stdout was captured and the exit code became 0. Run the child as a statement and exit with its code. add-credentials now refreshes the installed helper on every run so fixes reach existing machines. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
249 lines
9.3 KiB
Python
249 lines
9.3 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 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')
|
|
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; join continued lines."""
|
|
command = LINE_CONTINUATION.sub(' ', command)
|
|
segments, current, quote, index = [], [], None, 0
|
|
while index < len(command):
|
|
character = command[index]
|
|
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)'
|
|
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):
|
|
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
|
|
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
|
|
return 0
|
|
|
|
|
|
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())
|
|
args = parser.parse_args()
|
|
if args.hook:
|
|
return run_hook(sys.stdin.buffer.read())
|
|
# 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())
|