关于前端安全问题,一直关注的比较少。从target="_blank"开始!
如果你开启了eslint校验,如下的写法:
<a
target="_blank"
href={`https://work.alibaba-inc.com/nwpipe/search?keywords=${item.nickName}&type=person`}
>XXXX
</a>
那就会得到以下的错误提示:
ESLint: Using target="_blank" without rel="noopener noreferrer" is a security risk: see https://mathiasbynens.github.io/rel-noopener (react/jsx-no-target-blank)
而且提示这是一个很严重的安全漏洞。
真是让人烦恼,解决方法很 easy呀,加上
rel="noopener noreferrer"
Buuuuuutttttttttt,why?
参考原文:
https://mathiasbynens.github.io/rel-noopener/
关于rel = noopener
它解决了什么问题呢?
当你正在浏览index.html
想象一下以下的链接是你网站上用户生成的内容。
点击上面的链接,新打开malicious.html在新的页面(使用target=_blank)。就本身而言,并不是一件让人兴奋的事情。
但是malicious.html文档在一个新的tab页包含了一个window.opener,它指向你当前正在浏览的页面。
这意味着一旦用户点击了链接,malicious.html就可以对文档的window的对象有着觉得的控制权。
index.html:
<a target=_blank href="./malicious.html">
Click me !! one (same-origin)
</a>
malicious.html
// window.opener 返回打开当前窗口的那个窗口的引用
if(window.opener){
opener.location = 'http://localhost:63342/Security/index.html/#hax'
// Just `opener.location.hash = '#hax'` only works on the same origin.
}
注意,当index.html和malicious.html如果是不同源,这也是有效的,windoe.opener.location可以跨源访问!(像window.opener.document是不能跨源访问的,因此CORS不适用在此处)。
在此概念证明中,malicious.html用index.html#hax替换包含index.html的选项卡,index.html#hax选项卡显示隐藏的信息。这是一个相对无害的示例,但它可以重定向到网页仿冒页面,设计看起来像真正的index.html,要求用户填写登录凭据。用户可能不会注意到这一点,因为当重定向发生在后台时,用户焦点会集中在新窗口中的恶意页面上。通过在重定向到后台的网络钓鱼页面之前添加延迟,可以使此攻击更加微妙。
LT;DR如果设置了window.opener,则无论安全性来源如何,页面都可以在开启器中触发导航。
推荐
防止页面滥用window.opener,使用rel=noopener,这样做保证了window.opener是null,在以下浏览器中适用:
Chrome 49 & Opera 36, Firefox 52, Desktop Safari 10.1+, and iOS Safari 10.3+.
对于老版本的浏览器,可以使用rel=noreferrer, 它也会禁用referer HTTP头部,或者以下JavaScript解决方法可能触发弹出窗口阻止程序:
var otherWindow = window.open();
otherWindow.opener = null;
otherWindow.location = url;
注意,基于JavaScript的解决方法在Safari中失败。 对于Safari支持,请注入隐藏的iframe以打开新标签,然后立即删除iframe。