Manager.php 12 KB

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