Skip to content
XSS Write-up Intermediate

Exploiting DOM Based XSS via Misconfigured postMessage() Function

The article explains three ways a postMessage listener can be misconfigured: missing origin validation, using indexOf for origin checks, and trusting a whitelisted origin that itself has XSS. An attacker could send a crafted message containing HTML to the victim page, leading to DOM-based XSS.

medium.com

Published on medium.com

Armaan Pathan

Armaan Pathan, on 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. 7 min read.

Context

This write-up is about DOM-based XSS that arises when a page listens for message events and trusts what arrives without validating the sender properly. The feature in question is the browser's cross-origin messaging API: window.postMessage() and the message event listener. Two windows can talk to each other across origins only through this mechanism, and the receiving side is supposed to check e.origin before acting on e.data.

The article walks through three misconfigurations of that check, each with a small vulnerable page, an exploit page, and, in the third case, a chained reflected XSS. The vulnerable pages all render attacker-controlled data into the DOM:

JavaScript
document.getElementById('s').innerHTML = e.data.s;

Because the sink is innerHTML, any HTML in e.data.s is parsed and executed, so the origin check is the only thing standing between a remote attacker and script execution in the victim page.

Setup

The author does not describe a specific target program, account or tooling. The work is done against demonstration pages hosted under begbounty.xyz (for example http://begbounty.xyz/postmessage1.html and http://begbounty.xyz/postmessage2.html) and, in the third scenario, against a host identified only by address and port, http://[redacted]:8083. The exploit pages are served from a separate origin, including a subdomain created for the second scenario:

Text
https://begbounty.xyz.x3b.in/index.html

No browser version, server version or other software version is given.

Finding it

The starting point is the Same Origin Policy: two sites can communicate directly only when they share protocol, hostname and port. postMessage is the sanctioned way around that restriction, and it consists of two halves, window.addEventListener on the receiving side and postMessage() on the sending side. The vulnerability appears when the receiving side either skips the origin check or performs it incorrectly. The author presents three such scenarios.

Exploitation

Step 1: no origin validation at all

The first vulnerable page registers a message listener and writes e.data.s straight into the DOM, with no check on where the message came from:

HTML
<html><head><title>XSS_ME_</title>        </head>    <script>          window.addEventListener('message', function(e) {           document.getElementById('s').innerHTML = e.data.s;})</script><form>                            <h3 id="s">Postmessage XSS</h3>            <input type=text> </input>                            <input type="button" value="Click"> </form>            </div>         </body></html>

The listener accepts a message from any domain. The attacker page opens the vulnerable page in a new window, keeps a reference to it, and after a short delay posts a payload to it with a wildcard target origin:

HTML
<html><body><input type=button value="Click Me" id="btn"></body><script>  document.getElementById('btn').onclick = function(e){       window.poc = window.open('http://begbounty.xyz/postmessage1.html');    setTimeout(function(){        window.poc.postMessage     (                      {                                           "s": "<img src =x onerror=alert(1);>",                      },                     '*'             );   }, 2000);}</script></html>

Clicking the button opens the target and stores the window handle in window.poc. The setTimeout gives the page two seconds to load, then sends an object whose s property contains an img tag with a broken src and an onerror handler. The second argument '*' means the message is delivered regardless of the target window's origin. On the receiving side, innerHTML parses the string, the image fails to load, and alert(1) runs in the context of the vulnerable page.

From the original on medium.com

Step 2: origin validation with indexOf()

The second page does check the origin, but with indexOf():

HTML
<html>    <head>        <title>XSS_ME_</title> </head>   <script>             window.addEventListener('message', function(e) {                 if(e.origin.indexOf("begbounty.xyz") > 0){                document.getElementById('s').innerHTML = e.data.s;                         }             });   </script> <body>  <div class="container"><form> <h3 id="s">Postmessage XSS</h3> <input type=text> </input>                            <input type="button" value="hehe!">                            </form> </div> </body></html>

The check is:

JavaScript
(e.origin.indexOf("begbounty.xyz") > 0)

This asks whether the string begbounty.xyz appears anywhere in the origin after position zero. It does not ask whether the origin is begbounty.xyz. Any origin that contains the whitelisted string at a position greater than zero passes, so an attacker can register a domain that embeds it. The author created exactly such a subdomain and hosted the exploit there:

Text
https://begbounty.xyz.x3b.in/index.html

The exploit page follows the same pattern as before, opening the second vulnerable page and posting the payload after a delay:

HTML
<html><body><input type=button value="Click Me" id="btn"></body><script>document.getElementById('btn').onclick = function(e){       window.poc = window.open('http://begbounty.xyz/postmessage2.html');setTimeout(function(){        window.poc.postMessage     ({                                           "s": "<img src =x onerror=alert(1);>",},'*'             );   },2000);}</script></html>

When the message arrives, e.origin is the attacker's subdomain. The author's bypass relies on the string appearing at a position greater than zero in the origin, so the attacker's hostname must place begbounty.xyz after the start of the origin string. and the payload reaches innerHTML. The result is the same alert(1) in the victim page.

From the original on medium.com

Step 3: a whitelisted origin that is itself vulnerable to XSS

The third page performs a strict comparison against a full origin, including scheme, host and port:

HTML
<html>    <head>        <title>XSS_ME_</title>            </head>    <script>             window.addEventListener('message', function(e) {                 if (e.origin == "http://[redacted]:8083") {                document.getElementById('s').innerHTML = e.data.s;                    }             });                    </script>        <body>            <div class="container">                <form>                            <h3 id="s">Postmessage XSS</h3>            <input type=text> </input>                            <input type="button" value="hehe!">                            </form>            </div>         </body></html>

Here addEventListener() validates protocol, hostname/IP and port number, so the listener only accepts messages from http://[redacted]:8083. That looks correct. The author's next question is what happens if that whitelisted origin is itself vulnerable to stored or reflected XSS: if an attacker can run script inside the trusted origin, the origin check no longer protects anything, because the message genuinely comes from the trusted origin.

From the original on medium.com

In this case the whitelisted host was vulnerable to reflected XSS, so the author used that to inject the postMessage() exploit code into the trusted origin itself.

From the original on medium.com

The final exploit is shown in the article as an image rather than as text.

Root cause

The mistake is in how the receiving page decides whether a message is trustworthy. In the first scenario there is no decision at all: the listener acts on any message from any origin. In the second, indexOf() is used as a substring test rather than an equality test, so any origin containing the whitelisted string is accepted; the author notes that this can be bypassed by creating a subdomain that starts with the given string. In the third, the comparison is correct, but the trust model is not: whitelisting an origin assumes that origin is not itself attacker-controllable, and a reflected XSS there breaks that assumption.

In all three cases the payload reaches innerHTML, which parses and executes HTML, so once the origin check is passed or bypassed there is nothing else in the way.

Impact

When the check is missing or bypassable, an attacker who can get a victim to load an attacker-controlled page can execute script in the context of the vulnerable application, as demonstrated by the alert(1) payloads. In the third scenario the attacker needs the additional precondition that the whitelisted origin is vulnerable to reflected or stored XSS; when it is, the attacker can run script in that trusted origin and send a message that passes the strict check. The article does not describe any specific real target, data exposure or account impact beyond script execution in the page.

Fix

The author's recommendations are:

  1. Whitelist the origin in the window.addEventListener function.
  2. Use proper regex while whitelisting the domain.
  3. Perform cross-site scripting related test cases on all pages before whitelisting a domain or host in the function.

The article does not say whether any of these were applied to a live target.

Variants to test

  • Missing origin check. Look for message listeners that read e.data without inspecting e.origin. A positive result is a listener that writes message data into a DOM sink such as innerHTML and accepts a message from a page you control.
  • Substring checks. Grep for indexOf, includes, startsWith or endsWith applied to e.origin. A positive result is an origin you can register that contains the whitelisted string, for example whitelisted.example.attacker.tld, and whose message is accepted.
  • Loose equality and type confusion. Check for comparisons that do not pin scheme, host and port exactly. A positive result is a message from an origin that differs from the intended one but still satisfies the comparison.
  • Trusted origin with its own XSS. For a strict origin check, test the whitelisted origin for reflected or stored XSS. A positive result is script execution inside that origin, which lets you send a message that passes the check.
  • Dangerous sinks. Wherever a listener passes message data to innerHTML, outerHTML, document.write or similar, confirm whether HTML in the payload is parsed. A positive result is an onerror or similar handler firing in the receiving page.

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

What happened, in plain words

Imagine two people in separate rooms who can only pass notes under the door. The building has a rule: notes are only allowed between rooms that belong to the same company. That rule is the browser's Same Origin Policy, and it exists to stop one website from quietly reading or changing another website's page.

Sometimes two websites genuinely need to talk to each other even though they belong to different companies. The browser provides a controlled way to do that, called postMessage. One page sends a message, and the other page listens for it. The catch is that the page receiving the message is supposed to check who sent it before trusting the contents. If it forgets that check, or does the check badly, an attacker's page can send a message that the victim page treats as its own.

This write-up shows three ways that check can go wrong. In each case the receiving page takes whatever arrives in the message and drops it straight into the page as HTML. Because of that, a message containing a small piece of HTML with a script inside it runs as code in the victim page. That is DOM-based XSS: the page's own JavaScript builds the dangerous content, without the server ever being involved.

The two halves of postMessage

Before the three scenarios, it helps to know the two pieces involved.

  1. window.addEventListener('message', ...) is the listening side. A page says: whenever a message arrives, run this function. The function receives an event object, usually called e, which carries two useful things: e.origin (where the message came from) and e.data (what was sent).
  2. window.postMessage(data, targetOrigin) is the sending side. It takes the data to send and a target origin. The special value '*' means "deliver this no matter what origin the receiving window has".

A window here is just a browser tab or frame. When one page opens another with window.open(...), it gets back a handle to that new window, and it can use that handle to post messages to it.

All three vulnerable pages in the article share the same dangerous line:

JavaScript
document.getElementById('s').innerHTML = e.data.s;

In plain words: find the element whose id is s, and set its HTML content to whatever is in the s property of the message data. The word innerHTML matters. It does not treat the value as harmless text; it parses it as HTML. So if the value contains an <img> tag with an error handler, the browser builds that image, the image fails to load, and the handler runs. That is the whole trick behind the payloads below.

Setting the scene

The article does not describe a real company, a bug bounty programme, an account or any particular tool. The demonstration pages live under the domain begbounty.xyz, for example http://begbounty.xyz/postmessage1.html and http://begbounty.xyz/postmessage2.html. In the third scenario the page is identified only by an address and port, http://[redacted]:8083. The attacker's own pages are served from a different origin, including a subdomain created specially for the second scenario:

Text
https://begbounty.xyz.x3b.in/index.html

No browser version, server version or other software version is mentioned.

Scenario 1: no check at all

The vulnerable page

The first page listens for messages and writes the data into the page without asking where the message came from:

HTML
<html><head><title>XSS_ME_</title>        </head>    <script>          window.addEventListener('message', function(e) {           document.getElementById('s').innerHTML = e.data.s;})</script><form>                            <h3 id="s">Postmessage XSS</h3>            <input type=text> </input>                            <input type="button" value="Click"> </form>            </div>         </body></html>

Line by line:

  • <html><head><title>XSS_ME_</title> starts the page and gives it a title.
  • window.addEventListener('message', function(e) { ... }) registers a listener. Every time a message event reaches this window, the function runs with the event as e.
  • document.getElementById('s').innerHTML = e.data.s; takes the s property of the message data and puts it into the element with id s as HTML. There is no check on e.origin anywhere.
  • The rest is a simple form with a heading (<h3 id="s">) and two inputs, one text field and one button. The heading is the element the script writes into.

Because nothing inspects e.origin, this page will accept a message from any website in the world. The origin check is the only thing that would normally stand between a stranger and this page, and here it is missing entirely.

The attacker's page

The attacker builds a page that opens the vulnerable page and then sends it a message:

HTML
<html><body><input type=button value="Click Me" id="btn"></body><script>  document.getElementById('btn').onclick = function(e){       window.poc = window.open('http://begbounty.xyz/postmessage1.html');    setTimeout(function(){        window.poc.postMessage     (                      {                                           "s": "<img src =x onerror=alert(1);>",                      },                     '*'             );   }, 2000);}</script></html>

Line by line:

  • <input type=button value="Click Me" id="btn"> is a button the victim is meant to click. The click is what starts everything, because browsers generally only let a page open a new window in response to a user action.
  • document.getElementById('btn').onclick = function(e){ ... } attaches a function that runs when the button is clicked.
  • window.poc = window.open('http://begbounty.xyz/postmessage1.html'); opens the vulnerable page in a new window and stores a handle to that window in a variable called poc. The handle is needed later to send it a message.
  • setTimeout(function(){ ... }, 2000); waits two seconds before running the inner function. The reason is practical: the new window needs time to load and register its listener. If the message were sent immediately, there might be nobody listening yet.
  • window.poc.postMessage({ "s": "<img src =x onerror=alert(1);>" }, '*'); sends an object with one property, s, whose value is an image tag. The src is deliberately broken (x), so the image cannot load. The onerror attribute is code that runs when loading fails. The second argument, '*', tells the browser to deliver the message regardless of the receiving window's origin.

Why this works: the receiving page has no origin check, so it accepts the message. It then puts the s value into innerHTML. The browser parses the <img> tag, tries to load x, fails, and runs alert(1). The alert appears inside the vulnerable page, not the attacker's page, which is what makes it cross-site scripting.

From the original on medium.com

Scenario 2: checking the origin with indexOf()

The vulnerable page

The second page does check the origin, but in a flawed way:

HTML
<html>    <head>        <title>XSS_ME_</title> </head>   <script>             window.addEventListener('message', function(e) {                 if(e.origin.indexOf("begbounty.xyz") > 0){                document.getElementById('s').innerHTML = e.data.s;                         }             });   </script> <body>  <div class="container"><form> <h3 id="s">Postmessage XSS</h3> <input type=text> </input>                            <input type="button" value="hehe!">                            </form> </div> </body></html>

Line by line:

  • The listener is registered the same way as before.
  • if(e.origin.indexOf("begbounty.xyz") > 0){ ... } is the check. indexOf is a string function that reports the position where a piece of text first appears inside another piece of text, or -1 if it does not appear at all. So this asks: does the text begbounty.xyz appear somewhere in the origin, at a position greater than zero?
  • If the answer is yes, the same innerHTML assignment runs.

The check is written out on its own in the article:

JavaScript
(e.origin.indexOf("begbounty.xyz") > 0)

The problem is that this is a "contains" test, not an "is equal to" test. It never asks whether the origin is begbounty.xyz. Any origin that contains that text at a position greater than zero passes. An attacker can register a domain that embeds the trusted name.

The attacker's page

The author created exactly such a subdomain and hosted the exploit there:

Text
https://begbounty.xyz.x3b.in/index.html

Read that address carefully. The browser treats the whole thing as one hostname, begbounty.xyz.x3b.in, which belongs to whoever controls x3b.in, not to the owners of begbounty.xyz. The text begbounty.xyz appears inside it, which is what the flawed check looks for.

The exploit page follows the same pattern as before:

HTML
<html><body><input type=button value="Click Me" id="btn"></body><script>document.getElementById('btn').onclick = function(e){       window.poc = window.open('http://begbounty.xyz/postmessage2.html');setTimeout(function(){        window.poc.postMessage     ({                                           "s": "<img src =x onerror=alert(1);>",},'*'             );   },2000);}</script></html>

Line by line:

  • The button and click handler are the same idea as before.
  • window.open('http://begbounty.xyz/postmessage2.html') opens the second vulnerable page and keeps the handle in window.poc.
  • After a two-second delay, postMessage sends the same object with the same s value, the broken image with onerror=alert(1), and the same wildcard '*' target.

When the message arrives, e.origin is the attacker's host. The indexOf call looks for begbounty.xyz anywhere in that string, and the author's bypass depends on it appearing at a position greater than zero. The result is the same alert(1), this time in the second vulnerable page.

From the original on medium.com

Scenario 3: a trusted origin that is itself vulnerable

The vulnerable page

The third page compares the origin strictly against a full address, including the scheme, the host and the port:

HTML
<html>    <head>        <title>XSS_ME_</title>            </head>    <script>             window.addEventListener('message', function(e) {                 if (e.origin == "http://[redacted]:8083") {                document.getElementById('s').innerHTML = e.data.s;                    }             });                    </script>        <body>            <div class="container">                <form>                            <h3 id="s">Postmessage XSS</h3>            <input type=text> </input>                            <input type="button" value="hehe!">                            </form>            </div>         </body></html>

Line by line:

  • The listener is registered as before.
  • if (e.origin == "http://[redacted]:8083") { ... } compares the origin of the message with one exact string. An origin in the browser is made of three parts: the protocol (http), the host (here an IP address) and the port (8083). All three must match for the comparison to be true.
  • Only if the comparison is true does the innerHTML assignment run.

This check is correct in the narrow sense. The listener will only act on messages coming from http://[redacted]:8083. So far, so good.

The author then asks a different question: what if that trusted address is itself vulnerable to stored or reflected XSS? Reflected XSS means the site takes something from the request, such as a value in the URL, and echoes it back into the page without making it safe. Stored XSS means the dangerous value is saved on the server and shown to later visitors. Either way, the attacker gets code running inside the trusted site.

That matters because the origin check assumes the trusted origin is trustworthy. If an attacker can run script inside that origin, then a message sent from it really does come from the trusted origin. The check passes honestly, and the protection is gone.

From the original on medium.com

In this case the trusted host was vulnerable to reflected XSS, so the author used that to inject the postMessage() exploit code into the trusted origin itself.

From the original on medium.com

The final exploit is shown in the article as an image rather than as text.

Why it works

The mistake is always in how the receiving page decides whether a message can be trusted.

  1. No check. The listener acts on any message from any origin. There is no decision to get wrong because there is no decision at all.
  2. Substring check. indexOf() is used as a "contains" test instead of an equality test. Any origin that contains the trusted text is accepted, and the author notes this can be bypassed by creating a subdomain that starts with the given string.
  3. Correct check, wrong trust. The comparison is exact, but whitelisting an origin assumes that origin cannot be controlled by an attacker. A reflected XSS there breaks that assumption.

In every case the payload ends up in innerHTML, which parses and runs HTML. Once the origin check is passed or bypassed, nothing else stands in the way.

What an attacker could do

When the check is missing or can be bypassed, an attacker who gets a victim to load an attacker-controlled page can run script in the context of the vulnerable application. The demonstrations use alert(1) to prove it. In the third scenario the attacker needs one extra condition: the trusted origin must itself be vulnerable to reflected or stored XSS. When it is, the attacker can run script in that trusted origin and send a message that passes the strict check. The article does not describe any specific real target, any data that was exposed, or any account impact beyond script execution in the page.

How to fix it

The author's recommendations are:

  1. Whitelist the origin in the window.addEventListener function.
  2. Use proper regex while whitelisting the domain.
  3. Perform cross-site scripting related test cases on all pages before whitelisting a domain or host in the function.

The article does not say whether any of these were applied to a live target.

Things to look for

  • Missing origin check. Look for message listeners that read e.data without inspecting e.origin. A positive result is a listener that writes message data into a DOM sink such as innerHTML and accepts a message from a page you control.
  • Substring checks. Search for indexOf, includes, startsWith or endsWith applied to e.origin. A positive result is an origin you can register that contains the whitelisted string, for example whitelisted.example.attacker.tld, and whose message is accepted.
  • Loose equality and type confusion. Check for comparisons that do not pin scheme, host and port exactly. A positive result is a message from an origin that differs from the intended one but still satisfies the comparison.
  • Trusted origin with its own XSS. For a strict origin check, test the whitelisted origin for reflected or stored XSS. A positive result is script execution inside that origin, which lets you send a message that passes the check.
  • Dangerous sinks. Wherever a listener passes message data to innerHTML, outerHTML, document.write or similar, confirm whether HTML in the payload is parsed. A positive result is an onerror or similar handler firing in the receiving page.

Glossary

  • API: a defined set of functions a program offers so other programs can use its features without knowing how it works inside. The browser's postMessage is an API for sending messages between windows.
  • Cross-origin communication: two pages on different origins (different protocol, host or port) exchanging data. Normally blocked by the browser, allowed in a controlled way through postMessage.
  • DOM: the browser's in-memory model of a page, a tree of elements such as headings, forms and inputs. JavaScript reads and changes the page through the DOM.
  • DOM-based XSS: cross-site scripting where the dangerous content is assembled by the page's own JavaScript in the browser, rather than being sent by the server.
  • Event listener: a function registered to run when something happens, such as a message arriving or a button being clicked.
  • innerHTML: a property that sets or reads the HTML inside an element. Assigning to it makes the browser parse the value as HTML, which is why script-bearing markup can run.
  • indexOf(): a string function that returns the position where a piece of text first appears inside another, or -1 if it is absent. It answers "does this contain that", not "is this equal to that".
  • onerror: an HTML attribute that holds code to run when an element, such as an image, fails to load.
  • Origin: the combination of protocol, host and port, for example http://[redacted]:8083. Two pages share an origin only if all three parts match.
  • Port: a number that identifies a specific service on a machine, such as 8083 in the address above.
  • postMessage(): the browser function used to send a message from one window to another, optionally restricted to a target origin.
  • Protocol: the scheme part of an address, such as http or https.
  • Reflected XSS: cross-site scripting where input from a request, such as a URL value, is echoed straight back into the page without being made safe.
  • Regex: a pattern language for matching text, used here to describe which origins are allowed.
  • Same Origin Policy: the browser rule that pages from different origins cannot freely read or change each other's content.
  • setTimeout(): a JavaScript function that runs another function after a delay in milliseconds. Here it gives the opened page time to load.
  • Sink: a place in code where data ends up being interpreted, such as innerHTML. A dangerous sink turns text into executable content.
  • Stored XSS: cross-site scripting where the dangerous value is saved on the server and served to later visitors.
  • Subdomain: a name placed in front of a domain, such as shop.example.com. Here the attacker's begbounty.xyz.x3b.in is a hostname under x3b.in that merely contains the trusted text.
  • Whitelist: an explicit list of things that are allowed, such as the origins a page will accept messages from.
  • window.open(): a browser function that opens a URL in a new window or tab and returns a handle to it, which can then be used to post messages.
  • XSS (cross-site scripting): a class of vulnerability where an attacker gets their own code to run inside another website's page, in that site's context.

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.