VibeSecurity

Web attacks

What is CSP nonce?

A CSP nonce is a random value, generated fresh for every page response, that appears both in the Content-Security-Policy header and on each script tag you trust. The browser runs only the inline scripts that carry the matching value.

A Content Security Policy is most useful when it blocks inline scripts, because injected inline script is how most cross-site scripting attacks run. The trouble is that real apps and frameworks also use inline scripts. Many people give up and add the unsafe-inline keyword, which switches that protection off.

A nonce solves this. Your server creates an unpredictable random value for each response, puts it in the header as 'nonce-VALUE', and adds the same value as a nonce attribute on the script tags it generated. An attacker who injects a script tag cannot know the value for that response, so the browser refuses to run their script.

The protection depends on the value being unguessable and used once. A fixed nonce written into a config file, or a page cached with its nonce and served to everyone, gives no protection because the value can simply be read and reused. This means nonces need server rendering per request. Fully static pages should use script hashes instead.

The same per-response value in the header and the tag
Content-Security-Policy: script-src 'nonce-R4nd0mV4lu3' 'strict-dynamic'

<script nonce="R4nd0mV4lu3" src="/app.js"></script>

Related terms

Sources

  1. 1.MDN: nonce global attribute
  2. 2.MDN: Content Security Policy guide
  3. 3.OWASP Content Security Policy Cheat Sheet