是否可以使用 Content-Security-Policy 来允许来自一台主机的内联脚本,但只允许来自其他主机的外部脚本?

Is it possible to use Content-Security-Policy to allow inline scripts from one host, but only external scripts from other hosts?

是否可以使用 Content-Security-Policy 允许来自一台主机的内联脚本,但只允许来自其他主机的外部脚本?

我想做这样的事情:

Header set Content-Security-Policy script-src myhost.com 'unsafe-inline'; script-src someothersite.com

但显然这是无效的。

Is it possible to use Content-Security-Policy to allow inline scripts from one host, but only external scripts from other hosts?

不,这不可能。内容安全策略(实际上是设计的)没有任何表达方式。

特别是,就 CSP 语法而言,myhost.com'unsafe-inline' 都是 CSP 规范所称的 “源表达式”,并且script-src CSP 指令的值是 CSP 规范所称的 “源列表” — 即单独的单个源表达式的列表。

并且在 CSP 源列表中,源表达式在内部彼此没有关系——相反,它们每个都适用于它们所属的整个指令。因此,如果您为 script-src 指令的值指定 'unsafe-inline',那么这始终具有全局允许文档中任何位置的内联脚本的效果,句号。

所以它的要点是:CSP 没有语法来表达 “只允许 myhost.com 的内联脚本”.


有关规格详情,请参阅 https://w3c.github.io/webappsec-csp/#framework-directive-source-list:

Many directives' values consist of source lists: sets of strings which identify content that can be fetched and potentially embedded or executed. Each string represents one of the following types of source expression:

  1. Keywords such as 'none' and 'self' (which match nothing and the current URL’s origin, respectively)

  2. Serialized URLs such as https://example.com/path/to/file.js (which matches a specific file) or https://example.com/ (which matches everything on that origin)

  3. Schemes such as https: (which matches any resource having the specified scheme)

  4. Hosts such as example.com (which matches any resource on the host, regardless of scheme) or *.example.com (which matches any resource on the host’s subdomains (and any of its subdomains' subdomains, and so on))

  5. Nonces such as 'nonce-ch4hvvbHDpv7xCSvXCs3BrNggHdTzxUA' (which can match specific elements on a page)

  6. Digests such as 'sha256-abcd...' (which can match specific elements on a page)