TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › Content Security Policy with Nonces

Content Security Policy with Nonces

Output encoding is the real fix for cross-site scripting, but one missed spot in a large application is enough for an attacker. Content Security Policy (CSP) is the second line: the page tells the browser which scripts it is allowed to run, and the browser refuses everything else, so an injected <script> or onerror= handler doesn't execute even when the HTML injection succeeded. A good CSP turns many XSS bugs from "account takeover" into "a broken-looking page and a violation report". A bad one, full of 'unsafe-inline' and wide host lists, does nothing. This lesson writes a nonce-based policy and watches it block an injection inside a sandboxed frame.

Definitions (CSP Level 3, W3C)

  • Policy: sent as the Content-Security-Policy response header (or, with fewer features, a <meta http-equiv> tag), a list of directives such as script-src, style-src, img-src, connect-src, object-src, base-uri, frame-ancestors, form-action, default-src (the fallback).
  • Source expressions: 'self', host names (https://cdn.lab.test), 'none', 'nonce-<value>', 'sha256-<hash>', 'strict-dynamic', and the dangerous 'unsafe-inline' and 'unsafe-eval'.
  • Nonce: a fresh random value per response, put both in the header ('nonce-…') and on each legitimate <script nonce="…">. An attacker who injects markup can't know this response's nonce, so their script is refused.
  • 'strict-dynamic': scripts loaded by an already-trusted (nonced) script are trusted too, and host allow-lists are ignored. It makes nonces practical with loaders and bundlers.
  • Report-only: Content-Security-Policy-Report-Only reports violations (to report-to/report-uri endpoints) without blocking: the way to roll a policy out.

A policy blocking an injection

The frame below declares this policy in a <meta> tag (a real site would send it as a header, with a new nonce per response; the nonce here is fixed so the example is readable):

text
script-src 'nonce-lab4Xq9' 'strict-dynamic'; object-src 'none'; base-uri 'none'

It then simulates a page that places an untrusted "comment" into the DOM with innerHTML, which is an HTML injection bug. The comment carries two classic payloads. A listener for securitypolicyviolation events prints what the browser refused.

html · try it yourself
<!doctype html>
<meta http-equiv="Content-Security-Policy" content="script-src 'nonce-lab4Xq9' 'strict-dynamic'; object-src 'none'; base-uri 'none'">
<style>body{font:14px system-ui;margin:8px} .c{border:1px solid #999;padding:6px} pre{background:#8881;padding:6px}</style>
<p>Latest comment:</p>
<div class="c" id="comment"></div>
<pre id="log"></pre>
<script nonce="lab4Xq9">
  const log = (s) => { document.getElementById('log').textContent += s + '\n'; };
  document.addEventListener('securitypolicyviolation', (e) =>
    log(`CSP blocked: ${e.effectiveDirective} (${e.blockedURI || 'inline'})`));
  log('nonced script: running');

  // The bug: untrusted text written with innerHTML.
  const untrusted = 'Nice post! <img src="x" onerror="document.title=\'pwned\'; log(\'handler ran\')">';
  document.getElementById('comment').innerHTML = untrusted;

  // A script element created by trusted code: allowed by 'strict-dynamic'.
  const s = document.createElement('script');
  s.textContent = "log('script created by nonced code: running')";
  document.body.append(s);

  // A script element injected as markup into the page: no nonce, refused.
  document.getElementById('comment').insertAdjacentHTML('beforeend', '<script>log("injected script ran")<\/script>');
  setTimeout(() => log('document.title is still: "' + document.title + '"'), 300);
</script>

You should see the nonced script and the script it created run, a violation for the inline onerror handler (script-src-attr), and a title that never became pwned. The insertAdjacentHTML script produces no line at all: HTML parsed by innerHTML-style sinks never executes <script> elements, with or without CSP, which is why real payloads use event handlers like onerror and why CSP must cover those. The HTML injection still happened (the broken image is visible), so CSP is a seatbelt, not a fix: the XSS defences lesson fixes the sink itself.

Strict versus allow-list policies

Policy Verdict
script-src 'self' https://cdn.lab.test 'unsafe-inline' blocks nothing useful: 'unsafe-inline' lets every injected handler run
script-src 'self' https://cdnjs.cloudflare.com bypassable if that CDN hosts any library with a "gadget" (old AngularJS, JSONP endpoints)
script-src 'nonce-{random}' 'strict-dynamic'; object-src 'none'; base-uri 'none' the "strict CSP" recommended by Google's web.dev guidance and OWASP's CSP cheat sheet; host lists unnecessary
script-src 'sha256-…' for static pages whose inline scripts never change

Add frame-ancestors 'none' (or 'self') for clickjacking, which the next lesson covers, and consider require-trusted-types-for 'script'.

Computing a hash source

For a static inline script, a hash avoids per-response nonces. The value is the Base64 of the SHA-256 of the script's exact text, whitespace included:

python · try it yourself
import base64, hashlib

script = "console.log('static widget loaded')"
digest = hashlib.sha256(script.encode()).digest()
print(f"script-src 'sha256-{base64.b64encode(digest).decode()}'")
print("one space more:", base64.b64encode(hashlib.sha256((script + " ").encode()).digest()).decode()[:16] + "...")
script-src 'sha256-cvYZ4mb6HlxyWtF/8gGso+SJbf7ctqDvHAI1eZFBbtU='
one space more: 4llNUzFdCSHF99sl...

One extra space gives a completely different hash, so hash sources break whenever a build tool reformats the script; nonces don't.

How CSP weaknesses are detected

  • Header review: look for 'unsafe-inline' in script-src, 'unsafe-eval', * or https: as a source, missing object-src and base-uri, and nonces that repeat between responses (load the page twice and compare). Google's CSP Evaluator and the ZAP and Burp passive checks automate this.
  • Violation reports: a report-to endpoint receives JSON reports. A burst of script-src-attr or script-src-elem violations from one page often means someone is probing an injection, and is an early XSS warning.
  • DevTools console prints every blocked resource (Chrome: Executing inline event handler violates the following Content Security Policy directive…).

How to deploy it

  1. Generate a nonce per response with a CSPRNG (secrets.token_urlsafe(16)), put it in the header and on every legitimate <script>; never cache pages that contain it.
  2. Move inline event handlers (onclick=) into scripts with addEventListener.
  3. Ship it as Content-Security-Policy-Report-Only first, read the reports, fix the page, then enforce.
  4. Keep object-src 'none' and base-uri 'none'; a <base href> injection would otherwise redirect every relative script URL.

Pitfalls

  • A static nonce (hard-coded in a template) is no better than 'unsafe-inline': the attacker reads it from any response.
  • Reflecting the nonce from the request or putting it in the URL.
  • <meta> policies can't use frame-ancestors, report-uri or sandbox, and only apply to content after the tag; prefer headers.
  • JSONP and old frameworks on allow-listed hosts let attackers run code through "trusted" URLs.

Practice

1. A site sends script-src 'self' 'unsafe-inline' 'nonce-abc'. Does the nonce help?

In CSP Level 2+ browsers, a nonce or hash in the directive makes them ignore 'unsafe-inline', so the nonce does take effect there; 'unsafe-inline' remains only as a fallback for very old browsers. But the nonce abc is static, so attackers can include it: generate it per response.

2. In the demo, why didn't the insertAdjacentHTML script need CSP to be blocked?

Script elements inserted through innerHTML/insertAdjacentHTML are marked as "already started" by the HTML parser and never run. Event handler attributes on inserted elements do run, which is what CSP stopped.

Test yourself

Why can't an attacker's injected script use the page's nonce?

  1. Nonces are encrypted
  2. The nonce is random and new on every response, so the attacker can't know it when crafting the payload
  3. Browsers strip nonces from injected scripts
  4. Nonces only work over HTTP/2

Which source expression makes a script-src policy nearly useless against XSS?

  1. 'self'
  2. 'nonce-…'
  3. 'unsafe-inline' (without a nonce or hash)
  4. 'strict-dynamic'

In the demo, what did the CSP block?

  1. The nonced script
  2. The script created by the nonced script
  3. The inline onerror handler from the untrusted comment
  4. The image request

How should a new CSP be rolled out on a large site?

  1. Enforce immediately
  2. As Content-Security-Policy-Report-Only, then fix the reported violations, then enforce
  3. Only in development
  4. With 'unsafe-eval' first