postMessage Vulnerability refers to security issues arising from improper use of the window.postMessage() API, which enables cross-origin communication between windows. Vulnerabilities occur when origin validation is missing or messages are processed unsafely.
// Sender (e.g., in iframe or popup)
targetWindow.postMessage(data, targetOrigin);
// Receiver
window.addEventListener('message', function(event) {
// event.origin - sender's origin
// event.data - the message content
// event.source - reference to sender window
});
// VULNERABLE: No origin check
window.addEventListener('message', function(event) {
eval(event.data); // Arbitrary code execution!
});
// VULNERABLE: Using * as targetOrigin
window.postMessage(sensitiveData, '*'); // Any window can receive
// VULNERABLE: Weak origin validation
if (event.origin.indexOf('trusted.com') !== -1) {
// Bypassed with: attacker-trusted.com
}
// Receiver: Validate origin strictly
window.addEventListener('message', function(event) {
if (event.origin !== 'https://trusted.com') {
return; // Reject untrusted origins
}
// Safely process event.data (avoid eval, innerHTML)
});
// Sender: Specify exact origin
window.postMessage(data, 'https://specific-origin.com');