Generate a nonce with Apache 2.4 (for a Content Security Policy header)

Viewed 9772

We're working on creating a strict Content Security Policy (https://csp.withgoogle.com/docs/strict-csp.html) which necessitates Apache creating a nonce each time a resource is requested, so that we can insert this nonce into the http header.

How can we create a nonce with Apache 2.4?

All of the CSP related documentation I've read says something to the effect of "A nonce is just a random string that's generated on the server, included in the CSP header..." but haven't found any info on how to do this with Apache. We could of course do this with app code, but doing it via Apache seems like a cleaner solution/will ensure every single page gets the CSP header.

4 Answers

You need to generate the nonce on the server, and then have Apache pass that nonce to your script where it can be used.

We've created an open source module for Apache that simplifies this process: mod_cspnonce.

Here's a simple example of the server-side config:

LoadModule headers_module modules/mod_headers.so
LoadModule cspnonce_module modules/mod_cspnonce.so

# add the CSP_NONCE to the "default-src"
Header add Content-Security-Policy "default-src 'self' 'nonce-%{CSP_NONCE}e';"

Here's a simple example of using the nonce in your script:

<script nonce="<?= $_SERVER['CSP_NONCE'] ?>">
  var inline = 1;
</script>

That example is php, but you can use any language.

Related