Session.php 29 KB

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