OauthApiController.php 8.0 KB

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