mediumCWE-346A01:2021

PostMessage Without Origin Verification

window.addEventListener('message') handlers that process messages without checking the event.origin, allowing any website to send commands to your app's message handler.

How It Works

postMessage is used for cross-origin iframe communication. When you listen for messages without verifying origin, any page on the internet can send a message to your window (if they can get a reference to it via a popup or iframe). If your handler performs actions based on message data, the attacker controls those actions.

Vulnerable Code
// BAD: no origin check — any site can send messages
window.addEventListener('message', (event) => {
  if (event.data.type === 'navigate') {
    window.location.href = event.data.url; // open redirect via postMessage
  }
});
Secure Code
// GOOD: verify origin before processing
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://trusted-parent.com') return;
  if (event.data.type === 'navigate') {
    const allowed = ['/dashboard', '/settings'];
    if (allowed.includes(event.data.url)) window.location.href = event.data.url;
  }
});

Real-World Example

PostMessage origin bypass vulnerabilities have been found in payment widgets, OAuth popups, and chat widgets. Attackers can redirect users, steal tokens passed via postMessage, or trigger actions in the embedded frame. HackerOne has hundreds of reports for this class.

How to Prevent It

  • Always check event.origin against a hardcoded allowlist before processing any message
  • Validate the structure and content of event.data — don't trust it blindly
  • Use a specific message protocol/type system and ignore unknown message types
  • When sending messages, always specify the targetOrigin parameter (never use '*')

Affected Technologies

ReactNext.jsjavascript

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities