Cross-site scripting (XSS)

Introduction

A course forum shows students' comments. If the page inserts each comment into its HTML as it is, a comment can contain HTML too, and a <script> tag inside it runs in the browser of everyone who reads the forum. That is cross-site scripting (XSS): an attacker's code running on your site, with your users' sessions.

It is called "cross-site" for historical reasons; what matters is that the attacker's script runs as part of your page, so it can read what the page can read and do what the user can do.

How it works

There are three common kinds:

KindWhere the script comes from
StoredSaved on the server (a comment, a profile name) and shown to every visitor
ReflectedTaken from the request (a search term in the address) and echoed back in the reply
DOM-basedPut into the page by the page's own JavaScript, for example from the address's # part

The cause is always the same: text was treated as HTML. The fix is output encoding: before putting text into HTML, replace the characters HTML treats specially (<, >, &, ", ') with entities such as &lt;. The browser then shows those characters instead of reading them as tags. In JavaScript, setting element.textContent instead of innerHTML does this automatically, and frameworks such as React escape text by default.

The sandbox below opens on Cross-site scripting; try its examples. The left side shows the HTML a vulnerable page would build, and what in it would run; the right side shows the escaped HTML and the plain text readers would see. Nothing here is inserted into the page as HTML, so nothing runs.

A second layer is a Content-Security-Policy: a response header that tells the browser which scripts it may run, so an injected inline script is blocked even if encoding was missed somewhere. This site uses one.

Example

The program escapes four comments, two of them attacks, and prints the HTML a safe page would build.

// Output encoding: turn the characters HTML treats specially into entities, so text stays text.
function escapeHtml(text) {
  return text
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

const comments = ["Great lesson!", "<script>steal(document.cookie)</script>", '<img src=x onerror="alert(1)">', "Tom & Jerry's notes"];
for (const c of comments) {
  console.log("<p>" + escapeHtml(c) + "</p>");
}
Open in compiler

Line by line

  1. escapeHtml replaces & first (so the & it adds later is not replaced again), then <, >, " and '.
  2. A normal comment passes through unchanged.
  3. The <script> comment becomes &lt;script&gt;…: the browser shows the text <script> and runs nothing.
  4. The <img … onerror=…> comment, which runs code when the image fails to load, also becomes harmless text, because its < and " are encoded.
  5. Even ordinary text with & and ' is encoded, which keeps the HTML valid.

Expected result

<p>Great lesson!</p>
<p>&lt;script&gt;steal(document.cookie)&lt;/script&gt;</p>
<p>&lt;img src=x onerror=&quot;alert(1)&quot;&gt;</p>
<p>Tom &amp; Jerry&#39;s notes</p>

In the real world

  • With XSS an attacker can read anything the page shows, act as the user (post, transfer, change settings) and sometimes steal session cookies; cookies marked HttpOnly cannot be read by scripts, which limits that last risk.
  • Frameworks escape text by default, so XSS today often comes from their escape hatches: dangerouslySetInnerHTML in React, v-html in Vue, or innerHTML in plain JavaScript.
  • If users must post formatted text, use a well-tested sanitizer library that keeps only safe tags, never a home-made filter.
  • Encoding depends on context: text inside HTML, inside an attribute, inside a URL and inside JavaScript each need their own rules.

Common mistakes

  • Filtering for the word "script". There are many other ways to run code: event attributes, javascript: links, SVG.
  • Encoding on input instead of output. Data used in several places needs the right encoding for each place it is shown.
  • Trusting data from your own database. Stored XSS arrives exactly that way.
  • Using innerHTML for plain text "because it was easier".

Best practices

  • Put text into pages with textContent or a framework's normal text binding.
  • Encode for the right context whenever you build HTML yourself.
  • Add a Content-Security-Policy that blocks inline scripts, as a second layer.
  • Mark session cookies HttpOnly and Secure.

Summary

Cross-site scripting happens when text from users is treated as HTML, so a script in it runs in every reader's browser, with their session. It can be stored, reflected or DOM-based, but the cause is the same. Output encoding (escaping <, >, & and quotes, or using textContent) makes text stay text, and a Content-Security-Policy and HttpOnly cookies are extra layers.

Quick check

1. A search page shows "You searched for: …" using the text from the address. What kind of XSS can this allow?
2. What does escapeHtml turn < into?
3. Why is filtering out the word "script" not enough?
4. Which setting stops a script from reading the session cookie, even if XSS happens?

Key takeaways

  • XSS comes from treating text as HTML; encode output for where it goes.
  • Use textContent or the framework's normal text binding, not innerHTML.
  • Filters for "script" fail; there are many ways to run code.
  • A Content-Security-Policy and HttpOnly cookies limit the damage of a mistake.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.