Content Security Policy, Your Future Best Friend ===== A long time ago, my personal website was attacked. I do not know how it happened, but it happened. Fortunately, the damage from the attack was quite minor: A piece of JavaScript was inserted at the bottom of some pages. I updated the FTP and other credentials, cleaned up some files, and that was that. One point made me mad: At the time, there was no simple solution that could have informed me there was a problem and — more importantly — that could have protected the website’s visitors from this annoying piece of code. A solution exists now, and it is a technology that succeeds in both roles. Its name is content security policy (CSP). ### What Is A CSP? Link The idea is quite simple: By sending a CSP header from a website, you are telling the browser what it is authorized to execute and what it is authorized to block. Here is an example with PHP: ``` "); ?> ``` #### SOME DIRECTIVES LINK You may define global rules or define rules related to a type of asset: ``` default-src 'self' ; # self = same port, same domain name, same protocol => OK ``` The base argument is default-src: If no directive is defined for a type of asset, then the browser will use this value. ``` script-src 'self' www.google-analytics.com ; # JS files on these domains => OK ``` In this example, we’ve authorized the domain name www.google-analytics.com as a source of JavaScript files to use on our website. We’ve added the keyword 'self'; if we redefined the directive script-src with another rule, it would override default-src rules. If no scheme or port is specified, then it enforces the same scheme or port from the current page. This prevents mixed content. If the page is https://example.com, then you wouldn’t be able to load http://www.google-analytics.com/file.js because it would be blocked (the scheme wouldn’t match). However, there is an exception to allow a scheme upgrade. If http://example.com tries to load https://www.google-analytics.com/file.js, then the scheme or port would be allowed to change to facilitate the scheme upgrade. ``` style-src 'self' data: ; # Data-Uri in a CSS => OK ``` In this example, the keyword data: authorizes embedded content in CSS files. Under the CSP level 1 specification, you may also define rules for the following: - `img-src` valid sources of images - `connect-src` applies to XMLHttpRequest (AJAX), WebSocket or EventSource - `font-src` valid sources of fonts - `object-src` valid sources of plugins (for example, `, , `) - `media-src` valid sources of `