Lesson 4.2: Cross-site scripting (XSS)
Injection in the browser: when a page includes visitor input as HTML, an attacker can make it run JavaScript inside the site's origin, with everything the logged-in user can see and do. Reflected, stored and DOM-based XSS, what an attacker can do with it, and the defences: context-aware output encoding (htmlspecialchars in PHP), safe templates, HttpOnly cookies and a Content Security Policy. In the lab a heading added to the search page yesterday echoes the search text unescaped. You inject HTML, then a script, find the line, encode the output and prove the script is now shown as harmless text.
19 min
You will learn to
- Explain how XSS happens and what it allows
- Tell reflected, stored and DOM-based XSS apart
- Encode output with htmlspecialchars
- Explain how CSP and HttpOnly limit XSS
- Fix and prove a reflected XSS
Key terms
- Cross-site scripting (XSS)
- An attacker gets their JavaScript to run in a page of the target site, in the victim's browser.
- Reflected XSS
- The script comes from the request (often a link) and is echoed back in the response.
- Stored XSS
- The script is saved by the application (a review, a profile name, a message) and shown to every visitor of that page.
- DOM-based XSS
- The page's own JavaScript writes untrusted data into the page (for example with innerHTML), without the server being involved.
- Output encoding
- Converting characters that have meaning in the output's language (HTML, an attribute, JavaScript, a URL) into a harmless form.
← TCP: the three-way handshake, flags and connection states · All lessons · Defence in depth and least privilege →