1
0

Manager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Authentication\TwoFactorAuth;
  9. use BadMethodCallException;
  10. use Exception;
  11. use OC\Authentication\Token\IProvider as TokenProvider;
  12. use OCP\Activity\IManager;
  13. use OCP\AppFramework\Db\DoesNotExistException;
  14. use OCP\AppFramework\Utility\ITimeFactory;
  15. use OCP\Authentication\Exceptions\InvalidTokenException;
  16. use OCP\Authentication\TwoFactorAuth\IActivatableAtLogin;
  17. use OCP\Authentication\TwoFactorAuth\IProvider;
  18. use OCP\Authentication\TwoFactorAuth\IRegistry;
  19. use OCP\Authentication\TwoFactorAuth\TwoFactorProviderChallengeFailed;
  20. use OCP\Authentication\TwoFactorAuth\TwoFactorProviderChallengePassed;
  21. use OCP\Authentication\TwoFactorAuth\TwoFactorProviderForUserDisabled;
  22. use OCP\Authentication\TwoFactorAuth\TwoFactorProviderForUserEnabled;
  23. use OCP\EventDispatcher\IEventDispatcher;
  24. use OCP\IConfig;
  25. use OCP\ISession;
  26. use OCP\IUser;
  27. use OCP\Session\Exceptions\SessionNotAvailableException;
  28. use Psr\Log\LoggerInterface;
  29. use function array_diff;
  30. use function array_filter;
  31. class Manager {
  32. public const SESSION_UID_KEY = 'two_factor_auth_uid';
  33. public const SESSION_UID_DONE = 'two_factor_auth_passed';
  34. public const REMEMBER_LOGIN = 'two_factor_remember_login';
  35. public const BACKUP_CODES_PROVIDER_ID = 'backup_codes';
  36. /** @var ProviderLoader */
  37. private $providerLoader;
  38. /** @var IRegistry */
  39. private $providerRegistry;
  40. /** @var MandatoryTwoFactor */
  41. private $mandatoryTwoFactor;
  42. /** @var ISession */
  43. private $session;
  44. /** @var IConfig */
  45. private $config;
  46. /** @var IManager */
  47. private $activityManager;
  48. /** @var LoggerInterface */
  49. private $logger;
  50. /** @var TokenProvider */
  51. private $tokenProvider;
  52. /** @var ITimeFactory */
  53. private $timeFactory;
  54. /** @var IEventDispatcher */
  55. private $dispatcher;
  56. /** @psalm-var array<string, bool> */
  57. private $userIsTwoFactorAuthenticated = [];
  58. public function __construct(ProviderLoader $providerLoader,
  59. IRegistry $providerRegistry,
  60. MandatoryTwoFactor $mandatoryTwoFactor,
  61. ISession $session,
  62. IConfig $config,
  63. IManager $activityManager,
  64. LoggerInterface $logger,
  65. TokenProvider $tokenProvider,
  66. ITimeFactory $timeFactory,
  67. IEventDispatcher $eventDispatcher) {
  68. $this->providerLoader = $providerLoader;
  69. $this->providerRegistry = $providerRegistry;
  70. $this->mandatoryTwoFactor = $mandatoryTwoFactor;
  71. $this->session = $session;
  72. $this->config = $config;
  73. $this->activityManager = $activityManager;
  74. $this->logger = $logger;
  75. $this->tokenProvider = $tokenProvider;
  76. $this->timeFactory = $timeFactory;
  77. $this->dispatcher = $eventDispatcher;
  78. }
  79. /**
  80. * Determine whether the user must provide a second factor challenge
  81. */
  82. public function isTwoFactorAuthenticated(IUser $user): bool {
  83. if (isset($this->userIsTwoFactorAuthenticated[$user->getUID()])) {
  84. return $this->userIsTwoFactorAuthenticated[$user->getUID()];
  85. }
  86. if ($this->mandatoryTwoFactor->isEnforcedFor($user)) {
  87. return true;
  88. }
  89. $providerStates = $this->providerRegistry->getProviderStates($user);
  90. $providers = $this->providerLoader->getProviders($user);
  91. $fixedStates = $this->fixMissingProviderStates($providerStates, $providers, $user);
  92. $enabled = array_filter($fixedStates);
  93. $providerIds = array_keys($enabled);
  94. $providerIdsWithoutBackupCodes = array_diff($providerIds, [self::BACKUP_CODES_PROVIDER_ID]);
  95. $this->userIsTwoFactorAuthenticated[$user->getUID()] = !empty($providerIdsWithoutBackupCodes);
  96. return $this->userIsTwoFactorAuthenticated[$user->getUID()];
  97. }
  98. /**
  99. * Get a 2FA provider by its ID
  100. */
  101. public function getProvider(IUser $user, string $challengeProviderId): ?IProvider {
  102. $providers = $this->getProviderSet($user)->getProviders();
  103. return $providers[$challengeProviderId] ?? null;
  104. }
  105. /**
  106. * @return IActivatableAtLogin[]
  107. * @throws Exception
  108. */
  109. public function getLoginSetupProviders(IUser $user): array {
  110. $providers = $this->providerLoader->getProviders($user);
  111. return array_filter($providers, function (IProvider $provider) {
  112. return ($provider instanceof IActivatableAtLogin);
  113. });
  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 array<string, bool> $providerStates
  122. * @param IProvider[] $providers
  123. * @param IUser $user
  124. * @return array<string, bool> 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', (string)$tokenId);
  217. $this->dispatcher->dispatchTyped(new TwoFactorProviderForUserEnabled($user, $provider));
  218. $this->dispatcher->dispatchTyped(new TwoFactorProviderChallengePassed($user, $provider));
  219. $this->publishEvent($user, 'twofactor_success', [
  220. 'provider' => $provider->getDisplayName(),
  221. ]);
  222. } else {
  223. $this->dispatcher->dispatchTyped(new TwoFactorProviderForUserDisabled($user, $provider));
  224. $this->dispatcher->dispatchTyped(new TwoFactorProviderChallengeFailed($user, $provider));
  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', 'exception' => $e]);
  249. }
  250. }
  251. /**
  252. * Check if the currently logged in user needs to pass 2FA
  253. *
  254. * @param IUser $user the currently logged in user
  255. * @return boolean
  256. */
  257. public function needsSecondFactor(?IUser $user = null): bool {
  258. if ($user === null) {
  259. return false;
  260. }
  261. // If we are authenticated using an app password or AppAPI Auth, skip all this
  262. if ($this->session->exists('app_password') || $this->session->get('app_api') === true) {
  263. return false;
  264. }
  265. // First check if the session tells us we should do 2FA (99% case)
  266. if (!$this->session->exists(self::SESSION_UID_KEY)) {
  267. // Check if the session tells us it is 2FA authenticated already
  268. if ($this->session->exists(self::SESSION_UID_DONE) &&
  269. $this->session->get(self::SESSION_UID_DONE) === $user->getUID()) {
  270. return false;
  271. }
  272. /*
  273. * If the session is expired check if we are not logged in by a token
  274. * that still needs 2FA auth
  275. */
  276. try {
  277. $sessionId = $this->session->getId();
  278. $token = $this->tokenProvider->getToken($sessionId);
  279. $tokenId = $token->getId();
  280. $tokensNeeding2FA = $this->config->getUserKeys($user->getUID(), 'login_token_2fa');
  281. if (!\in_array((string)$tokenId, $tokensNeeding2FA, true)) {
  282. $this->session->set(self::SESSION_UID_DONE, $user->getUID());
  283. return false;
  284. }
  285. } catch (InvalidTokenException|SessionNotAvailableException $e) {
  286. }
  287. }
  288. if (!$this->isTwoFactorAuthenticated($user)) {
  289. // There is no second factor any more -> let the user pass
  290. // This prevents infinite redirect loops when a user is about
  291. // to solve the 2FA challenge, and the provider app is
  292. // disabled the same time
  293. $this->session->remove(self::SESSION_UID_KEY);
  294. $keys = $this->config->getUserKeys($user->getUID(), 'login_token_2fa');
  295. foreach ($keys as $key) {
  296. $this->config->deleteUserValue($user->getUID(), 'login_token_2fa', $key);
  297. }
  298. return false;
  299. }
  300. return true;
  301. }
  302. /**
  303. * Prepare the 2FA login
  304. *
  305. * @param IUser $user
  306. * @param boolean $rememberMe
  307. */
  308. public function prepareTwoFactorLogin(IUser $user, bool $rememberMe) {
  309. $this->session->set(self::SESSION_UID_KEY, $user->getUID());
  310. $this->session->set(self::REMEMBER_LOGIN, $rememberMe);
  311. $id = $this->session->getId();
  312. $token = $this->tokenProvider->getToken($id);
  313. $this->config->setUserValue($user->getUID(), 'login_token_2fa', (string)$token->getId(), (string)$this->timeFactory->getTime());
  314. }
  315. public function clearTwoFactorPending(string $userId) {
  316. $tokensNeeding2FA = $this->config->getUserKeys($userId, 'login_token_2fa');
  317. foreach ($tokensNeeding2FA as $tokenId) {
  318. $this->config->deleteUserValue($userId, 'login_token_2fa', $tokenId);
  319. try {
  320. $this->tokenProvider->invalidateTokenById($userId, (int)$tokenId);
  321. } catch (DoesNotExistException $e) {
  322. }
  323. }
  324. }
  325. }