Session.php 31 KB

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