'HTML Iframes overwrite document.write

Main context

  • I inject a js script in every HTML page through a proxy
  • My js code is the first evaluated script in the page
  • I can modify the page with the proxy
  • My goal is to add a dynamic attribute to every scripts generated client side before the execution.
  • All function overwrites work properly except for the write function
  • The page could have IFrame nodes statically or dynamically generated (or modifed!) which use the write function.

Code

In my injected script there is this code which overwrites the native write function, checks the content, if there are script tags it adds an attribute and recall the original function:

...
var TYPE_WRITE = "type_write";
var f_write = HTMLDocument.prototype.write;
HTMLDocument.prototype.write = function () {
    arguments = my_mitm_function(arguments, TYPE_WRITE);
    return f_write.apply(this, arguments);
};
...

Problems

It works perfectly except in case of "write" in a "IFrame", here an example:

...
var myIFrame = document.createElement("iframe");
document.body.appendChild(myIFrame);
myIFrame = (myIFrame.contentWindow) ? myIFrame.contentWindow : (myIFrame.contentDocument.document) ? myIFrame.contentDocument.document : myIFrame.contentDocument;
myIFrame.document.open();
myIFrame.document.write("<script>alert('Msg from inside');<\/script>");
myIFrame.document.close();
...

I think the problem is that every IFrame have a different document

Is there a way to hook every "write" function in every "IFrame" context? or a way to get around ?

More details

  • I need to add a "nonce" attribute because the CSP policy of the page does not allow scripts but only "nonce" attributes.
  • I already tested other alternative such as 'MutationObserver' but my function must add the attribute before the CSP engine evalutation.


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source