A while ago I wrote a post on HTTP Security Headers and part of that invloved setting up a content security policy (CSP) and in that I say
I've done a SHA-256 hash of the script
and I just left it at that, simple right? Only now a it's little over a year later, I've changed my piwik domain and I need to change my inline script only I can't remember how I calculated the sum.
For those who have already have a CSP I'd recomend;
- Open Chrome
- Hit F12 to get the console
- Load your page
- Find the error message which helpfully contains exactly what you need to add to your CSP
So in my case chrome provided me with:
Either the 'unsafe-inline' keyword, a hash ('sha256-j69kMLNHErwf2Xyju05S+HrqhF6iQdmyWjxO2peCm10='), or a nonce ('nonce-...') is required to enable inline execution.
(emphasis mine)
Of course that's fine if you are ok with temporarily breaking your script but what if you want to calculate it before putting it on you your site?
My new inline script is:
<!-- Piwik -->
<script type="text/javascript">
var _paq = _paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//piwik.xo.tc/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', 2]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><p><img src="//piwik.xo.tc/piwik.php?idsite=2" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
Now we don't include the <script> tags but white space is significant so in my case I needed a line break (blank line) at the start because there is a linebreak just after the opeing <script> tag but I didn't need a blank line at the end. I saved a text file with the script in it and ran
openssl dgst -sha256 -binary piwik_script.txt | openssl enc -base64
which is based on the example from the W3C recommendation about CSPs.