OauthApiController.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OCA\OAuth2\Controller;
  27. use OC\Authentication\Exceptions\ExpiredTokenException;
  28. use OC\Authentication\Exceptions\InvalidTokenException;
  29. use OC\Authentication\Token\IProvider as TokenProvider;
  30. use OC\Security\Bruteforce\Throttler;
  31. use OCA\OAuth2\Db\AccessTokenMapper;
  32. use OCA\OAuth2\Db\ClientMapper;
  33. use OCA\OAuth2\Exceptions\AccessTokenNotFoundException;
  34. use OCA\OAuth2\Exceptions\ClientNotFoundException;
  35. use OCP\AppFramework\Controller;
  36. use OCP\AppFramework\Http;
  37. use OCP\AppFramework\Http\JSONResponse;
  38. use OCP\AppFramework\Utility\ITimeFactory;
  39. use OCP\DB\Exception;
  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. // the authorization code expires after 10 minutes
  46. public const AUTHORIZATION_CODE_EXPIRES_AFTER = 10 * 60;
  47. public function __construct(
  48. string $appName,
  49. IRequest $request,
  50. private ICrypto $crypto,
  51. private AccessTokenMapper $accessTokenMapper,
  52. private ClientMapper $clientMapper,
  53. private TokenProvider $tokenProvider,
  54. private ISecureRandom $secureRandom,
  55. private ITimeFactory $timeFactory,
  56. private LoggerInterface $logger,
  57. private Throttler $throttler,
  58. ) {
  59. parent::__construct($appName, $request);
  60. }
  61. /**
  62. * @PublicPage
  63. * @NoCSRFRequired
  64. * @BruteForceProtection(action=oauth2GetToken)
  65. *
  66. * @param string $grant_type
  67. * @param string|null $code
  68. * @param string|null $refresh_token
  69. * @param string|null $client_id
  70. * @param string|null $client_secret
  71. * @return JSONResponse
  72. * @throws Exception
  73. */
  74. public function getToken(
  75. string $grant_type, ?string $code, ?string $refresh_token,
  76. ?string $client_id, ?string $client_secret
  77. ): JSONResponse {
  78. // We only handle two types
  79. if ($grant_type !== 'authorization_code' && $grant_type !== 'refresh_token') {
  80. $response = new JSONResponse([
  81. 'error' => 'invalid_grant',
  82. ], Http::STATUS_BAD_REQUEST);
  83. $response->throttle(['invalid_grant' => $grant_type]);
  84. return $response;
  85. }
  86. // We handle the initial and refresh tokens the same way
  87. if ($grant_type === 'refresh_token') {
  88. $code = $refresh_token;
  89. }
  90. try {
  91. $accessToken = $this->accessTokenMapper->getByCode($code);
  92. } catch (AccessTokenNotFoundException $e) {
  93. $response = new JSONResponse([
  94. 'error' => 'invalid_request',
  95. ], Http::STATUS_BAD_REQUEST);
  96. $response->throttle(['invalid_request' => 'token not found', 'code' => $code]);
  97. return $response;
  98. }
  99. if ($grant_type === 'authorization_code') {
  100. // check this token is in authorization code state
  101. $deliveredTokenCount = $accessToken->getTokenCount();
  102. if ($deliveredTokenCount > 0) {
  103. $response = new JSONResponse([
  104. 'error' => 'invalid_request',
  105. ], Http::STATUS_BAD_REQUEST);
  106. $response->throttle(['invalid_request' => 'authorization_code_received_for_active_token']);
  107. return $response;
  108. }
  109. // check authorization code expiration
  110. $now = $this->timeFactory->now()->getTimestamp();
  111. $codeCreatedAt = $accessToken->getCodeCreatedAt();
  112. if ($codeCreatedAt < $now - self::AUTHORIZATION_CODE_EXPIRES_AFTER) {
  113. // we know this token is not useful anymore
  114. $this->accessTokenMapper->delete($accessToken);
  115. $response = new JSONResponse([
  116. 'error' => 'invalid_request',
  117. ], Http::STATUS_BAD_REQUEST);
  118. $expiredSince = $now - self::AUTHORIZATION_CODE_EXPIRES_AFTER - $codeCreatedAt;
  119. $response->throttle(['invalid_request' => 'authorization_code_expired', 'expired_since' => $expiredSince]);
  120. return $response;
  121. }
  122. }
  123. try {
  124. $client = $this->clientMapper->getByUid($accessToken->getClientId());
  125. } catch (ClientNotFoundException $e) {
  126. $response = new JSONResponse([
  127. 'error' => 'invalid_request',
  128. ], Http::STATUS_BAD_REQUEST);
  129. $response->throttle(['invalid_request' => 'client not found', 'client_id' => $accessToken->getClientId()]);
  130. return $response;
  131. }
  132. if (isset($this->request->server['PHP_AUTH_USER'])) {
  133. $client_id = $this->request->server['PHP_AUTH_USER'];
  134. $client_secret = $this->request->server['PHP_AUTH_PW'];
  135. }
  136. try {
  137. $storedClientSecret = $this->crypto->decrypt($client->getSecret());
  138. } catch (\Exception $e) {
  139. $this->logger->error('OAuth client secret decryption error', ['exception' => $e]);
  140. // we don't throttle here because it might not be a bruteforce attack
  141. return new JSONResponse([
  142. 'error' => 'invalid_client',
  143. ], Http::STATUS_BAD_REQUEST);
  144. }
  145. // The client id and secret must match. Else we don't provide an access token!
  146. if ($client->getClientIdentifier() !== $client_id || $storedClientSecret !== $client_secret) {
  147. $response = new JSONResponse([
  148. 'error' => 'invalid_client',
  149. ], Http::STATUS_BAD_REQUEST);
  150. $response->throttle(['invalid_client' => 'client ID or secret does not match']);
  151. return $response;
  152. }
  153. $decryptedToken = $this->crypto->decrypt($accessToken->getEncryptedToken(), $code);
  154. // Obtain the appToken associated
  155. try {
  156. $appToken = $this->tokenProvider->getTokenById($accessToken->getTokenId());
  157. } catch (ExpiredTokenException $e) {
  158. $appToken = $e->getToken();
  159. } catch (InvalidTokenException $e) {
  160. //We can't do anything...
  161. $this->accessTokenMapper->delete($accessToken);
  162. $response = new JSONResponse([
  163. 'error' => 'invalid_request',
  164. ], Http::STATUS_BAD_REQUEST);
  165. $response->throttle(['invalid_request' => 'token is invalid']);
  166. return $response;
  167. }
  168. // Rotate the apptoken (so the old one becomes invalid basically)
  169. $newToken = $this->secureRandom->generate(72, ISecureRandom::CHAR_ALPHANUMERIC);
  170. $appToken = $this->tokenProvider->rotate(
  171. $appToken,
  172. $decryptedToken,
  173. $newToken
  174. );
  175. // Expiration is in 1 hour again
  176. $appToken->setExpires($this->timeFactory->getTime() + 3600);
  177. $this->tokenProvider->updateToken($appToken);
  178. // Generate a new refresh token and encrypt the new apptoken in the DB
  179. $newCode = $this->secureRandom->generate(128, ISecureRandom::CHAR_ALPHANUMERIC);
  180. $accessToken->setHashedCode(hash('sha512', $newCode));
  181. $accessToken->setEncryptedToken($this->crypto->encrypt($newToken, $newCode));
  182. // increase the number of delivered oauth token
  183. // this helps with cleaning up DB access token when authorization code has expired
  184. // and it never delivered any oauth token
  185. $tokenCount = $accessToken->getTokenCount();
  186. $accessToken->setTokenCount($tokenCount + 1);
  187. $this->accessTokenMapper->update($accessToken);
  188. $this->throttler->resetDelay($this->request->getRemoteAddress(), 'login', ['user' => $appToken->getUID()]);
  189. return new JSONResponse(
  190. [
  191. 'access_token' => $newToken,
  192. 'token_type' => 'Bearer',
  193. 'expires_in' => 3600,
  194. 'refresh_token' => $newCode,
  195. 'user_id' => $appToken->getUID(),
  196. ]
  197. );
  198. }
  199. }