当前位置:网站首页>关于 Web Content-Security-Policy Directive 通过 meta 元素指定的一些测试用例

关于 Web Content-Security-Policy Directive 通过 meta 元素指定的一些测试用例

2022-07-07 10:07:00 InfoQ

Content Security Policy 是一种使用标题或 meta 元素来限制或批准加载到指定网站上的内容的策略。 这是一个广受支持的安全标准,所有网站运营者都应该对这些标准了然于心。

使用 CSP 通过说明允许或不允许的规则为 Web 网站增加了一层保护。 这些规则有助于防御内容注入和跨站点脚本 (XSS) 攻击,这是 OWASP 的十大 Web 应用程序安全风险中的两个。

当攻击者能够通过注入恶意代码来破坏未受保护的网站时,就会发生 XSS 攻击。 当用户尝试与站点交互时,恶意脚本会在用户的浏览器中执行,从而使攻击者能够访问受害者与站点的交互,例如登录信息等。

CSP 将阻止大多数脚本注入攻击的发生,因为它可以设置为将 JavaScript 限制为仅从受信任的位置加载。

本文介绍一些基于 
frame-src
 这个 Directive 的各种测试用例。作为容器,定义 iframe 的 web 应用,监听在 3000 端口:wechat 文件夹下

null
嵌入了另一个网页,监听在 3002 端口,Jerrylist 文件夹下面:

null
如果 Jerrylist 文件夹下的 csp html 里没有声明任何 csp 相关的 Directive(通过 meta 标签),则 iframe 工作正常:

null

测试1:3000 应用(即嵌入 3002 应用的 web 应用里)增加 frame-src

源代码:

<html>
 <head>
 <meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;frame-src 'self'&quot;>
 </head>
 <h1>Parent</h1>
 <iframe src=&quot;http://localhost:3002/csp&quot;></iframe>
</html>

null
测试结果:

Refused to frame 'http://localhost:3002/' because it violates the following Content Security Policy directive: &quot;frame-src 'self'&quot;.

iframe 加载失败:

null

测试2

null
<html>
 <head>
 <meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;frame-src 'http://localhost:3002'&quot;>
 </head>
 <h1>Parent</h1>
 <iframe src=&quot;http://localhost:3002/csp&quot;></iframe>
</html>

错误消息:

The source list for the Content Security Policy directive 'frame-src' contains an invalid source: ''http://localhost:3002''. It will be ignored.11:25:37.549 localhost/:6 Refused to frame 'http://localhost:3002/' because it violates the following Content Security Policy directive: &quot;frame-src 'none'&quot;.

iframe 加载失败:

null
改成 
*
 的话,又重新工作了:

null
null
下列代码也工作:

null
<html>
 <head>
 <meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;frame-src http://localhost:3002/csp&quot;>
 </head>
 <h1>Parent</h1>
 <iframe src=&quot;http://localhost:3002/csp&quot;></iframe>
</html>

下列代码也工作:

<html>
 <head>
 <meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;frame-src http://localhost:*/csp&quot;>
 </head>
 <h1>Parent</h1>
 <iframe src=&quot;http://localhost:3002/csp&quot;></iframe>
</html>

null
null
下列代码也工作:

null
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://xie.infoq.cn/article/23680109628cc4c3207242162