TwoFactorMiddleware.php 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Core\Middleware;
  9. use Exception;
  10. use OC\Authentication\Exceptions\TwoFactorAuthRequiredException;
  11. use OC\Authentication\Exceptions\UserAlreadyLoggedInException;
  12. use OC\Authentication\TwoFactorAuth\Manager;
  13. use OC\Core\Controller\LoginController;
  14. use OC\Core\Controller\TwoFactorChallengeController;
  15. use OC\User\Session;
  16. use OCA\TwoFactorNextcloudNotification\Controller\APIController;
  17. use OCP\AppFramework\Controller;
  18. use OCP\AppFramework\Http\RedirectResponse;
  19. use OCP\AppFramework\Middleware;
  20. use OCP\AppFramework\Utility\IControllerMethodReflector;
  21. use OCP\Authentication\TwoFactorAuth\ALoginSetupController;
  22. use OCP\IRequest;
  23. use OCP\ISession;
  24. use OCP\IURLGenerator;
  25. use OCP\IUser;
  26. class TwoFactorMiddleware extends Middleware {
  27. public function __construct(
  28. private Manager $twoFactorManager,
  29. private Session $userSession,
  30. private ISession $session,
  31. private IURLGenerator $urlGenerator,
  32. private IControllerMethodReflector $reflector,
  33. private IRequest $request,
  34. ) {
  35. }
  36. /**
  37. * @param Controller $controller
  38. * @param string $methodName
  39. */
  40. public function beforeController($controller, $methodName) {
  41. if ($this->reflector->hasAnnotation('NoTwoFactorRequired')) {
  42. // Route handler explicitly marked to work without finished 2FA are
  43. // not blocked
  44. return;
  45. }
  46. if ($controller instanceof APIController && $methodName === 'poll') {
  47. // Allow polling the twofactor nextcloud notifications state
  48. return;
  49. }
  50. if ($controller instanceof TwoFactorChallengeController
  51. && $this->userSession->getUser() !== null
  52. && !$this->reflector->hasAnnotation('TwoFactorSetUpDoneRequired')) {
  53. $providers = $this->twoFactorManager->getProviderSet($this->userSession->getUser());
  54. if (!($providers->getPrimaryProviders() === [] && !$providers->isProviderMissing())) {
  55. throw new TwoFactorAuthRequiredException();
  56. }
  57. }
  58. if ($controller instanceof ALoginSetupController
  59. && $this->userSession->getUser() !== null
  60. && $this->twoFactorManager->needsSecondFactor($this->userSession->getUser())) {
  61. $providers = $this->twoFactorManager->getProviderSet($this->userSession->getUser());
  62. if ($providers->getPrimaryProviders() === [] && !$providers->isProviderMissing()) {
  63. return;
  64. }
  65. }
  66. if ($controller instanceof LoginController && $methodName === 'logout') {
  67. // Don't block the logout page, to allow canceling the 2FA
  68. return;
  69. }
  70. if ($this->userSession->isLoggedIn()) {
  71. $user = $this->userSession->getUser();
  72. if ($this->session->exists('app_password') // authenticated using an app password
  73. || $this->session->exists('app_api') // authenticated using an AppAPI Auth
  74. || $this->twoFactorManager->isTwoFactorAuthenticated($user)) {
  75. $this->checkTwoFactor($controller, $methodName, $user);
  76. } elseif ($controller instanceof TwoFactorChallengeController) {
  77. // Allow access to the two-factor controllers only if two-factor authentication
  78. // is in progress.
  79. throw new UserAlreadyLoggedInException();
  80. }
  81. }
  82. // TODO: dont check/enforce 2FA if a auth token is used
  83. }
  84. private function checkTwoFactor(Controller $controller, $methodName, IUser $user) {
  85. // If two-factor auth is in progress disallow access to any controllers
  86. // defined within "LoginController".
  87. $needsSecondFactor = $this->twoFactorManager->needsSecondFactor($user);
  88. $twoFactor = $controller instanceof TwoFactorChallengeController;
  89. // Disallow access to any controller if 2FA needs to be checked
  90. if ($needsSecondFactor && !$twoFactor) {
  91. throw new TwoFactorAuthRequiredException();
  92. }
  93. // Allow access to the two-factor controllers only if two-factor authentication
  94. // is in progress.
  95. if (!$needsSecondFactor && $twoFactor) {
  96. throw new UserAlreadyLoggedInException();
  97. }
  98. }
  99. public function afterException($controller, $methodName, Exception $exception) {
  100. if ($exception instanceof TwoFactorAuthRequiredException) {
  101. $params = [
  102. 'redirect_url' => $this->request->getParam('redirect_url'),
  103. ];
  104. if (!isset($params['redirect_url']) && isset($this->request->server['REQUEST_URI'])) {
  105. $params['redirect_url'] = $this->request->server['REQUEST_URI'];
  106. }
  107. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', $params));
  108. }
  109. if ($exception instanceof UserAlreadyLoggedInException) {
  110. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
  111. }
  112. throw $exception;
  113. }
  114. }