Course contentsShow
← Security
Lesson 1065 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

postMessage Origin Validation Vulnerabilities

Exploiting weak origin checks, wildcard origins, and validation bypass techniques in postMessage handlers.

postMessage Origin Validation Vulnerabilities

What you'll learn: You'll discover how attackers exploit weak or missing origin checks in postMessage handlers to inject malicious data across origins.

The Core Problem

The postMessage API allows cross-origin communication, but it's your responsibility to validate who sent the message. Many developers either skip validation entirely, use overly permissive checks, or implement flawed logic that attackers can bypass. This turns a controlled communication channel into an open backdoor.

Common Validation Mistakes

Weak Origin Checks:

// INSECURE: accepts any subdomain
window.addEventListener('message', (event) => {
  if (event.origin.includes('example.com')) {
    // Process message - DANGEROUS!
  }
});

An attacker controlling evil-example.com or example.com.attacker.com bypasses this check.

Wildcard Origins:

// INSECURE: accepts anything
window.addEventListener('message', (event) => {
  // No origin check at all!
  processData(event.data);
});

Regex Bypass:

// INSECURE: flawed regex
if (event.origin.match(/example\.com$/)) { ... }

Bypassed by attackerexample.com or example.com.evil.com.

Proper Validation

Always use exact matching with an allowlist:

// SECURE
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://trusted.example.com') {
    return; // Reject everything else
  }
  // Safe to process
  processData(event.data);
});

Analogy: It's like checking someone's ID at the door. Don't just glance for the word "Smith" anywhere on the card—verify the exact full name, address, and photo against your guest list.

Key Takeaway: Always validate postMessage origins with exact string comparison (===) against a strict allowlist of trusted origins, never using substring matching, wildcards, or flawed regex patterns.