Session.php 29 KB

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