Session.php 31 KB

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