PHP Classes
elePHPant
Icontem

PHP CSP Header Builder: Generate Content Security Policy headers

Recommend this page to a friend!

  Author Author  
Name: Scott Arciszewski <contact>
Classes: 14 packages by
Country: United States United States
Innovation award
Innovation award
Nominee: 10x

Winner: 1x


  Detailed description   Download Download .zip .tar.gz  
This package can generate Content Security Policy headers.

It can take configuration values from a JSON file or are defined programatically and generates HTTP response headers.

The package can also statically generate HTTP response header files for Web servers like Apache and NGinx.

Details

Content Security Policy Builder

Build Status

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 our effort to encourage better application security practices.

Check out our other open source projects too.

There's also a CSP middleware available that uses this library.

Installing

First, get Composer, then run:

composer require paragonie/csp-builder

Build a Content Security Policy header from a JSON configuration file

<?php

use ParagonIE\CSPBuilder\CSPBuilder;

$csp = CSPBuilder::fromFile('/path/to/source.json');
$csp->sendCSPHeader();

You can also load the configuration from a JSON string, like so:

<?php

use ParagonIE\CSPBuilder\CSPBuilder;

$configuration = file_get_contents('/path/to/source.json');
if (!is_string($configuration)) {
    throw new Error('Could not read configuration file!');
}
$csp = CSPBuilder::fromData($configuration);
$csp->sendCSPHeader();

Finally, you can just pass an array to the first argument of the constructor:

<?php

use ParagonIE\CSPBuilder\CSPBuilder;

$configuration = file_get_contents('/path/to/source.json');
if (!is_string($configuration)) {
    throw new Error('Could not read configuration file!');
}
$decoded = json_decode($configuration, true);
if (!is_array($decoded)) {
  throw new Error('Could not parse configuration!');
}
$csp = new CSPBuilder($decoded);
$csp->sendCSPHeader();

Example

{
    "report-only": false,
    "report-uri": "/csp_violation_reporting_endpoint",
    "base-uri": [],
    "default-src": [],    
    "child-src": {
        "allow": [
            "https://www.youtube.com",
            "https://www.youtube-nocookie.com"
        ],
        "self": false
    },
    "connect-src": [],
    "font-src": {
        "self": true
    },
    "form-action": {
        "allow": [
            "https://example.com"
        ],
        "self": true
    },
    "frame-ancestors": [],
    "img-src": {
        "blob": true,
        "self": true,
        "data": true
    },
    "media-src": [],
    "object-src": [],
    "plugin-types": [],
    "script-src": {
        "allow": [
            "https://www.google-analytics.com"
        ],
        "self": true,
        "unsafe-inline": false,
        "unsafe-eval": false
    },
    "style-src": {
        "self": true
    },
    "upgrade-insecure-requests": true
}

Build a Content Security Policy, programmatically

<?php

use ParagonIE\CSPBuilder\CSPBuilder;

$csp = CSPBuilder::fromFile('/path/to/source.json');

// Let's add a nonce for inline JS
$nonce = $csp->nonce('script-src');
$body .= "<script nonce={$nonce}>";
    $body .= $desiredJavascriptCode;
$body .= "</script>";

// Let's add a hash to the CSP header for $someScript
$hash = $csp->hash('script-src', $someScript, 'sha256');

// Add a new source domain to the whitelist
$csp->addSource('image', 'https://ytimg.com');

// Set the Report URI
$csp->setReportUri('https://example.com/csp_report.php');

// Let's turn on HTTPS enforcement
$csp->addDirective('upgrade-insecure-requests', true);

$csp->sendCSPHeader();

Note that many of these methods can be chained together:

$csp = CSPBuilder::fromFile('/path/to/source.json');
$csp->addSource('image', 'https://ytimg.com')
    ->addSource('frame', 'https://youtube.com')
    ->addDirective('upgrade-insecure-requests', true)
    ->sendCSPHeader();

  • addSource()
  • addDirective()
  • disableOldBrowserSupport()
  • enableOldBrowserSupport()
  • hash()
  • preHash()
  • setDirective()
  • setBlobAllowed()
  • setDataAllowed()
  • setFileSystemAllowed()
  • setMediaStreamAllowed()
  • setReportUri()
  • setSelfAllowed()
  • setAllowUnsafeEval()
  • setAllowUnsafeInline()

Inject a CSP header into a PSR-7 message

Instead of invoking sendCSPHeader(), you can instead inject the headers into your PSR-7 message object by calling it like so:

/
 * $yourMessageHere is an instance of an object that implements 
 * \Psr\Http\Message\MessageInterface
 *
 * Typically, this will be a Response object that implements 
 * \Psr\Http\Message\ResponseInterface
 *
 * @ref https://github.com/guzzle/psr7/blob/master/src/Response.php
 */
$csp->injectCSPHeader($yourMessageHere);

Save a CSP header for configuring Apache/nginx

Instead of calling sendCSPHeader() on every request, you can build the CSP once and save it to a snippet for including in your server configuration:

$policy = CSPBuilder::fromFile('/path/to/source.json');
$policy->saveSnippet(
    '/etc/nginx/snippets/my-csp.conf',
    CSPBuilder::FORMAT_NGINX
);

Make sure you reload your webserver afterwards.

Support Contracts

If your company uses this library in their products or services, you may be interested in purchasing a support contract from Paragon Initiative Enterprises.


  Classes of Scott Arciszewski  >  PHP CSP Header Builder  >  Download Download .zip .tar.gz  >  Support forum Support forum  >  Blog Blog  >  RSS 1.0 feed RSS 2.0 feed Latest changes  
Name: PHP CSP Header Builder
Base name: csp-builder
Description: Generate Content Security Policy headers
Version: -
PHP version: 5
License: MIT/X Consortium License
 
  Groups   Applications   Files Files  

  Groups  
Group folder image HTTP HTTP protocol clients, headers and cookies View top rated classes
Group folder image PHP 5 Classes using PHP 5 specific features View top rated classes
Group folder image Security Security protection and attack detection View top rated classes


  Applications that use this package  
No pages of applications that use this class were specified.

Add link image If you know an application of this package, send a message to the author to add a link here.

  Files folder image Files  
File Role Description
Files folder imagebin (3 files)
Files folder imagesrc (1 file)
Files folder imagetest (1 file, 1 directory)
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpcs.xml Data Auxiliary data
Accessible without login Plain text file phpunit.xml.dist Data Auxiliary data
Accessible without login Plain text file psalm.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Read me

  Files folder image Files  /  bin  
File Role Description
  Accessible without login Plain text file compile_apache.php Example Example script
  Accessible without login Plain text file compile_csp.php Example Example script
  Accessible without login Plain text file compile_nginx.php Example Example script

  Files folder image Files  /  src  
File Role Description
  Accessible without login Plain text file CSPBuilder.php Class Class source

  Files folder image Files  /  test  
File Role Description
Files folder imagevectors (4 files)
  Accessible without login Plain text file BasicTest.php Class Class source

  Files folder image Files  /  test  /  vectors  
File Role Description
  Accessible without login Plain text file basic-csp-hash.out Data Auxiliary data
  Accessible without login Plain text file basic-csp-no-old.out Data Auxiliary data
  Accessible without login Plain text file basic-csp.json Data Auxiliary data
  Accessible without login Plain text file basic-csp.out Data Auxiliary data

Download Download all files: csp-builder.tar.gz csp-builder.zip
NOTICE: if you are using a download manager program like 'GetRight', please Login before trying to download this archive.