Manager.php 12 KB

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