1
0

Session.php 31 KB

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