Is it a good idea to use nginx $request_id for CSP nonce value?

Solution 1:

If you compile nginx with the NGX_OPENSSL flag, $request_id value will be sufficient for a CSP nonce because it's a 128-bit cryptographically strong random number returned by OpenSSL's RAND_bytes(). Otherwise, the value will be pseudo-random which means that an attacker who deduces the state of your server's PRNG may be able to forge the correct request_id / CSP nonce in their XSS payload. In practice, I wouldn't worry about this too much because the attack is not straightforward and would require sending a lot of traffic to the server, but it's worth keeping this in mind.

One thing to watch out for is making sure that the request_id value isn't used for anything else that might be sensitive in your application, because you will be exposing it to the user in the source of the HTML page.