跳转到主要内容

category

同源策略是一种浏览器安全功能,它限制一个源上的文档和脚本如何与另一源上的资源交互。

浏览器可以同时加载和显示来自多个站点的资源。您可能同时打开多个选项卡,或者一个网站可以嵌入来自不同网站的多个iframe。如果这些资源之间的交互没有限制,并且脚本被攻击者破坏,则脚本可能会暴露用户浏览器中的所有内容。

同源策略通过阻止对从不同源加载的资源的读取访问来防止这种情况发生。“但是等一下,”你说,“我一直从其他来源加载图像和脚本。”浏览器允许一些标签嵌入来自不同来源的资源。此策略主要是一个历史工件,可能会使您的网站暴露于使用iframe的点击劫持等漏洞。您可以使用内容安全策略限制这些标记的跨来源读取。

什么被认为是同源的?


origin 由schema(也称为协议,例如HTTP或HTTPS)、端口(如果已指定)和主机定义。当这三个URL对于两个URL都相同时,它们被认为是同源的。例如http://www.example.com/foo与同源http://www.example.com/bar但不是https://www.example.com/bar因为schema不同。


什么是允许的,什么是阻止的?

iframes Cross-origin embedding is usually permitted (depending on the X-Frame-Options directive), but cross-origin reading (such as using JavaScript to access a document in an iframe) isn't.
CSS Cross-origin CSS can be embedded using a <link> element or an @import in a CSS file. The correct Content-Type header may be required.
forms Cross-origin URLs can be used as the action attribute value of form elements. A web application can write form data to a cross-origin destination.
images Embedding cross-origin images is permitted. However, reading cross-origin image data (such as retrieving binary data from a cross-origin image using JavaScript) is blocked.
multimedia Cross-origin video and audio can be embedded using <video> and <audio> elements.
script Cross-origin scripts can be embedded; however, access to certain APIs (such as cross-origin fetch requests) might be blocked.

如何防止点击劫持

Figure: Clickjacking mechanism illustrated in 3 separate layers (base site, iframed site, transparent button).

一种名为“点击劫持”的攻击将网站嵌入iframe中,并覆盖链接到不同目的地的透明按钮。用户在向攻击者发送数据时,会被诱骗以为自己正在访问您的应用程序。

若要阻止其他网站将您的网站嵌入到iframe中,请在HTTP标头中添加一个带有框架祖先指令(frame-ancestors directive )的内容安全策略。

或者,您可以将X-Frame-Options添加到HTTP标头中。有关选项列表,请参阅MDN

总结


希望您能松一口气,因为浏览器努力成为网络安全的守护者。尽管浏览器试图通过阻止对资源的访问来确保安全,但有时您希望访问应用程序中的跨源资源。在下一个指南中,了解跨来源资源共享(CORS),以及如何告诉浏览器允许从可信来源加载跨来源资源。

文章链接