window-postmessage-unsafe-target-origin¶
window.postMessage
is a browser API that allows sending structured data between two domains with with signature:
postMessage(message: any, targetOrigin: string)
The parameter in question is targetOrigin
as it is the URL of the window that the message is being sent to. The protocol, port and hostname of the target window must match this parameter for the message to be sent.
It is possible to specify "*"
as the targetOrigin
parameter to match any URL however. This however, is strongly discouraged as it opens a vector for an attacker
to send sensitive information from the browser to an origin of their choice.
Examples¶
Insecure Example
const myWindow = document.getElementById("myIFrame").contentWindow;
myWindow.postMessage(message, "*");
Secure Example
The secure way is to be very explicit about the target origin. As most code is deployed and tested
on different environments (dev, staging, production, etc) it is more practical to employ a configuration file
for the value targetOrigin
as opposed to hard coded literal as described below.
const myWindow = document.getElementById('myIFrame').contentWindow;
myWindow.postMessage(message, "http://knownsite.com/where/myWindow/is/hosted");