如何为 style-src-attr 或 script-src-attr 定义 nonce?

How to define nonce for style-src-attr or script-src-attr?

我正在尝试使用内容安全策略 (CSP) 来锁定我的页面。默认的 CSP 限制太多(我无法更改代码以使其兼容,因为它来自第三方),因此我试图在 CSP 中定义最小权限集。为此,我想使用 style-src-attr 和 script-src-attr。我想将这些与随机数一起使用。我可以看到如何在 CSP 中为这两个指定随机数。我不确定的是如何为 html 元素(在 style-src-attr 的情况下)和 javascript 对象(在 script-src-attr 的情况下)指定随机数).我找了一个例子,但找不到任何东西。请举例说明如何做到这一点。

我在实际准备有关该主题的讲座时偶然发现了这个问题。问题的答案是:你不能。

查看 CSP 规范 (https://www.w3.org/TR/CSP3/#match-element-to-source-list), only script or style tags can be nonced. The -attr variants do not apply to stand-alone elements (script tags, style tags, or links to CSS files), as per the spec (https://w3c.github.io/webappsec-csp/#directive-script-src-attr)

The script-src-attr directive applies to event handlers and, if present, it will override the script-src directive for relevant checks.

最重要的是,在当前规范中,不允许事件处理程序通过随机数。可以依赖 unsafe-hashes 并将已知事件处理程序的哈希值放在那里,但浏览器甚至不完全支持(FF 和 Safari 缺乏支持,参见 https://caniuse.com/mdn-http_headers_csp_content-security-policy_unsafe-hashes