← Back to Frontend, page 2

frontend-0031 · Medium mid

A page shows 'Results for' followed by the search text from the URL, using innerHTML. What attack does that allow, and how do you fix it and prevent the whole class of bug?

This is DOM-based XSS: a crafted link makes the attacker's JavaScript run in your page and your origin. XSS can also be stored or reflected. Prevent it by treating all data as text, using textContent or a framework's escaping, sanitizing any HTML you must allow, avoiding dangerous sinks, and adding a Content Security Policy as a second layer.

Full answer

In XSS the attacker's script runs with the privileges of your site. It can read the page, call your API as the user, change the page and send data out. If tokens are readable by scripts, they can be stolen.

Types:

  • Stored XSS. The payload is saved on the server, for example in a comment, and shown to every visitor.
  • Reflected XSS. The payload is in the request, for example a query parameter that the server puts into the page, and a victim opens a crafted link.
  • DOM-based XSS. The payload never goes through the server. Client code takes a value from location, postMessage or storage and writes it into a dangerous sink.

Dangerous sinks include innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, new Function, setTimeout with a string, javascript: URLs in href, and framework escape hatches such as dangerouslySetInnerHTML or v-html.

Prevention, in order of value:

  1. Use safe sinks. textContent, setAttribute for harmless attributes and framework templates escape text for you. Escaping must match the place: HTML text, attribute, URL and script contexts differ.
  2. Never build HTML by joining strings with user data.
  3. If users must supply HTML, such as rich text, sanitize it with a maintained sanitizer library on the server or the client, with an allowlist of tags and attributes. Writing a regex filter is a known source of bypasses.
  4. Validate URL schemes. Allow http, https and mailto, and reject javascript:.
  5. Add a Content Security Policy and cookies with HttpOnly. These limit the damage, but they do not replace output handling.

A note: a <script> tag inserted through innerHTML does not run, but an image onerror attribute does. Do not rely on that as a defence.

The page below writes the same input into two elements. The innerHTML version creates an image whose error handler runs, and sets a flag. The textContent version shows the same text without creating an element. The escapeHtml function shows what a template engine does for you.

html
<div id="unsafe"></div>
<div id="safe"></div>
<script>
  const userInput = '<img src="/no-such-image" onerror="window.attacked = true">';

  unsafe.innerHTML = userInput;     // parsed as HTML: the handler runs
  safe.textContent = userInput;     // shown as text: no element is created

  const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) =>
    ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  window.escaped = escapeHtml(userInput);
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Checked in headless Chrome. The unsafe version sets the flag, the safe version creates no image, and the escaped text has no angle brackets. The escape function covers the HTML text and quoted attribute contexts only. It is a teaching example, and a maintained library should be used in real code.

Key points

  • XSS runs attacker code in your origin. Types: stored, reflected, DOM-based.
  • Treat data as text. Use textContent and framework escaping.
  • Sanitize HTML with a maintained library and an allowlist when HTML is required.
  • Validate URL schemes such as javascript:.
  • CSP and HttpOnly cookies limit damage as a second layer.

Common mistakes

  • Blocking only the script tag, while image handlers and svg still work.
  • Using a regex to strip tags.
  • Escaping once for HTML and using the value in a URL or script context.
  • Using dangerouslySetInnerHTML or v-html with unsanitized data.

Follow-ups

  • Why is escaping context dependent?
  • How do Trusted Types reduce DOM XSS?
  • Why is a javascript: link dangerous in an href?

Tips

  • Name the three types and one sink for each.
  • Say that framework defaults help, and name the escape hatches.