Inside a Sub-Millisecond PreToolUse Firewall: Shell Normalization, Path Containment & Zero-Trust Agent Isolation

Naive regex filters break the moment an indirect prompt injection uses backslash escaping, subshell expansion, or symlink traversal. Here is how to engineer a deterministic PreToolUse firewall that resolves canonical paths, scores taint, and blocks exfiltration in under 5 microseconds.

Inside a Sub-Millisecond PreToolUse Firewall: Shell Normalization, Path Containment & Zero-Trust Agent Isolation

Why Naive String Filters Fail Against Real Shell Obfuscation

Most teams start securing autonomous coding agents by adding a blacklist of forbidden strings (rm -rf, .env, curl) inside a wrapper script or CLAUDE.md. That collapses on the first adversarial input.

Consider three trivial bypasses against naive string matching:

  1. Path Aliasing & Traversal: Blocking .env misses ./config/../.env, ~/.aws/../.ssh/id_ed25519, or Windows-style separators.
  2. Token Obfuscation: Shell parsers normalize c\at, $'\x63\x61\x74', or base64-decoded pipes (echo ... | base64 -d | sh) into identical OS syscalls.
  3. Indirect Injection Delimiters: Untrusted HTML comments or fetched web payloads embed raw role tags (<system>, [INST], <|im_start|>system) that hijack downstream reasoning unless quarantined at PostToolUse.
flowchart LR CALL[Claude Code Tool Call] --> NORM[Path & Token Normalizer] NORM --> PATH{Inside workspace_root?} PATH -->|No: Traversal / Symlink Escape| DENY1[Exit 2: Containment Violation] PATH -->|Yes| INJ[Prompt & Delimiter Scanner] INJ -->|risk_score >= 0.85| DENY2[Exit 2: INJ-001..004 Block] INJ -->|Clean| CRED[Credential & IaC Policy Matrix] CRED -->|Match SEC/INFRA Rule| DENY3[Exit 2: Hard Policy Block] CRED -->|Pass| ALLOW[Execute + Append SHA-256 Trace]

1. The Verdict Contract: Latency-Bounded & Auditable

Every security check on the hot path of a coding agent must be both deterministic and effectively free in wall-clock time. In Benni-OS/claude-code-sovereign, firewall.py returns a frozen FirewallVerdict dataclass carrying the exact rule ID, risk score, and microsecond-precision latency:

@dataclass(frozen=True)
class FirewallVerdict:
    allowed: bool
    risk_score: float
    category: str
    reason: str
    matched_rule: str
    latency_ms: float

    def to_dict(self) -> dict[str, Any]:
        return {
            "allowed": self.allowed,
            "risk_score": round(self.risk_score, 4),
            "category": self.category,
            "reason": self.reason,
            "matched_rule": self.matched_rule,
            "latency_ms": round(self.latency_ms, 4),
        }

2. Canonical Path Containment Before Regex Evaluation

Never run pattern matching on raw unnormalized file arguments. Before any Read, Write, or Edit executes, resolve both the workspace root and the target path using Path.resolve() and verify containment via relative_to(). Only after containment passes should the policy engine inspect secret filenames (.env*, id_rsa, id_ed25519, credentials.json).

Attack Surface Bypass Attempt Deterministic Control P50 Overhead
Role Delimiter Injection <|im_start|>system inside fetched issue INJ-003 pre-compiled regex + PostToolUse taint 0.0046 ms
Workspace Escape ../../.ssh/id_ed25519 Path.resolve().relative_to(workspace_root) 0.012 ms
Obfuscated Exfiltration printenv | base64 or curl -d @.env Pipe/sink rule + outbound flag inspection 0.006 ms
Destructive Cloud CLI terraform destroy -auto-approve IaC block requiring explicit human terminal 0.004 ms

3. Quarantine Untrusted Tool Outputs at PostToolUse

Preventing bad commands is only half the boundary. When an agent runs WebFetch or reads an external dependency README, untrusted text enters the context window. Scanning tool outputs at PostToolUse before they reach the next turn stops indirect prompt injection at the ingestion boundary, sealing the event into the SHA-256 ledger.

Ready-to-Deploy Rules & Team Audits

The entire claude-code-sovereign kernel is MIT open source. If you want our pre-tuned 16-rule Enterprise PreToolUse pack + 27-probe red-team harness ready to drop into .claude/settings.json, grab the Sovereign Policy & Red-Team Pro Pack ($49), or test deterministic verification invariants live in the Benni Master OS v10 Sandbox.

Question for readers: What is the sneakiest shell or path-aliasing bypass you have caught an autonomous coding agent attempting in CI or local dev? Drop it in the comments so we can benchmark it against our red-team suite.

Launch the Benni Master OS v10 Sandbox

Verify 38 canonical skills, 8 deterministic packs, and Reality Lock invariants live in your browser, or contact bennialencar@gmail.com for B2B pilots.

Open Live Sandbox →

Frequently Asked Questions

Why enforce security in PreToolUse hooks instead of inside the LLM system prompt?
System prompts are probabilistic suggestions that degrade under long context or indirect injection. PreToolUse executes out-of-band on CPU with exit code 2 before the OS ever spawns a child process.
What is the runtime latency impact per tool call?
Pre-compiled regex and canonical path checks execute in 0.0046 ms P50 on local CPU with zero extra LLM token cost.