You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Manager.php 11KB

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