Content Security Policies

CSP-Builder

Easily integrate Content-Security-Policy headers into your web application, either from a JSON configuration file, or programatically.

CSP Builder was created by Paragon Initiative Enterprises as part of their effort to encourage better application security practices.

Check out their other open source projects too.

Installation

Download and install the script sources:

$ cd /usr/local/lib
$ sudo git clone https://github.com/paragonie/csp-builder.git
$ sudo chown -R ${USER} csp-builder
$ cd csp-builder
$ composer install

Create the calling script in /usr/local/bin//build_csp.php:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/usr/bin/php
<?php

require '/usr/local/libcsp-builder/vendor/autoload.php';

use \ParagonIE\CSPBuilder\CSPBuilder;

//$policy = CSPBuilder::fromFile('./my_csp.json');
$policy = CSPBuilder::fromFile("$argv[1].json");
$policy->saveSnippet(
    "$argv[1].conf",
    CSPBuilder::FORMAT_NGINX
);

Make it executable:

$ sudo chmod +x /usr/local/bin/nginx_build_csp.php

JSON Policy Files

Create a directory to store the JSON policy files and Nginx CSP files:

$ sudo mkdir /etc/nginx/csp

Create your JSON files like the following simple example example.net.csp.json:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
 {
     "base-uri": {
         "self": true
     },
     "default-src": [],
     "frame-ancestors": [],
     "img-src": {
         "self": true
     },
     "plugin-types": [],
     "style-src": {
         "self": true,
         "unsafe-inline": true
     },
     "script-src": {
         "self": true,
         "unsafe-inline": true
     },
     "upgrade-insecure-requests": false,
     "block-all-mixed-content": true
 }

Policy Generation

To build the HTTP headers for this policy, use the name of the JSON file but without the “.json” extension …:

$ /etc/nginx/csp
$ nginx_build_csp.php example.net.csp

If successful, a Nginx configuration file /etc/nginx/csp/example.net.csp.conf has been created.

1
 add_header Content-Security-Policy "base-uri 'self'; default-src 'none'; frame-ancestors 'none'; img-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';";

If you get errors, most likely your JSON file isn’t syntactically correct. You can check your syntax on https://jsonchecker.com/

CSP Directives

As of the time this writing (November 2017) the CSP builder understands the following CSP directives:

The following are currently not supported: