CSP with Kirby - how to best generate a nonce?

Going over our site’s CSP settings I asked myself what the recommended way is to generate and use a Content Security Policy (CSP) nonce (for inline scripts) using kirby?

The “headers” option from the cheatsheet sounds interesting as a starting point for defining the CSP configuration (instead of e.g. .htaccess) - and could certainly also be used to generate a CSP nonce. But I am not clear how to use or access such value later on when traversing the templates and snippets.

Additionally, the nonce should of course be unique for each web server request and independent from “external data” that could otherwise be guessed…

Thoughts and suggestions highly welcome…

Peter

You can see an example use of the header option in the config file of the getkirby.com website:
https://github.com/getkirby/getkirby.com/blob/master/site/config/config.getkirby.com.php. While this doesn’t make use of nonce, it might be a starting point.

That’s exactly the article that I had in mind when I wrote the message above. Yet, that’s probably the easy part.

Any idea on how to best pass around a HTTP request specific “variable” during HTML generation (without passing it around to templates and snippets as an argument/parameter)? I hope there’s a smarter choice than a global variable… any idea on what “hook” to link in to?

The easiest way to pass around a variable would be via the c::set() and c::get() methods. Suppose you generate a secure unique random string for each request, set it in the config, and then pass it around via c::get.

If anyone finds this conversation and wants to know how to do it, here’s my solution, with thanks to @texnixe :

The nonce is generated with PHP random_bytes() function, so it might not be the most secure solution. But at least it’s unique, regenerated for each page load, non trivial and not so easily guessable.

Let me know if it works for you !