Richard Richard - 7 months ago 17
PHP Question

How to implement content security policy?

There's good articles explaining the options for CSP like this one:
http://www.html5rocks.com/en/tutorials/security/content-security-policy/

Perhaps it's completely obvious because I can't find any good examples but how do you actually implement CSP in practise?

In PHP you can set the header on a page you serve, but what if you just have a HTML file? Do you have to do it through your webserver, apache or similar? That doesn't seem an easy approach.

What's the best practise here? Every individual page served should have the header manually set?

Thanks!

Answer

That doesn't seem an easy approach.

Yeah, it's not. There are some clever shortcuts you can take, however.

how do you actually implement CSP in practise?

In PHP you can set the header on a page you serve, but what if you just have a HTML file? Do you have to do it through your webserver, apache or similar? That doesn't seem an easy approach.

I wrote a command line PHP script that took a JSON blob like code block A assembled a string that looks like code block B and saved it to a separate file.

A:

{
    "script-src": [ "self",  "https://apis.google.com" ]
}

B:

add_header Content-Security-Policy "script-src: 'self' https://apis.google.com";

Then I added a line to configure my nginx configuration for that virtualhost to include the generated CSP directive:

include /path/to/script/output.conf;

As a consequence of this system, if I wanted to make a change to the CSP headers, I only need to edit a JSON file.

And that's how I made CSP headers easy to manage. Your mileage may vary.

Here it is: CSP Builder.

Comments