Web Security & OWASP (50 Qs)•Part 2: OWASP Top 10 & Critical Vulnerability Deep-Dives (11 - 25)
Content Security Policy (CSP): Nonce-based architecture, strict-dynamic, and eliminating unsafe-inline.
Content Security Policy (CSP Level 3)
A Content Security Policy is an HTTP response header that restricts the resources (scripts, styles, images, iframes) the browser is allowed to load and execute for a given page.
javascript
[ Incoming HTTP Request ]
|
v
[ Server generates random 128-bit CSP Nonce per request ]
Nonce: "r4nd0mN0nc3Str1ng=="
|
+---> Injects Nonce into HTTP Header:
| Content-Security-Policy: script-src 'nonce-r4nd0mN0nc3Str1ng==' 'strict-dynamic';
|
+---> Injects Nonce into Legitimate Inline Script:
<script nonce="r4nd0mN0nc3Str1ng==">console.log("Allowed!");</script>
Attacker attempts XSS injection:
<script>alert(document.cookie);</script>
Browser: "Script missing valid nonce! EXECUTION BLOCKED!"
Production Nonce Blueprint (Next.js / Node.js Middleware)
typescript
import crypto from 'crypto';
export function middleware(req, res, next) {
const nonce = crypto.randomBytes(16).toString('base64');
const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
style-src 'self' 'nonce-${nonce}';
img-src 'self' data: https:;
font-src 'self';
object-src 'none';
base-uri 'none';
frame-ancestors 'none';
form-action 'self';
`.replace(/\s{2,}/g, ' ').trim();
res.setHeader('Content-Security-Policy', cspHeader);
res.locals.nonce = nonce;
next();
}
Why 'strict-dynamic' is Revolutionary
In CSP Level 3, 'strict-dynamic' tells the browser that any script trusted via a valid cryptographic nonce can dynamically load downstream child scripts, eliminating the need to maintain massive, brittle host allowlists.