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.

1016 lines
28 KiB

3 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017, Sandro Lutz <sandro.lutz@temparus.ch>
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  8. * @author Bjoern Schiessle <bjoern@schiessle.org>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Felix Rupp <github@felixrupp.com>
  11. * @author Greta Doci <gretadoci@gmail.com>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  14. * @author Lionel Elie Mamane <lionel@mamane.lu>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author Morris Jobke <hey@morrisjobke.de>
  17. * @author Robin Appelman <robin@icewind.nl>
  18. * @author Robin McCorkell <robin@mccorkell.me.uk>
  19. * @author Roeland Jago Douma <roeland@famdouma.nl>
  20. * @author Sandro Lutz <sandro.lutz@temparus.ch>
  21. * @author Thomas Müller <thomas.mueller@tmit.eu>
  22. * @author Vincent Petry <pvince81@owncloud.com>
  23. *
  24. * @license AGPL-3.0
  25. *
  26. * This code is free software: you can redistribute it and/or modify
  27. * it under the terms of the GNU Affero General Public License, version 3,
  28. * as published by the Free Software Foundation.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU Affero General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU Affero General Public License, version 3,
  36. * along with this program. If not, see <http://www.gnu.org/licenses/>
  37. *
  38. */
  39. namespace OC\User;
  40. use OC;
  41. use OC\Authentication\Exceptions\ExpiredTokenException;
  42. use OC\Authentication\Exceptions\InvalidTokenException;
  43. use OC\Authentication\Exceptions\PasswordlessTokenException;
  44. use OC\Authentication\Exceptions\PasswordLoginForbiddenException;
  45. use OC\Authentication\Token\IProvider;
  46. use OC\Authentication\Token\IToken;
  47. use OC\Hooks\Emitter;
  48. use OC\Hooks\PublicEmitter;
  49. use OC_User;
  50. use OC_Util;
  51. use OCA\DAV\Connector\Sabre\Auth;
  52. use OCP\AppFramework\Utility\ITimeFactory;
  53. use OCP\EventDispatcher\IEventDispatcher;
  54. use OCP\Files\NotPermittedException;
  55. use OCP\IConfig;
  56. use OCP\ILogger;
  57. use OCP\IRequest;
  58. use OCP\ISession;
  59. use OCP\IUser;
  60. use OCP\IUserSession;
  61. use OCP\Lockdown\ILockdownManager;
  62. use OCP\Security\ISecureRandom;
  63. use OCP\Session\Exceptions\SessionNotAvailableException;
  64. use OCP\User\Events\PostLoginEvent;
  65. use OCP\Util;
  66. use Symfony\Component\EventDispatcher\GenericEvent;
  67. /**
  68. * Class Session
  69. *
  70. * Hooks available in scope \OC\User:
  71. * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  72. * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  73. * - preDelete(\OC\User\User $user)
  74. * - postDelete(\OC\User\User $user)
  75. * - preCreateUser(string $uid, string $password)
  76. * - postCreateUser(\OC\User\User $user)
  77. * - assignedUserId(string $uid)
  78. * - preUnassignedUserId(string $uid)
  79. * - postUnassignedUserId(string $uid)
  80. * - preLogin(string $user, string $password)
  81. * - postLogin(\OC\User\User $user, string $loginName, string $password, boolean $isTokenLogin)
  82. * - preRememberedLogin(string $uid)
  83. * - postRememberedLogin(\OC\User\User $user)
  84. * - logout()
  85. * - postLogout()
  86. *
  87. * @package OC\User
  88. */
  89. class Session implements IUserSession, Emitter {
  90. /** @var Manager|PublicEmitter $manager */
  91. private $manager;
  92. /** @var ISession $session */
  93. private $session;
  94. /** @var ITimeFactory */
  95. private $timeFactory;
  96. /** @var IProvider */
  97. private $tokenProvider;
  98. /** @var IConfig */
  99. private $config;
  100. /** @var User $activeUser */
  101. protected $activeUser;
  102. /** @var ISecureRandom */
  103. private $random;
  104. /** @var ILockdownManager */
  105. private $lockdownManager;
  106. /** @var ILogger */
  107. private $logger;
  108. /** @var IEventDispatcher */
  109. private $dispatcher;
  110. /**
  111. * @param Manager $manager
  112. * @param ISession $session
  113. * @param ITimeFactory $timeFactory
  114. * @param IProvider $tokenProvider
  115. * @param IConfig $config
  116. * @param ISecureRandom $random
  117. * @param ILockdownManager $lockdownManager
  118. * @param ILogger $logger
  119. */
  120. public function __construct(Manager $manager,
  121. ISession $session,
  122. ITimeFactory $timeFactory,
  123. $tokenProvider,
  124. IConfig $config,
  125. ISecureRandom $random,
  126. ILockdownManager $lockdownManager,
  127. ILogger $logger,
  128. IEventDispatcher $dispatcher
  129. ) {
  130. $this->manager = $manager;
  131. $this->session = $session;
  132. $this->timeFactory = $timeFactory;
  133. $this->tokenProvider = $tokenProvider;
  134. $this->config = $config;
  135. $this->random = $random;
  136. $this->lockdownManager = $lockdownManager;
  137. $this->logger = $logger;
  138. $this->dispatcher = $dispatcher;
  139. }
  140. /**
  141. * @param IProvider $provider
  142. */
  143. public function setTokenProvider(IProvider $provider) {
  144. $this->tokenProvider = $provider;
  145. }
  146. /**
  147. * @param string $scope
  148. * @param string $method
  149. * @param callable $callback
  150. */
  151. public function listen($scope, $method, callable $callback) {
  152. $this->manager->listen($scope, $method, $callback);
  153. }
  154. /**
  155. * @param string $scope optional
  156. * @param string $method optional
  157. * @param callable $callback optional
  158. */
  159. public function removeListener($scope = null, $method = null, callable $callback = null) {
  160. $this->manager->removeListener($scope, $method, $callback);
  161. }
  162. /**
  163. * get the manager object
  164. *
  165. * @return Manager|PublicEmitter
  166. */
  167. public function getManager() {
  168. return $this->manager;
  169. }
  170. /**
  171. * get the session object
  172. *
  173. * @return ISession
  174. */
  175. public function getSession() {
  176. return $this->session;
  177. }
  178. /**
  179. * set the session object
  180. *
  181. * @param ISession $session
  182. */
  183. public function setSession(ISession $session) {
  184. if ($this->session instanceof ISession) {
  185. $this->session->close();
  186. }
  187. $this->session = $session;
  188. $this->activeUser = null;
  189. }
  190. /**
  191. * set the currently active user
  192. *
  193. * @param IUser|null $user
  194. */
  195. public function setUser($user) {
  196. if (is_null($user)) {
  197. $this->session->remove('user_id');
  198. } else {
  199. $this->session->set('user_id', $user->getUID());
  200. }
  201. $this->activeUser = $user;
  202. }
  203. /**
  204. * get the current active user
  205. *
  206. * @return IUser|null Current user, otherwise null
  207. */
  208. public function getUser() {
  209. // FIXME: This is a quick'n dirty work-around for the incognito mode as
  210. // described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
  211. if (OC_User::isIncognitoMode()) {
  212. return null;
  213. }
  214. if (is_null($this->activeUser)) {
  215. $uid = $this->session->get('user_id');
  216. if (is_null($uid)) {
  217. return null;
  218. }
  219. $this->activeUser = $this->manager->get($uid);
  220. if (is_null($this->activeUser)) {
  221. return null;
  222. }
  223. $this->validateSession();
  224. }
  225. return $this->activeUser;
  226. }
  227. /**
  228. * Validate whether the current session is valid
  229. *
  230. * - For token-authenticated clients, the token validity is checked
  231. * - For browsers, the session token validity is checked
  232. */
  233. protected function validateSession() {
  234. $token = null;
  235. $appPassword = $this->session->get('app_password');
  236. if (is_null($appPassword)) {
  237. try {
  238. $token = $this->session->getId();
  239. } catch (SessionNotAvailableException $ex) {
  240. return;
  241. }
  242. } else {
  243. $token = $appPassword;
  244. }
  245. if (!$this->validateToken($token)) {
  246. // Session was invalidated
  247. $this->logout();
  248. }
  249. }
  250. /**
  251. * Checks whether the user is logged in
  252. *
  253. * @return bool if logged in
  254. */
  255. public function isLoggedIn() {
  256. $user = $this->getUser();
  257. if (is_null($user)) {
  258. return false;
  259. }
  260. return $user->isEnabled();
  261. }
  262. /**
  263. * set the login name
  264. *
  265. * @param string|null $loginName for the logged in user
  266. */
  267. public function setLoginName($loginName) {
  268. if (is_null($loginName)) {
  269. $this->session->remove('loginname');
  270. } else {
  271. $this->session->set('loginname', $loginName);
  272. }
  273. }
  274. /**
  275. * get the login name of the current user
  276. *
  277. * @return string
  278. */
  279. public function getLoginName() {
  280. if ($this->activeUser) {
  281. return $this->session->get('loginname');
  282. }
  283. $uid = $this->session->get('user_id');
  284. if ($uid) {
  285. $this->activeUser = $this->manager->get($uid);
  286. return $this->session->get('loginname');
  287. }
  288. return null;
  289. }
  290. /**
  291. * @return null|string
  292. */
  293. public function getImpersonatingUserID(): ?string {
  294. return $this->session->get('oldUserId');
  295. }
  296. public function setImpersonatingUserID(bool $useCurrentUser = true): void {
  297. if ($useCurrentUser === false) {
  298. $this->session->remove('oldUserId');
  299. return;
  300. }
  301. $currentUser = $this->getUser();
  302. if ($currentUser === null) {
  303. throw new \OC\User\NoUserException();
  304. }
  305. $this->session->set('oldUserId', $currentUser->getUID());
  306. }
  307. /**
  308. * set the token id
  309. *
  310. * @param int|null $token that was used to log in
  311. */
  312. protected function setToken($token) {
  313. if ($token === null) {
  314. $this->session->remove('token-id');
  315. } else {
  316. $this->session->set('token-id', $token);
  317. }
  318. }
  319. /**
  320. * try to log in with the provided credentials
  321. *
  322. * @param string $uid
  323. * @param string $password
  324. * @return boolean|null
  325. * @throws LoginException
  326. */
  327. public function login($uid, $password) {
  328. $this->session->regenerateId();
  329. if ($this->validateToken($password, $uid)) {
  330. return $this->loginWithToken($password);
  331. }
  332. return $this->loginWithPassword($uid, $password);
  333. }
  334. /**
  335. * @param IUser $user
  336. * @param array $loginDetails
  337. * @param bool $regenerateSessionId
  338. * @return true returns true if login successful or an exception otherwise
  339. * @throws LoginException
  340. */
  341. public function completeLogin(IUser $user, array $loginDetails, $regenerateSessionId = true) {
  342. if (!$user->isEnabled()) {
  343. // disabled users can not log in
  344. // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
  345. $message = \OC::$server->getL10N('lib')->t('User disabled');
  346. throw new LoginException($message);
  347. }
  348. if ($regenerateSessionId) {
  349. $this->session->regenerateId();
  350. }
  351. $this->setUser($user);
  352. $this->setLoginName($loginDetails['loginName']);
  353. $isToken = isset($loginDetails['token']) && $loginDetails['token'] instanceof IToken;
  354. if ($isToken) {
  355. $this->setToken($loginDetails['token']->getId());
  356. $this->lockdownManager->setToken($loginDetails['token']);
  357. $firstTimeLogin = false;
  358. } else {
  359. $this->setToken(null);
  360. $firstTimeLogin = $user->updateLastLoginTimestamp();
  361. }
  362. $this->dispatcher->dispatchTyped(new PostLoginEvent(
  363. $user,
  364. $loginDetails['loginName'],
  365. $loginDetails['password'],
  366. $isToken
  367. ));
  368. $this->manager->emit('\OC\User', 'postLogin', [
  369. $user,
  370. $loginDetails['loginName'],
  371. $loginDetails['password'],
  372. $isToken,
  373. ]);
  374. if ($this->isLoggedIn()) {
  375. $this->prepareUserLogin($firstTimeLogin, $regenerateSessionId);
  376. return true;
  377. }
  378. $message = \OC::$server->getL10N('lib')->t('Login canceled by app');
  379. throw new LoginException($message);
  380. }
  381. /**
  382. * Tries to log in a client
  383. *
  384. * Checks token auth enforced
  385. * Checks 2FA enabled
  386. *
  387. * @param string $user
  388. * @param string $password
  389. * @param IRequest $request
  390. * @param OC\Security\Bruteforce\Throttler $throttler
  391. * @throws LoginException
  392. * @throws PasswordLoginForbiddenException
  393. * @return boolean
  394. */
  395. public function logClientIn($user,
  396. $password,
  397. IRequest $request,
  398. OC\Security\Bruteforce\Throttler $throttler) {
  399. $currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
  400. if ($this->manager instanceof PublicEmitter) {
  401. $this->manager->emit('\OC\User', 'preLogin', [$user, $password]);
  402. }
  403. try {
  404. $isTokenPassword = $this->isTokenPassword($password);
  405. } catch (ExpiredTokenException $e) {
  406. // Just return on an expired token no need to check further or record a failed login
  407. return false;
  408. }
  409. if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
  410. throw new PasswordLoginForbiddenException();
  411. }
  412. if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
  413. throw new PasswordLoginForbiddenException();
  414. }
  415. // Try to login with this username and password
  416. if (!$this->login($user, $password)) {
  417. // Failed, maybe the user used their email address
  418. $users = $this->manager->getByEmail($user);
  419. if (!(\count($users) === 1 && $this->login($users[0]->getUID(), $password))) {
  420. $this->logger->warning('Login failed: \'' . $user . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']);
  421. $throttler->registerAttempt('login', $request->getRemoteAddress(), ['user' => $user]);
  422. $this->dispatcher->dispatchTyped(new OC\Authentication\Events\LoginFailed($user));
  423. if ($currentDelay === 0) {
  424. $throttler->sleepDelay($request->getRemoteAddress(), 'login');
  425. }
  426. return false;
  427. }
  428. }
  429. if ($isTokenPassword) {
  430. $this->session->set('app_password', $password);
  431. } elseif ($this->supportsCookies($request)) {
  432. // Password login, but cookies supported -> create (browser) session token
  433. $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
  434. }
  435. return true;
  436. }
  437. protected function supportsCookies(IRequest $request) {
  438. if (!is_null($request->getCookie('cookie_test'))) {
  439. return true;
  440. }
  441. setcookie('cookie_test', 'test', $this->timeFactory->getTime() + 3600);
  442. return false;
  443. }
  444. private function isTokenAuthEnforced() {
  445. return $this->config->getSystemValue('token_auth_enforced', false);
  446. }
  447. protected function isTwoFactorEnforced($username) {
  448. Util::emitHook(
  449. '\OCA\Files_Sharing\API\Server2Server',
  450. 'preLoginNameUsedAsUserName',
  451. ['uid' => &$username]
  452. );
  453. $user = $this->manager->get($username);
  454. if (is_null($user)) {
  455. $users = $this->manager->getByEmail($username);
  456. if (empty($users)) {
  457. return false;
  458. }
  459. if (count($users) !== 1) {
  460. return true;
  461. }
  462. $user = $users[0];
  463. }
  464. // DI not possible due to cyclic dependencies :'-/
  465. return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
  466. }
  467. /**
  468. * Check if the given 'password' is actually a device token
  469. *
  470. * @param string $password
  471. * @return boolean
  472. * @throws ExpiredTokenException
  473. */
  474. public function isTokenPassword($password) {
  475. try {
  476. $this->tokenProvider->getToken($password);
  477. return true;
  478. } catch (ExpiredTokenException $e) {
  479. throw $e;
  480. } catch (InvalidTokenException $ex) {
  481. $this->logger->logException($ex, [
  482. 'level' => ILogger::DEBUG,
  483. 'message' => 'Token is not valid: ' . $ex->getMessage(),
  484. ]);
  485. return false;
  486. }
  487. }
  488. protected function prepareUserLogin($firstTimeLogin, $refreshCsrfToken = true) {
  489. if ($refreshCsrfToken) {
  490. // TODO: mock/inject/use non-static
  491. // Refresh the token
  492. \OC::$server->getCsrfTokenManager()->refreshToken();
  493. }
  494. //we need to pass the user name, which may differ from login name
  495. $user = $this->getUser()->getUID();
  496. OC_Util::setupFS($user);
  497. if ($firstTimeLogin) {
  498. // TODO: lock necessary?
  499. //trigger creation of user home and /files folder
  500. $userFolder = \OC::$server->getUserFolder($user);
  501. try {
  502. // copy skeleton
  503. \OC_Util::copySkeleton($user, $userFolder);
  504. } catch (NotPermittedException $ex) {
  505. // read only uses
  506. }
  507. // trigger any other initialization
  508. \OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
  509. }
  510. }
  511. /**
  512. * Tries to login the user with HTTP Basic Authentication
  513. *
  514. * @todo do not allow basic auth if the user is 2FA enforced
  515. * @param IRequest $request
  516. * @param OC\Security\Bruteforce\Throttler $throttler
  517. * @return boolean if the login was successful
  518. */
  519. public function tryBasicAuthLogin(IRequest $request,
  520. OC\Security\Bruteforce\Throttler $throttler) {
  521. if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
  522. try {
  523. if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
  524. /**
  525. * Add DAV authenticated. This should in an ideal world not be
  526. * necessary but the iOS App reads cookies from anywhere instead
  527. * only the DAV endpoint.
  528. * This makes sure that the cookies will be valid for the whole scope
  529. * @see https://github.com/owncloud/core/issues/22893
  530. */
  531. $this->session->set(
  532. Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
  533. );
  534. // Set the last-password-confirm session to make the sudo mode work
  535. $this->session->set('last-password-confirm', $this->timeFactory->getTime());
  536. return true;
  537. }
  538. } catch (PasswordLoginForbiddenException $ex) {
  539. // Nothing to do
  540. }
  541. }
  542. return false;
  543. }
  544. /**
  545. * Log an user in via login name and password
  546. *
  547. * @param string $uid
  548. * @param string $password
  549. * @return boolean
  550. * @throws LoginException if an app canceld the login process or the user is not enabled
  551. */
  552. private function loginWithPassword($uid, $password) {
  553. $user = $this->manager->checkPasswordNoLogging($uid, $password);
  554. if ($user === false) {
  555. // Password check failed
  556. return false;
  557. }
  558. return $this->completeLogin($user, ['loginName' => $uid, 'password' => $password], false);
  559. }
  560. /**
  561. * Log an user in with a given token (id)
  562. *
  563. * @param string $token
  564. * @return boolean
  565. * @throws LoginException if an app canceled the login process or the user is not enabled
  566. */
  567. private function loginWithToken($token) {
  568. try {
  569. $dbToken = $this->tokenProvider->getToken($token);
  570. } catch (InvalidTokenException $ex) {
  571. return false;
  572. }
  573. $uid = $dbToken->getUID();
  574. // When logging in with token, the password must be decrypted first before passing to login hook
  575. $password = '';
  576. try {
  577. $password = $this->tokenProvider->getPassword($dbToken, $token);
  578. } catch (PasswordlessTokenException $ex) {
  579. // Ignore and use empty string instead
  580. }
  581. $this->manager->emit('\OC\User', 'preLogin', [$uid, $password]);
  582. $user = $this->manager->get($uid);
  583. if (is_null($user)) {
  584. // user does not exist
  585. return false;
  586. }
  587. return $this->completeLogin(
  588. $user,
  589. [
  590. 'loginName' => $dbToken->getLoginName(),
  591. 'password' => $password,
  592. 'token' => $dbToken
  593. ],
  594. false);
  595. }
  596. /**
  597. * Create a new session token for the given user credentials
  598. *
  599. * @param IRequest $request
  600. * @param string $uid user UID
  601. * @param string $loginName login name
  602. * @param string $password
  603. * @param int $remember
  604. * @return boolean
  605. */
  606. public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
  607. if (is_null($this->manager->get($uid))) {
  608. // User does not exist
  609. return false;
  610. }
  611. $name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
  612. try {
  613. $sessionId = $this->session->getId();
  614. $pwd = $this->getPassword($password);
  615. // Make sure the current sessionId has no leftover tokens
  616. $this->tokenProvider->invalidateToken($sessionId);
  617. $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
  618. return true;
  619. } catch (SessionNotAvailableException $ex) {
  620. // This can happen with OCC, where a memory session is used
  621. // if a memory session is used, we shouldn't create a session token anyway
  622. return false;
  623. }
  624. }
  625. /**
  626. * Checks if the given password is a token.
  627. * If yes, the password is extracted from the token.
  628. * If no, the same password is returned.
  629. *
  630. * @param string $password either the login password or a device token
  631. * @return string|null the password or null if none was set in the token
  632. */
  633. private function getPassword($password) {
  634. if (is_null($password)) {
  635. // This is surely no token ;-)
  636. return null;
  637. }
  638. try {
  639. $token = $this->tokenProvider->getToken($password);
  640. try {
  641. return $this->tokenProvider->getPassword($token, $password);
  642. } catch (PasswordlessTokenException $ex) {
  643. return null;
  644. }
  645. } catch (InvalidTokenException $ex) {
  646. return $password;
  647. }
  648. }
  649. /**
  650. * @param IToken $dbToken
  651. * @param string $token
  652. * @return boolean
  653. */
  654. private function checkTokenCredentials(IToken $dbToken, $token) {
  655. // Check whether login credentials are still valid and the user was not disabled
  656. // This check is performed each 5 minutes
  657. $lastCheck = $dbToken->getLastCheck() ? : 0;
  658. $now = $this->timeFactory->getTime();
  659. if ($lastCheck > ($now - 60 * 5)) {
  660. // Checked performed recently, nothing to do now
  661. return true;
  662. }
  663. try {
  664. $pwd = $this->tokenProvider->getPassword($dbToken, $token);
  665. } catch (InvalidTokenException $ex) {
  666. // An invalid token password was used -> log user out
  667. return false;
  668. } catch (PasswordlessTokenException $ex) {
  669. // Token has no password
  670. if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
  671. $this->tokenProvider->invalidateToken($token);
  672. return false;
  673. }
  674. $dbToken->setLastCheck($now);
  675. return true;
  676. }
  677. // Invalidate token if the user is no longer active
  678. if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
  679. $this->tokenProvider->invalidateToken($token);
  680. return false;
  681. }
  682. // If the token password is no longer valid mark it as such
  683. if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false) {
  684. $this->tokenProvider->markPasswordInvalid($dbToken, $token);
  685. // User is logged out
  686. return false;
  687. }
  688. $dbToken->setLastCheck($now);
  689. return true;
  690. }
  691. /**
  692. * Check if the given token exists and performs password/user-enabled checks
  693. *
  694. * Invalidates the token if checks fail
  695. *
  696. * @param string $token
  697. * @param string $user login name
  698. * @return boolean
  699. */
  700. private function validateToken($token, $user = null) {
  701. try {
  702. $dbToken = $this->tokenProvider->getToken($token);
  703. } catch (InvalidTokenException $ex) {
  704. return false;
  705. }
  706. // Check if login names match
  707. if (!is_null($user) && $dbToken->getLoginName() !== $user) {
  708. // TODO: this makes it imposssible to use different login names on browser and client
  709. // e.g. login by e-mail 'user@example.com' on browser for generating the token will not
  710. // allow to use the client token with the login name 'user'.
  711. return false;
  712. }
  713. if (!$this->checkTokenCredentials($dbToken, $token)) {
  714. return false;
  715. }
  716. // Update token scope
  717. $this->lockdownManager->setToken($dbToken);
  718. $this->tokenProvider->updateTokenActivity($dbToken);
  719. return true;
  720. }
  721. /**
  722. * Tries to login the user with auth token header
  723. *
  724. * @param IRequest $request
  725. * @todo check remember me cookie
  726. * @return boolean
  727. */
  728. public function tryTokenLogin(IRequest $request) {
  729. $authHeader = $request->getHeader('Authorization');
  730. if (strpos($authHeader, 'Bearer ') === false) {
  731. // No auth header, let's try session id
  732. try {
  733. $token = $this->session->getId();
  734. } catch (SessionNotAvailableException $ex) {
  735. return false;
  736. }
  737. } else {
  738. $token = substr($authHeader, 7);
  739. }
  740. if (!$this->loginWithToken($token)) {
  741. return false;
  742. }
  743. if (!$this->validateToken($token)) {
  744. return false;
  745. }
  746. // Set the session variable so we know this is an app password
  747. $this->session->set('app_password', $token);
  748. return true;
  749. }
  750. /**
  751. * perform login using the magic cookie (remember login)
  752. *
  753. * @param string $uid the username
  754. * @param string $currentToken
  755. * @param string $oldSessionId
  756. * @return bool
  757. */
  758. public function loginWithCookie($uid, $currentToken, $oldSessionId) {
  759. $this->session->regenerateId();
  760. $this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]);
  761. $user = $this->manager->get($uid);
  762. if (is_null($user)) {
  763. // user does not exist
  764. return false;
  765. }
  766. // get stored tokens
  767. $tokens = $this->config->getUserKeys($uid, 'login_token');
  768. // test cookies token against stored tokens
  769. if (!in_array($currentToken, $tokens, true)) {
  770. return false;
  771. }
  772. // replace successfully used token with a new one
  773. $this->config->deleteUserValue($uid, 'login_token', $currentToken);
  774. $newToken = $this->random->generate(32);
  775. $this->config->setUserValue($uid, 'login_token', $newToken, $this->timeFactory->getTime());
  776. try {
  777. $sessionId = $this->session->getId();
  778. $token = $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
  779. } catch (SessionNotAvailableException $ex) {
  780. return false;
  781. } catch (InvalidTokenException $ex) {
  782. \OC::$server->getLogger()->warning('Renewing session token failed', ['app' => 'core']);
  783. return false;
  784. }
  785. $this->setMagicInCookie($user->getUID(), $newToken);
  786. //login
  787. $this->setUser($user);
  788. $this->setLoginName($token->getLoginName());
  789. $this->setToken($token->getId());
  790. $this->lockdownManager->setToken($token);
  791. $user->updateLastLoginTimestamp();
  792. $password = null;
  793. try {
  794. $password = $this->tokenProvider->getPassword($token, $sessionId);
  795. } catch (PasswordlessTokenException $ex) {
  796. // Ignore
  797. }
  798. $this->manager->emit('\OC\User', 'postRememberedLogin', [$user, $password]);
  799. return true;
  800. }
  801. /**
  802. * @param IUser $user
  803. */
  804. public function createRememberMeToken(IUser $user) {
  805. $token = $this->random->generate(32);
  806. $this->config->setUserValue($user->getUID(), 'login_token', $token, $this->timeFactory->getTime());
  807. $this->setMagicInCookie($user->getUID(), $token);
  808. }
  809. /**
  810. * logout the user from the session
  811. */
  812. public function logout() {
  813. $user = $this->getUser();
  814. $this->manager->emit('\OC\User', 'logout', [$user]);
  815. if ($user !== null) {
  816. try {
  817. $this->tokenProvider->invalidateToken($this->session->getId());
  818. } catch (SessionNotAvailableException $ex) {
  819. }
  820. }
  821. $this->setUser(null);
  822. $this->setLoginName(null);
  823. $this->setToken(null);
  824. $this->unsetMagicInCookie();
  825. $this->session->clear();
  826. $this->manager->emit('\OC\User', 'postLogout', [$user]);
  827. }
  828. /**
  829. * Set cookie value to use in next page load
  830. *
  831. * @param string $username username to be set
  832. * @param string $token
  833. */
  834. public function setMagicInCookie($username, $token) {
  835. $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
  836. $webRoot = \OC::$WEBROOT;
  837. if ($webRoot === '') {
  838. $webRoot = '/';
  839. }
  840. $maxAge = $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  841. \OC\Http\CookieHelper::setCookie(
  842. 'nc_username',
  843. $username,
  844. $maxAge,
  845. $webRoot,
  846. '',
  847. $secureCookie,
  848. true,
  849. \OC\Http\CookieHelper::SAMESITE_LAX
  850. );
  851. \OC\Http\CookieHelper::setCookie(
  852. 'nc_token',
  853. $token,
  854. $maxAge,
  855. $webRoot,
  856. '',
  857. $secureCookie,
  858. true,
  859. \OC\Http\CookieHelper::SAMESITE_LAX
  860. );
  861. try {
  862. \OC\Http\CookieHelper::setCookie(
  863. 'nc_session_id',
  864. $this->session->getId(),
  865. $maxAge,
  866. $webRoot,
  867. '',
  868. $secureCookie,
  869. true,
  870. \OC\Http\CookieHelper::SAMESITE_LAX
  871. );
  872. } catch (SessionNotAvailableException $ex) {
  873. // ignore
  874. }
  875. }
  876. /**
  877. * Remove cookie for "remember username"
  878. */
  879. public function unsetMagicInCookie() {
  880. //TODO: DI for cookies and IRequest
  881. $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
  882. unset($_COOKIE['nc_username']); //TODO: DI
  883. unset($_COOKIE['nc_token']);
  884. unset($_COOKIE['nc_session_id']);
  885. setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
  886. setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
  887. setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
  888. // old cookies might be stored under /webroot/ instead of /webroot
  889. // and Firefox doesn't like it!
  890. setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
  891. setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
  892. setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
  893. }
  894. /**
  895. * Update password of the browser session token if there is one
  896. *
  897. * @param string $password
  898. */
  899. public function updateSessionTokenPassword($password) {
  900. try {
  901. $sessionId = $this->session->getId();
  902. $token = $this->tokenProvider->getToken($sessionId);
  903. $this->tokenProvider->setPassword($token, $sessionId, $password);
  904. } catch (SessionNotAvailableException $ex) {
  905. // Nothing to do
  906. } catch (InvalidTokenException $ex) {
  907. // Nothing to do
  908. }
  909. }
  910. public function updateTokens(string $uid, string $password) {
  911. $this->tokenProvider->updatePasswords($uid, $password);
  912. }
  913. }