Session.php 31 KB

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