Content Security Policy problem with Cloudflare

Viewed 1101

Info in advance:
I use Netlify and therefore also the netlify.toml file given by Netlify to clear things like CSP or HSTS.
Also, I am using Cloudflare.

The problem:
Cloudflare's JavaScript Detection service injects code into my website. However, since my Content Security Policy is not adjusted accordingly, the following error occurs:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' ..."
The whole error message is on the website.

The current CSP:
I have tried to adjust my CSP / script-src accordingly. Here is my approach:
script-src 'self' ajax.cloudflare.com cdnjs.cloudflare.com static.cloudflareinsights.com;
The default-src is set to none.

Any help is appreciated. I haven't tried setting the CSP in the HTML script yet.

2 Answers

So, it is not the linked Javascript files that are failing the CSP, it is the inline javascript (directly after rocket loader js file). Looking at the error message being generated, it actually gives some info about what would allow the CSP to pass -

Either the 'unsafe-inline' keyword, a hash ('sha256-DHoAlYi+jbDdRYheBA8zRtbuAh9tH4/dMM2Krte5NJM='), or a nonce ('nonce-...') is required to enable inline execution.

It looks like Cloudflare supports using the "nonce" method -

If your CSP uses a nonce for script tags, Cloudflare will add these nonces to the scripts it injects by parsing your CSP response header.

More info here - https://content-security-policy.com/nonce/

Cloudflare's JavaScript Detection service is a very bad feature. Switch it off if you can, because CSP is intended to block such script injection made by ISP. Since injected script does not sent response to Cloudflare, the Cloudflare treat browser as a bot with no JS execution.

Netlify is a static file hosting therefore you have no chance to allow inline scripts with 'nonce-value', only 'hash-value' can be used. But you have no control over injected inline script so any change of code leads to blocking it.
Or just ignore this CSP violation, it does not lead to a disruption of the functioning of the site.

There is no beautiful solution to your problem, you only can raise a issue in Cloudflare and ask them to migrate this inline script to the external script and whitelist it.

Note: This is not the only problem when proxying traffic through Cloudflare, but any time you can stop using Cloudflare as proxy and use it as DNS server only. Just press the bypass button.

Related