Content-Security-Policy: default-src *

Content-Security-Policy: default-src *

我开始在一个使用内联脚本和其他犯罪的网站上探索内容安全策略。我为每个 header 字段配置了 CSP,如下所示:

content-security-policy: default-src *; frame-ancestors 'self'; style-src 'self' 'unsafe-inline' fonts.googleapis.com cdn.jsdelivr.net *.stripe.com; report-uri https://sentry.io/api/x/csp-report/?sentry_key=y

我现在的问题是浏览器抱怨以下消息:

Refused to execute inline script because it violates the following Content Security Policy directive: "default-src *"

我阅读了 default-src <source> 的文档,其中指出 <source> 可以是以下来源之一:

在我看来,星号只能用于主机来源。但是我还能做什么,因为似乎只允许一个 <source>default-src * 'unsafe-inline' 不合规,对吧?

我的目标基本上是使用有效的最小 CSP 配置(并且可以通过 iframe 嵌入)。我知道继续执行特定规则是最佳做法。

It seems to me that the asterisk can only be used for host sources.

But what else can I do since only one <source> seems to be allowed?

允许多个 <source>

default-src * 'unsafe-inline' would not be compliant, right?

合规。

您可以使用 https://cspvalidator.org/ to check. Or https://csp-evaluator.withgoogle.com/.

但您确实希望避免在任何 CSP 策略中指定 'unsafe-inline'。使用 'unsafe-inline' 几乎违背了 CSP 的全部目的。

对于任何导致 CSP 错误的内联脚本,您想要做的是:将脚本从您的文档中取出并将它们移动到单独的文件中。这就是重点。

但如果您真的必须指定 'unsafe-inline',那么就处理问题中引用的特定错误而言,您应该只为 script-src 指定 'unsafe-inline' — 因为错误消息说,“拒绝执行内联 script。”

如果您为 default-src 指定 'unsafe-inline',则会导致浏览器无法对文档中的 any 内联资源进行 CSP 检查 —样式表等,不仅仅是脚本。

因此,如果唯一的问题是内联脚本并且由于某种原因您无法通过将脚本移出到单独的文件或为其指定哈希或随机数来解决该问题,那么您至少应该仅指定'unsafe-inline' 对于 script-src.