UnixDroid

Lesson 5 of 5 · 8 min

Cross-site scripting (XSS)

How attackers make their JavaScript run in someone else’s browser, the three types of XSS, and how sites stop it.

Cross-site scripting (XSS) happens when a website shows user input on a page without making it safe first. If that input is JavaScript, the victim's browser runs it, as if the website itself had sent it.

Practise only in your lab or on legal training platforms.

The three types of XSS and the three main defences
The three types of XSS and the three main defences

Why it's dangerous

The script runs with the website's trust, so it can:

  • read cookies that aren't HttpOnly and send them to the attacker,
  • show a fake login form on the real site,
  • take actions as the logged-in user, like changing their email address.

The three types

Reflected. The script is in a link, like site.com/search?q=<script>...</script>. The page reflects it back once, to whoever opens that link.

Stored. The script is saved, for example in a comment, and runs for every visitor who views it. This is the most dangerous kind.

DOM-based. The server is fine, but the page's own JavaScript takes something like the URL and writes it into the page unsafely.

Try it in DVWA

With DVWA security set to low:

  1. Open XSS (Reflected) and enter your name. It's shown back to you.
  2. Now enter:
<script>alert('XSS')</script>

A pop-up appears. The page ran your script.

  1. Open XSS (Stored), post the same script as a guestbook message, then reload. It runs again, and it would run for anyone visiting.

How sites defend against it

  • Encode output. Show < as &lt; so the browser displays it as text instead of running it. Modern frameworks like React and Django do this by default, until a developer switches it off.
  • Content-Security-Policy. A response header that tells the browser which scripts are allowed to run.
  • HttpOnly cookies. Even if XSS happens, the session cookie can't be read by script.

alert() is only a harmless way to prove a script ran. In real attacks, nothing visible happens at all.

Try it yourself
  1. Complete the reflected and stored steps in DVWA on low.
  2. Click View Source on the low level and find where the input is printed without encoding.
  3. Switch to high and view the source again. Which PHP function makes the output safe?

Quick check

Which type of XSS saves the script so it runs for every visitor?

Need a hint?

It is kept, for example, in the database.

Finished this lesson?

Done lessons keep your daily streak going 🔥

0 day streak

0 lessons done

best 0 days

Log in to keep your streak on every device →