Manager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. <?php
  2. declare(strict_types = 1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@owncloud.com>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Robin Appelman <robin@icewind.nl>
  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\Authentication\TwoFactorAuth;
  27. use function array_diff;
  28. use function array_filter;
  29. use BadMethodCallException;
  30. use Exception;
  31. use OC\Authentication\Exceptions\ExpiredTokenException;
  32. use OC\Authentication\Exceptions\InvalidTokenException;
  33. use OC\Authentication\Token\IProvider as TokenProvider;
  34. use OCP\Activity\IManager;
  35. use OCP\AppFramework\Utility\ITimeFactory;
  36. use OCP\Authentication\TwoFactorAuth\IProvider;
  37. use OCP\Authentication\TwoFactorAuth\IRegistry;
  38. use OCP\IConfig;
  39. use OCP\ILogger;
  40. use OCP\ISession;
  41. use OCP\IUser;
  42. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  43. use Symfony\Component\EventDispatcher\GenericEvent;
  44. class Manager {
  45. const SESSION_UID_KEY = 'two_factor_auth_uid';
  46. const SESSION_UID_DONE = 'two_factor_auth_passed';
  47. const REMEMBER_LOGIN = 'two_factor_remember_login';
  48. const BACKUP_CODES_PROVIDER_ID = 'backup_codes';
  49. /** @var ProviderLoader */
  50. private $providerLoader;
  51. /** @var IRegistry */
  52. private $providerRegistry;
  53. /** @var MandatoryTwoFactor */
  54. private $mandatoryTwoFactor;
  55. /** @var ISession */
  56. private $session;
  57. /** @var IConfig */
  58. private $config;
  59. /** @var IManager */
  60. private $activityManager;
  61. /** @var ILogger */
  62. private $logger;
  63. /** @var TokenProvider */
  64. private $tokenProvider;
  65. /** @var ITimeFactory */
  66. private $timeFactory;
  67. /** @var EventDispatcherInterface */
  68. private $dispatcher;
  69. public function __construct(ProviderLoader $providerLoader,
  70. IRegistry $providerRegistry,
  71. MandatoryTwoFactor $mandatoryTwoFactor,
  72. ISession $session, IConfig $config,
  73. IManager $activityManager, ILogger $logger, TokenProvider $tokenProvider,
  74. ITimeFactory $timeFactory, EventDispatcherInterface $eventDispatcher) {
  75. $this->providerLoader = $providerLoader;
  76. $this->providerRegistry = $providerRegistry;
  77. $this->mandatoryTwoFactor = $mandatoryTwoFactor;
  78. $this->session = $session;
  79. $this->config = $config;
  80. $this->activityManager = $activityManager;
  81. $this->logger = $logger;
  82. $this->tokenProvider = $tokenProvider;
  83. $this->timeFactory = $timeFactory;
  84. $this->dispatcher = $eventDispatcher;
  85. }
  86. /**
  87. * Determine whether the user must provide a second factor challenge
  88. *
  89. * @param IUser $user
  90. * @return boolean
  91. */
  92. public function isTwoFactorAuthenticated(IUser $user): bool {
  93. if ($this->mandatoryTwoFactor->isEnforcedFor($user)) {
  94. return true;
  95. }
  96. $providerStates = $this->providerRegistry->getProviderStates($user);
  97. $providers = $this->providerLoader->getProviders($user);
  98. $fixedStates = $this->fixMissingProviderStates($providerStates, $providers, $user);
  99. $enabled = array_filter($fixedStates);
  100. $providerIds = array_keys($enabled);
  101. $providerIdsWithoutBackupCodes = array_diff($providerIds, [self::BACKUP_CODES_PROVIDER_ID]);
  102. return !empty($providerIdsWithoutBackupCodes);
  103. }
  104. /**
  105. * Get a 2FA provider by its ID
  106. *
  107. * @param IUser $user
  108. * @param string $challengeProviderId
  109. * @return IProvider|null
  110. */
  111. public function getProvider(IUser $user, string $challengeProviderId) {
  112. $providers = $this->getProviderSet($user)->getProviders();
  113. return $providers[$challengeProviderId] ?? null;
  114. }
  115. /**
  116. * Check if the persistant mapping of enabled/disabled state of each available
  117. * provider is missing an entry and add it to the registry in that case.
  118. *
  119. * @todo remove in Nextcloud 17 as by then all providers should have been updated
  120. *
  121. * @param string[] $providerStates
  122. * @param IProvider[] $providers
  123. * @param IUser $user
  124. * @return string[] the updated $providerStates variable
  125. */
  126. private function fixMissingProviderStates(array $providerStates,
  127. array $providers, IUser $user): array {
  128. foreach ($providers as $provider) {
  129. if (isset($providerStates[$provider->getId()])) {
  130. // All good
  131. continue;
  132. }
  133. $enabled = $provider->isTwoFactorAuthEnabledForUser($user);
  134. if ($enabled) {
  135. $this->providerRegistry->enableProviderFor($provider, $user);
  136. } else {
  137. $this->providerRegistry->disableProviderFor($provider, $user);
  138. }
  139. $providerStates[$provider->getId()] = $enabled;
  140. }
  141. return $providerStates;
  142. }
  143. /**
  144. * @param array $states
  145. * @param IProvider $providers
  146. */
  147. private function isProviderMissing(array $states, array $providers): bool {
  148. $indexed = [];
  149. foreach ($providers as $provider) {
  150. $indexed[$provider->getId()] = $provider;
  151. }
  152. $missing = [];
  153. foreach ($states as $providerId => $enabled) {
  154. if (!$enabled) {
  155. // Don't care
  156. continue;
  157. }
  158. if (!isset($indexed[$providerId])) {
  159. $missing[] = $providerId;
  160. $this->logger->alert("two-factor auth provider '$providerId' failed to load",
  161. [
  162. 'app' => 'core',
  163. ]);
  164. }
  165. }
  166. if (!empty($missing)) {
  167. // There was at least one provider missing
  168. $this->logger->alert(count($missing) . " two-factor auth providers failed to load", ['app' => 'core']);
  169. return true;
  170. }
  171. // If we reach this, there was not a single provider missing
  172. return false;
  173. }
  174. /**
  175. * Get the list of 2FA providers for the given user
  176. *
  177. * @param IUser $user
  178. * @throws Exception
  179. */
  180. public function getProviderSet(IUser $user): ProviderSet {
  181. $providerStates = $this->providerRegistry->getProviderStates($user);
  182. $providers = $this->providerLoader->getProviders($user);
  183. $fixedStates = $this->fixMissingProviderStates($providerStates, $providers, $user);
  184. $isProviderMissing = $this->isProviderMissing($fixedStates, $providers);
  185. $enabled = array_filter($providers, function (IProvider $provider) use ($fixedStates) {
  186. return $fixedStates[$provider->getId()];
  187. });
  188. return new ProviderSet($enabled, $isProviderMissing);
  189. }
  190. /**
  191. * Verify the given challenge
  192. *
  193. * @param string $providerId
  194. * @param IUser $user
  195. * @param string $challenge
  196. * @return boolean
  197. */
  198. public function verifyChallenge(string $providerId, IUser $user, string $challenge): bool {
  199. $provider = $this->getProvider($user, $providerId);
  200. if ($provider === null) {
  201. return false;
  202. }
  203. $passed = $provider->verifyChallenge($user, $challenge);
  204. if ($passed) {
  205. if ($this->session->get(self::REMEMBER_LOGIN) === true) {
  206. // TODO: resolve cyclic dependency and use DI
  207. \OC::$server->getUserSession()->createRememberMeToken($user);
  208. }
  209. $this->session->remove(self::SESSION_UID_KEY);
  210. $this->session->remove(self::REMEMBER_LOGIN);
  211. $this->session->set(self::SESSION_UID_DONE, $user->getUID());
  212. // Clear token from db
  213. $sessionId = $this->session->getId();
  214. $token = $this->tokenProvider->getToken($sessionId);
  215. $tokenId = $token->getId();
  216. $this->config->deleteUserValue($user->getUID(), 'login_token_2fa', $tokenId);
  217. $dispatchEvent = new GenericEvent($user, ['provider' => $provider->getDisplayName()]);
  218. $this->dispatcher->dispatch(IProvider::EVENT_SUCCESS, $dispatchEvent);
  219. $this->publishEvent($user, 'twofactor_success', [
  220. 'provider' => $provider->getDisplayName(),
  221. ]);
  222. } else {
  223. $dispatchEvent = new GenericEvent($user, ['provider' => $provider->getDisplayName()]);
  224. $this->dispatcher->dispatch(IProvider::EVENT_FAILED, $dispatchEvent);
  225. $this->publishEvent($user, 'twofactor_failed', [
  226. 'provider' => $provider->getDisplayName(),
  227. ]);
  228. }
  229. return $passed;
  230. }
  231. /**
  232. * Push a 2fa event the user's activity stream
  233. *
  234. * @param IUser $user
  235. * @param string $event
  236. * @param array $params
  237. */
  238. private function publishEvent(IUser $user, string $event, array $params) {
  239. $activity = $this->activityManager->generateEvent();
  240. $activity->setApp('core')
  241. ->setType('security')
  242. ->setAuthor($user->getUID())
  243. ->setAffectedUser($user->getUID())
  244. ->setSubject($event, $params);
  245. try {
  246. $this->activityManager->publish($activity);
  247. } catch (BadMethodCallException $e) {
  248. $this->logger->warning('could not publish activity', ['app' => 'core']);
  249. $this->logger->logException($e, ['app' => 'core']);
  250. }
  251. }
  252. /**
  253. * Check if the currently logged in user needs to pass 2FA
  254. *
  255. * @param IUser $user the currently logged in user
  256. * @return boolean
  257. */
  258. public function needsSecondFactor(IUser $user = null): bool {
  259. if ($user === null) {
  260. return false;
  261. }
  262. // If we are authenticated using an app password skip all this
  263. if ($this->session->exists('app_password')) {
  264. return false;
  265. }
  266. // First check if the session tells us we should do 2FA (99% case)
  267. if (!$this->session->exists(self::SESSION_UID_KEY)) {
  268. // Check if the session tells us it is 2FA authenticated already
  269. if ($this->session->exists(self::SESSION_UID_DONE) &&
  270. $this->session->get(self::SESSION_UID_DONE) === $user->getUID()) {
  271. return false;
  272. }
  273. /*
  274. * If the session is expired check if we are not logged in by a token
  275. * that still needs 2FA auth
  276. */
  277. try {
  278. $sessionId = $this->session->getId();
  279. $token = $this->tokenProvider->getToken($sessionId);
  280. $tokenId = $token->getId();
  281. $tokensNeeding2FA = $this->config->getUserKeys($user->getUID(), 'login_token_2fa');
  282. if (!\in_array($tokenId, $tokensNeeding2FA, true)) {
  283. $this->session->set(self::SESSION_UID_DONE, $user->getUID());
  284. return false;
  285. }
  286. } catch (InvalidTokenException $e) {
  287. }
  288. }
  289. if (!$this->isTwoFactorAuthenticated($user)) {
  290. // There is no second factor any more -> let the user pass
  291. // This prevents infinite redirect loops when a user is about
  292. // to solve the 2FA challenge, and the provider app is
  293. // disabled the same time
  294. $this->session->remove(self::SESSION_UID_KEY);
  295. $keys = $this->config->getUserKeys($user->getUID(), 'login_token_2fa');
  296. foreach ($keys as $key) {
  297. $this->config->deleteUserValue($user->getUID(), 'login_token_2fa', $key);
  298. }
  299. return false;
  300. }
  301. return true;
  302. }
  303. /**
  304. * Prepare the 2FA login
  305. *
  306. * @param IUser $user
  307. * @param boolean $rememberMe
  308. */
  309. public function prepareTwoFactorLogin(IUser $user, bool $rememberMe) {
  310. $this->session->set(self::SESSION_UID_KEY, $user->getUID());
  311. $this->session->set(self::REMEMBER_LOGIN, $rememberMe);
  312. $id = $this->session->getId();
  313. $token = $this->tokenProvider->getToken($id);
  314. $this->config->setUserValue($user->getUID(), 'login_token_2fa', $token->getId(), $this->timeFactory->getTime());
  315. }
  316. public function clearTwoFactorPending(string $userId) {
  317. $tokensNeeding2FA = $this->config->getUserKeys($userId, 'login_token_2fa');
  318. foreach ($tokensNeeding2FA as $tokenId) {
  319. $this->tokenProvider->invalidateTokenById($userId, $tokenId);
  320. }
  321. }
  322. }