OauthApiController.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. * @author Kate Döen <kate.doeen@nextcloud.com>
  10. *
  11. * @license GNU AGPL version 3 or any later version
  12. *
  13. * This program is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License as
  15. * published by the Free Software Foundation, either version 3 of the
  16. * License, or (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. *
  26. */
  27. namespace OCA\OAuth2\Controller;
  28. use OC\Authentication\Exceptions\ExpiredTokenException;
  29. use OC\Authentication\Exceptions\InvalidTokenException;
  30. use OC\Authentication\Token\IProvider as TokenProvider;
  31. use OC\Security\Bruteforce\Throttler;
  32. use OCA\OAuth2\Db\AccessTokenMapper;
  33. use OCA\OAuth2\Db\ClientMapper;
  34. use OCA\OAuth2\Exceptions\AccessTokenNotFoundException;
  35. use OCA\OAuth2\Exceptions\ClientNotFoundException;
  36. use OCP\AppFramework\Controller;
  37. use OCP\AppFramework\Http;
  38. use OCP\AppFramework\Http\JSONResponse;
  39. use OCP\AppFramework\Utility\ITimeFactory;
  40. use OCP\IRequest;
  41. use OCP\Security\ICrypto;
  42. use OCP\Security\ISecureRandom;
  43. use Psr\Log\LoggerInterface;
  44. class OauthApiController extends Controller {
  45. public function __construct(
  46. string $appName,
  47. IRequest $request,
  48. private ICrypto $crypto,
  49. private AccessTokenMapper $accessTokenMapper,
  50. private ClientMapper $clientMapper,
  51. private TokenProvider $tokenProvider,
  52. private ISecureRandom $secureRandom,
  53. private ITimeFactory $time,
  54. private LoggerInterface $logger,
  55. private Throttler $throttler
  56. ) {
  57. parent::__construct($appName, $request);
  58. }
  59. /**
  60. * @PublicPage
  61. * @NoCSRFRequired
  62. * @BruteForceProtection(action=oauth2GetToken)
  63. *
  64. * Get a token
  65. *
  66. * @param string $grant_type Token type that should be granted
  67. * @param string $code Code of the flow
  68. * @param string $refresh_token Refresh token
  69. * @param string $client_id Client ID
  70. * @param string $client_secret Client secret
  71. * @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{}>
  72. *
  73. * 200: Token returned
  74. * 400: Getting token is not possible
  75. */
  76. public function getToken($grant_type, $code, $refresh_token, $client_id, $client_secret): JSONResponse {
  77. // We only handle two types
  78. if ($grant_type !== 'authorization_code' && $grant_type !== 'refresh_token') {
  79. $response = new JSONResponse([
  80. 'error' => 'invalid_grant',
  81. ], Http::STATUS_BAD_REQUEST);
  82. $response->throttle(['invalid_grant' => $grant_type]);
  83. return $response;
  84. }
  85. // We handle the initial and refresh tokens the same way
  86. if ($grant_type === 'refresh_token') {
  87. $code = $refresh_token;
  88. }
  89. try {
  90. $accessToken = $this->accessTokenMapper->getByCode($code);
  91. } catch (AccessTokenNotFoundException $e) {
  92. $response = new JSONResponse([
  93. 'error' => 'invalid_request',
  94. ], Http::STATUS_BAD_REQUEST);
  95. $response->throttle(['invalid_request' => 'token not found', 'code' => $code]);
  96. return $response;
  97. }
  98. try {
  99. $client = $this->clientMapper->getByUid($accessToken->getClientId());
  100. } catch (ClientNotFoundException $e) {
  101. $response = new JSONResponse([
  102. 'error' => 'invalid_request',
  103. ], Http::STATUS_BAD_REQUEST);
  104. $response->throttle(['invalid_request' => 'client not found', 'client_id' => $accessToken->getClientId()]);
  105. return $response;
  106. }
  107. if (isset($this->request->server['PHP_AUTH_USER'])) {
  108. $client_id = $this->request->server['PHP_AUTH_USER'];
  109. $client_secret = $this->request->server['PHP_AUTH_PW'];
  110. }
  111. try {
  112. $storedClientSecret = $this->crypto->decrypt($client->getSecret());
  113. } catch (\Exception $e) {
  114. $this->logger->error('OAuth client secret decryption error', ['exception' => $e]);
  115. // we don't throttle here because it might not be a bruteforce attack
  116. return new JSONResponse([
  117. 'error' => 'invalid_client',
  118. ], Http::STATUS_BAD_REQUEST);
  119. }
  120. // The client id and secret must match. Else we don't provide an access token!
  121. if ($client->getClientIdentifier() !== $client_id || $storedClientSecret !== $client_secret) {
  122. $response = new JSONResponse([
  123. 'error' => 'invalid_client',
  124. ], Http::STATUS_BAD_REQUEST);
  125. $response->throttle(['invalid_client' => 'client ID or secret does not match']);
  126. return $response;
  127. }
  128. $decryptedToken = $this->crypto->decrypt($accessToken->getEncryptedToken(), $code);
  129. // Obtain the appToken associated
  130. try {
  131. $appToken = $this->tokenProvider->getTokenById($accessToken->getTokenId());
  132. } catch (ExpiredTokenException $e) {
  133. $appToken = $e->getToken();
  134. } catch (InvalidTokenException $e) {
  135. //We can't do anything...
  136. $this->accessTokenMapper->delete($accessToken);
  137. $response = new JSONResponse([
  138. 'error' => 'invalid_request',
  139. ], Http::STATUS_BAD_REQUEST);
  140. $response->throttle(['invalid_request' => 'token is invalid']);
  141. return $response;
  142. }
  143. // Rotate the apptoken (so the old one becomes invalid basically)
  144. $newToken = $this->secureRandom->generate(72, ISecureRandom::CHAR_ALPHANUMERIC);
  145. $appToken = $this->tokenProvider->rotate(
  146. $appToken,
  147. $decryptedToken,
  148. $newToken
  149. );
  150. // Expiration is in 1 hour again
  151. $appToken->setExpires($this->time->getTime() + 3600);
  152. $this->tokenProvider->updateToken($appToken);
  153. // Generate a new refresh token and encrypt the new apptoken in the DB
  154. $newCode = $this->secureRandom->generate(128, ISecureRandom::CHAR_ALPHANUMERIC);
  155. $accessToken->setHashedCode(hash('sha512', $newCode));
  156. $accessToken->setEncryptedToken($this->crypto->encrypt($newToken, $newCode));
  157. $this->accessTokenMapper->update($accessToken);
  158. $this->throttler->resetDelay($this->request->getRemoteAddress(), 'login', ['user' => $appToken->getUID()]);
  159. return new JSONResponse(
  160. [
  161. 'access_token' => $newToken,
  162. 'token_type' => 'Bearer',
  163. 'expires_in' => 3600,
  164. 'refresh_token' => $newCode,
  165. 'user_id' => $appToken->getUID(),
  166. ]
  167. );
  168. }
  169. }