我正在尝试实施内容安全策略,以便为每个内联事件脚本使用sha-256
哈希启用Chrome扩展中的内联处理程序执行。
但是我不能让它工作:我提取了所有的内联和计算的哈希值,所以我的content_security_policy
现在看起来像这样:
"content_security_policy": "script-src 'self' 'unsafe-eval' 'sha256-Zy8+Ft7FDcIkrTYgl2BKmEW5XD97XustxKPceyLSioQ=' 'sha256-YNkUpNj1B2/FuE2RmwQf40OIO5rH69xQbG5AAxwshrA=' 'sha256-Pmun4RTarna683hWYftYdXPERPfEVV5fB+qvqh3xnmg=' ... ... 'sha256-RoSxVuvjYKDbU5f+aUEw02rEM9e2Lp9Hz/+rxbp6OMw='; object-src 'self'"
例如,对于onclick="w2ui['grid'].click('1', event);"
,我得到sha256-Zy8+Ft7FDcIkrTYgl2BKmEW5XD97XustxKPceyLSioQ=
The docs state这是一种受支持的方法,但它仍然会抛出错误
Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval' 'sha256-Zy8+Ft7FDcIkrTYgl2BKmEW5XD97XustxKPceyLSioQ=' 'sha256-YNkUpNj1B2/FuE2RmwQf40OIO5rH69xQbG5AAxwshrA=' 'sha256-Pmun4RTarna683hWYftYdXPERPfEVV5fB+qvqh3xnmg=' ... ... Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
这是一个已知的错误还是我只是在滥用这个概念?
答案 0 :(得分:0)
这里的答案似乎是铬 - 出于某种原因 - 根本不支持内联事件散列;我能够通过使用'unsafe-eval'
权限预先评估所有内联来解决这个问题:
var events = ["onclick", "onmouseover", "onmouseout", "onmousedown",
"onmouseup", "onscroll", "oncontextmenu", "onmousewheel", "ondblclick"];
function vulcanize_inlines() {
for(var i=0;i<events.length;i++) {
var els = getAllElementsWithAttribute(events[i]);
for(var j=0;j<els.length;j++) {
var fun = eval("(function a(){"+els[j].getAttribute(events[i])+"})");
els[j].removeAttribute(events[i]);
els[j][events[i]] = fun;
}
}
}
并将其添加到.onload
:
vulcanize_inlines();
var target = document.body;
var observer = new MutationObserver(function(mutations) {
vulcanize_inlines();
});
var config = { /*attributes: true,*/ childList: true,
characterData: true, subtree: true };
observer.observe(target, config);
getAllElementsWithAttribute
我使用this answer