Content Security Policy: writing, testing, and enforcing a strict policy
How CSP tells the browser which scripts, styles, frames, and connections a page may use, how to build a nonce-based strict policy, how to roll it out with report-only mode, and how to read violation reports.
Diagram
Rolling out a strict policy
Step 1 of 4
Inventory
List the scripts, styles, fonts, frames, and API origins the page uses.
# Inventory # List the scripts, styles, fonts, frames, and API origins # the page uses.
The example on the open step is one illustration, or the fix you can paste into an application you own.
What this page is made of
3 pieces. Each one says what fails, who is affected, what you would notice, and what you change.
Allow-lists of hosts are weak
- What fails
- Policies that allow whole CDNs can include script hosts that serve user content or old libraries.
- Who is affected
- Users, if any allowed host can serve attacker-chosen script.
- What you would notice
- script-src https://cdn.jsdelivr.net or similar broad hosts.
- What you change
- Use nonces with strict-dynamic instead of host lists.
unsafe-inline undoes it
- What fails
- Allowing inline script removes most XSS protection.
- Who is affected
- Users of pages with any injection bug.
- What you would notice
- unsafe-inline in script-src.
- What you change
- Refactor inline scripts and event handlers.
Reports are data
- What fails
- Violation reports show both broken features and attempted injection.
- Who is affected
- The team that needs to know when the policy blocks something.
- What you would notice
- Enforcing without any report endpoint.
- What you change
- Collect reports, filter browser-extension noise, and review weekly.
Evaluating an existing policy
Read the deployed header and check script-src first. Google’s CSP Evaluator flags common weaknesses. Then check object-src, base-uri, and frame-ancestors, which are often forgotten.
$ curl -sI https://app.example.org | grep -i content-security-policy content-security-policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com # issues: unsafe-inline; no object-src; no base-uri; no frame-ancestors
Nonces in practice
Generate a random nonce per response, add it to the header and to each script tag you trust. strict-dynamic lets those scripts load others without listing hosts. Never reuse nonces across responses or cache pages with a fixed nonce.
Check yourself
Recognition and the fix. Nothing here is a procedure.
Which script-src value removes most of CSP’s XSS protection?
Sibling techniques
Pages at the same depth, plus a lab and a glossary card for this one.
- 01DOM XSS: sinks in the browserA page can be safe on the wire and still treat a URL, a message, or a stored string as HTML once script already on the page assigns it.
- 02Stored XSS in rich textA comment, a profile, or a document that allows formatting is stored and later parsed as HTML for someone else.