Content Security Policy, explained simply
What stops a stranger's code from running on your site? One answer is a short list that your server sends with every page: the Content Security Policy, or CSP.
Can a comment run code on myblog.com?
We use one example for the whole lesson: a blog at myblog.com that lets anyone post a comment. First we attack it. Then we protect it with CSP, one step at a time.
Colours: blue is your site and your code, amber is the policy, green is allowed, red is the attacker or a block.
1The attack: cross-site scripting
A comment box takes text from a stranger and shows it on your page. If the site doesn't clean that text, the stranger can post HTML. And HTML can include a <script> tag.
This attack is cross-site scripting, or XSS. The script runs inside your page, with your page's rights. It can read the login cookie (if the cookie isn't HttpOnly), change the page, or send requests as the user.
The first fix is always in your code: clean or escape the comment text. But one missed bug is enough for an attacker. CSP is a second wall for that case.
2The fix: a list from your server
Your server sends the policy as a response header, next to the page. It tells the browser where each kind of content can come from. Tap each part:
So this policy says: run scripts only from my own site, and from trusted.com. Every other script is blocked. The browser does the blocking, not your server. Your server only sends the list.
3The browser checks every script
For each script, image or stylesheet, the browser finds the directive for that kind of content and compares the source with the list. Try it. Your page loads four things, and the attacker has put three things into the comments.
The goal: all your code runs, and none of the attacker's code runs. The lab starts with no policy. Choose an example, or type your own.
https://myblog.com, and ports are ignored. The console messages are shortened forms of the messages in Chrome.Things to see in the lab:
- No policy: everything runs, the attacker's code too.
- 'self' is the exact origin of the page:
https://myblog.com. It doesn't includeimg.trusted.comor other subdomains. - 'unsafe-inline' lets inline code run again, so the attacker's inline script and the
onerrorcode run too. Avoid it inscript-src. - default-src is the fallback. When a page has no
img-src, the browser usesdefault-srcfor images. A strictdefault-srccan block your own files, so add the directives that you need. - Quotes matter. Without quotes,
selfis the name of a host, not your site. So your own scripts are blocked.
"Scripts from a list" reaches the goal. But a good policy also sets default-src, so content that you didn't think of is blocked too. This one also reaches the goal. Paste it into the lab:
default-src 'self'; script-src 'self' https://trusted.com; img-src 'self' https://*.trusted.com
4Inline code and nonces
With a script-src list, the browser blocks all inline code: <script>…</script> written into the page, and attributes like onclick. That is good, because injected code is usually inline. But what if your page needs one inline script?
Don't add 'unsafe-inline'. Use a nonce: a random value that your server makes again for every response. The server puts it in the header and in your own script tags. A script runs only if its nonce matches.
Content-Security-Policy: script-src 'nonce-'
Two rules make nonces safe: make a new nonce for every response, from a secure random source (128 bits or more), and never put a nonce on a script tag that contains user text.
A hash is the other choice: 'sha256-…' is the hash of the exact text of one inline script. It suits static pages, where the script never changes. When a policy has a nonce or a hash, the browser ignores 'unsafe-inline'.
5More than scripts
script-src does the most work against XSS, but each kind of content has its own directive. The last column shows which directives use default-src when they are missing.
| directive | controls | falls back |
|---|---|---|
default-src | the fallback for the other -src directives | — |
script-src | JavaScript | yes |
style-src | CSS | yes |
img-src | images | yes |
connect-src | fetch, XHR and WebSockets: where scripts can send data | yes |
font-src | web fonts | yes |
frame-src | pages that your page shows in an iframe | yes |
object-src | <object> and <embed>; set it to 'none' | yes |
base-uri | the <base> tag, which changes where relative URLs point | no |
form-action | where forms can send their data | no |
frame-ancestors | which sites can show your page in an iframe (stops clickjacking) | no |
The directives with "no" don't use default-src. If you don't set them, they allow everything. So set them on their own.
6Turn it on without breaking your site
A strict policy on a real site often blocks something that you forgot: an analytics script, a font, an inline onclick. So test first, in report-only mode. The browser blocks nothing. It only reports what it would block.
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' https://trusted.com; report-to csp Reporting-Endpoints: csp="https://myblog.com/csp-reports"
Each blocked item sends a JSON report to your endpoint, and shows a message in the console. Fix your pages until the reports stop. Then change the header name to Content-Security-Policy. Older browsers use report-uri in place of report-to, so many sites send both.
Where to set the header
On the server. In nginx, for example:
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.com; object-src 'none'; base-uri 'none'; frame-ancestors 'none'" always;
A page can also set a policy with a <meta http-equiv="Content-Security-Policy"> tag. But a meta tag can't use frame-ancestors, report-only mode or reports. A header is better.
Check yourself
The whole picture
- XSS puts a stranger's script into your page, and the browser runs it like your own code.
- CSP is a list in a response header: where each kind of content can come from.
- The browser checks every script against the list and blocks the rest, inline code too.
- Nonces let your own inline scripts run, without
'unsafe-inline'. - Report-only mode lets you test a policy before you enforce it.
CSP doesn't replace a fix in your code. It's a second wall: if one bug gets through, the attacker's script still can't run.
Next level
Not published yet. It will cover:
'strict-dynamic': trust the scripts that a trusted script loads- Trusted Types: stop DOM-based XSS with
require-trusted-types-for - reading CSP reports at scale
- CSP for single-page apps and frameworks