Manager.php 13 KB

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