JavaScript - Avoid unrestricted targetOrigin on cross-domain messaging - UI Policy scriptTrue

Impact area

Security

Severity

High

Affected element

UI Policy

Rule number

SN-0332

Impact

HTML5 adds the ability to send messages to documents served from other domains. If improperly used, this can cause a data leak.

Remediation

Do not use unrestricted targetOrigin calls.

Time to fix

20 min

References

This rule is linked to Common Weakness Enumeration CWE-1021 Improper Restriction of Rendered UI Layers or Frames.

Code examples


Noncompliant code

When sending message:

var iframe = document.getElementById("testiframe");
iframe.contentWindow.postMessage("secret", "*"); // Noncompliant: * is used

When receiving message:

window.addEventListener("message", function(event) { // Noncompliant: no checks are done on the origin property.
console.log(event.data);
});

Compliant code

When sending message:

var iframe = document.getElementById("testsecureiframe");
iframe.contentWindow.postMessage("hello", "https://secure.example.com"); // Compliant

When receiving message:

window.addEventListener("message", function(event) {
if (event.origin !== "http://example.org") // Compliant
return;

});




Last modified on Mar 19, 2021