问题
I am in the process of adding CSP headers to a site that has a long way to go before it can adopt a strict policy. There are quite a few inline scripts, so I am using nonce- to allow specific inline scripts. I have found that it doesn't work on the onload
attribute of a script tag with src. Here's an example:
// header:
Content-Security-Policy: script-src self https: 'nonce-d3adbe3fed'
<script async defer src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" nonce="d3adbe3fed" onload="console.log('onload', _.VERSION)"></script>
Full working demo at https://brave-pasteur-0d438b.netlify.com/
Chrome gives the following error:
Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src self https: 'nonce-d3adbe3fed'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
The message suggests that it should be possible to enable inline event handlers with a nonce, but as far I as I can tell, nonce is only intended to work on inline scripts.
This is just a demo, but the use case is an async/deferred tracking script which loads the tracking library, then in the onload
handler makes a tracking call to the loaded library.
Is it possible to use a nonce on an onload
or other event handler attribute, or will I need to change my implementation? Using script-src 'unsafe-inline'
or script-src-attr 'unsafe-inline'
is not an option, as those are the vulnerabilities I am specifically trying to address. And putting the contents of the onload
handler into a separate script following the script tag is also not an option because the script is async deferred
, and needs to stay that way.
回答1:
If there is a way to use nonce
on an inline handler, I will accept an answer that demonstrates it. Unfortunately, at the time of writing, I don't think there is.
As a workaround, the following script exhibits the same behavior and timing as an script with async/defer and an onload handler, while satisfying the specified CSP policy:
<script nonce="d3adbe3fed">
let s = document.createElement('script');
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js';
s.onload = () => console.log(_.VERSION);
document.documentElement.appendChild(s);
</script>
Of course, the long term solution is to eliminate inline scripts completely, but in the short term that isn't always feasible, and it is better to implement a more lax policy quickly, than to put it off and have no CSP at all.
来源:https://stackoverflow.com/questions/56399872/content-security-policy-nonce-does-not-apply-to-event-handler-attributes