Adding Content Security Policy (CSP) to Apache Virtual Hosts
What is CSP?
With more and more web attacks happening each day, the web community came up with a new technology called Content Security Policy (CSP) to protect its users. CSP is a mechanism in the browser that restricts what content will be requested and run by the browser. CSP does this by passing flags in the response header that tells the browser what resources (images, javascript, css, etc.) can be requested and accepted to execute.
Who supports CSP?
- Firefox 4 and greater
- Chrome 13 and greater
- Safari support is coming
- Opera support is coming
- Internet Explorer has no plans to support CSP (so disappointing)
Why use CSP?
- Mitigate Cross Site Scripting (XSS)
- Mitigate Clickjacking
- Mitigate Packet Sniffing Attacks
- Doesn’t affect browsers that don’t support CSP
Any drawbacks to CSP?
- No Inline Javascript or CSS (which may require coding changes to your web site)
- Thats about it!
How do I add it to an Apache Virtual Host?
Okay, lets get started.
Step 1 – Make sure mod_headers is enabled
Most configurations have mod_headers enabled by default, but it would be wise to check your apache httpd.conf file to make sure its enabled. The line below allows apache to inject http headers into your response, which is necessary for this example.
LoadModule headers_module modules/mod_headers.so
Step 2 – Add CSP Header to your virtual host
In this step, we only want our users to request and process images that come from linux.dashexamples.com. The line below shows how we setup CSP to only allow images from linux.dashexamples.com to be allowed.
Header add X-Content-Security-Policy-Report-Only "allow 'self'; img-src linux.dashexamples.com;
Example of the linux.dashexamples.com Virtual Host
Here’s the real virtual host file for linux.dashexamples.com domain, linux.dashexamples.conf.
<VirtualHost *:80> DocumentRoot /var/www/html/linux.dashexamples.com ServerName linux.dashexamples.com ServerAlias www.linux.dashexamples.com Header add X-Content-Security-Policy-Report-Only "allow 'self'; img-src linux.dashexamples.com; report-uri /violation.php" </VirtualHost>
Take a look at the screenshot below, more specifically, look at the response headers from the server. You’ll see X-Content-Security-Policy-Report-Only is now being sent back to your browser!

What does a CSP Violation look like?
Below is a screenshot of firefox’s console (you’ll also notice the firebug plugin installed) with 2 CSP Violations showing.

