Skip to content

harden(hooks): fix G2 audit findings — payload+deny fail-closed, proxy path-traversal, +8 more - #102

Merged
thehoff merged 3 commits into
developfrom
harden/hooks-dispatch-100
May 20, 2026
Merged

thehoff merged 3 commits into
developfrom
harden/hooks-dispatch-100

Conversation

@thehoff

@thehoff thehoff commented May 20, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes the G2 (hook system + dispatch) findings from the full-codebase audit, issue #100. Two Codex review rounds — the first caught 2 CRITICAL holes in the initial fix; the second confirmed both closed.

Findings fixed

Sev Fix
CRITICAL hook_cmd.rs — hook payload parse/shape/oversize errors now emit a deny JSON (fail closed).
CRITICAL hook_cmd.rs — explicit PermissionVerdict::Deny (a deny-rule hit) was collapsing to a silent Skip — command ran unchecked. Now emits deny JSON via both run_claude and run_claude_inner.
CRITICAL main.rs proxy — argv kept as OsString end-to-end; shell-splitting moved behind an opt-in --via-shell flag (no more lossy-split of whitespace paths).
CRITICAL main.rs — proxy/meta argv[0] containing a path separator is now rejected (token_has_path_separator), at both the meta-flag intercept and Commands::Proxy. Previously bin_basename normalised only the membership check while the raw ../../evil/npm token was exec'd.
IMPORTANT main.rs — bin_basename() normalises the bin token before the META_PASSTHROUGH_BINS check (absolute-path invocations now get secure_meta_command hardening).
IMPORTANT init.rs — patch_gemini_settings() errors on parse failure instead of overwriting config with {}.
IMPORTANT init.rs — env-var config roots escaping $HOME rejected unless CONTEXTCRAWLER_ALLOW_NONHOME_ROOT=1.
IMPORTANT init.rs — uninstall matches the hook entry by exact final path-component, not substring.
IMPORTANT hook_check.rs — new HookStatus::Broken; status() verifies the hook binary exists + is executable (no more silent-broken-hook false negative).
IMPORTANT hook_audit_cmd.rs — validate_log_path() canonicalises + rejects symlink escapes; stream-read with 16 MiB / 200k-line caps.
IMPORTANT hook_cmd.rs — as_object_mut().unwrap() → checked; unreachable!() deny arm → exit(2).
NICE branding: stale rtk strings → contextcrawler; hook-version marker renamed (legacy form still accepted); --shell → --via-shell in error text.

Out of scope (tracked under #100)

  • Wiring tirith_gate/supply_chain_gate into the hook claude path — pending a design decision.
  • Deny-output-contract normalisation across runtimes — needs its own protocol pass.

Test plan

  • cargo test --workspace — 2323 pass, 0 fail (≈27 new tests)
  • cargo build --release clean, no warnings
  • Codex review round 1 — found 2 CRITICAL (deny fail-open, proxy path-traversal); round 2 — both confirmed closed, mergeable

Part of the #100 audit — that issue stays open for the remaining fix branches (G3–G8 findings).

🤖 Generated with Claude Code

thehoff and others added 3 commits May 20, 2026 17:57
Addresses the G2 group of the full-codebase audit (#100).

CRITICAL 1 — hook_cmd.rs: Claude PreToolUse hook fails OPEN.
Malformed JSON, oversized stdin and malformed payload shapes all
returned Ok(()) / Ignore, letting the agent's command run unchecked.
Every payload error path now emits a `deny` verdict (new
emit_claude_deny + PayloadAction::Deny). A valid payload with no
command stays Ignore. Non-string `command` is classed as a shape
error and denied.

CRITICAL 2 — main.rs proxy: argv injection via lossy OsString +
shell_split. A binary path containing whitespace was word-split into
the wrong program. proxy now keeps argv as OsString end-to-end —
argv[0] is the binary, argv[1..] its args, never split. Shell
word-splitting is now an explicit `--shell` opt-in, never a heuristic.

IMPORTANT 3 — main.rs: absolute-path bin bypassed secure_meta_command.
`contextcrawler /usr/bin/npm --version` never matched META_PASSTHROUGH_BINS
and skipped per-tool env hardening. The bin token is now basename-
normalised (new bin_basename helper) before the membership check.

IMPORTANT 4 — init.rs patch_gemini_settings: destroyed user config on
parse failure (silently replaced a malformed settings.json with `{}`).
Now errors on parse failure and never writes unless the parse
succeeded — matching the sibling Claude/Cursor patch functions.

IMPORTANT 5 — init.rs: RTK_CLAUDE_DIR / CODEX_HOME / HERMES_HOME used
verbatim as write/delete roots. A poisoned env var could redirect
writes outside $HOME. Resolved roots are now canonicalised and
rejected if they escape $HOME, gated by an explicit
CONTEXTCRAWLER_ALLOW_NONHOME_ROOT opt-in for legitimate non-home setups.

IMPORTANT 6 — init.rs: uninstall substring-matched the hook entry via
contains(REWRITE_HOOK_FILE), so an unrelated hook merely mentioning
that filename was deleted. New command_is_legacy_rewrite_hook matches
the exact final path component instead — no install-time marker
migration needed, existing installs stay removable.

IMPORTANT 7 — hook_check.rs: status() reported healthy on a stale
registration without checking the hook binary exists / is executable.
New HookStatus::Broken variant; status() now resolves and verifies the
hook command's binary.

IMPORTANT 8 — hook_audit_cmd.rs: unbounded/uncanonicalised log read.
Path is now canonicalised and confirmed inside the audit dir (rejects
symlink escapes); the log is stream-read with byte and line caps
instead of read_to_string of an arbitrary file.

IMPORTANT 9 — replaced the `.unwrap()` on as_object_mut() and the
`unreachable!()` deny arm with checked branches that fail closed.

NICE-TO-HAVE 10 — branding: stale `rtk` strings in hook output, the
local CLAUDE.md install-detection grep (now keyed on the exact block
markers), and the on-disk hook-version marker (now
`# contextcrawler-hook-version:`, old form still accepted).

Adds tests for each fix. cargo test --workspace: 2312 passed.

Refs #100 (G2)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Codex review of the first fix pass (04827d9) found two CRITICAL holes the
fix missed plus two PARTIAL gaps. This is the second pass.

CRITICAL 1 — explicit deny-rule path fails open (src/hooks/hook_cmd.rs)
  When the permission engine returned PermissionVerdict::Deny for a
  command (an explicit deny-rule hit), process_claude_payload mapped it
  to PayloadAction::Skip — audit-logged and returned silently, so the
  denied command ran unchecked. Now routed through PayloadAction::Deny →
  emit_claude_deny(), emitting the Claude PreToolUse deny JSON the
  harness blocks on. Ask/Allow/Default verdicts are untouched.

CRITICAL 2 — proxy path-traversal exec (src/main.rs)
  bin_basename() normalised argv[0] ONLY for the META_PASSTHROUGH_BINS
  membership check; the spawn ran the RAW token. `proxy ../../evil/npm`
  passed the `npm` hardening check but executed the attacker binary.
  Both call sites (Commands::Proxy and the meta-flag intercept) now
  reject any argv[0] containing a path separator — proxied commands must
  be bare tool names resolved via PATH. The dead has_sep raw-exec branch
  in the proxy spawn is removed.

PARTIAL 3 — --shell flag arg collision (src/main.rs)
  Renamed the proxy flag --shell → --via-shell so a proxied child whose
  own arg is literally `--shell` reaches the child intact.

PARTIAL 4 — CONTEXTCRAWLER_ALLOW_NONHOME_ROOT re-read per call (init.rs)
  nonhome_root_allowed() now reads the env var exactly once via a
  OnceLock, closing the theoretical mid-run TOCTOU window.

PARTIAL 5 — tests
  Added: explicit deny-rule hit → deny JSON; non-deny verdicts never
  deny; malformed JSON / non-string command / oversized stdin → deny
  JSON (tests/hook_claude_deny.rs); proxy path-separator argv[0]
  rejected and literal --shell child arg reaches child
  (tests/proxy_nudge.rs).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…mment

Codex re-review NICE-TO-HAVE: the proxy flag was renamed --shell ->
--via-shell but the bail! message and an adjacent comment still said
--shell, which would misdirect operators.
@thehoff
thehoff merged commit 912a35d into develop May 20, 2026
4 checks passed
@thehoff
thehoff deleted the harden/hooks-dispatch-100 branch May 20, 2026 08:26
noogalabs pushed a commit to noogalabs/contextcrawler that referenced this pull request Jun 4, 2026
…on-go-complete

docs: comprehensive v0.15.1 documentation for Python/Go support
noogalabs pushed a commit to noogalabs/contextcrawler that referenced this pull request Jun 4, 2026
…path

G1 audit finding thehoff#2 of thehoff#100: the Tirith pre-execution gate and the
supply-chain gate only ran on the legacy `contextcrawler rewrite`
subcommand (hooks/rewrite_cmd.rs). The live Claude Code PreToolUse path
(`contextcrawler hook claude` -> process_claude_payload) did permissions
+ rewrite but never invoked either gate, so the defence-in-depth layer
was effectively dark for every real agent session.

Wire both gates into process_claude_payload_with, after the existing
PermissionVerdict::Deny handling and before get_rewritten:

  * New pure helper gate_decision(tirith, supply_chain) -> GateDecision
    { Proceed, Ask, Deny } maps the two gate verdicts. supply-chain
    Block -> Deny; supply-chain Unavailable -> Ask (fail closed);
    tirith should_downgrade -> Ask; both clean -> Proceed. Block
    outranks Ask.
  * supply-chain Block reuses the thehoff#102 deny machinery -- emits a
    PayloadAction::Deny (audit_tag deny:supply_chain_block) routed
    through the existing emit_claude_deny. No new PayloadAction variant.
  * A gate Ask sets gate_ask, which suppresses the permissionDecision
    "allow" so Claude Code prompts -- a gate Ask wins over a
    permissions Allow.
  * A gate-flagged command with no rewrite (e.g. `pip install foo`)
    cannot express "ask" in the PreToolUse protocol, so it fails CLOSED
    to a deny rather than a silent Skip.

Both gates stay opt-in: Tirith via CONTEXTCRAWLER_TIRITH_REQUIRED,
supply-chain via supply_chain.enabled. When disabled the gates are
no-ops and the hook behaves byte-for-byte as before -- covered by a
no-regression test asserting `git status` still rewrites with no deny.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
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