0

我最近将 jQuery 从 2.1.1 升级到 3.5.1,我开始在 Chrome 浏览器的控制台中看到这个 CSP 违规

拒绝执行内联脚本,因为它违反了以下内容安全策略指令:“script-src 'self' 'nonce-7xyNokwFS08H1wnqtUmzycmiRKTgUZJQZJUN34B0v8A=' 'unsafe-eval'”。启用内联执行需要“unsafe-inline”关键字、哈希(“sha256-+oZkjQp5ZgVWtUq2rV5UqKJhNxGno8jem/DRZmR+mcI=”)或随机数(“nonce-...”)。

b@jquery.min.js:2

但是发布的 CSP 报告显示

"csp-report": {
    "document-uri": "https://subdomain.mydomain.com/docs/s",
    "referrer": "https://subdomain.mydomain.com/",
    "violated-directive": "script-src-elem",
    "effective-directive": "script-src-elem",
    "original-policy": "default-src 'none'; script-src 'self' 'nonce-7xyNokwFS08H1wnqtUmzycmiRKTgUZJQZJUN34B0v8A=' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; object-src 'self'; frame-src 'self'; connect-src 'self'; child-src 'self'; report-uri /csp/report;",
    "disposition": "enforce",
    "blocked-uri": "inline",
    "line-number": 2,
    "column-number": 839,
    "source-file": "https://subdomain.mydomain.com/lib/jquery/3.5.1/jquery.min.js",
    "status-code": 0,
    "script-sample": ""
  }

所以违反的指令script-src-elem并不script-src像浏览器的控制台日志显示的那样。

我知道这script-src-elem是在 CSP 3 中添加的,如果该指令不存在,用户代理将查找该script-src指令,如果它们都不存在,则回退到该default-src指令。

如果我使用 nonce 添加script-src-elem 'self' 'unsafe-inline'并保持script-src原样,那么我看不到任何违规行为。

default-src 'none'; script-src 'self' 'nonce-xxxxxxxx' 'unsafe-eval';script-src-elem 'self' 'unsafe-inline'; .......

我正在使用支持 CSP 3 的 Chrome 版本 90.0.4430.93,我的问题是当用户代理不支持 CSP 3 时会发生什么?在那种情况下,它会回退到然后抛出错误,因为script-src我没有unsafe-inlinescript-src

4

1 回答 1

1

I recently upgraded jQuery from 2.1.1 to 3.5.1 and I started seeing this CSP violation in Chrome browser's console

jQuery 2.x uses 'unsafe-eval' to execute all scripts when use strict is omitted. This technique unintentionally does bypass the 'nonce-value'.
jQuery 3.x doesn't do that, therefore:

  • you do not need to have 'unsafe-eval'unless you do not use eval-expressions on your own.
  • you have to use 'nonce-value' to allow inline scripts. You gave a link that jQuery 3.x had an issue with 'nonce-value', and it was fixed since JQuery 3.1.1.

My question is what happens when user agent is not supporting CSP 3? In that case will it fallback to script-src and then throws error because I don't have unsafe-inline for script-src.

The script-src-elem is supported by Chrome only. Other browsers support 'script-src' only.
So Chrome browser will use the policy:

  • script-src-elem 'self' 'unsafe-inline' for <script> and <script src=> tags
  • script-src 'self' 'nonce-xxxxxxxx' 'unsafe-eval' for inline event handlers and javascript-navigation (since script-src-attr is omitted).

The Firefox/Edge/Safari will use the policy: script-src 'self' 'nonce-xxxxxxxx' 'unsafe-eval'.

于 2021-05-06T04:31:57.710 回答