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.

LostController.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Julius Haertl <jus@bitgrid.net>
  12. * @author Julius Härtl <jus@bitgrid.net>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Rémy Jacquin <remy@remyj.fr>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Roeland Jago Douma <roeland@famdouma.nl>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  20. *
  21. * @license AGPL-3.0
  22. *
  23. * This code is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU Affero General Public License, version 3,
  25. * as published by the Free Software Foundation.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU Affero General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU Affero General Public License, version 3,
  33. * along with this program. If not, see <http://www.gnu.org/licenses/>
  34. *
  35. */
  36. namespace OC\Core\Controller;
  37. use function array_filter;
  38. use function count;
  39. use OC\Authentication\TwoFactorAuth\Manager;
  40. use OC\Core\Exception\ResetPasswordException;
  41. use OC\HintException;
  42. use OCP\AppFramework\Controller;
  43. use OCP\AppFramework\Http\JSONResponse;
  44. use OCP\AppFramework\Http\TemplateResponse;
  45. use OCP\AppFramework\Utility\ITimeFactory;
  46. use OCP\Defaults;
  47. use OCP\Encryption\IEncryptionModule;
  48. use OCP\Encryption\IManager;
  49. use OCP\IConfig;
  50. use OCP\IInitialStateService;
  51. use OCP\IL10N;
  52. use OCP\ILogger;
  53. use OCP\IRequest;
  54. use OCP\IURLGenerator;
  55. use OCP\IUser;
  56. use OCP\IUserManager;
  57. use OCP\Mail\IMailer;
  58. use OCP\Security\ICrypto;
  59. use OCP\Security\ISecureRandom;
  60. use function reset;
  61. /**
  62. * Class LostController
  63. *
  64. * Successfully changing a password will emit the post_passwordReset hook.
  65. *
  66. * @package OC\Core\Controller
  67. */
  68. class LostController extends Controller {
  69. /** @var IURLGenerator */
  70. protected $urlGenerator;
  71. /** @var IUserManager */
  72. protected $userManager;
  73. /** @var Defaults */
  74. protected $defaults;
  75. /** @var IL10N */
  76. protected $l10n;
  77. /** @var string */
  78. protected $from;
  79. /** @var IManager */
  80. protected $encryptionManager;
  81. /** @var IConfig */
  82. protected $config;
  83. /** @var ISecureRandom */
  84. protected $secureRandom;
  85. /** @var IMailer */
  86. protected $mailer;
  87. /** @var ITimeFactory */
  88. protected $timeFactory;
  89. /** @var ICrypto */
  90. protected $crypto;
  91. /** @var ILogger */
  92. private $logger;
  93. /** @var Manager */
  94. private $twoFactorManager;
  95. /** @var IInitialStateService */
  96. private $initialStateService;
  97. /**
  98. * @param string $appName
  99. * @param IRequest $request
  100. * @param IURLGenerator $urlGenerator
  101. * @param IUserManager $userManager
  102. * @param Defaults $defaults
  103. * @param IL10N $l10n
  104. * @param IConfig $config
  105. * @param ISecureRandom $secureRandom
  106. * @param string $defaultMailAddress
  107. * @param IManager $encryptionManager
  108. * @param IMailer $mailer
  109. * @param ITimeFactory $timeFactory
  110. * @param ICrypto $crypto
  111. */
  112. public function __construct($appName,
  113. IRequest $request,
  114. IURLGenerator $urlGenerator,
  115. IUserManager $userManager,
  116. Defaults $defaults,
  117. IL10N $l10n,
  118. IConfig $config,
  119. ISecureRandom $secureRandom,
  120. $defaultMailAddress,
  121. IManager $encryptionManager,
  122. IMailer $mailer,
  123. ITimeFactory $timeFactory,
  124. ICrypto $crypto,
  125. ILogger $logger,
  126. Manager $twoFactorManager,
  127. IInitialStateService $initialStateService) {
  128. parent::__construct($appName, $request);
  129. $this->urlGenerator = $urlGenerator;
  130. $this->userManager = $userManager;
  131. $this->defaults = $defaults;
  132. $this->l10n = $l10n;
  133. $this->secureRandom = $secureRandom;
  134. $this->from = $defaultMailAddress;
  135. $this->encryptionManager = $encryptionManager;
  136. $this->config = $config;
  137. $this->mailer = $mailer;
  138. $this->timeFactory = $timeFactory;
  139. $this->crypto = $crypto;
  140. $this->logger = $logger;
  141. $this->twoFactorManager = $twoFactorManager;
  142. $this->initialStateService = $initialStateService;
  143. }
  144. /**
  145. * Someone wants to reset their password:
  146. *
  147. * @PublicPage
  148. * @NoCSRFRequired
  149. *
  150. * @param string $token
  151. * @param string $userId
  152. * @return TemplateResponse
  153. */
  154. public function resetform($token, $userId) {
  155. if ($this->config->getSystemValue('lost_password_link', '') !== '') {
  156. return new TemplateResponse('core', 'error', [
  157. 'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
  158. ],
  159. 'guest'
  160. );
  161. }
  162. try {
  163. $this->checkPasswordResetToken($token, $userId);
  164. } catch (\Exception $e) {
  165. return new TemplateResponse(
  166. 'core', 'error', [
  167. "errors" => [["error" => $e->getMessage()]]
  168. ],
  169. 'guest'
  170. );
  171. }
  172. $this->initialStateService->provideInitialState('core', 'resetPasswordUser', $userId);
  173. $this->initialStateService->provideInitialState('core', 'resetPasswordTarget',
  174. $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', ['userId' => $userId, 'token' => $token])
  175. );
  176. return new TemplateResponse(
  177. 'core',
  178. 'login',
  179. [],
  180. 'guest'
  181. );
  182. }
  183. /**
  184. * @param string $token
  185. * @param string $userId
  186. * @throws \Exception
  187. */
  188. protected function checkPasswordResetToken($token, $userId) {
  189. $user = $this->userManager->get($userId);
  190. if ($user === null || !$user->isEnabled()) {
  191. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  192. }
  193. $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
  194. if ($encryptedToken === null) {
  195. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  196. }
  197. try {
  198. $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
  199. $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
  200. } catch (\Exception $e) {
  201. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  202. }
  203. $splittedToken = explode(':', $decryptedToken);
  204. if (count($splittedToken) !== 2) {
  205. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  206. }
  207. if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 24 * 7) ||
  208. $user->getLastLogin() > $splittedToken[0]) {
  209. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
  210. }
  211. if (!hash_equals($splittedToken[1], $token)) {
  212. throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
  213. }
  214. }
  215. /**
  216. * @param $message
  217. * @param array $additional
  218. * @return array
  219. */
  220. private function error($message, array $additional = []) {
  221. return array_merge(['status' => 'error', 'msg' => $message], $additional);
  222. }
  223. /**
  224. * @param array $data
  225. * @return array
  226. */
  227. private function success($data = []) {
  228. return array_merge($data, ['status' => 'success']);
  229. }
  230. /**
  231. * @PublicPage
  232. * @BruteForceProtection(action=passwordResetEmail)
  233. * @AnonRateThrottle(limit=10, period=300)
  234. *
  235. * @param string $user
  236. * @return JSONResponse
  237. */
  238. public function email($user) {
  239. if ($this->config->getSystemValue('lost_password_link', '') !== '') {
  240. return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
  241. }
  242. \OCP\Util::emitHook(
  243. '\OCA\Files_Sharing\API\Server2Server',
  244. 'preLoginNameUsedAsUserName',
  245. ['uid' => &$user]
  246. );
  247. // FIXME: use HTTP error codes
  248. try {
  249. $this->sendEmail($user);
  250. } catch (ResetPasswordException $e) {
  251. // Ignore the error since we do not want to leak this info
  252. $this->logger->warning('Could not send password reset email: ' . $e->getMessage());
  253. } catch (\Exception $e) {
  254. $this->logger->logException($e);
  255. }
  256. $response = new JSONResponse($this->success());
  257. $response->throttle();
  258. return $response;
  259. }
  260. /**
  261. * @PublicPage
  262. * @param string $token
  263. * @param string $userId
  264. * @param string $password
  265. * @param boolean $proceed
  266. * @return array
  267. */
  268. public function setPassword($token, $userId, $password, $proceed) {
  269. if ($this->config->getSystemValue('lost_password_link', '') !== '') {
  270. return $this->error($this->l10n->t('Password reset is disabled'));
  271. }
  272. if ($this->encryptionManager->isEnabled() && !$proceed) {
  273. $encryptionModules = $this->encryptionManager->getEncryptionModules();
  274. foreach ($encryptionModules as $module) {
  275. /** @var IEncryptionModule $instance */
  276. $instance = call_user_func($module['callback']);
  277. // this way we can find out whether per-user keys are used or a system wide encryption key
  278. if ($instance->needDetailedAccessList()) {
  279. return $this->error('', ['encryption' => true]);
  280. }
  281. }
  282. }
  283. try {
  284. $this->checkPasswordResetToken($token, $userId);
  285. $user = $this->userManager->get($userId);
  286. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', ['uid' => $userId, 'password' => $password]);
  287. if (!$user->setPassword($password)) {
  288. throw new \Exception();
  289. }
  290. \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', ['uid' => $userId, 'password' => $password]);
  291. $this->twoFactorManager->clearTwoFactorPending($userId);
  292. $this->config->deleteUserValue($userId, 'core', 'lostpassword');
  293. @\OC::$server->getUserSession()->unsetMagicInCookie();
  294. } catch (HintException $e) {
  295. return $this->error($e->getHint());
  296. } catch (\Exception $e) {
  297. return $this->error($e->getMessage());
  298. }
  299. return $this->success(['user' => $userId]);
  300. }
  301. /**
  302. * @param string $input
  303. * @throws ResetPasswordException
  304. * @throws \OCP\PreConditionNotMetException
  305. */
  306. protected function sendEmail($input) {
  307. $user = $this->findUserByIdOrMail($input);
  308. $email = $user->getEMailAddress();
  309. if (empty($email)) {
  310. throw new ResetPasswordException('Could not send reset e-mail since there is no email for username ' . $input);
  311. }
  312. // Generate the token. It is stored encrypted in the database with the
  313. // secret being the users' email address appended with the system secret.
  314. // This makes the token automatically invalidate once the user changes
  315. // their email address.
  316. $token = $this->secureRandom->generate(
  317. 21,
  318. ISecureRandom::CHAR_DIGITS.
  319. ISecureRandom::CHAR_LOWER.
  320. ISecureRandom::CHAR_UPPER
  321. );
  322. $tokenValue = $this->timeFactory->getTime() .':'. $token;
  323. $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
  324. $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
  325. $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $user->getUID(), 'token' => $token]);
  326. $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
  327. 'link' => $link,
  328. ]);
  329. $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
  330. $emailTemplate->addHeader();
  331. $emailTemplate->addHeading($this->l10n->t('Password reset'));
  332. $emailTemplate->addBodyText(
  333. htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
  334. $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
  335. );
  336. $emailTemplate->addBodyButton(
  337. htmlspecialchars($this->l10n->t('Reset your password')),
  338. $link,
  339. false
  340. );
  341. $emailTemplate->addFooter();
  342. try {
  343. $message = $this->mailer->createMessage();
  344. $message->setTo([$email => $user->getDisplayName()]);
  345. $message->setFrom([$this->from => $this->defaults->getName()]);
  346. $message->useTemplate($emailTemplate);
  347. $this->mailer->send($message);
  348. } catch (\Exception $e) {
  349. // Log the exception and continue
  350. $this->logger->logException($e);
  351. }
  352. }
  353. /**
  354. * @param string $input
  355. * @return IUser
  356. * @throws ResetPasswordException
  357. */
  358. protected function findUserByIdOrMail($input) {
  359. $user = $this->userManager->get($input);
  360. if ($user instanceof IUser) {
  361. if (!$user->isEnabled()) {
  362. throw new ResetPasswordException('User is disabled');
  363. }
  364. return $user;
  365. }
  366. $users = array_filter($this->userManager->getByEmail($input), function (IUser $user) {
  367. return $user->isEnabled();
  368. });
  369. if (count($users) === 1) {
  370. return reset($users);
  371. }
  372. throw new ResetPasswordException('Could not find user');
  373. }
  374. }