Build Content-Security-Policy headers from a JSON file (or build them programmatically)
Build Content-Security-Policy headers from a JSON file (or build them programmatically)
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.
First, get Composer, then run:
composer require paragonie/csp-buildersendCSPHeader();
You can also load the configuration from a JSON string, like so:
sendCSPHeader();
Finally, you can just pass an array to the first argument of the constructor:
sendCSPHeader();
…nonce('script-src');
$body .= "
";
// 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()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);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.
$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
If your company uses this library in their products or services, you may be interested in purchasing a support contract from Paragon Initiative Enterprises.
No open issues yet, or sync has not completed.