Is it secure to use window.origin with postMessage?

Viewed 1184

When using postMessage it's important to define a targetOrigin to ensure we don't leak data to other sites.

It's equally important to check the origin when receiving a message to prevent other sites from triggering our scripts.

But, if we're just expecting to do this on our own domain, is there anything wrong with:

targetWindow.postMessage({message}, window.origin);

--

window.addEventListener("message", e => {
  if (e.origin == window.origin){
    //Trigger something
  }
});
1 Answers

I'm not a security expert, but MDN recommends to check message's origin & possibly source properties. So, that's right to check it & we can consider it safe.

Now, the question starts to be:

How safe is it to check the message's origin against the window's origin?

First of all, consider that there are 2 ways to check the origin of the window. The one you are trying to use is WindowOrWorkerGlobalScope.origin the alternative one is window.location.origin.

I wouldn't use WindowOrWorkerGlobalScope.origin because it can be overwritten on client-side. Try it out:

window.origin = 'https://www.example.com';
console.log(window.origin === 'https://www.example.com');

I don't think it's a direct security threat (though I'm not a security expert as I stated above), but given certain conditions, it can make it too easy to perform a successful attack.

window.location.origin might be a better choice because it is read-only & it cannot be modified on client-side. As a bonus, it has wider browser support.

So, I would use either window.location.origin or hard-code the URL as shown at MDN.

If hard-coding URL seems problematic because of testing, you could use environmental variables if your project uses modern building tools.

Related