Manager.php 11 KB

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