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#!/usr/bin/php
2<?php
3
4require '/usr/local/libcsp-builder/vendor/autoload.php';
5
6use \ParagonIE\CSPBuilder\CSPBuilder;
7
8//$policy = CSPBuilder::fromFile('./my_csp.json');
9$policy = CSPBuilder::fromFile("$argv[1].json");
10$policy->saveSnippet(
11 "$argv[1].conf",
12 CSPBuilder::FORMAT_NGINX
13);
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 "base-uri": {
3 "self": true
4 },
5 "default-src": [],
6 "frame-ancestors": [],
7 "img-src": {
8 "self": true
9 },
10 "plugin-types": [],
11 "style-src": {
12 "self": true,
13 "unsafe-inline": true
14 },
15 "script-src": {
16 "self": true,
17 "unsafe-inline": true
18 },
19 "upgrade-insecure-requests": false,
20 "block-all-mixed-content": true
21 }
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:
referrer - obsolete, use Referrer-Policy HTTP header instead.
reflected-xss - obsolete, use X-XSS-Protection HTTP header instead.
worker-src - will use
default-source
as fallback, if absent.