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.

https://myblog.com/first-post
My first post
Ana: Nice post!
Policy: none
Post the attacker's comment. Then turn CSP on and try again.
Figure 1. A simulation: no real script runs on this page. The attacker's comment holds a script tag. Without CSP, the browser can't tell it from your own code, so it runs it.

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:

:
Tap a part of the header.
Figure 2. One header, one directive, two allowed sources. A real policy often has several directives, with a semicolon between them.

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.

Browser console

      
Figure 3. Edit the policy or choose an example. The checks follow the CSP rules, simplified: the page is https://myblog.com, and ports are ignored. The console messages are shortened forms of the messages in Chrome.

Things to see in the lab:

"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-'
Figure 4. The attacker's comment is saved on the server, so its text is the same on every load. The nonce changes on every load, so the attacker can't know the next one.

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.

directivecontrolsfalls back
default-srcthe fallback for the other -src directives—
script-srcJavaScriptyes
style-srcCSSyes
img-srcimagesyes
connect-srcfetch, XHR and WebSockets: where scripts can send datayes
font-srcweb fontsyes
frame-srcpages that your page shows in an iframeyes
object-src<object> and <embed>; set it to 'none'yes
base-urithe <base> tag, which changes where relative URLs pointno
form-actionwhere forms can send their datano
frame-ancestorswhich 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

    1. XSS puts a stranger's script into your page, and the browser runs it like your own code.
    2. CSP is a list in a response header: where each kind of content can come from.
    3. The browser checks every script against the list and blocks the rest, inline code too.
    4. Nonces let your own inline scripts run, without 'unsafe-inline'.
    5. 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: