postMessage Vulnerability
Security issues from improper use of window.postMessage() for cross-origin communication, typically due to missing origin validation or unsafe message handling.
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.
How postMessage Works
// 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
});
Secure Implementation
// 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');
Exploitation Scenarios
- XSS via unsanitized message content
- Sensitive data leakage to attacker windows
- DOM manipulation through injected messages
- OAuth token theft from cross-origin popups