What is XSS?
Learn what cross-site scripting (XSS) attacks are and their types.
What is XSS?
XSS (cross-site scripting) is an attack where the intruder injects their own JavaScript into a page. It is used to steal session cookies, alter the page or run phishing.
There are three common types: stored (kept on the server), reflected (echoed through the URL) and DOM (processed on the client). All stem from untrusted data written to the page without proper encoding.
How does injection happen?
An attacker who types <script>alert(1)</script> into a comment box affects everyone who prints that data as raw HTML. If the server stores the data as-is, it is stored XSS.
Code that writes a URL parameter straight to the page creates reflected XSS. Code that processes data like location.hash on the client produces DOM XSS. The defense is always output encoding.
Exercise Write a safe greeting
Write a function named renderGreeting. Parameter name. Get the box variable with document.getElementById('box') and assign 'Hello ' + name to box.textContent. This prevents XSS.
Show example solution
First define the function, then get the box variable, finally assign the value to textContent.
Example solution:
function renderGreeting(name) {
const box = document.getElementById('box');
box.textContent = 'Hello ' + name;
}
Test yourself
-
Which of the following is a type of XSS?
- Buffered
- Cached
- Stored
- Deferred
Show answer
Stored — Correct! Stored XSS is the type where the injected code is kept on the server.
-
Pass the malicious tag to the escape function
const payload = '____';Show answer
const payload = '<script>'; -
Match the XSS types
- Stored
- kept on the server
- Reflected
- echoed via the URL
- DOM
- processed on the client
- XSS
- injection attack