TwoFactorChallengeController.php 8.5 KB

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