Merge feature/extract-guard into develop

This commit is contained in:
bchanot committed 2026-11-05 15:08:11 +01:00
commit 2be5df4eb8
14 files changed
+828 -4

No files matched your search

+6
View File
@@ -364,3 +364,9 @@ rules:
- **Real cause**: the installed gitleaks does not honour the allowlist block under the hook's invocation (rules compiled in; allowlist silently ignored).
- **Solution**: secret-shaped fixtures built at runtime by concatenation (`'AKIA' + 'I'.repeat(16)`, `'eyJ' + 'a'.repeat(20) + …`), expected strings stay literal (LRN-237); spec and NOISE.md quote shapes by reference, never a literal.
- **Status**: resolved 2026-11-03.
## BLK-042 — Package extracted into the root filesystem of a VM replaced usr-merge symlinks and overwrote system binaries [resolved] (2026-11-05)
- **Friction**: on a VM (vaas-cli ssh, no package manager), a Debian package was extracted with `dpkg -x` into the root filesystem; system binaries overwritten, usr-merge symlinks (bin, sbin, lib, lib64) replaced by real directories carrying the archive's paths.
- **Real cause**: no rule or guard named package/archive extraction into system dirs; the ssh deny rule did not cover vaas-cli ssh; extraction improvised instead of telling the user there was no package manager.
- **Solution**: `hooks/extract-guard.sh` (deny before run, quoted remote scripts re-scanned) + soft_deny line + doctrine bullet (list first, extract into a literal mktemp -d path, PATH/PYTHONPATH, no package manager → tell the user). See the extract-guard BDR.
- **Status**: resolved 2026-11-05.
+8
View File
@@ -1495,3 +1495,11 @@ Supersedes [[BDR-030]].
- **Alternatives rejected**: classic hooks (no store, no tool); gitleaks as redaction engine (rules compiled in, allowlist ignored); per-session store (lost at /clear); index cache (stale registries); option B no sub-agent capture (loses reviewer findings); option C ship as is (70 % noise per call).
- **Residuals**: cross-process writes last-writer-wins; non-Bash failures; lexical superseded reader; 40-hex Gitea tokens kept (SHA-shaped); `user:p@ss@host` partial; `key: value` pair rule over-redacts prose (`token: expected`); session root moves with /cd or a worktree; bare finish on a chore branch counts; common-phrase 4-gram collisions (every ENOENT → known LRN-056 here) → 4c.
- **Gates**: plan r1 correctness FATAL(9) → r2, confirmation CONCERNS(5) → r3; SDD Tasks 1-6 + 8 (sonnet, 7 fix rounds), 7 and 9 controller; headless proof PASS; final opus review Approved with fixes (2 Important, 13 minors, 2 rounds); verifier ECARTS(3) → ECARTS(1) (interactive /clear half, user); security PASS ×3 (coverage rounds). 36+ commits.
## BDR-138 — extract-guard: narrow text hook refusing package/archive extraction into system dirs, plus soft_deny, not a full shell parser (2026-11-05)
- **Context**: user incident 2026-11-04 (Debian package extracted on a VM overwrote system binaries); /feat on feature/extract-guard, contract `.claude/tasks/contracts/2026-11-04-extract-guard-2214.md`, plan r3.
- **Decision**: `hooks/extract-guard.sh`, PreToolUse `Bash|Monitor`, timeout 10, DENY (not ask). Watched: dpkg/dpkg-deb extract flags, tar extract (bsdtar, gtar), unzip, cpio copy-in and pass-through, recursive cp. System roots: the root dir itself and usr, etc, bin, sbin, lib*, boot, opt, var, srv, root, sys, proc, dev with subdirs; var/tmp, var/folders, HOME free. One POSIX awk scanner (bash 3.2 safe wrapper): re-tokenizes EVERY quoted word holding a blank, command substitutions, backticks, heredoc bodies (depth ≤ 3), no carrier list; detector starts at every watched tool word (covers sudo, find -exec, both vaas-cli ssh forms). Unresolvable destination (variable, substitution, glob, brace) refused; >64 KiB naming a tool refused; awk failure past prefilter refused; jq/awk/grep/sed/tr/wc missing → warn + allow. Remote follows local rules (relative or absent dest passes); quoted script inherits caller's cd (stated FP: cd to the root dir, then an ssh extract); subshell restores cd. Plus `autoMode.soft_deny` line for intent text hides; doctrine bullet in CLAUDE.global.md § Destructive tools & data loss.
- **Why**: static shell parsing never complete (plan r1 FATAL ×3, r2 FATAL(9)/(7): 30+ forms); ssh, sudo, su, eval, pipe-to-bash already denied statically, real exposed carrier = vaas-cli ssh (remote root); classifier reads intent → soft_deny covers MISSES.
- **Alternatives rejected**: fine parser with carrier/wrapper lists (r2, endless holes); doctrine + soft_deny only (no deterministic refusal); ask (inert in headless sub-agents, BDR-090); folding into withheld guard-bash.sh (BLK-022 spec would turn red).
- **Residuals**: destination built outside the text; old-style tar C letter, long-option abbreviations; tool names built by expansion; archive members escaping a safe destination; the cd-then-ssh FP; prose or a heredoc body quoting a complete extraction command into a system dir is refused too (it hit this memory write: memory bodies go through Write + --body-file, prose uses `<pkg> <dir>` placeholders).
- **Gates**: verifier ECARTS(2) → CONFORME; security PASS ×2 (4 MEDIUM then 2 MEDIUM fixed: size cap, control-byte RS, obfuscated names, globs, cpio pass-through, busybox timing); 134+ tests under gawk/mawk/busybox awk; make test green. Commits 5507972..f02fd8a, settings 42e37cb via index, docs 8d5a7bd.
+3
View File
@@ -693,3 +693,6 @@ rules:
## 2026-11-04
- 2026-11-04 — 4b memory capture built on feature/memory-capture (mod, consumers, docs, noise 83 % → errorish filter; GATE 0 MET, verifier ECARTS(1) interactive half, security PASS ×3); interactive note check + merge pending user; 4c next.
- 2026-11-04 — 4b memory capture merged into develop (dfadf8a); live proof: note once after fix: commit, NEW failure survives /clear; 4c follow-up (earlier-session milestones) in TODO; 4c next.
## 2026-11-05
- 2026-11-05: extract-guard built on feature/extract-guard (hook, soft_deny, doctrine; verifier CONFORME, security PASS); live in settings working copy; 4c paused at plan r2; merge pending user.
+5
View File
@@ -1951,3 +1951,8 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s
- **Pattern**: before shipping a rule that fires on tool output, measure its noise: sonnet ports the rule to Python (`noise.py`, stdlib, read-only, `--seed`), replays 14 days of `~/.claude/projects/<repo>/*.jsonl` + `*/subagents/*.jsonl`, prints 30 redacted samples; the controller labels useful/noise. Result 4b: 83 % noise, concentrated in sub-agents (23/25) vs main loop (2/5); candidate tightenings (`probe`, `errorish`) measured on the WHOLE corpus (81 → 60 / 27) before the gate; the user picked one, amending a gated answer.
- **Context**: 4b Task 7, LRN-047 lineage; NOISE.md holds counts and shares only (contract check forbids `excerpt:`/`command:` lines); samples stay in the job tmp.
- **Apply**: a capture or injection rule ships with its measured noise share and the numbers of the alternatives; a port claims "1:1" only while the TS rule is frozen (ours drifted twice).
## LRN-262 — A shell-text guard is never complete: re-scan every quoted word, refuse unresolvable dests, soft_deny for intent (2026-11-05)
- **Pattern**: a guard over shell command TEXT is never complete; plan challenges kept finding forms (r1: quote chars used as segment delimiters cut a quoted destination off its option; r2: multi-line quoted scripts split into orphan lines, wrappers hiding carriers, ssh value options, heredoc owner = last command on the line, here-strings read as heredocs, command substitutions cutting argv). Ship narrow: re-tokenize EVERY quoted word holding a blank (no carrier list), run the detector from every watched tool word, refuse unresolvable destinations, and put intent in an `autoMode.soft_deny` line for what text cannot show.
- **Context**: extract-guard, feature/extract-guard 2026-11-05. awk traps found by the security gate: `index(substr(txt, i))` per quote/heredoc line = quadratic (1 MB → hook timeout → command RUNS, LRN-196); `RS="\001"` + `all = all $0` drops 0x01 bytes (comment desync); busybox awk slow on per-char appends (cap 64 KiB); the prefilter must run on a de-quoted copy or split tool names skip it. The accepted FP bit its author twice: a memory heredoc quoting a complete extraction command was refused, then the `<pkg> <dir>` placeholder too (angle brackets read as redirections) until placeholders were kept as words.
- **Apply**: any PreToolUse text guard: prefilter on a de-quoted copy, size cap before parsing, linear tokenizer (forward scans), timed flood tests under gawk + mawk + busybox awk, fail closed only past the prefilter, MISSES in the header + soft_deny as net; text bodies about the guarded command go through Write + --body-file, never a heredoc in the Bash call.
@@ -0,0 +1,33 @@
# CONTRACT — extract-guard
- date: 2026-11-04 | flow: feat | branch: feature/extract-guard (off develop 06d2576)
- status: active
## REQUEST (verbatim — IMMUTABLE)
on a eu un cas la ou on a extrait un paquet debian et ca a ecrase des binaires etc. voici le raport claude
[pasted incident report, verbatim essentials:] « Une règle dans ~/.claude/CLAUDE.md, sous « Destructive tools & data loss », à côté de la règle lftp. Texte proposé : Installer un paquet ou une archive sur une machine ou une VM : jamais d'extraction (dpkg -x, tar x, unzip, cp -r) vers /, /usr, /etc ou un autre répertoire système. Les distributions usr-merge ont /lib, /bin, /sbin et /lib64 en liens symboliques, et une archive qui contient ces chemins les remplace par de vrais dossiers. D'abord lister le contenu (dpkg -c, tar tf), puis extraire dans un dossier de travail et passer par PATH ou PYTHONPATH. Sans gestionnaire de paquets sur la cible, on le dit à l'utilisateur au lieu de bricoler. 2. Un hook PreToolUse sur Bash qui bloque ces commandes avant exécution. C'est le seul vrai garde-fou, puisqu'une règle écrite peut être oubliée ou mal appliquée. Il refuserait toute commande, y compris dans un ssh ou vaas-cli ssh, qui contient : dpkg -x ou dpkg-deb -x avec une destination / ou absente ; tar avec -C / ; unzip -d /. Cela passerait par la skill update-config. »
fais en sorte d'eviter ca a l'avenir en ajoutant au harnais
## CLARIFICATIONS
Pass A: request complete (outcome: such commands are refused before they run and the doctrine names the rule; scope: the harness = this repo's hooks, settings.json, CLAUDE.global.md).
Context: BLK-022 (open) — the general `hooks/guard-bash.sh` was withheld by the safety classifier; its spec `lib/tests/guard-bash.test.sh` (214 cases) SKIPs while the hook is absent. This guard is a separate, narrow hook so that spec stays untouched.
Pass B `[gated 2026-11-04]` (user: recommended options): deny, not ask (the user runs a real install with `! <command>`); watched commands = dpkg -x / dpkg-deb -x (long forms), tar extraction, unzip, cpio -i, plus recursive `cp` (-r/-R/-a); system roots = /, /usr, /etc, /bin, /sbin, /lib, /lib32, /lib64, /libx32, /boot, /opt, /var, /srv, /root, /sys, /proc, /dev (subdirectories included; /tmp, /home, /mnt, /media and relative paths pass); an unresolvable destination ($VAR, $(…), backtick) is refused.
Design gate `[gated 2026-11-04]` (after the plan challenge: r1 FATAL ×3, r2 FATAL(9)/FATAL(7)/CONCERNS(2); user: "Hook simple + soft_deny", vaas-cli "les deux formes"): one POSIX-awk scanner that re-tokenizes every quoted, `$(…)`, backtick and heredoc text (no carrier list) and runs a detector from every watched tool word; remote commands follow the local rules (relative or absent destination passes); plus an `autoMode.soft_deny` line in settings.json for the forms no static parser sees; `vaas-cli ssh <vm> -- <cmd>` and `vaas-cli ssh <vm> '<cmd>'` both covered; accepted false positive: a text containing a complete extraction command into a system dir. Ruling: matcher `Bash|Monitor` (push-guard precedent, BDR-112), FILE SCOPE gains templates/settings/SETTINGS.md and CHANGELOG.md (doc-sync).
Gate rulings `[gated 2026-11-05]` (proposed by the controller after GATE 1 ECARTS(2) and GATE 2 PASS with 4 MEDIUM; user approved both the SC2016 suppression and the cd inheritance: "Oui, les deux"): the test suite's `# shellcheck disable=SC2016` is authorized (the single-quoted forms are the commands under test; same line in guard-bash.test.sh and seven other suites); a quoted script inherits the caller's cd directory (a `bash -c` script runs in the caller's cwd), so `cd / && ssh vm "tar xf a"` is a stated false positive; a `( … )` subshell restores the directory at its end; glob and brace destinations (`*`, `?`, `[`, `{a,b}`) are unresolvable (refused); cpio copy-pass (`-p`) counts as an extraction; commands over 256 KiB that name a watched tool are refused as too large to check. Re-scan round `[gated 2026-11-05]` (user: "Oui"): the cap is 64 KiB (busybox awk timing), `$"…"` is a quote, tool names built by expansion (`t$'a'r`, `t${x}ar`, empty `$()`/backticks) are a stated MISS.
## ACCEPTANCE CRITERIA
1. A PreToolUse Bash hook refuses, before it runs, a command that extracts a package or archive into `/` or a system directory: `dpkg -x` / `dpkg-deb -x` (and their long forms) with such a destination; `tar` extracting with `-C` / `--directory` to one, or after a `cd` to one in the same command; `unzip -d` to one; including when the command sits inside `ssh … '<cmd>'`, `vaas-cli ssh … '<cmd>'` or `bash -c '<cmd>'`. The refusal names the rule and the safe path (list first, extract into a work dir, or let the user run it).
2. The same tools with a non-system destination (a relative path, `/tmp/x`, a `mktemp -d` path, the project dir) and listing forms (`dpkg -c`, `tar tf`, `unzip -l`) pass untouched; any other command passes silently.
3. The hook fails safe on its own errors per the push-guard precedent (missing jq: warn on stderr and allow), never prints on an allowed command, and is wired in settings.json `hooks.PreToolUse` (matcher `Bash`) committed through the git index without the uncommitted UI writes (LRN-253).
4. CLAUDE.global.md § "Destructive tools & data loss" holds the doctrine bullet (list first, work dir + PATH/PYTHONPATH, usr-merge reason, no package manager → tell the user), and the doctrine-citers census stays green.
5. A test suite drives the hook with deny and allow cases (each criterion-1 form, each criterion-2 form) and `make test` is green; shellcheck clean.
## FILE SCOPE
- hooks/extract-guard.sh (new), lib/tests/extract-guard.test.sh (new)
- settings.json (one PreToolUse entry + one autoMode.soft_deny line, through the index)
- CLAUDE.global.md (one bullet)
- README.md / USAGE.md / templates/settings/SETTINGS.md / CHANGELOG.md (doc-sync), .claude/tasks/plans/ (plan), this contract
@@ -0,0 +1,66 @@
# PLAN r3 — extract-guard (feat, contract .claude/tasks/contracts/2026-11-04-extract-guard-2214.md)
Branch `feature/extract-guard` off develop. Pass B and design gate `[gated 2026-11-04]`: deny; watched = extraction tools + recursive `cp`; wide system roots; unresolvable destination refused; design = "simple hook + soft_deny" (user, after r1 FATAL ×3 and r2 FATAL(9)/FATAL(7)/CONCERNS(2)); `vaas-cli ssh` in both forms (`vaas-cli ssh <vm> -- <cmd>` and `vaas-cli ssh <vm> '<cmd>'`); remote commands follow the local rules (a relative or absent destination passes); accepted false positive: a text that itself contains a complete extraction command into a system dir (write it `dpkg -x <pkg> <dir>` in prose).
Why simple: a static shell parser cannot be complete (r1/r2 found 30+ forms); `ssh`, `sudo`, `su`, `eval`, `… | bash` are already denied statically in settings.json; the auto-mode classifier reads intent, so a `soft_deny` line covers what the hook cannot see. The hook targets the incident shapes and their common variants, and states its MISSES.
PLAN:
[ ] hooks/extract-guard.sh — bash wrapper (≤ 60 lines, bash 3.2 safe: no arrays under `set -u`, no `mapfile`, no `declare -A`, no `${a[-1]}`) + one POSIX awk program (no gawk-only functions: no `gensub`, `asort`, `length(array)`, `\y`) that does all parsing and prints either nothing (allow) or one reason line (deny)
[ ] lib/tests/extract-guard.test.sh — deny/allow suite, timed flood cases, quiet corpus, plumbing, wiring assertion (run last)
[ ] settings.json — PreToolUse entry `{"matcher":"Bash|Monitor","hooks":[{"type":"command","command":"bash ~/.claude/hooks/extract-guard.sh","timeout":10}]}` after the push-guard group, AND one `autoMode.soft_deny` line (text below); index route (§ Wiring)
[ ] CLAUDE.global.md — doctrine bullet after the lftp bullet (text below)
[ ] (doc-sync) templates/settings/SETTINGS.md guardrail table row, CHANGELOG `[Unreleased]`
## Hook flow (bash wrapper)
1. jq or awk missing → one stderr line `extract-guard: <tool> missing, guard inactive`, exit 0.
2. `cmd=$(jq -r '.tool_input.command // empty')`; empty or unparseable → exit 0.
3. Prefilter: `printf '%s' "$cmd" | grep -qE '(^|[^[:alnum:]_.-])(dpkg|dpkg-deb|tar|bsdtar|gtar|unzip|cpio|cp)([^[:alnum:]_-]|$)' || exit 0`.
4. `reason=$(printf '%s' "$cmd" | awk -f <(the program) )` — the program text is a shell variable passed with `awk "$PROG"`; rc ≠ 0 → reason `extract-guard: refused: the checker failed on a command that names <first watched word>; run it yourself if it is safe: ! <command>` (fail closed only past the prefilter).
5. Non-empty reason → print the deny JSON with `jq -n --arg r "$reason" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$r}}'`, exit 0; else exit 0 silently. Exactly one JSON object (test: two violations in one command → `jq -s length` is 1).
## The awk program
- `scan(text, depth)`: tokenizes `text` into records and words; `depth > 3` with a watched word → deny `nesting too deep`.
- Tokenizer (adapted from hooks/push-guard.sh `simple_cmds` at fe7d5cd, the adaptations named in a comment): quotes removed with their content kept in the word, INCLUDING newlines (a newline inside quotes never ends a record); `\`+newline folded; records end at unquoted `;`, `&&`, `||`, `|`, `&` (not part of `>&`, `&>`, `2>&1`), newline, `(`, `)`; `<<<` is a redirection operator (no heredoc); `<<`/`<<-` reads a delimiter and the heredoc BODY text is passed to `scan(body, depth+1)` whatever command owns it; `$(…)` (balanced) and backticks: the inner text goes to `scan(inner, depth+1)` and the outer word keeps a literal `$` marker so a destination built from it is unresolvable; `#` at a word start (unquoted) starts a comment to end of line.
- Re-scan rule: every word that contains a blank or a newline (it came from quotes) is also passed to `scan(word, depth+1)` — no carrier list (covers `ssh … '…'`, `vaas-cli ssh … '…'`, `bash -c '…'`, `sudo sh -c "…"`, `timeout 9 ssh …`, `find -exec sh -c '…'`, multi-line scripts).
- Flood: more than 5000 records or 300 re-scans in total → deny `command too large to check`.
- Per record: drop redirection words (`>`, `>>`, `<`, `2>`, `&>`, `>&2`, `2>&1`, `>file`, `2>/dev/null`) and the word after a bare operator; drop find terminators `;`, `+`, `\;` and `{}`; track `cd`/`pushd` (options `-P -L --` skipped) → `DIR` (relative target joined to the previous `DIR`; empty `DIR` + relative → stays empty; `~`/`$HOME` targets → home; `cd -`, bare `cd`, `popd` → empty). `DIR` is per scan level (a nested scan starts with the caller's `DIR` and does not change it).
- For every word position k whose basename is a watched tool, run its detector on the words after k (this one rule covers wrappers `sudo`, `nice -n 10`, `stdbuf -oL`, `busybox`, `xargs`, `find -exec`, and argv-form remotes `vaas-cli ssh vm -- …`, `ssh vm sudo …`).
- Bundle = a word matching `^-[A-Za-z]+$`.
- Detectors (collect every destination; refuse if any is system or unresolvable):
- tar/bsdtar/gtar: extract when a bundle contains `x`, or the first word after the tool matches `^[A-Za-z]+$` and contains `x` (old style), or a word is `--extract` / `--get`; never when a bundle or the old-style word contains `t` or a word is `--list`. Destinations: `-C <d>`, `-C<d>`, a bundle ending in `C` takes the next word, `--directory <d>`, `--directory=<d>`.
- dpkg / dpkg-deb: a word `-x`, `-X`, `--extract`, `--vextract` (dpkg-deb also `-R`, `--raw-extract`); destination = the second non-option word after it; absent → refused.
- unzip: listing when a bundle contains `l`, `v`, `t`, `Z` or `z` → no verdict; destination `-d <d>`, `-d<d>`, a bundle ending in `d` takes the next word.
- cpio: extract when a bundle contains `i` and no `t`, or `--extract`; destination `-D <d>`, `-D<d>`, `--directory <d>`, `--directory=<d>`, a bundle ending in `D` takes the next word.
- cp: recursive when a bundle contains `r`, `R` or `a`, or `--recursive` / `--archive`; destination `-t <d>`, `-t<d>`, a bundle ending in `t` takes the next word, `--target-directory <d>`, `--target-directory=<d>`, else the last non-option word of the record.
- An extraction with no destination option → the destination is `DIR` when set, else no verdict (local and remote alike).
- `is_system(p)`: `~` / `~/…` / `$HOME` / `${HOME}` prefixes → replaced by `/HOME`; any other `$` or backtick → unresolvable; relative → joined to `DIR` when set, else not system; normalize (collapse `//`, drop `/.`, resolve `..`, trailing `/` stripped while length > 1); `/HOME` and below, `/var/tmp`, `/var/folders` and below → not system; system when `/` or under `/usr /etc /bin /sbin /lib /lib32 /lib64 /libx32 /boot /opt /var /srv /root /sys /proc /dev`.
- Reason text: `extract-guard: refused: <tool> writes into system directory <dest> (CLAUDE.md "Destructive tools & data loss"). List it first (dpkg -c, tar tf, unzip -l), run mktemp -d alone and extract into the literal path it prints, then use PATH or PYTHONPATH; a real system install is the user's: ! <command>`; unresolvable: `… destination <dest> cannot be checked; write the literal path`.
## soft_deny line (settings.json autoMode.soft_deny, appended)
`Extracting, unpacking or recursively copying a package or an archive into / or a system directory (/usr, /etc, /bin, /sbin, /lib*, /boot, /opt, /var, /srv, /root), on this machine or on a remote machine or VM (ssh, vaas-cli ssh, a script it runs): refuse; list the archive, extract into a work dir and use PATH or PYTHONPATH, or tell the user there is no package manager.`
## Doctrine bullet (CLAUDE.global.md, after the lftp bullet)
```
- Installing a package or an archive on a machine or a VM never extracts it
(`dpkg -x`, `tar x`, `unzip`, `cpio -i`, `cp -r`) into `/`, `/usr`, `/etc`
or another system directory: on usr-merge distributions `/bin`, `/sbin`,
`/lib`, `/lib64` are symlinks that an archive carrying those paths
replaces with real directories. List it first (`dpkg -c`, `tar tf`),
extract into a literal `mktemp -d` path and use PATH or PYTHONPATH; no
package manager on the target → say so to the user, never improvise.
`hooks/extract-guard.sh` refuses these commands.
```
## Wiring (LRN-253)
After the suite is green except its wiring assertion: `git show HEAD:settings.json > T`; `jq '<add the PreToolUse entry and the soft_deny line>' T > T2`; `jq -e` checks both are present in T2; `h=$(git hash-object -w T2)`; `git update-index --cacheinfo 100644,$h,settings.json`; commit. The working copy (UI writes kept) gets the same jq into a temp file, `jq -e` checked, `cp` over `settings.json` — only after the verifier and security gates pass (the hook goes live machine-wide through the `~/.claude` symlinks). Rollback: the same route with both removed. Then the wiring assertion runs green.
## Tests (lib/tests/extract-guard.test.sh), literal commands
Deny: `dpkg -x p.deb /`; `dpkg-deb --extract p.deb /usr`; `dpkg -x p.deb`; `dpkg -x p.deb \⏎/`; `tar -xzf a.tgz -C /usr`; `tar -xf a.tar -C "/usr"`; `tar -C /usr -xzf a.tgz`; `tar -z -xvf a.tgz -C /`; `tar xzf a.tgz -C/`; `tar -xvC / -f a.tar`; `tar -xf a.tar --directory=/etc`; `tar -C /tmp/w -C / -xf a.tar`; `tar -xzf a.tgz \⏎ -C /usr`; `cd / && tar xf a.tar`; `cd / && cd usr && tar xf a.tar`; `pushd /usr && unzip a.zip`; `unzip a.zip -d '/opt'`; `unzip -od /usr a.zip`; `cpio -idm -D /usr < a.cpio`; `cd / && cpio -vidm < a.cpio`; `cp -r build /opt/app`; `cp -r build /opt/app 2>/dev/null`; `cp -rt /usr/lib src`; `cp -a src "/usr/local/x"`; `find dist -exec cp -r {} /var/www/html \;`; `ssh vm 'dpkg -x p.deb /'`; `ssh -i k -p 2222 root@vm 'tar -xf /tmp/a.tar -C /'`; `vaas-cli ssh vm -- tar -xzf a.tgz -C /usr`; `vaas-cli ssh vm 'dpkg -x /tmp/p.deb /'`; `vaas-cli ssh vm "⏎set -e⏎cd /⏎tar xf /tmp/a.tar⏎"` (multi-line); `bash -c "cd /usr/lib && unzip a.zip"`; `sudo sh -c 'cd / && tar xzf /tmp/a.tgz'`; `timeout 600 vaas-cli ssh vm 'dpkg -x p.deb /'`; `ssh vm bash -s <<'EOF' 2>&1 | tail -5⏎tar -xf a.tar -C /⏎EOF`; `grep -q ok <<< "$x"⏎tar -xf a.tar -C /`; `tar -xf $(ls *.tar) -C /`; ``tar -xf `ls *.tar` -C /usr``; `out="$(vaas-cli ssh vm 'dpkg -x /tmp/p.deb /')"`; `tar -xf a.tar -C "$DEST"`; `tar -xf a.tar -C ~/../../usr`; `stdbuf -oL tar -xf a.tar -C /`; `busybox tar -xf a.tar -C /`; `for f in *.deb; do dpkg -x $f /; done`; two violations in one command (one JSON object); a 5001-record flood with one `tar` word (deny under 2 s).
Allow: `tar -C /tmp/x -xf a.tar`; `tar -cf /tmp/a.tar /usr`; `tar tf a.tar`; `tar -tvf a.tar -C /`; `tar -xf a.tar`; `tar -xf a.tar -C ~/x`; `tar -xf a.tar -C "$HOME/x"`; `tar -xf a.tar -C /var/folders/ab/T/tmp.X`; `tar -xf a.tar -C /var/tmp/w`; `dpkg -c p.deb`; `dpkg -R -i debs/`; `unzip -l a.zip`; `unzip -Z1 a.zip`; `cpio -itv < a.cpio`; `unzip a.zip -d build`; `cp a.txt /etc/hosts`; `cp -r src dist`; `cp --parents a /tmp/x`; `cp -r a b > /dev/null`; `grep -rn "dpkg -x" docs`; `echo "tar xf a"`; `vaas-cli ssh vm 'tar -xf a.tar -C /tmp/w'`; `vaas-cli ssh vm 'unzip a.zip -d build'`; `vaas-cli ssh vm 'command -v unzip || sudo apt-get install -y unzip'`; `sudo apt install tar xz-utils`; `git commit -m "doc: list an archive with tar tf before extracting"`; `bash ~/.claude/lib/memory.sh add learning --title "dpkg -x into a system dir breaks usr-merge" --body-file /tmp/b`; a quiet corpus of 20 ordinary commands (jq filters, awk scripts, a heredoc commit, `echo "a" "b"`, `ls /usr/lib | grep tar`) → silent rc 0; a 5000-line text without watched words → allow under 1 s; 299 `bash -c 'cp -r a b'` records → allow under 3 s.
Plumbing: jq missing (PATH shim) → rc 0 + one stderr line; deny output parses with `permissionDecision == "deny"`; allowed commands print nothing; the suite also runs the hook under `/bin/sh`-free paths only (the hook is invoked with `bash`); wiring assertion (last): committed settings.json holds the `Bash|Monitor` entry and the soft_deny line.
## MISSES (header comment)
A destination built at runtime outside the text (script file, Makefile, alias, variable set in an earlier call); option values swallowed by the "watched word anywhere" rule; old-style tar `C` letter (`tar xfC a.tar /usr`), getopt_long abbreviations (`--dir=`), `--one-top-level=`; archive members escaping a safe `-C` (`../../usr`, `-P`) — the doctrine's "list first" covers them; an extraction with no destination run from a remote shell whose cwd is a system dir. The soft_deny line is the net for these.
## Disposition
Honors BDR-095 (layer C static refusal), BDR-090 (soft_deny for what static rules miss; deny over inert ask), BDR-111/112 (deny shape, `Bash|Monitor` matcher, a ruling: push-guard precedent, the contract's "matcher Bash" read as the floor), BLK-022 (narrow hook; guard-bash spec untouched), BLK-026 (bash 3.2: logic in POSIX awk), LRN-253 + BDR-131 (index route, UI writes kept), LRN-196 (timeout 10), LRN-199 (quoted prose of ordinary commands only denied when it holds a complete extraction into a system dir: accepted FP), LRN-201 (timed flood tests), BDR-100 (bullet adds no heading). EVAL-057: the adapted tokenizer names push-guard fe7d5cd.
+1 -1
View File
@@ -20,7 +20,7 @@ claude-config/
├── update-all.sh # One-command update for all components
├── Makefile # Unified entry point: make install / doctor / update / test (make help)
├── plugins.lock.json # Version pinning for non-marketplace dependencies and vendored skills
├── hooks/ # Claude Code hooks: session start, statusline, RTK rewrite, ctx7 + design-toolchain reminders, attention notify, unpushed-work guard, manual-mode push guard, instruction-load log, code-limits line-width signal
├── hooks/ # Claude Code hooks: session start, statusline, RTK rewrite, ctx7 + design-toolchain reminders, attention notify, unpushed-work guard, manual-mode push guard, system-dir extraction guard, instruction-load log, code-limits line-width signal
├── githooks/ # Generated git hooks (pre-commit, post-commit, post-merge, reference-transaction), git's global core.hooksPath
├── .githooks/ # This repo's own copy of the same hooks
├── .claude/rules/ # This repo's project path rules (paths: frontmatter), loaded on Read of a matching file
+1
View File
@@ -14,6 +14,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project
- **model-router first-use confirmation**: `mods/model-router/routing.json` (tracked) is the single source of the phase table and of every skill and agent row, and keeps the decisions: `confirmed`, `changed` (`from`/`to`), `projects` exceptions keyed by the origin remote reduced to `host/path` (credentials and local paths never stored), and `ask`. The first use of a rowed typed skill, a rowed agent spawn or a main-loop phase declared through the `route` tool opens a dialog with context: the skill's description (first sentence of its `SKILL.md` frontmatter) or the agent's, the phase with its `about` line (a new field on each of the 12 phases) and the model id and effort the next step really runs on. A row offers Later, Keep or Change; a main-loop phase Later or Keep. Change asks the model (fable, opus, sonnet, haiku with their tier), then the effort among those the phases of that model use (skipped when there is only one), then Everywhere or This project only; the pair maps to an existing phase (rows stay phase names, the same phase counts as Keep, a pair no phase offers is added by hand as a new phase). A skill-row change toasts the model and effort it now runs on, with the `/route switch on` hint when the main loop holds back a downgrade; a free-text answer counts as Later. One dialog at a time, never in headless (`-p`) runs or inside a sub-agent. Only a dialog answer, `/route ask on|off` or `/route forget` (which takes decisions back; a changed row returns to its shipped phase, the frontmatter floors stay yours to realign) writes the file (serialized, 64 KiB cap, never created when absent); each write asks you to commit it from the config repo. `/route pending` lists unconfirmed rows and phases. Layers: routing.json < `~/.claude/model-router.json` (its `ask` wins); a project's `.claude/model-router.json` is never read. Tests: `mods/model-router/hooks/register.test.ts`.
- **model-router `/model` scope**: a `/model <name>` typed in the composer, or a pick in the `/model` picker, with a model the table knows asks where it applies. The picker's switch is held first (PreModelSwitch deny; the engine prints that a hook blocked it); a pick while another dialog is open is refused with `answer the open dialog first`. This project writes the full id as `model` into the project's `.claude/settings.local.json` (created if absent, refused through a link) and sets a sticky model route. This conversation sets the sticky route only. Everywhere runs the native `/model` (user `settings.json`). Both non-native answers drop the run slot and keep a sticky effort. With the picker's Default, an unknown name, a headless run or another origin, the native command runs with no question. A model chosen in that dialog always switches: it bypasses the cold-read caps and the `mainUpgrade` / `mainModelSwitch` flags, and while it is marked down or outside a known window it waits and the automatic chain decides. A native switch or `/clear` drops it; `/route model=` keeps the caps. Known limits: the `/config` Model row still writes user `settings.json`; a dialog never answered has no timeout. Tests: `mods/model-router/hooks/register.test.ts`.
- **Manual-push mode**: `git config gitflow.autopush false` (human-set) now stops every push the gitflow lib makes, not only the post-commit / post-merge hooks. `gitflow start` and `finish` branch, commit and merge locally and push nothing; `gitflow delete` leaves the `origin/` copy in place and prints `git push origin --delete <br>` for the user to run. `hooks/unpushed-guard.sh` stays silent at turn end in this mode and opens each session with one `ℹ manual push mode:` line counting the commits no remote holds across every local branch; an unparseable or unreadable `gitflow.autopush` value is treated as manual push mode too, and that line names it. `hooks/push-guard.sh` (PreToolUse, `Bash|Monitor`) refuses any `git push` Claude types while `gitflow.autopush` reads false in the session cwd or in a literal `-C`/`cd` directory the command names (global config counts outside a repo); the refusal tells the user to run it with `! git push`. It reads the mode through the same lib verb as every other reader and fails closed: an unparseable or unreadable value reads as manual, and an internal error, a missing `lib/gitflow.sh`, more than 20 distinct directory tokens in one command (capped before any token is classified), a `cd`/`-C` directory token mixing quoted and unquoted parts, or a payload jq cannot parse whose raw text looks like a push refuse the push (these pathological cases fire in auto mode too). Directory tokens are read as whole shell words, adjacent quoted segments and backslash escapes included. Once the text looks like a push, the command is split into simple commands (quotes, escapes, separators, heredoc bodies dropped) and a push must be git's own subcommand in one of them: `grep "git push"`, `git log -S "git push"`, `git config --get push.default`, `git stash push`, a heredoc quoting a push or a commit message naming one are allowed; `bash -c` scripts are re-checked, wrappers (`sudo`, `env`, `eval`, `xargs`, `timeout`, `git subtree`...) and assignments keep the text verdict. The misses listed in its header fall to a new `autoMode.soft_deny` rule that no request in the turn clears. The session banner adds `🔒 push : manual (autopush=false) — ! git push` when the key reads false, and `🔒 push : manual (autopush bad) — ! git push` when the value is invalid. Skills read the mode through a new lib verb, `bash ~/.claude/lib/gitflow.sh push-mode`: it prints `auto`, `manual` or `invalid` (rc 0) and names an invalid value on stderr (printable characters only, 64 at most). It is the one reader a skill may call, since the `git config` read of the key is denied to Claude. Skills push nothing on their own, except the `/release-candidate` tag in auto-push mode on an explicit go. Every "on origin" or "not pushed" line they print comes from `git rev-list --count origin/<br>..<br>` read after the fact, with the complete `! git …` command when something is left for the user to push. An invalid value (anything but unset, true or false, or a read that fails) is manual push mode for every reader and is named where it is read (see Fixed). Tests: `lib/gitflow-test.sh` T11b (push-mode verb), T18m and T18q blocks, `lib/tests/unpushed-guard.test.sh` T10-T16, `lib/tests/push-guard.test.sh` (98 checks).
- **extract-guard hook**: `hooks/extract-guard.sh` (PreToolUse, `Bash|Monitor`) refuses a package or archive extraction into `/` or a system directory (`/usr`, `/etc`, `/bin`, `/sbin`, `/lib*`, `/boot`, `/opt`, `/var`, `/srv`, `/root`, `/sys`, `/proc`, `/dev`; `/var/tmp` and `$HOME` stay free), after `dpkg -x` into `/` replaced the usr-merge `/bin` and `/lib` symlinks with real directories. Watched: `dpkg -x`, `dpkg-deb -x`/`-R`, `tar x` (`bsdtar`, `gtar` too), `unzip`, `cpio -i` and `-p`, recursive `cp`; the destination comes from `-C`/`--directory`, `unzip -d`, `cpio -D`, `cp -t` or the last argument, or from a `cd` before the command. Every quoted word holding a blank is re-scanned, so a script run through `ssh`, `vaas-cli ssh`, `bash -c`, `sudo sh -c` or `find -exec` is checked, as are `$(…)`, backticks and heredoc bodies. A destination it cannot resolve (`$VAR`, `$(…)`, a glob or brace) is refused, and so are a command over 64 KiB that names a watched tool, nesting deeper than three levels and an awk failure (fail closed). The refusal says to list the archive (`dpkg -c`, `tar tf`, `unzip -l`), extract into the literal path `mktemp -d` prints and use PATH or PYTHONPATH; a real system install is the user's to run with `!`. With jq, awk, grep, sed, tr or wc missing it warns once on stderr and allows. The misses listed in its header (a destination built outside the text, old-style `tar xfC`, archive members escaping a safe `-C`) fall to a new `autoMode.soft_deny` line. Doctrine bullet in `CLAUDE.global.md` § Destructive tools & data loss. Tests: `lib/tests/extract-guard.test.sh` (134 checks).
- **model-router prompt classifier**: a plain prompt typed in the composer (12 characters or more, not a slash command, not mid-turn, never under `-p` or in a sub-agent) that no keyword rule, skill, run slot, `/route` or floor covers is labelled by one call to the engine's small model (`design`, `analysis`, `coding`, `bookkeeping`, `chat`), bounded to 3 s. The label maps to plan, reflect, implement or apply and the turn takes that phase's route: its effort, and its model under the switch and the downgrade cap, never above the session model (an `ultrathink` floor raises the effort only, the guess's model holds); no dialog, no file write, gone at the end of the turn, replaced by any route call or typed skill, and dropped for that turn by a `/effort` typed between turns. Three failures in a row pause it for `cooldownMinutes` (one toast, `classifier: paused` in the status line). `"classify": false` in `~/.claude/model-router.json` and `/route classify on|off` turn it off; `/route show` prints `classify:`. The status line reads `route: classifier <phase>` and `/route verbose on` adds `(<phase>: classifier)`.
- **model-router cold-read caps**: both main-loop caps measure the cold read a switch costs, from a per-model record of main's last step, warm within the engine's prompt-cache TTL (`cache_ttl` 5m or 1h from main's model-switch events, 1 h before the first, kept across `/clear`; records cleared by `/clear` and `/route reload`), plus the submitted prompt the engine's usage may not count yet (code points / 3 of its text, context entries and a typed skill's body, added at the turn's first main step unless usage already grew by half of it; a `document` attachment blocks the switch for that step); `downgradeMaxTokens` (default 120000) joins `upgradeMaxTokens` (200000). A model-loaded helper skill inside a best-tier run moves effort only; main routed onto a model whose window the context outgrew returns to the session model. `/route show` prints `switch: on (downgrade, cap 120000 tokens cold, ttl 60 min)`, the status line shows ` · switch off` only when the switch is off, the skip line is logged once per cap crossing and the change toast names a cap hold. A built-in `general-purpose` agent that main spawns with no model while main sits below the session model starts on the session model instead of inheriting the lower one.
+8
View File
@@ -221,6 +221,14 @@ days of work never pushed.
- Claude never deploys and never runs a transfer or mirror tool (`lftp`,
`sftp`, `ftp`, `rsync --delete`): it writes or explains the runbook, the
user runs it. A test is a dev server on this machine, nothing more.
- Installing a package or an archive on a machine or a VM never extracts it
(`dpkg -x`, `tar x`, `unzip`, `cpio -i`, `cp -r`) into `/`, `/usr`, `/etc`
or another system directory: on usr-merge distributions `/bin`, `/sbin`,
`/lib`, `/lib64` are symlinks that an archive carrying those paths
replaces with real directories. List it first (`dpkg -c`, `tar tf`),
extract into a literal `mktemp -d` path and use PATH or PYTHONPATH; no
package manager on the target → say so to the user, never improvise.
`hooks/extract-guard.sh` refuses these commands.
- A destructive tool is never run "to see what it would do", not even on a
scratch tree: trace it by reading. If a run is unavoidable, the target is
a fresh `mktemp -d` path written literally in the same command, after a
+2 -1
View File
@@ -21,7 +21,8 @@ Not a collection of prompts — an operating layer on top of Claude Code:
post-commit and post-merge hooks (nothing pushed in a repo the user puts
in manual-push mode, where a PreToolUse hook also refuses Claude's own
`git push`), `main`/`develop` undeletable by a reference-transaction hook,
deny-first permission rules, secrets kept in `~/.claude/.env` and
package and archive extraction into system directories refused by a
PreToolUse hook (here or on a VM over ssh), deny-first permission rules, secrets kept in `~/.claude/.env` and
never in config files.
- **Templates and memory** seed every project with persistent registries
(decisions, learnings, blockers, journal, evals) — what a session
+462
View File
@@ -0,0 +1,462 @@
#!/usr/bin/env bash
# extract-guard.sh — PreToolUse (Bash|Monitor): refuse a package/archive
# extraction into / or a system directory (usr-merge incident: dpkg -x into
# / replaced /bin /lib symlinks with real dirs). Watched: dpkg -x, dpkg-deb
# -x/-R, tar x, unzip, cpio -i, recursive cp. System dirs: / /usr /etc /bin
# /sbin /lib* /boot /opt /var /srv /root /sys /proc /dev (not /var/tmp,
# /var/folders, $HOME). An unresolvable destination ($VAR, $(..)) is refused.
#
# Deny form: JSON on stdout, exit 0 (shape of hooks/push-guard.sh, BDR-111).
# Silent on every allowed command. jq, awk, grep, sed, tr or wc missing: one
# stderr warning, allow. A command that names no watched word (also with
# quotes and backslashes removed) never reaches awk; past that prefilter a
# command over 64 KiB or an awk failure denies (fail closed). The cap bounds
# the awk tokenizer, which rebuilds a word by concatenation.
#
# The parser is one POSIX awk program (bash 3.2 safe). Its tokenizer is
# adapted from push-guard.sh simple_cmds at fe7d5cd: newlines inside quotes
# stay in the word, redirections and `<<<` are words of their own, `$(..)`
# and backticks and heredoc bodies are queued for a scan of their own, and
# every quoted word holding a blank is re-scanned (no carrier list: ssh,
# vaas-cli ssh, bash -c, sudo sh -c, find -exec all fall out of it).
#
# MISSES: a destination built outside the text (script file, Makefile, alias,
# variable set in an earlier call); old-style tar `C` letter (tar xfC a
# /usr), --dir= abbreviations, --one-top-level=; a tool name built by $'\x74'
# escapes (the prefilter strips only quotes and backslashes) or by expansion
# (t$'a'r, t$''ar, t$"a"r, t${x}ar, an empty $() or backticks inside a
# name): mostly stopped by the prefilter, the soft_deny line is the net;
# archive members escaping a safe -C (../../usr, -P); a cd to a system dir in a
# remote shell then an extraction with no destination; option values read as
# tool words.
# ACCEPTED FALSE POSITIVES: text holding a complete extraction into a system
# dir, `dpkg -x <word>` with no directory, a glob or brace destination, and
# a quoted script run after a cd to a system dir (cd / && ssh vm "tar xf a":
# the script inherits the caller's directory; a ( .. ) subshell restores
# it). The autoMode soft_deny rule is the net.
set -u
for t in jq awk grep sed tr wc; do
command -v "$t" >/dev/null 2>&1 || {
echo "extract-guard: $t missing, guard inactive" >&2
exit 0
}
done
cmd=$(jq -r '.tool_input.command // empty' 2>/dev/null) || exit 0
[ -n "$cmd" ] || exit 0
SOH=$'\001'
WATCHED='(^|[^[:alnum:]_.-])(dpkg|dpkg-deb|tar|bsdtar|gtar|unzip|cpio|cp)([^[:alnum:]_-]|$)'
hit() { printf '%s' "$1" | grep -qE "$WATCHED"; }
# second look with quotes, backslashes and backslash-newline removed, so
# t'a'r, "t"ar, ta\<newline>r and $'tar' still reach the parser
flat=$(printf '%s' "$cmd" | tr '\n' '\001' | sed "s/\\\\$SOH//g" \
| tr -d "'\"\\\\")
hit "$cmd" || hit "$flat" || exit 0
IFS= read -r -d '' PROG <<'AWK' || true
function base(s) { sub(/^.*\//, "", s); return s }
function hasblank(w) { return index(w, " ") || index(w, "\t") || index(w, "\n") }
function deny(msg) { print msg; exit 0 }
function toobig() {
deny("extract-guard: refused: command too large to check; run it yourself if it is safe: ! <command> (CLAUDE.md § Destructive tools & data loss)")
}
function enqueue(t, d, dir) {
if (d > 3) {
if (t ~ WRE) deny("extract-guard: refused: nesting too deep to check a command that names an extraction tool; run it yourself if it is safe: ! <command> (CLAUDE.md § Destructive tools & data loss)")
return
}
if (++nenq > 300) toobig()
qn++; QT[qn] = t; QD[qn] = d; QDIR[qn] = dir
}
function endword() {
if (have) { nrw++; RW[nrw] = word; RQ[nrw] = wq }
word = ""; have = 0; wq = 0
}
function endcmd() { if (nrw) process(); nrw = 0 }
# closing quote q of the quote opened at k; n + 1 when unclosed
function qend(k, q, m, ch) {
for (m = k + 1; m <= n; m++) {
ch = substr(txt, m, 1)
if (q == "\"" && ch == "\\") { m++; continue }
if (ch == q) return m
}
return n + 1
}
# $( ... ) at i: balanced inner text queued, the word keeps a "$" marker
function subst( k, dp, ch) {
dp = 1; k = i + 2
while (k <= n && dp > 0) {
ch = substr(txt, k, 1)
if (ch == "'" || ch == "\"") k = qend(k, ch) + 1
else if (ch == "\\") k += 2
else { if (ch == "(") dp++; else if (ch == ")") dp--; k++ }
}
if (dp == 0) { enqueue(substr(txt, i + 2, k - i - 3), cdep + 1, DIR); i = k }
else { enqueue(substr(txt, i + 2), cdep + 1, DIR); i = n + 1 }
word = word "$"; have = 1
}
# backtick command substitution at i
function bq( k, ch) {
for (k = i + 1; k <= n; k++) {
ch = substr(txt, k, 1)
if (ch == "\\") { k++; continue }
if (ch == "`") break
}
enqueue(substr(txt, i + 1, k - i - 1), cdep + 1, DIR)
word = word "$"; have = 1; i = k + 1
}
function dquote( c, d) {
while (i <= n) {
c = substr(txt, i, 1)
if (c == "\"") { i++; return }
d = substr(txt, i + 1, 1)
if (c == "\\" && i < n && index("\"\\$`\n", d)) {
if (d != "\n") word = word d
i += 2
} else if (c == "$" && d == "(") subst()
else if (c == "`") bq()
else { word = word c; i++ }
}
}
# $'...' at i (ANSI-C quoting): content kept, \n \t \xHH \NNN decoded
function ansi( c, d) {
have = 1; wq = 1; i += 2
while (i <= n) {
c = substr(txt, i, 1)
if (c == "'") { i++; return }
if (c != "\\") { word = word c; i++; continue }
d = substr(txt, i + 1, 1); i += 2
if (d == "n") word = word "\n"
else if (d == "t") word = word "\t"
else if (d == "x" || d ~ /^[0-7]$/) word = word ansi_num(d)
else word = word d
}
}
# up to two more digits after \x (hex) or the octal digit d
function ansi_num(d, rad, left, v, dg) {
rad = (d == "x") ? 16 : 8; left = 2
v = (d == "x") ? -1 : d + 0
while (left > 0 && i <= n) {
dg = index("0123456789abcdef", tolower(substr(txt, i, 1)))
if (dg == 0 || dg > rad) break
v = (v < 0 ? 0 : v) * rad + dg - 1; i++; left--
}
return v <= 0 ? "" : sprintf("%c", v)
}
function quoted(c, j, d) {
if (c == "'") {
have = 1; wq = 1
j = qend(i, "'")
word = word substr(txt, i + 1, j - i - 1); i = j + 1
} else if (c == "\"") { have = 1; wq = 1; i++; dquote()
} else if (c == "`") bq()
else {
d = substr(txt, i + 1, 1)
if (i < n && d != "\n") { word = word d; have = 1; wq = 1 }
i += 2
}
}
# heredoc delimiter after << (quotes and backslashes removed)
function read_delim( q, d, ch) {
if (substr(txt, i, 1) == "-") i++
while (substr(txt, i, 1) == " " || substr(txt, i, 1) == "\t") i++
d = ""
while (i <= n) {
ch = substr(txt, i, 1)
if (index(" \t\n;&|()<>", ch)) break
if (ch == "'" || ch == "\"") {
q = ch; i++
while (i <= n && substr(txt, i, 1) != q) { d = d substr(txt, i, 1); i++ }
i++; continue
}
if (ch == "\\") { d = d substr(txt, i + 1, 1); i += 2; continue }
d = d ch; i++
}
hd[++nh] = d
}
# heredoc bodies start after the newline that ended the command line
function read_heredocs( k, e, ln, chk, body) {
for (k = 1; k <= nh; k++) {
body = ""
while (i <= n) {
for (e = i; e <= n && substr(txt, e, 1) != "\n"; e++) ;
ln = substr(txt, i, e - i); i = e + 1
chk = ln; sub(/^\t+/, "", chk)
if (chk == hd[k]) break
body = body ln "\n"
}
enqueue(body, cdep + 1, DIR)
}
nh = 0
}
# a redirection operator becomes a word of its own (fd prefix kept)
function redir( c, d, op) {
if (!(have && !wq && word ~ /^[0-9]+$/)) endword()
c = substr(txt, i, 1); d = substr(txt, i + 1, 1)
if (c == "&") { op = "&>"; i += 2; if (substr(txt, i, 1) == ">") { op = op ">"; i++ } }
else {
op = c; i++
if (c == ">" && (d == ">" || d == "|")) { op = op d; i++ }
else if (d == "&") {
op = op d; i++
while (i <= n && index("0123456789-", substr(txt, i, 1))) { op = op substr(txt, i, 1); i++ }
} else if (c == "<" && d == ">") { op = op d; i++ }
}
word = word op; have = 1; endword()
}
# length of an angle-bracket placeholder (<pkg>, <root-dir>) at i, else 0:
# no valid redirection has that shape: kept as an ordinary (quoted) word
function placeholder( k, ch) {
if (have || substr(txt, i, 1) != "<") return 0
if (substr(txt, i + 1, 1) !~ /^[A-Za-z]$/) return 0
for (k = i + 2; k <= n && k <= i + 41; k++) {
ch = substr(txt, k, 1)
if (ch == ">") break
if (ch !~ /^[A-Za-z0-9_.-]$/) return 0
}
if (substr(txt, k, 1) != ">") return 0
if (k < n && !index(" \t\n;|()&", substr(txt, k + 1, 1))) return 0
return k - i + 1
}
function op_item(c, pl) {
if ((pl = placeholder())) { word = substr(txt, i, pl); have = 1; wq = 1; i += pl; return }
if (c == "(") { endword(); endcmd(); SD[++sdn] = DIR; i++ }
else if (c == ")") { endword(); endcmd(); if (sdn > 0) DIR = SD[sdn--]; i++ }
else if (c == ";" || c == "|") { endword(); endcmd(); i++ }
else if (c == "&" && substr(txt, i + 1, 1) != ">") { endword(); endcmd(); i++ }
else if (c == "<" && substr(txt, i + 1, 2) == "<<") {
endword(); word = "<<<"; have = 1; endword(); i += 3
} else if (c == "<" && substr(txt, i + 1, 1) == "<") { endword(); i += 2; read_delim() }
else redir()
}
function token( c) {
c = substr(txt, i, 1)
if (c == "'" || c == "\"" || c == "\\" || c == "`") quoted(c)
else if (c == "$" && substr(txt, i + 1, 1) == "'") ansi()
else if (c == "$" && substr(txt, i + 1, 1) == "\"") { i++; quoted("\"") }
else if (c == "$" && substr(txt, i + 1, 1) == "(") subst()
else if (c == "\n") { endword(); endcmd(); i++; if (nh) read_heredocs() }
else if (c == " " || c == "\t") { endword(); i++ }
else if (c == "#" && !have) { while (i <= n && substr(txt, i, 1) != "\n") i++ }
else if (index(";|()<>&", c)) op_item(c)
else { word = word c; have = 1; i++ }
}
function scan(t, d, dir) {
txt = t; n = length(t); i = 1; cdep = d; DIR = dir
word = ""; have = 0; wq = 0; nrw = 0; nh = 0; sdn = 0
while (i <= n) token()
endword(); endcmd()
}
# absolute normalized path; "$" = unresolvable (also glob and brace); "" = relative without a cwd
function norm(p, nc, k, c, sp, out) {
if (p ~ /^~(\/|$)/) p = "/HOME" substr(p, 2)
else if (p ~ /^[$]HOME(\/|$)/) p = "/HOME" substr(p, 6)
else if (p ~ /^[$][{]HOME[}](\/|$)/) p = "/HOME" substr(p, 8)
if (substr(p, 1, 1) == "~" || index(p, "$") || index(p, "`")) return "$"
if (p ~ /[[*?]/ || p ~ /[{][^}]*(,|[.][.])[^}]*[}]/) return "$"
if (substr(p, 1, 1) != "/") {
if (DIR == "" || DIR == "$") return DIR
p = DIR "/" p
}
nc = split(p, parts, "/"); sp = 0
for (k = 1; k <= nc; k++) {
c = parts[k]
if (c == "" || c == ".") continue
if (c == "..") { if (sp > 0) sp--; continue }
stack[++sp] = c
}
out = ""
for (k = 1; k <= sp; k++) out = out "/" stack[k]
return out == "" ? "/" : out
}
# 1 system, 2 unresolvable, 0 fine
function is_system(p, q, nc) {
q = norm(p)
if (q == "$") return 2
if (q == "") return 0
if (q == "/") return 1
nc = split(q, parts, "/")
if (parts[2] == "HOME") return 0
if (parts[2] == "var" && (parts[3] == "tmp" || parts[3] == "folders")) return 0
return (parts[2] in SYS) ? 1 : 0
}
function track_cd( j) {
if (base(W[1]) == "popd") { DIR = ""; return }
if (base(W[1]) != "cd" && base(W[1]) != "pushd") return
j = 2
while (j <= nw && W[j] ~ /^(-P|-L|-e|-@|--)$/) j++
DIR = (j > nw || W[j] == "-") ? "" : norm(W[j])
}
# dest option at A[j]: -s <d>, -s<d>, bundle ending in s, --l <d>, --l=<d>
function dopt(j, s, l, w, wl) {
w = A[j]; DSKIP = 0
if (w ~ /^-[A-Za-z]+$/ && substr(w, length(w)) == s) { DV = A[j + 1]; DSKIP = 1; return 1 }
if (l != "") {
if (w == "--" l) { DV = A[j + 1]; DSKIP = 1; return 1 }
wl = "--" l "="
if (substr(w, 1, length(wl)) == wl) { DV = substr(w, length(wl) + 1); return 1 }
}
if (substr(w, 1, 2) == "-" s && length(w) > 2 && w !~ /^-[A-Za-z]+$/) { DV = substr(w, 3); return 1 }
return 0
}
function adddest() { D[++nd] = DV }
function det_tar( j, w, x, t) {
if (A[1] ~ /^[A-Za-z]+$/) { x = (A[1] ~ /x/); t = (A[1] ~ /t/) }
for (j = 1; j <= na; j++) {
w = A[j]
if (w == "--extract" || w == "--get") x = 1
else if (w == "--list") t = 1
else if (w ~ /^-[A-Za-z]+$/) { if (w ~ /x/) x = 1; if (w ~ /t/) t = 1 }
if (dopt(j, "C", "directory")) { adddest(); j += DSKIP }
}
ext = (x && !t)
}
function det_dpkg(b, j, w, seen, nn, n2) {
for (j = 1; j <= na; j++) {
w = A[j]
if (!seen) {
seen = (w == "-x" || w == "-X" || w == "--extract" || w == "--vextract" || (b == "dpkg-deb" && (w == "-R" || w == "--raw-extract")))
} else if (w !~ /^-/) { nn++; if (nn == 2) n2 = w }
}
if (!seen || nn == 0) return
ext = 1
if (nn >= 2) { DV = n2; adddest() } else absent = 1
}
function det_unzip( j, w, lst) {
for (j = 1; j <= na; j++) {
w = A[j]
if ((w ~ /^-[A-Za-z]+$/ && w ~ /[lvtzZ]/) || w ~ /^-Z/) lst = 1
if (dopt(j, "d", "")) { adddest(); j += DSKIP }
}
ext = !lst
}
# -i extracts; -p (copy-pass) writes into its first non-option word
function det_cpio( j, w, x, t, p, first) {
for (j = 1; j <= na; j++) {
w = A[j]
if (w == "--extract") x = 1
else if (w == "--pass-through") p = 1
else if (w ~ /^-[A-Za-z]+$/) {
if (w ~ /i/) x = 1; if (w ~ /t/) t = 1; if (w ~ /p/) p = 1
}
if (dopt(j, "D", "directory")) { adddest(); j += DSKIP; continue }
if (w ~ /^-[REFHIOM]$/) j++
else if (w !~ /^-/ && first == "") first = w
}
if (p && first != "") { DV = first; adddest(); ext = 1; return }
ext = (x && !t)
}
function det_cp( j, w, rec, last) {
for (j = 1; j <= na; j++) {
w = A[j]
if (w == "--recursive" || w == "--archive") rec = 1
else if (w ~ /^-[A-Za-z]+$/ && w ~ /[rRa]/) rec = 1
if (dopt(j, "t", "target-directory")) { adddest(); j += DSKIP; continue }
if (w !~ /^-/) last = w
}
if (!rec) return
if (nd == 0 && last != "") { DV = last; adddest() }
ext = (nd > 0)
}
function why(b, dest, kind) {
gsub(/\n/, " ", dest)
if (kind == 2)
return "extract-guard: refused: " b " destination " dest " cannot be checked; write the literal path, run mktemp -d alone and extract into the path it prints (CLAUDE.md § Destructive tools & data loss); a real install is the user's: ! <command>"
return "extract-guard: refused: " b " writes into system directory " dest " (CLAUDE.md § Destructive tools & data loss). List it first (dpkg -c, tar tf, unzip -l), run mktemp -d alone and extract into the literal path it prints, then use PATH or PYTHONPATH; a real system install is the user's: ! <command>"
}
function verdict(b, j, s) {
if (!ext) return
if (absent) deny(why(b, "(none)", 2))
if (nd == 0) { if (DIR == "") return; D[++nd] = DIR }
for (j = 1; j <= nd; j++) {
s = is_system(D[j])
if (s) deny(why(b, D[j], s))
}
}
function detect(b, k, j) {
na = 0; nd = 0; ext = 0; absent = 0
for (j = k + 1; j <= nw; j++) A[++na] = W[j]
A[na + 1] = ""
if ((work += na + 1) > 300000) toobig()
if (b ~ /^(tar|bsdtar|gtar)$/) det_tar()
else if (b == "dpkg" || b == "dpkg-deb") det_dpkg(b)
else if (b == "unzip") det_unzip()
else if (b == "cpio") det_cpio()
else det_cp()
verdict(b)
}
# one simple command: drop redirections, track cd, run each watched tool
function process( k, w, skip) {
if (++nrec > 5000) toobig()
nw = 0
for (k = 1; k <= nrw; k++) {
w = RW[k]
if (hasblank(w)) enqueue(w, cdep + 1, DIR)
if (skip) { skip = 0; continue }
if (!RQ[k] && (w ~ /^[0-9]*[<>]/ || w ~ /^&>/)) { skip = (w ~ BARE); continue }
if (w == "{}" || w == "+" || (RQ[k] && w == ";")) continue
W[++nw] = w
}
track_cd()
for (k = 1; k <= nw; k++) if (base(W[k]) in WATCH) detect(base(W[k]), k)
}
BEGIN {
RS = "\001"
split("usr etc bin sbin lib lib32 lib64 libx32 boot opt var srv root sys proc dev", sy, " ")
for (j in sy) SYS[sy[j]] = 1
split("dpkg dpkg-deb tar bsdtar gtar unzip cpio cp", wt, " ")
for (j in wt) WATCH[wt[j]] = 1
WRE = "(^|[^[:alnum:]_.-])(dpkg|dpkg-deb|tar|bsdtar|gtar|unzip|cpio|cp)([^[:alnum:]_-]|$)"
BARE = "^[0-9]*(>>|>[|]|>&|>|<&|<>|<<<|<|&>>|&>)$"
}
{ all = (NR > 1 ? all RS : "") $0 }
END {
scan(all, 0, "")
while (qh < qn) { qh++; scan(QT[qh], QD[qh], QDIR[qh]) }
}
AWK
size=$(printf '%s' "$cmd" | wc -c | tr -d ' ')
if [ "$size" -gt 65536 ]; then
reason="extract-guard: refused: command too large to check; run it yourself if it is safe: ! <command> (CLAUDE.md § Destructive tools & data loss)"
else
reason=$(printf '%s' "$cmd" | LC_ALL=C awk "$PROG" 2>/dev/null) || {
word=$(printf '%s' "$flat" | grep -oE 'dpkg-deb|dpkg|bsdtar|gtar|tar|unzip|cpio|cp' | head -n 1)
reason="extract-guard: refused: the checker failed on a command that names $word; run it yourself if it is safe: ! <command> (CLAUDE.md § Destructive tools & data loss)"
}
fi
[ -n "$reason" ] || exit 0
jq -cn --arg r "$reason" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$r}}'
exit 0
+217
View File
@@ -0,0 +1,217 @@
#!/usr/bin/env bash
# lib/tests/extract-guard.test.sh
# hooks/extract-guard.sh: denies an extraction into / or a system dir,
# silent on everything else. Also locks the settings.json wiring (last).
# shellcheck disable=SC2016 # single-quoted forms are the commands under test
set -u
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
H="$ROOT/hooks/extract-guard.sh"
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
pass=0; fail=0
check() { if [ "$2" = "$3" ]; then pass=$((pass+1)); else fail=$((fail+1));
printf 'FAIL %s: got[%s] want[%s]\n' "$1" "$2" "$3"; fi; }
OUT=""; RC=0
run() { # run <cmd>
OUT=$(printf '%s' "$1" \
| jq -Rs '{tool_name:"Bash",tool_input:{command:.}}' \
| bash "$H" 2>/dev/null); RC=$?
}
decision() { printf '%s' "$OUT" \
| jq -r '.hookSpecificOutput.permissionDecision // "none"' 2>/dev/null; }
deny() { run "$1"; check "deny[$1]" "$RC $(decision)" "0 deny"; }
allow() { run "$1"; check "allow[$1]" "$RC [$OUT]" "0 []"; }
# ── deny ──
deny 'dpkg -x p.deb /'
deny 'dpkg-deb --extract p.deb /usr'
deny 'dpkg -x p.deb'
deny $'dpkg -x p.deb \\\n/'
deny 'tar -xzf a.tgz -C /usr'
deny 'tar -xf a.tar -C "/usr"'
deny 'tar -C /usr -xzf a.tgz'
deny 'tar -z -xvf a.tgz -C /'
deny 'tar xzf a.tgz -C/'
deny 'tar -xvC / -f a.tar'
deny 'tar -xf a.tar --directory=/etc'
deny 'tar -C /tmp/w -C / -xf a.tar'
deny $'tar -xzf a.tgz \\\n -C /usr'
deny 'cd / && tar xf a.tar'
deny 'cd / && cd usr && tar xf a.tar'
deny 'pushd /usr && unzip a.zip'
deny "unzip a.zip -d '/opt'"
deny 'unzip -od /usr a.zip'
deny 'cpio -idm -D /usr < a.cpio'
deny 'cd / && cpio -vidm < a.cpio'
deny 'cp -r build /opt/app'
deny 'cp -r build /opt/app 2>/dev/null'
deny 'cp -rt /usr/lib src'
deny 'cp -a src "/usr/local/x"'
deny 'find dist -exec cp -r {} /var/www/html \;'
deny "ssh vm 'dpkg -x p.deb /'"
deny "ssh -i k -p 2222 root@vm 'tar -xf /tmp/a.tar -C /'"
deny 'vaas-cli ssh vm -- tar -xzf a.tgz -C /usr'
deny "vaas-cli ssh vm 'dpkg -x /tmp/p.deb /'"
deny $'vaas-cli ssh vm "\nset -e\ncd /\ntar xf /tmp/a.tar\n"'
deny 'bash -c "cd /usr/lib && unzip a.zip"'
deny "sudo sh -c 'cd / && tar xzf /tmp/a.tgz'"
deny "timeout 600 vaas-cli ssh vm 'dpkg -x p.deb /'"
deny $'ssh vm bash -s <<\'EOF\' 2>&1 | tail -5\ntar -xf a.tar -C /\nEOF'
deny $'cat <<< "$x"\ntar -xf a.tar -C /'
deny 'tar -xf $(ls *.tar) -C /'
deny 'tar -xf `ls *.tar` -C /usr'
deny 'out="$(vaas-cli ssh vm '"'dpkg -x /tmp/p.deb /'"')"'
deny 'tar -xf a.tar -C "$DEST"'
deny 'tar -xf a.tar -C ~/../../usr'
deny 'stdbuf -oL tar -xf a.tar -C /'
deny 'busybox tar -xf a.tar -C /'
deny 'for f in *.deb; do dpkg -x $f /; done'
deny 'cd "$work" && tar xf a.tar'
deny "bash -c \"ssh vm 'sh -c \\\"bash -c \\\\\\\"tar xf a -C /\\\\\\\"\\\"'\""
deny 'dpkg-deb -x p.deb /'
deny 'dpkg --extract p.deb /usr'
deny 'cd / && ssh vm "tar xf a"'
deny '(cd /; tar xf a.tar)'
deny 't'"'a'"'r xf a.tar -C /'
deny '"t"ar xf a.tar -C /'
deny $'ta\\\nr xf a.tar -C /'
deny $'$\'tar\' xf a.tar -C /'
deny '$"tar" xf a.tar -C /'
deny $'tar xf a.tar -C $\'\\x2f\''
deny $'echo \x01# ; tar xf a.tar -C /'
deny 'tar xf a.tar -C /u?r'
deny 'cp -r build /{usr,}'
deny 'cp -r build /op*'
deny 'cp -r build dist*'
deny 'find . | cpio -pdm /'
# two violations: exactly one JSON object
run 'dpkg -x a.deb / ; tar -xf a.tar -C /usr'
check two-violations "$(printf '%s' "$OUT" | jq -s length)" 1
# ── allow ──
allow 'tar -C /tmp/x -xf a.tar'
allow 'tar -cf /tmp/a.tar /usr'
allow 'tar tf a.tar'
allow 'tar -tvf a.tar -C /'
allow 'tar -xf a.tar'
allow 'tar -xf a.tar -C ~/x'
allow 'tar -xf a.tar -C "$HOME/x"'
allow 'tar -xf a.tar -C /var/folders/ab/T/tmp.X'
allow 'tar -xf a.tar -C /var/tmp/w'
allow 'tar -xf a.tar -C /home/u/proj/build'
allow 'cd /home/u/proj && unzip a.zip'
allow '(cd / && ls) && tar xf a.tar'
allow 'find . | cpio -pdm /tmp/w'
allow 'dpkg -c p.deb'
allow 'dpkg -R -i debs/'
allow 'unzip -l a.zip'
allow 'unzip -Z1 a.zip'
allow 'cpio -itv < a.cpio'
allow 'unzip a.zip -d build'
allow 'cp a.txt /etc/hosts'
allow 'cp -r src dist'
allow 'cp --parents a /tmp/x'
allow 'cp -r a b > /dev/null'
allow 'grep -rn "dpkg -x" docs'
allow 'echo "tar xf a"'
allow "vaas-cli ssh vm 'tar -xf a.tar -C /tmp/w'"
allow "vaas-cli ssh vm 'unzip a.zip -d build'"
allow "vaas-cli ssh vm 'command -v unzip || sudo apt-get install -y unzip'"
allow 'sudo apt install tar xz-utils'
allow 'git commit -m "doc: list an archive with tar tf before extracting"'
allow 'bash ~/.claude/lib/memory.sh add learning --title "dpkg -x into a system dir breaks usr-merge" --body-file /tmp/b'
# quiet corpus: ordinary commands, silent rc 0
while IFS= read -r c; do allow "$c"; done <<'EOF'
ls -la /usr/lib | grep tar
jq -r '.a[] | select(.x > 1)' f.json
awk '{ print $1 }' data.txt
echo "a" "b"
git status --short
git log --oneline -n 5
cat /etc/hosts
grep -rn "cp" src
make test suite=memory
npm run build && npm test
sed -n '1,20p' README.md
find . -name '*.sh' -exec shellcheck {} +
curl -sS https://example.org/x -o /tmp/x.json
mkdir -p /tmp/w && cd /tmp/w && ls
python3 -I -c 'print(1)'
docker ps --format '{{.Names}}'
ssh vm 'uname -a'
rsync -n a/ b/
cp a.txt b.txt
git commit -m "$(printf 'fix: a\n\nbody')"
EOF
run $'git commit -m "$(cat <<\'EOF\'\nfeat: x\n\nbody about archives\nEOF\n)"'
check quiet-heredoc-commit "$RC [$OUT]" "0 []"
# angle-bracket placeholders are words, real redirections are not
allow 'dpkg -x <pkg> <dir>'
allow 'tar -xf <archive> -C <dir>'
allow $'git commit -F - <<\'EOF\'\nnever run dpkg -x <pkg> <rootdir>\nEOF'
deny 'dpkg -x p.deb /'
deny 'cp -r a /opt/app >log'
deny 'dpkg -x <pkg> /'
deny 'dpkg -x <pkg> </dev/null'
# ── timed flood cases ──
flood=$(awk 'BEGIN { for (i = 1; i <= 5001; i++) print "echo " i; print "tar xf a" }')
SECONDS=0; run "$flood"; el=$SECONDS
check flood-5001-deny "$RC $(decision)" "0 deny"
check flood-5001-fast "$([ "$el" -le 2 ] && echo ok || echo "slow ${el}s")" ok
plain=$(awk 'BEGIN { for (i = 1; i <= 5000; i++) print "echo line " i }')
SECONDS=0; run "$plain"; el=$SECONDS
check plain-5000-allow "$RC [$OUT]" "0 []"
check plain-5000-fast "$([ "$el" -le 1 ] && echo ok || echo "slow ${el}s")" ok
many=$(awk "BEGIN { for (i = 1; i <= 299; i++) print \"bash -c 'cp -r a b'\" }")
SECONDS=0; run "$many"; el=$SECONDS
check rescan-299-allow "$RC [$OUT]" "0 []"
check rescan-299-fast "$([ "$el" -le 3 ] && echo ok || echo "slow ${el}s")" ok
over=$(awk "BEGIN { for (i = 1; i <= 301; i++) print \"bash -c 'cp -r a b'\" }")
run "$over"; check rescan-301-deny "$RC $(decision)" "0 deny"
big=$(awk 'BEGIN { for (i = 0; i < 7000; i++) print "echo tar xf" }')
SECONDS=0; run "$big"; el=$SECONDS
check cap-70k-deny "$RC $(decision)" "0 deny"
check cap-70k-reason "$(printf '%s' "$OUT" | jq -r \
'.hookSpecificOutput.permissionDecisionReason' | grep -c 'too large')" 1
check cap-70k-fast "$([ "$el" -le 2 ] && echo ok || echo "slow ${el}s")" ok
small=$(awk 'BEGIN { for (i = 0; i < 4000; i++) print "echo hello wor" }')
run "$small"; check cap-60k-silent "$RC [$OUT]" "0 []"
deep="bash -c \"bash -c 'bash -c \\\"bash -c \\\\\\\"tar xf a\\\\\\\"\\\"'\""
run "$deep"; check nesting-deny "$RC $(decision)" "0 deny"
check nesting-reason-names-rule "$(printf '%s' "$OUT" | jq -r \
'.hookSpecificOutput.permissionDecisionReason' \
| grep -c 'Destructive tools & data loss')" 1
# ── plumbing ──
BASH_BIN=$(command -v bash)
mkdir -p "$WORK/shim"
for t in awk grep head; do ln -s "$(command -v "$t")" "$WORK/shim/$t"; done
err=$(printf '%s' '{"tool_input":{"command":"tar xf a -C /"}}' \
| PATH="$WORK/shim" "$BASH_BIN" "$H" 2>&1 >"$WORK/o"); rc=$?
check nojq "$rc [$(cat "$WORK/o")] [$err]" \
"0 [] [extract-guard: jq missing, guard inactive]"
run 'tar xf a -C /'
check deny-json-shape "$(printf '%s' "$OUT" | jq -r \
'.hookSpecificOutput | .hookEventName + " " + .permissionDecision')" \
"PreToolUse deny"
check deny-reason-names-rule "$(printf '%s' "$OUT" \
| jq -r '.hookSpecificOutput.permissionDecisionReason' \
| grep -c 'Destructive tools & data loss')" 1
out=$(printf 'not json' | bash "$H" 2>/dev/null); check badjson "$? [$out]" "0 []"
out=$(printf '{}' | bash "$H" 2>/dev/null); check nocmd "$? [$out]" "0 []"
# ── wiring (last): settings.json carries the entry and the soft_deny line ──
S="$ROOT/settings.json"
check wiring-entry "$(jq -e '.hooks.PreToolUse[]
| select(any(.hooks[]; .command=="bash ~/.claude/hooks/extract-guard.sh"))
| .matcher=="Bash|Monitor" and .hooks[0].timeout==10' "$S" 2>&1)" true
check wiring-soft-deny "$(jq -r '[.autoMode.soft_deny[]
| select(startswith("Extracting, unpacking or recursively copying"))]
| length' "$S")" 1
printf 'PASS=%s FAIL=%s\n' "$pass" "$fail"; [ "$fail" -eq 0 ]
+12 -1
View File
@@ -448,6 +448,16 @@
"timeout": 10
}
]
},
{
"matcher": "Bash|Monitor",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/extract-guard.sh",
"timeout": 10
}
]
}
],
"Notification": [
@@ -570,7 +580,8 @@
"Undeclared node packages: `npx <pkg>`, `pnpm dlx` or `yarn dlx` of a package absent from the manifest and lockfile runs code fetched at call time; `npm install <name>` or `pnpm add <name>` adds a dependency the house rule requires naming first. Clear only when the user named the package in this turn.",
"Global npm installs: `npm install -g`, `npm i -g`, `npm add -g`, the `--global` spellings and a flag placed after the package name. A global package runs its install scripts with the user's rights on the whole machine. Before running one, state the package, its publisher, its age and download volume, whether it carries install scripts, and any known advisory. Clear only when the user named the package in this turn.",
"Publishing to the 21st.dev public catalog: `21st publish`, `publish-theme`, `publish-template`, `publish-gradient`, `publish-ascii`, `submit` and `resubmit` push a component, theme or template from this machine onto a public listing under the user's account; `21st edit`, `delete`, `withdraw`, `remove-from-catalog` and `21st profile set|upload` change or remove what is already published there. Retrieval and generation (`search`, `logo`, `get`, `add`, `generate`, `iterate`) are ordinary design work and pass. Clear only when the user asked to publish or change that specific item in this turn.",
"Static rule blind spots: the permission matcher cannot see `$(…)` in command position, a quoted literal argument (`echo \"SECRET\"`, `git push origin \":ref\"`), an inline interpreter (`python3 -c`, `python -c`, `node -e`, `perl -e`), a script piped into a shell (`… | bash -s`) or a sourced shell function (`source …/gitflow.sh; gitflow_finish`). A command that uses one of these shapes to reach an action a deny or ask rule names is that action: refuse it unless the user asked for that exact action in this turn."
"Static rule blind spots: the permission matcher cannot see `$(…)` in command position, a quoted literal argument (`echo \"SECRET\"`, `git push origin \":ref\"`), an inline interpreter (`python3 -c`, `python -c`, `node -e`, `perl -e`), a script piped into a shell (`… | bash -s`) or a sourced shell function (`source …/gitflow.sh; gitflow_finish`). A command that uses one of these shapes to reach an action a deny or ask rule names is that action: refuse it unless the user asked for that exact action in this turn.",
"Extracting, unpacking or recursively copying a package or an archive into / or a system directory (/usr, /etc, /bin, /sbin, /lib*, /boot, /opt, /var, /srv, /root), on this machine or on a remote machine or VM (ssh, vaas-cli ssh, a script it runs): refuse; list the archive, extract into a work dir and use PATH or PYTHONPATH, or tell the user there is no package manager."
],
"hard_deny": [
"$defaults",
+4 -1
View File
@@ -146,6 +146,7 @@ local trace, and the brief had authorized it. What holds now, by tier:
| Writing the human-only `gitflow.*` toggles: any `git … config` spelling, section remove/rename, `git -c`, the git config env overrides, Edit/Write of git config files | `permissions.deny` | Claude never flips the mode that binds it. Side effect: the trailing glob also matches the bare read, so Claude cannot read `gitflow.autopush` through `git config`; hooks and `lib/gitflow.sh` still do, and skills read it through `gitflow.sh push-mode`. |
| Merging: `git merge`, `bash`/`sh` `…gitflow.sh finish` | `permissions.ask` | `finish` runs only on an explicit human signal: one prompt per merge, and a declined prompt merges nothing. `git -C <dir> merge` and a sourced `gitflow_finish` escape the static rules; the sourced form falls to `autoMode.soft_deny` "Static rule blind spots". |
| Pushing in manual-push mode (`gitflow.autopush false`, or any invalid value) | `hooks/push-guard.sh` (PreToolUse) + `autoMode.soft_deny` | An `ask` would prompt, and a click would push. The hook denies the direct forms; the soft_deny covers scripted, aliased, subshell and sub-agent pushes, and a request in the turn does not clear it: the user types `! git push`. |
| Extracting or recursively copying a package or an archive into `/` or a system directory (`dpkg -x`, `dpkg-deb -x`/`-R`, `tar x`, `unzip`, `cpio -i`/`-p`, recursive `cp`), on this machine or on a VM through a quoted `ssh`, `vaas-cli ssh` or `bash -c` script | `hooks/extract-guard.sh` (PreToolUse) + `autoMode.soft_deny` | On usr-merge systems an archive carrying `/bin` or `/lib` replaces those symlinks with real directories. A static rule cannot read a destination inside a quoted remote script; the hook parses the command, re-scans every quoted script and refuses a destination it cannot resolve. The soft_deny covers what the text does not show (a script file, an alias, a variable set in an earlier call). |
| Destructive tool against a local path (variable, `~`, `..`, wildcard, outside cwd/tmp), even as a trace or a rehearsal a brief allows | `autoMode.hard_deny` | A pattern cannot express "the target resolves outside the project"; the classifier can. A sub-agent brief carries no user authority. |
| `docker rm -f`, bind mount outside cwd; discarding uncommitted work | `autoMode.soft_deny` | Recoverable or user-intended in the turn. |
@@ -154,7 +155,9 @@ a compound command; a tool nested in another command (`docker compose run …
lftp`) is not matched by a static rule. The PreToolUse guard hook that scans
the whole command, its executable spec in `lib/tests/guard-bash.test.sh`,
is not shipped yet (BLK-022). `hooks/push-guard.sh` scans the command text
for `git push` only, in manual-push mode (see below).
for `git push` only, in manual-push mode (see below), and
`hooks/extract-guard.sh` for an extraction into a system directory only,
quoted remote scripts included.
Push discipline lives in `lib/gitflow.sh`: `start` pushes the branch,
`finish` pushes each merge target, and the post-commit / post-merge hooks