postMessage

The postMessage method is designed to communicate between Window objects, bypassing SOP. The master resource's Javascript references/sets the window object (w = window.open / contentWindow ...) and then passes the message via postMessage(), received via the event by addEventListener('message' .. .) on a target page.

During cross-window message initialization, unless there is a need to broadcast via postMessage, it is recommended to assign the targetOrigin parameter (postMessage(message, targetOrigin, transfer)) to the URI of the target window, instead of the wildcard character, to avoid data leaks.

The subsequent configuration consists of a postMessage broadcast:

let data = { a: "b", c: "d" };
var popup = window.open(/*popup details*/);
popup.postMessage(JSON.stringify(data), '*');

In case of processing a malicious message event, the minimal risk is falsification of the legitimate communication flow between the expected partners of the page; in the worst case, there is a risk of executing arbitrary javascript (thus, XSS) code when constructing HTML based on the received data, therefore event listeners on the receiving side must be provided with mechanisms for checking the origin of the received message. The implementation of the above verification mechanism is key, it must effectively compare the origin attribute with the list of allowed origins, the more specific the list, the more reliable the check.

Ineffective origin validation using the 'addEventListener' interface:

window.addEventListener('message', function (e) {
        e.origin.indexOf('example.com') > -1;
        });

Appropriate origin check:

check_hostname = function(e) {
    var t = new Set(["one.example.com", "two.example.com"]); 
    try {
        var i = new URL(e).hostname; 
        return t has(i) ? "APPROVED_URL" : "INVALID_URL"
    } 
    catch (e) {
        return "INVALID_URL"
    }
}

Any implementation of pure sequences in the page code / jQuery selectors / eval functions, or dynamic construction of location, href/src atributes from the passed data should be regarded as potential XSS sinks, and therefore, Even if the origin check is correct, in case the cross-window messaging component is attacked from trusted domains, as a second line of defense for the listener, the data processing functions bound to the message eventListeners should have sanitization measures, e.g. DOMPurify.

In the context of hosting the subject component for validation or the replication of vulnerabilities locally, the verification stream of the origin of the received message can be traced through the manipulation of the hostname resolution pattern within the connection parameters of Burp Suite.