# Security Hooks for Claude Code A general-purpose, distributable set of Claude Code hooks that catch prompt injection, agent autonomy drift, supply chain attacks, and data exfiltration. Ships as a single binary (Elixir daemon via Burrito) with a shell shim, a custom rule DSL, and layered command analysis (regex + AST parsing). ## Threat Model 1. **Prompt injection via untrusted content** — a malicious README, fetched webpage, or MCP response tricks the agent into running harmful commands 2. **Agent autonomy drift** — the agent does something "helpful" that is destructive (force push, delete files, install malware packages) 3. **Supply chain / dependency attacks** — the agent installs compromised packages or runs untrusted scripts 4. **Data exfiltration** — the agent leaks secrets, env vars, or private code to external services ## Architecture Three components: ### 1. Shell shim (`security-hook`) A short bash script that Claude Code invokes as a hook command. It: - Reads the JSON hook payload from stdin - Sends it to the daemon over a Unix socket - Prints the daemon's JSON response to stdout The shim is deliberately simple — it does not manage daemon lifecycle. That responsibility belongs to the platform service manager (see Daemon Lifecycle below). **Fail-closed policy:** If the shim cannot reach the daemon within its timeout (default: 500ms), it exits with code 2 (blocking error) and writes a deny reason to stderr. The system never fails open. 500ms is enough for socket-activated startup but fast enough that users don't notice. **Socket paths:** - Linux/WSL with systemd: managed by systemd socket activation at `$XDG_RUNTIME_DIR/security-hooks/sock` - macOS with launchd: managed by launchd at `$TMPDIR/security-hooks/sock` - Fallback (no service manager): `$XDG_RUNTIME_DIR/security-hooks/sock` (Linux/WSL) or `$TMPDIR/security-hooks/sock` (macOS) The socket's containing directory is created with mode `0700` to prevent other local processes from connecting. ### 2. Elixir daemon (`security-hookd`) A long-running BEAM process distributed as a Burrito binary (single executable, no Erlang/Elixir runtime required). Target platforms: macOS (aarch64, x86_64), Linux (x86_64, aarch64), WSL (x86_64). Components: - **Socket listener** — accepts connections on Unix socket, parses JSON payloads - **Rule engine** — loads rules from `.rules` files, evaluates them against the payload using the appropriate matching strategy (regex or AST), returns the first matching result - **Bash analyzer** — parses shell commands into an AST using the `bash` Hex package, enabling structural matching that catches evasion via subshells, pipes, and obfuscation (see Matching Strategies below) - **Rule loader** — parses the custom `.rules` DSL. Validator modules are compiled into the Burrito binary at build time (not loaded dynamically) to prevent code injection into the security daemon. Users who add custom validators must rebuild the binary. - **File watcher** — monitors `rules/` and `config/` directories, triggers hot-reload on change - **Config manager** — loads `config.toml`, merges `config.local.toml` overrides (see Configuration) - **Logger** — writes JSONL to `$XDG_STATE_HOME/security-hooks/hook.log` (macOS: `~/Library/Logs/security-hooks/hook.log`) ### 3. Rule files Two kinds: - **Pattern rules** in `.rules` files using a custom DSL (see Rule Format below). Rules can use regex patterns for simple matching or AST functions for structural analysis. - **Validator modules** in `daemon/lib/security_hooks/validators/*.ex` for complex logic that cannot be expressed in the DSL. These are compiled into the binary at build time — not loaded dynamically — to prevent code injection into the security daemon. ## Directory Structure ``` security-hooks/ ├── bin/ │ └── security-hook # shell shim ├── service/ │ ├── security-hookd.service # systemd user service unit │ ├── security-hookd.socket # systemd socket activation unit │ └── com.security-hooks.daemon.plist # macOS launchd agent ├── rules/ │ ├── bash.rules # bash command rules │ ├── edit.rules # file edit rules │ └── mcp.rules # MCP tool rules ├── config/ │ ├── config.toml # default settings │ └── config.local.toml # user overrides (gitignored) ├── daemon/ # Elixir application source │ ├── lib/ │ │ ├── security_hooks/ │ │ │ ├── application.ex │ │ │ ├── socket_listener.ex │ │ │ ├── rule_engine.ex │ │ │ ├── rule_loader.ex │ │ │ ├── bash_analyzer.ex # AST parsing via bash Hex package │ │ │ ├── file_watcher.ex │ │ │ ├── config.ex │ │ │ ├── logger.ex │ │ │ └── validators/ │ │ │ ├── unknown_executable.ex │ │ │ ├── dependency_mutation.ex │ │ │ └── secret_access.ex │ │ └── security_hooks.ex │ ├── mix.exs │ └── test/ ├── install.sh └── README.md ``` ## Hook Events & Claude Code Integration Hooks are registered via `install.sh` into Claude Code's `settings.json`: ### PreToolUse hooks (can allow/deny/ask) **Bash** (matcher: `Bash`): ``` security-hook pre bash ``` **Edit/Write** (matcher: `Edit|Write`): ``` security-hook pre edit ``` **MCP** (matcher: `mcp__.*`): ``` security-hook pre mcp ``` ### PostToolUse hook Deferred to a future version. Post-tool-use linting is project-specific and requires detecting the project's toolchain, choosing the right linter, handling timeouts, and distinguishing agent-introduced errors from pre-existing ones. This deserves its own design pass. ### Response format The daemon returns JSON matching Claude Code's hook output spec. PreToolUse allow: ```json { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "allow" } } ``` PreToolUse deny (tier: block): ```json { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "destructive rm detected (in subshell)", "additionalContext": "Use trash-cli or move to a temp directory" } } ``` PreToolUse ask (tier: suspicious): ```json { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "ask", "permissionDecisionReason": "unknown executable: foo", "additionalContext": "Add foo to allowed_executables in config.toml" } } ``` ## Rule Format: `.rules` DSL Rules use a custom DSL designed so that regex patterns are never quoted (everything after `match ` to end of line is the pattern, verbatim) and AST-based structural matching uses readable function syntax. ### Matching strategies The rule loader inspects each `match` value to determine the matching strategy: - **Regex path** — if the value does not start with a known DSL function name, it is treated as a regex pattern matched against the raw input string. Fast, good for simple patterns. - **AST path** — if the value starts with a DSL function (`command(`, `pipeline_to(`, `reads_file(`, etc.), the command is parsed into an AST using the `bash` Hex package, and the function is evaluated against the tree. This catches evasion via subshells, pipes, quoting tricks, and obfuscation. The two paths are distinguished unambiguously: regex patterns will never start with `identifier(`. For bash rules specifically, the AST parser walks the full command tree — including subshells `$(...)`, pipes `|`, logical chains `&&`/`||`, and process substitution `<(...)` — to find matching command nodes regardless of nesting depth. ### Syntax ``` # Regex matching — pattern is everything after "match " to end of line block "fork-bomb" match :\(\)\s*\{.*\|.*&\s*\}\s*; nudge "Fork bomb detected" # AST matching — structural analysis of parsed command block "destructive-rm" match command("rm") with_flags("-r", "-rf", "-fr") nudge "Use trash-cli or move to a temp directory" block "pipe-to-exfil" match pipeline_to("curl", "wget", "nc") nudge "Don't pipe output to network commands" block "curl-data-upload" match command("curl") with_flags("-d", "--data", "-F", "--form") nudge "Don't upload data via curl — only downloads are allowed" block "eval-obfuscation" match command("eval", "exec") nudge "Don't use eval/exec — run the command directly" # Regex is fine for things that can't be obfuscated block "agent-recursion" match claude\s+.*--dangerously-skip-permissions nudge "Don't spawn Claude without permission checks" # Config-referenced matching suspicious "unknown-executable" match_base_command_not_in allowed_executables nudge "Unknown command '{base_command}'. Add it to allowed_executables in config.toml" # Elixir validator for complex logic block "dependency-mutation" validator SecurityHooks.Validators.DependencyMutation nudge "Don't modify dependencies directly — use the package manager CLI" ``` ### AST match functions These functions operate on the parsed AST of a bash command. They match against any command node in the tree, including those nested inside subshells, pipelines, and logical chains. | Function | Description | Example | |----------|-------------|---------| | `command("name", ...)` | Matches if any command node has one of the given executables | `command("rm", "rmdir")` | | `with_flags("flag", ...)` | Modifier: command must also have one of these flags | `command("rm") with_flags("-r", "-rf")` | | `with_args_matching(regex)` | Modifier: command args must match regex | `command("chmod") with_args_matching("777")` | | `pipeline_to("name", ...)` | Matches if a pipeline ends with one of these commands | `pipeline_to("curl", "nc")` | | `pipeline_from("name", ...)` | Matches if a pipeline starts with one of these commands | `pipeline_from("cat", "echo") pipeline_to("curl")` | | `reads_file("path", ...)` | Matches if any command reads from a sensitive path | `reads_file("~/.ssh", "~/.aws")` | | `writes_file("path", ...)` | Matches if any command writes to a path | `writes_file("/etc/", "~/.bashrc")` | | `sets_env("var", ...)` | Matches if command sets one of these env vars | `sets_env("LD_PRELOAD", "PATH")` | Functions can be chained. All conditions must match (AND logic): ``` block "exfil-secrets-via-curl" match pipeline_from("cat", "echo") pipeline_to("curl", "wget") nudge "Don't pipe local data to network commands" ``` `match_any` works with both regex and AST functions: ``` block "privilege-escalation" match_any command("sudo") command("su") with_flags("-") command("chmod") with_args_matching("777|u\+s") command("chown") with_args_matching("root") nudge "Privilege escalation is not allowed" ``` ### Grammar ``` file := (comment | blank | rule)* comment := '#' rule := tier SP name NL clauses tier := "block" | "suspicious" name := '"' '"' clauses := matcher nudge matcher := match | match_any | match_not_in | validator match := INDENT "match " (ast_expr | regex_pattern) NL match_any := INDENT "match_any" NL (INDENT2 (ast_expr | regex_pattern) NL)+ match_not_in := INDENT "match_base_command_not_in " NL validator := INDENT "validator " NL nudge := INDENT "nudge " '"' '"' NL ast_expr := ast_func (SP ast_func)* ast_func := IDENT '(' quoted_args ')' [SP modifier]* modifier := IDENT '(' quoted_args ')' quoted_args := '"' '"' (',' SP '"' '"')* regex_pattern := ``` `INDENT` = 2 spaces, `INDENT2` = 4 spaces. **Note:** `only_when` / `except_when` conditions are deferred to a future version. ### Tiers - **block** — hard deny via `permissionDecision: "deny"`. The nudge is sent as `additionalContext` so the agent can self-correct. - **suspicious** — soft deny via `permissionDecision: "ask"`. Falls through to Claude Code's permission prompt so the human decides. The nudge is shown as context. ### Match targets Each hook type matches against a specific field from the Claude Code JSON payload: | Hook file | Payload field matched | Example value | |-----------|----------------------|---------------| | bash.rules | `tool_input.command` | `rm -rf /tmp/foo` | | edit.rules | `tool_input.file_path` | `/home/user/project/src/main.rs` | | mcp.rules | `tool_name` (parsed into server + tool) | `mcp__context7__query-docs` | For bash rules, `{base_command}` is extracted as the first whitespace-delimited token of `tool_input.command` after stripping leading environment variable assignments. For AST-matched rules, it is extracted from the parsed command node. ### Evaluation Rules are evaluated in file order. First match wins. Place specific rules before general catch-alls. The rule engine runs both matching strategies in sequence: 1. Regex rules are checked first (fast, microsecond-level) 2. If no regex rule matched, the command is parsed into an AST (once, cached for the request) 3. AST rules are checked against the parsed tree This means regex rules can serve as a fast pre-filter: if a regex rule already caught the command, the AST parser is never invoked. ### Variable interpolation in nudges - `{command}` — the full command string (Bash hooks) - `{base_command}` — the first token / primary executable - `{file_path}` — the target file path (Edit/Write hooks) - `{tool_name}` — the tool name - `{server_name}` — the MCP server name (MCP hooks) ## Default Rule Sets ### bash.rules **Tier: block (AST-matched where evasion is a concern)** Destructive filesystem operations: - `command("rm") with_flags("-r", "-rf", "-fr")` — recursive delete - `command("mkfs")` — format filesystem - `command("dd") with_args_matching("of=/dev/")` — raw disk write Git history destruction: - `command("git") with_args_matching("push\\s+.*--force(?!-with-lease)")` — force push (not `--force-with-lease`) - `command("git") with_args_matching("reset\\s+--hard")` — hard reset - `command("git") with_args_matching("clean\\s+.*-f")` — force clean Package registry attacks: - `command("npm") with_args_matching("unpublish")` — npm unpublish - `command("gem") with_args_matching("yank")` — gem yank - `command("cargo") with_args_matching("yank")` — cargo yank Cloud resource deletion: - `command("aws") with_args_matching("delete-|terminate-|destroy")` — AWS destructive ops - `command("gcloud") with_args_matching("delete")` — GCloud destructive ops - `command("az") with_args_matching("delete")` — Azure destructive ops - `command("fly") with_args_matching("destroy")` — Fly.io destructive ops Privilege escalation: ``` block "privilege-escalation" match_any command("sudo") command("su") with_flags("-") command("chmod") with_args_matching("777|u\\+s|4[0-7]{3}") command("chown") with_args_matching("root") nudge "Privilege escalation is not allowed" ``` Environment variable poisoning: - `sets_env("LD_PRELOAD", "LD_LIBRARY_PATH", "PATH", "NODE_OPTIONS", "PYTHONPATH", "RUBYOPT")` Data exfiltration (AST-matched to catch piped patterns): - `command("curl") with_flags("-d", "--data", "-F", "--form", "--upload-file")` — data upload - `command("wget") with_flags("--post-data", "--post-file")` — data upload - `pipeline_to("curl", "wget", "nc", "ncat")` — piping to network commands - `reads_file("~/.ssh", "~/.aws/credentials", "~/.config/gcloud", "~/.netrc")` — sensitive file access Agent recursion: - `command("claude") with_flags("--dangerously-skip-permissions")` — unguarded agent spawn **Tier: block (regex for non-evasible patterns)** - Fork bombs: `:\(\)\s*\{.*\|.*&\s*\}\s*;` - Crypto miners: `xmrig|minerd|stratum\+tcp://` **Tier: suspicious** - Unknown base command not in allowed executables list (`match_base_command_not_in`) - Long base64-encoded strings: `[A-Za-z0-9+/]{100,}={0,2}` (obfuscation signal) ### edit.rules **Tier: block** - Edits outside `$CLAUDE_PROJECT_DIR` — path prefix check - Edits to shell config files: `.bashrc`, `.zshrc`, `.profile`, `.bash_profile` - Edits to `.env` files - Edits to `~/.ssh/`, `~/.aws/`, `~/.config/gcloud/` **Tier: suspicious** - Edits to CI/CD config: `.github/workflows/`, `.gitlab-ci.yml`, `Jenkinsfile` - Edits to `Dockerfile`, `docker-compose.yml` - Edits to lockfiles: `package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`, `mix.lock`, `Cargo.lock`, `poetry.lock`, `Gemfile.lock`, `go.sum`, `composer.lock` - Dependency field changes in manifest files (validator: `DependencyMutation`) ### mcp.rules **Tier: block** - Unknown/unregistered MCP servers (catch-all deny at end of file) - MCP tool call parameters containing shell metacharacters or injection patterns **Tier: suspicious** - MCP tools that fetch URLs or access external resources Allowed MCP servers and their tools are configured in `config.toml`. The install script auto-detects MCP servers from Claude Code's existing config and pre-populates the allowlist. The nudge for unknown servers includes the exact TOML to add: ``` block "unknown-mcp-server" match_base_command_not_in mcp_allowed_tools nudge "Unknown MCP server '{server_name}'. Add it to [mcp.servers] in config.toml:\n\n[[mcp.servers]]\nname = \"{server_name}\"\ntools = [\"*\"]" ``` ## Configuration ### config.toml (defaults, checked into repo) ```toml [meta] version = "1.0.0" [executables] allowed = [ "git", "mix", "elixir", "iex", "cargo", "rustc", "go", "python", "pip", "uv", "node", "npm", "pnpm", "yarn", "rg", "fd", "jq", "cat", "ls", "head", "tail", "wc", "sort", "uniq", "mkdir", "cp", "mv", "touch", "echo", "grep", "sed", "awk", "make", "cmake", "gcc", "clang", "ruby", "gem", "bundler", "rake", "php", "composer", "java", "javac", "mvn", "gradle", "curl", "wget", ] [secrets] env_vars = [ "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_ACCESS_KEY_ID", "GITHUB_TOKEN", "GH_TOKEN", "DATABASE_URL", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "STRIPE_SECRET_KEY", "PRIVATE_KEY", "SECRET_KEY", ] [paths] sensitive = [ "~/.ssh", "~/.aws/credentials", "~/.config/gcloud", "~/.netrc", "/etc/shadow", "/etc/passwd", ] [[mcp.servers]] name = "context7" tools = ["resolve-library-id", "query-docs"] [[mcp.servers]] name = "sequential-thinking" tools = ["sequentialthinking"] [daemon] idle_timeout_minutes = 30 log_format = "jsonl" shim_timeout_ms = 500 [rules] disabled = [] ``` ### config.local.toml (user overrides, gitignored) Merges on top of `config.toml` with three operations per list: - `append` — add entries to the default list - `exclude` — remove entries from the default list - Scalar values are overwritten ```toml # Example: customize allowed executables [executables] append = ["my-custom-tool", "deno", "bun"] exclude = ["curl", "wget"] # force these through AST exfil checks only # Example: add project-specific MCP servers [[mcp.servers]] name = "my-internal-tool" tools = ["*"] # Example: disable specific rules [rules] disabled = ["force-push"] # I use --force intentionally # Example: lower the shim timeout [daemon] shim_timeout_ms = 200 ``` ## Daemon Lifecycle The daemon is managed by the OS service manager where available, with a portable fallback. The `install.sh` script detects the platform and installs the appropriate mechanism. ### Linux/WSL: systemd user service + socket activation `install.sh` installs two systemd user units: **`~/.config/systemd/user/security-hookd.socket`** — systemd holds the socket open at all times. When the first connection arrives, systemd starts the daemon and hands over the file descriptor. Zero cold-start latency from the caller's perspective. ```ini [Unit] Description=Security Hooks socket [Socket] ListenStream=%t/security-hooks/sock SocketMode=0600 DirectoryMode=0700 [Install] WantedBy=sockets.target ``` **`~/.config/systemd/user/security-hookd.service`** — the daemon unit. `Restart=on-failure` handles crashes automatically. No PID files, no health checks, no lock files. ```ini [Unit] Description=Security Hooks daemon Requires=security-hookd.socket [Service] Type=simple ExecStart=%h/.local/bin/security-hookd Restart=on-failure RestartSec=1 Environment=SECURITY_HOOKS_CONFIG=%h/.config/security-hooks [Install] WantedBy=default.target ``` After install: `systemctl --user enable --now security-hookd.socket` ### macOS: launchd plist `install.sh` installs a launchd agent: **`~/Library/LaunchAgents/com.security-hooks.daemon.plist`** — `KeepAlive` restarts on crash. The `Sockets` key provides socket activation analogous to systemd. ```xml Label com.security-hooks.daemon ProgramArguments ~/.local/bin/security-hookd Sockets Listeners SockPathName /tmp/security-hooks/sock SockPathMode 384 KeepAlive SuccessfulExit EnvironmentVariables SECURITY_HOOKS_CONFIG ~/.config/security-hooks ``` After install: `launchctl load ~/Library/LaunchAgents/com.security-hooks.daemon.plist` ### Fallback: shim-managed daemon When neither systemd nor launchd is available (rare — containers, minimal VMs), the shim falls back to managing the daemon directly: - Acquires a lock file (`$RUNTIME_DIR/security-hooks/lock`) via `flock` (Linux) or `shlock` (macOS) before starting - The daemon writes its PID to `$RUNTIME_DIR/security-hooks/pid` - The shim checks socket connectivity; if the PID file is stale, it kills the old process and restarts - Race condition between concurrent sessions is handled by the lock file This path is less reliable than the service manager paths and is documented as a fallback only. ### Common lifecycle behavior (all platforms) **Idle shutdown:** The daemon exits after 30 minutes of inactivity (configurable via `daemon.idle_timeout_minutes`). The service manager restarts it on the next connection via socket activation. Handles `SIGTERM` gracefully — flushes pending log writes. **Hot-reload:** A `FileSystem` watcher monitors `rules/` and `config/` directories. On change, the rule engine reloads rules and config without restarting the daemon. The AST function registry is also refreshed. Users see updated rules on the next tool call. **Socket activation support in the daemon:** The daemon checks for an inherited file descriptor (systemd: `$LISTEN_FDS`, launchd: `launch_activate_socket`). If present, it uses the inherited socket. Otherwise, it opens its own (fallback path). **Logging:** All decisions are written as JSONL: ```jsonl {"ts":"2026-03-27T14:02:03Z","event":"PreToolUse","tool":"Bash","input":"rm -rf $(echo /)","rule":"destructive-rm","match_type":"ast","decision":"deny","nudge":"Use trash-cli or move to a temp directory"} {"ts":"2026-03-27T14:02:05Z","event":"PreToolUse","tool":"Bash","input":"mix test","rule":null,"match_type":null,"decision":"allow"} ``` The `match_type` field records whether the rule was matched via `regex`, `ast`, `config_list`, or `validator` — useful for understanding which matching layer caught a command and for tuning rules. Log rotation and size limits are deferred — users can manage this with external tools (logrotate, etc.) since the log path is well-defined. Future: streaming connectors for centralized logging (stdout, webhook, syslog). ## Installation ```bash ./install.sh ``` The install script: 1. Downloads the Burrito binary for the current platform (macOS aarch64/x86_64, Linux x86_64/aarch64) or builds from source if Elixir is available 2. Installs the binary and shell shim to `~/.local/bin/` (or user-specified location) 3. Copies default rules and config to `~/.config/security-hooks/` 4. Creates `config.local.toml` from a template if it does not exist 5. Auto-detects installed MCP servers from Claude Code config and pre-populates the MCP allowlist in `config.local.toml` 6. Detects the platform and installs the appropriate service manager integration: - Linux/WSL with systemd: installs user units, enables socket activation - macOS: installs launchd plist, loads agent - Fallback: prints instructions noting the shim will manage the daemon directly 7. Merges hook entries into Claude Code's `~/.claude/settings.json` (preserving existing hooks) 8. Prints a summary of what was configured **Existing hooks:** Claude Code supports multiple hooks per event. `install.sh` appends security-hooks entries without removing existing user hooks. Both run on each tool call. **Uninstall:** `./install.sh --uninstall` removes hook entries from settings and optionally removes the config directory and binary. ## Versioning & Updates Rule files and config carry a `version` field: ``` # rules/bash.rules # version: 1.0.0 ``` ```toml # config/config.toml [meta] version = "1.0.0" ``` `install.sh --update` compares installed version against the repo version, merges new default rules (preserving `config.local.toml` overrides and `disabled` entries), and logs what changed. ## Target Platforms - macOS (aarch64, x86_64) - Linux (x86_64, aarch64) - WSL (x86_64) — uses Linux binary with Linux-style paths ## Supported Language Ecosystems The default allowed executables and dependency mutation validators cover: - Rust (cargo) - Python (pip, uv, poetry) - TypeScript/JavaScript (npm, pnpm, yarn) - Go (go) - Java (maven, gradle) - Ruby (gem, bundler) - PHP (composer) - C/C++ (gcc, clang, make, cmake) - Elixir (mix) ## Dependencies Elixir/Hex packages required by the daemon: - `bash` — Bash parser producing a full AST (pipes, subshells, redirections, logical chains) - `jason` — JSON encoding/decoding - `toml` — TOML config parsing - `file_system` — cross-platform file watcher for hot-reload - `burrito` — compile to single-binary for distribution