Content Security Policy 是一种使用标题或 meta 元素来限制或批准加载到指定网站上的内容的策略。 这是一个广受支持的安全标准,所有网站运营者都应该对这些标准了然于心。
使用 CSP 通过说明允许或不允许的规则为 Web 网站增加了一层保护。 这些规则有助于防御内容注入和跨站点脚本 (XSS) 攻击,这是 OWASP 的十大 Web 应用程序安全风险中的两个。
当攻击者能够通过注入恶意代码来破坏未受保护的网站时,就会发生 XSS 攻击。 当用户尝试与站点交互时,恶意脚本会在用户的浏览器中执行,从而使攻击者能够访问受害者与站点的交互,例如登录信息等。
CSP 将阻止大多数脚本注入攻击的发生,因为它可以设置为将 JavaScript 限制为仅从受信任的位置加载。
本文介绍一些基于 frame-src
这个 Directive 的各种测试用例。
作为容器,定义 iframe 的 web 应用,监听在 3000 端口:wechat 文件夹下

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

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

测试1:3000 应用(即嵌入 3002 应用的 web 应用里)增加 frame-src
源代码:
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="frame-src 'self'">
</head>
<h1>Parent</h1>
<iframe src="http://localhost:3002/csp"></iframe>
</html>

测试结果:
Refused to frame 'http://localhost:3002/' because it violates the following Content Security Policy directive: "frame-src 'self'".
iframe 加载失败:

测试2

<html>
<head>
<meta http-equiv="Content-Security-Policy" content="frame-src 'http://localhost:3002'">
</head>
<h1>Parent</h1>
<iframe src="http://localhost:3002/csp"></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: "frame-src 'none'".
iframe 加载失败:

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


下列代码也工作:

<html>
<head>
<meta http-equiv="Content-Security-Policy" content="frame-src http://localhost:3002/csp">
</head>
<h1>Parent</h1>
<iframe src="http://localhost:3002/csp"></iframe>
</html>
下列代码也工作:
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="frame-src http://localhost:*/csp">
</head>
<h1>Parent</h1>
<iframe src="http://localhost:3002/csp"></iframe>
</html>


下列代码也工作:

网友评论