捕获内容安全策略 (CSP) 错误
Catching Content Security Policy (CSP) errors
我正在使用此方法检测 CSP 与 eval
(也用于 AngularJS):
function noUnsafeEval() {
try {
new Function('');
return false;
} catch (err) {
return true;
}
}
但我手边没有带有 CSP 的服务器来彻底测试它。
靠谱吗?代码中存在 new Function('')
行是否会导致无法捕获的错误?
什么是err
?那里捕获了哪种错误(Error
、TypeError
等)? CSP 错误消息是什么意思?
我找不到有关 CSP 中运行时错误的文档。
关于如何检测CSP,还有一个Whosebug问题:How to detect Content Security Policy (CSP) 也显示了你的功能。
使用它应该是安全的,因为只要代码到达函数构造函数(即它之前没有被其他限制阻塞),你总是会从noUnsafeEval.
据我所知,如果 CSP 不允许不安全的 eval,它将抛出一个 EvalError (mozilla)。但这可能因浏览器而异。
确定的最佳方法是对此进行测试。您可以使用 http://mockbin.org to create a HTTP endpoint which return a page with the right CSP headers and your function. I made such a bin here: http://mockbin.org/bin/cc6029e5-8aac-4a54-8fd1-abf41e17042a。如果你打开它,打开开发控制台并调试代码,你会看到异常:
稍后编辑
您还可以在 W3C 建议/草案中找到此信息:CSP 1.1, CSP 2, CSP 3。在 1.1 中你会得到一个 SecurityError 而不是 EvalError。
我正在使用此方法检测 CSP 与 eval
(也用于 AngularJS):
function noUnsafeEval() {
try {
new Function('');
return false;
} catch (err) {
return true;
}
}
但我手边没有带有 CSP 的服务器来彻底测试它。
靠谱吗?代码中存在 new Function('')
行是否会导致无法捕获的错误?
什么是err
?那里捕获了哪种错误(Error
、TypeError
等)? CSP 错误消息是什么意思?
我找不到有关 CSP 中运行时错误的文档。
关于如何检测CSP,还有一个Whosebug问题:How to detect Content Security Policy (CSP) 也显示了你的功能。
使用它应该是安全的,因为只要代码到达函数构造函数(即它之前没有被其他限制阻塞),你总是会从noUnsafeEval.
据我所知,如果 CSP 不允许不安全的 eval,它将抛出一个 EvalError (mozilla)。但这可能因浏览器而异。
确定的最佳方法是对此进行测试。您可以使用 http://mockbin.org to create a HTTP endpoint which return a page with the right CSP headers and your function. I made such a bin here: http://mockbin.org/bin/cc6029e5-8aac-4a54-8fd1-abf41e17042a。如果你打开它,打开开发控制台并调试代码,你会看到异常:
稍后编辑
您还可以在 W3C 建议/草案中找到此信息:CSP 1.1, CSP 2, CSP 3。在 1.1 中你会得到一个 SecurityError 而不是 EvalError。