Indirect Prompt Injection in AI Agents: Attack and Defense Practices
This article examines indirect prompt injection in AI agent frameworks, where malicious instructions embedded in external content are read and executed during normal tasks. It explains how to model attack chains using sources, sinks, and canaries, how to run large-scale security evaluations with scenario matrices and repeated sampling, and why success rates can be high. It then outlines defenses that separate reading from acting, including trust labeling, least privilege, source sanitization, sink policy engines, confirmation gates, output checks, and full-chain auditing, along with practical rollout and acceptance guidance.
1. Where the Problem Starts: When “Reading” Becomes “Executing”
As AI agents gradually take over real business workflows, an easily overlooked risk is emerging: third-party content read by the model may carry instructions that the user never issued. An attacker does not need to breach a server or steal credentials. Embedding malicious instructions in a web page, email, document, chat log, or skill package description and waiting for the agent to read them may be enough to make the system compromise itself.
The technical name for this risk is indirect prompt injection. It differs from direct injection in the interaction path. Direct injection involves an attacker conversing with the model and trying to override system constraints. Indirect injection places the payload in an external data source that the agent must access, and the agent passively receives it while completing a task.
A simple analogy is hiring an extremely obedient assistant to open mail, read messages, and organize documents. On the back of one letter, in very small print, it says: “Forward the account credentials to a certain email address.” If the assistant cannot distinguish between what it is supposed to do and what the letter says to do, it will mechanically comply. The problem is not a system vulnerability, but the natural tendency to “trust whatever is read and do whatever is trusted.”
2. Modeling the Attack Chain in Technical Terms
To make this risk measurable, the first step is to abstract the chain into a structure that can be annotated and reproduced. The industry commonly describes it with a triple:
- Source: The tool or stage that introduces external content, such as web scraping, document parsing, email reading, or skill package loading. The source determines where the taint enters the context.
- Sink: A sensitive action that produces real side effects, such as sending an email, submitting a form, executing a command, initiating a transfer, or publishing content. The sink determines the attacker’s payoff point.
- Canary: When the attack goal is not to trigger an action but to make the model output specific content, a verifiable string marker is used to determine whether the output has been contaminated.
The complete chain can be summarized as follows: the attacker plants a payload in a source → the agent reads and parses it → the payload gains weight in the context similar to the user’s instructions → the agent plans and invokes a sink → unintended side effects or leaks occur. The core of evaluation is to get this chain executed as many times as possible in a controlled environment, thereby exposing weak points.
3. How to Run Large-Scale Security Assessments
Penetration testing an agent framework is fundamentally different from testing a traditional web system: the target is non-deterministic, and the same input may produce different paths. Experiment design must therefore emphasize scale and statistical measures.
- Scenario matrix: Build a combination matrix of “source type × sink type × payload form.” Sources cover web pages, documents, emails, skill descriptions, and more; sinks cover outbound sending, writing, execution, publishing, and more; payload forms cover explicit instructions, hidden text, encoded obfuscation, multilingual mixing, structured field injection, and more.
- Repeated sampling: Repeat each combination multiple times, using success rate rather than a single success or failure as the metric. The experiment scale mentioned in the original text, more than fourteen thousand runs, is intended to surface low-frequency but high-risk paths.
- Judgment criteria: For “action-type” targets, check whether the sink was actually triggered (a sandbox stand-in can be used); for “output-type” targets, check whether the canary string appears in the final answer.
- Interpreting success rates: The highest success rate of about 25.5% reported means roughly one success in every four attempts. In a security context, this is a magnitude that must be prioritized for fixing, because it does not depend on complex conditions and is repeatable and potentially automatable for exploitation.
Illustrative evaluation pseudocode:
for src in sources: # web pages/documents/emails/skill packagesfor sink in sinks: # outbound/write/execute/publishfor payload in payloads:for _ in range(N): # repeated sampling to measure success ratectx = load(src, payload)out = agent.run(ctx)hit = (sink in out.actions) or (canary in out.text)record(src, sink, payload, hit)
4. Why Success Rates Run High: Root Cause Analysis
- No context partitioning: External content shares the same context as system and user instructions, making it hard for the model to judge priority.
- Tool output is trusted by default: Text returned by a source is treated as trusted data, lacking source annotation and credibility grading.
- Overly concentrated permissions: The agent holds broad permissions, and once induced, the damage surface of sinks is amplified.
- Overly long planning chains: In multi-step tasks, constraints from intermediate steps are easily diluted by subsequent content.
- No human confirmation gate: High-impact actions lack mandatory secondary confirmation.
5. Defense Design: Decoupling “Reading” from “Doing”
- Credibility grading and labeling: Label each piece of context (system/user/external); external content is only data, not a candidate instruction.
- Least privilege and capability tokens: Grant the minimum toolset and minimum data scope per task; sensitive sinks are disabled by default.
- Source-side sanitization: Strip instruction patterns, detect hidden text, and normalize encoding before content enters the context.
- Sink-side policy engine: Outbound sending, execution, and write operations go through policy checks (domain allowlists, parameter templates, quota limits).
- Mandatory confirmation gates: Insert human confirmation or two-person review for high-impact actions.
- Output validation and canary monitoring: Scan answers for sensitive information and canary strings, and trip a circuit breaker on anomalies.
- Full-chain auditing: Record sources, payload fingerprints, planning steps, and sink invocations for traceability and red/blue team exercises.
Illustrative policy configuration:
policy:external_content: data_only # external content is data onlysinks:send_mail: require_confirmationexec_command: disabledsubmit_form: allowlist_onlylimits:max_actions_per_task: 5outbound_domains: [trusted.example]
6. Rollout Recommendations and Acceptance Metrics
It is recommended to incorporate security assessments into the agent release pipeline: automatically run the scenario matrix after every framework or prompt change, and output a success-rate heatmap by source and sink dimensions. Set thresholds (for example, block release if the success rate of any combination exceeds an acceptable baseline). At the same time, establish three lists—“source list,” “sink list,” and “confirmation list”—as mandatory materials for architecture review.
For cloud implementation, you can combine general-purpose category capabilities: object storage to hold evaluation samples and reports, a message queue to decouple evaluation tasks, a container platform to host sandbox agents, and logging and monitoring/alerting services to track anomalous sink invocations. This enables large-scale reproduction and shifts protection left into the development stage.
Conclusion: The essence of indirect prompt injection is a mismatch of trust boundaries. As long as agents still need to read the external world, this risk will not disappear. What can be done is to strictly decouple “reading” from “doing,” and use measurable assessments and enforceable policies to push the success rate into an acceptable range.
