Testing X-Content-Security-Policy

If you wondered how X-Content-Security-Policy works in real life here's an example.

X-Content-Security-Policy is a proposed mechanism for limiting impact of injection attacks against websites — such as Cross-Site-Scripting. For each page the server will return the CSP header in HTTP response. The header describes what the browser should expect from the page and what it shouldn't.

For example this website returns the following CSP header:

X-Content-Security-Policy: allow 'self'; script-src www.google.com www.readability.com; options inline-script; img-src *.creativecommons.org

It means that for every page loaded from this website the user's browser should only load content (HTML, images etc) from itself with one exception — JavaScript is also allowed from Google. The reason is that it's using Google Custom Search Engine and loading JS from Google is part of CSE operations. But Google should be the only exception — all other externally referenced JS should be blocked.

Does this really work? Let's try. The following line contains a JS block that should execute a remote script. It's classical Cross-Site Scripting test from ha.ckers.org forum. On browsers supporting CSP you should see nothing (except for the JS souce code block). On other browsers you will see a pop-up telling that this website is vulnerable to XSS:

<script src="http://ha.ckers.org/xss.js"/>

I have tested this on Firefox 4 and MSIE9. On Firefox the pop-up doesn't appear. On MSIE it does — version 9 does not support CSP yet. In general, for some websites CSP seems to be pretty useful and easy to implement safeguard. Why "for some"? Because for large, complicated sites it might be quite difficult to index all the external references required to write CSP that will not block legitimate functions.