TwoFactorChallengeController.php 8.5 KB

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