我将我的 React 应用程序与 Webpack 捆绑在一起并添加 Content Security Policy (CSP) header (特别是不允许 script-src
中的 unsafe-eval
)。当然,我确保我的最终包和 block 不包含 eval()
。然而,最新的 Firefox-dev 63.0b10 仍然拒绝加载主 block 并出现以下错误:
Content Security Policy: The page’s settings blocked the loading of a resource at self (“script-src”). Source: call to eval() or related function blocked by CSP.
好吧,但我的包中没有 eval()
。
这些“相关功能”可能是什么?
附言这是 self-answered question ,但可以随意扩展
最佳答案
Mozilla docs on CSP , 将“eval()
和类似方法”列为可能的违规者:
[…]
'unsafe-eval'
Allows the use ofeval()
and similar methods for creating code from strings. […]
CSP3 specification § 1.2.1 , 提到“eval()
和类似的构造”:
Mitigate the risk of content-injection attacks by giving developers fairly granular control over […] Dynamic code execution (via
eval()
and similar constructs) […]
但最终答案在 CSP3 规范中,在 § 6.1.10.4 中:
The following JavaScript execution sinks are gated on the "
unsafe-eval
" source expression:
eval()
Function()
setTimeout()
with an initial argument which is not callable.setInterval()
with an initial argument which is not callable.Note: If a user agent implements non-standard sinks like
setImmediate()
orexecScript()
, they SHOULD also be gated on "unsafe-eval
".
因此,对于 CSP 而言,“动态代码执行构造”、eval()
的“类似方法”、“相关函数”、“类似构造”的完整列表是:
eval()
Function() // typically new Function()
setTimeout() // with non-callable argument
setInterval() // with non-callable argument
setImmediate()
execScript()
就我而言,我在 bundle 中发现了一些 new Function(...)
片段,现在想知道如何防止它们出现。
奖金
如果你取grepl
或类似 grep
的类似工具,它可以逐个字符地查找字符串匹配项并打印周围的上下文(而不是像正常的 grep
那样逐行打印)你可以使用以下命令在捆绑(缩小和代码拆分)应用程序的所有文件中查找“动态代码执行结构”:
find "<build_dir>" -type f -iname "*.js" -exec grepl -k 512 -H "(eval|Function)(\s|\t)*\(" '{}' \;
或者,您可以关闭 JS 压缩器(例如 UglifyJS)并使用正常的 grep
检查您的构建。
关于javascript - 启用 CSP 时应避免哪些与 eval() 相关的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52573756/