跨域脚本攻击 XSS 是最常见、危害最大的网页安全漏洞。
上面代码指定,将注入行为报告给/my_amazing_csp_report_parser这个 URL。
浏览器会使用POST方法,发送一个JSON对象,下面是一个例子。

三、Content-Security-Policy-Report-Only
除了Content-Security-Policy,还有一个Content-Security-Policy-Report-Only字段,表示不执行限制选项,只是记录违反限制的行为。它必须与report-uri选项配合使用。
四、选项值
每个限制选项可以设置以下几种值,这些值就构成了白名单。
如果同一个限制选项使用多次,只有第一次会生效。
除了常规值,script-src还可以设置一些特殊值。注意,下面这些值都必须放在单引号里面。
页面内嵌脚本,必须有这个token才能执行。
hash值的例子如下,服务器给出一个允许执行的代码的hash值。
下面的代码就会允许执行,因为hash值相符。
注意,计算hash值的时候,<script>标签不算在内。
(3)必须特别注意 JSONP 的回调函数。
Content-Security-Policy: default-src 'self'; ...; report-uri /my_amazing_csp_report_parser;
浏览器会使用POST方法,发送一个JSON对象,下面是一个例子。
{ "csp-report": { "document-uri": "http://example.org/page.html", "referrer": "http://evil.example.com/", "blocked-uri": "http://evil.example.com/evil.js", "violated-directive": "script-src 'self' https://apis.google.com", "original-policy": "script-src 'self' https://apis.google.com; report-uri http://example.org/my_amazing_csp_report_parser" } }


除了Content-Security-Policy,还有一个Content-Security-Policy-Report-Only字段,表示不执行限制选项,只是记录违反限制的行为。它必须与report-uri选项配合使用。
Content-Security-Policy-Report-Only: default-src 'self'; ...; report-uri /my_amazing_csp_report_parser;
四、选项值
每个限制选项可以设置以下几种值,这些值就构成了白名单。
- 主机名:http://example.org,https://example.com:443
- 路径名:http://example.org/resources/js/
- 通配符:*.http://example.org,*://*.example.com:*(表示任意协议、任意子域名、任意端口)
- 协议名:https:、data:
- 关键字'self':当前域名,需要加引号
- 关键字'none':禁止加载任何外部资源,需要加引号
Content-Security-Policy: script-src 'self' https://apis.google.com
# 错误的写法 script-src https://host1.com; script-src https://host2.com
# 正确的写法 script-srchttps://host1.com https://host2.com
如果不设置某个限制选项,就是默认允许任何值。
五、script-src 的特殊值除了常规值,script-src还可以设置一些特殊值。注意,下面这些值都必须放在单引号里面。
- 'unsafe-inline':允许执行页面内嵌的<script>标签和事件监听函数
- unsafe-eval:允许将字符串当作代码执行,比如使用eval、setTimeout、setInterval和Function等函数。
- nonce值:每次HTTP回应给出一个授权token,页面内嵌脚本必须有这个token,才会执行
- hash值:列出允许执行的脚本代码的Hash值,页面内嵌脚本的哈希值只有吻合的情况下,才能执行。
Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'
<script nonce=EDNnf03nceIOfn39fn3e9h3sdfa> // some code </script>
Content-Security-Policy: script-src 'sha256-qznLcsROx4GACP2dm0UCKCzCG-HiZ1guq6ZZDob_Tng='
下面的代码就会允许执行,因为hash值相符。
<script>alert('Hello, world.');</script>
除了script-src选项,nonce值和hash值还可以用在style-src选项,控制页面内嵌的样式表。
六、注意点
(1)script-src和object-src是必设的,除非设置了default-src。
因为攻击者只要能注入脚本,其他限制都可以规避。而object-src必设是因为 Flash 里面可以执行外部脚本。
(2)script-src不能使用unsafe-inline关键字(除非伴随一个nonce值),也不能允许设置data:URL。
下面是两个恶意攻击的例子。<img src="x" onerror="evil()"> <script src="data:text/javascript,evil()"></script>
(3)必须特别注意 JSONP 的回调函数。
<script src="/path/jsonp?callback=alert(document.domain)//"> </script>
上面的代码中,虽然加载的脚本来自当前域名,但是通过改写回调函数,攻击者依然可以执行恶意代码。
七、参考链接
CSP Is Dead, Long Live CSP! , by Lukas Weichselbaum
An Introduction to Content Security Policy, by Mike West
文章内容来源自《Content Security Policy 入门教程》,作者:阮一峰@蚂蚁金服