Skip to content

Instantly share code, notes, and snippets.

@andybeak
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andybeak/492ec80040a87153226c to your computer and use it in GitHub Desktop.
Save andybeak/492ec80040a87153226c to your computer and use it in GitHub Desktop.
Adding content security policy (PHP / Apache)
<?php
/**
* addContentSecurityPolicy
*
* Read : https://www.owasp.org/index.php/List_of_useful_HTTP_headers
* https://www.owasp.org/index.php/Content_Security_Policy_Cheat_Sheet
* http://www.html5rocks.com/en/tutorials/security/content-security-policy/
* https://www.owasp.org/index.php/Content_Security_Policy
* http://content-security-policy.com/
*
* Google Analytics requires you to allow 'unsafe-eval' for scripts. Remove this if you
* are using something which does not.
*
* @author Andy Beak
* @date 2014-10-22
* @version 1.0.0
* @access private
*
*/
private function addContentSecurityPolicy()
{
header_remove( 'Content-Security-Policy' );
// I'm explicitly listing them instead of relying on default so that we can think about each one independently
$csp = array(
"default-src 'none'",
"script-src 'self' 'unsafe-inline' https://apis.google.com https://ssl.google-analytics.com 'unsafe-eval'",
"object-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' https://images.cdn.com/",
"media-src 'none'",
"frame-src 'none'",
"font-src 'self'",
"connect-src 'self'",
"form-action 'self'",
"reflected-xss block",
"report-uri /security/csp_reports"
);
$policy = implode( '; ', $csp );
$headers = array(
'X-Content-Type-Options' => 'nosniff', // protect against drive-by download attacks and sites serving user uploaded content that,
// by clever naming, could be treated by MSIE as executable or dynamic HTML files.
'X-XSS-Protection' => '1; mode=block',
'X-Frame-Options' => 'deny',
'Strict-Transport-Security' => 'max-age=631138519',
'Content-Security-Policy' => $policy // when we are ready stop this from being -report-only and enforce the policy
);
foreach( $headers as $header => $value )
{
header( $header . ' : ' . $value );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment