|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Component\Security\Csrf; |
| 13 | + |
| 14 | +use Psr\Log\LoggerInterface; |
| 15 | +use Symfony\Component\HttpFoundation\Request; |
| 16 | +use Symfony\Component\HttpFoundation\RequestStack; |
| 17 | +use Symfony\Component\HttpFoundation\Response; |
| 18 | +use Symfony\Component\HttpFoundation\Session\Session; |
| 19 | +use Symfony\Component\HttpKernel\Event\ResponseEvent; |
| 20 | + |
| 21 | +/** |
| 22 | + * A CSRF token manager that uses a cookie and a header to validate non-persistent tokens. |
| 23 | + * |
| 24 | + * @author Nicolas Grekas <p@tchwork.com> |
| 25 | + */ |
| 26 | +final class DoubleSubmitCsrfTokenManager implements CsrfTokenManagerInterface |
| 27 | +{ |
| 28 | + public const HEADER_NAME = 'x-csrf-token'; |
| 29 | + |
| 30 | + public function __construct( |
| 31 | + private RequestStack $requestStack, |
| 32 | + private ?LoggerInterface $logger = null, |
| 33 | + private string $headerName = self::HEADER_NAME, |
| 34 | + private bool $acceptAsFallback = false, |
| 35 | + ) { |
| 36 | + } |
| 37 | + |
| 38 | + public function getToken(string $tokenId): CsrfToken |
| 39 | + { |
| 40 | + return new CsrfToken($tokenId, $this->headerName); |
| 41 | + } |
| 42 | + |
| 43 | + public function refreshToken(string $tokenId): CsrfToken |
| 44 | + { |
| 45 | + return new CsrfToken($tokenId, $this->headerName); |
| 46 | + } |
| 47 | + |
| 48 | + public function removeToken(string $tokenId): ?string |
| 49 | + { |
| 50 | + return null; |
| 51 | + } |
| 52 | + |
| 53 | + public function isTokenValid(CsrfToken $token): bool |
| 54 | + { |
| 55 | + // This token is not for us |
| 56 | + if ($token->getValue() !== $this->headerName) { |
| 57 | + $this->logger?->debug('CSRF validation failed: Unknown CSRF token.'); |
| 58 | + |
| 59 | + return false; |
| 60 | + } |
| 61 | + |
| 62 | + if (!$request = $this->requestStack->getCurrentRequest()) { |
| 63 | + $this->logger?->debug('CSRF validation failed: No request found.'); |
| 64 | + |
| 65 | + return false; |
| 66 | + } |
| 67 | + |
| 68 | + if (false === $isValidOrigin = $this->isValidOrigin($request)) { |
| 69 | + $this->logger?->debug('CSRF validation failed: Origin doesn\'t match.'); |
| 70 | + |
| 71 | + return false; |
| 72 | + } |
| 73 | + |
| 74 | + if ($this->isValidDoubleSubmit($request)) { |
| 75 | + // Mark the request as validated using double-submit info |
| 76 | + $request->attributes->set($this->headerName, 'double-submit'); |
| 77 | + $this->logger?->debug('CSRF validation accepted using double-submit info.'); |
| 78 | + |
| 79 | + return true; |
| 80 | + } |
| 81 | + |
| 82 | + // Opportunistically lookup at the session for a previous CSRF validation strategy |
| 83 | + $session = $request->hasPreviousSession() ? $request->getSession() : null; |
| 84 | + $usageIndexValue = $session instanceof Session ? $usageIndexReference = &$session->getUsageIndex() : 0; |
| 85 | + $usageIndexReference = \PHP_INT_MIN; |
| 86 | + $csrfProtection = $session?->get($this->headerName); |
| 87 | + $usageIndexReference = $usageIndexValue; |
| 88 | + |
| 89 | + // If a previous request was validated using double-submit info, stick to it |
| 90 | + if ('double-submit' === $csrfProtection) { |
| 91 | + $this->logger?->debug('CSRF validation failed: double-submit info was used in a previous request but didn\'t pass this time.'); |
| 92 | + |
| 93 | + return false; |
| 94 | + } |
| 95 | + |
| 96 | + // If a previous request was validated using origin info, stick to it |
| 97 | + if ('origin' === $csrfProtection && null === $isValidOrigin) { |
| 98 | + $this->logger?->debug('CSRF validation failed: origin info was used in a previous request but didn\'t pass this time.'); |
| 99 | + |
| 100 | + return false; |
| 101 | + } |
| 102 | + |
| 103 | + if (true === $isValidOrigin) { |
| 104 | + // Mark the request as validated using origin info |
| 105 | + $request->attributes->set($this->headerName, 'origin'); |
| 106 | + $this->logger?->debug('CSRF validation accepted using origin info.'); |
| 107 | + |
| 108 | + return true; |
| 109 | + } |
| 110 | + |
| 111 | + if ($this->acceptAsFallback) { |
| 112 | + $this->logger?->debug('CSRF validation accepted despite the absence of double-submit and origin info.'); |
| 113 | + |
| 114 | + return true; |
| 115 | + } |
| 116 | + |
| 117 | + $this->logger?->debug('CSRF validation failed: double-submit and origin info not found.'); |
| 118 | + |
| 119 | + return false; |
| 120 | + } |
| 121 | + |
| 122 | + public function clearCookie(Request $request, Response $response): void |
| 123 | + { |
| 124 | + $cookieName = ($request->isSecure() ? '__Host-' : '').$this->headerName; |
| 125 | + |
| 126 | + if (!$request->cookies->has($cookieName)) { |
| 127 | + $response->headers->clearCookie($cookieName, '/', null, $request->isSecure(), false, 'strict'); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + public function persistStrategy(Request $request): void |
| 132 | + { |
| 133 | + if ($request->hasSession(true) && $request->attributes->has($this->headerName)) { |
| 134 | + $request->getSession()->set($this->headerName, $request->attributes->get($this->headerName)); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + public function onKernelResponse(ResponseEvent $event): void |
| 139 | + { |
| 140 | + if (!$event->isMainRequest()) { |
| 141 | + return; |
| 142 | + } |
| 143 | + |
| 144 | + $this->clearCookie($event->getRequest(), $event->getResponse()); |
| 145 | + $this->persistStrategy($event->getRequest()); |
| 146 | + } |
| 147 | + |
| 148 | + /** |
| 149 | + * @return bool|null Whether the origin is valid, null if missing |
| 150 | + */ |
| 151 | + private function isValidOrigin(Request $request): ?bool |
| 152 | + { |
| 153 | + $source = $request->headers->get('Origin') ?? $request->headers->get('Referer') ?? 'null'; |
| 154 | + |
| 155 | + return 'null' === $source ? null : str_starts_with($source.'/', $request->getScheme().'://'.$request->getHttpHost().'/'); |
| 156 | + } |
| 157 | + |
| 158 | + private function isValidDoubleSubmit(Request $request): bool |
| 159 | + { |
| 160 | + $token = $request->headers->get($this->headerName); |
| 161 | + |
| 162 | + if (!\is_string($token) || \strlen($token) < 32) { |
| 163 | + return $token; |
| 164 | + } |
| 165 | + |
| 166 | + $cookieName = ($request->isSecure() ? '__Host-' : '').$this->headerName; |
| 167 | + |
| 168 | + return dump($request->cookies->get($cookieName) === $token); |
| 169 | + } |
| 170 | +} |
0 commit comments