Files
claude_mac/.claude/tasks/plans/2026-11-04-extract-guard-2214.md
T

13 KiB
Raw Blame History

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.