Reflected and Stored XSS
Cross-site scripting (XSS) is injection into a web page: text from an attacker ends up in a page as HTML or JavaScript, and the victim's browser runs it inside the vulnerable site's origin. From there the script can do anything the user can: read the page, call the site's APIs with the user's cookies, change their e-mail address, show a fake login form. The survey lesson introduced the three kinds. This lesson builds the two server-side kinds on a toy app in your sandbox: reflected XSS, where the payload travels in the request (usually a link the victim is tricked into opening), and stored XSS, where it is saved once and served to every visitor. It ends with the output encoding that fixes both. DOM-based XSS, which never touches the server, is the next lesson.
Definitions
- Reflected XSS: a request parameter is echoed into the response without encoding. Delivered by a crafted link, a form on another site, or a redirect.
- Stored (persistent) XSS: input is saved (a comment, a profile field, a file name, a support ticket) and rendered later to other users, including administrators.
- Output encoding: converting characters that are special in the output context into their escaped forms, for HTML text
&→&,<→<,>→>,"→",'→'. Python'shtml.escape(s, quote=True)does this. - Context: where in the page the data lands (HTML text, an attribute, a URL, JavaScript, CSS). Each needs its own encoding; the DOM lesson covers them.
The server side: what the app sends
The toy app (on 127.0.0.1 in your sandbox) has a search page that echoes q and a guestbook that stores comments. curl shows the exact HTML a browser would receive. The payloads are classic harmless probes: they only change text in the page; a real attacker's script would act as the user instead.
cat > app.py <<'PY'
import html, sys
from urllib.parse import parse_qs
from wsgiref.simple_server import make_server, WSGIRequestHandler
FIXED = sys.argv[1] == "fixed"
COMMENTS = []
esc = (lambda s: html.escape(s, quote=True)) if FIXED else (lambda s: s)
class Quiet(WSGIRequestHandler):
def log_message(self, *args):
pass
def app(environ, start_response):
path = environ["PATH_INFO"]
if path == "/search":
q = parse_qs(environ.get("QUERY_STRING", "")).get("q", [""])[0]
body = f"<h1>Results for {esc(q)}</h1>"
elif path == "/guestbook" and environ["REQUEST_METHOD"] == "POST":
form = parse_qs(environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH") or 0)).decode())
COMMENTS.append(form.get("text", [""])[0]) # stored raw: encoding happens on output
body = "saved"
else:
body = "<ul>" + "".join(f"<li>{esc(c)}</li>" for c in COMMENTS) + "</ul>"
headers = [("Content-Type", "text/html; charset=utf-8")]
if FIXED:
headers.append(("Content-Security-Policy", "script-src 'none'; object-src 'none'; base-uri 'none'"))
start_response("200 OK", headers)
return [body.encode()]
make_server("127.0.0.1", 8000, app, handler_class=Quiet).serve_forever()
PY
for mode in vulnerable fixed; do
python3 app.py $mode &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done
echo "=== $mode"
echo " reflected:"
curl -s -G --data-urlencode 'q=<script>document.title="xss-probe"</script>' http://127.0.0.1:8000/search; echo
curl -s -o /dev/null --data-urlencode 'text=Nice shop!' http://127.0.0.1:8000/guestbook
curl -s -o /dev/null --data-urlencode 'text=<img src=x onerror="document.body.dataset.probe=1">' http://127.0.0.1:8000/guestbook
echo " stored, as every visitor receives it:"
curl -s http://127.0.0.1:8000/guestbook; echo
curl -s -D - -o /dev/null http://127.0.0.1:8000/ | tr -d '\r' | grep -i '^content-security-policy' | sed 's/^/ header: /'
kill %1; wait 2>/dev/null
done=== vulnerable
reflected:
<h1>Results for <script>document.title="xss-probe"</script></h1>
stored, as every visitor receives it:
<ul><li>Nice shop!</li><li><img src=x onerror="document.body.dataset.probe=1"></li></ul>
=== fixed
reflected:
<h1>Results for <script>document.title="xss-probe"</script></h1>
stored, as every visitor receives it:
<ul><li>Nice shop!</li><li><img src=x onerror="document.body.dataset.probe=1"></li></ul>
header: Content-Security-Policy: script-src 'none'; object-src 'none'; base-uri 'none'
In the vulnerable mode the payloads appear byte for byte in the HTML: the browser would parse a real <script> element and a real <img> with an onerror handler. In the fixed mode the same characters arrive as <script> and <img …>, which the browser displays as text. The comments are stored raw and encoded when they are output: the database keeps what the user typed, and each output context applies its own encoding. The fixed app also sends a CSP that forbids scripts entirely, a second layer in case one output is missed.
The browser side: what the HTML does
The playground renders the two responses from the session, the vulnerable one and the fixed one, in its sandboxed frame (its own opaque origin, so the payload can only touch this frame).
<!doctype html>
<style>body{font:14px system-ui;margin:8px} section{border:1px solid #999;padding:4px 8px;margin:6px 0} pre{background:#8881;padding:6px}</style>
<section id="vuln"></section>
<section id="fixed"></section>
<pre id="log"></pre>
<script>
const log = (s) => { document.getElementById('log').textContent += s + '\n'; };
// The two guestbook responses captured from the session above:
const vulnerable = '<ul><li>Nice shop!</li><li><img src=x onerror="document.body.dataset.probe=1"></li></ul>';
const fixed = '<ul><li>Nice shop!</li><li><img src=x onerror="document.body.dataset.probe=1"></li></ul>';
document.getElementById('fixed').innerHTML = '<b>fixed</b>' + fixed;
setTimeout(() => {
log('after the fixed page: probe = ' + (document.body.dataset.probe || 'not set'));
document.getElementById('vuln').innerHTML = '<b>vulnerable</b>' + vulnerable;
setTimeout(() => log('after the vulnerable page: probe = ' + (document.body.dataset.probe || 'not set')), 300);
}, 300);
</script>The fixed comment is shown as visible text and runs nothing; the vulnerable one renders a broken image whose onerror handler sets the probe. In a real browser on the real site, that handler would run with the visitor's session.
Why stored XSS is usually worse
A reflected payload needs each victim to open a crafted link. A stored payload runs for everyone who views the page, without any action, and often in the most privileged views: a support agent opening a ticket, an administrator reviewing new users. Stored XSS in an admin panel is a classic path from "anyone can register" to "attacker controls the site".
How XSS is detected
- Testing (in scope): put a unique, harmless marker with special characters into every input, such as
xss'"<b>t3st</b>, then search every response and every page that later displays it for the raw<b>t3st</b>(vulnerable) versus<b>(encoded). Check the context: inside an attribute, inside<script>, inside a URL. Burp and ZAP automate reflection detection; stored XSS needs you to visit the places where data is shown, including admin views and e-mails. - Code review: templates with auto-escaping turned off (
|safein Jinja2/Django,{!! !!}in Blade,<%- %>in EJS,Html.Rawin Razor,th:utextin Thymeleaf), string-built HTML,Markup()on user data. - Logs: parameters with
<script,onerror=,javascript:,<svg, encoded variants (%3Cscript); CSP violation reports (script-src-attrblocked on a page that shows user content is a strong signal).
How it is fixed
- Contextual output encoding by default: use a template engine with auto-escaping on (Jinja2, Django, React's JSX, Angular, Razor) and never turn it off for user data.
- Sanitise only where users must submit HTML (rich text): an allow-list sanitizer such as DOMPurify or bleach's successors, server-side and/or client-side (XSS defences).
- CSP with nonces as the second layer;
HttpOnlysession cookies to keep the cookie itself out of reach. - Validate input where a format is known (a number, a date, a country code): defence in depth, not the fix.
Pitfalls
- Encoding on input ("we escape everything before saving") corrupts data, double-encodes in some outputs and misses others (JSON APIs, e-mails, PDF exports).
- Blocklisting
<script>: there are hundreds of other vectors (<img onerror>,<svg onload>,<a href="javascript:…">,<iframe srcdoc>). - "It's only in the admin panel": that's the worst place.
Practice
1. A profile page renders <div title="{{ bio }}"> with a template that HTML-escapes < and > but not quotes. Is it vulnerable?
Yes: a bio such as " onmouseover="… closes the attribute and adds an event handler without any angle brackets. Attribute contexts need quotes encoded ("), which html.escape(s, quote=True) and every good template engine do.
2. Why did the fixed app store the comment raw instead of escaping it before saving?
Encoding depends on the output context. The same comment might later go into JSON, a CSV export, an e-mail or a mobile app, each with different rules. Storing raw and encoding at output means each consumer applies the right encoding exactly once.
Test yourself
What is the difference between reflected and stored XSS?
- Reflected uses JavaScript, stored uses HTML
- Reflected echoes the payload from the current request; stored saves it and serves it to later visitors
- Stored needs HTTPS
- There is none
What did the fixed app send for <script>?
- Nothing
- <script>
- An error
- <script> inside a comment
Where should user data be HTML-encoded?
- When it is saved
- At output, for the context it is written into
- In the browser only
- Never
Which template feature is the most common source of XSS in code review?
- Auto-escaping
- Turning auto-escaping off for user data (|safe, Html.Raw, v-html)
- Template inheritance
- Partials