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.

189 lines
5.9 KiB

  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Controller;
  8. use OC\Authentication\Events\AppPasswordCreatedEvent;
  9. use OC\Authentication\Token\IProvider;
  10. use OC\Authentication\Token\IToken;
  11. use OC\User\Session;
  12. use OCP\AppFramework\Http;
  13. use OCP\AppFramework\Http\Attribute\ApiRoute;
  14. use OCP\AppFramework\Http\Attribute\BruteForceProtection;
  15. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  16. use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired;
  17. use OCP\AppFramework\Http\Attribute\UseSession;
  18. use OCP\AppFramework\Http\DataResponse;
  19. use OCP\AppFramework\OCS\OCSForbiddenException;
  20. use OCP\AppFramework\OCSController;
  21. use OCP\Authentication\Exceptions\CredentialsUnavailableException;
  22. use OCP\Authentication\Exceptions\InvalidTokenException;
  23. use OCP\Authentication\Exceptions\PasswordUnavailableException;
  24. use OCP\Authentication\LoginCredentials\IStore;
  25. use OCP\EventDispatcher\IEventDispatcher;
  26. use OCP\IRequest;
  27. use OCP\ISession;
  28. use OCP\IUserManager;
  29. use OCP\Security\Bruteforce\IThrottler;
  30. use OCP\Security\ISecureRandom;
  31. class AppPasswordController extends OCSController {
  32. public function __construct(
  33. string $appName,
  34. IRequest $request,
  35. private ISession $session,
  36. private ISecureRandom $random,
  37. private IProvider $tokenProvider,
  38. private IStore $credentialStore,
  39. private IEventDispatcher $eventDispatcher,
  40. private Session $userSession,
  41. private IUserManager $userManager,
  42. private IThrottler $throttler,
  43. ) {
  44. parent::__construct($appName, $request);
  45. }
  46. /**
  47. * Create app password
  48. *
  49. * @return DataResponse<Http::STATUS_OK, array{apppassword: string}, array{}>
  50. * @throws OCSForbiddenException Creating app password is not allowed
  51. *
  52. * 200: App password returned
  53. */
  54. #[NoAdminRequired]
  55. #[PasswordConfirmationRequired]
  56. #[ApiRoute(verb: 'GET', url: '/getapppassword', root: '/core')]
  57. public function getAppPassword(): DataResponse {
  58. // We do not allow the creation of new tokens if this is an app password
  59. if ($this->session->exists('app_password')) {
  60. throw new OCSForbiddenException('You cannot request an new apppassword with an apppassword');
  61. }
  62. try {
  63. $credentials = $this->credentialStore->getLoginCredentials();
  64. } catch (CredentialsUnavailableException $e) {
  65. throw new OCSForbiddenException();
  66. }
  67. try {
  68. $password = $credentials->getPassword();
  69. } catch (PasswordUnavailableException $e) {
  70. $password = null;
  71. }
  72. $userAgent = $this->request->getHeader('user-agent');
  73. $token = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
  74. $generatedToken = $this->tokenProvider->generateToken(
  75. $token,
  76. $credentials->getUID(),
  77. $credentials->getLoginName(),
  78. $password,
  79. $userAgent,
  80. IToken::PERMANENT_TOKEN,
  81. IToken::DO_NOT_REMEMBER
  82. );
  83. $this->eventDispatcher->dispatchTyped(
  84. new AppPasswordCreatedEvent($generatedToken)
  85. );
  86. return new DataResponse([
  87. 'apppassword' => $token
  88. ]);
  89. }
  90. /**
  91. * Delete app password
  92. *
  93. * @return DataResponse<Http::STATUS_OK, list<empty>, array{}>
  94. * @throws OCSForbiddenException Deleting app password is not allowed
  95. *
  96. * 200: App password deleted successfully
  97. */
  98. #[NoAdminRequired]
  99. #[ApiRoute(verb: 'DELETE', url: '/apppassword', root: '/core')]
  100. public function deleteAppPassword(): DataResponse {
  101. if (!$this->session->exists('app_password')) {
  102. throw new OCSForbiddenException('no app password in use');
  103. }
  104. $appPassword = $this->session->get('app_password');
  105. try {
  106. $token = $this->tokenProvider->getToken($appPassword);
  107. } catch (InvalidTokenException $e) {
  108. throw new OCSForbiddenException('could not remove apptoken');
  109. }
  110. $this->tokenProvider->invalidateTokenById($token->getUID(), $token->getId());
  111. return new DataResponse();
  112. }
  113. /**
  114. * Rotate app password
  115. *
  116. * @return DataResponse<Http::STATUS_OK, array{apppassword: string}, array{}>
  117. * @throws OCSForbiddenException Rotating app password is not allowed
  118. *
  119. * 200: App password returned
  120. */
  121. #[NoAdminRequired]
  122. #[ApiRoute(verb: 'POST', url: '/apppassword/rotate', root: '/core')]
  123. public function rotateAppPassword(): DataResponse {
  124. if (!$this->session->exists('app_password')) {
  125. throw new OCSForbiddenException('no app password in use');
  126. }
  127. $appPassword = $this->session->get('app_password');
  128. try {
  129. $token = $this->tokenProvider->getToken($appPassword);
  130. } catch (InvalidTokenException $e) {
  131. throw new OCSForbiddenException('could not rotate apptoken');
  132. }
  133. $newToken = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
  134. $this->tokenProvider->rotate($token, $appPassword, $newToken);
  135. return new DataResponse([
  136. 'apppassword' => $newToken,
  137. ]);
  138. }
  139. /**
  140. * Confirm the user password
  141. *
  142. * @param string $password The password of the user
  143. *
  144. * @return DataResponse<Http::STATUS_OK, array{lastLogin: int}, array{}>|DataResponse<Http::STATUS_FORBIDDEN, list<empty>, array{}>
  145. *
  146. * 200: Password confirmation succeeded
  147. * 403: Password confirmation failed
  148. */
  149. #[NoAdminRequired]
  150. #[BruteForceProtection(action: 'sudo')]
  151. #[UseSession]
  152. #[ApiRoute(verb: 'PUT', url: '/apppassword/confirm', root: '/core')]
  153. public function confirmUserPassword(string $password): DataResponse {
  154. $loginName = $this->userSession->getLoginName();
  155. $loginResult = $this->userManager->checkPassword($loginName, $password);
  156. if ($loginResult === false) {
  157. $response = new DataResponse([], Http::STATUS_FORBIDDEN);
  158. $response->throttle(['loginName' => $loginName]);
  159. return $response;
  160. }
  161. $confirmTimestamp = time();
  162. $this->session->set('last-password-confirm', $confirmTimestamp);
  163. $this->throttler->resetDelay($this->request->getRemoteAddress(), 'sudo', ['loginName' => $loginName]);
  164. return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
  165. }
  166. }