From 6789092ada8f5c1e807e7010cea7a9d2adc279c1 Mon Sep 17 00:00:00 2001 From: Bruno Meilick Date: Fri, 3 Aug 2018 20:45:11 +0200 Subject: [PATCH] added proper nonces implementation Signed-off-by: Bruno Meilick --- classes/securityheaders.php | 11 +++++++++++ composer.json | 2 +- config.php | 9 +++++++++ snippets/securityheaders.php | 10 ++++++++-- 4 files changed, 29 insertions(+), 3 deletions(-) diff --git a/classes/securityheaders.php b/classes/securityheaders.php index 5b249fc..4c7b5f9 100644 --- a/classes/securityheaders.php +++ b/classes/securityheaders.php @@ -28,6 +28,17 @@ public static function headers($headers) } } + private static $nonces = null; + public static function nonce($string, $value = null) { + if(!static::$nonces) { + static::$nonces = []; + } + if($value && is_string($value)) { + static::$nonces[$string] = $value; + } + return \Kirby\Toolkit\A::get(static::$nonces, $string); + } + private static function isWebpack() { return !!( diff --git a/composer.json b/composer.json index a70728a..de35c51 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "bnomei/kirby3-security-headers", "type": "plugin", - "version": "0.5.6", + "version": "0.5.7", "license": "MIT", "description": "Kirby 3 Plugin for easier Security Headers setup", "autoload": { diff --git a/config.php b/config.php index 4985f32..2c11bb6 100644 --- a/config.php +++ b/config.php @@ -16,5 +16,14 @@ ], 'snippets' => [ 'plugin-securityheaders' => __DIR__ . '/snippets/securityheaders.php', + ], + 'pageMethods' => [ + 'nonce' => function($string) { + $n = \Bnomei\SecurityHeaders::nonce($string); + if($n) { + $n = 'nonce="'.$n.'"'; + } + return $n; + } ] ]); diff --git a/snippets/securityheaders.php b/snippets/securityheaders.php index 8717ce9..fea773a 100644 --- a/snippets/securityheaders.php +++ b/snippets/securityheaders.php @@ -19,8 +19,14 @@ foreach ($directives as $d) { $policy->addSourceSet($d, $sourcesetID); } -foreach (option('bnomei.securityheaders.nounces', []) as $n) { - $policy->addNonce(ContentSecurityPolicyHeaderBuilder::DIRECTIVE_SCRIPT_SRC, $n); +$nc = ['loadjs.min.js', 'loadjs.min.js-fn', 'webfontloader.js']; // https://github.com/bnomei/kirby3-htmlhead +$nc = array_merge($nc, option('bnomei.securityheaders.nounces', [])); +foreach ($nc as $id) { + $nonceArr = [$id, time(), \filemtime(__FILE__), kirby()->roots()->assets()]; + shuffle($nonceArr); + $nonce = 'nonce-'.base64_encode(sha1(implode('', $nonceArr))); + \Bnomei\SecurityHeaders::nonce($id, $nonce); + $policy->addNonce(ContentSecurityPolicyHeaderBuilder::DIRECTIVE_SCRIPT_SRC, $nonce); } foreach (option('bnomei.securityheaders.hashes', []) as $h) { $policy->addHash(ContentSecurityPolicyHeaderBuilder::HASH_SHA_256, $h);