vendor/symfony/security-http/Firewall/SwitchUserListener.php line 42

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Security\Http\Firewall;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpKernel\Event\RequestEvent;
  16. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  17. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  18. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  19. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  20. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  21. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  22. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  23. use Symfony\Component\Security\Core\Role\SwitchUserRole;
  24. use Symfony\Component\Security\Core\User\UserCheckerInterface;
  25. use Symfony\Component\Security\Core\User\UserInterface;
  26. use Symfony\Component\Security\Core\User\UserProviderInterface;
  27. use Symfony\Component\Security\Http\Event\SwitchUserEvent;
  28. use Symfony\Component\Security\Http\SecurityEvents;
  29. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  30. /**
  31.  * SwitchUserListener allows a user to impersonate another one temporarily
  32.  * (like the Unix su command).
  33.  *
  34.  * @author Fabien Potencier <fabien@symfony.com>
  35.  *
  36.  * @final since Symfony 4.3
  37.  */
  38. class SwitchUserListener extends AbstractListener implements ListenerInterface
  39. {
  40.     use LegacyListenerTrait;
  41.     const EXIT_VALUE '_exit';
  42.     private $tokenStorage;
  43.     private $provider;
  44.     private $userChecker;
  45.     private $providerKey;
  46.     private $accessDecisionManager;
  47.     private $usernameParameter;
  48.     private $role;
  49.     private $logger;
  50.     private $dispatcher;
  51.     private $stateless;
  52.     public function __construct(TokenStorageInterface $tokenStorageUserProviderInterface $providerUserCheckerInterface $userCheckerstring $providerKeyAccessDecisionManagerInterface $accessDecisionManagerLoggerInterface $logger nullstring $usernameParameter '_switch_user'string $role 'ROLE_ALLOWED_TO_SWITCH'EventDispatcherInterface $dispatcher nullbool $stateless false)
  53.     {
  54.         if (empty($providerKey)) {
  55.             throw new \InvalidArgumentException('$providerKey must not be empty.');
  56.         }
  57.         $this->tokenStorage $tokenStorage;
  58.         $this->provider $provider;
  59.         $this->userChecker $userChecker;
  60.         $this->providerKey $providerKey;
  61.         $this->accessDecisionManager $accessDecisionManager;
  62.         $this->usernameParameter $usernameParameter;
  63.         $this->role $role;
  64.         $this->logger $logger;
  65.         $this->dispatcher LegacyEventDispatcherProxy::decorate($dispatcher);
  66.         $this->stateless $stateless;
  67.     }
  68.     /**
  69.      * {@inheritdoc}
  70.      */
  71.     public function supports(Request $request): ?bool
  72.     {
  73.         // usernames can be falsy
  74.         $username $request->get($this->usernameParameter);
  75.         if (null === $username || '' === $username) {
  76.             $username $request->headers->get($this->usernameParameter);
  77.         }
  78.         // if it's still "empty", nothing to do.
  79.         if (null === $username || '' === $username) {
  80.             return false;
  81.         }
  82.         $request->attributes->set('_switch_user_username'$username);
  83.         return true;
  84.     }
  85.     /**
  86.      * Handles the switch to another user.
  87.      *
  88.      * @throws \LogicException if switching to a user failed
  89.      */
  90.     public function authenticate(RequestEvent $event)
  91.     {
  92.         $request $event->getRequest();
  93.         $username $request->attributes->get('_switch_user_username');
  94.         $request->attributes->remove('_switch_user_username');
  95.         if (null === $this->tokenStorage->getToken()) {
  96.             throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
  97.         }
  98.         if (self::EXIT_VALUE === $username) {
  99.             $this->tokenStorage->setToken($this->attemptExitUser($request));
  100.         } else {
  101.             try {
  102.                 $this->tokenStorage->setToken($this->attemptSwitchUser($request$username));
  103.             } catch (AuthenticationException $e) {
  104.                 // Generate 403 in any conditions to prevent user enumeration vulnerabilities
  105.                 throw new AccessDeniedException('Switch User failed: '.$e->getMessage(), $e);
  106.             }
  107.         }
  108.         if (!$this->stateless) {
  109.             $request->query->remove($this->usernameParameter);
  110.             $request->server->set('QUERY_STRING'http_build_query($request->query->all(), '''&'));
  111.             $response = new RedirectResponse($request->getUri(), 302);
  112.             $event->setResponse($response);
  113.         }
  114.     }
  115.     /**
  116.      * Attempts to switch to another user and returns the new token if successfully switched.
  117.      *
  118.      * @throws \LogicException
  119.      * @throws AccessDeniedException
  120.      */
  121.     private function attemptSwitchUser(Request $requeststring $username): ?TokenInterface
  122.     {
  123.         $token $this->tokenStorage->getToken();
  124.         $originalToken $this->getOriginalToken($token);
  125.         if (null !== $originalToken) {
  126.             if ($token->getUsername() === $username) {
  127.                 return $token;
  128.             }
  129.             throw new \LogicException(sprintf('You are already switched to "%s" user.'$token->getUsername()));
  130.         }
  131.         $currentUsername $token->getUsername();
  132.         $nonExistentUsername '_'.md5(random_bytes(8).$username);
  133.         // To protect against user enumeration via timing measurements
  134.         // we always load both successfully and unsuccessfully
  135.         try {
  136.             $user $this->provider->loadUserByUsername($username);
  137.             try {
  138.                 $this->provider->loadUserByUsername($nonExistentUsername);
  139.             } catch (AuthenticationException $e) {
  140.             }
  141.         } catch (AuthenticationException $e) {
  142.             $this->provider->loadUserByUsername($currentUsername);
  143.             throw $e;
  144.         }
  145.         if (false === $this->accessDecisionManager->decide($token, [$this->role], $user)) {
  146.             $exception = new AccessDeniedException();
  147.             $exception->setAttributes($this->role);
  148.             throw $exception;
  149.         }
  150.         if (null !== $this->logger) {
  151.             $this->logger->info('Attempting to switch to user.', ['username' => $username]);
  152.         }
  153.         $this->userChecker->checkPostAuth($user);
  154.         $roles $user->getRoles();
  155.         $roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN'$this->tokenStorage->getToken(), false);
  156.         $token = new SwitchUserToken($user$user->getPassword(), $this->providerKey$roles$token);
  157.         if (null !== $this->dispatcher) {
  158.             $switchEvent = new SwitchUserEvent($request$token->getUser(), $token);
  159.             $this->dispatcher->dispatch($switchEventSecurityEvents::SWITCH_USER);
  160.             // use the token from the event in case any listeners have replaced it.
  161.             $token $switchEvent->getToken();
  162.         }
  163.         return $token;
  164.     }
  165.     /**
  166.      * Attempts to exit from an already switched user and returns the original token.
  167.      *
  168.      * @throws AuthenticationCredentialsNotFoundException
  169.      */
  170.     private function attemptExitUser(Request $request): TokenInterface
  171.     {
  172.         if (null === ($currentToken $this->tokenStorage->getToken()) || null === $original $this->getOriginalToken($currentToken)) {
  173.             throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
  174.         }
  175.         if (null !== $this->dispatcher && $original->getUser() instanceof UserInterface) {
  176.             $user $this->provider->refreshUser($original->getUser());
  177.             $switchEvent = new SwitchUserEvent($request$user$original);
  178.             $this->dispatcher->dispatch($switchEventSecurityEvents::SWITCH_USER);
  179.             $original $switchEvent->getToken();
  180.         }
  181.         return $original;
  182.     }
  183.     private function getOriginalToken(TokenInterface $token): ?TokenInterface
  184.     {
  185.         if ($token instanceof SwitchUserToken) {
  186.             return $token->getOriginalToken();
  187.         }
  188.         foreach ($token->getRoles(false) as $role) {
  189.             if ($role instanceof SwitchUserRole) {
  190.                 return $role->getSource();
  191.             }
  192.         }
  193.         return null;
  194.     }
  195. }