1
0

Session.php 30 KB

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