DEV Community

Cover image for Inside a Sub-Millisecond PreToolUse Firewall: Shell Normalization, Path Containment & Zero-Trust Agent Isolation
Benni Alencar
Benni Alencar

Posted on Originally published at benni-os.net

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

By **Benni Alencar* — Chief AI Systems Architect at Benni OS. Canonical article & interactive benchmarks at benni-os.net.*

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 (`,[INST],<|im_start|>system) that hijack downstream reasoning unless quarantined atPostToolUse`.

`mermaid
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:

`python
@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),
    }
Enter fullscreen mode Exit fullscreen mode

`

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
Workspace Escape ../../.ssh/id_ed25519 Path.resolve().relative_to(workspace_root) 0.012 ms
Obfuscated Exfiltration `printenv \ base64orcurl -d @.env` Pipe/sink rule + outbound flag inspection
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 →
Enter fullscreen mode Exit fullscreen mode




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.
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode




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.


Production Packs, B2B Pilots & Open-Source Lab Support

All core tooling in the Benni-OS Claude Code suite remains 100% open source (MIT). To fund ongoing GPU benchmarks and keep these tools free for the community, we offer:

  1. Live Reality Lock Sandbox (Free): Test deterministic verification invariants across 8 engineering packs at benni-master-os.bennialencar.workers.dev.
  2. Sovereign Policy & Red-Team Pro Pack ($49): Drop-in PreToolUse guardrails & OWASP LLM probes at bennie6.gumroad.com/l/monxqo.
  3. Production Hardening & Custom Domain Packs (B2B): Enterprise policy packs, CI/CD Reality Lock gates, and 30-minute pilot reviews via bennialencar@benni-os.net (Architecture Portfolio & Services).
  4. Sponsor the Open-Source Research Lab: Found this architecture useful in production? Support reproducible benchmarks and new MIT releases via PayPal (alencaroyale@gmail.com) or star/follow on GitHub Benni-OS & BenniAlencar.

Top comments (0)