TwoFactorChallengeController.php 8.7 KB

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