XSS by Javascript Overriding
This post describes an interesting XSS that I recently encountered. I'll describe my thought process during the exploitation of this vulnerability as well.
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 here is a web application the researcher picked while hacking in Las Vegas during the gap between H1-702, a HackerOne live hacking event, and Def Con. The write-up does not name the program, the product or the specific feature beyond the fact that it contained a portion of JavaScript with a function called EatBanana() that took a parameter and wrote it into the page. The function is bound to a button: it runs when the user clicks that button, and it is meant to place the parameter value into an element in the opener window, close the current window and then focus the element it just wrote to.
Setup
No accounts, roles, tools or versions are described. The only precondition that matters for the exploitation is the state of window.opener: the vulnerable code assumes the page was opened as a popup from another window, so that window.opener points at a live document. The researcher's testing context did not satisfy that assumption.
Finding it
While browsing the target, the researcher noticed a portion of JavaScript in which a reflection took place in two parts without sanitising user input:
function EatBanana(param){
window.opener.document.getElementById('REFLECTION') = param;
window.close();
window.opener.document.getElementById('REFLECTION').focus();
}
The value of the parameter is reflected into the source twice, once in the assignment and once in the focus() call, and neither occurrence is sanitised. The obvious next step was to inject a single quote to escape the string context and insert a function such as print() to get script execution.
Two obstacles stood in the way:
window.openerwasnullin the researcher's context. The first line of the function would therefore throw before any injected payload further down could run.EatBanana()only executes when the user clicks a particular button, so any XSS reached this way would be 1-click, which reduces the impact.
Exploitation
Step 1: override the function to suppress the error
The idea was to redefine EatBanana() so that the window.opener error no longer stopped execution. The researcher tested this without having read up on the technique first, and it worked: JavaScript prefers the latest definition of a function with the same name and parameters. The payload only needs to close the existing function syntax, because the two reflections are very similar in context, so fixing one fixes the other:
');} function EatBanana(param){print();('
This closes the previous declaration and declares the function again, so that clicking the button executes print(); and then ('').focus(); instead of the original body. The result is still 1-click.
Step 2: move the payload between the declarations
The next question was whether the JavaScript could be placed between the function declarations rather than inside the redefined body:
');} print(); function EatBanana(param){print();('
This worked, and turned the bug into 0-click XSS: print() runs as the script is parsed, without waiting for the button. The final injected JavaScript, as the researcher presents it, looks like this:
function EatBanana(param){
window.opener.document.getElementById('');
}
print();
function EatBanana(param){
print();
('').value = param;
window.close();
window.opener.document.getElementById('');
}
print();
function EatBanana(param){
print();
('').focus();
}
With this shape, the function error is suppressed. The function will still error on the focus() call once EatBanana is invoked, but that happens after the payload has already run and does not affect it.
Step 3: shorter variants
Two shorter payloads were noted after the fact. Both work:
');} print();{('
This one did not occur to the researcher until after re-declaring EatBanana, and is described as less elegant. The second:
');} print();{//
Both rely on the same trick of breaking out of the original declaration and placing the call to print() outside any function body, so it executes on parse.
Root cause
The parameter of EatBanana() is written into the script source twice without sanitisation. That alone allows a single quote to break out of the string and inject arbitrary statements. The early error on the window.opener dereference was an obstacle, not a security control, and it is trivially bypassed by redefining the function, since JavaScript resolves a function name to its latest declaration.: the window.opener dereference would throw when the page was not opened as a popup, which would stop execution before the injected code ran. That is not a security control, and it is trivially bypassed by redefining the function, since JavaScript resolves a function name to its latest declaration. The click requirement was likewise not a real barrier, because injected statements placed between declarations run at parse time.
Impact
Where the reflection is reachable, an attacker can execute arbitrary JavaScript in the context of the vulnerable page. The original 1-click path required the victim to press the button; the final payload removes that requirement and runs on page load. The report does not describe which users or data are exposed, and does not state any bounty or severity.
Fix
The fix implied by the root cause is to stop reflecting unsanitised input into the script source at all, for example by passing the value as data rather than as code, or by encoding it correctly for the JavaScript string context so that quotes cannot terminate the string.
Variants to test
- Look for parameters reflected into inline script inside single-quoted strings. A positive result is that a single quote in the parameter changes the parsed script rather than appearing escaped.
- Look for functions that dereference
window.openeror other objects that may be null. A positive result is that redefining the function with the same name and parameters suppresses the error and lets later statements run. - Look for reflected values inside a function body that only runs on a click. A positive result is that a payload placed between two declarations executes on parse, giving 0-click execution.
- Try the short forms
');} print();{('and');} print();{//where the reflection sits in a similar context. A positive result is that the call outside the function body fires without any interaction.
What happened, in plain words
A security researcher was in Las Vegas between two conferences, hanging out with a friend in a hotel lobby, and they both started poking at websites to see if anything was broken. On the site the researcher picked, a small piece of JavaScript took a value supplied by the user and pasted it into the page twice without cleaning it first. That kind of flaw is called cross-site scripting, or XSS: it lets an attacker slip their own JavaScript into a page that other people trust, and that script then runs in the victim's browser as if the site itself had written it.
The catch was that the broken code was written assuming the page had been opened as a popup from another window, and in the researcher's test it had not been. The first line of the function therefore crashed before any injected code could run, and the function only ran when someone clicked a button anyway. By redefining the function, a technique called overriding, the researcher got around both problems and ended up with script that ran the moment the page loaded, with no click needed.
Background you need first
A few ideas come up repeatedly below, so here they are from scratch.
JavaScript is the programming language that web pages run inside your browser. It is what makes a page react when you click something, and it is what this whole story is about.
A function is a named block of instructions. You write it once, give it a name, and then "call" it by name whenever you want those instructions carried out. Think of it as a recipe card in a drawer: writing the card does not cook anything, but pulling it out and following it does.
A parameter is a value handed to a function when it is called, so the same function can work on different data each time. A function that prints a greeting might take the name to greet as its parameter.
Reflection means the site takes something you sent and echoes it back inside the page it returns to you. A search box that shows "results for: your words" is reflecting. Reflection is normal and useful; it only becomes a bug when the echoed value is not cleaned up.
Sanitising (or escaping) means neutralising characters that have special meaning in the place the value lands, so the value stays data and cannot turn into instructions. If a value is going inside a quoted piece of JavaScript, for example, a quote character in the value must be escaped, otherwise it ends the quote early and whatever follows is treated as code.
window.opener is a browser feature: when a page is opened as a popup by another page, window.opener is a handle to that other page, the one that opened it. If the page was not opened as a popup, window.opener is null, meaning "nothing here". Trying to use null as if it were a page causes an error and stops the script at that point.
Overriding a function means declaring a second function with the same name and parameters. JavaScript keeps the latest declaration, so the newer one replaces the older one when the name is called.
1-click and 0-click describe how much the victim has to do. A 1-click bug needs the victim to press a button before the malicious code runs; a 0-click bug runs as soon as the page loads. Less interaction means more impact, because more people will trigger it without realising.
Finding it
While browsing the target, the researcher noticed a portion of JavaScript in which a reflection took place in two parts without sanitising user input:
function EatBanana(param){
window.opener.document.getElementById('REFLECTION') = param;
window.close();
window.opener.document.getElementById('REFLECTION').focus();
}
Line by line:
function EatBanana(param){starts the definition of a function namedEatBanana, which accepts one value, calledparaminside the body.window.opener.document.getElementById('REFLECTION') = param;reaches into the page that opened this one, finds an element by its id, and assignsparamto it. The wordREFLECTIONstands in for the place where the user-supplied value is pasted into the script source.window.close();closes the current window, which makes sense for a popup that has done its job.window.opener.document.getElementById('REFLECTION').focus();finds the same element again and puts the keyboard focus on it, so the user's cursor lands there.- The closing
}ends the function.
The value of the parameter is reflected into the source twice, once in the assignment and once in the focus() call, and neither occurrence is sanitised. The obvious next step was to inject a single quote to escape the string context and insert a function such as print() to get script execution. A single quote is the character that ends the quoted string the value sits inside; once the string is closed early, whatever comes next is read as JavaScript rather than as text.
Two obstacles stood in the way:
window.openerwasnullin the researcher's context. The first line of the function would therefore throw before any injected payload further down could run. In everyday terms: the recipe's first instruction is "open the cupboard", but there is no cupboard, so the cook stops and never reaches the later steps.EatBanana()only executes when the user clicks a particular button, so any XSS reached this way would be 1-click, which reduces the impact.
Exploitation
Step 1: override the function to suppress the error
The idea was to redefine EatBanana() so that the window.opener error no longer stopped execution. The researcher tested this without having read up on the technique first, and it worked: JavaScript prefers the latest definition of a function with the same name and parameters. The payload only needs to close the existing function syntax, because the two reflections are very similar in context, so fixing one fixes the other:
');} function EatBanana(param){print();('
What each piece does:
');}closes the quoted string the value was sitting in ('), then closes the statement (;), then closes the function body (}). The script is now outside the original function, at the top level of the file.function EatBanana(param){starts a brand new declaration of the same function, with the same name and the same parameter. Because JavaScript keeps the latest declaration, this one wins.print();is the new body: when the button is clicked, it runs instead of the original code.- The original code's trailing
').focus();and closing brace then complete this new declaration harmlessly.
This closes the previous declaration and declares the function again, so that clicking the button executes print(); and then ('').focus(); instead of the original body. The result is still 1-click: the victim still has to press the button.
Step 2: move the payload between the declarations
The next question was whether the JavaScript could be placed between the function declarations rather than inside the redefined body:
');} print(); function EatBanana(param){print();('
Here the same breakout happens, but print(); now sits at the top level of the script, between the closing of the original function and the start of the new one. Top-level statements run as soon as the browser reads the script, so the print dialogue opens on page load, before anyone clicks anything. The second print(); inside the new function body is still there, so a click would also trigger it.
This worked, and turned the bug into 0-click XSS: print() runs as the script is parsed, without waiting for the button. The final injected JavaScript, as the researcher presents it, looks like this:
function EatBanana(param){
window.opener.document.getElementById('');
}
print();
function EatBanana(param){
print();
('').value = param;
window.close();
window.opener.document.getElementById('');
}
print();
function EatBanana(param){
print();
('').focus();
}
This is what the page's script looks like once the payload has been spliced in. Reading it in order:
- The first
function EatBanana(param){ ... }is the remains of the original declaration, now cut short. Its body still toucheswindow.opener, which isnull, so it would error if called, but nothing calls it. - The first
print();is the injected call at top level. It runs immediately when the script is parsed, which is the 0-click part. - The second
function EatBanana(param){ ... }is the redefined function. Its body callsprint();, assigns the parameter to an element, closes the window and toucheswindow.openeragain. - The second
print();is another top-level call, again running on parse. - The third
function EatBanana(param){ ... }is the final declaration, and because JavaScript keeps the latest one, this is the version that runs if the button is ever clicked. Its body callsprint();and thenfocus()on an element.
With this shape, the function error is suppressed. The function will still error on the focus() call once EatBanana is invoked, but that happens after the payload has already run and does not affect it. The researcher's friend Emperor witnessed the jump of delight when the payload worked.
Step 3: shorter variants
Two shorter payloads were noted after the fact. Both work:
');} print();{('
This one did not occur to the researcher until after re-declaring EatBanana, and is described as less elegant. The ');} still breaks out of the original function, print(); still runs at top level, and {( opens a bare block and a string so the leftover original source parses cleanly.
The second:
');} print();{//
Same breakout and same top-level print();, but {// opens a block and then starts a comment, so everything the site appends afterwards is ignored by the browser instead of being wrapped in a string.
Both rely on the same trick of breaking out of the original declaration and placing the call to print() outside any function body, so it executes on parse.
Why it worked
The parameter of EatBanana() is written into the script source twice without sanitisation. That alone allows a single quote to break out of the string and inject arbitrary statements. The early error on the window.opener dereference was an obstacle, not a security control, and it is trivially bypassed by redefining the function, since JavaScript resolves a function name to its latest declaration.: the window.opener dereference would throw when the page was not opened as a popup, which would stop execution before the injected code ran. That is not a security control, and it is trivially bypassed by redefining the function, since JavaScript resolves a function name to its latest declaration. The click requirement was likewise not a real barrier, because injected statements placed between declarations run at parse time.
What an attacker could do
Where the reflection is reachable, an attacker can execute arbitrary JavaScript in the context of the vulnerable page. The original 1-click path required the victim to press the button; the final payload removes that requirement and runs on page load. The report does not describe which users or data are exposed, and does not state any bounty or severity.
How it should be fixed
The write-up does not say what was changed. The fix implied by the root cause is to stop reflecting unsanitised input into the script source at all, for example by passing the value as data rather than as code, or by encoding it correctly for the JavaScript string context so that quotes cannot terminate the string.
Where to look for the same pattern
- Look for parameters reflected into inline script inside single-quoted strings. A positive result is that a single quote in the parameter changes the parsed script rather than appearing escaped.
- Look for functions that dereference
window.openeror other objects that may be null. A positive result is that redefining the function with the same name and parameters suppresses the error and lets later statements run. - Look for reflected values inside a function body that only runs on a click. A positive result is that a payload placed between two declarations executes on parse, giving 0-click execution.
- Try the short forms
');} print();{('and');} print();{//where the reflection sits in a similar context. A positive result is that the call outside the function body fires without any interaction.
Glossary
- JavaScript: the programming language web pages run in the browser to make them interactive.
- Function: a named block of instructions that runs when it is called by name.
- Parameter: a value passed into a function when it is called, so the function can work on different data each time.
- Reflection: when a site echoes a value you supplied back into the page it returns.
- Sanitising (escaping): neutralising characters that have special meaning in the place a value lands, so the value stays data and cannot become code.
- XSS (cross-site scripting): a flaw where an attacker gets their own JavaScript to run inside a page other users trust.
window.opener: a browser handle to the page that opened the current page as a popup; it isnullwhen there is no such page.null: the value meaning "nothing here"; using it as if it were an object causes an error.- Overriding: declaring a function again with the same name and parameters so the newer declaration replaces the older one.
- 1-click: an attack that needs the victim to click something before the malicious code runs.
- 0-click: an attack that runs as soon as the page loads, with no interaction from the victim.
- Parse time: the moment the browser reads and interprets a script, before any function in it is called.
- Top-level statement: a statement outside any function body, which runs as soon as the script is parsed.
- Comment: text in code that the browser ignores, started in JavaScript with
//. print(): a browser function that opens the print dialogue; used here as a harmless stand-in to prove code execution.