PATCH//NOTES Open the interactive version
← All lessons
Web attacks · Beginner · 4 min

Cross-site scripting (XSS)

Make someone else's browser run your code.

What it is

XSS happens when a website shows user-supplied content without making it safe, so a script the attacker wrote runs in other visitors' browsers. Because it runs on the real site, it can read what the user sees, act as them and steal session tokens. Stored XSS is saved on the site (like a comment); reflected XSS bounces off a link the victim clicks.

See it: How stored XSS steals a visitor's session

  1. Attacker → Website: Posts a comment containing <script>…</script>. The site saves the comment without making it safe. Stopped by: Encode output for where it appears; use frameworks that escape by default.
  2. Website → Visitor: Serves the page, script included. Everyone who views the comment gets the attacker's script as part of the real page. Stopped by: A strict Content Security Policy stops inline scripts from running.
  3. Visitor → Attacker: Browser runs it and sends the session cookie. The script runs in the visitor's browser with the site's permissions. Stopped by: HttpOnly cookies can't be read by scripts.
  4. Attacker → Website: Uses the cookie to act as the visitor. With the session cookie, the attacker is logged in as the victim.

Step through the animated diagram in the app.

Real case · 2005

The Samy worm

A MySpace user hid a script in his profile that added him as a friend and copied itself to the profile of anyone who viewed it. Over a million people were infected in under a day.

Source: Wikipedia: Samy (computer worm)

How defenders stop it

  • Encode output for where it appears (HTML, attributes, JavaScript)
  • Use frameworks that escape by default
  • A strict Content Security Policy
  • HttpOnly cookies so scripts can't read sessions

Try it yourself

PortSwigger XSS labs (free)

Check yourself

1. Where does an XSS payload actually run?

  1. On the web server
  2. In the victim's browser
  3. In the database
  4. On the attacker's machine
Show answer

In the victim's browser. That's why it can act as the victim on the trusted site.

2. What's the difference between stored and reflected XSS?

  1. There's no difference
  2. Stored targets servers; reflected targets databases
  3. Reflected only works on phones
  4. Stored is saved on the site; reflected bounces off a link the victim clicks
Show answer

Stored is saved on the site; reflected bounces off a link the victim clicks. A stored payload sits on the site, like a comment, and hits every visitor; a reflected one comes from a crafted link.

3. Which cookie setting stops a script from reading the session cookie?

  1. A longer password
  2. HttpOnly
  3. Using HTTPS
  4. Disabling images
Show answer

HttpOnly. HttpOnly cookies are sent to the server but can't be read by JavaScript, so an XSS script can't steal them.

Answer them in the app to earn XP.

Next: Broken access control & IDOR →