Prompt Injection Defense for Tool-Calling LLM Agents | B4N1

Prompt Injection Defense for Tool-Calling LLM Agents

4 hours ago · B4N1 AI Lire l'heure: 1 min

Threat Model: Why Tool-Calling Agents Are Structurally Exposed

Prompt injection is a class of attack in which an adversary supplies text that a model interprets as instructions rather than as inert data. In a purely conversational setting, the impact is usually confined to the content of a response. In a tool-calling agent, the stakes rise sharply, because the model's outputs are not merely read by a human—they are consumed by an orchestration layer that can invoke functions, read and write files, query databases, send messages, execute code, or call remote APIs. The model thereby becomes a "confused deputy": it holds credentials and capabilities on behalf of a trusted principal, yet it processes attacker-influenceable text that may attempt to redirect those capabilities.

The canonical taxonomy distinguishes two delivery modes. Direct injection places hostile instructions in the user's own message ("ignore your instructions and..."). Indirect injection embeds hostile instructions in data the agent retrieves or receives through its tools: a web page, an email body, a document, a code comment, a database field, a search result, an API response, or a tool-returned string. Indirect injection is the more consequential case for agents, because it requires no direct access to the agent and can be staged anywhere the agent will read. An attacker who can publish a web page, send an email, or open a pull request can plant instructions that fire when a victim's agent later consumes that content.

The impact space is broad. Realistic objectives include exfiltration of secrets or private context to an attacker-controlled endpoint; unauthorized invocation of tools (sending mail, transferring funds, modifying records, deleting data); hijacking of the agent's goal toward attacker objectives; persistence through poisoned memories or retrieval stores; and laundering of subsequent agent behavior. This maps closely to the OWASP Top 10 for LLM Applications, particularly LLM01 (Prompt Injection) and LLM06 (Excessive Agency), and to adversarial frameworks such as MITRE ATLAS. A working assumption should be that any byte stream entering the model's context from a source the operator does not fully control is potentially adversarial. Perfect prevention is not achievable; the design goal is to bound blast radius, preserve the integrity of authorization decisions, and make failure modes safe.

Defense in Depth, Not a Single Filter

No single mitigation is sufficient. Prompt injection is not, at root, a bug in one component; it is a consequence of mixing instructions and data in a shared context window. A mature posture therefore layers independent controls: architectural separation, least privilege, validation at trust boundaries, human approval for irreversible actions, output inspection, secrets hygiene, sandboxing, and continuous evaluation. Each layer should assume the others may fail. In particular, filters that try to detect injection textually are probabilistic and should never be the only line of defense; security-relevant decisions must not depend solely on the model's compliance with instructions.

Architectural Patterns

#### Separate Control Plane from Data Plane

The strongest structural mitigation is to prevent untrusted content from reaching the component that authorizes tool execution. In the dual-LLM pattern, a privileged planner model orchestrates work but never sees raw untrusted text; a separate, quarantined model summarizes or transforms untrusted input, and only its sanitized, typed output crosses into the privileged context. Frameworks along these lines attach provenance to data, distinguishing "trusted instructions" from "untrusted observations," and constrain the privileged model to act only on values whose integrity can be established. Recent proposals go further, enforcing information-flow rules so that data tainted by untrusted sources cannot influence the arguments of sensitive tool calls without explicit declassification. The shared theme is architectural: do not rely on the model to voluntarily keep data and instructions separate.

#### Least Privilege and Capability Scoping

Tool exposure should follow least privilege. An agent should receive only the tools it needs for the current task; read and write capabilities should be separable; credentials should be scoped per tool and per operation; and high-risk actions (deletion, payment, external communication, code execution, privilege changes) should require elevated authorization. Session-scoped capabilities or single-use tokens reduce replay risk. Where possible, run tool execution in a sandbox with no ambient authority, restrict filesystem access to a working directory, and deny network egress except to an explicit allowlist. Even a perfectly injected model should find its reachable attack surface small.

#### Human-in-the-Loop for Consequential Actions

For actions that are irreversible, externally visible, financially significant, or security-relevant, require explicit human approval before execution. Approval should display a faithful rendering of exactly what will happen—full tool name, complete arguments, resolved recipients, amounts, URLs—so that an operator can catch anomalies introduced by injection. Approval fatigue is a real risk; combine mandatory review for high-risk classes with automated policy checks for routine ones, and consider second-opinion review by a separate checker rather than the same model that proposed the action.

Handling Untrusted Content

#### Spotlighting, Delimiting, and Labeling

Content originating outside the trusted boundary should be clearly marked as data. Practices collectively known as "spotlighting" wrap untrusted segments in explicit delimiters, prepend provenance headers, or transform them (e.g., base64, escaped formats) so instruction-like text inside is structurally inert. The model should be told, in the system prompt, that such regions are never to be treated as instructions and that any instructions found within them must be ignored. This reduces attack success probabilistically but does not eliminate it; delimiters can be forged inside the data unless paired with robust parsing and downstream validation.

#### Output Sanitization and Schema Enforcement

Tool outputs re-entering the context should be sanitized: strip or neutralize control characters, known injection markers, hidden text, and unexpected instruction-like content; cap length; and validate shape against an expected schema. Where a tool's result can be reduced to a typed value (a number, an enum, a constrained string), extract only that value rather than forwarding raw content. Similarly, model outputs that trigger tool calls must be validated against a strict schema with type checks, allowlists, range constraints, canonicalization, and rejection of unknown fields. Schema validity is necessary but not sufficient; semantic policy checks are still required.

#### Injection Detection Classifiers

Secondary detectors—lightweight classifiers trained or tuned to flag injection attempts in inputs and tool outputs—can serve as an additional signal. They can gate suspicious content, route it to quarantine, or raise human review. But classifiers have false negatives and can themselves be adversarially influenced; they should complement, never replace, architectural controls. Calibration, drift monitoring, and regular re-evaluation on fresh attack corpora are essential.

Tool-Call Validation and Authorization

Every tool call should pass through an orchestration-layer policy engine before execution. The engine should re-check authorization independently of the model's intent, evaluate arguments against allowlists and business rules, restrict recipients and destinations, enforce rate and volume limits, and deny by default. Authorization decisions must never be inferred from model output or from text inside tool results claiming approval has been granted; approval must come from a trusted channel outside the model's influence. Sensitive operations should also be logged with full provenance, supporting audit and rollback.

#### Exfiltration-Resistant Tool Design

Because injected instructions frequently aim to steal data, tools should be designed so that misuse is ineffective. Avoid tools that combine reading sensitive data with arbitrary outbound communication; restrict network egress; block attachment of secrets to outbound calls; validate and canonicalize URLs; screen tool arguments for unexpected data flows; and keep secrets out of the model's context entirely (reference secrets by handle; have the execution layer inject them at call time, then scrub logs). Mark sensitive outputs for redaction before they re-enter context. Canary tokens planted in private data can reveal exfiltration attempts when they appear in outbound requests.

Protocol-Specific Considerations for Tool Servers

In ecosystems where tools are exposed by remote tool servers or dynamically discovered tool providers, the attack surface extends beyond data poisoning. Tool definitions themselves—names, descriptions, schemas—are untrusted input. "Tool poisoning" attacks hide instructions inside tool descriptions; name shadowing can override or confuse trusted tools; rug-pull updates can silently change a tool's behavior after approval. Defenses include allowlisting and pinning approved tool servers, verifying signed tool manifests, snapshotting tool definitions and alerting on changes, restricting dynamic discovery, applying strict schemas, and namespacing tools by server. Tool outputs from third-party servers should receive the same untrusted treatment as any other external data. Equally, operators should audit what a server can see: a tool server may receive the full context passed to it and must not be granted more than it needs.

Memory, Retrieval, and Persistence Poisoning

Agents that persist memories, notes, or retrieved documents introduce a durable injection channel. An attacker who can plant content in a retrieval corpus, shared workspace, or long-term memory can influence future sessions—including sessions involving other users. Mitigations include treating retrieved content as untrusted at read time, provenance tracking for stored memories, sanitization before persistence, per-user and per-tenant isolation, TTLs and review for long-lived memories, and preferring append-only audit trails over silently editable state. Retrieval results should be ranked with provenance in mind, and sensitive memories should not cross trust boundaries.

Agentic Loop Safeguards

Multi-step agents need runtime bounds independent of content. Enforce maximum iterations, wall-clock and token budgets, tool-call rate limits, and recursion depth. Detect anomalous patterns—repeated failed calls, sudden expansion of scope, newly appearing destinations, privilege escalation attempts—and halt or escalate. Circuit breakers should stop automated execution when risk thresholds are exceeded. Provide a safe "pause and ask" path, checkpointing for rollback, and idempotent or reversible tool designs so that partial progress can be safely undone. Plan-then-execute with human approval of the plan, followed by execution constrained to that plan, shrinks the window in which injected instructions can alter actions.

Secrets, Data Hygiene, and Context Minimization

Minimize what enters the context. Do not place secrets, private keys, or credentials in prompts or system messages; scope and rotate credentials; prefer short-lived tokens; separate environments; and scrub secrets from logs and tool outputs. Assume anything in context could later be exfiltrated by injection; therefore, data classification and egress filtering remain essential complements to injection defenses.

Evaluation, Red-Teaming, and Observability

Defenses must be measured. Maintain regression suites of injection scenarios—direct, indirect via web/email/documents, tool-poisoning, memory-poisoning, exfiltration attempts, cross-tool confusion—and run them continuously against new model and orchestration versions. Red-team exercises should target the full pipeline, not just the model. Track metrics such as injection success rate, blocked-attempt rate, false-positive rate of detectors, time-to-detect, and downstream incident rate. Instrument provenance end-to-end: log which sources influenced each tool call, retain audit trails, and support incident replay. Security incidents should feed back into updated filters, policies, and tests. Nothing about this posture is one-time; model updates, new tools, and new data sources each re-open the evaluation question.

Known Limitations

It is important to be honest about the ceiling. Because instructions and data share a common channel, there is no provable separation inside the model, and no textual filter can guarantee detection of all injections. Adversaries adapt; novel phrasings, multi-step chains, and cross-context tricks will sometimes succeed at influencing the model. The practical security claim is not "the model cannot be injected"; it is "injection cannot be converted into unauthorized effects." Achieving that requires that authorization, validation, sandboxing, and approval live outside the model and outside untrusted content, and that blast radius is bounded even when the model is compromised. Every layer described above should be read with this standard in mind.

Conclusion

Prompt injection in tool-calling agents is not solved by better prompting alone. It is a systems-security problem requiring defense in depth across the trust boundary. The durable principles are clear: treat all external content as hostile; separate instructions from data; constrain authorization outside the model; enforce least privilege on tools and credentials; sandbox execution and restrict egress; validate every tool call semantically; require human approval for consequential or irreversible actions; protect memory and retrieval integrity; bound agentic loops; keep secrets out of context; and continuously test with adversarial evaluation. Filters and classifiers add resilience but never guarantee. Organizations that design agents on the assumption that injection will sometimes succeed—and that success must not translate into harm—will be far better positioned than those relying on model compliance alone. As agents gain broader tool access, these controls move from nice-to-have hardening to a mandatory baseline for safe deployment.


Vous avez des questions ?

Parlons

Contactez-moi sur LinkedIn