LLM Output Security: Preventing XSS and SQL Injection at Sink Boundaries
Treat LLM responses as untrusted input. See how prompt injection turns generated text into XSS or SQLi, and enforce context encoding and parameterized queries.

Table of Contents (8)
- Why Does LLM Output Cross a Critical Trust Boundary?
- How Do Browsers Turn Generated Text into Cross-Site Scripting (XSS)?
- Vulnerable vs. Hardened HTML and Markdown Handling in Python
- How Does AI-Generated Text Trigger SQL Injection (SQLi)?
- The Harder Case: Securing Text-to-SQL Features
- Vulnerable vs. Hardened SQL Patterns
- Why Do Naive Defenses Fail Against Malicious Model Output?
- How Should You Architect Defense-in-Depth for LLM Sinks?
A backend engineer wires a large language model into a customer support dashboard at 2 AM so agents can summarize ticket threads or ask natural-language questions about account activity. Because the API call originates from the server using a private provider key, it is tempting to treat the returned JSON payload as trusted internal data. Five minutes later, the generated text is interpolated straight into an HTML template or a database query.
That shortcut rests on a dangerous assumption. A language model is not a deterministic compiler producing verified output; it is a probabilistic text generator whose context window blends your system instructions with user prompts, retrieved emails, web pages, and database records. When an external document contains hidden instructions, the model can echo attacker-controlled markup or SQL fragments right back to your application. Handing raw LLM text directly to a browser or a database parser is like letting anyone who mails a letter to your office dictate edits straight into your production templates.
Why Does LLM Output Cross a Critical Trust Boundary?
LLM output crosses a trust boundary because the model merges trusted system instructions with untrusted external data inside a single shared token stream. Once your backend forwards that generated text to a browser DOM or a SQL engine without context-specific controls, attacker-supplied payloads embedded in prompts or retrieved documents become executable code.
To see why, trace how data enters a modern AI feature. In a direct prompt injection, the end user types malicious syntax into a chat box and asks the model to repeat or transform it. In an indirect prompt injection, the danger arrives silently through Retrieval-Augmented Generation (RAG), email ingestion, or web scraping: a customer embeds hidden text inside a support ticket, a resume PDF, or a public web page, and the model reads that untrusted content alongside your system prompt.
System prompts cannot enforce privilege separation because transformer attention operates uniformly across the combined token sequence. Instructing a model to "never output HTML tags or SQL keywords" acts as a soft behavioral preference, not an access control boundary. Your application server must therefore treat every byte returned by an LLM API with the exact same suspicion as an unauthenticated HTTP query parameter, enforcing deterministic safety checks at every downstream sink.
How Do Browsers Turn Generated Text into Cross-Site Scripting (XSS)?
Browsers trigger Cross-Site Scripting when unencoded LLM output enters a webpage in a position where the parser switches from reading passive text to interpreting HTML markup, attribute delimiters, or JavaScript. Because browsers execute multiple layered parsers on a single document, escaping data for the wrong rendering context still lets attackers break out and run code inside the victim's authenticated origin.
An HTML document is not flat text; it is a state machine. When the browser parses content inside an ordinary element such as a <div> or <p> tag (an HTML body context), it stays in the data state until it encounters <, which transitions the tokenizer into the tag open state. If raw LLM output contains <img src="x" onerror="fetch('/api/export')">, the browser constructs a live image element, fails to load x, and immediately executes the onerror handler with full access to the user's DOM, session state, and authenticated endpoints.
Different positions inside the same page invoke entirely different parser rules, which is why context-specific encoding matters:
- HTML element bodies: Converting
&,<,>,", and'into HTML character references (&,<,>,",') keeps the HTML parser in text mode. When updating the DOM from client-side JavaScript, assigningelement.textContent = llmTextcreates a pure text node without invoking the HTML parser at all, so you pass the original string without pre-encoding it. Never assign untrusted text toHTMLScriptElement.textContent, however, because script element text executes as JavaScript. - HTML attributes: Text attributes such as
titleorvaluemust always be wrapped in double or single quotes. In unquoted attributes, whitespace terminates the value and lets an attacker inject a new attribute such asonmouseover=.... Even inside quoted attributes, HTML attribute encoding cannot neutralize event-handler attributes (onload,onclick) orsrcdoc, because the HTML parser decodes character references before handing the resulting string to the JavaScript or sub-document parser. Attach listeners withaddEventListener()using static functions, and useelement.setAttribute("title", value)only on safe text attributes. - URL attributes: Placing an LLM-generated link into
hreforsrcintroduces a URL context wherejavascript:ordata:payloads execute code when clicked or loaded. Even though modern React (React 19) blocksjavascript:URLs insrcandhref, applications still need explicit scheme validation across server templates, custom renderers, and legacy components. - Markdown pipelines: Most AI chat interfaces convert LLM output from Markdown into HTML. Standard CommonMark permits raw inline HTML blocks and arbitrary link schemes by default. Without disabling raw HTML or filtering the rendered HTML through a strict allowlist sanitizer, a model tricked into outputting
[Open report](javascript:alert(document.domain))or inline<svg onload=...>compromises every user who views the thread.
| Rendering Context | Browser Parser Behavior | Required Defense | Common Engineering Mistake |
|---|---|---|---|
HTML element body (<div>) |
Switches to tag parsing on < |
Framework auto-escaping, HTML entity encoding, or element.textContent |
Using innerHTML or dangerouslySetInnerHTML for raw text |
HTML text attribute (value="...") |
Breaks out on matching quote or whitespace | Quoted attributes with attribute encoding or element.setAttribute |
Leaving attributes unquoted or injecting into onclick handlers |
Link or media attribute (href, src) |
Executes javascript: URIs on navigation |
Explicit URL scheme allowlist (http, https, mailto) or relative paths |
Assuming HTML entity encoding stops javascript: schemes |
| Rich Markdown output | Renders embedded inline HTML tags and links | Disable raw HTML in parser plus strict allowlist HTML sanitizer | Allowing raw HTML passthrough in Markdown converters |
Inline <script> data |
Executes JS syntax before HTML entity rules | JSON serialization into <script type="application/json"> or data attributes |
Interpolating LLM strings directly inside JS template literals |
Vulnerable vs. Hardened HTML and Markdown Handling in Python
Notice how easily a quick Flask prototype introduces XSS when it bypasses template auto-escaping with string formatting:
from flask import Flask, render_template_string
app = Flask(__name__)
@app.route("/summary")
def vulnerable_summary():
# Simulated indirect prompt injection echoed by the LLM
llm_output = "Summary complete. <img src=x onerror=alert('XSS')>"
# Vulnerable: f-string injects raw markup before Jinja2 sees the template
page = f"""
<!doctype html>
<html><body>
<div class="ai-reply">{llm_output}</div>
</body></html>
"""
return render_template_string(page)Because llm_output is interpolated into page before render_template_string compiles the Jinja2 template, Jinja2 treats the <img> tag as static developer markup and never escapes it. Passing llm_output as a template context variable enables Jinja2 auto-escaping, and adding a strict Markdown-plus-sanitizer pipeline lets you support formatting safely:
from urllib.parse import urlparse
import bleach
from flask import Flask, render_template_string
from markupsafe import Markup
import markdown
app = Flask(__name__)
ALLOWED_TAGS = ["p", "strong", "em", "ul", "ol", "li", "code", "pre", "a"]
ALLOWED_PROTOCOLS = ["http", "https", "mailto"]
def safe_link_filter(attrs, new=False):
href = attrs.get((None, "href"), "")
parsed = urlparse(href)
# Allow relative paths or explicitly allowlisted URI schemes only
if parsed.scheme and parsed.scheme.lower() not in ALLOWED_PROTOCOLS:
attrs.pop((None, "href"), None)
attrs[(None, "rel")] = "noopener noreferrer"
return attrs
def render_llm_markdown(raw_text: str) -> Markup:
raw_html = markdown.markdown(raw_text, extensions=["fenced_code"])
cleaned = bleach.clean(
raw_html,
tags=ALLOWED_TAGS,
attributes={"a": ["href", "rel", "title"]},
protocols=ALLOWED_PROTOCOLS,
strip=True,
)
linked = bleach.linkify(cleaned, callbacks=[safe_link_filter])
return Markup(linked)
@app.route("/summary")
def hardened_summary():
llm_output = "Check [the ticket](javascript:alert(1)) <img src=x onerror=alert(1)>"
safe_html = render_llm_markdown(llm_output)
return render_template_string(
"<!doctype html><html><body><div class='ai-reply'>{{ reply }}</div></body></html>",
reply=safe_html,
)In this hardened version, plain text paths rely on Jinja2's automatic context escaping, while rich formatting passes through an explicit allowlist sanitizer that strips arbitrary tags, drops event attributes, and neutralizes dangerous link schemes before wrapping the result in Markup.
How Does AI-Generated Text Trigger SQL Injection (SQLi)?
AI-generated text causes SQL injection whenever an application concatenates model output directly into a SQL statement before the database compiles the query. Whether the model produces a literal filter value or constructs an entire analytics query, string interpolation allows injected quotes and keywords to rewrite the query's abstract syntax tree (AST).
Database engines process queries in distinct phases. First, a lexer and parser tokenize the SQL text and build an AST representing commands (SELECT, UPDATE, DROP), table identifiers, operators, and literal values. Only after parsing succeeds does the planner optimize and run the AST. When application code builds a SQL string with format operators (f"SELECT * FROM tickets WHERE category = '{llm_category}'"), the database receives one undifferentiated string. If an attacker tricks the LLM into returning billing' OR '1'='1, the parser closes the string literal early and attaches a boolean predicate that dumps every tenant's records.
Parameterized queries (prepared statements) enforce structural separation at the database wire protocol level. Instead of merging data into the SQL text, you send a static SQL template containing parameter placeholders (? in SQLite, $1 in PostgreSQL) alongside a separate array of bound values. The engine compiles the AST from the static template first, locking down the query structure, and inserts each bound value strictly as a typed scalar leaf node that can never be re-parsed as SQL syntax.
The Harder Case: Securing Text-to-SQL Features
Parameterized queries protect scalar values, yet many teams build analytics copilots where the LLM is explicitly asked to generate SELECT queries, dynamic ORDER BY clauses, or table joins. Bound parameters cannot represent SQL keywords, table names, or column identifiers.
If you execute raw LLM-generated SQL directly, a prompt injection inside a document summary or chat input can pivot the query into UNION SELECT against sensitive credential tables, stack destructive statements, or call expensive database functions like pg_sleep(30) for denial of service. To secure text-to-SQL systems, replace free-form SQL generation with a two-layer boundary:
- Prefer structured intent over raw SQL: Configure the LLM via strict JSON schema tool-calling to emit a constrained query specification (metric name, allowed filter fields, sort direction, limit). Deterministic backend code then maps validated enum keys to an allowlist of column names and builds a parameterized query.
- Parse and enforce AST policies when SQL is mandatory: If users truly need ad-hoc SQL syntax, parse the generated string with a SQL AST parser before touching the database, reject multi-statement batches, permit only
SELECTnodes referencing allowlisted schemas and columns, and run the query over a dedicated read-only database connection with row-level security and a strictstatement_timeout.
Vulnerable vs. Hardened SQL Patterns
The following Python example contrasts unsafe interpolation with safe parameterization for value lookups and structured intent mapping for AI analytics:
import json
import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("CREATE TABLE tickets (id INTEGER, customer TEXT, status TEXT)")
cur.execute("INSERT INTO tickets VALUES (1, 'app.example', 'open')")
# VULNERABLE: Raw LLM text interpolated into SQL
llm_filter = "open' OR '1'='1"
unsafe_query = f"SELECT id, customer FROM tickets WHERE status = '{llm_filter}'"
# Executes altered AST and returns rows regardless of status
# SAFE 1: Parameterized query for scalar values
cur.execute("SELECT id, customer FROM tickets WHERE status = ?", (llm_filter,))
# SAFE 2: Structured JSON intent mapped to an identifier allowlist for AI analytics
ALLOWED_SORT_COLUMNS = {"id": "id", "customer": "customer", "status": "status"}
ALLOWED_DIRECTIONS = {"asc": "ASC", "desc": "DESC"}
llm_json_intent = '{"status": "open", "sort_by": "customer", "direction": "asc", "limit": 20}'
intent = json.loads(llm_json_intent)
sort_col = ALLOWED_SORT_COLUMNS.get(intent.get("sort_by"))
sort_dir = ALLOWED_DIRECTIONS.get(intent.get("direction"))
limit = int(intent.get("limit", 10))
if not sort_col or not sort_dir or not (1 <= limit <= 100):
raise ValueError("Rejected invalid AI query intent")
safe_sql = f"SELECT id, customer FROM tickets WHERE status = ? ORDER BY {sort_col} {sort_dir} LIMIT ?"
cur.execute(safe_sql, (intent["status"], limit))Notice how sort_col and sort_dir never originate from the raw JSON string at runtime; they are looked up from hardcoded Python dictionaries, while status and limit travel through bound parameters.
Why Do Naive Defenses Fail Against Malicious Model Output?
Naive defenses such as system-prompt prohibitions, regex keyword filters, and input-time escaping fail because they attempt to police unpredictable text patterns outside the final parser context. Attackers routinely bypass lexical filters with nested tags, encoding tricks, and indirect prompt injections that coerce the model into assembling payloads piece by piece.
Four common shortcuts break repeatedly in production systems:
- Relying on prompt guardrails or classifier sidecars: Asking a secondary LLM to check whether the primary LLM emitted XSS or SQLi still yields a probabilistic guess. An attacker can ask the primary model to output hex-encoded fragments, split tags across Markdown constructs, or exploit parser quirks that look benign to a language classifier.
- Regex and substring blocklists: Stripping
<script>once turns<scr<script>ipt>into<script>. BlockingonerrororSELECTmisses dozens of valid HTML event attributes (ontoggle,onfocus,onanimationstart) and SQL comment obfuscation (SEL/**/ECT). Context-free grammars like HTML and SQL cannot be safely neutralized with regular expressions. - Escaping on ingestion instead of at the sink: HTML-encoding text before saving it to Postgres corrupts non-HTML consumers such as JSON APIs, CSV exports, and mobile clients, forcing developers to decode it later and reintroducing bugs. Worse, HTML entity encoding does nothing to prevent SQL injection or
javascript:URL execution if that stored value reaches a different sink. - Framework escape hatches: Modern frontend frameworks auto-escape ordinary template bindings by default, which lulls teams into thinking XSS is solved. Yet AI UIs frequently bypass framework protections to render rich text using React's
dangerouslySetInnerHTML, Angular'sbypassSecurityTrustAs*methods, Lit'sunsafeHTML, or Polymer'sinner-h-t-m-landhtmlLiteral. Coverage is asymmetric: securing 99 components while leaving one unsanitized escape hatch exposes the entire origin.
How Should You Architect Defense-in-Depth for LLM Sinks?
Resilient LLM applications pair deterministic sink-level encoding and sanitization with browser and database isolation layers so that a missed check cannot escalate into full compromise. Following Secure by Design principles, these protections live inside shared libraries, middleware, and infrastructure policies rather than relying on individual developers remembering to sanitize every endpoint.
On the browser side, deploy a strict Content Security Policy (CSP) alongside context-aware encoding. Disallow inline JavaScript using cryptographic nonces or hashes, restrict embedding with frame-ancestors 'none' (or explicit trusted origins), and enable require-trusted-types-for 'script'. Trusted Types changes the browser's DOM API contract: dangerous sinks like element.innerHTML throw a runtime TypeError if handed a plain string, forcing every rich-text path to return an object produced by a centralized TrustedTypePolicy backed by an audited sanitizer. Pair CSP with HttpOnly, Secure, and SameSite=Strict (or Lax) session cookies with short lifetimes so even a worst-case DOM bug cannot read session tokens directly.
These architectural controls involve real operational tradeoffs that engineering teams should plan for upfront. Turning on Trusted Types and strict CSP in enforcement mode immediately can break legacy analytics scripts or inline event handlers. Roll them out using Content-Security-Policy-Report-Only first to capture violation telemetry across staging and production traffic before flipping to enforcement. Likewise, replacing free-form text-to-SQL with structured JSON schemas limits users from asking arbitrary multi-join queries on day one, but eliminates an entire class of query-rewriting bugs and keeps database CPU predictable.
Finally, wire telemetry and adversarial tests into your CI/CD pipeline so regressions cannot slip in silently:
- Monitor sink anomalies: Emit structured alerts whenever your HTML sanitizer strips disallowed tags or attributes, your URL validator drops a non-allowlisted scheme, your SQL parser rejects an unexpected AST node, or browsers send CSP violation reports.
- Run polyglot regression tests: Feed simulated indirect prompt injections containing
<svg onload=...>,javascript:Markdown links, and' UNION SELECTstrings through your LLM response handlers in automated tests to verify that rendered HTML and SQL queries remain inert. - Enforce least-privilege database roles: Isolate AI query workloads on read-only credentials scoped to explicit views, backed by row-level security and short statement timeouts.
- Audit framework escape hatches: Block raw DOM and raw SQL helpers (
dangerouslySetInnerHTML,bypassSecurityTrustAs*,unsafeHTML,text()raw SQL fragments) in code review and static analysis rules unless paired with an approved sanitizer or parameterized wrapper.
Treating LLM responses as untrusted external input aligns AI features with decades of hard-won web and database security discipline. When every HTML render, URL attribute, and SQL query enforces strict boundary semantics at the sink, even a fully prompt-injected model cannot turn generated text into executable code.
References & Sources
Related Security Reads

Rate Limiting and Brute-Force Defense: Blocking Attackers, Not Users
Build multi-dimensional rate limiting with GCRA token buckets, trusted proxy parsing, and HTTP 429 cooldowns to block brute force without self-DoS.

TLS Handshake in HTTPS: How Browsers Negotiate Encrypted Web Connections
Explore how TLS 1.3 and 1.2 handshakes verify server identity, derive forward-secret AEAD keys, prevent downgrade attacks, and handle 0-RTT replay tradeoffs.

Software Bill of Materials (SBOM): Internals, Formats, and CVE Response
Learn how SBOMs map transitive dependencies via CycloneDX, SPDX, and PURLs, integrate with VEX and SLSA attestations, and cut CVE triage from hours to seconds.

Kubernetes NetworkPolicy: Locking Down East-West Pod Traffic
By default, every Kubernetes pod can reach any other pod. Learn how CNI plugins enforce NetworkPolicies, avoid YAML AND/OR traps, and block lateral movement.
Get new posts by email
No ads, no tracking. Just new posts, unsubscribe any time.
Comments
No comments yet.