You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LoginController.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2017, Sandro Lutz <sandro.lutz@temparus.ch>
  5. * @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
  6. * @copyright Copyright (c) 2016, ownCloud, Inc.
  7. *
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author John Molakvoæ <skjnldsv@protonmail.com>
  12. * @author Julius Härtl <jus@bitgrid.net>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Michael Weimann <mail@michael-weimann.eu>
  15. * @author Rayn0r <andrew@ilpss8.myfirewall.org>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Kate Döen <kate.doeen@nextcloud.com>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OC\Core\Controller;
  35. use OC\AppFramework\Http\Request;
  36. use OC\Authentication\Login\Chain;
  37. use OC\Authentication\Login\LoginData;
  38. use OC\Authentication\WebAuthn\Manager as WebAuthnManager;
  39. use OC\User\Session;
  40. use OC_App;
  41. use OCA\User_LDAP\Configuration;
  42. use OCA\User_LDAP\Helper;
  43. use OCP\App\IAppManager;
  44. use OCP\AppFramework\Controller;
  45. use OCP\AppFramework\Http;
  46. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  47. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  48. use OCP\AppFramework\Http\Attribute\OpenAPI;
  49. use OCP\AppFramework\Http\Attribute\UseSession;
  50. use OCP\AppFramework\Http\DataResponse;
  51. use OCP\AppFramework\Http\RedirectResponse;
  52. use OCP\AppFramework\Http\TemplateResponse;
  53. use OCP\AppFramework\Services\IInitialState;
  54. use OCP\Defaults;
  55. use OCP\IConfig;
  56. use OCP\IL10N;
  57. use OCP\IRequest;
  58. use OCP\ISession;
  59. use OCP\IURLGenerator;
  60. use OCP\IUser;
  61. use OCP\IUserManager;
  62. use OCP\Notification\IManager;
  63. use OCP\Security\Bruteforce\IThrottler;
  64. use OCP\Util;
  65. class LoginController extends Controller {
  66. public const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
  67. public const LOGIN_MSG_USERDISABLED = 'userdisabled';
  68. public const LOGIN_MSG_CSRFCHECKFAILED = 'csrfCheckFailed';
  69. public function __construct(
  70. ?string $appName,
  71. IRequest $request,
  72. private IUserManager $userManager,
  73. private IConfig $config,
  74. private ISession $session,
  75. private Session $userSession,
  76. private IURLGenerator $urlGenerator,
  77. private Defaults $defaults,
  78. private IThrottler $throttler,
  79. private IInitialState $initialState,
  80. private WebAuthnManager $webAuthnManager,
  81. private IManager $manager,
  82. private IL10N $l10n,
  83. private IAppManager $appManager,
  84. ) {
  85. parent::__construct($appName, $request);
  86. }
  87. /**
  88. * @NoAdminRequired
  89. *
  90. * @return RedirectResponse
  91. */
  92. #[UseSession]
  93. #[FrontpageRoute(verb: 'GET', url: '/logout')]
  94. public function logout() {
  95. $loginToken = $this->request->getCookie('nc_token');
  96. if (!is_null($loginToken)) {
  97. $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
  98. }
  99. $this->userSession->logout();
  100. $response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
  101. 'core.login.showLoginForm',
  102. ['clear' => true] // this param the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
  103. ));
  104. $this->session->set('clearingExecutionContexts', '1');
  105. $this->session->close();
  106. if (
  107. $this->request->getServerProtocol() === 'https' &&
  108. !$this->request->isUserAgent([Request::USER_AGENT_CHROME, Request::USER_AGENT_ANDROID_MOBILE_CHROME])
  109. ) {
  110. $response->addHeader('Clear-Site-Data', '"cache", "storage"');
  111. }
  112. return $response;
  113. }
  114. /**
  115. * @PublicPage
  116. * @NoCSRFRequired
  117. *
  118. * @param string $user
  119. * @param string $redirect_url
  120. *
  121. * @return TemplateResponse|RedirectResponse
  122. */
  123. #[UseSession]
  124. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  125. #[FrontpageRoute(verb: 'GET', url: '/login')]
  126. public function showLoginForm(string $user = null, string $redirect_url = null): Http\Response {
  127. if ($this->userSession->isLoggedIn()) {
  128. return new RedirectResponse($this->urlGenerator->linkToDefaultPageUrl());
  129. }
  130. $loginMessages = $this->session->get('loginMessages');
  131. if (!$this->manager->isFairUseOfFreePushService()) {
  132. if (!is_array($loginMessages)) {
  133. $loginMessages = [[], []];
  134. }
  135. $loginMessages[1][] = $this->l10n->t('This community release of Nextcloud is unsupported and push notifications are limited.');
  136. }
  137. if (is_array($loginMessages)) {
  138. [$errors, $messages] = $loginMessages;
  139. $this->initialState->provideInitialState('loginMessages', $messages);
  140. $this->initialState->provideInitialState('loginErrors', $errors);
  141. }
  142. $this->session->remove('loginMessages');
  143. if ($user !== null && $user !== '') {
  144. $this->initialState->provideInitialState('loginUsername', $user);
  145. } else {
  146. $this->initialState->provideInitialState('loginUsername', '');
  147. }
  148. $this->initialState->provideInitialState(
  149. 'loginAutocomplete',
  150. $this->config->getSystemValue('login_form_autocomplete', true) === true
  151. );
  152. if (!empty($redirect_url)) {
  153. [$url, ] = explode('?', $redirect_url);
  154. if ($url !== $this->urlGenerator->linkToRoute('core.login.logout')) {
  155. $this->initialState->provideInitialState('loginRedirectUrl', $redirect_url);
  156. }
  157. }
  158. $this->initialState->provideInitialState(
  159. 'loginThrottleDelay',
  160. $this->throttler->getDelay($this->request->getRemoteAddress())
  161. );
  162. $this->setPasswordResetInitialState($user);
  163. $this->setEmailStates();
  164. $this->initialState->provideInitialState('webauthn-available', $this->webAuthnManager->isWebAuthnAvailable());
  165. $this->initialState->provideInitialState('hideLoginForm', $this->config->getSystemValueBool('hide_login_form', false));
  166. // OpenGraph Support: http://ogp.me/
  167. Util::addHeader('meta', ['property' => 'og:title', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
  168. Util::addHeader('meta', ['property' => 'og:description', 'content' => Util::sanitizeHTML($this->defaults->getSlogan())]);
  169. Util::addHeader('meta', ['property' => 'og:site_name', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
  170. Util::addHeader('meta', ['property' => 'og:url', 'content' => $this->urlGenerator->getAbsoluteURL('/')]);
  171. Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
  172. Util::addHeader('meta', ['property' => 'og:image', 'content' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-touch.png'))]);
  173. $parameters = [
  174. 'alt_login' => OC_App::getAlternativeLogIns(),
  175. 'pageTitle' => $this->l10n->t('Login'),
  176. ];
  177. $this->initialState->provideInitialState('countAlternativeLogins', count($parameters['alt_login']));
  178. $this->initialState->provideInitialState('alternativeLogins', $parameters['alt_login']);
  179. $this->initialState->provideInitialState('loginTimeout', $this->config->getSystemValueInt('login_form_timeout', 5 * 60));
  180. return new TemplateResponse(
  181. $this->appName,
  182. 'login',
  183. $parameters,
  184. TemplateResponse::RENDER_AS_GUEST,
  185. );
  186. }
  187. /**
  188. * Sets the password reset state
  189. *
  190. * @param string $username
  191. */
  192. private function setPasswordResetInitialState(?string $username): void {
  193. if ($username !== null && $username !== '') {
  194. $user = $this->userManager->get($username);
  195. } else {
  196. $user = null;
  197. }
  198. $passwordLink = $this->config->getSystemValueString('lost_password_link', '');
  199. $this->initialState->provideInitialState(
  200. 'loginResetPasswordLink',
  201. $passwordLink
  202. );
  203. $this->initialState->provideInitialState(
  204. 'loginCanResetPassword',
  205. $this->canResetPassword($passwordLink, $user)
  206. );
  207. }
  208. /**
  209. * Sets the initial state of whether or not a user is allowed to login with their email
  210. * initial state is passed in the array of 1 for email allowed and 0 for not allowed
  211. */
  212. private function setEmailStates(): void {
  213. $emailStates = []; // true: can login with email, false otherwise - default to true
  214. // check if user_ldap is enabled, and the required classes exist
  215. if ($this->appManager->isAppLoaded('user_ldap')
  216. && class_exists(Helper::class)) {
  217. $helper = \OCP\Server::get(Helper::class);
  218. $allPrefixes = $helper->getServerConfigurationPrefixes();
  219. // check each LDAP server the user is connected too
  220. foreach ($allPrefixes as $prefix) {
  221. $emailConfig = new Configuration($prefix);
  222. array_push($emailStates, $emailConfig->__get('ldapLoginFilterEmail'));
  223. }
  224. }
  225. $this->initialState->provideInitialState('emailStates', $emailStates);
  226. }
  227. /**
  228. * @param string|null $passwordLink
  229. * @param IUser|null $user
  230. *
  231. * Users may not change their passwords if:
  232. * - The account is disabled
  233. * - The backend doesn't support password resets
  234. * - The password reset function is disabled
  235. *
  236. * @return bool
  237. */
  238. private function canResetPassword(?string $passwordLink, ?IUser $user): bool {
  239. if ($passwordLink === 'disabled') {
  240. return false;
  241. }
  242. if (!$passwordLink && $user !== null) {
  243. return $user->canChangePassword();
  244. }
  245. if ($user !== null && $user->isEnabled() === false) {
  246. return false;
  247. }
  248. return true;
  249. }
  250. private function generateRedirect(?string $redirectUrl): RedirectResponse {
  251. if ($redirectUrl !== null && $this->userSession->isLoggedIn()) {
  252. $location = $this->urlGenerator->getAbsoluteURL($redirectUrl);
  253. // Deny the redirect if the URL contains a @
  254. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  255. if (!str_contains($location, '@')) {
  256. return new RedirectResponse($location);
  257. }
  258. }
  259. return new RedirectResponse($this->urlGenerator->linkToDefaultPageUrl());
  260. }
  261. /**
  262. * @PublicPage
  263. * @NoCSRFRequired
  264. * @BruteForceProtection(action=login)
  265. *
  266. * @return RedirectResponse
  267. */
  268. #[UseSession]
  269. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  270. #[FrontpageRoute(verb: 'POST', url: '/login')]
  271. public function tryLogin(Chain $loginChain,
  272. string $user = '',
  273. string $password = '',
  274. string $redirect_url = null,
  275. string $timezone = '',
  276. string $timezone_offset = ''): RedirectResponse {
  277. if (!$this->request->passesCSRFCheck()) {
  278. if ($this->userSession->isLoggedIn()) {
  279. // If the user is already logged in and the CSRF check does not pass then
  280. // simply redirect the user to the correct page as required. This is the
  281. // case when a user has already logged-in, in another tab.
  282. return $this->generateRedirect($redirect_url);
  283. }
  284. // Clear any auth remnants like cookies to ensure a clean login
  285. // For the next attempt
  286. $this->userSession->logout();
  287. return $this->createLoginFailedResponse(
  288. $user,
  289. $user,
  290. $redirect_url,
  291. self::LOGIN_MSG_CSRFCHECKFAILED
  292. );
  293. }
  294. $user = trim($user);
  295. if (strlen($user) > 255) {
  296. return $this->createLoginFailedResponse(
  297. $user,
  298. $user,
  299. $redirect_url,
  300. $this->l10n->t('Unsupported email length (>255)')
  301. );
  302. }
  303. $data = new LoginData(
  304. $this->request,
  305. $user,
  306. $password,
  307. $redirect_url,
  308. $timezone,
  309. $timezone_offset
  310. );
  311. $result = $loginChain->process($data);
  312. if (!$result->isSuccess()) {
  313. return $this->createLoginFailedResponse(
  314. $data->getUsername(),
  315. $user,
  316. $redirect_url,
  317. $result->getErrorMessage()
  318. );
  319. }
  320. if ($result->getRedirectUrl() !== null) {
  321. return new RedirectResponse($result->getRedirectUrl());
  322. }
  323. return $this->generateRedirect($redirect_url);
  324. }
  325. /**
  326. * Creates a login failed response.
  327. *
  328. * @param string $user
  329. * @param string $originalUser
  330. * @param string $redirect_url
  331. * @param string $loginMessage
  332. *
  333. * @return RedirectResponse
  334. */
  335. private function createLoginFailedResponse(
  336. $user, $originalUser, $redirect_url, string $loginMessage) {
  337. // Read current user and append if possible we need to
  338. // return the unmodified user otherwise we will leak the login name
  339. $args = $user !== null ? ['user' => $originalUser, 'direct' => 1] : [];
  340. if ($redirect_url !== null) {
  341. $args['redirect_url'] = $redirect_url;
  342. }
  343. $response = new RedirectResponse(
  344. $this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)
  345. );
  346. $response->throttle(['user' => substr($user, 0, 64)]);
  347. $this->session->set('loginMessages', [
  348. [$loginMessage], []
  349. ]);
  350. return $response;
  351. }
  352. /**
  353. * Confirm the user password
  354. *
  355. * @NoAdminRequired
  356. * @BruteForceProtection(action=sudo)
  357. *
  358. * @license GNU AGPL version 3 or any later version
  359. *
  360. * @param string $password The password of the user
  361. *
  362. * @return DataResponse<Http::STATUS_OK, array{lastLogin: int}, array{}>|DataResponse<Http::STATUS_FORBIDDEN, array<empty>, array{}>
  363. *
  364. * 200: Password confirmation succeeded
  365. * 403: Password confirmation failed
  366. */
  367. #[UseSession]
  368. #[NoCSRFRequired]
  369. #[FrontpageRoute(verb: 'POST', url: '/login/confirm')]
  370. public function confirmPassword(string $password): DataResponse {
  371. $loginName = $this->userSession->getLoginName();
  372. $loginResult = $this->userManager->checkPassword($loginName, $password);
  373. if ($loginResult === false) {
  374. $response = new DataResponse([], Http::STATUS_FORBIDDEN);
  375. $response->throttle(['loginName' => $loginName]);
  376. return $response;
  377. }
  378. $confirmTimestamp = time();
  379. $this->session->set('last-password-confirm', $confirmTimestamp);
  380. $this->throttler->resetDelay($this->request->getRemoteAddress(), 'sudo', ['loginName' => $loginName]);
  381. return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
  382. }
  383. }