大网数据广告活动
网站运营与故障问答

Cannot get Content-Security-Policy to work

· 52CE 我爱测

I'm trying to implement CSP, but cannot make the script-src work correctly. I strongly want to avoid unsafe-inline , but all attempts to circumvent this by using sha256 hashes seem to fail. This is what happens: Several <a> tags …

问题原文

原帖链接 · Hagen von Eitzen · CC BY-SA 3.0

I'm trying to implement CSP, but cannot make the script-src work correctly. I strongly want to avoid unsafe-inline, but all attempts to circumvent this by using sha256 hashes seem to fail.

This is what happens: Several <a>tags on the page are being modified by javascript after loading (the modifying javascript is an external file from selfand is accepted and correctly executed). This javascript does the following to such an <a> tag:

MyAElement.href="javascript:void(0);";
MyAElement.onclick=function(){showpart(this);}
MyAElement.onfocus=function(){showpart(this);}

(where showpart is defined in the aforementioend external javascript file). When I click on such a modified link, I get a CSP violation report. What confuses me slightly is that even if I temporarily use Content-Securtity-Policy: and not just Content-Securtity-Policy-Report-Only:, the website seems to function alright. I conclude that it is in fact the javascript:void(0); that triggers the error.

It should be possible to get rid of the error by supplying a suitable hash. I tried both

#echo -n "javascript:void(0);" | openssl dgst -binary -sha256 | base64

and

#echo -n "void(0);" | openssl dgst -binary -sha256 | base64

but without success (i.e. even with script-src containing

'sha256-kbHtQyYDQKz4SWMQ8OHVol3EC0t3tHEJFPCSwNG9NxQ=' 
'sha256-Deekn20h+++EarpL0nFQLX7JSJv7s/2W9f988ZFAh14='

) the message still occurs.

What am I doing wrong?

已采纳解答

原帖链接 · oreoshake · CC BY-SA 3.0

Sorry, javascript: hrefs are not supported by csp hashes or nonces. I don't think they will ever be supported either. I used to actively participate in the w3c webappsec where csp and hashes were defined and I seem to recall this coming up and the group simply saying that javascript: hrefs need to go away. I could also be misremembering with a bias to my own feelings towards that pattern :)

If you want to avoid the violation, I think you could bind the click event and prevent propagation of the event.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2016-05-04)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。