Content Security Policy
A script injected into a page runs with the same access as the site's own code: it can read the page and local storage, and send requests with the visitor's credentials. A Content Security Policy (CSP) narrows that access. The website sends the browser a set of rules for what the page's code may do, most often which resources, JavaScript above all, the document may load, so that cross-site scripting does less damage.1
How the policy is sent
The policy is the Content-Security-Policy response header. It consists of directives separated by semicolons, each with a name and a value.1 Every response the site sends should carry the header.
Content-Security-Policy: default-src 'self'; img-src 'self' example.comHere default-src is the fallback for every resource type without its own directive, and 'self' means the page's own origin. Images may also come from example.com.1 A page on a static host that cannot set headers can use a <meta http-equiv="Content-Security-Policy"> tag instead, but that form cannot set frame-ancestors, sandbox or a reporting endpoint, and the older X-Content-Security-Policy and X-WebKit-CSP headers are obsolete.2
What a policy blocks
When default-src or script-src is present, inline script elements, inline event handlers such as onclick, and javascript: URLs do not run, and eval() is blocked. The keywords 'unsafe-inline' and 'unsafe-eval' switch these protections off, and inline JavaScript is one of the most common XSS vectors, so 'unsafe-inline' gives back much of what the policy took away.1 Code that relied on inline handlers has to be rewritten, for example by replacing onclick="doSomething()" with addEventListener('click', doSomething), and eval() of JSON with JSON.parse().3
Allowlists and strict policies
The first style of policy lists the hosts that may serve scripts. A 2016 Google study of about 100 billion pages found 26,011 unique policies on 1,680,867 hosts. It found bypasses in 94.72% of the distinct policies. Of the 15 domains most often allowed for loading scripts, 14 contain unsafe endpoints, and 75.81% of the distinct policies use a script allowlist that lets an attacker bypass the policy.4 Allowlists also grow long; one developer needed 187 Google domains in the list to add Google Analytics.1
A strict policy replaces host lists with a nonce or a hash. A nonce must be new and unpredictable for every response: a cryptographically strong random value, ideally 128 bits or more, Base64 encoded.3 A script runs only when its tag carries the current nonce. Because the server writes a new nonce into each response, the HTML cannot be static.1 A middleware that adds the nonce to every script tag defeats the purpose, since injected scripts then receive it too.2 A hash is the digest of the script, Base64 encoded, and suits static pages; changing the script by one whitespace character changes the hash.2
Content-Security-Policy:
script-src 'nonce-{RANDOM}' 'strict-dynamic';
object-src 'none';
base-uri 'none';The keyword 'strict-dynamic' passes the trust given by a nonce or hash to the scripts that script loads, so the files it loads need no nonces of their own. It weakens the policy when a trusted script builds <script> elements from input an attacker controls.1 object-src 'none' disables plugins, and base-uri 'none' blocks an injected <base> tag, which would change where relative script URLs load from.3
What a policy does not stop
A policy does not replace validating input and encoding output.2 A nonce does not help when the injection lands in the body or the src parameter of a nonced script tag, or in the location of a dynamically created script. With 'unsafe-eval' an injection into eval() or setTimeout() also works.3
Other directives
frame-ancestors controls which documents may embed the page. It replaces X-Frame-Options and does not fall back to default-src, so it needs its own entry; frame-ancestors 'none' suits a site that need not be embedded.2 form-action limits where forms may send data, which stops an injected phishing form from posting to an attacker. Where a strict policy cannot be used, a basic one is default-src 'self'; frame-ancestors 'self'; form-action 'self'.2
Rollout and reporting
The Content-Security-Policy-Report-Only header applies no restrictions but sends every violation to the reporting endpoint. It can be sent together with an enforced policy, so a strict policy can be tested beside a looser one.2 A rollout runs report-only first and enforces after.5 Reports go to the endpoint chosen with the report-to directive; report-uri is deprecated.2 Google's CSP Evaluator checks a policy for weaknesses.3
Setting a policy
Express
This handler creates a nonce for each response and passes it to the template:3
app.get('/', function (request, response) {
const nonce = crypto.randomBytes(16).toString('base64');
const csp = `script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none';`;
response.set('Content-Security-Policy', csp);
response.render(template, { nonce: nonce });
});Every script tag in the template must set its nonce attribute to that value.3 Helmet's helmet() sets 13 headers, one of them a default CSP with script-src 'self' and object-src 'none'. Helmet does little validation of a custom policy, and its documentation points to CSP checkers for that.6
Next.js
With nonces, all pages must be dynamically rendered: static optimization and Incremental Static Regeneration are disabled, and Partial Prerendering is incompatible. Next.js reads the nonce from the CSP header during rendering and applies it to framework scripts and to <Script> components. The nonce is set in the proxy.ts file in version 16. In development React needs 'unsafe-eval'; production does not.7 An experimental option, experimental.sri, uses hashes to keep static generation in the App Router; the feature may still change or be removed.7
In SecFlash
On the Security page, SecFlash reports SF-SEC-103 when a site sends no content security policy and SF-SEC-104 when the policy contains 'unsafe-inline' or a wildcard in script-src. The ZAP scan adds SF-SEC-620 for a CSP weakness and SF-SEC-621 for a missing CSP header, on the same page.
See also
- Cross-site scripting
- HTTP security headers
- Input validation
- Output encoding
- Defence in depth
- Cross-origin resource sharing
- Category: Security concepts
References
- a b c d e f g "Content Security Policy (CSP)". MDN Web Docs. Mozilla.
- a b c d e f g h "Content Security Policy Cheat Sheet". OWASP Cheat Sheet Series.
- a b c d e f g Weichselbaum, Lukas (13 September 2024). "Mitigate cross-site scripting (XSS) with a strict Content Security Policy (CSP)". web.dev. Google.
- back Weichselbaum, Lukas; Spagnuolo, Michele; Lekies, Sebastian; Janc, Artur (2016). "CSP Is Dead, Long Live CSP: On the Insecurity of Whitelists and the Future of Content Security Policy". Proceedings of the 23rd ACM Conference on Computer and Communications Security (CCS), Vienna.
- back "Content Security Policy". Vercel Docs.
- back "Helmet.js". Helmet documentation.
- a b "How to set a Content Security Policy (CSP) for your Next.js application". Next.js Docs. Vercel.
External links
- Content Security Policy (CSP), MDN Web Docs
- Content Security Policy Cheat Sheet, OWASP Cheat Sheet Series