Manager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. <?php
  2. declare(strict_types = 1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@owncloud.com>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Robin Appelman <robin@icewind.nl>
  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 function array_diff;
  28. use function array_filter;
  29. use BadMethodCallException;
  30. use Exception;
  31. use OC\Authentication\Exceptions\InvalidTokenException;
  32. use OC\Authentication\Token\IProvider as TokenProvider;
  33. use OCP\Activity\IManager;
  34. use OCP\AppFramework\Utility\ITimeFactory;
  35. use OCP\Authentication\TwoFactorAuth\IProvider;
  36. use OCP\Authentication\TwoFactorAuth\IRegistry;
  37. use OCP\IConfig;
  38. use OCP\ILogger;
  39. use OCP\ISession;
  40. use OCP\IUser;
  41. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  42. use Symfony\Component\EventDispatcher\GenericEvent;
  43. class Manager {
  44. const SESSION_UID_KEY = 'two_factor_auth_uid';
  45. const SESSION_UID_DONE = 'two_factor_auth_passed';
  46. const REMEMBER_LOGIN = 'two_factor_remember_login';
  47. const BACKUP_CODES_PROVIDER_ID = 'backup_codes';
  48. /** @var ProviderLoader */
  49. private $providerLoader;
  50. /** @var IRegistry */
  51. private $providerRegistry;
  52. /** @var MandatoryTwoFactor */
  53. private $mandatoryTwoFactor;
  54. /** @var ISession */
  55. private $session;
  56. /** @var IConfig */
  57. private $config;
  58. /** @var IManager */
  59. private $activityManager;
  60. /** @var ILogger */
  61. private $logger;
  62. /** @var TokenProvider */
  63. private $tokenProvider;
  64. /** @var ITimeFactory */
  65. private $timeFactory;
  66. /** @var EventDispatcherInterface */
  67. private $dispatcher;
  68. public function __construct(ProviderLoader $providerLoader,
  69. IRegistry $providerRegistry,
  70. MandatoryTwoFactor $mandatoryTwoFactor,
  71. ISession $session, IConfig $config,
  72. IManager $activityManager, ILogger $logger, TokenProvider $tokenProvider,
  73. ITimeFactory $timeFactory, EventDispatcherInterface $eventDispatcher) {
  74. $this->providerLoader = $providerLoader;
  75. $this->providerRegistry = $providerRegistry;
  76. $this->mandatoryTwoFactor = $mandatoryTwoFactor;
  77. $this->session = $session;
  78. $this->config = $config;
  79. $this->activityManager = $activityManager;
  80. $this->logger = $logger;
  81. $this->tokenProvider = $tokenProvider;
  82. $this->timeFactory = $timeFactory;
  83. $this->dispatcher = $eventDispatcher;
  84. }
  85. /**
  86. * Determine whether the user must provide a second factor challenge
  87. *
  88. * @param IUser $user
  89. * @return boolean
  90. */
  91. public function isTwoFactorAuthenticated(IUser $user): bool {
  92. if ($this->mandatoryTwoFactor->isEnforcedFor($user)) {
  93. return true;
  94. }
  95. $providerStates = $this->providerRegistry->getProviderStates($user);
  96. $providers = $this->providerLoader->getProviders($user);
  97. $fixedStates = $this->fixMissingProviderStates($providerStates, $providers, $user);
  98. $enabled = array_filter($fixedStates);
  99. $providerIds = array_keys($enabled);
  100. $providerIdsWithoutBackupCodes = array_diff($providerIds, [self::BACKUP_CODES_PROVIDER_ID]);
  101. return !empty($providerIdsWithoutBackupCodes);
  102. }
  103. /**
  104. * Get a 2FA provider by its ID
  105. *
  106. * @param IUser $user
  107. * @param string $challengeProviderId
  108. * @return IProvider|null
  109. */
  110. public function getProvider(IUser $user, string $challengeProviderId) {
  111. $providers = $this->getProviderSet($user)->getProviders();
  112. return $providers[$challengeProviderId] ?? null;
  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 string[] $providerStates
  121. * @param IProvider[] $providers
  122. * @param IUser $user
  123. * @return string[] 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', $tokenId);
  216. $dispatchEvent = new GenericEvent($user, ['provider' => $provider->getDisplayName()]);
  217. $this->dispatcher->dispatch(IProvider::EVENT_SUCCESS, $dispatchEvent);
  218. $this->publishEvent($user, 'twofactor_success', [
  219. 'provider' => $provider->getDisplayName(),
  220. ]);
  221. } else {
  222. $dispatchEvent = new GenericEvent($user, ['provider' => $provider->getDisplayName()]);
  223. $this->dispatcher->dispatch(IProvider::EVENT_FAILED, $dispatchEvent);
  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']);
  248. $this->logger->logException($e, ['app' => 'core']);
  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 skip all this
  262. if ($this->session->exists('app_password')) {
  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($tokenId, $tokensNeeding2FA, true)) {
  282. $this->session->set(self::SESSION_UID_DONE, $user->getUID());
  283. return false;
  284. }
  285. } catch (InvalidTokenException $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', $token->getId(), $this->timeFactory->getTime());
  314. }
  315. }