← All lessons
How Content Security Policy works
A policy blocks an injected script
Browser
blog.test
server.js
app.get("/post/:id", (req, res) => { const nonce = crypto.randomBytes(16).toString("base64"); res.set("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'; report-to csp`); res.set("Reporting-Endpoints", 'csp="/csp-report"'); res.render("post", { nonce, comments });}); app.post("/csp-report", (req, res) => log(req.body));post.html
<script src="/app.js"></script><script nonce="{{nonce}}">initComments()</script> <!-- a comment from the database, never escaped --><script>steal()</script><img src="x" onerror="steal()"><script src="https://evil.test/x.js"></script>Write a script-src and see what still runs
Add
The page at https://blog.test
browser.js
function allowed(script, policy) { const list = policy["script-src"] ?? policy["default-src"]; if (!list) return true; if (script.nonce && list.includes(`'nonce-${script.nonce}'`)) return true; if (script.src) return list.some((s) => matches(s, script.src)); // a nonce or hash switches 'unsafe-inline' off if (list.some(isNonceOrHash)) return false; return list.includes("'unsafe-inline'");}Why the nonce changes on every response
1. The attacker opens the page and reads its nonce
2. They post a comment that carries it
3. You open the page
A shared cache serving the same HTML to everyone repeats the nonce too
server.js
app.get("/post/:id", (req, res) => { const nonce = crypto.randomBytes(16) .toString("base64"); // const nonce = "r4nd0m"; // never a constant, or anyone can copy it res.set("Content-Security-Policy", `script-src 'nonce-${nonce}'`); res.render("post", { nonce });});Topics
Next: How SSRF works
Open lesson