8000 [Security] Implement stateless headers/cookies-based CSRF protection by nicolas-grekas · Pull Request #58095 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Security] Implement stateless headers/cookies-based CSRF protection #58095

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

Merged
merged 1 commit into from
Oct 8, 2024
Merged
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
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ CHANGELOG
* Deprecate making `cache.app` adapter taggable, use the `cache.app.taggable` adapter instead
* Enable `json_decode_detailed_errors` in the default serializer context in debug mode by default when `seld/jsonlint` is installed
* Register `Symfony\Component\Serializer\NameConverter\SnakeCaseToCamelCaseNameConverter` as a service named `serializer.name_converter.snake_case_to_camel_case` if available
* Add `framework.csrf_protection.stateless_token_ids`, `.cookie_name`, and `.check_header` options to use stateless headers/cookies-based CSRF protection
* Add `framework.form.csrf_protection.field_attr` option
* Deprecate `session.sid_length` and `session.sid_bits_per_character` config options
* Add the ability to use an existing service as a lock/semaphore resource
* Add support for configuring multiple serializer instances via the configuration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,22 @@
->treatTrueLike(['enabled' => true])
->treatNullLike(['enabled' => true])
->addDefaultsIfNotSet()
->fixXmlConfig('stateless_token_id')
->children()
// defaults to framework.session.enabled && !class_exists(FullStack::class) && interface_exists(CsrfTokenManagerInterface::class)
->booleanNode('enabled')->defaultNull()->end()
// defaults to framework.csrf_protection.stateless_token_ids || framework.session.enabled && !class_exists(FullStack::class) && interface_exists(CsrfTokenManagerInterface::class)
->scalarNode('enabled')->defaultNull()->end()
->arrayNode('stateless_token_ids')

Check failure on line 216 in src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php

View workflow job for this annotation

GitHub Actions / Psalm

UndefinedInterfaceMethod

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php:216:27: UndefinedInterfaceMethod: Method Symfony\Component\Config\Definition\Builder\NodeParentInterface::arrayNode does not exist (see https://psalm.dev/181)

Check failure on line 216 in src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php

View workflow job for this annotation

GitHub Actions / Psalm

UndefinedInterfaceMethod

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php:216:27: UndefinedInterfaceMethod: Method Symfony\Component\Config\Definition\Builder\NodeParentInterface::arrayNode does not exist (see https://psalm.dev/181)
->scalarPrototype()->end()
->info('Enable headers/cookies-based CSRF validation for the listed token ids.')
->end()
->scalarNode('check_header')
->defaultFalse()
->info('Whether to check the CSRF token in a header in addition to a cookie when using stateless protection.')
->end()
->scalarNode('cookie_name')
->defaultValue('csrf-token')
->info('The name of the cookie to use when using stateless protection.')
->end()
->end()
->end()
->end()
Expand All @@ -232,8 +245,14 @@
->treatNullLike(['enabled' => true])
->addDefaultsIfNotSet()
->children()
->booleanNode('enabled')->defaultNull()->end() // defaults to framework.csrf_protection.enabled
->scalarNode('enabled')->defaultNull()->end() // defaults to framework.csrf_protection.enabled
->scalarNode('token_id')->defaultNull()->end()
->scalarNode('field_name')->defaultValue('_token')->end()
->arrayNode('field_attr')
->performNoDeepMerging()
->scalarPrototype()->end()
->defaultValue(['data-controller' => 'csrf-protection'])
->end()
->end()
->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ public function load(array $configs, ContainerBuilder $container): void

// csrf depends on session being registered
if (null === $config['csrf_protection']['enabled']) {
$this->writeConfigEnabled('csrf_protection', $this->readConfigEnabled('session', $container, $config['session']) && !class_exists(FullStack::class) && ContainerBuilder::willBeAvailable('symfony/security-csrf', CsrfTokenManagerInterface::class, ['symfony/framework-bundle']), $config['csrf_protection']);
$this->writeConfigEnabled('csrf_protection', $config['csrf_protection']['stateless_token_ids'] || $this->readConfigEnabled('session', $container, $config['session']) && !class_exists(FullStack::class) && ContainerBuilder::willBeAvailable('symfony/security-csrf', CsrfTokenManagerInterface::class, ['symfony/framework-bundle']), $config['csrf_protection']);
}
$this->registerSecurityCsrfConfiguration($config['csrf_protection'], $container, $loader);

Expand Down Expand Up @@ -765,6 +765,10 @@ private function registerFormConfiguration(array $config, ContainerBuilder $cont

$container->setParameter('form.type_extension.csrf.enabled', true);
$container->setParameter('form.type_extension.csrf.field_name', $config['form']['csrf_protection']['field_name']);
$container->setParameter('form.type_extension.csrf.field_attr', $config['form']['csrf_protection']['field_attr']);

$container->getDefinition('form.type_extension.csrf')
->replaceArgument(7, $config['form']['csrf_protection']['token_id']);
} else {
$container->setParameter('form.type_extension.csrf.enabled', false);
}
Expand Down Expand Up @@ -1815,8 +1819,7 @@ private function registerSecurityCsrfConfiguration(array $config, ContainerBuild
if (!class_exists(\Symfony\Component\Security\Csrf\CsrfToken::class)) {
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->isInitializedConfigEnabled('session')) {
if (!$config['stateless_token_ids'] && !$this->isInitializedConfigEnabled('session')) {
throw new \LogicException('CSRF protection needs sessions to be enabled.');
}

Expand All @@ -1826,6 +1829,24 @@ private function registerSecurityCsrfConfiguration(array $config, ContainerBuild
if (!class_exists(CsrfExtension::class)) {
$container->removeDefinition('twig.extension.security_csrf');
}

if (!$config['stateless_token_ids']) {
$container->removeDefinition('security.csrf.same_origin_token_manager');

return;
}

$container->getDefinition('security.csrf.same_origin_token_manager')
->replaceArgument(3, $config['stateless_token_ids'])
->replaceArgument(4, $config['check_header'])
->replaceArgument(5, $config['cookie_name']);

if (!$this->isInitializedConfigEnabled('session')) {
$container->setAlias('security.csrf.token_manager', 'security.csrf.same_origin_token_manager');
$container->getDefinition('security.csrf.same_origin_token_manager')
->setDecoratedService(null)
->replaceArgument(2, null);
}
}

private function registerSerializerConfiguration(array $config, ContainerBuilder $container, PhpFileLoader $loader): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
service('translator')->nullOnInvalid(),
param('validator.translation_domain'),
service('form.server_params'),
param('form.type_extension.csrf.field_attr'),
abstract_arg('framework.form.csrf_protection.token_id'),
])
->tag('form.type_extension')
;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,25 @@
</xsd:complexType>

<xsd:complexType name="form_csrf_protection">
<xsd:sequence>
<xsd:element name="field-attr" type="field_attr" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="token-id" type="xsd:string" />
<xsd:attribute name="field-name" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="field_attr">
<xsd:attribute name="name" type="xsd:string" use="required"/>
</xsd:complexType>

<xsd:complexType name="csrf_protection">
<xsd:sequence>
<xsd:element name="stateless-token-id" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="check-header" type="xsd:string" />
<xsd:attribute name="cookie-name" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="esi">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Bridge\Twig\Extension\CsrfRuntime;
use Symfony\Component\Security\Csrf\CsrfTokenManager;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Csrf\SameOriginCsrfTokenManager;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;
use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;
Expand Down Expand Up @@ -46,5 +47,18 @@

->set('twig.extension.security_csrf', CsrfExtension::class)
->tag('twig.extension')

->set('security.csrf.same_origin_token_manager', SameOriginCsrfTokenManager::class)
->decorate('security.csrf.token_manager')
->args([
service('request_stack'),
service('logger')->nullOnInvalid(),
service('.inner'),
abstract_arg('framework.csrf_protection.stateless_token_ids'),
abstract_arg('framework.csrf_protection.check_header'),
abstract_arg('framework.csrf_protection.cookie_name'),
])
->tag('monolog.logger', ['channel' => 'request'])
->tag('kernel.event_listener', ['event' => 'kernel.response', 'method' => 'onKernelResponse'])
;
};
Original file line number Diff line number Diff line change
Expand Up @@ -715,13 +715,18 @@ protected static function getBundleDefaultConfig()
'trusted_proxies' => ['%env(default::SYMFONY_TRUSTED_PROXIES)%'],
'trusted_headers' => ['%env(default::SYMFONY_TRUSTED_HEADERS)%'],
'csrf_protection' => [
'enabled' => false,
'enabled' => null,
'cookie_name' => 'csrf-token',
'check_header' => false,
'stateless_token_ids' => [],
],
'form' => [
'enabled' => !class_exists(FullStack::class),
'csrf_protection' => [
'enabled' => null, // defaults to csrf_protection.enabled
'field_name' => '_token',
'field_attr' => ['data-controller' => 'csrf-protection'],
'token_id' => null,
],
],
'esi' => ['enabled' => false],
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@
"symfony/runtime": "<6.4.13|>=7.0,<7.1.6",
"symfony/scheduler": "<6.4.4|>=7.0.0,<7.0.4",
"symfony/serializer": "<6.4",
"symfony/security-csrf": "<6.4",
"symfony/security-csrf": "<7.2",
"symfony/security-core": "<6.4",
"symfony/stopwatch": "<6.4",
"symfony/translation": "<6.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Util\ServerParams;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
Expand All @@ -35,6 +36,8 @@ public function __construct(
private ?TranslatorInterface $translator = null,
private ?string $translationDomain = null,
private ?ServerParams $serverParams = null,
private array $fieldAttr = [],
private ?string $defaultTokenId = null,
) {
}

Expand Down Expand Up @@ -73,6 +76,7 @@ public function finishView(FormView $view, FormInterface $form, array $options):
$csrfForm = $factory->createNamed($options['csrf_field_name'], HiddenType::class, $data, [
'block_prefix' => 'csrf_token',
'mapped' => false,
'attr' => $this->fieldAttr + ['autocomplete' => 'off'],
Copy link
Member
@GromNaN GromNaN Dec 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The autocomplete attribute with value off on an hidden field seems invalid: #59294

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see #59296

]);

$view->children[$options['csrf_field_name']] = $csrfForm->createView($view);
Expand All @@ -81,13 +85,24 @@ public function finishView(FormView $view, FormInterface $form, array $options):

public function configureOptions(OptionsResolver $resolver): void
{
if ($defaultTokenId = $this->defaultTokenId) {
$defaultTokenManager = $this->defaultTokenManager;
$defaultTokenId = static fn (Options $options) => $options['csrf_token_manager'] === $defaultTokenManager ? $defaultTokenId : null;
}

$resolver->setDefaults([
'csrf_protection' => $this->defaultEnabled,
'csrf_field_name' => $this->defaultFieldName,
'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.',
'csrf_token_manager' => $this->defaultTokenManager,
'csrf_token_id' => null,
'csrf_token_id' => $defaultTokenId,
]);

$resolver->setAllowedTypes('csrf_protection', 'bool');
$resolver->setAllowedTypes('csrf_field_name', 'string');
$resolver->setAllowedTypes('csrf_message', 'string');
$resolver->setAllowedTypes('csrf_token_manager', CsrfTokenManagerInterface::class);
$resolver->setAllowedTypes('csrf_token_id', ['null', 'string']);
}

public static function getExtendedTypes(): iterable
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Security/Csrf/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

7.2
---

* Add `SameOriginCsrfTokenManager`

6.0
---

Expand Down
Loading
Loading
0