KHAGAN AYDIN

OWASP 2017 A7: Cross-Site Scripting

Frameworks closed the front door. The bugs moved to the side doors.

· 11 min read

Cross-Site Scripting (XSS) is a security vulnerability in which text supplied by an attacker ends up running as code in someone else’s browser, on your site. It is number seven on the 2017 OWASP Top 10. In 2010 it was number two; in 2013, number three. It is tempting to read that slide as a sign the problem is fading. It is not. The 2017 entry itself calls XSS the second most common issue on the whole list, found in about two thirds of the applications OWASP’s data covered.

That code runs with your site’s full authority: it can read the page, fill in and submit forms, call your application programming interfaces (APIs) with the victim’s session, and send whatever it collects anywhere it likes. The 2013 essay on this list covered the basics: reflected, stored and DOM-based XSS (DOM is the Document Object Model, the browser’s live copy of the page), and encoding output for each context. This one is about what changed since, and where the bug lives now.

Why it moved down

The first reason is arithmetic. Each item is scored from 1 to 3 on how common it is, how easy it is to find and how easy it is to exploit, and the average is multiplied by a technical impact score, also 1 to 3. XSS gets the top mark on all three likelihood factors and a 2 for impact: a total of 6. Broken Access Control and Security Misconfiguration also score exactly 6, and sit at five and six. Four items that sat below XSS in 2013, or did not exist, now sit above it. XSS did not fall because it became rare. It was overtaken, then placed last in a three-way tie.

The second change does not show in the score yet, but it decides where the bug lives now. React, Angular, Vue and current Ruby on Rails escape text by default, and OWASP’s 2017 advice starts with using a framework that does. In React, this is safe with no effort from the developer:

function Profile({ user }) {
  // A bio of <img src=x onerror=alert(1)> shows up as harmless text.
  return <div className="bio">{user.bio}</div>;
}

The classic bug, a developer forgetting to encode one variable in one template, mostly does not happen by accident in new code anymore. What remains is the code where the framework was told to stop protecting you, the places it never protected you, and code that is not yours at all.

The escape hatches

Every framework has a way to say “trust me, this is HTML”:

Framework Escape hatch Effect
React dangerouslySetInnerHTML Inserts the string as live HTML
Angular (2 and later) bypassSecurityTrustHtml, bypassSecurityTrustUrl and three siblings Switches off Angular’s sanitizer for that value
Vue v-html Inserts the string as live HTML
jQuery .html(), .append() with a string Parses the string as HTML

The need is real: rich text from an editor, Markdown turned into HTML, a fragment from a content system. The input is often stored, which makes any bug here stored XSS against every visitor.

Vulnerable code

function Bio({ user }) {
  // user.bio comes from the rich text editor on the profile page
  return <div className="bio" dangerouslySetInnerHTML={{ __html: user.bio }} />;
}

Fixed code

import DOMPurify from 'dompurify';

const BIO_OPTIONS = {
  ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p', 'br', 'ul', 'ol', 'li', 'a'],
  ALLOWED_ATTR: ['href']
};

function Bio({ user }) {
  const clean = DOMPurify.sanitize(user.bio, BIO_OPTIONS);
  return <div className="bio" dangerouslySetInnerHTML={{ __html: clean }} />;
}

DOMPurify parses the string the way the browser will, keeps only the tags and attributes you list, and strips event handlers and javascript: links. Sanitize at output, not only on save: records also arrive through imports and admin tools that never ran your input filter. Keep the sanitizer updated, because bypasses are found and fixed.

The rule I give teams: every escape hatch is a mandatory review point. Searching for these names lists most of the places XSS can happen in a framework app. That list should be short, and every line on it should have a sanitizer next to it.

The link React does not check

React escapes the characters in an attribute. It does not look at what the value means. React 16 renders this exactly as written:

Vulnerable code

function AuthorLink({ author }) {
  return <a href={author.website}>{author.name}</a>;
}

If the attacker sets their website to javascript:alert(document.domain), the link runs that code on your site when anyone clicks it. Vue’s :href binding behaves the same way. Angular is the exception: its URL sanitizer prefixes dangerous values with unsafe:, unless someone called bypassSecurityTrustUrl to make an error go away.

Blocklists do not fix this. Browsers ignore case and leading spaces in the scheme, and they strip tabs and newlines from inside it, so JaVaScRiPt: and java followed by a tab and script: both run. The fix is to parse the URL with the same rules the browser uses and allow only the schemes you want.

Fixed code

function safeUrl(value) {
  try {
    const url = new URL(value, window.location.origin);
    if (url.protocol === 'http:' || url.protocol === 'https:') {
      return url.href;
    }
  } catch (err) {
    // not a URL at all
  }
  return 'about:blank';
}

function AuthorLink({ author }) {
  return <a href={safeUrl(author.website)}>{author.name}</a>;
}

Apply the same check on the server when the URL is saved.

DOM XSS in single page apps

In a single page app, much of the page is built in the browser, through the Document Object Model (DOM), from data the server never inspected. Two variants recur.

The first reads the part of the address after #, called the fragment:

// Shows a message passed in the address, e.g. /#welcome=Hello
const params = new URLSearchParams(location.hash.slice(1));
document.getElementById('banner').innerHTML = params.get('welcome');

The fragment is never sent to the server, so your logs, filters and web application firewall never see this payload. Use textContent instead of innerHTML and the problem disappears.

The second is quieter. Apps rendered on the server often pass their starting data to the browser by writing JSON into a script tag:

<script>window.__STATE__ = <%- JSON.stringify(state) %>;</script>

JSON.stringify does not escape <. If a user names themselves </script><script>alert(document.domain)</script>, the HTML parser sees the first </script> and ends the block before JavaScript ever reads the string. The fix is one line:

function serializeState(state) {
  return JSON.stringify(state).replace(/</g, '\\u003c');
}

The output is still valid JSON with the same data, but it can no longer close the tag.

Case: Fortnite and an old subdomain, January 2019

On January 16, 2019, Check Point Research published an account takeover chain against Epic Games, maker of Fortnite, a game the firm put at nearly 80 million players. It began on an old subdomain, ut2004stats.epicgames.com, which served statistics for Unreal Tournament 2004. A search box on its maps page reflected input without encoding it: plain reflected XSS on a page almost nobody visited.

On its own, that is a minor finding. But Epic’s login flow would redirect to any page on any epicgames.com subdomain, and the server did not validate the value that carried the destination. The researchers showed that one click on a crafted link started a normal sign-in through a single sign-on provider (their demonstration used Facebook) and ended on the old stats page, with a login token in the address. The XSS there read the token and sent it to a server the researchers controlled. The victim typed nothing. With the token, an attacker could take over the account and buy in-game currency with the saved card. Epic fixed the issues after the report.

The root cause was three small things lined up: an unmaintained page, a redirect rule that trusted every subdomain, and a token carried in a URL. The lesson is that XSS anywhere in your domain counts. A wildcard redirect list, cookies scoped to the parent domain and any rule that trusts *.example.com all extend your trust to your oldest, least maintained server.

Case: British Airways and Ticketmaster, 2018

From 22:58 on August 21 to 21:45 on September 5, 2018 (UK time), card payments on ba.com and in the British Airways app were copied to attackers. The security firm RiskIQ found 22 lines added to the end of a copy of the Modernizr JavaScript library served from British Airways’ own site. The added code waited for the payment form’s submit button to be clicked or tapped, then sent the form contents to baways.com, a lookalike domain the attackers had bought a paid certificate for. The app was hit because it loaded the same web pages. The airline first put the count at 380,000 cards. In October it revised that to 244,000 and said another 185,000 cards may have been exposed in reward bookings made between April 21 and July 28, 2018. How the attackers got write access to the file has not been made public.

This was not XSS in the textbook sense: no input was reflected or stored. The attackers changed a file on the server. But the end state is identical to stored XSS, attacker code running inside your page with full authority, and the browser-side defenses below limit both.

Ticketmaster UK disclosed a similar breach on June 27, 2018. A chatbot from a vendor, Inbenta, ran on its sites through a script that Inbenta customized and hosted. Inbenta said Ticketmaster had added that script to its payment page without telling it. An attacker altered the script on Inbenta’s servers, and press reports put the exposure at about 40,000 UK customers who bought tickets between February and June 23, 2018. When you load another company’s script, you hand that company, and anyone who breaks into it, the power of stored XSS on your page.

Strict Content Security Policy

Content Security Policy (CSP) is a response header that tells the browser which scripts may run. The common version lists allowed domains, and it mostly fails. A 2016 study by Google researchers of about 26,000 distinct policies found roughly 95 percent could be bypassed, and 14 of the 15 domains most often allowed for scripts hosted files an attacker could abuse. Allowing a domain allows every file on it.

The version that works uses a nonce: a fresh random value per response, sent in the header and placed on each script tag you meant to include. Injected markup cannot guess it.

const crypto = require('crypto');

app.use((req, res, next) => {
  const nonce = crypto.randomBytes(16).toString('base64');
  res.locals.nonce = nonce;
  res.setHeader('Content-Security-Policy', [
    "script-src 'nonce-" + nonce + "' 'strict-dynamic' https: 'unsafe-inline'",
    "object-src 'none'",
    "base-uri 'none'",
    "report-uri /csp-report"
  ].join('; '));
  next();
});
<script nonce="<%= nonce %>" src="/static/app.js"></script>

'strict-dynamic' lets a script you trusted load further scripts, so bundle loaders keep working without a domain list; Chrome and Firefox have supported it since version 52. https: and 'unsafe-inline' are only fallbacks for older browsers: a browser that understands nonces ignores 'unsafe-inline', and one that understands 'strict-dynamic' ignores https:. object-src 'none' blocks plugins, and base-uri 'none' stops an injected <base> tag from redirecting your relative script paths.

A point many guides miss: once 'unsafe-inline' is ignored, the browser also refuses inline event handlers such as onerror= and refuses javascript: links. So a strict policy blocks the payloads in every vulnerable example above. The cost is that your own inline handlers must move into script files. One trap: if a cache or content delivery network stores the HTML, every visitor gets the same nonce, and an attacker can read it. Roll out with the Content-Security-Policy-Report-Only header first, read the reports, fix, then enforce.

CSP does not help when a script you trust is itself changed, as at British Airways. A connect-src list naming your own API domains makes sending stolen data harder, though not impossible.

Subresource Integrity

Subresource Integrity (SRI), a World Wide Web Consortium (W3C) standard since June 2016 and supported in Chrome, Firefox, Safari 11 and Edge 17, lets you pin a script to a hash of its exact contents. If one byte changes, the browser refuses to run it.

<script src="https://cdn.example.net/widget/2.3.1/widget.min.js"
        integrity="sha384-qSRxqO2dhNJarxa3Umg1LEnIZYUwDQlKSjjaHHOhAvt66YKqvavozq4wp6BM0y8a"
        crossorigin="anonymous"></script>

Generate the hash at build time with openssl dgst -sha384 -binary widget.min.js | openssl base64 -A.

SRI only works for a file that never changes, and that is its honest limit. A vendor script that updates itself, such as a chat widget or tag manager, cannot be pinned. You either host a reviewed copy of a fixed version or keep the script off sensitive pages. SRI is also worth putting on your own static files: if an attacker changes only the JavaScript file on the server and not the HTML that carries its hash, the browser refuses the altered file.

The rule underneath both cases: login and payment pages load no third-party script at all.

How to test your own application

  1. Search the code for every escape hatch: grep -rnE "dangerouslySetInnerHTML|v-html|bypassSecurityTrust|innerHTML|outerHTML|insertAdjacentHTML|document\.write|\.html\(" src/. Each hit needs a sanitizer or a written reason.
  2. Find every user-controlled link with grep -rnE "href=\{|:href=" src/, then enter javascript:alert(document.domain) into every URL field the app accepts: website, avatar link, return address.
  3. Find every place the browser code reads location.hash, location.search or postMessage data, and send <img src=x onerror=alert(document.domain)> through each one.
  4. Save </script><svg onload=alert(document.domain)> as a display name, then view the source of any server-rendered page that shows it.
  5. List every subdomain from your domain name records and the public logs of issued certificates. Each one is either maintained or switched off.
  6. Open the login and payment pages with the browser’s network panel filtered to scripts. Each file needs an owner and a reason.
  7. Ship a strict policy in report-only mode and read a week of reports before enforcing.

Checklist

  • Every escape hatch (dangerouslySetInnerHTML, v-html, bypassSecurityTrustHtml, .html()) has a sanitizer next to it, applied at output.
  • Every link built from user data is parsed and allowed only with the schemes you chose, in the browser and on the server.
  • Browser code writes user data with textContent, never innerHTML.
  • JSON written into a script tag has < escaped.
  • A strict Content Security Policy with a nonce is in place, rolled out in report-only mode first.
  • Subresource Integrity is set on every script file that does not change.
  • Login and payment pages load no third-party script.
  • Every subdomain is maintained or switched off.

XSS slid down the list because other risks climbed past it, not because it went away. Frameworks fixed the default, so the bug moved to the exceptions: the escape hatches, the URL attributes, the browser-side code, the forgotten subdomain and the scripts other companies host for you. Testing the main page with a quote mark finds none of them. Find each one, put a check or a sanitizer on it, and put a strict policy behind them all for the day one gets through.