How to inject random CSP nonce in APACHE?

I want to add the following CSP directive in APACHE because I want it to be applied on every page.

<IfModule mod_headers.c>
    <FilesMatch "\.(htm|html|php)$">
        Content-Security-Policy: script-src 'strict-dynamic' 'nonce-{random}' 'unsafe-inline' ' https:;
    </FilesMatch>
</IfModule>

I'd like to generate the {random} value directly in APACHE as well (if possible).

Is it possible to generate and insert it directly in the APACHE CSP directive? Or is this a bad idea, should I be generate and insert at the application layer instead (PHP)?

NOTE: I did find this which Generate a nonce with Apache 2.4 (for a Content Security Policy header) looked promising but I'm not sure if the $_SERVER[UNIQUE_ID] is actually a random enough value.


Solution 1:

The nonce you set up in your CSP header has to be the same you use with your script tag. That's why it is typically set at the application level, where the save value can be used in the HTTP header and in your HTML. If you set it at the Apache level, how do you use it in your application?

Solution 2:

@user3526609 gets credit for this wonderful solution, but I wanted to summarize it to make it clear for any others out there like me who hunted everywhere for this and found it buried in a comment.

In short, this is how to create a CSP nonce in an .htaccess file rather than in a web application, but still be able to utilize it in the web application.

You can “generate” a nonce with Apache by reusing the Unique ID it creates for every request. Create the Content Security Policy header as follows (lots of other important bits excluded for brevity):

Header always set Content-Security-Policy "\
  default-src 'self'; \
  script-src 'self' 'nonce-%{UNIQUE_ID}e';"

Note that the backslash breaks a command into nicely readable lines which will be removed by Apache later.

This creates something like the following:

'nonce-STRINGofRANDOMcharacters'

And PHP can access it as follows:

$_SERVER['UNIQUE_ID']

Example in a web page:

<script 
  src="https://www.google.com/recaptcha/api.js?render=your-site-key"
  nonce="nonce-<?php echo $_SERVER['UNIQUE_ID']; ?>">
</script>