动态加载所有内容时了解 connect-src、script-src 和 style-src

Understanding connect-src, script-src and style-src when everything is loaded dynamically

我对 Content Security Policy Header 可用的指令有点困惑。主要与 connect-srcscript-srcstyle-src

混淆

我有一个 javascript,它发送 FetchAjax(在同一个域上)并动态加载一个具有样式表的 link 标签。

如果我必须让我的脚本在域中列入白名单,这应该是所有 connect-srcscript-srcstyle-src 的一部分吗?我在这里有点困惑。

为了更清楚,在 https://example.com 有一个脚本,它从 https://example.com 加载、发送数据并加载位于 https://some-another-domain.com 的样式表。内容安全策略应如何反映这一点? connect-srcscript-srcstyle-src 是否应该包括这两个域?

有人可以帮忙澄清一下吗?

每个指令应仅包含它涵盖(控制)的来源。

  1. connect-src指令covers the URLs from which resources can be loaded using following script API interfaces(see the test):
  • <a ping='...'>
  • fetch()
  • XMLHttpRequest()
  • sendBeacon()
  • WebSocket()(因此只能在connect-src/default-src中指定ws:/wss:方案)
  • EventSource()

因此,如果您执行 XMLHttpRequest('https://example.com/ajax') 或使用内部调用 XMLHttpRequest() 的 jQuery $ajax('https://example.com/ajax'),您需要允许 https://example.comconnect-src:
connect-src https://example.com;
同样,如果您使用 fetch('https://google.com/api/json'),则需要将此 host-source 添加到 connect-src:
connect-src https://example.com https://google.com/api/;
以上所有 6 个 API 依此类推。

  1. script-src 指令 controls 5 件事:
  • 通过 <script src='http://example.com/script.js'></script> 加载外部脚本。为此,您需要在 script-src 中允许相关的 host-source。或者可以使用 'nonce-value'/'hash-value' 令牌。
  • 内联脚本块,如 <script>...</script>。您需要在 script-src 中使用 'unsafe-inline' 或 'nonce-value'/'hash-value' 标记以允许此类脚本。
  • eval()setTimeout()setInterval()Function()setImmediate()execScript() 函数调用在 'unsafe-eval' 源表达式。如果你使用那些你需要在 script-src 中有 'unsafe-eval'setTimeout()/setInterval() 有一些例外)。
  • 导航到 javascript-URLs 喜欢 <a href='javascript:...'>
  • 标签中的内联事件处理程序,例如 <div onblur='...'><input onclick='...'>
    * 对于最后两件事,你需要在 script-src 指令中包含 'unsafe-inline' 或使用 unsafe-hashes + 'hash-value' 标记配对(目前支持一些错误) .
  1. style-src指令covers several things(see the test):
  • 样式表请求通过 <link href='http://example.com/min/css.css' rel='stylesheet'>。在这种情况下,您需要将 http://example.com host-source 添加到 style-src 指令。
  • 来自 CSS @import url('https://example.com/style_import.css')
  • 的样式表请求
  • 来自 Link HTTP 响应 header 字段 Link: https://example.com/file.css; rel=stylesheet 的样式表请求。
  • 内联样式块:<style>...</style>。您需要在 style-src 中包含 'unsafe-inline''nonce-value'/'hash-value' 才能允许这些。
  • style= 标签中的属性:<tag style='color:green; margin:0 auto;'>。您需要在 style-src 中包含 'unsafe-inline' 才能允许这些。或者配对使用 'unsafe-hashes' + 'hash-value'(目前还没有得到广泛支持)。
    * JS调用setAttribute('style', 'display:none;')被认为是上面的<tag style='display:none;'>
  • 使用 CSSStyleSheet.insertRule()CSSGroupingRule.insertRule()CSSStyleDeclaration.cssTextCSSStyleRule.selectorText 的目的是在 style-src 中限制到 'unsafe-eval',但是还没有实现。

上述结构的任何使用(即使通过脚本调用)都需要在 styler-src 指令中允许相关来源或标记。