Session.php 30 KB

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