src/EventSubscriber/TrustedDeviceSubscriber.php line 239

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace MedBrief\MSR\EventSubscriber;
  4. use DateTimeImmutable;
  5. use MedBrief\MSR\Entity\User;
  6. use MedBrief\MSR\Repository\UserRepository;
  7. use MedBrief\MSR\Service\TrustedDevice\BrowserSession;
  8. use MedBrief\MSR\Service\TrustedDevice\Enforcement;
  9. use MedBrief\MSR\Service\TrustedDevice\Stage;
  10. use MedBrief\MSR\Service\TrustedDevice\StageCoordinator;
  11. use MedBrief\MSR\Service\TrustedDevice\Verification\VerificationService;
  12. use Override;
  13. use Psr\Log\LoggerInterface;
  14. use Scheb\TwoFactorBundle\Security\Authentication\Token\TwoFactorTokenInterface;
  15. use Scheb\TwoFactorBundle\Security\Http\Authenticator\Passport\TwoFactorPassport;
  16. use Scheb\TwoFactorBundle\Security\Http\Authenticator\TwoFactorAuthenticator;
  17. use Scheb\TwoFactorBundle\Security\TwoFactor\Event\TwoFactorAuthenticationEvent;
  18. use Scheb\TwoFactorBundle\Security\TwoFactor\Event\TwoFactorAuthenticationEvents;
  19. use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
  20. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  21. use Symfony\Component\HttpFoundation\JsonResponse;
  22. use Symfony\Component\HttpFoundation\RedirectResponse;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpFoundation\RequestStack;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Component\HttpKernel\Event\RequestEvent;
  27. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  28. use Symfony\Component\HttpKernel\KernelEvents;
  29. use Symfony\Component\Routing\RouterInterface;
  30. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  31. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  32. use Symfony\Component\Security\Http\SecurityEvents;
  33. use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
  34. use Symfony\Component\Security\Http\Event\LogoutEvent;
  35. use Symfony\Component\Security\Http\Event\SwitchUserEvent;
  36. use Throwable;
  37. final class TrustedDeviceSubscriber implements EventSubscriberInterface
  38. {
  39. /** Named routes that can complete a mandatory local MFA stage. */
  40. private const array MFA_ROUTES = [
  41. 'mfa_enable_force', 'mfa_generate_initial_codes', 'auth_app_enable', 'email_mfa_enable',
  42. 'duo_enroll', 'duo_authenticate',
  43. ];
  44. /** Wire the main-firewall gate with its session, challenge and routing dependencies. */
  45. public function __construct(
  46. private readonly FirewallMap $firewalls,
  47. private readonly RequestStack $requests,
  48. private readonly TokenStorageInterface $tokens,
  49. private readonly Enforcement $enforcement,
  50. private readonly StageCoordinator $coordinator,
  51. private readonly BrowserSession $browserSession,
  52. private readonly VerificationService $verification,
  53. private readonly RouterInterface $router,
  54. private readonly LoggerInterface $logger,
  55. private readonly UserRepository $users,
  56. ) {
  57. }
  58. /** Register the stage gate and the authentication and session lifecycle handlers. */
  59. #[Override]
  60. public static function getSubscribedEvents(): array
  61. {
  62. return [
  63. KernelEvents::REQUEST => [['hideDisabledRoutes', 20], ['gateRequest', 6]],
  64. LoginSuccessEvent::class => ['resetOnLogin', -32],
  65. LogoutEvent::class => ['cancelOnLogout', 64],
  66. SecurityEvents::SWITCH_USER => ['checkSwitch', 64],
  67. TwoFactorAuthenticationEvents::COMPLETE => ['recordMfa', 32],
  68. ];
  69. }
  70. /** Hide the feature's routes after routing and before firewall or controller processing. */
  71. public function hideDisabledRoutes(RequestEvent $event): void
  72. {
  73. $route = $event->getRequest()->attributes->get('_route');
  74. if (!$this->enforcement->isFeatureEnabled() && is_string($route) && str_starts_with($route, 'trusted_device_')) {
  75. $event->setResponse(new Response('Not Found', Response::HTTP_NOT_FOUND, ['Cache-Control' => 'no-store']));
  76. }
  77. }
  78. /** Apply the required sign-in stage to requests on eligible main browser sessions. */
  79. public function gateRequest(RequestEvent $event): void
  80. {
  81. $request = $event->getRequest();
  82. $mainRequest = $this->requests->getMainRequest() ?? $request;
  83. if ($this->firewalls->getFirewallConfig($mainRequest)?->getName() !== 'main') {
  84. return;
  85. }
  86. $route = $request->attributes->get('_route');
  87. if ($event->isMainRequest() && in_array($route, ['logout', 'MedBriefMSRBundle_medbrief_inactivity_login_redirect'], true)) {
  88. return;
  89. }
  90. $token = $this->tokens->getToken();
  91. $activeImpersonation = $this->enforcement->isActive() && $token instanceof SwitchUserToken;
  92. $actor = $activeImpersonation ? $this->originalUser($token) : $token?->getUser();
  93. if ($activeImpersonation && (!$actor instanceof User || !$actor->isEnabled() || !$actor->isAccountNonLocked())) {
  94. $event->setResponse(new Response('The original administrator session is unavailable.', 403, ['Cache-Control' => 'no-store']));
  95. return;
  96. }
  97. if (!$actor instanceof User) {
  98. return;
  99. }
  100. if (!$this->enforcement->appliesToAccount($actor)) {
  101. $this->restartStagedSignIn($event, $mainRequest);
  102. return;
  103. }
  104. if ($token instanceof TwoFactorTokenInterface) {
  105. if (!$event->isMainRequest() || !in_array($route, ['2fa_login', '2fa_login_check'], true)) {
  106. $this->restrict($event, $this->router->generate('2fa_login'));
  107. }
  108. return;
  109. }
  110. try {
  111. $stage = $this->coordinator->stage($mainRequest, $actor, new DateTimeImmutable());
  112. } catch (Throwable) {
  113. $this->logger->error('Trusted Device stage resolution failed.');
  114. $event->setResponse(new Response('Security verification is temporarily unavailable.', 503, ['Cache-Control' => 'no-store']));
  115. return;
  116. }
  117. if ($token instanceof SwitchUserToken && ($stage !== Stage::Complete
  118. || in_array($route, ['trusted_device_stage', 'trusted_device_action'], true)
  119. )) {
  120. $event->setResponse(new Response('Security verification is unavailable during impersonation.', 403, ['Cache-Control' => 'no-store']));
  121. return;
  122. }
  123. // The staged page replaces the legacy modal during an applicable rollout.
  124. if ($mainRequest->hasSession()) {
  125. $session = $mainRequest->getSession();
  126. $session->set(BrowserSession::STAGED_SIGN_IN, true);
  127. foreach (['pending-policies', 'pending-policies-detail', 'policy_redirect_needed', 'policy_redirect_url'] as $key) {
  128. $session->remove($key);
  129. }
  130. }
  131. if ($stage === Stage::Complete) {
  132. if (in_array($route, ['user_policy_accept_policies', 'user_policy_decline_policies'], true)) {
  133. $event->setResponse(new Response('Use the current policy verification screen.', 403, ['Cache-Control' => 'no-store']));
  134. }
  135. return;
  136. }
  137. if ($event->isMainRequest()) {
  138. if ($stage === Stage::MfaSetup && in_array($route, self::MFA_ROUTES, true)) {
  139. $request->attributes->set('_trusted_device_mfa_setup', true);
  140. $request->getSession()->set('_trusted_device_mfa_setup', true);
  141. return;
  142. }
  143. if ($stage !== Stage::MfaSetup && in_array($route, ['trusted_device_stage', 'trusted_device_action'], true)) {
  144. return;
  145. }
  146. if ($request->isMethodSafe() && !$request->isXmlHttpRequest() && $request->getPreferredFormat() === 'html'
  147. && $request->hasSession() && !$request->getSession()->has(BrowserSession::TARGET)
  148. ) {
  149. $target = $this->coordinator->safeTarget($request, $request->getRequestUri());
  150. if ($target !== null) {
  151. $request->getSession()->set(BrowserSession::TARGET, $target);
  152. }
  153. }
  154. }
  155. $next = $stage === Stage::MfaSetup
  156. ? ($actor->hasEnabledMfa() ? 'mfa_generate_initial_codes' : 'mfa_enable_force')
  157. : 'trusted_device_stage';
  158. $this->restrict($event, $this->router->generate($next));
  159. }
  160. /** Restart sign-in after leaving a rollout that took over legacy policy checks. */
  161. private function restartStagedSignIn(RequestEvent $event, Request $mainRequest): void
  162. {
  163. if (!$mainRequest->hasSession()) {
  164. return;
  165. }
  166. $session = $mainRequest->getSession();
  167. if ($session->has(BrowserSession::STAGED_SIGN_IN) || $session->has(BrowserSession::FLOW)
  168. || $session->has(BrowserSession::BINDING) || $session->has(BrowserSession::TARGET)) {
  169. $event->setResponse(new RedirectResponse($this->router->generate('logout'), Response::HTTP_SEE_OTHER, ['Cache-Control' => 'no-store']));
  170. }
  171. }
  172. /** Reset authority on primary sign-in and preserve safe continuation through completed MFA. */
  173. public function resetOnLogin(LoginSuccessEvent $event): void
  174. {
  175. $request = $event->getRequest();
  176. $token = $event->getAuthenticatedToken();
  177. $user = $token->getUser();
  178. if ($event->getFirewallName() !== 'main' || !$user instanceof User || !$request->hasSession()) {
  179. return;
  180. }
  181. $session = $request->getSession();
  182. $isMfaLogin = $event->getPassport() instanceof TwoFactorPassport || $event->getAuthenticator() instanceof TwoFactorAuthenticator;
  183. if (!$isMfaLogin) {
  184. $this->browserSession->clear($session);
  185. $session->remove('_trusted_device_mfa_setup');
  186. $session->remove('_trusted_device_mfa_email_requested');
  187. if ($this->enforcement->isFeatureEnabled()) {
  188. $session->set(BrowserSession::ORIGINAL_MFA, $user->hasEnabledMfa() ? $user->getId() : null);
  189. }
  190. }
  191. if (!$this->enforcement->appliesToAccount($user)) {
  192. return;
  193. }
  194. $response = $event->getResponse();
  195. if ($response instanceof RedirectResponse && !$token instanceof TwoFactorTokenInterface) {
  196. $target = $this->coordinator->safeTarget($request, $response->getTargetUrl());
  197. if ($target !== null) {
  198. $session->set(BrowserSession::TARGET, $target);
  199. } elseif ($isMfaLogin || $response->getTargetUrl() !== $this->router->generate('mfa_enable_force')) {
  200. $response->setTargetUrl($this->router->generate('trusted_device_stage'));
  201. }
  202. if ($isMfaLogin && !$user->hasBackupCodes()) {
  203. $session->set(BrowserSession::BACKUP_CODES_REMINDER, $user->getId());
  204. $response->setTargetUrl($this->router->generate('trusted_device_stage'));
  205. }
  206. }
  207. }
  208. /** Record eligible existing MFA assurance for subsequent browser stages. */
  209. public function recordMfa(TwoFactorAuthenticationEvent $event): void
  210. {
  211. $user = $event->getToken()->getUser();
  212. $request = $event->getRequest();
  213. if ($this->enforcement->isFeatureEnabled() && $user instanceof User && $request->hasSession()
  214. && $request->getSession()->get(BrowserSession::ORIGINAL_MFA) === $user->getId()
  215. ) {
  216. $request->getSession()->set(BrowserSession::ASSURANCE, [$user->getId(), $user->getTrustedDeviceGeneration(), time()]);
  217. }
  218. }
  219. /** Cancel session-bound challenges and remove Trusted Device session state during logout. */
  220. public function cancelOnLogout(LogoutEvent $event): void
  221. {
  222. $request = $event->getRequest();
  223. $user = $event->getToken()?->getUser();
  224. if (!$user instanceof User || !$request->hasSession() || $event->getToken() instanceof SwitchUserToken) {
  225. return;
  226. }
  227. $flow = $request->getSession()->get(BrowserSession::FLOW);
  228. $mobileFlow = $request->getSession()->get(\MedBrief\MSR\Service\TrustedDevice\MobileChange::FLOW);
  229. if (is_string($flow)) {
  230. try {
  231. $this->verification->cancelFlow($user->getId(), $flow);
  232. } catch (Throwable) {
  233. $this->logger->warning('Unable to clear Trusted Device challenges during sign-out.');
  234. }
  235. }
  236. if ($mobileFlow instanceof \MedBrief\MSR\Dto\TrustedDevice\MobileChangeFlow && $mobileFlow->ownerId === $user->getId()) {
  237. try {
  238. $this->verification->cancelFlow($user->getId(), $mobileFlow->id);
  239. } catch (Throwable) {
  240. $this->logger->warning('Unable to clear mobile number challenges during sign-out.');
  241. }
  242. }
  243. $this->browserSession->clear($request->getSession());
  244. }
  245. /** Check the original administrator's authority before switching users. */
  246. public function checkSwitch(SwitchUserEvent $event): void
  247. {
  248. $token = $event->getToken();
  249. if (!$this->enforcement->isActive() || !$token instanceof SwitchUserToken) {
  250. return;
  251. }
  252. $actor = $this->originalUser($token);
  253. $subject = $event->getTargetUser();
  254. if (!$actor instanceof User || !$actor->isEnabled() || !$actor->isAccountNonLocked()
  255. || !$subject instanceof User || !$subject->isEnabled() || !$subject->isAccountNonLocked()
  256. ) {
  257. throw new AccessDeniedHttpException('The current impersonation request is unavailable.');
  258. }
  259. if ($this->enforcement->appliesToAccount($actor)
  260. && $this->coordinator->stage($event->getRequest(), $actor, new DateTimeImmutable()) !== Stage::Complete
  261. ) {
  262. throw new AccessDeniedHttpException('Complete security verification before impersonating another user.');
  263. }
  264. }
  265. /** Read the original administrator from the server-authenticated switch token. */
  266. private function originalUser(SwitchUserToken $token): ?User
  267. {
  268. $original = $token->getOriginalToken()->getUser();
  269. return $original instanceof User ? $this->users->find($original->getId()) : null;
  270. }
  271. /** Redirect navigations or return the existing structured denial for other requests. */
  272. private function restrict(RequestEvent $event, string $next): void
  273. {
  274. $request = $event->getRequest();
  275. if (!$event->isMainRequest() || !$request->isMethodSafe() || $request->isXmlHttpRequest()
  276. || $request->getPreferredFormat() === 'json' || $request->attributes->has('_api_resource_class')
  277. ) {
  278. $response = new JsonResponse([
  279. 'success' => false,
  280. 'error' => [
  281. 'code' => 'TRUSTED_DEVICE_VERIFICATION_REQUIRED',
  282. 'message' => 'Please complete security verification before continuing.',
  283. 'next' => $next,
  284. ],
  285. ], 403);
  286. } else {
  287. $response = new RedirectResponse($next);
  288. }
  289. $response->headers->set('Cache-Control', 'no-store');
  290. $event->setResponse($response);
  291. }
  292. }