ClientFlowLoginController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Core\Controller;
  7. use OC\Authentication\Events\AppPasswordCreatedEvent;
  8. use OC\Authentication\Exceptions\PasswordlessTokenException;
  9. use OC\Authentication\Token\IProvider;
  10. use OC\Authentication\Token\IToken;
  11. use OCA\OAuth2\Db\AccessToken;
  12. use OCA\OAuth2\Db\AccessTokenMapper;
  13. use OCA\OAuth2\Db\ClientMapper;
  14. use OCP\AppFramework\Controller;
  15. use OCP\AppFramework\Http;
  16. use OCP\AppFramework\Http\Attribute\FrontpageRoute;
  17. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  18. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  19. use OCP\AppFramework\Http\Attribute\OpenAPI;
  20. use OCP\AppFramework\Http\Attribute\PublicPage;
  21. use OCP\AppFramework\Http\Attribute\UseSession;
  22. use OCP\AppFramework\Http\Response;
  23. use OCP\AppFramework\Http\StandaloneTemplateResponse;
  24. use OCP\AppFramework\Utility\ITimeFactory;
  25. use OCP\Authentication\Exceptions\InvalidTokenException;
  26. use OCP\Defaults;
  27. use OCP\EventDispatcher\IEventDispatcher;
  28. use OCP\IL10N;
  29. use OCP\IRequest;
  30. use OCP\ISession;
  31. use OCP\IURLGenerator;
  32. use OCP\IUser;
  33. use OCP\IUserSession;
  34. use OCP\Security\ICrypto;
  35. use OCP\Security\ISecureRandom;
  36. use OCP\Session\Exceptions\SessionNotAvailableException;
  37. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  38. class ClientFlowLoginController extends Controller {
  39. public const STATE_NAME = 'client.flow.state.token';
  40. public function __construct(
  41. string $appName,
  42. IRequest $request,
  43. private IUserSession $userSession,
  44. private IL10N $l10n,
  45. private Defaults $defaults,
  46. private ISession $session,
  47. private IProvider $tokenProvider,
  48. private ISecureRandom $random,
  49. private IURLGenerator $urlGenerator,
  50. private ClientMapper $clientMapper,
  51. private AccessTokenMapper $accessTokenMapper,
  52. private ICrypto $crypto,
  53. private IEventDispatcher $eventDispatcher,
  54. private ITimeFactory $timeFactory,
  55. ) {
  56. parent::__construct($appName, $request);
  57. }
  58. private function getClientName(): string {
  59. $userAgent = $this->request->getHeader('USER_AGENT');
  60. return $userAgent !== '' ? $userAgent : 'unknown';
  61. }
  62. private function isValidToken(string $stateToken): bool {
  63. $currentToken = $this->session->get(self::STATE_NAME);
  64. if (!is_string($currentToken)) {
  65. return false;
  66. }
  67. return hash_equals($currentToken, $stateToken);
  68. }
  69. private function stateTokenForbiddenResponse(): StandaloneTemplateResponse {
  70. $response = new StandaloneTemplateResponse(
  71. $this->appName,
  72. '403',
  73. [
  74. 'message' => $this->l10n->t('State token does not match'),
  75. ],
  76. 'guest'
  77. );
  78. $response->setStatus(Http::STATUS_FORBIDDEN);
  79. return $response;
  80. }
  81. #[PublicPage]
  82. #[NoCSRFRequired]
  83. #[UseSession]
  84. #[FrontpageRoute(verb: 'GET', url: '/login/flow')]
  85. public function showAuthPickerPage(string $clientIdentifier = '', string $user = '', int $direct = 0): StandaloneTemplateResponse {
  86. $clientName = $this->getClientName();
  87. $client = null;
  88. if ($clientIdentifier !== '') {
  89. $client = $this->clientMapper->getByIdentifier($clientIdentifier);
  90. $clientName = $client->getName();
  91. }
  92. // No valid clientIdentifier given and no valid API Request (APIRequest header not set)
  93. $clientRequest = $this->request->getHeader('OCS-APIREQUEST');
  94. if ($clientRequest !== 'true' && $client === null) {
  95. return new StandaloneTemplateResponse(
  96. $this->appName,
  97. 'error',
  98. [
  99. 'errors' =>
  100. [
  101. [
  102. 'error' => 'Access Forbidden',
  103. 'hint' => 'Invalid request',
  104. ],
  105. ],
  106. ],
  107. 'guest'
  108. );
  109. }
  110. $stateToken = $this->random->generate(
  111. 64,
  112. ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS
  113. );
  114. $this->session->set(self::STATE_NAME, $stateToken);
  115. $csp = new Http\ContentSecurityPolicy();
  116. if ($client) {
  117. $csp->addAllowedFormActionDomain($client->getRedirectUri());
  118. } else {
  119. $csp->addAllowedFormActionDomain('nc://*');
  120. }
  121. $response = new StandaloneTemplateResponse(
  122. $this->appName,
  123. 'loginflow/authpicker',
  124. [
  125. 'client' => $clientName,
  126. 'clientIdentifier' => $clientIdentifier,
  127. 'instanceName' => $this->defaults->getName(),
  128. 'urlGenerator' => $this->urlGenerator,
  129. 'stateToken' => $stateToken,
  130. 'serverHost' => $this->getServerPath(),
  131. 'oauthState' => $this->session->get('oauth.state'),
  132. 'user' => $user,
  133. 'direct' => $direct,
  134. ],
  135. 'guest'
  136. );
  137. $response->setContentSecurityPolicy($csp);
  138. return $response;
  139. }
  140. /**
  141. * @NoSameSiteCookieRequired
  142. */
  143. #[NoAdminRequired]
  144. #[NoCSRFRequired]
  145. #[UseSession]
  146. #[FrontpageRoute(verb: 'GET', url: '/login/flow/grant')]
  147. public function grantPage(string $stateToken = '',
  148. string $clientIdentifier = '',
  149. int $direct = 0): StandaloneTemplateResponse {
  150. if (!$this->isValidToken($stateToken)) {
  151. return $this->stateTokenForbiddenResponse();
  152. }
  153. $clientName = $this->getClientName();
  154. $client = null;
  155. if ($clientIdentifier !== '') {
  156. $client = $this->clientMapper->getByIdentifier($clientIdentifier);
  157. $clientName = $client->getName();
  158. }
  159. $csp = new Http\ContentSecurityPolicy();
  160. if ($client) {
  161. $csp->addAllowedFormActionDomain($client->getRedirectUri());
  162. } else {
  163. $csp->addAllowedFormActionDomain('nc://*');
  164. }
  165. /** @var IUser $user */
  166. $user = $this->userSession->getUser();
  167. $response = new StandaloneTemplateResponse(
  168. $this->appName,
  169. 'loginflow/grant',
  170. [
  171. 'userId' => $user->getUID(),
  172. 'userDisplayName' => $user->getDisplayName(),
  173. 'client' => $clientName,
  174. 'clientIdentifier' => $clientIdentifier,
  175. 'instanceName' => $this->defaults->getName(),
  176. 'urlGenerator' => $this->urlGenerator,
  177. 'stateToken' => $stateToken,
  178. 'serverHost' => $this->getServerPath(),
  179. 'oauthState' => $this->session->get('oauth.state'),
  180. 'direct' => $direct,
  181. ],
  182. 'guest'
  183. );
  184. $response->setContentSecurityPolicy($csp);
  185. return $response;
  186. }
  187. /**
  188. * @return Http\RedirectResponse|Response
  189. */
  190. #[NoAdminRequired]
  191. #[UseSession]
  192. #[FrontpageRoute(verb: 'POST', url: '/login/flow')]
  193. public function generateAppPassword(string $stateToken,
  194. string $clientIdentifier = '') {
  195. if (!$this->isValidToken($stateToken)) {
  196. $this->session->remove(self::STATE_NAME);
  197. return $this->stateTokenForbiddenResponse();
  198. }
  199. $this->session->remove(self::STATE_NAME);
  200. try {
  201. $sessionId = $this->session->getId();
  202. } catch (SessionNotAvailableException $ex) {
  203. $response = new Response();
  204. $response->setStatus(Http::STATUS_FORBIDDEN);
  205. return $response;
  206. }
  207. try {
  208. $sessionToken = $this->tokenProvider->getToken($sessionId);
  209. $loginName = $sessionToken->getLoginName();
  210. try {
  211. $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
  212. } catch (PasswordlessTokenException $ex) {
  213. $password = null;
  214. }
  215. } catch (InvalidTokenException $ex) {
  216. $response = new Response();
  217. $response->setStatus(Http::STATUS_FORBIDDEN);
  218. return $response;
  219. }
  220. $clientName = $this->getClientName();
  221. $client = false;
  222. if ($clientIdentifier !== '') {
  223. $client = $this->clientMapper->getByIdentifier($clientIdentifier);
  224. $clientName = $client->getName();
  225. }
  226. $token = $this->random->generate(72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
  227. $uid = $this->userSession->getUser()->getUID();
  228. $generatedToken = $this->tokenProvider->generateToken(
  229. $token,
  230. $uid,
  231. $loginName,
  232. $password,
  233. $clientName,
  234. IToken::PERMANENT_TOKEN,
  235. IToken::DO_NOT_REMEMBER
  236. );
  237. if ($client) {
  238. $code = $this->random->generate(128, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
  239. $accessToken = new AccessToken();
  240. $accessToken->setClientId($client->getId());
  241. $accessToken->setEncryptedToken($this->crypto->encrypt($token, $code));
  242. $accessToken->setHashedCode(hash('sha512', $code));
  243. $accessToken->setTokenId($generatedToken->getId());
  244. $accessToken->setCodeCreatedAt($this->timeFactory->now()->getTimestamp());
  245. $this->accessTokenMapper->insert($accessToken);
  246. $redirectUri = $client->getRedirectUri();
  247. if (parse_url($redirectUri, PHP_URL_QUERY)) {
  248. $redirectUri .= '&';
  249. } else {
  250. $redirectUri .= '?';
  251. }
  252. $redirectUri .= sprintf(
  253. 'state=%s&code=%s',
  254. urlencode($this->session->get('oauth.state')),
  255. urlencode($code)
  256. );
  257. $this->session->remove('oauth.state');
  258. } else {
  259. $redirectUri = 'nc://login/server:' . $this->getServerPath() . '&user:' . urlencode($loginName) . '&password:' . urlencode($token);
  260. // Clear the token from the login here
  261. $this->tokenProvider->invalidateToken($sessionId);
  262. }
  263. $this->eventDispatcher->dispatchTyped(
  264. new AppPasswordCreatedEvent($generatedToken)
  265. );
  266. return new Http\RedirectResponse($redirectUri);
  267. }
  268. #[PublicPage]
  269. #[FrontpageRoute(verb: 'POST', url: '/login/flow/apptoken')]
  270. public function apptokenRedirect(string $stateToken, string $user, string $password): Response {
  271. if (!$this->isValidToken($stateToken)) {
  272. return $this->stateTokenForbiddenResponse();
  273. }
  274. try {
  275. $token = $this->tokenProvider->getToken($password);
  276. if ($token->getLoginName() !== $user) {
  277. throw new InvalidTokenException('login name does not match');
  278. }
  279. } catch (InvalidTokenException $e) {
  280. $response = new StandaloneTemplateResponse(
  281. $this->appName,
  282. '403',
  283. [
  284. 'message' => $this->l10n->t('Invalid app password'),
  285. ],
  286. 'guest'
  287. );
  288. $response->setStatus(Http::STATUS_FORBIDDEN);
  289. return $response;
  290. }
  291. $redirectUri = 'nc://login/server:' . $this->getServerPath() . '&user:' . urlencode($user) . '&password:' . urlencode($password);
  292. return new Http\RedirectResponse($redirectUri);
  293. }
  294. private function getServerPath(): string {
  295. $serverPostfix = '';
  296. if (str_contains($this->request->getRequestUri(), '/index.php')) {
  297. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/index.php'));
  298. } elseif (str_contains($this->request->getRequestUri(), '/login/flow')) {
  299. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/login/flow'));
  300. }
  301. $protocol = $this->request->getServerProtocol();
  302. if ($protocol !== 'https') {
  303. $xForwardedProto = $this->request->getHeader('X-Forwarded-Proto');
  304. $xForwardedSSL = $this->request->getHeader('X-Forwarded-Ssl');
  305. if ($xForwardedProto === 'https' || $xForwardedSSL === 'on') {
  306. $protocol = 'https';
  307. }
  308. }
  309. return $protocol . '://' . $this->request->getServerHost() . $serverPostfix;
  310. }
  311. }