OauthApiController.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\OAuth2\Controller;
  8. use OC\Authentication\Token\IProvider as TokenProvider;
  9. use OCA\OAuth2\Db\AccessTokenMapper;
  10. use OCA\OAuth2\Db\ClientMapper;
  11. use OCA\OAuth2\Exceptions\AccessTokenNotFoundException;
  12. use OCA\OAuth2\Exceptions\ClientNotFoundException;
  13. use OCP\AppFramework\Controller;
  14. use OCP\AppFramework\Http;
  15. use OCP\AppFramework\Http\JSONResponse;
  16. use OCP\AppFramework\Utility\ITimeFactory;
  17. use OCP\Authentication\Exceptions\ExpiredTokenException;
  18. use OCP\Authentication\Exceptions\InvalidTokenException;
  19. use OCP\DB\Exception;
  20. use OCP\IRequest;
  21. use OCP\Security\Bruteforce\IThrottler;
  22. use OCP\Security\ICrypto;
  23. use OCP\Security\ISecureRandom;
  24. use Psr\Log\LoggerInterface;
  25. class OauthApiController extends Controller {
  26. // the authorization code expires after 10 minutes
  27. public const AUTHORIZATION_CODE_EXPIRES_AFTER = 10 * 60;
  28. public function __construct(
  29. string $appName,
  30. IRequest $request,
  31. private ICrypto $crypto,
  32. private AccessTokenMapper $accessTokenMapper,
  33. private ClientMapper $clientMapper,
  34. private TokenProvider $tokenProvider,
  35. private ISecureRandom $secureRandom,
  36. private ITimeFactory $time,
  37. private LoggerInterface $logger,
  38. private IThrottler $throttler,
  39. private ITimeFactory $timeFactory,
  40. ) {
  41. parent::__construct($appName, $request);
  42. }
  43. /**
  44. * @PublicPage
  45. * @NoCSRFRequired
  46. * @BruteForceProtection(action=oauth2GetToken)
  47. *
  48. * Get a token
  49. *
  50. * @param string $grant_type Token type that should be granted
  51. * @param ?string $code Code of the flow
  52. * @param ?string $refresh_token Refresh token
  53. * @param ?string $client_id Client ID
  54. * @param ?string $client_secret Client secret
  55. * @throws Exception
  56. * @return JSONResponse<Http::STATUS_OK, array{access_token: string, token_type: string, expires_in: int, refresh_token: string, user_id: string}, array{}>|JSONResponse<Http::STATUS_BAD_REQUEST, array{error: string}, array{}>
  57. *
  58. * 200: Token returned
  59. * 400: Getting token is not possible
  60. */
  61. public function getToken(
  62. string $grant_type, ?string $code, ?string $refresh_token,
  63. ?string $client_id, ?string $client_secret
  64. ): JSONResponse {
  65. // We only handle two types
  66. if ($grant_type !== 'authorization_code' && $grant_type !== 'refresh_token') {
  67. $response = new JSONResponse([
  68. 'error' => 'invalid_grant',
  69. ], Http::STATUS_BAD_REQUEST);
  70. $response->throttle(['invalid_grant' => $grant_type]);
  71. return $response;
  72. }
  73. // We handle the initial and refresh tokens the same way
  74. if ($grant_type === 'refresh_token') {
  75. $code = $refresh_token;
  76. }
  77. try {
  78. $accessToken = $this->accessTokenMapper->getByCode($code);
  79. } catch (AccessTokenNotFoundException $e) {
  80. $response = new JSONResponse([
  81. 'error' => 'invalid_request',
  82. ], Http::STATUS_BAD_REQUEST);
  83. $response->throttle(['invalid_request' => 'token not found', 'code' => $code]);
  84. return $response;
  85. }
  86. if ($grant_type === 'authorization_code') {
  87. // check this token is in authorization code state
  88. $deliveredTokenCount = $accessToken->getTokenCount();
  89. if ($deliveredTokenCount > 0) {
  90. $response = new JSONResponse([
  91. 'error' => 'invalid_request',
  92. ], Http::STATUS_BAD_REQUEST);
  93. $response->throttle(['invalid_request' => 'authorization_code_received_for_active_token']);
  94. return $response;
  95. }
  96. // check authorization code expiration
  97. $now = $this->timeFactory->now()->getTimestamp();
  98. $codeCreatedAt = $accessToken->getCodeCreatedAt();
  99. if ($codeCreatedAt < $now - self::AUTHORIZATION_CODE_EXPIRES_AFTER) {
  100. // we know this token is not useful anymore
  101. $this->accessTokenMapper->delete($accessToken);
  102. $response = new JSONResponse([
  103. 'error' => 'invalid_request',
  104. ], Http::STATUS_BAD_REQUEST);
  105. $expiredSince = $now - self::AUTHORIZATION_CODE_EXPIRES_AFTER - $codeCreatedAt;
  106. $response->throttle(['invalid_request' => 'authorization_code_expired', 'expired_since' => $expiredSince]);
  107. return $response;
  108. }
  109. }
  110. try {
  111. $client = $this->clientMapper->getByUid($accessToken->getClientId());
  112. } catch (ClientNotFoundException $e) {
  113. $response = new JSONResponse([
  114. 'error' => 'invalid_request',
  115. ], Http::STATUS_BAD_REQUEST);
  116. $response->throttle(['invalid_request' => 'client not found', 'client_id' => $accessToken->getClientId()]);
  117. return $response;
  118. }
  119. if (isset($this->request->server['PHP_AUTH_USER'])) {
  120. $client_id = $this->request->server['PHP_AUTH_USER'];
  121. $client_secret = $this->request->server['PHP_AUTH_PW'];
  122. }
  123. try {
  124. $storedClientSecret = $this->crypto->decrypt($client->getSecret());
  125. } catch (\Exception $e) {
  126. $this->logger->error('OAuth client secret decryption error', ['exception' => $e]);
  127. // we don't throttle here because it might not be a bruteforce attack
  128. return new JSONResponse([
  129. 'error' => 'invalid_client',
  130. ], Http::STATUS_BAD_REQUEST);
  131. }
  132. // The client id and secret must match. Else we don't provide an access token!
  133. if ($client->getClientIdentifier() !== $client_id || $storedClientSecret !== $client_secret) {
  134. $response = new JSONResponse([
  135. 'error' => 'invalid_client',
  136. ], Http::STATUS_BAD_REQUEST);
  137. $response->throttle(['invalid_client' => 'client ID or secret does not match']);
  138. return $response;
  139. }
  140. $decryptedToken = $this->crypto->decrypt($accessToken->getEncryptedToken(), $code);
  141. // Obtain the appToken associated
  142. try {
  143. $appToken = $this->tokenProvider->getTokenById($accessToken->getTokenId());
  144. } catch (ExpiredTokenException $e) {
  145. $appToken = $e->getToken();
  146. } catch (InvalidTokenException $e) {
  147. //We can't do anything...
  148. $this->accessTokenMapper->delete($accessToken);
  149. $response = new JSONResponse([
  150. 'error' => 'invalid_request',
  151. ], Http::STATUS_BAD_REQUEST);
  152. $response->throttle(['invalid_request' => 'token is invalid']);
  153. return $response;
  154. }
  155. // Rotate the apptoken (so the old one becomes invalid basically)
  156. $newToken = $this->secureRandom->generate(72, ISecureRandom::CHAR_ALPHANUMERIC);
  157. $appToken = $this->tokenProvider->rotate(
  158. $appToken,
  159. $decryptedToken,
  160. $newToken
  161. );
  162. // Expiration is in 1 hour again
  163. $appToken->setExpires($this->time->getTime() + 3600);
  164. $this->tokenProvider->updateToken($appToken);
  165. // Generate a new refresh token and encrypt the new apptoken in the DB
  166. $newCode = $this->secureRandom->generate(128, ISecureRandom::CHAR_ALPHANUMERIC);
  167. $accessToken->setHashedCode(hash('sha512', $newCode));
  168. $accessToken->setEncryptedToken($this->crypto->encrypt($newToken, $newCode));
  169. // increase the number of delivered oauth token
  170. // this helps with cleaning up DB access token when authorization code has expired
  171. // and it never delivered any oauth token
  172. $tokenCount = $accessToken->getTokenCount();
  173. $accessToken->setTokenCount($tokenCount + 1);
  174. $this->accessTokenMapper->update($accessToken);
  175. $this->throttler->resetDelay($this->request->getRemoteAddress(), 'login', ['user' => $appToken->getUID()]);
  176. return new JSONResponse(
  177. [
  178. 'access_token' => $newToken,
  179. 'token_type' => 'Bearer',
  180. 'expires_in' => 3600,
  181. 'refresh_token' => $newCode,
  182. 'user_id' => $appToken->getUID(),
  183. ]
  184. );
  185. }
  186. }