Skip to content

[Security][CSRF] Added CSRF CookieStorageInterface #33171

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
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,19 @@ private function addCsrfSection(ArrayNodeDefinition $rootNode)
->treatTrueLike(['enabled' => true])
->treatNullLike(['enabled' => true])
->addDefaultsIfNotSet()
->beforeNormalization()
->ifArray()
->then(function ($v) {
$v['enabled'] = isset($v['enabled']) ? $v['enabled'] : true;

return $v;
})
->end()
->children()
// defaults to framework.session.enabled && !class_exists(FullStack::class) && interface_exists(CsrfTokenManagerInterface::class)
->booleanNode('enabled')->defaultNull()->end()
// defaults to session if framework.session.enabled, cookie otherwise
->scalarNode('storage')->defaultNull()->end()
->end()
->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@
use Symfony\Component\Routing\Matcher\Dumper\PhpMatcherDumper;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Csrf\EventListener\CookieTokenStorageListener;
use Symfony\Component\Security\Csrf\TokenStorage\CookieTokenStorage;
use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;
use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata;
Expand Down Expand Up @@ -257,8 +260,11 @@ public function load(array $configs, ContainerBuilder $container)
$this->registerRequestConfiguration($config['request'], $container, $loader);
}

if (null === $config['csrf_protection']['storage']) {
$config['csrf_protection']['storage'] = $this->sessionConfigEnabled || !class_exists(CookieTokenStorage::class) ? 'session' : 'cookie';
}
if (null === $config['csrf_protection']['enabled']) {
$config['csrf_protection']['enabled'] = $this->sessionConfigEnabled && !class_exists(FullStack::class) && interface_exists(CsrfTokenManagerInterface::class);
$config['csrf_protection']['enabled'] = ($this->sessionConfigEnabled || 'session' !== $config['csrf_protection']['storage']) && !class_exists(FullStack::class) && interface_exists(CsrfTokenManagerInterface::class);
}
$this->registerSecurityCsrfConfiguration($config['csrf_protection'], $container, $loader);

Expand Down Expand Up @@ -1450,12 +1456,31 @@ private function registerSecurityCsrfConfiguration(array $config, ContainerBuild
throw new LogicException('CSRF support cannot be enabled as the Security CSRF component is not installed. Try running "composer require symfony/security-csrf".');
}

if (!$this->sessionConfigEnabled) {
throw new \LogicException('CSRF protection needs sessions to be enabled.');
}

// Enable services for CSRF protection (even without forms)
$loader->load('security_csrf.xml');
switch ($config['storage']) {
case 'session':
if (!$this->sessionConfigEnabled) {
throw new \LogicException('CSRF protection needs sessions to be enabled.');
}

$container->setAlias('security.csrf.token_storage', SessionTokenStorage::class);
break;
case 'cookie':
if (!class_exists(CookieTokenStorage::class)) {
throw new LogicException('CSRF support with Cookie Storage is not installed. Try running "composer require symfony/security-csrf:^4.4".');
}

$container->setAlias('security.csrf.token_storage', CookieTokenStorage::class);
break;
default:
$container->setAlias('security.csrf.token_storage', $config['storage']);
break;
}

if ('cookie' !== $config['storage']) {
$container->removeDefinition(CookieTokenStorageListener::class);
}

if (!class_exists(CsrfExtension::class)) {
$container->removeDefinition('twig.extension.security_csrf');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@

<xsd:complexType name="csrf_protection">
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="storage" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="esi">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,17 @@
<service id="security.csrf.token_generator" class="Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator" />
<service id="Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface" alias="security.csrf.token_generator" />

<service id="security.csrf.token_storage" class="Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage">
<service id="Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage">
<argument type="service" id="session" />
</service>
<service id="Symfony\Component\Security\Csrf\TokenStorage\CookieTokenStorage">
<argument type="service" id="request_stack" />
<argument>%kernel.secret%</argument>
</service>
<service id="Symfony\Component\Security\Csrf\EventListener\CookieTokenStorageListener">
<argument type="service" id="security.csrf.token_storage"/>
<tag name="kernel.event_subscriber" />
</service>
<service id="Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface" alias="security.csrf.token_storage" />

<service id="security.csrf.token_manager" class="Symfony\Component\Security\Csrf\CsrfTokenManager" public="true">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,8 @@ protected static function getBundleDefaultConfig()
'ide' => null,
'default_locale' => 'en',
'csrf_protection' => [
'enabled' => false,
'enabled' => null,
'storage' => null,
],
'form' => [
'enabled' => !class_exists(FullStack::class),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

$container->loadFromExtension('framework', [
'session' => false,
'csrf_protection' => [
'enabled' => true,
],
]);
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

$container->loadFromExtension('framework', [
'csrf_protection' => [
'enabled' => true,
'storage' => 'session',
],
]);
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

<framework:config>
<framework:csrf-protection />
</framework:config>
</container>
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

<framework:config>
<framework:csrf-protection />
<framework:csrf-protection storage="session"/>
</framework:config>
</container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
framework:
csrf_protection: ~
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
framework:
csrf_protection: ~
csrf_protection:
storage: session
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage;
use Symfony\Component\Messenger\Transport\TransportFactory;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Security\Csrf\TokenStorage\CookieTokenStorage;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader;
use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader;
Expand Down Expand Up @@ -131,6 +132,16 @@ public function testCsrfProtectionNeedsSessionToBeEnabled()
$this->createContainerFromFile('csrf_needs_session');
}

public function testCsrfProtectionFallbackToCookie()
{
if (!class_exists(CookieTokenStorage::class)) {
$this->markTestSkipped('Cookie storage requires symfony/security 4.4+');
}
$container = $this->createContainerFromFile('csrf_fallback_to_cookie');

$this->assertSame(CookieTokenStorage::class, (string) $container->getAlias('security.csrf.token_storage'));
}

public function testCsrfProtectionForFormsEnablesCsrfProtectionAutomatically()
{
$container = $this->createContainerFromFile('csrf');
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Security/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ CHANGELOG
for "guard" authenticators that deal with user passwords
* Marked all dispatched event classes as `@final`
* Deprecated returning a non-boolean value when implementing `Guard\AuthenticatorInterface::checkCredentials()`.
* Added `CookieTokenStorage`

4.3.0
-----
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?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\Component\Security\Csrf\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Csrf\TokenStorage\CookieTokenStorage;

/**
* Inject transient cookies in the response.
*
* @author Oliver Hoff <oliver@hofff.com>
* @author Jérémy Derussé <jeremy@derusse.com>
*/
class CookieTokenStorageListener implements EventSubscriberInterface
{
private $cookieTokenStorage;

public function __construct(CookieTokenStorage $cookieTokenStorage)
{
$this->cookieTokenStorage = $cookieTokenStorage;
}

public function onKernelResponse(ResponseEvent $event)
{
$this->cookieTokenStorage->sendCookies($event->getResponse());
}

/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?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\Component\Security\Csrf\Exception;

use Symfony\Component\Security\Core\Exception\RuntimeException as CoreRuntimeException;

/**
* @author Jérémy Derussé <jeremy@derusse.com>
*/
class RuntimeException extends CoreRuntimeException
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@

namespace Symfony\Component\Security\Csrf\Exception;

use Symfony\Component\Security\Core\Exception\RuntimeException;

/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
Expand Down
Loading