The Same Origin Policy / Chapter 13 of 14

postMessage API Implementation and limitations

postMessage API Implementation and limitations in Pankaj Mouriya's Same Origin Policy guide.

All chapters ↘
  1. 01 / Introduction
  2. 02 / What should be Allowed?
  3. 03 / Same Origin Policy
  4. 04 / Access Different Orgins
  5. 05 / Same Origin Policy in Tabs
  6. 06 / Same Origin Policy to Anchors
  7. 07 / Same Origin Policy to Forms
  8. 08 / Same Origin Policy to Images and CSS
  9. 09 / Same Origin Policy to JavaScript
  10. 10 / Same Origin Policy to Web Storage
  11. 11 / Same Origin Policy to Cookies
  12. 12 / Getting Around Same Origin Policy
  13. 13 / postMessage API Implementation and limitations
  14. 14 / References

postMessage#

postMessage safely enables cross origin communication between objects, e.g., between a page, pop up, between a page and an iframe.

Requirement: You need to have some kind of reference to the other origin with whom you want to talk to. It can be an embedded iframe

postMessage API Implementation and limitations, figure 1

Sender

Code
targetWindow.postMessage("hello other document!", "*");

Receiver

Code
window.addEventListener("message",function(message){console.log(message.data)});

Limitation#

Let's assume, store.sitea.com wants to retrieve a username, so it listens for messages from login.sitea.com

Code
window.addEventListener(‘message’ event => {
setCurrentUser(event.data.name)
})

Store.sitea.com embeds an iframe to login.sitea.com which runs below code

Code
const data = { username: ‘PankajMouriya’ }
window.parent.postMessage(data, ‘*’)
postMessage API Implementation and limitations, figure 2

Imagine what if attacker embeds login.sitea.com

postMessage API Implementation and limitations, figure 3

Remediation#

You can specify the destination origin for which the message is intended to

Validate Destination of message -

Code
const data = { username: ‘PankajMouriya’ }
window.parent.postMessage(data, ‘http://store.sitea.com’)

But again, because store.sitea.com listens for messages from any source as it does not explicitly mentions which source, an attacker can embed store.sitea.com and send bogus messages to it

postMessage API Implementation and limitations, figure 4

Remediation#

Validate source of message -

Code
window.addEventListener(‘message’ event => {
if(event.origin !== ‘http://login.sitea.com’) return
setCurrentUser(event.data.name)
})
On this page