Prompt injection explained: how it works and how to defend against it

Prompt injection explained: how direct and indirect attacks work, ten published cases, what each defence measures, and what to build and test.

Illustration: Prompt injection explained: how it works and how to defend against it

Prompt injection is an attack in which text that a language model reads is taken as an instruction. The model then does what the text says and sets aside what its developer or user asked for. It works because a model receives instructions and data as one stream of text, and no filter has yet been shown to separate the two every time.

This guide is for developers, CTOs and security leads who build products on large language models and AI agents. It covers how the attack works, ten published cases, what each defence has been measured to do, and what to build so an injection that lands has little to reach. Every fact is linked to the body that published it.

ExploitOps WeeklyStories like this one, by email every Friday.Subscribe

Direct and indirect prompt injection

OWASP ranks prompt injection first in its Top 10 for LLM applications. Its entry, LLM01:2025 ↗, says the vulnerability occurs when prompts alter a model’s behaviour or output in ways nobody intended. It splits the attack in two. Direct injection comes from the user’s own input. Indirect injection comes from an outside source the model reads, such as a website or a file.

NIST draws the same line in AI 100-2 E2025 ↗, its taxonomy of attacks on machine learning. In a direct attack the primary user adds instructions that compete with higher-trust ones such as the system prompt. In an indirect attack the attacker is someone else, who controls a resource the system reads.

Diagram: two routes for a prompt injection. In the direct route the user types the instruction into the chat box. In the indirect route an outsider plants it in content the product fetches, and tools then act with the real user’s access.
Direct injection is written by the user. Indirect injection is written by someone the user never meets.

The name dates from 12 September 2022. Simon Willison coined the term ↗ after Riley Goodside showed a translation prompt that could be made to print a taunt in place of the translation. In February 2023 Kai Greshake and co-authors published the first paper on indirect injection ↗. It showed that an attacker could plant instructions in content an application retrieves, and says such applications “blur the line between data and instructions”.

Indirect injection is the kind that reaches other people’s data, because the product’s real user never sees the instruction. Most of this guide is about it.

Why prompt injection works

In a database query, code and data travel separately. A parameterised query tells the database which part is the command and which part is a value. That separation is why SQL injection has a fix.

A language model has no such separation. NIST puts it in one line: generative models combine the data channel and the instruction channel. The system prompt, the user’s request, a fetched page and a tool’s output all arrive as text in one context window.

The UK’s National Cyber Security Centre made the same point in a post of 8 December 2025 ↗. Its author, Dave Chismon, describes the model as an “inherently confusable deputy”: a component with real authority that can be talked into misusing it. The post says the problem may never be totally mitigated, and gives four steps: raise awareness, design with deterministic limits around the model, make attacks harder, and monitor.

Model makers train against this. OpenAI’s Model Spec ↗ says tool outputs, files and quoted text carry no authority by default. Training lowers the rate at which a model follows planted text. It leaves the single channel in place.

How an indirect prompt injection attack occurs: a worked example

The example below is invented. The product and the ticket exist only on this page, and the hidden instruction is described in plain words.

A shop runs a support assistant for its own staff. The assistant can read open tickets. It can look up any customer’s record, saved cards included. Its replies appear in a staff dashboard that displays links and images.

  • →1. A ticket arrives. An outsider opens a support ticket. One line is hidden from human readers. It tells the assistant to look up the customer’s saved cards and include them in a link.
  • →2. A summary is requested. A support agent asks the assistant to summarise today’s open tickets.
  • →3. The model reads the hidden line. The ticket text enters the same context as the agent’s request. The model treats the line as part of its task.
  • →4. A tool is called. The assistant calls the customer lookup. The lookup works for any account, so it returns the saved card details.
  • →5. The reply carries the data. The assistant writes its summary. It adds a link to an outside address, with the card details placed in the address.
  • →6. The data leaves. The dashboard loads the link. The outside server records the address it was asked for, and with it the details.
Diagram: an illustrative six-step path from a poisoned support ticket to data leaving, with two steps marked where a control stops it: scoping the lookup tool to the ticket’s own customer, and loading only addresses on an allowlist.
An illustrative example. Two controls, at steps 4 and 6, would each end the path.

Nothing in this path is a bug in the usual sense. Each part did its job. The failure is in the combination.

Two changes would each end it. A lookup tool scoped to the customer who opened the ticket returns nothing useful at step 4. A dashboard that loads only addresses on an allowlist sends nothing at step 6. Neither change depends on spotting the hidden line.

The three conditions that make it dangerous

In June 2025 Simon Willison named the combination the lethal trifecta ↗. An agent is exposed when it has all three of these at once: access to private data, exposure to untrusted content, and the ability to communicate externally.

Meta turned this into a design rule on 31 October 2025. Its Agents Rule of Two ↗ says an agent should hold no more than two of three properties in one session: it processes untrustworthy inputs, it has access to sensitive systems or private data, and it can change state or communicate externally. If a task needs all three, a person approves.

Diagram: three overlapping circles labelled private data, untrusted content and a way out. The area where all three meet is marked as the place where data can leave. Three cards show what happens when each one is removed.
Remove any one of the three and an injection has far less to work with. After Simon Willison and Meta.

Both give a team a question for a design review. For each feature, list what the model can read, who can write the content it reads, and what it can send or change. A feature with all three needs a control that holds when the model has been fooled.

Published cases

Each row is a public write-up or advisory. The last column gives the fix or status as the source states it.

Case and dateWhere the instruction hidWhat it reachedFix or status
Slack AI, PromptArmor ↗, 20 Aug 2024A message in a public channel the attacker createdAn API key from a private channel, placed in a link shown to the userSlack said ↗ it patched on 20 Aug 2024 and found no evidence of unauthorised access
ChatGPT memory (“SpAIware”), Johann Rehberger ↗, 20 Sep 2024An untrusted web page or documentLong-term memory. Later chats were sent out through image addressesSending path fixed in version 1.2024.247. Planting memories remained possible
GitLab Duo, Legit Security ↗, 20 May 2025Hidden text in merge requests, comments and codePrivate source code, sent out through an HTML image tag in the streamed answerReported 12 Feb 2025 and fixed by GitLab
GitHub MCP server, Invariant Labs ↗, 26 May 2025An issue in a public repositoryPrivate repositories, published in a public pull requestNo server patch: the server worked as designed. Advice: one token per repository
Microsoft 365 Copilot, CVE-2025-32711 ↗ (reported as EchoLeak), 11 Jun 2025The advisory says “AI command injection” and gives no pathInformation disclosure over a network. Scored 9.3 by Microsoft and 7.5 by NVD ↗Fully mitigated on Microsoft’s servers, with no customer action
Supabase MCP, General Analysis ↗, 8 Jul 2025A message sent through a public support formA table of integration tokens, read by a coding agent with a full-access key and written into the ticketA design finding. Advice: read-only mode and review of tool calls
Cursor, CVE-2025-54135 ↗ and CVE-2025-54136 ↗, Aug 2025Injected text that made the agent write an MCP settings file; and an approved MCP entry changed later in a shared repositoryCommands run on the developer’s machineFixed in 1.3.9 and 1.3. MCP settings changes now need approval
Gemini, SafeBreach ↗, 6 Aug 2025The title of a calendar inviteSmart-home controls, a Zoom call, and email subject lines sent out in a web addressReported Feb 2025. Google described added layers in June 2025
Perplexity Comet, Brave ↗, 20 Aug 2025A Reddit comment behind a spoiler tagThe account’s email address and a one-time code from Gmail, posted back as a replyBrave’s later tests found the fix incomplete
Cursor, CVE-2026-22708 ↗, 14 Jan 2026Direct or indirect injection, per the advisoryShell environment variables, set through built-ins the command allowlist missedFixed in 2.3. Needed settings that are off by default

The cases share a shape. In every one the instruction arrived in content the product was built to read: a ticket, an invite, a comment, a repository. The agent already had access to something private, and there was a way out. Most fixes landed in the product around the model: what gets displayed, what a tool may touch, and what needs approval.

Two rows had no patch at all. The GitHub and Supabase write-ups describe servers that worked as designed. The exposure came from the access the agent had been given, and that is the builder’s decision.

How the data gets out

An injection needs a channel to send data along. The write-ups name these.

  • →Images. The answer contains an image whose address holds the data. The interface fetches it with no click. See GitLab Duo ↗ and SpAIware ↗.
  • →Links. The answer contains a link whose address holds the data. The user is nudged to click. See Slack AI ↗.
  • →Tool calls. A pull request, a database write, a web fetch, a posted reply. See GitHub MCP ↗, Supabase MCP ↗ and Comet ↗.
  • →Memory. The instruction is saved to long-term memory and applies to later sessions. See SpAIware ↗.
  • →MCP tool descriptions. A tool’s own description carries instructions that the model reads and the user rarely sees. Invariant Labs calls this tool poisoning ↗, and describes descriptions that change after approval.
  • →Invisible characters. Text in Unicode Tag characters ↗ is invisible in most interfaces and readable by some models.
  • →Hidden text. White text, HTML comments and collapsed sections. See Brave ↗ and Legit Security ↗.
  • →Calendar invites and email. Content lands in a user’s account unasked. See SafeBreach ↗.
  • →Retrieved documents. Any indexed document can carry an instruction, as NIST ↗ and Greshake and co-authors ↗ describe.

For each channel, ask whether your product has it and what limits it.

Defences, and what each has been measured to do

Several defences have published results. Read each number with its test conditions.

DefenceWhat it doesReported resultLimit
Spotlighting (Hines et al. ↗, Mar 2024)Marks or transforms untrusted text so the model can tell where it came fromAttack success fell from above 50% to below 2% in the authors’ testsTested on GPT-family models
Detection classifiers, such as Microsoft Prompt Shields ↗A separate model screens user prompts and documents for attack patternsNo headline figure in the product pageTrained mainly on English, by Microsoft’s own note
Layered product defences (Google ↗, Jun 2025)Classifiers, reminders to the model, markdown sanitising, redaction of suspicious addresses, user confirmationNo single figurePresented as layers that work together
Model and product safeguards (Anthropic, Aug 2025 ↗; Nov 2025 ↗)Safety mitigations around a browser agent, then a newer model with new safeguardsBrowser agent: 23.6% to 11.2% over 123 test cases. Later, 1.4% against an adaptive attacker given 100 attemptsAnthropic says no browser agent is immune
CaMeL (Debenedetti et al. ↗, Mar 2025)Separates control flow from data flow, so untrusted data cannot choose the toolCompleted 77% of AgentDojo tasks with provable security, against 84% with no defenceSome tasks no longer complete
Design patterns (Beurer-Kellner et al. ↗, Jun 2025)Six patterns that limit what an agent can do after it reads untrusted textA design method. No rateThe authors say general-purpose agents are unlikely to offer reliable guarantees

The six patterns in that last row are Action-Selector, Plan-Then-Execute, LLM Map-Reduce, Dual LLM, Code-Then-Execute and Context-Minimization. Each trades some flexibility for a limit that holds whatever the model reads.

Now the caution. In October 2025 a paper titled The Attacker Moves Second ↗ tested 12 published defences against attackers who adapt to each one. The adaptive attacks got past all 12, with success above 90% for most. Most of those defences had first reported rates near zero.

A filter that catches 95% of attacks is, in his words, “very much a failing grade” in security, because an attacker tries again. OpenAI wrote in December 2025 ↗ that prompt injection is “unlikely to ever be fully ‘solved’”.

Diagram: five defence layers in order, input screening, tool permissions, human approval, egress control and logging, each with what it stops and its limit.
Five layers. The first lowers how often an injection lands. The next three limit what a landed injection can do.

The honest conclusion has two halves. Filters reduce. Screening, spotlighting and training lower the rate. Architecture contains. Permissions, approvals and outbound limits decide what happens on the attempt that gets through.

What to build: an engineering checklist

A team can start each item today, with any model or vendor.

  • →Give each tool the least access that does the job. A lookup takes the current customer’s id from the session, never from the model. Source: OWASP LLM01:2025 ↗; the OWASP AI Agent Security Cheat Sheet ↗.
  • →Keep untrusted content in its own place. Pass fetched text as a tool result, encoded as data, never in system or developer messages. Sources: Anthropic’s guidance ↗ and OpenAI’s agent safety guide ↗.
  • →Ask a person before consequential actions. Sending, deleting, paying and publishing each get a prompt that shows exactly what will happen. Sources: OWASP LLM01:2025 ↗; Meta ↗.
  • →Close the outbound channels sensitive data could use. Display images and links, and let the agent fetch, only from an allowlist. Sources: Google ↗; Anthropic’s computer use documentation ↗.
  • →Treat model output as untrusted input. Encode it before display, set a strict content security policy, and use parameterised queries for anything it feeds. Source: OWASP LLM05:2025 ↗.
  • →Issue credentials per task. One token per repository or project, short-lived, with the narrowest scope. Sources: Invariant Labs ↗; General Analysis ↗.
  • →Treat memory as untrusted content. Show users what is saved, and keep fetched content from writing to it unseen. See the OWASP AI Agent Security Cheat Sheet ↗ on memory security.
  • →Log every prompt, tool call and result. Logs are how you learn that an injection was tried. Source: NCSC ↗.
  • →Keep MCP servers on a short lead. The protocol’s security best practices ↗ asks for minimal scopes, sandboxed local servers, and the exact command shown before consent. It leaves tool poisoning out, so add a rule: review tool descriptions, and approve again when one changes.
  • →Run high-risk agents in a sandbox. A container or virtual machine limits what a hijacked session can touch. Source: Anthropic’s computer use documentation ↗.

How to test your own product

Testing for prompt injection is a measurement, repeated. The OWASP AI Testing Guide ↗, first released on 26 November 2025, has a test case for it: AITG-APP-02, Testing for Indirect Prompt Injection. A plan in seven steps:

  • →1. List every input. Every place outside text reaches the model: tickets, emails, uploads, web pages, tool results, memory, tool descriptions.
  • →2. List every tool and every way out. What each tool can read and change, and where the interface loads an address.
  • →3. Mark the paths where all three conditions meet.
  • →4. Write a rule for each path, in plain words. For example: “content inside a ticket never causes a lookup of a different customer”.
  • →5. Plant harmless test instructions. Put a marker instruction in each input that asks for a visible, harmless action. Use test accounts and test data only.
  • →6. Measure, many times. Models vary from run to run. Repeat each case and record how often the marker action happens.
  • →7. Run it again on every change. A new model version, a prompt edit or a new tool can each change the result.

The number that comes out is the attack success rate: the share of test cases in which the attacker’s goal was met. The AgentDojo ↗ benchmark reports it beside two utility figures, one for ordinary use and one for use under attack. Anthropic reports a per-attempt rate and a rate against an attacker who adapts. For any rate, ask: against which attacks, over how many attempts, and with or without adaptation.

Open-source tools cover much of the work:

ToolMaintained byWhat it is
garak ↗NVIDIAA vulnerability scanner for language models, under Apache-2.0
PyRIT ↗MicrosoftA toolkit for finding security and safety weaknesses in generative AI systems, under MIT
promptfoo ↗The promptfoo projectOpen-source red teaming, with plugins for attack types
Giskard ↗GiskardAn evaluation and testing library for LLM agents, under Apache-2.0
Inspect ↗UK AI Security InstituteA framework for language model evaluations
AgentDojo ↗Debenedetti et al.A benchmark of 97 agent tasks and 629 security test cases

Tools run the known attacks. If you buy outside testing, the buyer’s guide to penetration testing services covers scope, reports and retests. For code written by AI assistants, see AI code security tools compared.

Questions to ask a vendor that claims to stop prompt injection

The NCSC advises scepticism towards any product that claims to stop prompt injection. Ask these.

  • →Which attack sets was the product measured against, and who chose them?
  • →What was the attack success rate with the product on, and with it off?
  • →Was the attacker allowed to adapt to the defence? Over how many attempts?
  • →What is the false positive rate on ordinary traffic, and what does a block look like to the user?
  • →Which languages were tested?
  • →Does it screen indirect inputs: tool results, documents, memory and MCP tool descriptions?
  • →What limits the damage on the attempt it misses?
  • →Can we run our own test cases against it before we buy?
  • →How are we told when a bypass is found?

Clear answers describe a filter with a measured rate. That is a useful layer. Your own permissions and outbound limits remain the containment.

What regulators and standards say

No law names prompt injection yet. Several documents cover it in substance.

DocumentDateWhat it says
EU AI Act, Article 15(5) ↗2024; amended 2026High-risk AI systems must resist third parties who exploit vulnerabilities, including data poisoning, model poisoning, adversarial examples and confidentiality attacks. Under Regulation (EU) 2026/1744 ↗ the high-risk rules apply from 2 December 2027 (Annex III) and 2 August 2028 (Annex I)
NIST AI 600-1 ↗26 July 2024Defines direct and indirect prompt injection under information security, with suggested action MS-2.7-007
NIST AI 100-2 E2025 ↗24 March 2025The taxonomy used above. It states that current mitigations give partial protection
OWASP Top 10 for Agentic Applications 2026 ↗9 December 2025Lists Agent Goal Hijack first, as ASI01
Careful Adoption of Agentic AI Services ↗1 May 2026Joint guidance from Australia’s ASD ACSC, CISA and the NSA in the US, and the cyber agencies of Canada, New Zealand and the UK

Mapping your controls to OWASP LLM01:2025 and the agentic Top 10 is a practical start.

Where an attacker’s‑eye test fits

Checklists and scanners cover known ground. The paths that matter are specific to your product: this tool, with that credential, reading those tickets. Finding them takes someone who thinks like the attacker.

MATT is one option for that work. It tests a product the way a modern, AI-assisted attacker does, writes each finding as a plain-English rule with a check, and re-proves the rules on every release, so each rule is reported as holding or broken. Its attack library includes a prompt injection pattern for agents with tools, and there is a page on securing AI-written code. Whichever route you choose, ask for the paths tested, the rate measured, and a check you can run again.

Sources

Every source is linked where it is used. The main ones, by publisher:

Product and company names belong to their owners and are named because they appear in the public write-ups cited. No affiliation is implied.

Questions

What is prompt injection?

Prompt injection is an attack in which text a language model reads is taken as an instruction, so the model follows the text and sets aside what its developer or user asked for. OWASP lists it first, as LLM01:2025, in its Top 10 for LLM applications.

What is indirect prompt injection?

It is prompt injection where the instruction comes from content the model reads, such as a web page, email, file or ticket, and the user never typed it. NIST AI 100-2 describes the attacker as controlling a resource the system reads.

How does an indirect prompt injection attack occur?

An outsider plants an instruction in content your product will fetch. A real user asks the product to do something with that content. The model reads the instruction as part of its task and uses a tool or a displayed link to act on it.

Can a prompt injection attack be fully prevented?

No published defence stops every attempt. The UK NCSC says it may never be totally mitigated, and OpenAI says it is unlikely to ever be fully solved. Filters lower the rate. Permissions, approvals and outbound limits contain what gets through.

How do you defend against prompt injection?

Give each tool the least access it needs, keep untrusted content separate, ask a person before consequential actions, close outbound channels for sensitive data, treat model output as untrusted, and log every tool call. Then add screening as a further layer.

How do you test for prompt injection?

List every input and tool, plant harmless marker instructions in each input using test data, and measure how often the marker action happens. OWASP’s AI Testing Guide has a test case for it, AITG-APP-02. Repeat on every model, prompt or tool change.

ExploitOps WeeklyBy email

The week in security,in one email.

Every Friday: the five to seven stories that mattered for people who build software. What happened, why it matters and the source, then rules to check before Monday. Stop any time.

Know where you stand.

Book a discovery call→

Let’s understand your priority

What brings you to MATT?

What would you like help with?
01 / 02