Session.php 29 KB

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