• Stars
    star
    543
  • Rank 81,848 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 9 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Build Content-Security-Policy headers from a JSON file (or build them programmatically)

Content Security Policy Builder

Build Status Psalm Status Latest Stable Version Latest Unstable Version License Downloads

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-to": "PolicyName",
    "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.

Processing output before save to disk through hook

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

The output will change before save to file

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.

More Repositories

1

random_compat

PHP 5.x support for random_bytes() and random_int()
PHP
8,170
star
2

awesome-appsec

A curated list of resources for learning about application security
PHP
6,305
star
3

paseto

Platform-Agnostic Security Tokens
PHP
3,248
star
4

halite

High-level cryptography interface powered by libsodium
PHP
1,124
star
5

sodium_compat

Pure PHP polyfill for ext/sodium
PHP
894
star
6

constant_time_encoding

Constant-Time Character Encoding in PHP Projects
PHP
816
star
7

easydb

Easy-to-use PDO wrapper for PHP projects.
PHP
736
star
8

chronicle

Public append-only ledger microservice built with Slim Framework
PHP
469
star
9

ciphersweet

Fast, searchable field-level encryption for PHP projects
PHP
436
star
10

airship

Secure Content Management for the Modern Web - "The sky is only the beginning"
PHP
418
star
11

sapient

Secure API Toolkit
PHP
314
star
12

anti-csrf

Full-Featured Anti-CSRF Library
PHP
297
star
13

certainty

Automated cacert.pem management for PHP projects
PHP
262
star
14

EasyRSA

Simple and Secure Wrapper for phpseclib
PHP
198
star
15

password_lock

Wraps Bcrypt-SHA2 in Authenticated Encryption
PHP
190
star
16

sodium-plus

Developer-friendly libsodium interface
JavaScript
171
star
17

multi_factor

Vendor-Agnostic Two-Factor Authentication
PHP
142
star
18

gpg-mailer

GnuPG-encrypted emails made easy
PHP
96
star
19

pecl-libsodium-doc

Free Online Documentation for the Libsodium PHP Extension
88
star
20

typed-arrays

Userland typed array implementation
PHP
74
star
21

ciphersweet-js

Searchable Encryption for Node.js projects
JavaScript
65
star
22

hidden-string

The HiddenString class extracted from Halite.
PHP
64
star
23

corner

Exceptions and Errors made more user-friendly
PHP
62
star
24

paseto-io

Paseto Website
Twig
58
star
25

iaso

Powerful JSON Toolkit, includes a JSON parser immune to Hash-DoS attacks
PHP
51
star
26

easy-ecc

High-Level Usability Wrapper for PHPECC
PHP
44
star
27

hpkp-builder

Build HTTP Public-Key-Pinning headers from a JSON file (or build them programmatically)
PHP
41
star
28

seedspring

Seeded, Deterministic PRNG (based on AES-CTR instead of LCG)
PHP
39
star
29

passwdqc

Password/passphrase strength checking and enforcement (PHP port)
PHP
39
star
30

pharaoh

Utility to quickly and effectively diff two PHP Archives
PHP
36
star
31

libgossamer

Public Key Infrastructure without Certificate Authorities, for WordPress and Packagist
PHP
33
star
32

ionizer

Input Filter System for PHP Software
PHP
32
star
33

easydb-cache

EasyDB with Prepared Statement Caching
PHP
30
star
34

argon2-refiner

Generate Parameter Recommendations for Argon2id in PHP 7.3+
PHP
25
star
35

bsidesorl-2017

Supplementary Material for Building Defensible Solutions to Weird Problems
PHP
23
star
36

blakechain

Hash chains built with BLAKE2b
PHP
22
star
37

quill

Library for quickly and easily writing data to a Chronicle instance
PHP
21
star
38

stern

Stern lets you built type-safe PHP projects, even if your project's users aren't writing type-safe code
PHP
21
star
39

herd

Hash-Ensured Replicated Database
PHP
16
star
40

eloquent-ciphersweet

Bridge library between Eloquent ORM and CipherSweet
PHP
14
star
41

discretion

On-demand and reusable contact forms that only send GnuPG-encrypted messages to your inbox.
PHP
13
star
42

xchacha20-js

JavaScript implementation of ChaCha20, HChaCha20, and XChaCha20
JavaScript
12
star
43

pco_prototype

PCO - PHP Crypto Objects
PHP
12
star
44

paserk-php

PHP Implementation of PASERK
PHP
12
star
45

slim-sapient

Slim Framework Adapter for Sapient
PHP
10
star
46

airship-docs

Documentation for CMS Airship
Nginx
10
star
47

php-jwt-guard

Security Defense for Firebase's PHP-JWT Library
PHP
9
star
48

zend-diactoros-sapient

Zend Diactoros Adapter for Sapient
PHP
8
star
49

phone-to-pick

Whitelist Your Incoming Phone Calls (for Android)
Java
7
star
50

gossamer-server

Standalone Gossamer server
PHP
5
star
51

poly1305-js

JavaScript implementation of the Poly1305 one-time authenticator
JavaScript
5
star
52

paseto-browser.js

PASETO in the Web Browser
JavaScript
4
star
53

airship-barge

Build Gadgets for Airship projects (Command Line Interface)
PHP
3
star
54

monolog-quill

A Monolog Handler for writing to a Chronicle instance
PHP
3
star
55

sodium-jvm

Pure-Java implementation of the Sodium cryptography library.
3
star
56

blogpost-translations

Translations of Paragon Initiative Enterprise blog posts
2
star
57

ward-docs

Online Documentation for Ward (Web Application Realtime Defender)
2
star
58

php71_crypto

Pluggable Cryptography Interface for PHP 7.1
2
star
59

ristretto-php

Implements a type-safe API for working with the Ristretto Group in PHP projects.
PHP
2
star
60

node-halite

High-level cryptography interface powered by node-sodium
1
star
61

pie-hosted.com

Source code for the pie-hosted.com website
PHP
1
star
62

halite-legacy

Legacy versions of Halite to facilitate migrations from older ciphersuites to the latest supported version
PHP
1
star
63

certainty-js

Certainty-js: Automated CACert.pem Management for Node.js Software
JavaScript
1
star