TwoFactorMiddleware.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\Core\Middleware;
  27. use Exception;
  28. use OC\Authentication\Exceptions\TwoFactorAuthRequiredException;
  29. use OC\Authentication\Exceptions\UserAlreadyLoggedInException;
  30. use OC\Authentication\TwoFactorAuth\Manager;
  31. use OC\Core\Controller\LoginController;
  32. use OC\Core\Controller\TwoFactorChallengeController;
  33. use OC\User\Session;
  34. use OCA\TwoFactorNextcloudNotification\Controller\APIController;
  35. use OCP\AppFramework\Controller;
  36. use OCP\AppFramework\Http\RedirectResponse;
  37. use OCP\AppFramework\Middleware;
  38. use OCP\AppFramework\Utility\IControllerMethodReflector;
  39. use OCP\Authentication\TwoFactorAuth\ALoginSetupController;
  40. use OCP\IRequest;
  41. use OCP\ISession;
  42. use OCP\IURLGenerator;
  43. use OCP\IUser;
  44. class TwoFactorMiddleware extends Middleware {
  45. public function __construct(
  46. private Manager $twoFactorManager,
  47. private Session $userSession,
  48. private ISession $session,
  49. private IURLGenerator $urlGenerator,
  50. private IControllerMethodReflector $reflector,
  51. private IRequest $request,
  52. ) {
  53. }
  54. /**
  55. * @param Controller $controller
  56. * @param string $methodName
  57. */
  58. public function beforeController($controller, $methodName) {
  59. if ($this->reflector->hasAnnotation('NoTwoFactorRequired')) {
  60. // Route handler explicitly marked to work without finished 2FA are
  61. // not blocked
  62. return;
  63. }
  64. if ($controller instanceof APIController && $methodName === 'poll') {
  65. // Allow polling the twofactor nextcloud notifications state
  66. return;
  67. }
  68. if ($controller instanceof TwoFactorChallengeController
  69. && $this->userSession->getUser() !== null
  70. && !$this->reflector->hasAnnotation('TwoFactorSetUpDoneRequired')) {
  71. $providers = $this->twoFactorManager->getProviderSet($this->userSession->getUser());
  72. if (!($providers->getPrimaryProviders() === [] && !$providers->isProviderMissing())) {
  73. throw new TwoFactorAuthRequiredException();
  74. }
  75. }
  76. if ($controller instanceof ALoginSetupController
  77. && $this->userSession->getUser() !== null
  78. && $this->twoFactorManager->needsSecondFactor($this->userSession->getUser())) {
  79. $providers = $this->twoFactorManager->getProviderSet($this->userSession->getUser());
  80. if ($providers->getPrimaryProviders() === [] && !$providers->isProviderMissing()) {
  81. return;
  82. }
  83. }
  84. if ($controller instanceof LoginController && $methodName === 'logout') {
  85. // Don't block the logout page, to allow canceling the 2FA
  86. return;
  87. }
  88. if ($this->userSession->isLoggedIn()) {
  89. $user = $this->userSession->getUser();
  90. if ($this->session->exists('app_password') || $this->twoFactorManager->isTwoFactorAuthenticated($user)) {
  91. $this->checkTwoFactor($controller, $methodName, $user);
  92. } elseif ($controller instanceof TwoFactorChallengeController) {
  93. // Allow access to the two-factor controllers only if two-factor authentication
  94. // is in progress.
  95. throw new UserAlreadyLoggedInException();
  96. }
  97. }
  98. // TODO: dont check/enforce 2FA if a auth token is used
  99. }
  100. private function checkTwoFactor(Controller $controller, $methodName, IUser $user) {
  101. // If two-factor auth is in progress disallow access to any controllers
  102. // defined within "LoginController".
  103. $needsSecondFactor = $this->twoFactorManager->needsSecondFactor($user);
  104. $twoFactor = $controller instanceof TwoFactorChallengeController;
  105. // Disallow access to any controller if 2FA needs to be checked
  106. if ($needsSecondFactor && !$twoFactor) {
  107. throw new TwoFactorAuthRequiredException();
  108. }
  109. // Allow access to the two-factor controllers only if two-factor authentication
  110. // is in progress.
  111. if (!$needsSecondFactor && $twoFactor) {
  112. throw new UserAlreadyLoggedInException();
  113. }
  114. }
  115. public function afterException($controller, $methodName, Exception $exception) {
  116. if ($exception instanceof TwoFactorAuthRequiredException) {
  117. $params = [];
  118. if (isset($this->request->server['REQUEST_URI'])) {
  119. $params['redirect_url'] = $this->request->server['REQUEST_URI'];
  120. }
  121. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', $params));
  122. }
  123. if ($exception instanceof UserAlreadyLoggedInException) {
  124. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
  125. }
  126. throw $exception;
  127. }
  128. }