CSP header woes: generating hashes for scripts

After pushing Hugo version of my site live, I expected a handful of issues mostly surrounding URLs changing (ditching the .html extension). I’d completely forgot about my security settings, and came upon a lovely CSP warning immediately after:

Content Security Policy: The page’s settings blocked the loading of a resource at inline (“script-src”).

Awesome, at least I know what that one is - I include hashes of the inline script (just a short stub that fires timeago.js), and when I switched my theme around I changed the whitespace, which will have invalidated the hash I bundle in. Problem is, I generated these headers so fucking long ago, and if I did document how it was done I sure didn’t put them in a place that’s easy to find.

So it turns out generating them isn’t super hard. Here’s the offending script:

		    jQuery(document).ready(function() {

It’s (probably) important that there’s a newline at the start, and then some tabs and no newline at the end - not sure if either of those things will come through on my site’s formatting though.

So I just copy+paste that, verbatim (as in, exactly what’s between the opening and closing script tags, whitespace and all) into a text file, and per SRI hash instructions, generate the hash like so (I’ve slightly modified the one-liner:)

echo -n 'sha384-'; (openssl dgst -sha384 -binary /path/to/script.js | openssl base64 -A); echo

The resulting has is stuffed into the CSP header:

script-src 'self' 'sha384-XC2Oe5F/T4ZBZrVZ/lb529X77T7ZPuJtaH+i+uz3+GVRCQCqPEMT7UFDsCNwm0JD'

I also put it into the integrity attribute of the script tag, though I’m not actually sure if that’s required (I can’t see how it would help, but it was like that the first time I did it so I’ve left it).

After flushing the cache on my site, the tiny bit of jQuery I use is working again.

Horsham, VIC, Australia fwaggle



Filed under:


Horsham, VIC, Australia

Navigation: Older Entry Newer Entry