Session.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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. $this->session->remove(Auth::DAV_AUTHENTICATED);
  340. }
  341. $this->setUser($user);
  342. $this->setLoginName($loginDetails['loginName']);
  343. $isToken = isset($loginDetails['token']) && $loginDetails['token'] instanceof IToken;
  344. if ($isToken) {
  345. $this->setToken($loginDetails['token']->getId());
  346. $this->lockdownManager->setToken($loginDetails['token']);
  347. $firstTimeLogin = false;
  348. } else {
  349. $this->setToken(null);
  350. $firstTimeLogin = $user->updateLastLoginTimestamp();
  351. }
  352. $this->dispatcher->dispatchTyped(new PostLoginEvent(
  353. $user,
  354. $loginDetails['loginName'],
  355. $loginDetails['password'],
  356. $isToken
  357. ));
  358. $this->manager->emit('\OC\User', 'postLogin', [
  359. $user,
  360. $loginDetails['loginName'],
  361. $loginDetails['password'],
  362. $isToken,
  363. ]);
  364. if ($this->isLoggedIn()) {
  365. $this->prepareUserLogin($firstTimeLogin, $regenerateSessionId);
  366. return true;
  367. }
  368. $message = \OC::$server->getL10N('lib')->t('Login canceled by app');
  369. throw new LoginException($message);
  370. }
  371. /**
  372. * Tries to log in a client
  373. *
  374. * Checks token auth enforced
  375. * Checks 2FA enabled
  376. *
  377. * @param string $user
  378. * @param string $password
  379. * @param IRequest $request
  380. * @param OC\Security\Bruteforce\Throttler $throttler
  381. * @throws LoginException
  382. * @throws PasswordLoginForbiddenException
  383. * @return boolean
  384. */
  385. public function logClientIn($user,
  386. $password,
  387. IRequest $request,
  388. OC\Security\Bruteforce\Throttler $throttler) {
  389. $currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
  390. if ($this->manager instanceof PublicEmitter) {
  391. $this->manager->emit('\OC\User', 'preLogin', [$user, $password]);
  392. }
  393. try {
  394. $isTokenPassword = $this->isTokenPassword($password);
  395. } catch (ExpiredTokenException $e) {
  396. // Just return on an expired token no need to check further or record a failed login
  397. return false;
  398. }
  399. if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
  400. throw new PasswordLoginForbiddenException();
  401. }
  402. if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
  403. throw new PasswordLoginForbiddenException();
  404. }
  405. // Try to login with this username and password
  406. if (!$this->login($user, $password)) {
  407. // Failed, maybe the user used their email address
  408. if (!filter_var($user, FILTER_VALIDATE_EMAIL)) {
  409. return false;
  410. }
  411. $users = $this->manager->getByEmail($user);
  412. if (!(\count($users) === 1 && $this->login($users[0]->getUID(), $password))) {
  413. $this->logger->warning('Login failed: \'' . $user . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']);
  414. $throttler->registerAttempt('login', $request->getRemoteAddress(), ['user' => $user]);
  415. $this->dispatcher->dispatchTyped(new OC\Authentication\Events\LoginFailed($user, $password));
  416. if ($currentDelay === 0) {
  417. $throttler->sleepDelay($request->getRemoteAddress(), 'login');
  418. }
  419. return false;
  420. }
  421. }
  422. if ($isTokenPassword) {
  423. $this->session->set('app_password', $password);
  424. } elseif ($this->supportsCookies($request)) {
  425. // Password login, but cookies supported -> create (browser) session token
  426. $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
  427. }
  428. return true;
  429. }
  430. protected function supportsCookies(IRequest $request) {
  431. if (!is_null($request->getCookie('cookie_test'))) {
  432. return true;
  433. }
  434. setcookie('cookie_test', 'test', $this->timeFactory->getTime() + 3600);
  435. return false;
  436. }
  437. private function isTokenAuthEnforced() {
  438. return $this->config->getSystemValue('token_auth_enforced', false);
  439. }
  440. protected function isTwoFactorEnforced($username) {
  441. Util::emitHook(
  442. '\OCA\Files_Sharing\API\Server2Server',
  443. 'preLoginNameUsedAsUserName',
  444. ['uid' => &$username]
  445. );
  446. $user = $this->manager->get($username);
  447. if (is_null($user)) {
  448. $users = $this->manager->getByEmail($username);
  449. if (empty($users)) {
  450. return false;
  451. }
  452. if (count($users) !== 1) {
  453. return true;
  454. }
  455. $user = $users[0];
  456. }
  457. // DI not possible due to cyclic dependencies :'-/
  458. return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
  459. }
  460. /**
  461. * Check if the given 'password' is actually a device token
  462. *
  463. * @param string $password
  464. * @return boolean
  465. * @throws ExpiredTokenException
  466. */
  467. public function isTokenPassword($password) {
  468. try {
  469. $this->tokenProvider->getToken($password);
  470. return true;
  471. } catch (ExpiredTokenException $e) {
  472. throw $e;
  473. } catch (InvalidTokenException $ex) {
  474. $this->logger->debug('Token is not valid: ' . $ex->getMessage(), [
  475. 'exception' => $ex,
  476. ]);
  477. return false;
  478. }
  479. }
  480. protected function prepareUserLogin($firstTimeLogin, $refreshCsrfToken = true) {
  481. if ($refreshCsrfToken) {
  482. // TODO: mock/inject/use non-static
  483. // Refresh the token
  484. \OC::$server->getCsrfTokenManager()->refreshToken();
  485. }
  486. if ($firstTimeLogin) {
  487. //we need to pass the user name, which may differ from login name
  488. $user = $this->getUser()->getUID();
  489. OC_Util::setupFS($user);
  490. // TODO: lock necessary?
  491. //trigger creation of user home and /files folder
  492. $userFolder = \OC::$server->getUserFolder($user);
  493. try {
  494. // copy skeleton
  495. \OC_Util::copySkeleton($user, $userFolder);
  496. } catch (NotPermittedException $ex) {
  497. // read only uses
  498. }
  499. // trigger any other initialization
  500. \OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
  501. }
  502. }
  503. /**
  504. * Tries to login the user with HTTP Basic Authentication
  505. *
  506. * @todo do not allow basic auth if the user is 2FA enforced
  507. * @param IRequest $request
  508. * @param OC\Security\Bruteforce\Throttler $throttler
  509. * @return boolean if the login was successful
  510. */
  511. public function tryBasicAuthLogin(IRequest $request,
  512. OC\Security\Bruteforce\Throttler $throttler) {
  513. if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
  514. try {
  515. if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
  516. /**
  517. * Add DAV authenticated. This should in an ideal world not be
  518. * necessary but the iOS App reads cookies from anywhere instead
  519. * only the DAV endpoint.
  520. * This makes sure that the cookies will be valid for the whole scope
  521. * @see https://github.com/owncloud/core/issues/22893
  522. */
  523. $this->session->set(
  524. Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
  525. );
  526. // Set the last-password-confirm session to make the sudo mode work
  527. $this->session->set('last-password-confirm', $this->timeFactory->getTime());
  528. return true;
  529. }
  530. // If credentials were provided, they need to be valid, otherwise we do boom
  531. throw new LoginException();
  532. } catch (PasswordLoginForbiddenException $ex) {
  533. // Nothing to do
  534. }
  535. }
  536. return false;
  537. }
  538. /**
  539. * Log an user in via login name and password
  540. *
  541. * @param string $uid
  542. * @param string $password
  543. * @return boolean
  544. * @throws LoginException if an app canceld the login process or the user is not enabled
  545. */
  546. private function loginWithPassword($uid, $password) {
  547. $user = $this->manager->checkPasswordNoLogging($uid, $password);
  548. if ($user === false) {
  549. // Password check failed
  550. return false;
  551. }
  552. return $this->completeLogin($user, ['loginName' => $uid, 'password' => $password], false);
  553. }
  554. /**
  555. * Log an user in with a given token (id)
  556. *
  557. * @param string $token
  558. * @return boolean
  559. * @throws LoginException if an app canceled the login process or the user is not enabled
  560. */
  561. private function loginWithToken($token) {
  562. try {
  563. $dbToken = $this->tokenProvider->getToken($token);
  564. } catch (InvalidTokenException $ex) {
  565. return false;
  566. }
  567. $uid = $dbToken->getUID();
  568. // When logging in with token, the password must be decrypted first before passing to login hook
  569. $password = '';
  570. try {
  571. $password = $this->tokenProvider->getPassword($dbToken, $token);
  572. } catch (PasswordlessTokenException $ex) {
  573. // Ignore and use empty string instead
  574. }
  575. $this->manager->emit('\OC\User', 'preLogin', [$dbToken->getLoginName(), $password]);
  576. $user = $this->manager->get($uid);
  577. if (is_null($user)) {
  578. // user does not exist
  579. return false;
  580. }
  581. return $this->completeLogin(
  582. $user,
  583. [
  584. 'loginName' => $dbToken->getLoginName(),
  585. 'password' => $password,
  586. 'token' => $dbToken
  587. ],
  588. false);
  589. }
  590. /**
  591. * Create a new session token for the given user credentials
  592. *
  593. * @param IRequest $request
  594. * @param string $uid user UID
  595. * @param string $loginName login name
  596. * @param string $password
  597. * @param int $remember
  598. * @return boolean
  599. */
  600. public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
  601. if (is_null($this->manager->get($uid))) {
  602. // User does not exist
  603. return false;
  604. }
  605. $name = isset($request->server['HTTP_USER_AGENT']) ? mb_convert_encoding($request->server['HTTP_USER_AGENT'], 'UTF-8', 'ISO-8859-1') : 'unknown browser';
  606. try {
  607. $sessionId = $this->session->getId();
  608. $pwd = $this->getPassword($password);
  609. // Make sure the current sessionId has no leftover tokens
  610. $this->tokenProvider->invalidateToken($sessionId);
  611. $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
  612. return true;
  613. } catch (SessionNotAvailableException $ex) {
  614. // This can happen with OCC, where a memory session is used
  615. // if a memory session is used, we shouldn't create a session token anyway
  616. return false;
  617. }
  618. }
  619. /**
  620. * Checks if the given password is a token.
  621. * If yes, the password is extracted from the token.
  622. * If no, the same password is returned.
  623. *
  624. * @param string $password either the login password or a device token
  625. * @return string|null the password or null if none was set in the token
  626. */
  627. private function getPassword($password) {
  628. if (is_null($password)) {
  629. // This is surely no token ;-)
  630. return null;
  631. }
  632. try {
  633. $token = $this->tokenProvider->getToken($password);
  634. try {
  635. return $this->tokenProvider->getPassword($token, $password);
  636. } catch (PasswordlessTokenException $ex) {
  637. return null;
  638. }
  639. } catch (InvalidTokenException $ex) {
  640. return $password;
  641. }
  642. }
  643. /**
  644. * @param IToken $dbToken
  645. * @param string $token
  646. * @return boolean
  647. */
  648. private function checkTokenCredentials(IToken $dbToken, $token) {
  649. // Check whether login credentials are still valid and the user was not disabled
  650. // This check is performed each 5 minutes
  651. $lastCheck = $dbToken->getLastCheck() ? : 0;
  652. $now = $this->timeFactory->getTime();
  653. if ($lastCheck > ($now - 60 * 5)) {
  654. // Checked performed recently, nothing to do now
  655. return true;
  656. }
  657. try {
  658. $pwd = $this->tokenProvider->getPassword($dbToken, $token);
  659. } catch (InvalidTokenException $ex) {
  660. // An invalid token password was used -> log user out
  661. return false;
  662. } catch (PasswordlessTokenException $ex) {
  663. // Token has no password
  664. if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
  665. $this->tokenProvider->invalidateToken($token);
  666. return false;
  667. }
  668. $dbToken->setLastCheck($now);
  669. $this->tokenProvider->updateToken($dbToken);
  670. return true;
  671. }
  672. // Invalidate token if the user is no longer active
  673. if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
  674. $this->tokenProvider->invalidateToken($token);
  675. return false;
  676. }
  677. // If the token password is no longer valid mark it as such
  678. if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false) {
  679. $this->tokenProvider->markPasswordInvalid($dbToken, $token);
  680. // User is logged out
  681. return false;
  682. }
  683. $dbToken->setLastCheck($now);
  684. $this->tokenProvider->updateToken($dbToken);
  685. return true;
  686. }
  687. /**
  688. * Check if the given token exists and performs password/user-enabled checks
  689. *
  690. * Invalidates the token if checks fail
  691. *
  692. * @param string $token
  693. * @param string $user login name
  694. * @return boolean
  695. */
  696. private function validateToken($token, $user = null) {
  697. try {
  698. $dbToken = $this->tokenProvider->getToken($token);
  699. } catch (InvalidTokenException $ex) {
  700. return false;
  701. }
  702. // Check if login names match
  703. if (!is_null($user) && $dbToken->getLoginName() !== $user) {
  704. // TODO: this makes it impossible to use different login names on browser and client
  705. // e.g. login by e-mail 'user@example.com' on browser for generating the token will not
  706. // allow to use the client token with the login name 'user'.
  707. $this->logger->error('App token login name does not match', [
  708. 'tokenLoginName' => $dbToken->getLoginName(),
  709. 'sessionLoginName' => $user,
  710. ]);
  711. return false;
  712. }
  713. if (!$this->checkTokenCredentials($dbToken, $token)) {
  714. return false;
  715. }
  716. // Update token scope
  717. $this->lockdownManager->setToken($dbToken);
  718. $this->tokenProvider->updateTokenActivity($dbToken);
  719. return true;
  720. }
  721. /**
  722. * Tries to login the user with auth token header
  723. *
  724. * @param IRequest $request
  725. * @todo check remember me cookie
  726. * @return boolean
  727. */
  728. public function tryTokenLogin(IRequest $request) {
  729. $authHeader = $request->getHeader('Authorization');
  730. if (strpos($authHeader, 'Bearer ') === 0) {
  731. $token = substr($authHeader, 7);
  732. } else {
  733. // No auth header, let's try session id
  734. try {
  735. $token = $this->session->getId();
  736. } catch (SessionNotAvailableException $ex) {
  737. return false;
  738. }
  739. }
  740. if (!$this->loginWithToken($token)) {
  741. return false;
  742. }
  743. if (!$this->validateToken($token)) {
  744. return false;
  745. }
  746. try {
  747. $dbToken = $this->tokenProvider->getToken($token);
  748. } catch (InvalidTokenException $e) {
  749. // Can't really happen but better save than sorry
  750. return true;
  751. }
  752. // Remember me tokens are not app_passwords
  753. if ($dbToken->getRemember() === IToken::DO_NOT_REMEMBER) {
  754. // Set the session variable so we know this is an app password
  755. $this->session->set('app_password', $token);
  756. }
  757. return true;
  758. }
  759. /**
  760. * perform login using the magic cookie (remember login)
  761. *
  762. * @param string $uid the username
  763. * @param string $currentToken
  764. * @param string $oldSessionId
  765. * @return bool
  766. */
  767. public function loginWithCookie($uid, $currentToken, $oldSessionId) {
  768. $this->session->regenerateId();
  769. $this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]);
  770. $user = $this->manager->get($uid);
  771. if (is_null($user)) {
  772. // user does not exist
  773. return false;
  774. }
  775. // get stored tokens
  776. $tokens = $this->config->getUserKeys($uid, 'login_token');
  777. // test cookies token against stored tokens
  778. if (!in_array($currentToken, $tokens, true)) {
  779. $this->logger->info('Tried to log in {uid} but could not verify token', [
  780. 'app' => 'core',
  781. 'uid' => $uid,
  782. ]);
  783. return false;
  784. }
  785. // replace successfully used token with a new one
  786. $this->config->deleteUserValue($uid, 'login_token', $currentToken);
  787. $newToken = $this->random->generate(32);
  788. $this->config->setUserValue($uid, 'login_token', $newToken, (string)$this->timeFactory->getTime());
  789. try {
  790. $sessionId = $this->session->getId();
  791. $token = $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
  792. } catch (SessionNotAvailableException $ex) {
  793. $this->logger->warning('Could not renew session token for {uid} because the session is unavailable', [
  794. 'app' => 'core',
  795. 'uid' => $uid,
  796. ]);
  797. return false;
  798. } catch (InvalidTokenException $ex) {
  799. $this->logger->warning('Renewing session token failed', ['app' => 'core']);
  800. return false;
  801. }
  802. $this->setMagicInCookie($user->getUID(), $newToken);
  803. //login
  804. $this->setUser($user);
  805. $this->setLoginName($token->getLoginName());
  806. $this->setToken($token->getId());
  807. $this->lockdownManager->setToken($token);
  808. $user->updateLastLoginTimestamp();
  809. $password = null;
  810. try {
  811. $password = $this->tokenProvider->getPassword($token, $sessionId);
  812. } catch (PasswordlessTokenException $ex) {
  813. // Ignore
  814. }
  815. $this->manager->emit('\OC\User', 'postRememberedLogin', [$user, $password]);
  816. return true;
  817. }
  818. /**
  819. * @param IUser $user
  820. */
  821. public function createRememberMeToken(IUser $user) {
  822. $token = $this->random->generate(32);
  823. $this->config->setUserValue($user->getUID(), 'login_token', $token, (string)$this->timeFactory->getTime());
  824. $this->setMagicInCookie($user->getUID(), $token);
  825. }
  826. /**
  827. * logout the user from the session
  828. */
  829. public function logout() {
  830. $user = $this->getUser();
  831. $this->manager->emit('\OC\User', 'logout', [$user]);
  832. if ($user !== null) {
  833. try {
  834. $this->tokenProvider->invalidateToken($this->session->getId());
  835. } catch (SessionNotAvailableException $ex) {
  836. }
  837. }
  838. $this->setUser(null);
  839. $this->setLoginName(null);
  840. $this->setToken(null);
  841. $this->unsetMagicInCookie();
  842. $this->session->clear();
  843. $this->manager->emit('\OC\User', 'postLogout', [$user]);
  844. }
  845. /**
  846. * Set cookie value to use in next page load
  847. *
  848. * @param string $username username to be set
  849. * @param string $token
  850. */
  851. public function setMagicInCookie($username, $token) {
  852. $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
  853. $webRoot = \OC::$WEBROOT;
  854. if ($webRoot === '') {
  855. $webRoot = '/';
  856. }
  857. $maxAge = $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  858. \OC\Http\CookieHelper::setCookie(
  859. 'nc_username',
  860. $username,
  861. $maxAge,
  862. $webRoot,
  863. '',
  864. $secureCookie,
  865. true,
  866. \OC\Http\CookieHelper::SAMESITE_LAX
  867. );
  868. \OC\Http\CookieHelper::setCookie(
  869. 'nc_token',
  870. $token,
  871. $maxAge,
  872. $webRoot,
  873. '',
  874. $secureCookie,
  875. true,
  876. \OC\Http\CookieHelper::SAMESITE_LAX
  877. );
  878. try {
  879. \OC\Http\CookieHelper::setCookie(
  880. 'nc_session_id',
  881. $this->session->getId(),
  882. $maxAge,
  883. $webRoot,
  884. '',
  885. $secureCookie,
  886. true,
  887. \OC\Http\CookieHelper::SAMESITE_LAX
  888. );
  889. } catch (SessionNotAvailableException $ex) {
  890. // ignore
  891. }
  892. }
  893. /**
  894. * Remove cookie for "remember username"
  895. */
  896. public function unsetMagicInCookie() {
  897. //TODO: DI for cookies and IRequest
  898. $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
  899. unset($_COOKIE['nc_username']); //TODO: DI
  900. unset($_COOKIE['nc_token']);
  901. unset($_COOKIE['nc_session_id']);
  902. setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
  903. setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
  904. setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
  905. // old cookies might be stored under /webroot/ instead of /webroot
  906. // and Firefox doesn't like it!
  907. setcookie('nc_username', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
  908. setcookie('nc_token', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
  909. setcookie('nc_session_id', '', $this->timeFactory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
  910. }
  911. /**
  912. * Update password of the browser session token if there is one
  913. *
  914. * @param string $password
  915. */
  916. public function updateSessionTokenPassword($password) {
  917. try {
  918. $sessionId = $this->session->getId();
  919. $token = $this->tokenProvider->getToken($sessionId);
  920. $this->tokenProvider->setPassword($token, $sessionId, $password);
  921. } catch (SessionNotAvailableException $ex) {
  922. // Nothing to do
  923. } catch (InvalidTokenException $ex) {
  924. // Nothing to do
  925. }
  926. }
  927. public function updateTokens(string $uid, string $password) {
  928. $this->tokenProvider->updatePasswords($uid, $password);
  929. }
  930. }