<html>
<head>
<script src="../resources/libwrapjs.js"></script>
<script src="../resources/cross-frame-access.js"></script>
<script>
    var code;
    var openedWindow;

    window.onload = function()
    {
        if (window.testRunner) {
            testRunner.waitUntilDone();
            testRunner.dumpAsText();
            testRunner.dumpChildFramesAsText();
        }

        var message_fail = 'FAIL: XSS was allowed.';
        var message_success = 'SUCCESS: Window remained in original SecurityOrigin.';

        var write_func = 'function write(target, message) { target.document.body.innerHTML = message; }\n';

        var try_attack = 'write(window.opener.top.frames[0], ' + libwrapjs.in_string(message_fail) + ');';
        var attack = 'setTimeout(function() {' + try_attack + '}, 100);\n';

        var try_control = 'write(window.opener.top.frames[1], ' + libwrapjs.in_string(message_success) + ');';
        var control = 'setTimeout(function() {' + try_control + '}, 200);\n';

        var sigDone = 'setTimeout(function() { if (window.testRunner) testRunner.globalFlag = true; }, 300);';

        var payload = write_func + attack + control + sigDone;
        code = libwrapjs.in_script_tag(payload);
        log("Code injected into window:");
        log(code);

        if (window.testRunner) {
            runTest();
        } else {
            log("To run the test, click the button below when the frames finish loading.");
            var button = document.createElement("button");
            button.appendChild(document.createTextNode("Run Test"));
            button.onclick = runTest;
            document.body.appendChild(button);
        }
    }

    runTest = function()
    {
        openedWindow = window.open('', 'attacker');
        openedWindow.document.write(code);
        openedWindow.document.close();

        setTimeout(pollForDone, 1);

        window.open.call(frames[0], '', 'attacker');
    }

    pollForDone = function()
    {
        if (!testRunner.globalFlag) {
            setTimeout(pollForDone, 1);
            return;
        }
        closeWindowAndNotifyDone(openedWindow);
    }
</script>
</head>
<body>
<div>This page opens a window to &quot;&quot;, injects malicious code, and
then uses <code>window.open.call</code> to set its opener to the victim.
The opened window then tries to scripts its opener.</div>
<pre id="console"></pre>
<iframe style="border: solid 3px red;" src="http://localhost:8000/security/resources/innocent-victim.html"></iframe>
<iframe style="border: solid 3px green;" src="../resources/innocent-victim.html"></iframe>
</body>
</html>
