TwoFactorChallengeController.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Cornelius Kölbel <cornelius.koelbel@netknights.it>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. * @author Kate Döen <kate.doeen@nextcloud.com>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\Core\Controller;
  28. use OC\Authentication\TwoFactorAuth\Manager;
  29. use OC_User;
  30. use OCP\AppFramework\Controller;
  31. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  32. use OCP\AppFramework\Http\Attribute\OpenAPI;
  33. use OCP\AppFramework\Http\Attribute\UseSession;
  34. use OCP\AppFramework\Http\RedirectResponse;
  35. use OCP\AppFramework\Http\StandaloneTemplateResponse;
  36. use OCP\Authentication\TwoFactorAuth\IActivatableAtLogin;
  37. use OCP\Authentication\TwoFactorAuth\IProvider;
  38. use OCP\Authentication\TwoFactorAuth\IProvidesCustomCSP;
  39. use OCP\Authentication\TwoFactorAuth\TwoFactorException;
  40. use OCP\IRequest;
  41. use OCP\ISession;
  42. use OCP\IURLGenerator;
  43. use OCP\IUserSession;
  44. use Psr\Log\LoggerInterface;
  45. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  46. class TwoFactorChallengeController extends Controller {
  47. public function __construct(
  48. string $appName,
  49. IRequest $request,
  50. private Manager $twoFactorManager,
  51. private IUserSession $userSession,
  52. private ISession $session,
  53. private IURLGenerator $urlGenerator,
  54. private LoggerInterface $logger,
  55. ) {
  56. parent::__construct($appName, $request);
  57. }
  58. /**
  59. * @return string
  60. */
  61. protected function getLogoutUrl() {
  62. return OC_User::getLogoutUrl($this->urlGenerator);
  63. }
  64. /**
  65. * @param IProvider[] $providers
  66. */
  67. private function splitProvidersAndBackupCodes(array $providers): array {
  68. $regular = [];
  69. $backup = null;
  70. foreach ($providers as $provider) {
  71. if ($provider->getId() === 'backup_codes') {
  72. $backup = $provider;
  73. } else {
  74. $regular[] = $provider;
  75. }
  76. }
  77. return [$regular, $backup];
  78. }
  79. /**
  80. * @NoAdminRequired
  81. * @NoCSRFRequired
  82. * @TwoFactorSetUpDoneRequired
  83. *
  84. * @param string $redirect_url
  85. * @return StandaloneTemplateResponse
  86. */
  87. #[FrontpageRoute(verb: 'GET', url: '/login/selectchallenge')]
  88. public function selectChallenge($redirect_url) {
  89. $user = $this->userSession->getUser();
  90. $providerSet = $this->twoFactorManager->getProviderSet($user);
  91. $allProviders = $providerSet->getProviders();
  92. [$providers, $backupProvider] = $this->splitProvidersAndBackupCodes($allProviders);
  93. $setupProviders = $this->twoFactorManager->getLoginSetupProviders($user);
  94. $data = [
  95. 'providers' => $providers,
  96. 'backupProvider' => $backupProvider,
  97. 'providerMissing' => $providerSet->isProviderMissing(),
  98. 'redirect_url' => $redirect_url,
  99. 'logout_url' => $this->getLogoutUrl(),
  100. 'hasSetupProviders' => !empty($setupProviders),
  101. ];
  102. return new StandaloneTemplateResponse($this->appName, 'twofactorselectchallenge', $data, 'guest');
  103. }
  104. /**
  105. * @NoAdminRequired
  106. * @NoCSRFRequired
  107. * @TwoFactorSetUpDoneRequired
  108. *
  109. * @param string $challengeProviderId
  110. * @param string $redirect_url
  111. * @return StandaloneTemplateResponse|RedirectResponse
  112. */
  113. #[UseSession]
  114. #[FrontpageRoute(verb: 'GET', url: '/login/challenge/{challengeProviderId}')]
  115. public function showChallenge($challengeProviderId, $redirect_url) {
  116. $user = $this->userSession->getUser();
  117. $providerSet = $this->twoFactorManager->getProviderSet($user);
  118. $provider = $providerSet->getProvider($challengeProviderId);
  119. if (is_null($provider)) {
  120. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  121. }
  122. $backupProvider = $providerSet->getProvider('backup_codes');
  123. if (!is_null($backupProvider) && $backupProvider->getId() === $provider->getId()) {
  124. // Don't show the backup provider link if we're already showing that provider's challenge
  125. $backupProvider = null;
  126. }
  127. $errorMessage = '';
  128. $error = false;
  129. if ($this->session->exists('two_factor_auth_error')) {
  130. $this->session->remove('two_factor_auth_error');
  131. $error = true;
  132. $errorMessage = $this->session->get("two_factor_auth_error_message");
  133. $this->session->remove('two_factor_auth_error_message');
  134. }
  135. $tmpl = $provider->getTemplate($user);
  136. $tmpl->assign('redirect_url', $redirect_url);
  137. $data = [
  138. 'error' => $error,
  139. 'error_message' => $errorMessage,
  140. 'provider' => $provider,
  141. 'backupProvider' => $backupProvider,
  142. 'logout_url' => $this->getLogoutUrl(),
  143. 'redirect_url' => $redirect_url,
  144. 'template' => $tmpl->fetchPage(),
  145. ];
  146. $response = new StandaloneTemplateResponse($this->appName, 'twofactorshowchallenge', $data, 'guest');
  147. if ($provider instanceof IProvidesCustomCSP) {
  148. $response->setContentSecurityPolicy($provider->getCSP());
  149. }
  150. return $response;
  151. }
  152. /**
  153. * @NoAdminRequired
  154. * @NoCSRFRequired
  155. * @TwoFactorSetUpDoneRequired
  156. *
  157. * @UserRateThrottle(limit=5, period=100)
  158. *
  159. * @param string $challengeProviderId
  160. * @param string $challenge
  161. * @param string $redirect_url
  162. * @return RedirectResponse
  163. */
  164. #[UseSession]
  165. #[FrontpageRoute(verb: 'POST', url: '/login/challenge/{challengeProviderId}')]
  166. public function solveChallenge($challengeProviderId, $challenge, $redirect_url = null) {
  167. $user = $this->userSession->getUser();
  168. $provider = $this->twoFactorManager->getProvider($user, $challengeProviderId);
  169. if (is_null($provider)) {
  170. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  171. }
  172. try {
  173. if ($this->twoFactorManager->verifyChallenge($challengeProviderId, $user, $challenge)) {
  174. if (!is_null($redirect_url)) {
  175. return new RedirectResponse($this->urlGenerator->getAbsoluteURL(urldecode($redirect_url)));
  176. }
  177. return new RedirectResponse($this->urlGenerator->linkToDefaultPageUrl());
  178. }
  179. } catch (TwoFactorException $e) {
  180. /*
  181. * The 2FA App threw an TwoFactorException. Now we display more
  182. * information to the user. The exception text is stored in the
  183. * session to be used in showChallenge()
  184. */
  185. $this->session->set('two_factor_auth_error_message', $e->getMessage());
  186. }
  187. $ip = $this->request->getRemoteAddress();
  188. $uid = $user->getUID();
  189. $this->logger->warning("Two-factor challenge failed: $uid (Remote IP: $ip)");
  190. $this->session->set('two_factor_auth_error', true);
  191. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.showChallenge', [
  192. 'challengeProviderId' => $provider->getId(),
  193. 'redirect_url' => $redirect_url,
  194. ]));
  195. }
  196. /**
  197. * @NoAdminRequired
  198. * @NoCSRFRequired
  199. */
  200. #[FrontpageRoute(verb: 'GET', url: 'login/setupchallenge')]
  201. public function setupProviders(?string $redirect_url = null): StandaloneTemplateResponse {
  202. $user = $this->userSession->getUser();
  203. $setupProviders = $this->twoFactorManager->getLoginSetupProviders($user);
  204. $data = [
  205. 'providers' => $setupProviders,
  206. 'logout_url' => $this->getLogoutUrl(),
  207. 'redirect_url' => $redirect_url,
  208. ];
  209. return new StandaloneTemplateResponse($this->appName, 'twofactorsetupselection', $data, 'guest');
  210. }
  211. /**
  212. * @NoAdminRequired
  213. * @NoCSRFRequired
  214. */
  215. #[FrontpageRoute(verb: 'GET', url: 'login/setupchallenge/{providerId}')]
  216. public function setupProvider(string $providerId, ?string $redirect_url = null) {
  217. $user = $this->userSession->getUser();
  218. $providers = $this->twoFactorManager->getLoginSetupProviders($user);
  219. $provider = null;
  220. foreach ($providers as $p) {
  221. if ($p->getId() === $providerId) {
  222. $provider = $p;
  223. break;
  224. }
  225. }
  226. if ($provider === null) {
  227. return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
  228. }
  229. /** @var IActivatableAtLogin $provider */
  230. $tmpl = $provider->getLoginSetup($user)->getBody();
  231. $data = [
  232. 'provider' => $provider,
  233. 'logout_url' => $this->getLogoutUrl(),
  234. 'redirect_url' => $redirect_url,
  235. 'template' => $tmpl->fetchPage(),
  236. ];
  237. $response = new StandaloneTemplateResponse($this->appName, 'twofactorsetupchallenge', $data, 'guest');
  238. return $response;
  239. }
  240. /**
  241. * @NoAdminRequired
  242. * @NoCSRFRequired
  243. *
  244. * @todo handle the extreme edge case of an invalid provider ID and redirect to the provider selection page
  245. */
  246. #[FrontpageRoute(verb: 'POST', url: 'login/setupchallenge/{providerId}')]
  247. public function confirmProviderSetup(string $providerId, ?string $redirect_url = null) {
  248. return new RedirectResponse($this->urlGenerator->linkToRoute(
  249. 'core.TwoFactorChallenge.showChallenge',
  250. [
  251. 'challengeProviderId' => $providerId,
  252. 'redirect_url' => $redirect_url,
  253. ]
  254. ));
  255. }
  256. }