TwoFactorMiddleware.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. /** @var Manager */
  46. private $twoFactorManager;
  47. /** @var Session */
  48. private $userSession;
  49. /** @var ISession */
  50. private $session;
  51. /** @var IURLGenerator */
  52. private $urlGenerator;
  53. /** @var IControllerMethodReflector */
  54. private $reflector;
  55. /** @var IRequest */
  56. private $request;
  57. /**
  58. * @param Manager $twoFactorManager
  59. * @param Session $userSession
  60. * @param ISession $session
  61. * @param IURLGenerator $urlGenerator
  62. */
  63. public function __construct(Manager $twoFactorManager, Session $userSession, ISession $session,
  64. IURLGenerator $urlGenerator, IControllerMethodReflector $reflector, IRequest $request) {
  65. $this->twoFactorManager = $twoFactorManager;
  66. $this->userSession = $userSession;
  67. $this->session = $session;
  68. $this->urlGenerator = $urlGenerator;
  69. $this->reflector = $reflector;
  70. $this->request = $request;
  71. }
  72. /**
  73. * @param Controller $controller
  74. * @param string $methodName
  75. */
  76. public function beforeController($controller, $methodName) {
  77. if ($this->reflector->hasAnnotation('NoTwoFactorRequired')) {
  78. // Route handler explicitly marked to work without finished 2FA are
  79. // not blocked
  80. return;
  81. }
  82. if ($controller instanceof APIController && $methodName === 'poll') {
  83. // Allow polling the twofactor nextcloud notifications state
  84. return;
  85. }
  86. if ($controller instanceof TwoFactorChallengeController
  87. && $this->userSession->getUser() !== null
  88. && !$this->reflector->hasAnnotation('TwoFactorSetUpDoneRequired')) {
  89. $providers = $this->twoFactorManager->getProviderSet($this->userSession->getUser());
  90. if (!($providers->getPrimaryProviders() === [] && !$providers->isProviderMissing())) {
  91. throw new TwoFactorAuthRequiredException();
  92. }
  93. }
  94. if ($controller instanceof ALoginSetupController
  95. && $this->userSession->getUser() !== null
  96. && $this->twoFactorManager->needsSecondFactor($this->userSession->getUser())) {
  97. $providers = $this->twoFactorManager->getProviderSet($this->userSession->getUser());
  98. if ($providers->getPrimaryProviders() === [] && !$providers->isProviderMissing()) {
  99. return;
  100. }
  101. }
  102. if ($controller instanceof LoginController && $methodName === 'logout') {
  103. // Don't block the logout page, to allow canceling the 2FA
  104. return;
  105. }
  106. if ($this->userSession->isLoggedIn()) {
  107. $user = $this->userSession->getUser();
  108. if ($this->session->exists('app_password') // authenticated using an app password
  109. || $this->session->exists('app_api') // authenticated using an AppAPI Auth
  110. || $this->twoFactorManager->isTwoFactorAuthenticated($user)) {
  111. $this->checkTwoFactor($controller, $methodName, $user);
  112. } elseif ($controller instanceof TwoFactorChallengeController) {
  113. // Allow access to the two-factor controllers only if two-factor authentication
  114. // is in progress.
  115. throw new UserAlreadyLoggedInException();
  116. }
  117. }
  118. // TODO: dont check/enforce 2FA if a auth token is used
  119. }
  120. private function checkTwoFactor(Controller $controller, $methodName, IUser $user) {
  121. // If two-factor auth is in progress disallow access to any controllers
  122. // defined within "LoginController".
  123. $needsSecondFactor = $this->twoFactorManager->needsSecondFactor($user);
  124. $twoFactor = $controller instanceof TwoFactorChallengeController;
  125. // Disallow access to any controller if 2FA needs to be checked
  126. if ($needsSecondFactor && !$twoFactor) {
  127. throw new TwoFactorAuthRequiredException();
  128. }
  129. // Allow access to the two-factor controllers only if two-factor authentication
  130. // is in progress.
  131. if (!$needsSecondFactor && $twoFactor) {
  132. throw new UserAlreadyLoggedInException();
  133. }
  134. }
  135. public function afterException($controller, $methodName, Exception $exception) {
  136. if ($exception instanceof TwoFactorAuthRequiredException) {
  137. $params = [];
  138. if (isset($this->request->server['REQUEST_URI'])) {
  139. $params['redirect_url'] = $this->request->server['REQUEST_URI'];
  140. }
  141. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', $params));
  142. }
  143. if ($exception instanceof UserAlreadyLoggedInException) {
  144. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
  145. }
  146. throw $exception;
  147. }
  148. }