* @author Bernhard Posselt * @author Bjoern Schiessle * @author Christoph Wurst * @author Daniel Kesselberg * @author Joas Schilling * @author Julius Haertl * @author Julius Härtl * @author Lukas Reschke * @author Morris Jobke * @author Rémy Jacquin * @author Robin Appelman * @author Roeland Jago Douma * @author Thomas Müller * @author Victor Dubiniuk * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see * */ namespace OC\Core\Controller; use Exception; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\JSONResponse; use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Services\IInitialState; use OCP\Defaults; use OCP\Encryption\IEncryptionModule; use OCP\Encryption\IManager; use OCP\EventDispatcher\IEventDispatcher; use OCP\HintException; use OCP\IConfig; use OCP\IL10N; use OCP\IRequest; use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserManager; use OCP\Mail\IMailer; use OCP\Security\VerificationToken\IVerificationToken; use OCP\Security\VerificationToken\InvalidTokenException; use OC\Authentication\TwoFactorAuth\Manager; use OC\Core\Events\BeforePasswordResetEvent; use OC\Core\Events\PasswordResetEvent; use OC\Core\Exception\ResetPasswordException; use OC\Security\RateLimiting\Exception\RateLimitExceededException; use OC\Security\RateLimiting\Limiter; use Psr\Log\LoggerInterface; use function array_filter; use function count; use function reset; /** * Class LostController * * Successfully changing a password will emit the post_passwordReset hook. * * @package OC\Core\Controller */ class LostController extends Controller { protected IURLGenerator $urlGenerator; protected IUserManager $userManager; protected Defaults $defaults; protected IL10N $l10n; protected string $from; protected IManager $encryptionManager; protected IConfig $config; protected IMailer $mailer; private LoggerInterface $logger; private Manager $twoFactorManager; private IInitialState $initialState; private IVerificationToken $verificationToken; private IEventDispatcher $eventDispatcher; private Limiter $limiter; public function __construct( string $appName, IRequest $request, IURLGenerator $urlGenerator, IUserManager $userManager, Defaults $defaults, IL10N $l10n, IConfig $config, string $defaultMailAddress, IManager $encryptionManager, IMailer $mailer, LoggerInterface $logger, Manager $twoFactorManager, IInitialState $initialState, IVerificationToken $verificationToken, IEventDispatcher $eventDispatcher, Limiter $limiter ) { parent::__construct($appName, $request); $this->urlGenerator = $urlGenerator; $this->userManager = $userManager; $this->defaults = $defaults; $this->l10n = $l10n; $this->from = $defaultMailAddress; $this->encryptionManager = $encryptionManager; $this->config = $config; $this->mailer = $mailer; $this->logger = $logger; $this->twoFactorManager = $twoFactorManager; $this->initialState = $initialState; $this->verificationToken = $verificationToken; $this->eventDispatcher = $eventDispatcher; $this->limiter = $limiter; } /** * Someone wants to reset their password: * * @PublicPage * @NoCSRFRequired * @BruteForceProtection(action=passwordResetEmail) * @AnonRateThrottle(limit=10, period=300) */ public function resetform(string $token, string $userId): TemplateResponse { try { $this->checkPasswordResetToken($token, $userId); } catch (Exception $e) { if ($this->config->getSystemValue('lost_password_link', '') !== 'disabled' || ($e instanceof InvalidTokenException && !in_array($e->getCode(), [InvalidTokenException::TOKEN_NOT_FOUND, InvalidTokenException::USER_UNKNOWN])) ) { $response = new TemplateResponse( 'core', 'error', [ "errors" => [["error" => $e->getMessage()]] ], TemplateResponse::RENDER_AS_GUEST ); $response->throttle(); return $response; } return new TemplateResponse('core', 'error', [ 'errors' => [['error' => $this->l10n->t('Password reset is disabled')]] ], TemplateResponse::RENDER_AS_GUEST ); } $this->initialState->provideInitialState('resetPasswordUser', $userId); $this->initialState->provideInitialState('resetPasswordTarget', $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', ['userId' => $userId, 'token' => $token]) ); return new TemplateResponse( 'core', 'login', [], 'guest' ); } /** * @throws Exception */ protected function checkPasswordResetToken(string $token, string $userId): void { try { $user = $this->userManager->get($userId); $this->verificationToken->check($token, $user, 'lostpassword', $user ? $user->getEMailAddress() : '', true); } catch (InvalidTokenException $e) { $error = $e->getCode() === InvalidTokenException::TOKEN_EXPIRED ? $this->l10n->t('Could not reset password because the token is expired') : $this->l10n->t('Could not reset password because the token is invalid'); throw new Exception($error, (int)$e->getCode(), $e); } } private function error(string $message, array $additional = []): array { return array_merge(['status' => 'error', 'msg' => $message], $additional); } private function success(array $data = []): array { return array_merge($data, ['status' => 'success']); } /** * @PublicPage * @BruteForceProtection(action=passwordResetEmail) * @AnonRateThrottle(limit=10, period=300) */ public function email(string $user): JSONResponse { if ($this->config->getSystemValue('lost_password_link', '') !== '') { return new JSONResponse($this->error($this->l10n->t('Password reset is disabled'))); } $user = trim($user); \OCP\Util::emitHook( '\OCA\Files_Sharing\API\Server2Server', 'preLoginNameUsedAsUserName', ['uid' => &$user] ); // FIXME: use HTTP error codes try { $this->sendEmail($user); } catch (ResetPasswordException $e) { // Ignore the error since we do not want to leak this info $this->logger->warning('Could not send password reset email: ' . $e->getMessage()); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); } $response = new JSONResponse($this->success()); $response->throttle(); return $response; } /** * @PublicPage * @BruteForceProtection(action=passwordResetEmail) * @AnonRateThrottle(limit=10, period=300) */ public function setPassword(string $token, string $userId, string $password, bool $proceed): JSONResponse { if ($this->encryptionManager->isEnabled() && !$proceed) { $encryptionModules = $this->encryptionManager->getEncryptionModules(); foreach ($encryptionModules as $module) { /** @var IEncryptionModule $instance */ $instance = call_user_func($module['callback']); // this way we can find out whether per-user keys are used or a system wide encryption key if ($instance->needDetailedAccessList()) { return new JSONResponse($this->error('', ['encryption' => true])); } } } try { $this->checkPasswordResetToken($token, $userId); $user = $this->userManager->get($userId); $this->eventDispatcher->dispatchTyped(new BeforePasswordResetEvent($user, $password)); \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', ['uid' => $userId, 'password' => $password]); if (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) { throw new HintException('Password too long', $this->l10n->t('Password is too long. Maximum allowed length is 469 characters.')); } if (!$user->setPassword($password)) { throw new Exception(); } $this->eventDispatcher->dispatchTyped(new PasswordResetEvent($user, $password)); \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', ['uid' => $userId, 'password' => $password]); $this->twoFactorManager->clearTwoFactorPending($userId); $this->config->deleteUserValue($userId, 'core', 'lostpassword'); @\OC::$server->getUserSession()->unsetMagicInCookie(); } catch (HintException $e) { $response = new JSONResponse($this->error($e->getHint())); $response->throttle(); return $response; } catch (Exception $e) { $response = new JSONResponse($this->error($e->getMessage())); $response->throttle(); return $response; } return new JSONResponse($this->success(['user' => $userId])); } /** * @throws ResetPasswordException * @throws \OCP\PreConditionNotMetException */ protected function sendEmail(string $input): void { $user = $this->findUserByIdOrMail($input); $email = $user->getEMailAddress(); if (empty($email)) { throw new ResetPasswordException('Could not send reset e-mail since there is no email for username ' . $input); } try { $this->limiter->registerUserRequest('lostpasswordemail', 5, 1800, $user); } catch (RateLimitExceededException $e) { throw new ResetPasswordException('Could not send reset e-mail, 5 of them were already sent in the last 30 minutes', 0, $e); } // Generate the token. It is stored encrypted in the database with the // secret being the users' email address appended with the system secret. // This makes the token automatically invalidate once the user changes // their email address. $token = $this->verificationToken->create($user, 'lostpassword', $email); $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $user->getUID(), 'token' => $token]); $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [ 'link' => $link, ]); $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()])); $emailTemplate->addHeader(); $emailTemplate->addHeading($this->l10n->t('Password reset')); $emailTemplate->addBodyText( htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')), $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.') ); $emailTemplate->addBodyButton( htmlspecialchars($this->l10n->t('Reset your password')), $link, false ); $emailTemplate->addFooter(); try { $message = $this->mailer->createMessage(); $message->setTo([$email => $user->getDisplayName()]); $message->setFrom([$this->from => $this->defaults->getName()]); $message->useTemplate($emailTemplate); $this->mailer->send($message); } catch (Exception $e) { // Log the exception and continue $this->logger->error($e->getMessage(), ['app' => 'core', 'exception' => $e]); } } /** * @throws ResetPasswordException */ protected function findUserByIdOrMail(string $input): IUser { $user = $this->userManager->get($input); if ($user instanceof IUser) { if (!$user->isEnabled()) { throw new ResetPasswordException('User ' . $user->getUID() . ' is disabled'); } return $user; } $users = array_filter($this->userManager->getByEmail($input), function (IUser $user) { return $user->isEnabled(); }); if (count($users) === 1) { return reset($users); } throw new ResetPasswordException('Could not find user ' . $input); } } 'n102' href='#n102'>102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398