Why Prompt Firewalls Miss AI Agent Privilege Escalation (and How to Intercept Tool Calls at Runtime)
Most AI security gateways check what enters the model and stop watching once inference begins. That gap breaks down the moment an autonomous agent can run SQL queries, fetch URLs, or invoke shell tools. An indirect promp
Most AI security gateways check what enters the model and stop watching once inference begins. That gap breaks down the moment an autonomous agent can run SQL queries, fetch URLs, or invoke shell tools. An indirect prompt injection hidden in a retrieved ticket or web page can pass an input classifier, persuade the model to build a malicious tool payload, and reach your execution layer unchallenged.
To close that gap, you need a deterministic boundary between the model's tool intent and the underlying OS, database, or network runtime. While building ToolShield (an MIT-licensed Python runtime proxy), I tested a recursive argument scorer, a consecutive-violation circuit breaker, and structured audit hashing against real attack payloads. That testing also surfaced a subtle calibration bug where a standalone cloud metadata probe silently passed the default risk threshold.
Where input filters go blind
Input guardrails evaluate natural language, whereas tool-calling exploits rely on valid syntax aimed at downstream parsers. When an agent holds credentials for internal databases or cloud APIs, a poisoned retrieval snippet turns an ordinary model call into server-side request forgery (SSRF), path traversal, or command chaining.
A runtime proxy reverses the inspection order. Instead of guessing intent from prose, the proxy intercepts the exact tool_name and structured JSON arguments dictionary right before execution. Because those parameters conform to strict schemas, deterministic checks evaluate them in fractions of a millisecond without waiting on a second LLM call.
Inside a deterministic tool proxy
In toolshield/core.py, the ToolShield class enforces four controls on every call to guard(tool_name, arguments).
First, tool allowlists and blocklists gate which functions an agent can invoke. Calls outside allowed_tools add +0.70 risk (UNAUTHORIZED_TOOL), and calls matching blocked_tools add +0.80 (FORBIDDEN_TOOL), crossing the default 0.65 block threshold immediately.
Second, inspect_value() walks nested dictionaries and lists recursively so attackers cannot hide payloads inside deep JSON keys. Every matched regex rule in toolshield/rules.py adds a fixed weight (+0.50 for credential leakage or prompt hijack phrases, +0.45 for path traversal, +0.40 for shell chaining, and +0.35 for SSRF probes), capped at 1.0.
Third, a consecutive-violation circuit breaker tracks repeated blocks. If an agent triggers max_consecutive_violations blocks in a row (default 3), self.circuit_broken flips to True, and every subsequent call raises SecurityViolation with CIRCUIT_BREAKER_ACTIVE, including benign queries like SELECT 1;.
Fourth, SecurityAuditLogger emits Elastic Common Schema (ECS) JSON records containing the decision, latency, violation tags, and a SHA-256 fingerprint computed from the tool name, canonical sorted JSON arguments, and UTC timestamp.
Wrapping an existing Python tool function requires one decorator:
from toolshield import ToolShield, SecurityViolation
shield = ToolShield(
agent_id="tier2-analyst-agent",
allowed_tools={"query_db", "fetch_endpoint"},
max_risk_threshold=0.65,
max_consecutive_violations=3,
)
@shield.wrap("query_db", target_fn=run_sql)
def guarded_query(**kwargs):
return run_sql(**kwargs)
Running the local unit test suite (tests/test_core.py) verifies benign queries, shell chaining blocks, credential detection, forbidden tools, and circuit-breaker quarantine across all 6 test cases in 0.001s.
Testing payloads and catching a threshold bug
Theory looks tidy until you test single-vector payloads through the CLI. On bash, pass JSON arguments directly; on Windows PowerShell, wrap the JSON payload with escaped quotes or pass it via Python so the shell preserves internal braces and asterisks.
First, run a benign database read:
python -m toolshield.cli --tool query_db --args '{"query":"SELECT count(*) FROM alerts;"}'
That exits 0 with risk_score: 0.0 and an audit record:
[+] STATUS: ALLOWED
[+] Attestation Hash: c0b003243ccaf23f2693ff9563aa71ad0a52f14c957ea450a7efcf9f11d9b4ce
Next, send a combined shell injection, sensitive file read, and cloud metadata probe:
python -m toolshield.cli --tool execute_shell --args '{"cmd":"cat /etc/passwd; curl http://169.254.169.254"}'
ToolShield blocks the call and exits 2 (Risk Score: 1.00):
[-] STATUS: BLOCKED (Tool execution 'execute_shell' blocked by ToolShield: Risk score 1.00 exceeded threshold 0.65)
[-] Violations: SHELL_INJECTION:COMMAND_CHAINING, PATH_TRAVERSAL:SENSITIVE_SYSTEM_FILES, SSRF_PROBE:CLOUD_METADATA_ENDPOINT
[-] Risk Score: 1.00
Now test a single high-impact SSRF probe targeting an allowlisted HTTP helper (fetch_endpoint):
python -m toolshield.cli --tool fetch_endpoint --args '{"url":"http://169.254.169.254/latest/meta-data/"}'
Watch what happens at the default 0.65 threshold:
[+] STATUS: ALLOWED
[+] Attestation Hash: ddd7a131678cef064e2f34256143f7ea387bd7d1e369ba193e337b3cdcf69a07
{
"security": {
"decision": "ALLOW",
"risk_score": 0.35,
"violations": [
"SSRF_PROBE:CLOUD_METADATA_ENDPOINT"
]
}
}
Because SSRF_PROBE carries a +0.35 weight and fetch_endpoint is not on the blocklist, the total score (0.35) stays below 0.65 and the metadata request slips through! Lowering the threshold to 0.30 catches the probe immediately:
python -m toolshield.cli --tool fetch_endpoint --args '{"url":"http://169.254.169.254/latest/meta-data/"}' --threshold 0.30
[-] STATUS: BLOCKED (Tool execution 'fetch_endpoint' blocked by ToolShield: Risk score 0.35 exceeded threshold 0.30)
[-] Violations: SSRF_PROBE:CLOUD_METADATA_ENDPOINT
[-] Risk Score: 0.35
Weighted additive scoring is easy to miscalibrate for standalone critical rules. Any rule that represents an outright policy breach, such as querying 169.254.169.254 or metadata.google.internal, should either carry a weight at or above max_risk_threshold (>= 0.65) or act as an unconditional hard-deny trigger.
When regex proxies are not enough
A lightweight Python proxy lowers blast radius quickly, yet three engineering limits remain.
Regex rules catch obvious metacharacters (;, &&, ../), whereas double-URL encoding, Unicode homoglyphs, or DNS rebinding targeting private CIDRs require canonical URL parsing and network egress controls at the container or VPC layer.
Whenever you adjust max_risk_threshold or add rules in rules.py, write regression unit tests asserting that each standalone critical payload blocks on its own rather than relying on stacked violations.
Finally, compute_attestation_hash() hashes arguments and timestamps with a static string salt ("toolshield-v1") and no prior-event chaining. Treat that hash as a SIEM correlation ID; if you need tamper evidence against a compromised proxy host, add HMAC signing with an external secret or ship logs to append-only storage.
Next step
Audit the rule weights in your agent tool wrappers against your block threshold today. If any standalone indicator (cloud metadata IPs, private key headers, or path traversal) scores below your block cutoff, promote it to a hard-deny check and enforce egress filtering behind the proxy.
Drafted with AI-assisted editing and verified against local unit tests and CLI runs on ToolShield.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.