TwoFactorChallengeController.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Core\Controller;
  8. use OC\Authentication\TwoFactorAuth\Manager;
  9. use OC_User;
  10. use OCP\AppFramework\Controller;
  11. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  12. use OCP\AppFramework\Http\Attribute\OpenAPI;
  13. use OCP\AppFramework\Http\Attribute\UseSession;
  14. use OCP\AppFramework\Http\RedirectResponse;
  15. use OCP\AppFramework\Http\StandaloneTemplateResponse;
  16. use OCP\Authentication\TwoFactorAuth\IActivatableAtLogin;
  17. use OCP\Authentication\TwoFactorAuth\IProvider;
  18. use OCP\Authentication\TwoFactorAuth\IProvidesCustomCSP;
  19. use OCP\Authentication\TwoFactorAuth\TwoFactorException;
  20. use OCP\IRequest;
  21. use OCP\ISession;
  22. use OCP\IURLGenerator;
  23. use OCP\IUserSession;
  24. use Psr\Log\LoggerInterface;
  25. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  26. class TwoFactorChallengeController extends Controller {
  27. public function __construct(
  28. string $appName,
  29. IRequest $request,
  30. private Manager $twoFactorManager,
  31. private IUserSession $userSession,
  32. private ISession $session,
  33. private IURLGenerator $urlGenerator,
  34. private LoggerInterface $logger,
  35. ) {
  36. parent::__construct($appName, $request);
  37. }
  38. /**
  39. * @return string
  40. */
  41. protected function getLogoutUrl() {
  42. return OC_User::getLogoutUrl($this->urlGenerator);
  43. }
  44. /**
  45. * @param IProvider[] $providers
  46. */
  47. private function splitProvidersAndBackupCodes(array $providers): array {
  48. $regular = [];
  49. $backup = null;
  50. foreach ($providers as $provider) {
  51. if ($provider->getId() === 'backup_codes') {
  52. $backup = $provider;
  53. } else {
  54. $regular[] = $provider;
  55. }
  56. }
  57. return [$regular, $backup];
  58. }
  59. /**
  60. * @NoAdminRequired
  61. * @NoCSRFRequired
  62. * @TwoFactorSetUpDoneRequired
  63. *
  64. * @param string $redirect_url
  65. * @return StandaloneTemplateResponse
  66. */
  67. #[FrontpageRoute(verb: 'GET', url: '/login/selectchallenge')]
  68. public function selectChallenge($redirect_url) {
  69. $user = $this->userSession->getUser();
  70. $providerSet = $this->twoFactorManager->getProviderSet($user);
  71. $allProviders = $providerSet->getProviders();
  72. [$providers, $backupProvider] = $this->splitProvidersAndBackupCodes($allProviders);
  73. $setupProviders = $this->twoFactorManager->getLoginSetupProviders($user);
  74. $data = [
  75. 'providers' => $providers,
  76. 'backupProvider' => $backupProvider,
  77. 'providerMissing' => $providerSet->isProviderMissing(),
  78. 'redirect_url' => $redirect_url,
  79. 'logout_url' => $this->getLogoutUrl(),
  80. 'hasSetupProviders' => !empty($setupProviders),
  81. ];
  82. return new StandaloneTemplateResponse($this->appName, 'twofactorselectchallenge', $data, 'guest');
  83. }
  84. /**
  85. * @NoAdminRequired
  86. * @NoCSRFRequired
  87. * @TwoFactorSetUpDoneRequired
  88. *
  89. * @param string $challengeProviderId
  90. * @param string $redirect_url
  91. * @return StandaloneTemplateResponse|RedirectResponse
  92. */
  93. #[UseSession]
  94. #[FrontpageRoute(verb: 'GET', url: '/login/challenge/{challengeProviderId}')]
  95. public function showChallenge($challengeProviderId, $redirect_url) {
  96. $user = $this->userSession->getUser();
  97. $providerSet = $this->twoFactorManager->getProviderSet($user);
  98. $provider = $providerSet->getProvider($challengeProviderId);
  99. if (is_null($provider)) {
  100. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  101. }
  102. $backupProvider = $providerSet->getProvider('backup_codes');
  103. if (!is_null($backupProvider) && $backupProvider->getId() === $provider->getId()) {
  104. // Don't show the backup provider link if we're already showing that provider's challenge
  105. $backupProvider = null;
  106. }
  107. $errorMessage = '';
  108. $error = false;
  109. if ($this->session->exists('two_factor_auth_error')) {
  110. $this->session->remove('two_factor_auth_error');
  111. $error = true;
  112. $errorMessage = $this->session->get("two_factor_auth_error_message");
  113. $this->session->remove('two_factor_auth_error_message');
  114. }
  115. $tmpl = $provider->getTemplate($user);
  116. $tmpl->assign('redirect_url', $redirect_url);
  117. $data = [
  118. 'error' => $error,
  119. 'error_message' => $errorMessage,
  120. 'provider' => $provider,
  121. 'backupProvider' => $backupProvider,
  122. 'logout_url' => $this->getLogoutUrl(),
  123. 'redirect_url' => $redirect_url,
  124. 'template' => $tmpl->fetchPage(),
  125. ];
  126. $response = new StandaloneTemplateResponse($this->appName, 'twofactorshowchallenge', $data, 'guest');
  127. if ($provider instanceof IProvidesCustomCSP) {
  128. $response->setContentSecurityPolicy($provider->getCSP());
  129. }
  130. return $response;
  131. }
  132. /**
  133. * @NoAdminRequired
  134. * @NoCSRFRequired
  135. * @TwoFactorSetUpDoneRequired
  136. *
  137. * @UserRateThrottle(limit=5, period=100)
  138. *
  139. * @param string $challengeProviderId
  140. * @param string $challenge
  141. * @param string $redirect_url
  142. * @return RedirectResponse
  143. */
  144. #[UseSession]
  145. #[FrontpageRoute(verb: 'POST', url: '/login/challenge/{challengeProviderId}')]
  146. public function solveChallenge($challengeProviderId, $challenge, $redirect_url = null) {
  147. $user = $this->userSession->getUser();
  148. $provider = $this->twoFactorManager->getProvider($user, $challengeProviderId);
  149. if (is_null($provider)) {
  150. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  151. }
  152. try {
  153. if ($this->twoFactorManager->verifyChallenge($challengeProviderId, $user, $challenge)) {
  154. if (!is_null($redirect_url)) {
  155. return new RedirectResponse($this->urlGenerator->getAbsoluteURL(urldecode($redirect_url)));
  156. }
  157. return new RedirectResponse($this->urlGenerator->linkToDefaultPageUrl());
  158. }
  159. } catch (TwoFactorException $e) {
  160. /*
  161. * The 2FA App threw an TwoFactorException. Now we display more
  162. * information to the user. The exception text is stored in the
  163. * session to be used in showChallenge()
  164. */
  165. $this->session->set('two_factor_auth_error_message', $e->getMessage());
  166. }
  167. $ip = $this->request->getRemoteAddress();
  168. $uid = $user->getUID();
  169. $this->logger->warning("Two-factor challenge failed: $uid (Remote IP: $ip)");
  170. $this->session->set('two_factor_auth_error', true);
  171. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.showChallenge', [
  172. 'challengeProviderId' => $provider->getId(),
  173. 'redirect_url' => $redirect_url,
  174. ]));
  175. }
  176. /**
  177. * @NoAdminRequired
  178. * @NoCSRFRequired
  179. */
  180. #[FrontpageRoute(verb: 'GET', url: 'login/setupchallenge')]
  181. public function setupProviders(?string $redirect_url = null): StandaloneTemplateResponse {
  182. $user = $this->userSession->getUser();
  183. $setupProviders = $this->twoFactorManager->getLoginSetupProviders($user);
  184. $data = [
  185. 'providers' => $setupProviders,
  186. 'logout_url' => $this->getLogoutUrl(),
  187. 'redirect_url' => $redirect_url,
  188. ];
  189. return new StandaloneTemplateResponse($this->appName, 'twofactorsetupselection', $data, 'guest');
  190. }
  191. /**
  192. * @NoAdminRequired
  193. * @NoCSRFRequired
  194. */
  195. #[FrontpageRoute(verb: 'GET', url: 'login/setupchallenge/{providerId}')]
  196. public function setupProvider(string $providerId, ?string $redirect_url = null) {
  197. $user = $this->userSession->getUser();
  198. $providers = $this->twoFactorManager->getLoginSetupProviders($user);
  199. $provider = null;
  200. foreach ($providers as $p) {
  201. if ($p->getId() === $providerId) {
  202. $provider = $p;
  203. break;
  204. }
  205. }
  206. if ($provider === null) {
  207. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  208. }
  209. /** @var IActivatableAtLogin $provider */
  210. $tmpl = $provider->getLoginSetup($user)->getBody();
  211. $data = [
  212. 'provider' => $provider,
  213. 'logout_url' => $this->getLogoutUrl(),
  214. 'redirect_url' => $redirect_url,
  215. 'template' => $tmpl->fetchPage(),
  216. ];
  217. $response = new StandaloneTemplateResponse($this->appName, 'twofactorsetupchallenge', $data, 'guest');
  218. return $response;
  219. }
  220. /**
  221. * @NoAdminRequired
  222. * @NoCSRFRequired
  223. *
  224. * @todo handle the extreme edge case of an invalid provider ID and redirect to the provider selection page
  225. */
  226. #[FrontpageRoute(verb: 'POST', url: 'login/setupchallenge/{providerId}')]
  227. public function confirmProviderSetup(string $providerId, ?string $redirect_url = null) {
  228. return new RedirectResponse($this->urlGenerator->linkToRoute(
  229. 'core.TwoFactorChallenge.showChallenge',
  230. [
  231. 'challengeProviderId' => $providerId,
  232. 'redirect_url' => $redirect_url,
  233. ]
  234. ));
  235. }
  236. }