CSP: Content Security Policy

Difficulty: Advanced

Question

What is Content Security Policy (CSP), and how does it reduce the impact of XSS? How would you deploy a strict CSP on a real site?

Answer

Content Security Policy is an HTTP response header (Content-Security-Policy) that tells the browser which sources of scripts, styles, images, frames and other resources a page may load and execute. If an attacker manages to inject a <script> tag or an inline event handler, a strict CSP stops the browser from running it, turning many XSS bugs into harmless broken markup. CSP is a defence-in-depth layer: it reduces the impact of XSS, but you still need output encoding and safe templating.

How CSP blocks injected script

The browser enforces directives such as:

  • script-src: where JavaScript may come from. Without 'unsafe-inline', inline <script> blocks and onclick= handlers are blocked.
  • 'unsafe-eval' absent: eval(), new Function() and string setTimeout are blocked.
  • object-src 'none': blocks legacy plugin content.
  • base-uri 'none': stops an injected <base> tag from redirecting relative script URLs.
  • frame-ancestors: controls who may frame your page (clickjacking protection, replaces X-Frame-Options).

So if a comment field renders <img src=x onerror=alert(1)>, the inline handler simply does not run.

Allowlist CSP vs strict (nonce or hash) CSP

ApproachExampleWeakness
Host allowlistscript-src 'self' cdn.example.comBypassable if any allowed host serves JSONP or an old Angular build; long lists are hard to maintain
Nonce-basedscript-src 'nonce-r4nd0m' 'strict-dynamic'Nonce must be random per response; needs server rendering support
Hash-basedscript-src 'sha256-...'Good for static pages; every inline script change needs a new hash

Current guidance (Google, OWASP) favours a strict CSP: a fresh random nonce on every response, added as the nonce attribute on each legitimate script tag, plus 'strict-dynamic' so scripts you trust can load their own dependencies. Injected scripts do not know the nonce, so they are blocked. In CSP Level 3 browsers, when a nonce or hash is present, 'unsafe-inline' is ignored, so you can include it as a fallback for very old browsers.

Deploying without breaking production

  1. Ship it first as Content-Security-Policy-Report-Only with a report-to (or legacy report-uri) endpoint.
  2. Collect violation reports for a week or two and fix legitimate violations: move inline handlers into JS files, add nonces to scripts, remove eval.
  3. Switch to the enforcing header. Keep reporting on.
  4. Optionally add require-trusted-types-for 'script' to lock down DOM XSS sinks like innerHTML.

Gotchas

  • A static nonce hard-coded in HTML is worthless. It must be unpredictable and unique per response.
  • frame-ancestors, report-uri and sandbox do not work in a <meta http-equiv> CSP; send a real header.
  • CSP does not stop all injection: HTML injection that steals data via forms or dangling markup, and logic bugs in your own trusted scripts, still matter.
  • Third-party tags (analytics, chat widgets, payment SDKs) are the usual reason CSPs end up weak. 'strict-dynamic' helps a lot here.
  • Tools like Google's CSP Evaluator will flag a policy that looks strict but is trivially bypassable.
Nonce-based CSP blocking an injected script. Only scripts carrying this response's nonce are executed.
  1. Server → Browser: CSP header with nonce abc123
  2. Server → Browser: HTML with script nonce=abc123
  3. Browser → Browser: Runs script: nonce matches
  4. Attacker payload → Browser: Injected script, no nonce
  5. Browser → Server: Blocked, violation reported

Code examples

Express middleware issuing a fresh nonce per response

import crypto from "node:crypto";
import express from "express";

const app = express();

app.use((req, res, next) => {
  // 128 bits of randomness, new for every response
  res.locals.nonce = crypto.randomBytes(16).toString("base64");
  res.setHeader(
    "Content-Security-Policy",
    [
      `script-src 'nonce-${res.locals.nonce}' 'strict-dynamic' https: 'unsafe-inline'`,
      "object-src 'none'",
      "base-uri 'none'",
      "frame-ancestors 'self'",
      "report-to csp",
    ].join("; ")
  );
  res.setHeader("Reporting-Endpoints", 'csp="https://example.com/csp-reports"');
  next();
});

app.get("/", (req, res) => {
  res.send(`<script nonce="${res.locals.nonce}" src="/app.js"></script>`);
});

Modern browsers use the nonce and strict-dynamic and ignore https: and 'unsafe-inline', which exist only as fallbacks for old browsers. The nonce changes on every request so an attacker cannot predict it.

Report-only rollout header

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Security-Policy-Report-Only: script-src 'nonce-Q2hhbmdlTWU=' 'strict-dynamic'; object-src 'none'; base-uri 'none'; report-to csp
Reporting-Endpoints: csp="https://example.com/csp-reports"

Report-only mode logs what would be blocked without blocking it, so you can fix violations before enforcing.

Key points

  • CSP is defence in depth for XSS, not a replacement for output encoding.
  • Strict CSP = per-response random nonce (or hashes) + 'strict-dynamic' + object-src 'none' + base-uri 'none'.
  • Host allowlists are often bypassable via JSONP endpoints or old libraries on allowed domains.
  • Roll out with Content-Security-Policy-Report-Only first.
  • frame-ancestors replaces X-Frame-Options and does not work in a meta tag.

Common follow-up questions

  • Why is a domain allowlist CSP considered weaker than a nonce-based one?
  • What does 'strict-dynamic' do?
  • How would you handle third-party scripts like analytics under a strict CSP?
  • What are Trusted Types and how do they relate to CSP?

Interview tips

  • Say up front that CSP mitigates XSS impact; it does not fix the injection bug itself.
  • Mentioning nonces, 'strict-dynamic' and report-only rollout signals hands-on experience.
  • Be ready to explain why 'unsafe-inline' defeats most of CSP's XSS protection.

Concepts covered

Content Security Policy, XSS, Nonce-based CSP, strict-dynamic, Trusted Types, Security Headers

More Web Security (OWASP, JWT, XSS, CSRF) questions