Session.php 30 KB

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