Content Security Policy (CSP) - Cloudflare generated nonce


I realise that a content security policy (CSP) nonce can be generated by the origin server and passed through via Cloudflare. The only issue with this approach is that caching needs to be disabled and all requests then route to the origin server. This increases load on the origin server and slows down responses to the end user. I would prefer to have caching.

My suggestion would be for the origin server to send a nonce stub in the response headers and for Cloudflare to dynamically populate it, e.g. the origin server would send something like “...script src {CF_CSP_nonce} ...” in the CSP header as well as setting it the html body where the script is used, e.g. <script nonce="{CF_CSP_nonce}" src="abc.js"></script>. Cloudflare would then dynamically populate it with each request.

The Cloudflare “cf-ray” response header could easily achieve the same effect as the nonce if there was some way to inject it into the html.

What do you think ?


I don’t think that would serve the intended purpose of the CSP. Some hacker would just add CF_CSP_nonce to their injected script, and Cloudflare would happily update the CSP and the browser will accept the script.


… but surely this hacker would need to inject it upstream of Cloudflare for the substitution to take place which depending on your topology (eg. origin certs etc) shouldn’t be possible. Or at least, if a hacker is intercepting your traffic during this leg they’ve probably compromised your server or infrastructure itself so you’re buggered in any case.


I don’t think the hacker could do that as the nonce would be unique per response and set by Cloudflare before getting to the end user (or hacker). Unless the hacker had control over Cloudflare, he/she has no opportunity to inject. It is akin to trying to predict the CF-RAY response header


Could probably use the new Cloudflare Worker functionality for this. Sign up for the beta and see how you go.


Will check that out Saul, thank you.


I always thought one benefit of CSP is to prevent someone from exploiting a weakness in a site to inject unwanted resources. So if a user manages to add HTML code to, say, a comment on a blog, CSP would prevent that resource from loading on a browser.


That’s true sdayman, but my question is around reducing origin load while generating unique nones per request. Needs to be done at Cloudflare. Doing it at the origin server is easy but not desirable because of load, speed and lack of caching. Saul’s suggestion re Cloudflare Workers looks like it may work. I am not concerned about users/hackers trying to inject via comments, etc … if I could not sanitize that, I would have bigger problems :slight_smile:

FYI, the preferred method in CSP 3 is “strict-dynamic” scripts via nonces - no more whitelists … but causes cachability issues.