How can I prevent an iframe from accessing parent frame?

醉酒当歌 提交于 2019-12-03 12:05:18

If the child iframe is loaded from a different domain, then it will not be able to access the parent page or DOM.

However, there is a still a possible vulnerability to man-in-the-middle attack as follows. Suppose your page loads off http://yoursite.com and the iframe goes to http://badsite.org

  • first http://badsite.org redirects to http://yoursite.com/badpage

  • This is the step that requires a man-in-the-middle attack. The attacker must either be able to get between the user and yoursite.com, or control the answers to your DNS lookup. This is easier than it sounds -- anyone who has administrative control over a public WiFi access point could do it (think Starbucks, hotels, airports.) The goal is to serve the content of http://yoursite.com/badpage from the attacker's site, not your actual site.

  • The attacker can then serve whatever malicious code they like from the (fake) http://yoursite.org/badpage. Because this is in the same domain as the main page, it will have access to the parent DOM.

The HTML5 iframe sandbox attribute seems to be the way to avoid this. You can read the spec, but the best description might be here.

This seems to be supported on Chrome, IE10, FireFox, Safari.

The spec says that if the "allow-same-origin" attribute is not set, "the content is treated as being from a unique origin." This should prevent your child iframe from accessing any part of the parent's DOM, no matter what the browser thinks the URL is.

You shouldn't need to worry about that happening.

The only way iframes can talk cross-origin is with postMessage, and that's only possible if you're listening to that domain directly.

https://developer.mozilla.org/en/DOM/window.postMessage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!