Search code examples
javascriptsecurityiframexsspostmessage

Security concerns with window.postMessage() + iframes + developer tools


I've read up on how to avoid security issues when using window.postMessage() -- particularly the suggestions in this MDN doc.

But given all the preventative tips are all client-side, I'm having trouble understanding how they'd stop bad actors from simply editing changing the code in their developer tools.

Here's the situation I'm dealing with. I have a page that will contain an embedded iframe, and I have control over that iframe (it lives on a separate domain, but the vendor that provides it allows me to put custom JavaScript in the iframe source). The parent window and the iframe will communicate back and forth.

/**
  window at https://firstgoodorigin.com

  Receives message from iframe to indicate
  its contents have loaded.

  Once that message has been received,
  send a message back to the iframe.
*/
function handleMessage(message) {
  if (message.origin === 'https://secondgoodorigin.com') {
    // verify and sanitize what's in message.data
    // (it'll be something like "loaded")
    // if it's good, send a message back
    message.source.postMessage('foo', 'https://secondgoodorigin.com');
  }
}

window.addEventListener('message', handleMessage, false);


/**
  iframe at https://secondgoodorigin.com

  Tell parent window it has loaded. Once that happens
  it will receive a message from the parent window, for
  which we add an event listener.
*/
window.addEventListener('load', () => {
  window.parent.postMessage('loaded', https://firstgoodorigin.com);
});

window.addEventListener('message', (message) => {
  if (message.origin === 'https://firstgoodorigin.com') {
    // verify and sanitize what's in message.data
    // do stuff
  }
});

Given both the window source and iframe source will be editable inside someone's web inspector, what's to stop them from removing all the validation logic and replacing it with something malicious? What am I missing here?


Solution

  • As mentioned in the comment by Will any code in the browser can be edited by the end user if he or she may want to. The point of the locking down postmessages is to stop a third web site from posting unwanted messages.

    If a user is logged into the site in question, and then loads a malicious website, that website could load the web site in question in an iframe or a popup, and then post messages unauthorized to the site.