TwoFactorMiddleware.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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') // authenticated using an app password
  91. || $this->session->exists('app_api') // authenticated using an AppAPI Auth
  92. || $this->twoFactorManager->isTwoFactorAuthenticated($user)) {
  93. $this->checkTwoFactor($controller, $methodName, $user);
  94. } elseif ($controller instanceof TwoFactorChallengeController) {
  95. // Allow access to the two-factor controllers only if two-factor authentication
  96. // is in progress.
  97. throw new UserAlreadyLoggedInException();
  98. }
  99. }
  100. // TODO: dont check/enforce 2FA if a auth token is used
  101. }
  102. private function checkTwoFactor(Controller $controller, $methodName, IUser $user) {
  103. // If two-factor auth is in progress disallow access to any controllers
  104. // defined within "LoginController".
  105. $needsSecondFactor = $this->twoFactorManager->needsSecondFactor($user);
  106. $twoFactor = $controller instanceof TwoFactorChallengeController;
  107. // Disallow access to any controller if 2FA needs to be checked
  108. if ($needsSecondFactor && !$twoFactor) {
  109. throw new TwoFactorAuthRequiredException();
  110. }
  111. // Allow access to the two-factor controllers only if two-factor authentication
  112. // is in progress.
  113. if (!$needsSecondFactor && $twoFactor) {
  114. throw new UserAlreadyLoggedInException();
  115. }
  116. }
  117. public function afterException($controller, $methodName, Exception $exception) {
  118. if ($exception instanceof TwoFactorAuthRequiredException) {
  119. $params = [
  120. 'redirect_url' => $this->request->getParam('redirect_url'),
  121. ];
  122. if (!isset($params['redirect_url']) && isset($this->request->server['REQUEST_URI'])) {
  123. $params['redirect_url'] = $this->request->server['REQUEST_URI'];
  124. }
  125. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', $params));
  126. }
  127. if ($exception instanceof UserAlreadyLoggedInException) {
  128. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
  129. }
  130. throw $exception;
  131. }
  132. }