1
0

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