Session.php 28 KB

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