iframe的安全問題

今天嘗試在iframe中嵌入外部網站, 碰到了一些小問題.

如何讓自己的網站不被其他網站的iframe引用?

我測試的時候發現我把iframesrc指定到github不起作用. 原來是它把X-Frame-Options設置爲了DENY, 這樣就禁用了別的網站的iframe引用, 避免點擊劫持(clickjacking).

X-Frame-Options有三個可能值: DENYSAMEORIGINALLOW-FROM uri.

詳見: The X-Frame-Options response header

如何禁用自己iframe中鏈接的外部網站的JS?

我發現我把一個外部網站引入到我的iframe中時, 該網站的噁心JS會讓我的網頁跳轉到它的網站! 蛋疼. 但是我在測試的是否發現, Codepen就能夠避免這個跳轉, Console中有信息:

Unsafe JavaScript attempt to initiate navigation for frame with URL 'http://codepen.io/lzl124631x/pen/jWeOPL' from frame with URL 'http://keepvid.com/?url=https://www.youtube.com/watch?v=wY2vhSb3cVo'. The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.
(anonymous function) @ ?url=https://www.youtube.com/watch?v=wY2vhSb3cVo:108
?url=https://www.youtube.com/watch?v=wY2vhSb3cVo:579 GET http://www.5kplayer.com/kvads/keepvid-728-90.png net::ERR_BLOCKED_BY_CLIENT

原來是iframe的屬性sandbox的作用.

sandbox屬性可以設置的值包括:
allow-forms
allow-modals
allow-orientation-lock
allow-pointer-lock
allow-popups
allow-popups-to-escape-sandbox
allow-same-origin
allow-scripts
allow-top-navigation

如果給iframe加上sandbox="allow-forms allow-scripts", 就會打開allow-formsallow-scripts兩個選項, 其他的全部禁用.

如果想禁用讓外部網站的JS, 不要加allow-scripts就好了.

如果想禁用外部網站的JS跳轉, 不要加allow-top-navigation就可以了.

詳見: <iframe> Sandbox

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章