TwoFactorChallengeController.php 8.2 KB

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