"""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', 'command', 'builtin', 'exec', 'nohup', 'time', 'env', 'xargs'} 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 ;, &, |, &&, || and newlines that are outside quotes.""" segments, current, quote = [], [], None for character in command: if quote: current.append(character) if character == quote: quote = None elif character in '\'"': quote = character current.append(character) elif character in ';&|\n': segments.append(''.join(current)) current = [] else: current.append(character) 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): index = 0 while index < len(tokens): token = tokens[index] if program_name(token) in WRAPPERS or re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=.*', token): index += 1 continue break return tokens[index:] 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]) 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 == '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()) command = sys.stdin.read() if args.command == '-' else args.command return run_check(command, args.workspace) if __name__ == '__main__': sys.exit(main())