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.

Session.php 30KB

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