Lesson 8 of 14 · 13m
Nonces, Hashes, and strict-dynamic
Per-response nonce plumbing through middleware, why strict-dynamic makes host allowlists optional, and report-driven rollout.
The nonce is a capability
script-src 'nonce-abc123' means: execute script elements that carry nonce="abc123" — and nothing else. The browser compares the attribute to the header value at execution time. Injected markup fails because the attacker cannot guess a random value that changes every response.
That last clause is the entire contract. A nonce must be generated fresh per response — crypto.randomBytes(16).toString('base64') at request time, inserted into both the header and every <script nonce> in the rendered document. A static nonce is worse than no nonce: the attacker reads it from any response, stamps it on the injected script, and the script runs — while your audit trail shows a "nonce-based CSP" that looks correct. If the nonce appears in an HTML file rather than a rendered response, it is static.
Plumbing it through a real stack
The middleware generates the nonce once per request and hands it to the templating layer, which stamps it on every legitimate <script>:
// Express-flavored middleware
app.use((req, res, next) => {
res.locals.cspNonce = crypto.randomBytes(16).toString('base64');
res.setHeader(
'Content-Security-Policy',
`default-src 'none'; script-src 'nonce-${res.locals.cspNonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'`
);
next();
});Next.js documents the same shape in middleware — generate the nonce, put it on the request headers, read it in the page to stamp <Script nonce={nonce}>. The failure mode to watch for is caching: a CDN or framework cache that serves a rendered HTML body with a stale nonce alongside a fresh header breaks every script. Nonce-bearing responses must be uncached or generated at the edge where header and body stay in sync. For a purely static site on Nginx, per-response nonces are not available without Lua/sub_filter tricks — use hashes for the few inline blocks and external files for the rest.
strict-dynamic: trust propagates, hosts drop out
'strict-dynamic' changes what script-src means. With it present, the host allowlist in script-src is ignored by modern browsers; instead, any script loaded by a nonced script inherits trust. Your bundler's chunk loader, dynamic import() calls, and a widget loader that injects its own <script> all keep working — without you enumerating every host they might touch.
This exists because host allowlists turned out to be the weak part of CSP. The 2016 Google paper "CSP Is Dead, Long Live CSP! On the Insecurity of Whitelists and the Future of Content Security Policy" (Weichselbaum, Spagnuolo, Lekies, Janc — ACM CCS 2016) analyzed real deployments and found the overwhelming majority of script-src allowlists bypassable through gadgets on the allowed hosts — JSONP endpoints chiefly. 'strict-dynamic' is the fix the same research pointed at: stop trusting hosts, start trusting the nonced roots. For browsers that never implemented CSP3, the host list still applies — keep 'self' or an https: fallback in the directive so old engines degrade to allowlist behavior instead of nothing.
Hashes: exact bytes or nothing
script-src 'sha256-<base64>' authorizes a script block whose contents hash to that value — byte-exact, whitespace included. It is the right tool for a fixed bootstrap line you cannot move to a file, and useless for anything that varies per response. Compute it with openssl dgst -sha256 -binary | openssl base64 on the exact script text. Note that 'unsafe-hashes' extends this to inline event handlers like onclick — which reintroduces the precise sink CSP exists to close. Refactor handlers instead.
Reporting: see the violations before you enforce
report-uri /csp-violations posts violation JSON on every refusal; report-to does the same through the newer Reporting-Endpoints header. report-uri is officially deprecated and universally supported; ship both. A report tells you the blocked URL, the violated directive, and the line that triggered it — which in report-only rollout is your migration TODO list, and after enforcement is your attack telemetry. A sudden run of script-src violations naming a host you never allowed is a live injection attempt you can put on a dashboard.
What to actually do
Generate nonces per response in middleware, stamp them at render, never cache nonce-bearing HTML. Prefer nonce + 'strict-dynamic' over long host lists, with 'self' kept as the fallback for pre-CSP3 engines. Reserve hashes for fixed bootstrap blocks. Send reports to an endpoint you actually watch — a policy without reporting is a smoke detector with no buzzer.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
They Got Root on a Fully Patched Ivanti VPN and the Integrity Checker Said Everything Was Fine
Volexity caught an attacker chaining zero-days into unauthenticated root on an Ivanti Connect Secure appliance running the latest build. The payload never touched disk, commands rode in over the same HTTPS requests as the exploit, and Ivanti's Integrity Checker reported no modifications.
Gitea Shipped 21 CVEs in One Release and Eleven of Them Are the Same Bug
Gitea 28.3.0 landed November 1 with twenty-one CVE fixes. Read the list and a pattern jumps out: more than half are the same failure repeated across different route handlers, where a token scoped to public data gets handed private data anyway. That's not twenty-one mistakes.
php2shell: The PHP Bug That Fires Before Your Code Runs
Two critical PHP flaws landed October 21 and were in CISA's exploited-vulnerabilities catalog five days later. The 9.2 score isn't the part that should bother you. It's where the bug lives — it goes off while PHP is still assembling $_POST, before a single line of your application has run.
A Certificate Authority's Private Keys Were the Numbers 4, 56 and 66
Eight eMudhra intermediate CA keys turned out to be recoverable from their own public certificates. Not stolen — computable, because the key generation produced almost no entropy. A researcher pulled all eight in under a second and signed a message with each one to prove it.