Would it be possible to add a nonce option to Gatsby as a whole or to plugins such as Google Analytics individually? This could possibly help issue #3427 & allow people to use Content Security Policies with inline scripts protected.
If this is something that makes sense, I would be happy to try & create some pull requests.
I tried it here: https://github.com/zionis137/gatsby/commit/3c260c62ca0706294cf52ed975edace4753bfc72
Works suprisingly well for scripts, one would need to add a (different) nonce for inline-styles (here).
As I don't have much time this week feel free to take it and make a PR.
I misunderstood how nonce works. It needs to be generated by the server on each http request. This may not be the best approach upon re-thinking this problem. I'm going to close this and try to come up with a better solution.
sure, nonce = "number used once"
For static sites nonce might even work.... An attacker knows the nonce, but I don't think he can inject new content on the server without running gatsby build which changes the nonce.
Hashes are the better alternative https://github.com/gatsbyjs/gatsby/issues/3427.
The static-entry.js is called in one of the latest build-stages, every plugin that wants to inject js-code should have done so before that...
Using nonce for CSP requires a server to generate the nonce for _every request_.
From: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src
It is critical to provide an unguessable nonce, as bypassing a resource鈥檚 policy is otherwise trivial.
Also, code can be injected without needing to touch the server. XSS attack as follows
This attack and others can be completely mitigated with a good CSP. I'd recommend starting with
Content-Security-Policy: default-src 'self'; form-action 'self';
and the relaxing the policy from the as needed.
The SHA approach is definitely better.
For anyone stumbling across this now closed issue... I'd go a step further and advocate defaulting to Content-Security-Policy: default-src 'none'; and relaxing from there as per your requirements. For example there's no reason for most sites to allow object-src at all, even from same-origin. So just blocking it outright is a sensible default.
A good article worth checking out (a fews years old now, but still very valid): https://github.blog/2016-04-12-githubs-csp-journey/
We still need a solution to this since Google Tag Manager and Analytics otherwise require 'unsafe-inline'
Most helpful comment
For anyone stumbling across this now closed issue... I'd go a step further and advocate defaulting to
Content-Security-Policy: default-src 'none';and relaxing from there as per your requirements. For example there's no reason for most sites to allowobject-srcat all, even from same-origin. So just blocking it outright is a sensible default.A good article worth checking out (a fews years old now, but still very valid): https://github.blog/2016-04-12-githubs-csp-journey/