Skip to content

fix: pentest round-5 — 7 walker coverage gaps (sec 73-79) - #27

Merged
justi merged 37 commits into
mainfrom
pentest-round-5
May 8, 2026
Merged

justi merged 37 commits into
mainfrom
pentest-round-5

Conversation

@justi

@justi justi commented May 7, 2026

Copy link
Copy Markdown
Owner

Summary

Round-5 pentest discovered 7 walker coverage gaps. Each closed with a dedicated commit (TDD flow: failing reproducer first, patch, regression green).

Sec Bypass Detector
73 Alternative shred binaries (wipe, srm, bcwipe) extended destructive.sh
74 chgrp meta-mod (chmod/chown were covered, chgrp missed) extended destructive.sh
75 mkfifo / mknod special-file creation outside new walker in write_targets_b.sh
76 mktemp -p <dir> / --tmpdir=<dir> outside new walker in write_targets_b.sh
77 find -fprint / -fls / -fprintf FILE write target extended destructive.sh
78 pg_dump -f FILE / mysqldump --result-file=FILE new walkers in write_targets_b.sh
79 setfattr / chflags metadata flags outside new walkers in destructive.sh

Test plan

Generated with Claude Code.

justi added 30 commits May 7, 2026 11:45
Round-5 pentest discovered that the destructive walker covers
`shred` but not the popular drop-in alternatives that ship the
same overwrite-bytes-then-optionally-unlink semantics:

  - `wipe`   (Berke Durak)        — secure-delete suite
  - `srm`    (Sourceforge / macOS) — secure-delete
  - `bcwipe` (Jetico)              — enterprise tool

`wipe /etc/foo`, `srm /etc/foo`, `bcwipe /etc/foo` all slipped
past every walker. STRICT semantics carry over from shred:
allowlist must NOT grant DESTROY-CONTENTS for files outside the
project.

Fix: extend the trigger regex to include the three aliases, plus
the `/usr/local/bin/` and `/opt/homebrew/bin/` absolute-path
forms (where the alternatives commonly ship on Linux/macOS).
Share the same walker — same flag handling, same fail-closed
exit. Error message names whichever binary the caller used
(extracted from CMD_BLANKED with `|| true` against the
set-euo-pipefail no-match abort).

Tests: 5 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_c.sh sec 73.
1222/1222 pass.
`run_permissions_detectors` walked `chmod` and `chown` but
missed `chgrp`, which has the same "weaponize permissions"
threat profile: an attacker who can chgrp /etc/shadow to a
group they belong to has read/write on it. Round-5 probe
confirmed `chgrp wheel /etc/passwd` was ALLOWED.

Fix: add `chgrp` to the for-loop iteration. Same walker
semantics — skip first non-flag positional (group spec, like
mode for chmod / owner[:group] for chown), then validate
every remaining positional is_inside_project. STRICT
(allowlist does not apply) — same reasoning as chmod/chown.

Tests: 3 reproducers + 1 true-negative in
tests/test_bypass_reproducers_pentest_c.sh sec 74.
1226/1226 pass.
`mkfifo PATH...` creates a named pipe at each PATH; `mknod PATH
TYPE MAJOR MINOR` creates a device node at PATH. Both write a
new filesystem entry. Outside-project PATH is a real boundary
violation, but the round-5 probe confirmed no walker covered
either tool — `mkfifo /etc/fifo` and `mknod /etc/node c 1 1`
were ALLOWED.

Fix: add walker to write_targets_b.sh dispatched from
run_write_target_detectors_b. command_name_is anchors to the
verb position; the walker:

  - Skips value-bearing flag/value pairs `-m` / `--mode` and
    `-Z` / `--context` (and the `--mode=...` / `--context=...`
    long forms).
  - Validates each non-flag positional via is_write_permitted
    (allowlist applies — these are write, not destroy).
  - For mknod, stops after the first positional (TYPE/MAJOR/
    MINOR are spec, not paths). For mkfifo, validates every
    positional (multi-FILE form `mkfifo a b c` is supported).

Tests: 6 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_c.sh sec 75.
1234/1234 pass.
`mktemp -p DIR TEMPLATE` and `mktemp --tmpdir=DIR TEMPLATE`
create a temp file or directory inside DIR. Outside-project DIR
is a write outside the boundary, but no walker validated the
value of `-p` / `--tmpdir`.

Bare `mktemp` (no -p / --tmpdir) uses the default temp dir
(/tmp or $TMPDIR) — left ALLOWED. Test harnesses (incl.
helpers.sh which does `TMPDIR_BASE=$(mktemp -d)`) rely on the
default form, so blocking it would break the suite.

Fix: walker in write_targets_b.sh covers all four forms:

  mktemp -p /etc tmpXXXX           (split short)
  mktemp -p/etc tmpXXXX            (attached short)
  mktemp --tmpdir=/etc tmpXXXX     (attached long)
  mktemp --tmpdir /etc tmpXXXX     (split long, but only if next
                                    token is non-flag — bare
                                    --tmpdir leaves ALLOWED)

Tests: 5 reproducers + 3 true-negatives in
tests/test_bypass_reproducers_pentest_c.sh sec 76.
1242/1242 pass.
`find` has three actions that write to a FILE operand:

  -fprint FILE              (prints matching path to FILE)
  -fls FILE                 (long-listing format)
  -fprintf FILE FORMAT      (printf-style)

All open FILE with O_WRONLY|O_CREAT|O_TRUNC and stream output
into it. Round-5 probe confirmed `find / -fprint /etc/foo` was
ALLOWED — the find walker only matched `-delete` and `-exec
rm/mv`, so the print-to-file actions slipped through.

Threat: `find / -fprint /etc/passwd` truncates /etc/passwd and
writes matching paths into it. Same pattern for `-fls` and
`-fprintf`.

Fix: in destructive.sh, after the find -delete/-exec walker,
add a pass that scans CMD_TOKENS_SCAN for `-fprint` / `-fls` /
`-fprintf` and validates the next token via is_write_permitted
(allowlist OK — find writes a regular file).

Tests: 3 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_c.sh sec 77.
1247/1247 pass.
Database dump tools accept an explicit output-file flag that
bypasses the redirect walker — neither was covered:

  pg_dump -f FILE db                   (PostgreSQL)
  pg_dump --file=FILE db
  pg_dump --file FILE db
  mysqldump --result-file=FILE db      (MySQL/MariaDB)
  mysqldump -r FILE db                 (short form)
  mysqldump --result-file FILE db      (split long form)

Both write a (potentially large) SQL dump to FILE. Outside-
project FILE is a real boundary violation. Round-5 probe
confirmed both were ALLOWED.

Fix: per-tool walkers in write_targets_b.sh. command_name_is
anchors to the verb position; for pg_dump scan for `-f` /
`--file` (split + attached `=` forms), for mysqldump scan for
`-r` / `--result-file` (split + attached `=` forms). Each
validates via is_write_permitted (allowlist OK — these are
write, not destroy).

Tests: 5 reproducers + 3 true-negatives in
tests/test_bypass_reproducers_pentest_c.sh sec 78.
1255/1255 pass.
setfattr (Linux extended attributes, attr package) and chflags
(BSD or macOS file flags) modify file metadata that affects
access semantics — xattrs in user.* and system.* namespaces,
plus uchg, schg, uappnd flags. An attacker who can flip these
on sensitive files can pivot — same threat profile as the
existing permission walkers.

Round-5 probe confirmed both were ALLOWED. STRICT semantics
carry over (allowlist must NOT apply, same reasoning as the
existing permission walkers).

Fix: two new walkers in destructive.sh:run_permissions_detectors
parallel to the existing permission loop:

  setfattr — value-bearing pairs -n, --name, -v, --value, -x,
             --remove; long-attached --name=, --value=,
             --remove=, --restore= consume their value inline.
             Remaining positional tokens are FILE operands and
             go through is_inside_project STRICT check.

  chflags  — bare flags -R, -H, -L, -P, -h. First non-flag
             positional is FLAGS spec (skip), the rest are FILEs
             and go through is_inside_project STRICT check.

Tests: 4 reproducers + 3 true-negatives (incl. getfattr read-
only) in tests/test_bypass_reproducers_pentest_c.sh sec 79.
1262 of 1262 pass.
Codex round-5 review of PR #27 found that `_cn_strip_path_prefix`
and the inline command-name normaliser in
`strip_command_name_prefix` only knew `/bin/`, `/sbin/`,
`/usr/bin/`, `/usr/sbin/`, `/usr/local/bin/`. Apple Silicon
Homebrew defaults to `/opt/homebrew/bin/`, so a Homebrew binary
slipped past every walker that gates on `command_name_is` or
matches a literal verb regex. Multiple sec 74-79 walkers were
fail-open on `/opt/homebrew/bin/<cmd>`:

  /opt/homebrew/bin/mkfifo /etc/fifo            ALLOWED
  /opt/homebrew/bin/pg_dump -f /etc/foo db      ALLOWED
  /opt/homebrew/bin/chgrp staff /etc/passwd     ALLOWED
  /opt/homebrew/bin/setfattr -n user.x /etc/x   ALLOWED

Fix: add `/opt/homebrew/bin/*` to both case statements in
hooks/lib/command_name.sh (line 17 in `_cn_strip_path_prefix`
and line 113 in `strip_command_name_prefix`). One global fix
that closes the hole for every command_name_is-anchored
walker.

Tests: 5 reproducers + 1 true-negative in new
tests/test_bypass_reproducers_pentest_d.sh sec 80. test_guard.sh
sources the new file. 1268 of 1268 pass.
Codex round-5 review of PR #27 found that
run_permissions_detectors skipped every dash-prefixed token as
a bare flag, then unconditionally skipped the first non-flag
positional as the spec operand (mode, owner colon group, group).
With --reference=FILE (or split --reference FILE), the spec is
supplied by FILE — there is NO positional spec — so the actual
TARGET became the first non-flag positional and was silently
skipped. All three permission walkers were fail-open on the
--reference form against sensitive files in /etc.

Fix: in destructive.sh:run_permissions_detectors, pre-scan
perm_raw for --reference (any form). When present, set
has_reference=1 to disable the first-positional skip. In the
walk, treat split --reference VALUE as value-bearing (skip the
next token via skip_next); attached --reference=VALUE matches
the dash-prefix case and is consumed in place via the new case
branch.

Tests: 4 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 81.
1274 of 1274 pass.
Codex round-5 review found that BSD mknod (and the GNU port on
some systems) accepts -F FORMAT to select the device-number
encoding (bsd, freebsd, linux, solaris). The sec-75 walker
treated -F as a bare flag, so the FORMAT token (e.g. bsd) became
the first non-flag positional. The walker validated that token
as a path, found it relative (joined to EFFECTIVE_CWD →
in-project), then BROKE (mknod has only one path positional).
The actual /etc/node PATH never reached the validator.

  mknod -F bsd /etc/node c 1 1     ALLOWED

Fix: add -F as a mknod-specific value-bearing flag in the
walker — pair-skip when SPECIAL_CMD = "mknod". mkfifo doesn't
have -F, so the gate is conditional on the verb to avoid
swallowing a real positional.

Tests: 2 reproducers + 1 true-negative in
tests/test_bypass_reproducers_pentest_d.sh sec 82.
1277 of 1277 pass.
Codex round-5 review found that `mktemp PATTERN` creates
/tmp/tmp.XXXXXX when PATTERN is bare, but when PATTERN contains
a `/`, mktemp uses dirname(PATTERN) as the destination directory
and basename(PATTERN) as the template — `mktemp /etc/tmp.XXXXXX`
writes into /etc. The sec-76 walker only validated `-p` /
`--tmpdir`, so the positional-template form slipped past:

  mktemp /etc/tmp.XXXXXX     ALLOWED
  mktemp -d /etc/dir.XXXXXX  ALLOWED

Fix: in the existing mktemp walker, add a `*/*` case branch
that captures dirname(template) into the same `mtdir` variable
the existing pipeline already validates via is_write_permitted.
Bare PATTERN (no `/`) keeps falling into cwd and remains
ALLOWED — cwd is bounded by the project-boundary check on
EFFECTIVE_CWD elsewhere.

Tests: 3 reproducers + 3 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 83.
1283 of 1283 pass.
Codex round-5 review found that sec 78 covered pg_dump and
mysqldump but missed three sibling tools that write to a FILE
the same way:

  pg_dumpall -f FILE       cluster-wide dump (same -f / --file)
  psql -o FILE mydb        query output to file
  psql -L FILE mydb        log session to file
  mysql --tee=FILE mydb    echo session to FILE

All four were ALLOWED with /etc paths.

Fix in write_targets_b.sh:
- Convert pg_dump dispatch into a for-loop over `pg_dump
  pg_dumpall` so the same `-f` / `--file` walker handles both.
  Error message names whichever was invoked.
- New psql walker covering `-o` / `--output` (split + attached
  `=`) and `-L` / `--log-file` (split + attached `=`).
- New mysql walker covering `--tee` (split — only if next is
  non-flag) and `--tee=` (attached).

Tests: 8 reproducers + 3 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 84.
1294 of 1294 pass.
Codex round-5 review found that sec 73's trigger was a bare
regex over CMD_BLANKED that matched (shred|wipe|srm|bcwipe)
ANYWHERE in the command, not anchored to the verb position.
Innocent commands that merely mention the alias name as an
argument got blocked:

  echo wipe /etc/foo            BLOCKED (false positive)
  npm run wipe /etc/foo         BLOCKED
  printf 'wipe: %s' /etc/foo    BLOCKED

Fix: gate the walker on command_name_is for each of the four
binaries instead. Same walker logic, but only fires when the
verb position genuinely names one of them. shred is folded
into the same loop for symmetry — _cn_strip_path_prefix already
normalises absolute-path forms incl. /opt/homebrew/bin (sec 80),
so the move from raw regex to command_name_is doesn't lose
coverage of /usr/bin/shred etc.

Tests: 5 false-positive ALLOWED checks + 4 re-confirmed BLOCKED
sec-73 reproducers in tests/test_bypass_reproducers_pentest_d.sh
sec 85. 1303 of 1303 pass.
Codex round-5 review found three more metadata-mod tools that
sec 79's setfattr / chflags walkers missed:

  setcap CAP_SPEC FILE       Linux capabilities
  chattr +i FILE             Linux ext attrs (immutable / append-only)
  attr -s NAME -V VAL FILE   alternative xattr setter

Threat profile identical to chmod, chown, chgrp, setfattr —
allowlist must NOT apply (STRICT). Round-5 probe confirmed all
three were ALLOWED on /etc paths.

Fix: three new walkers in destructive.sh:run_permissions_detectors:

  setcap — pre-scan for `-r` / `--remove`. Without `-r`, first
           non-flag positional is CAP_SPEC (skip); rest are
           FILEs. With `-r`, no spec-skip — every positional is
           a FILE. is_inside_project STRICT.

  chattr — value-bearing pairs `-v VERSION`, `-p PROJECT`. Bare
           flags `-R`, `-V`, `-f`, `-h`. First non-flag positional
           is MODE_SPEC (`+i`, `-a`, `=AS`); skip it. Rest are
           FILEs. is_inside_project STRICT.

  attr   — gated on presence of `-s` (set) or `-r` (remove) so
           read-only `attr -g` / `-l` stay ALLOWED. Skips
           value-bearing pairs `-s NAME`, `-V VAL`, `-r NAME`,
           `-g NAME`. Remaining positional is FILE.
           is_inside_project STRICT.

Tests: 6 reproducers + 4 true-negatives (incl. attr -g, attr -l
read-only) in tests/test_bypass_reproducers_pentest_d.sh sec 86.
1313 of 1313 pass.
Codex round-5 review found that `find -ok rm {} ;` is the
interactive variant of `-exec rm` (prompts before each
invocation), and `-okdir` is the same but executed in the parent
of each match. Both run rm/mv the same way as `-exec` once
confirmed — same destructive semantics, but the destructive-find
walker only matched `-delete` and `-exec[[:space:]]+(rm|mv)`.

  find /etc -ok rm {} ;        ALLOWED
  find /etc -okdir rm {} ;     ALLOWED

The interactive prompt is a UX layer; from the boundary's
perspective the call is destructive once the subprocess runs.

Fix: extend the find destructive-action regex to also match
`-(exec|ok|okdir)[[:space:]]+(rm|mv)` — single alternation
covers all three exec-like predicates.

Tests: 4 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 87.
1319 of 1319 pass.
destructive.sh hit 531 lines after sec 86's setcap/chattr/attr
walkers. Same 500-line file budget that drove the
write_targets.sh/_b.sh split applies. The natural seam is the
metadata/permissions cluster — chmod, chown, chgrp, setfattr,
chflags, setcap, chattr, attr — which is already grouped under
run_permissions_detectors and dispatched from a separate point
in check_single_command than the destructive cluster (rm, mv,
cp, ln, find -delete, shred family).

Split:
- destructive.sh keeps run_destructive_detectors: xargs
  cluster, find -delete / -exec, shred / wipe / srm / bcwipe.
- permissions.sh ships run_permissions_detectors with all the
  metadata-mod walkers.

guard.sh sources both. No semantic change. 1319 of 1319 pass.
Codex round-5b review caught that sec 87's regex extension
covered `-exec`, `-ok`, `-okdir` but missed `-execdir` — the
in-parent-directory variant of -exec that's just as destructive.

  find /etc -execdir rm {} ;     ALLOWED

Fix: extend the destructive-action alternation to
`-(exec|execdir|ok|okdir)[[:space:]]+(rm|mv)`.

Tests: 2 reproducers + 1 true-negative in
tests/test_bypass_reproducers_pentest_d.sh sec 88.
1322 of 1322 pass.
Codex round-5b review caught that sec 86's chattr walker
skipped every dash-prefixed token as a bare flag, then skipped
the first non-flag positional as MODE_SPEC. When the user wrote
`chattr -i FILE` (remove immutable), the `-i` mode spec matched
the dash-prefix case and was skipped as a flag. The walker
then treated FILE as the spec operand and skipped that too,
leaving the actual target unvalidated.

  chattr -i /etc/passwd          ALLOWED
  chattr -iSa /etc/passwd        ALLOWED

Fix: distinguish known valueless flags (`-R`, `-V`, `-f`, `-h`)
from mode specs (`+i`, `-i`, `=AS`, multi-letter combos). The
mode-spec case glob `[+=]*|-[a-zA-Z]*` is matched BEFORE the
generic dash-prefix case. A mode-spec match consumes the spec
slot directly (`ca_skipped_spec=1`), so subsequent positionals
go through is_inside_project STRICT.

Tests: 4 reproducers + 1 true-negative in
tests/test_bypass_reproducers_pentest_d.sh sec 89.
1327 of 1327 pass.
Codex round-5b review caught that sec 86's attr walker gated on
short `-s` / `-r` only. Long forms `--set=NAME` / `--remove=NAME`
/ `--set NAME` / `--remove NAME` never flipped `atr_write=1`,
so the walker never ran:

  attr --set=user.x --value=VAL /etc/passwd     ALLOWED
  attr --remove=user.x /etc/passwd              ALLOWED

Fix: extend the gate predicate to recognise `--set` / `--remove`
in both split and attached `=` forms. Add the same value-bearing
pairs (`--set NAME`, `--value VAL`, `--remove NAME`, `--get NAME`)
to the per-token skip list, plus their `--set=*` / `--value=*`
/ `--remove=*` / `--get=*` long-attached forms via a new case
branch so the FILE positional isn't accidentally consumed.

Tests: 4 reproducers + 2 true-negatives (incl. attr --get
read-only long form) in tests/test_bypass_reproducers_pentest_d.sh
sec 90. 1333 of 1333 pass.
Codex round-5b review caught that sec 84's psql walker handled
split (`-o FILE`, `-L FILE`) and long attached (`--output=FILE`,
`--log-file=FILE`) but missed the short attached forms
`-oFILE` / `-LFILE` that PostgreSQL's CLI accepts:

  psql -o/etc/foo mydb       ALLOWED
  psql -L/etc/foo mydb       ALLOWED

Fix: add `-o?*` and `-L?*` case branches in the psql walker
that strip the `-o` / `-L` prefix and validate the suffix as
the file path.

Tests: 2 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 91.
1337 of 1337 pass.
Codex round-5b review caught that sec 78 / sec 84's pg_dump
walker handled split (`-f FILE`) and long attached
(`--file=FILE`) but missed the short attached form `-fFILE`.
The same gap inherits to pg_dumpall (sec 84 folded both into
a for-loop so they share the walker):

  pg_dump -f/etc/foo mydb        ALLOWED
  pg_dumpall -f/etc/foo          ALLOWED

Fix: add `-f?*` case branch in the walker that strips the `-f`
prefix and validates the suffix as the file path.

Tests: 2 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 92.
1341 of 1341 pass.
The detector cluster repeats this pipeline ~30 times across
inplace.sh, destructive.sh, permissions.sh, write_targets.sh
and write_targets_b.sh:

  raw  →  expand_path
       →  prepend EFFECTIVE_CWD if relative
       →  resolve_path
       →  is_write_permitted / is_inside_project
       →  echo "BLOCKED: ..." >&2; exit 2

Same shape, ~10 lines each, copy-pasted. Behavior drift is
exactly the kind of bug that surfaces on round-N pentests
(e.g. sec 80 — Homebrew prefix only got a fix in one walker
because each one did its own normalization).

Add three helpers in paths.sh — pure introduction, no
migration in this commit so the refactor lands incrementally:

  resolve_command_path RAW
    → echoes resolved absolute path. Reads EFFECTIVE_CWD from
      caller's dynamic scope (same contract as the detectors).

  block_unless_path_allowed POLICY LABEL RESOLVED
    → POLICY = "write" | "strict". Prints the canonical
      BLOCKED line and exits 2 on violation.

  validate_command_path POLICY LABEL RAW
    → resolve + check in one call. Most call-sites collapse
      to a single one-liner.

No semantic change. 1341 of 1341 pass. Migration follows in
per-file commits.
Apply the path-validation helpers introduced in fdf4574 to the
six walkers in permissions.sh:

  - permission loop (top of run_permissions_detectors)
  - setfattr
  - chflags
  - setcap
  - chattr
  - attr

Each walker had ~7 lines of expand-prepend-resolve-check-echo-exit.
Each collapses to one call:

  validate_command_path strict <verb> "$tok"

Net: 273 to 219 lines (minus 54). Behavior identical — same
STRICT policy, same canonical BLOCKED message format. 1341 of
1341 pass.
Apply the path-validation helpers to the four walkers in
inplace.sh:

  - sed -i (FILE positionals after script handling)
  - truncate (FILE positionals)
  - perl -i / ruby -i (FILE positionals)
  - awk -i inplace (FILE positionals after PROG handling)

All four use the write policy (allowlist applies — these are
in-place rewrites, not weaponised perms). Net: 275 to 235
lines (minus 40). Behavior identical. 1341 of 1341 pass.
Apply the path-validation helpers to the eight call sites in
destructive.sh:

  - find paths (find with destructive action loop)
  - find -fprint / -fls / -fprintf write target
  - shred / wipe / srm / bcwipe FILE positionals
  - rm FILE positionals (per-token strict loop)
  - mv --target-directory
  - mv FILE positionals
  - cp --target-directory
  - cp FILE positionals
  - ln FILE positionals

The rm walker keeps its post-validate "delete project root"
guard intact — validate_command_path only handles the boundary
check, the project-root self-protection follows.

Net: 281 to 205 lines (minus 76). Behavior identical — same
strict policy across all walkers, same canonical BLOCKED
message format. 1341 of 1341 pass.
Apply path-validation helpers to nine call sites: install
(--target-directory and FILE positionals), mkdir, rsync (six
long-attached options + FILE positionals), tar --directory,
unzip -d, cpio -D, 7z extract destination -o, 7z working
directory -w, 7z archive verb target.

Net: 459 to 354 lines (minus 105). Behavior identical. STRICT
policy preserved for install/mkdir/rsync; write policy for
archive walkers (allowlist applies — these are write, not
delete). 1341 of 1341 pass.
Apply path-validation helpers to ten call sites in
write_targets_b.sh: tee positionals (discard-aware), HTTP
download tools (discard-aware), dd of= operand (discard-aware),
shell redirect target (preserves symlink chain), DB dump file
flags (pg_dump and pg_dumpall), psql output and log flags, mysql
session-tee, mysqldump result-file, mktemp directory selectors
and positional template, mkfifo and mknod special-file creation.

Discard-aware walkers keep their is_discard_target check inline
before block_unless_path_allowed. The redirect walker preserves
the symlink-chain follow loop between resolve_command_path and
the discard or permitted check.

Net: 490 to 387 lines (minus 103). Behavior identical. 1341 of
1341 pass.
guard.sh duplicated the same 7-step normalization pipeline twice:
once for the live CMD, once for the heredoc-blanked CMD_BLANKED.
That was the round-5-architecture-review item 4 (Low priority).

Extract the pipeline to a single helper in command_name.sh:

  normalize_command_view INPUT
    1. trim leading and trailing whitespace
    2. strip subshell grouping parens at token boundaries
       (preserve dollar-paren substitution form)
    3. strip alias-escape backslash before [a-zA-Z_]
    4. strip surrounding quotes from the command-name token
    5. strip common binary-path prefix (sed fallback)
    6. apply strip_command_name_prefix (post-wrapper aware)
    7. collapse duplicated whitespace

guard.sh now calls `CMD=$(normalize_command_view "$CMD")` and
`CMD_BLANKED=$(normalize_command_view "$CMD_BLANKED")` after
the heredoc-blanking pass — both views go through the same
pipeline, so a fix to any normalization step lands in both
simultaneously.

Bonus: while extracting, noticed that sec 80 added /opt/homebrew/bin
to _cn_strip_path_prefix and strip_command_name_prefix but the
inline sed-based fallback in guard.sh:322,352 was NOT updated.
Fixed in the new helper — the sed regex now includes
opt/homebrew/bin alongside usr/local/bin etc.

guard.sh: 9 fewer lines. Pipeline drift impossible. 1341 of
1341 pass.
Codex round-3 review of PR #27 caught that sec 87/88 destructive-
action regex matched bare verb names only — `find -exec /bin/rm`
slipped past because the absolute-path form of the binary placed
`/bin/` between the action token and the verb basename. Same
pattern for `-execdir`, `-ok`, `-okdir`.

  find /etc -execdir /bin/rm -f {} ;        ALLOWED
  find /etc -exec /usr/bin/rm {} ;          ALLOWED
  find /etc -exec /opt/homebrew/bin/rm {} ; ALLOWED

Fix: extend the regex with an optional path-prefix segment
before the verb basename:

  -(exec|execdir|ok|okdir)[[:space:]]+([^[:space:]]+/)?(rm|mv)([[:space:]]|$)

The basename match still anchors to a whitespace or end-of-line
boundary, so unrelated names like `foo-rm` do not false-positive.

Tests: 4 reproducers + 3 true-negatives (incl. foo-rm basename
mismatch and read-only ls action) in
tests/test_bypass_reproducers_pentest_d.sh sec 93.
1348 of 1348 pass.
Codex round-3 review found that sec 84/91's psql output walker
treated `-o` and `--output` values as file paths and validated
them via is_write_permitted. But psql interprets a value
starting with `|` as a pipe to a shell command — the walker
silently accepted shell code as a file path:

  psql -o '|rm /etc/passwd' -c 'select 1'         ALLOWED
  psql --output='|destructive' mydb                ALLOWED
  psql -L '|cmd' mydb                              ALLOWED

Same un-inspectable surface as `bash -c`.

Fix: before passing `pqfile` to validate_command_path, check
if it starts with `|` and reject with a dedicated BLOCKED line.
Same shape applied to all four output flags
(-o / --output / -L / --log-file).

Side fix: the attached short and long-attached forms (-o?* and
--output=*, --log-file=*) needed strip_quotes — without it
single-quoted attached values like `--output='|cmd'` left the
literal apostrophes in `pqfile` and the pipe check missed them.

Tests: 4 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 94.
1354 of 1354 pass.
justi added 7 commits May 7, 2026 22:47
Codex round-3 review found that sec 84/91/94's psql walker only
inspected the `-o` / `--output` / `-L` / `--log-file` flags. The
`-c` / `--command` value was opaque to the walker, but psql
interprets several backslash meta-commands inside the SQL string
that write local files or execute shell commands:

  \o FILE     redirect query output to FILE
  \g FILE     execute query and write to FILE
  \gx FILE    execute, expanded output to FILE
  \w FILE     write query buffer to FILE
  \s FILE     save history to FILE
  \copy ...   client-side COPY (can write FILE)
  \!  CMD     execute shell command — un-inspectable

  psql -c '\o /etc/psql.out' -c 'select 1'  ALLOWED

Fix: in the psql walker, dispatch on `-c` / `--command` (split
+ attached short + attached long forms). Reject if the value
starts with any of the file-writing or shell-executing metas.

Subtle interaction with the alias-escape pass: guard's CMD
normalization strips a backslash before [a-zA-Z_], so `\o` /
`\g` / `\w` / `\s` / `\copy` arrive as bare `o` / `g` / `w` /
`s` / `copy` at the start of the value. `\!` keeps its
backslash (! is non-alphanumeric). Match either form anchored
at the start of the value:

  ^(o|g|gx|w|s|copy|\\!)([[:space:]]|$)

This is intentionally over-broad — `\copy` to an in-project
file is also blocked — because the path payload after a
backslash meta is too fragile to parse safely from bash.

Tests: 5 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 95.
1361 of 1361 pass.
Codex round-3 review caught that sec 86/90's attr walker gated
writes on the split forms (`-s`, `-r`) and the long forms
(`--set`, `--remove`, `--set=*`, `--remove=*`) but missed the
attached-short forms:

  attr -suser.test -V val /etc/passwd      ALLOWED
  attr -ruser.test /etc/passwd             ALLOWED

Fix: extend the gate predicate to also recognise `-s?*` and
`-r?*` (attached short with non-empty NAME). In the walker,
treat these tokens as single-step skips (the NAME is already
in the token; no separate value to consume) by adding
`-s?*|-r?*|-g?*|-V?*` to the long-attached case branch.

Tests: 3 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 96.
1366 of 1366 pass.
Item 2 of the round-5 architecture review: replace raw substring
regex command-gates with anchored command_name_is checks where it
is safe to do so.

New helper command_name_matches in command_name.sh accepts a
pipe-separated list of names and returns 0 iff command_name_is
matches any. Lets a detector that fires for several aliases get
one anchored gate instead of substring matches.

Migrated five gates in destructive.sh: xargs, find, the move
verb, cp, and ln. Each switched from raw substring regex to
command_name_is.

The rm walker is intentionally NOT migrated. Three suite tests
deliberately rely on the substring-matching over-block because
host-mount parsing is not in scope. command_name_is would only
fire when the post-wrapper verb is rm, missing wrapper-prefixed
forms. Documented inline with a NOTE comment so the next refactor
pass does not flip it silently.

1366 of 1366 pass.
Continuation of round-5 architecture review item 2: replace
raw substring regex command-gates with anchored predicates where
safe.

inplace.sh: sed, truncate (command_name_is); perl-or-ruby,
awk-family (command_name_matches).

write_targets.sh: rsync, tar, unzip, cpio (command_name_is);
seven-zip family (command_name_matches).

write_targets_b.sh: curl, wget, dd (command_name_is).

The tee walker is intentionally NOT migrated — same shape as the
rm walker note: a docker bind-mount test deliberately over-blocks
on substring matching because host-mount parsing is not in scope.
Documented inline.

1366 of 1366 pass.
Codex round-4 review found that sec 93's regex covered
`find -exec /bin/rm` (unquoted) but missed surrounding single
or double quotes around the binary path:

  find /tmp -exec '/bin/rm' {} +     ALLOWED
  find /tmp -exec "/bin/rm" {} +     ALLOWED

Bash strips the quotes before find executes, so find still
receives /bin/rm and runs it. The hook sees the raw text with
quote bytes; the path-prefix glob `[^[:space:]]+/` rejected
characters before the path.

Fix: extend the regex to accept an optional surrounding `'` or
`"` quote byte before/after the verb basename:

  -(exec|execdir|ok|okdir)[[:space:]]+['"]?([^[:space:]'"]+/)?(rm|mv)['"]?([[:space:]]|$)

Tests: 4 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 97.
1372 of 1372 pass.
Architecture review caught that sec 80 added /opt/homebrew/bin/
to the command-name prefix strip in command_name.sh
(_cn_strip_path_prefix and strip_command_name_prefix). The same
path-strip logic is duplicated in two sibling modules:

  hooks/lib/subcmd_flags.sh    : _sf_strip_path_prefix
  hooks/lib/remote_dispatch.sh : _rd_strip_path_prefix

Neither was updated, so a Homebrew-installed binary running a
subcommand sink or remote dispatch slipped past the verb match
in those modules — sec 80's fix was incomplete:

  /opt/homebrew/bin/tar --to-command='rm /etc/foo' -xf foo.tar
  /opt/homebrew/bin/git -c sequence.editor='rm /etc/x' rebase

Both ALLOWED before this commit. The first is a real bypass:
tar --to-command runs an external process per archive member,
and the subcmd_flags walker did not see "tar" as the verb when
prefixed with a Homebrew path.

Fix: add /opt/homebrew/bin/* to the case statements in both
helpers, mirroring command_name.sh.

A third probe — /opt/homebrew/bin/ssh host rm — is now ALLOWED
post-fix (the remote-dispatch rewrite kicks in correctly and
ssh runs the command on the remote host, which is outside the
local boundary scope). Pre-fix it was blocked as false-positive
because the prefix-strip drift kept ssh hidden from the
dispatcher and the rm walker saw rm in the local arg list.

Tests: 2 reproducers (tar and git -c sinks) + 2 true-negatives
(in-project tar, ssh remote dispatch) in
tests/test_bypass_reproducers_pentest_d.sh sec 100.
1376 of 1376 pass.
Codex round-4 review found two slip-throughs in sec 95's psql
backslash-meta walker:

(A) No-space args: psql -c '\o/tmp/out\g' was ALLOWED. After
    the alias-escape pass strips backslash before [a-zA-Z_],
    the value becomes `o/tmp/outg`. The sec-95 regex required
    space after `o`, but `/` follows — no match.

(B) ANSI-C quoting: psql -c $'\o /tmp/out' was ALLOWED.
    strip_quotes does not unwrap `$'...'`, so the value
    reaching the walker keeps the `$'` prefix and the meta is
    invisible to the anchored regex.

Fix:
- (A) Extend the meta separator class from `[[:space:]]|$` to
  `[[:space:]/|\\]|$` so `o/`, `o|`, `o\` all count as
  meta-then-arg. Applied to both walker branches (split -c
  and attached -c?* / --command=*).
- (B) Reject any -c value that starts with `$'` — ANSI-C
  quoting can carry arbitrary escapes the walker cannot safely
  decode in bash. Same fail-closed shape as the existing pipe
  rejection in sec 94.

Tests: 4 reproducers + 2 true-negatives in
tests/test_bypass_reproducers_pentest_d.sh sec 98.
1382 of 1382 pass.
@justi
justi merged commit a5b80d7 into main May 8, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant