PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Content Security Policy introduction

Note: This article was originally published at Planet PHP on 9 August 2010.
Planet PHP

I blogged Content Security Policy about this a 2 year ago when it was still called 'Site Security Policy'. It started as a specification and an add-on, and turned into a patch a bit later. Finally it made it into Firefox 4 beta 1. I think CSP is the next web security revolution, so make yourself aware of how it works and the implications.

So what is it? The short version is that it's a very effective measure against cross-site scripting. By specifying a policy through the 'X-Content-Security-Policy', you can specify exactly from which locations you accept javascript and other content. This allows you to block scripts from any domains unknown to you, and inline scripts altogether.

A simple example

  1. X-Content-Security-Policy: allow 'self'

A simple PHP example to see this in action:

  1. A
  2. header("X-Content-Security-Policy: allow 'self'");
  3. A
  4. ?
  5. A
  6. A A CSP test
  7. A
  8. A
  9. A
  10. A
  11. alert('XSS!');
  12. A
  13. A
  14. A

If the above code is opened in Firefox 4.0 beta1, the script will not execute, and a warning is added to the "Error Console" (in the Tools menu).

Not only does this header block inline scripts, it also blocks the following:

  • eval(). This important for people using eval() to parse json responses.
  • setTimeout and setInterval if the function is provided as a string.
  • javascript: urls
  • html event attributes (onclick, onload, etc.).
  • All images, plugin objects (flash, quicktime etc.), audio, video, html frames and fonts not served from the same domain as the html page.
  • XMLHttpRequest to domains other than the source domain.

Fortunately there are fine grained controls about what you want to allow from which domains. Here are some examples from the specification.

  1. X-Content-Security-Policy: allow 'self'; img-src *; \
  2. A A A A A A A A A A A A A Aobject-src media1.com media2.com *.cdn.com; \
  3. A A A A A A A A A A A A A Ascript-src trustedscripts.example.com

This example starts with "allow 'self'", allowing only content from the same domain. The "img-src *" rule allows images from any domain. "object-src: media1.com media2.com" allows tags to use files from media1.com, media1.com and the same domain as the html was served from. To learn more about these, I would recommend just taking a good look at the directives list in the specification.

Options and reporting

Truncated by Planet PHP, read more at the original (another 7000 bytes)