Skip to content

PostMessage Vulnerabilities

Concept

The PostMessage API is an alternative to JSONP, XHR with CORS headers requests that enable sending data between origins. To understand PostMessage you need to know cross-origin communication in modern browsers.

Cross-origin Communication

Modern web browsers employ an important security mechanism known as the Same Origin Policy (SOP) that acts as a security boundary between web pages loaded from different “origins”.

Same Origin Policy

The same-origin policy is a critical security mechanism that restricts how a document or script loaded by one origin can interact with a resource from another origin. Two URLs have the same origin if the protocol, port (if specified), and host are the same for both.

The following table gives examples of origin comparisons with the URL http://store.company.com/dir/page.html

URL Outcome Reason
http://store.company.com/dir2/other.html Same Origin Only the Path differs
http://store.company.com/dir/inner/another.html Same Origin Only the Path differs
https://store.company.com/page.html Failure Different protocol
http://store.company.com:81/dir/page.html Failure Different port
http://news.company.com/dir/page.html Failure Different host

PostMessage()

The window.postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.

Syntax

targetWindow.postMessage(message, targetOrigin, [transfer]);

Sending a Message

targetWindow.postMessage("unstable was here", "*");

Receiving a message

window.addEventListener("message", function(message){console.log(message.data)});

To send a message application calls "PostMessage" function with a message and target origin which in this case is a wildcard.

At the receiving end, a "message" event handler can be used.

Vulnerabilities

If PostMessage is not implemented correctly it can lead to Cross-site scripting vulnerabilities or in some cases information disclosure.

How to test?

XSS

Most of the time XSS arises when at receiving end there is no validation of an origin. So if you don't see the following origin validation code at the receiver end there might be a chance for XSS.

window.addEventListener("message", (event)=>{
    if (event.origin !== "http://safe.com")
    return;
    ...
}

Also at the parent window, the target origin must be set to a wildcard to perform the XSS.

targetWindow.postMessage("xss", "*");

When there is no validation on the child window an attacker can host a different webpage with the XSS payload as per the functionality.

Detection

The way to detect PostMessage vulnerabilities is to read the javascript code. There are some tools that can help you to some extent. The easiest way is to use the developer console. You can find this under sources -> Global Listeners. The other tools like PMHook with TamperMonkey can be used.

Tools

References