postMessage XSS and Data Injection
You'll learn: How attackers exploit postMessage to inject malicious scripts and manipulate trusted application contexts through cross-origin messaging.
The Vulnerability
When applications receive messages via postMessage without proper validation, attackers can inject malicious content that gets executed or processed as trusted data. Even if you validate the origin (which you learned in the previous lesson), you still must validate the message content itself.
How the Attack Works
Think of postMessage like accepting packages through your mail slot. Even if you verify the sender's address (origin), you still need to inspect what's inside the package before using it.
Attackers exploit applications that:
- Directly insert message data into the DOM without sanitization
- Use message content in
eval()or other dynamic code execution - Trust message structure without validating data types or formats
Common attack scenario:
// Vulnerable receiver
window.addEventListener('message', function(event) {
// Origin validated (good)
if (event.origin !== 'https://trusted.com') return;
// But data is blindly trusted (bad!)
document.getElementById('content').innerHTML = event.data;
});
An attacker controlling trusted.com (through XSS there, subdomain takeover, or other means) sends:
window.postMessage('<img src=x onerror=alert(document.cookie)>', 'https://yourapp.com');
The receiving application executes the injected script because it trusted the message content from a verified origin.
Prevention Pattern
Always validate and sanitize message content, treat it as untrusted user input, and avoid inserting it directly into the DOM or execution contexts.
Key Takeaway: Validating postMessage origin is necessary but insufficient—you must also sanitize and validate the message data itself, treating every message as potentially malicious even from trusted origins.