1
0

OauthApiController.php 7.4 KB

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