Safety Guard — for Claude Code & opencode
A deterministic tool-call guard for AI coding agents. It sees every tool call before it runs and blocks the catastrophic ones — rm -rf /, reading ~/.ssh, writing /etc, force-push to main, credential exfiltration — with a 3-level, agent-scoped override for when you genuinely need elevated rights, and a self-protection layer so the AI can never disarm its own guard. Same input, same verdict, every time. No LLM in the loop: it's the net for when the model's judgment (or the permission prompt) fails or gets subverted by prompt injection.
- Claude Code: runs as a
PreToolUsehook. - opencode: runs as a plugin that bridges to the same guard —
opencode/v2/for opencode 2.x, the older plugin for 1.x. opencode 2 does not load the 1.x plugin; if you updated opencode, install the v2 adapter. See opencode/README.md. - Antigravity (
agy): runs as aPreToolUseadapter against the same guard — see Supported tool chains.
Born from a real incident. This started after Claude Code executed a destructive
chown -Ron/etc/— a multi-hour recovery. The built-in permission system wasn't enough. This is defense-in-depth.
Hardened by self-audit. The guard was put through a white-box audit of its own code, which found five real bypasses (credential reads via
python3 -c,${IFS}obfuscation, a fail-open on a missing rules file, …). All five are fixed, each with a regression test. What it deliberately does not try to do is documented honestly in THREAT-MODEL.md — it's a bouncer inside the wall, not the wall itself.
Quickstart
# Claude Code: point a PreToolUse hook at command-guard.py (full guide in INSTALL.md)
cp security-rules.example.json ~/.claude/safety-guard/security-rules.json
# then register hooks/command-guard.py as a PreToolUse hook in ~/.claude/settings.json
# opencode 2.x: copy opencode/v2 to ~/.config/opencode/plugins/safety-guard and run
# npm ci --ignore-scripts --omit=optional there — see opencode/README.md (1.x: the older plugin)
Install: A full, from-scratch setup guide lives in INSTALL.md. This README explains what the guard does and why; INSTALL.md explains how to deploy it.
Built and maintained by inoX-Network. Bug reports — especially new bypasses — are very welcome.
Features
- Blocked patterns —
rm -rf /,mkfs,chmod 777, fork bombs, pipe-to-shell, recursivechown/chmod/chgrpon system paths. Always blocked, even with an active override. - Git safety —
git reset --hard, force-push (incl.--force-with-lease),commit --no-verify,commit --amend,git add -A/git add ., and writinggit configare always blocked. Force-push tomain/masterhas its own dedicated rule on top. - Self-protection — The AI cannot write the hook, the rules file, the rules document, the active override directory, or the
bin/scripts — via Bash or Write/Edit. No override lifts this. It reaches beyond this repo's own files: the shell's startup files (.zshrc,.bashrc,.profile, …) are the ground every command check stands on, and the control files of other CLIs (opencode, Antigravity) hand out the same power one directory over. - Delete protection — A second path list for paths that may be changed but never removed. Write protection would block four maintenance paths to stop one deletion; this separates the two.
- Glob-aware path matching — A write target containing
*,?or[…]is held against every protected path, component by component: if the pattern could hit one, it is refused. Patterns are never expanded — that would make the verdict depend on the filesystem. Without this,echo x > ~/.claude/setting*.jsonwalked past the self-protection while the spelled-out name was refused. - Container guard — Container calls are judged by their subcommand, not by the tool name: with the tool merely on the sudo allowlist, every subcommand used to be allowed. Reading and building stay free (
ps,logs,inspect,exec,run,build,cp,attach,pull…) — butexec,run,attachandcponly locally: on another machine (ssh/mosh, also behindtimeout/nice, or a container call with its own-H/--host/--context) they need a level-1+ override, because the production system stands there (since 2026.10.01-2); tearing down (rm,kill,stop,prune…) needs a level-1+ override. Escape flags —--privileged,--pid=host,--net=host,--ipc=host,--cap-add=ALL, mounting the container socket,seccomp=unconfined— are refused hard, with no override, extendable viadocker.blocked_flags; so is a bind-mount whose host source overlaps a self-protected path. What runs inside a container is a named boundary, not an oversight:execis the most frequent form (58.2 % of 107,593 audited calls), its inner command is an interpreter in roughly 70 % of cases, and paths inside a container cannot be judged from the host. Reads are still caught by the read protection, which sees the inner command. - Owner-only commands — The approval and dev-mode scripts are hard-blocked for AI Bash calls, so the AI cannot grant itself rights.
- Protected paths — Level-dependent write protection for
~/.ssh,~/.gnupg,/etc/shadow,/boot,/usr/bin, etc. - Credential &
.envread protection — The Read tool cannot reach private keys, cloud credentials, or.envfiles without a level-1+ override. Public keys and SSH config stay open. - 3-level, agent-scoped override system — Scoped, explicit, auditable, and per-instance.
- Audit log — Every allow/block decision is logged (JSONL) with secret redaction.
- Desktop notifications — Optional heads-up on package installs.
- Prompt injection detection — Warns the model (doesn't block) when a suspicious keyword appears in a command as a whole word.
- Diagnostics register — A second hook (
Stop+SessionStart) that records language-server warnings the AI would otherwise file away, and asks for a reason instead of an acknowledgement. Five states;fixedis measured, not claimed. See docs/diagnostics-register.md. - Update check — Optional, off by default: one line at session start when a newer version has been published. Reads and compares, nothing else.
Before you install: is this for you?
git clone https://github.com/inoX-Network/claude-code-safety-guard
cd claude-code-safety-guard
python3 tools/would-it-help.py
It tells you what it is about to read and waits for your yes; without one it reads nothing. Nothing is installed, written or sent anywhere. It counts what is reachable from your machine (keys, remote hosts, credentials — existence only, no protected file is ever opened), notes which AI assistants with tool access live there, and then feeds your own past commands to the real hook in this checkout to see how many of them it would have stopped.
Then it tells you, in plain sentences, whether that is worth it — including "probably not". If no assistant with tool access is found, it says the guard would protect you from nothing today and to come back when that changes. A report that recommends itself whatever it finds would be worthless, because you could not tell the honest cases from the sales pitch.
One caveat it prints rather than hides: the guard protects you from an agent, not from yourself. Where an agent's log exists it is used; where only shell history exists, the report says so and labels its own numbers as the weaker evidence they are.
What your assistant is told here
This repository contains AGENTS.md (and CLAUDE.md, a pointer to
the same file) — notes that an AI assistant reads when it opens the project.
They are worth reading yourself, because you should know what is being said
to something acting on your behalf.
The short version of what they say: this guard sits in front of the assistant's own tool calls; a refusal is a signal to stop and rephrase, never something to work around; the assessment above exists and is usually worth offering; do not oversell its verdict, and do not run it without asking. Nothing in there instructs an assistant to recommend this project.
That disclosure is deliberate. A file in a repository that issues instructions to a foreign agent has the same shape as a prompt injection, and a security tool should not be the one demonstrating it quietly.
If you would rather your assistant did not read it: delete both files. Nothing about what the guard blocks depends on them — they are addressed to a reader, not to the hook.
How it works
tool call ──► PreToolUse hook ──► command-guard.py ──► reads agent_id + tool from stdin
│
┌──────────────────┬──────────┴───────────┬──────────────────────────┐
▼ ▼ ▼ ▼
Read Write/Edit/ Bash other
MultiEdit/ tools
│ NotebookEdit │ │
▼ │ ▼ EXIT 0
env / credential ▼ ALWAYS, no override: (allow)
read protection self-protection? blocked_patterns · owner_only ·
│ env write? path? force-push · git-safety ·
│ │ self-protection
▼ ▼ │
allow / block allow / block ▼
load override for THIS context
(agent_id → no inheritance)
│
▼
level-dependent: protected paths,
sudo allowlist, notify, injection
│
▼
allow (EXIT 0) / block (EXIT 2)
Every branch ends by writing an audit line. EXIT 0 allows the tool call, EXIT 2 blocks it.
Bash checks, in order
The first group runs always — an active override never weakens it:
- Blocked patterns (
rm -rf /,mkfs, recursivechownon system paths, …) - Owner-only commands (
grant-override,hook-dev-mode) - Force-push to
main/master - Git-safety ops (
reset --hard,--no-verify,--amend,add -A/., writingconfig) - Self-protection — write access to the security system's own files
Only after those does the hook load the override for the calling context and run the level-dependent checks:
- Protected paths — level 0: none; level 1: only explicitly granted paths; level 2+: all protected paths (single ops — recursive-on-system stays hard-blocked above). Then the fixed root rule: deleting
/or the home directory itself is refused at every level, a recursive delete one level below/needs level 2 - Sudo allowlist — base allowlist plus
additional_sudogrants; level 2+ (oradditional_sudo: "all") allows all sudo. An allowed command that writes as root (cp,mv,install,tee,dd,ln,rsync,chmod,chown,chgrp,mkdir,touch,truncate,rm,rmdir,unlink) needs level 1 — locally and on a remote host; reading as root stays free. Setting a setuid/setgid bit (chmod 4755,u+s,install -m 4755) needs level 2 (since 2026.10.05-5) - Confirmation desktop notification, then prompt-injection warning
Read checks
.envfiles require a level-1+ override- Always-blocked reads (
/etc/shadow,/etc/gshadow) — no override possible - Always-allowed files (public keys,
~/.ssh/config,known_hosts,authorized_keys) - Override-required files (private keys, cloud credentials) — need a level-1+ override
Write / Edit / MultiEdit / NotebookEdit checks
- Self-protection — no override lifts it (only dev mode unlocks the hook sources)
.envwrite — requires a level-1+ override- Protected paths — same level logic as the Bash path check
Protection scope
Built for a session with no other brakes. Everyday work here — and every
test run in this repo — happens with Claude Code's permission prompts turned
off (bypass permissions). That is deliberate, not sloppy: an agent that stops
every few minutes to ask is not autonomous, and a human who clicks "allow"
fifty times a day stops reading what they are allowing. This guard replaces
those prompts rather than adding to them. Read the scope below with that in
mind — what it does not cover, nothing else covers either.
That is also why the refusals are hard by default and the override needs the owner: the guard is not one opinion among several, it is the only one asked.
The guard protects zones and catastrophic patterns, not "every write or delete". Knowing this contract avoids surprise:
- In scope — zones: writes/deletes to a configured
blocked_paths_writepath (e.g./etc,/bin,~/.ssh) or a hard-coded self-protection path are blocked. Detection is a write-verb gate (rm,rmdir,unlink,shred,mv,cp,truncate,tee,ln,>,find … -delete,rsync … --delete,git clean, …) combined with a boundary-accurate path match. - In scope — catastrophic patterns: a small set of always-block regexes
(
rm -rf /,rm -rf ~,chmod 777,mkfs,dd of=/dev/sd…, fork bomb,curl … | sh, recursivechown/chmodon system trees, …). - Out of scope — default allow: anything outside those zones and patterns is
allowed by design.
rm -rf ~/Downloads/projectis not blocked — the guard is a guardrail against catastrophic and protected-zone operations, not a general "are you sure?" for ordinary file management.
Known limitations
- Symlinks are not resolved. Path matching is purely lexical
(
os.path.normpath, norealpath/readlink) — see the_norm_pathdocstring ("no filesystem/symlink access, which the hook deliberately avoids"). A symlink in an unprotected zone whose target lives in a protected zone is matched by its lexical path, so a write through the link (> safe/link,truncate safe/link) can reach the protected target unblocked. This is a deliberate trade-off: resolving symlinks touches the filesystem and opens TOCTOU, performance, and existence questions. Tracked inBEFUND-guard-scope-symlink-2026-07-24.md(columns 3/4 of the test matrix). - Glob patterns are checked against the protection list, not expanded.
Since 2026-08-25 a write target containing
*,?or[…]is held against every protected path component by component: if the pattern could hit one, it is refused. Before that the comparison was literal, soecho x > ~/.claude/setting*.jsonwalked past the self-protection while the spelled-out name was refused. Expanding the pattern was rejected on purpose — it would touch the filesystem and reopen the TOCTOU question above. The remaining gap is the same one the symlink note describes: a target that only becomes a path later — through a variable, a decoder, word splitting — is still invisible to a text matcher. A pattern must be at least as deep as the protected path, otherwise a bare*would match everything. - The write-verb gate is not a strict verb→path binding. It is (a write verb)
AND (a protected path) within the same segment of the line: a write in one
segment no longer makes a protected path in another its target, and a directory
change, an assignment value or a line continuation still counts as part of the
write context. Inside a single segment, the redirect target is what counts:
sha256sum <protected file> > /tmp/sum.txtruns, because only the scratch file is written. Copying onto a protected path with a harmless redirect appended (cp x <protected file> > /tmp/log.txt) is still refused — the redirect does not launder the copy. - Interpreter one-liners are matched literally, and naming one is enough.
The inline branch compares the expanded command text against the protected
paths, shell assignments included —
VAR=<protected dir>; python3 -c "open('$VAR/x')"is matched. (It was not until 2026-08-23: only the ordinary write check resolved assignments, and the two branches disagreed.) Inside this branch even a plain read is refused:python3 -c "print(open(<control file>).read())"does not get through. That bluntness is deliberate and measured — of 608 real refusals, 44 wereopen(path,'w'), a write with no shell verb and no redirection that nothing else catches. The price is ten real reads across seven sessions, each withcat/grep/headas the way out, and the refusal now says so instead of claiming you tried to write. Assembling a path from pieces still escapes the branch, but only when the split falls inside the protected part:'/tmp/x/.clau' + 'de/settings.json'passes,'/tmp/x/.claude/settings.json'split anywhere before it does not. That is the general obfuscation limit named in THREAT-MODEL.md: no substring layer tames a Turing-complete shell. Sandbox and least privilege are the answer to that one, not the hook. - A downloader's output target must be readable as text. Since 2026.09.22-3
the output flag of
curl/wget(-o,-O,--output,-P, …) counts as a write, and its argument is held against the write and self-protection lists; an assignment on the same line is resolved first. A target that stays an external variable — set in an earlier command, or in the environment — names no protected path the hook could see, and passes. Same boundary as the interpreter branch above: text in, text out. - Delete protection names a path, not its ancestors.
blocked_paths_delete— and the self-protection of the guard's own files — refuses destroying a named path and everything under it, but naming an ancestor directory removes the protected path as a side effect without matching either list. Measured:rm -rf ~/.claude/projectsandrm -rf ~/.claude/hooksare refused, yetrm -rf ~/.claude— which takes both with it — passes, and so dofind ~/.claude -deleteandfind ~/.claude | xargs rm, where the protected path never appears as a literalrmargument. The intended fix is a depth-aware rule: block a recursive delete at or near the root of a protected tree while single-file deletes underneath stay free, so everyday maintenance is untouched. Until then, an OS sandbox / least privilege is the hard boundary — as for every row in THREAT-MODEL.md. - The root rule judges absolute targets.
rm -fr /usris refused, but a relative target aftercd /(cd / && rm -fr usr) is not resolved against the working directory yet — the hook reads the text, not the shell's state. The root and the home directory themselves are covered in every spelling measured; the relative form is tracked for the planned command parser.