-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[2.8][WebProfilerBundle] Fix bundle usage in Content-Security-Policy context #18434
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
253 changes: 253 additions & 0 deletions
253
src/Symfony/Bundle/WebProfilerBundle/Csp/ContentSecurityPolicyHandler.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,253 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Bundle\WebProfilerBundle\Csp; | ||
|
||
use Symfony\Component\HttpFoundation\Request; | ||
use Symfony\Component\HttpFoundation\Response; | ||
|
||
/** | ||
* Handles Content-Security-Policy HTTP header for the WebProfiler Bundle. | ||
* | ||
* @author Romain Neutron <imprec@gmail.com> | ||
*/ | ||
class ContentSecurityPolicyHandler | ||
{ | ||
private $nonceGenerator; | ||
|
||
public function __construct(NonceGenerator $nonceGenerator) | ||
{ | ||
return $this->nonceGenerator = $nonceGenerator; | ||
} | ||
|
||
/** | ||
* Returns an array of nonces to be used in Twig templates and Content-Security-Policy headers. | ||
* | ||
* Nonce can be provided by; | ||
* - The request - In case HTML content is fetched via AJAX and inserted in DOM, it must use the same nonce as origin | ||
* - The response - A call to getNonces() has already been done previously. Same nonce are returned | ||
* - They are otherwise randomly generated | ||
* | ||
* @param Request $request | ||
* @param Response $response | ||
* | ||
* @return array | ||
*/ | ||
public function getNonces(Request $request, Response $response) | ||
{ | ||
if ($request->headers->has('X-SymfonyProfiler-Script-Nonce') && $request->headers->has('X-SymfonyProfiler-Style-Nonce')) { | ||
return array( | ||
'csp_script_nonce' => $request->headers->get('X-SymfonyProfiler-Script-Nonce'), | ||
'csp_style_nonce' => $request->headers->get('X-SymfonyProfiler-Style-Nonce'), | ||
); | ||
} | ||
|
||
if ($response->headers->has('X-SymfonyProfiler-Script-Nonce') && $response->headers->has('X-SymfonyProfiler-Style-Nonce')) { | ||
return array( | ||
'csp_script_nonce' => $response->headers->get('X-SymfonyProfiler-Script-Nonce'), | ||
'csp_style_nonce' => $response->headers->get('X-SymfonyProfiler-Style-Nonce'), | ||
); | ||
} | ||
|
||
$nonces = array( | ||
'csp_script_nonce' => $this->generateNonce(), | ||
'csp_style_nonce' => $this->generateNonce(), | ||
); | ||
|
||
$response->headers->set('X-SymfonyProfiler-Script-Nonce', $nonces['csp_script_nonce']); | ||
$response->headers->set('X-SymfonyProfiler-Style-Nonce', $nonces['csp_style_nonce']); | ||
|
||
return $nonces; | ||
} | ||
|
||
/** | ||
* Cleanup temporary headers and updates Content-Security-Policy headers. | ||
* | ||
* This method should be called on KernelEvents::RESPONSE | ||
* | ||
* @param Request $request | ||
* @param Response $response | ||
* | ||
* @return array Nonce used by the bundle in Content-Security-Policy header | ||
*/ | ||
public function onKernelResponse(Request $request, Response $response) | ||
{ | ||
$nonces = $this->getNonces($request, $response); | ||
$this->cleanHeaders($response); | ||
$this->updateCspHeaders($response, $nonces); | ||
|
||
return $nonces; | ||
} | ||
|
||
/** | ||
* @param Response $response | ||
*/ | ||
private function cleanHeaders(Response $response) | ||
{ | ||
$response->headers->remove('X-SymfonyProfiler-Script-Nonce'); | ||
$response->headers->remove('X-SymfonyProfiler-Style-Nonce'); | ||
} | ||
|
||
/** | ||
* Updates Content-Security-Policy headers in a response. | ||
* | ||
* @param Response $response | ||
* @param array $nonces | ||
* | ||
* @return array | ||
*/ | ||
private function updateCspHeaders(Response $response, array $nonces = array()) { | ||
$nonces = array_replace(array( | ||
'csp_script_nonce' => $this->generateNonce(), | ||
'csp_style_nonce' => $this->generateNonce(), | ||
), $nonces); | ||
|
||
$ruleIsSet = false; | ||
|
||
$headers = $this->getCspHeaders($response); | ||
|
||
foreach ($headers as $header => $directives) { | ||
foreach (array('script-src' => 'csp_script_nonce', 'style-src' => 'csp_style_nonce') as $type => $tokenName) { | ||
if (!$this->authorizesInline($directives, $type)) { | ||
if (!isset($headers[$header][$type])) { | ||
if (isset($headers[$header]['default-src'])) { | ||
$headers[$header][$type] = $headers[$header]['default-src']; | ||
} else { | ||
$headers[$header][$type] = array(); | ||
} | ||
} | ||
$ruleIsSet = true; | ||
if (!in_array('\'unsafe-inline\'', $headers[$header][$type], true)) { | ||
$headers[$header][$type][] = '\'unsafe-inline\''; | ||
} | ||
$headers[$header][$type][] = sprintf('\'nonce-%s\'', $nonces[$tokenName]); | ||
} | ||
} | ||
} | ||
|
||
if (!$ruleIsSet) { | ||
return $nonces; | ||
} | ||
|
||
foreach ($headers as $header => $directives) { | ||
$response->headers->set($header, $this->generateCspHeader($directives)); | ||
} | ||
|
||
return $nonces; | ||
} | ||
|
||
/** | ||
* Generates a valid Content-Security-Policy nonce. | ||
* | ||
* @return string | ||
*/ | ||
private function generateNonce() | ||
{ | ||
return $this->nonceGenerator->generate(); | ||
} | ||
|
||
/** | ||
* Converts a directives set array into Content-Security-Policy header. | ||
* | ||
* @param array $directives The directives set | ||
* | ||
* @return string The Content-Security-Policy header | ||
*/ | ||
private function generateCspHeader(array $directives) | ||
{ | ||
return array_reduce(array_keys($directives), function ($res, $name) use ($directives) { | ||
return ($res !== '' ? $res.'; ' : '').sprintf('%s %s', $name, implode(' ', $directives[$name])); | ||
}, ''); | ||
} | ||
|
||
/** | ||
* Converts a Content-Security-Policy header value into a directives set array. | ||
* | ||
* @param string $header The header value | ||
* | ||
* @return array The directives set | ||
*/ | ||
private function parseDirectives($header) { | ||
$directives = array(); | ||
|
||
foreach (explode(';', $header) as $directive) { | ||
$parts = explode(' ', trim($directive)); | ||
if (count($parts) < 1) { | ||
continue; | ||
} | ||
$name = array_shift($parts); | ||
$directives[$name] = $parts; | ||
} | ||
|
||
return $directives; | ||
} | ||
|
||
/** | ||
* Detects if the 'unsafe-inline' is prevented for a directive within the directives set. | ||
* | ||
* @param array $directivesSet The directives set | ||
* @param string $type The name of the directive to check | ||
* | ||
* @return bool | ||
*/ | ||
private function authorizesInline(array $directivesSet, $type) | ||
{ | ||
if (isset($directivesSet[$type])) { | ||
$directives = $directivesSet[$type]; | ||
} elseif (isset($directivesSet['default-src'])) { | ||
$directives = $directivesSet['default-src']; | ||
} else { | ||
return false; | ||
} | ||
|
||
return in_array('\'unsafe-inline\'', $directives, true) && !$this->hasHashOrNonce($directives); | ||
} | ||
|
||
private function hasHashOrNonce(array $directives) | ||
{ | ||
foreach ($directives as $directive) { | ||
if ('\'' !== substr($directive, -1)) { | ||
continue; | ||
} | ||
if ('\'nonce-' === substr($directive, 0, 7)) { | ||
return true; | ||
} | ||
if (in_array(substr($directive, 0, 8), array('\'sha256-', '\'sha384-', '\'sha512-'), true)) { | ||
return true; | ||
} | ||
} | ||
|
||
return false; | ||
} | ||
|
||
/** | ||
* Retrieves the Content-Security-Policy headers (either X-Content-Security-Policy or Content-Security-Policy) from | ||
* a response. | ||
* | ||
* @param Response $response The response | ||
* | ||
* @return array An associative array of headers | ||
*/ | ||
private function getCspHeaders(Response $response) | ||
{ | ||
$headers = array(); | ||
|
||
if ($response->headers->has('Content-Security-Policy')) { | ||
$headers['Content-Security-Policy'] = $this->parseDirectives($response->headers->get('Content-Security-Policy')); | ||
} | ||
|
||
if ($response->headers->has('X-Content-Security-Policy')) { | ||
$headers['X-Content-Security-Policy'] = $this->parseDirectives($response->headers->get('X-Content-Security-Policy')); | ||
} | ||
|
||
return $headers; | ||
} | ||
} |
25 changes: 25 additions & 0 deletions
25
src/Symfony/Bundle/WebProfilerBundle/Csp/NonceGenerator.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Bundle\WebProfilerBundle\Csp; | ||
|
||
/** | ||
* Generates Content-Security-Policy nonce. | ||
* | ||
* @author Romain Neutron <imprec@gmail.com> | ||
*/ | ||
class NonceGenerator | ||
{ | ||
public function generate() | ||
{ | ||
return bin2hex(random_bytes(16)); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
according to your talk at the SymfonyLive right now, wouldn't it be better to use signatures instead ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually this PR provides CSP support for setups where
unsafe-inline
is disabled in development environment (because it only affects the WebProfilerBundle that should not be enabled in prod in any case)So, even if it's recommended to use signature instead of nonce, it's a recommendation for production or staging. In development, it enables user to fully uses test with their CSP and uses the WebProfilerBundle.
So, no, it's not a problem :)