ClientFlowLoginController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author Mario Danic <mario@lovelyhq.com>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author RussellAult <RussellAult@users.noreply.github.com>
  14. * @author Sergej Nikolaev <kinolaev@gmail.com>
  15. * @author Kate Döen <kate.doeen@nextcloud.com>
  16. *
  17. * @license GNU AGPL version 3 or any later version
  18. *
  19. * This program is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License as
  21. * published by the Free Software Foundation, either version 3 of the
  22. * License, or (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  31. *
  32. */
  33. namespace OC\Core\Controller;
  34. use OC\Authentication\Events\AppPasswordCreatedEvent;
  35. use OC\Authentication\Exceptions\InvalidTokenException;
  36. use OC\Authentication\Exceptions\PasswordlessTokenException;
  37. use OC\Authentication\Token\IProvider;
  38. use OC\Authentication\Token\IToken;
  39. use OCA\OAuth2\Db\AccessToken;
  40. use OCA\OAuth2\Db\AccessTokenMapper;
  41. use OCA\OAuth2\Db\ClientMapper;
  42. use OCP\AppFramework\Controller;
  43. use OCP\AppFramework\Http;
  44. use OCP\AppFramework\Http\Attribute\IgnoreOpenAPI;
  45. use OCP\AppFramework\Http\Attribute\UseSession;
  46. use OCP\AppFramework\Http\Response;
  47. use OCP\AppFramework\Http\StandaloneTemplateResponse;
  48. use OCP\AppFramework\Utility\ITimeFactory;
  49. use OCP\Defaults;
  50. use OCP\EventDispatcher\IEventDispatcher;
  51. use OCP\IL10N;
  52. use OCP\IRequest;
  53. use OCP\ISession;
  54. use OCP\IURLGenerator;
  55. use OCP\IUser;
  56. use OCP\IUserSession;
  57. use OCP\Security\ICrypto;
  58. use OCP\Security\ISecureRandom;
  59. use OCP\Session\Exceptions\SessionNotAvailableException;
  60. #[IgnoreOpenAPI]
  61. class ClientFlowLoginController extends Controller {
  62. public const STATE_NAME = 'client.flow.state.token';
  63. public function __construct(
  64. string $appName,
  65. IRequest $request,
  66. private IUserSession $userSession,
  67. private IL10N $l10n,
  68. private Defaults $defaults,
  69. private ISession $session,
  70. private IProvider $tokenProvider,
  71. private ISecureRandom $random,
  72. private IURLGenerator $urlGenerator,
  73. private ClientMapper $clientMapper,
  74. private AccessTokenMapper $accessTokenMapper,
  75. private ICrypto $crypto,
  76. private IEventDispatcher $eventDispatcher,
  77. private ITimeFactory $timeFactory,
  78. ) {
  79. parent::__construct($appName, $request);
  80. }
  81. private function getClientName(): string {
  82. $userAgent = $this->request->getHeader('USER_AGENT');
  83. return $userAgent !== '' ? $userAgent : 'unknown';
  84. }
  85. private function isValidToken(string $stateToken): bool {
  86. $currentToken = $this->session->get(self::STATE_NAME);
  87. if (!is_string($currentToken)) {
  88. return false;
  89. }
  90. return hash_equals($currentToken, $stateToken);
  91. }
  92. private function stateTokenForbiddenResponse(): StandaloneTemplateResponse {
  93. $response = new StandaloneTemplateResponse(
  94. $this->appName,
  95. '403',
  96. [
  97. 'message' => $this->l10n->t('State token does not match'),
  98. ],
  99. 'guest'
  100. );
  101. $response->setStatus(Http::STATUS_FORBIDDEN);
  102. return $response;
  103. }
  104. /**
  105. * @PublicPage
  106. * @NoCSRFRequired
  107. */
  108. #[UseSession]
  109. public function showAuthPickerPage(string $clientIdentifier = '', string $user = '', int $direct = 0): StandaloneTemplateResponse {
  110. $clientName = $this->getClientName();
  111. $client = null;
  112. if ($clientIdentifier !== '') {
  113. $client = $this->clientMapper->getByIdentifier($clientIdentifier);
  114. $clientName = $client->getName();
  115. }
  116. // No valid clientIdentifier given and no valid API Request (APIRequest header not set)
  117. $clientRequest = $this->request->getHeader('OCS-APIREQUEST');
  118. if ($clientRequest !== 'true' && $client === null) {
  119. return new StandaloneTemplateResponse(
  120. $this->appName,
  121. 'error',
  122. [
  123. 'errors' =>
  124. [
  125. [
  126. 'error' => 'Access Forbidden',
  127. 'hint' => 'Invalid request',
  128. ],
  129. ],
  130. ],
  131. 'guest'
  132. );
  133. }
  134. $stateToken = $this->random->generate(
  135. 64,
  136. ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS
  137. );
  138. $this->session->set(self::STATE_NAME, $stateToken);
  139. $csp = new Http\ContentSecurityPolicy();
  140. if ($client) {
  141. $csp->addAllowedFormActionDomain($client->getRedirectUri());
  142. } else {
  143. $csp->addAllowedFormActionDomain('nc://*');
  144. }
  145. $response = new StandaloneTemplateResponse(
  146. $this->appName,
  147. 'loginflow/authpicker',
  148. [
  149. 'client' => $clientName,
  150. 'clientIdentifier' => $clientIdentifier,
  151. 'instanceName' => $this->defaults->getName(),
  152. 'urlGenerator' => $this->urlGenerator,
  153. 'stateToken' => $stateToken,
  154. 'serverHost' => $this->getServerPath(),
  155. 'oauthState' => $this->session->get('oauth.state'),
  156. 'user' => $user,
  157. 'direct' => $direct,
  158. ],
  159. 'guest'
  160. );
  161. $response->setContentSecurityPolicy($csp);
  162. return $response;
  163. }
  164. /**
  165. * @NoAdminRequired
  166. * @NoCSRFRequired
  167. * @NoSameSiteCookieRequired
  168. */
  169. #[UseSession]
  170. public function grantPage(string $stateToken = '',
  171. string $clientIdentifier = '',
  172. int $direct = 0): StandaloneTemplateResponse {
  173. if (!$this->isValidToken($stateToken)) {
  174. return $this->stateTokenForbiddenResponse();
  175. }
  176. $clientName = $this->getClientName();
  177. $client = null;
  178. if ($clientIdentifier !== '') {
  179. $client = $this->clientMapper->getByIdentifier($clientIdentifier);
  180. $clientName = $client->getName();
  181. }
  182. $csp = new Http\ContentSecurityPolicy();
  183. if ($client) {
  184. $csp->addAllowedFormActionDomain($client->getRedirectUri());
  185. } else {
  186. $csp->addAllowedFormActionDomain('nc://*');
  187. }
  188. /** @var IUser $user */
  189. $user = $this->userSession->getUser();
  190. $response = new StandaloneTemplateResponse(
  191. $this->appName,
  192. 'loginflow/grant',
  193. [
  194. 'userId' => $user->getUID(),
  195. 'userDisplayName' => $user->getDisplayName(),
  196. 'client' => $clientName,
  197. 'clientIdentifier' => $clientIdentifier,
  198. 'instanceName' => $this->defaults->getName(),
  199. 'urlGenerator' => $this->urlGenerator,
  200. 'stateToken' => $stateToken,
  201. 'serverHost' => $this->getServerPath(),
  202. 'oauthState' => $this->session->get('oauth.state'),
  203. 'direct' => $direct,
  204. ],
  205. 'guest'
  206. );
  207. $response->setContentSecurityPolicy($csp);
  208. return $response;
  209. }
  210. /**
  211. * @NoAdminRequired
  212. *
  213. * @return Http\RedirectResponse|Response
  214. */
  215. #[UseSession]
  216. public function generateAppPassword(string $stateToken,
  217. string $clientIdentifier = '') {
  218. if (!$this->isValidToken($stateToken)) {
  219. $this->session->remove(self::STATE_NAME);
  220. return $this->stateTokenForbiddenResponse();
  221. }
  222. $this->session->remove(self::STATE_NAME);
  223. try {
  224. $sessionId = $this->session->getId();
  225. } catch (SessionNotAvailableException $ex) {
  226. $response = new Response();
  227. $response->setStatus(Http::STATUS_FORBIDDEN);
  228. return $response;
  229. }
  230. try {
  231. $sessionToken = $this->tokenProvider->getToken($sessionId);
  232. $loginName = $sessionToken->getLoginName();
  233. try {
  234. $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
  235. } catch (PasswordlessTokenException $ex) {
  236. $password = null;
  237. }
  238. } catch (InvalidTokenException $ex) {
  239. $response = new Response();
  240. $response->setStatus(Http::STATUS_FORBIDDEN);
  241. return $response;
  242. }
  243. $clientName = $this->getClientName();
  244. $client = false;
  245. if ($clientIdentifier !== '') {
  246. $client = $this->clientMapper->getByIdentifier($clientIdentifier);
  247. $clientName = $client->getName();
  248. }
  249. $token = $this->random->generate(72, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
  250. $uid = $this->userSession->getUser()->getUID();
  251. $generatedToken = $this->tokenProvider->generateToken(
  252. $token,
  253. $uid,
  254. $loginName,
  255. $password,
  256. $clientName,
  257. IToken::PERMANENT_TOKEN,
  258. IToken::DO_NOT_REMEMBER
  259. );
  260. if ($client) {
  261. $code = $this->random->generate(128, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
  262. $accessToken = new AccessToken();
  263. $accessToken->setClientId($client->getId());
  264. $accessToken->setEncryptedToken($this->crypto->encrypt($token, $code));
  265. $accessToken->setHashedCode(hash('sha512', $code));
  266. $accessToken->setTokenId($generatedToken->getId());
  267. $accessToken->setCodeCreatedAt($this->timeFactory->now()->getTimestamp());
  268. $this->accessTokenMapper->insert($accessToken);
  269. $redirectUri = $client->getRedirectUri();
  270. if (parse_url($redirectUri, PHP_URL_QUERY)) {
  271. $redirectUri .= '&';
  272. } else {
  273. $redirectUri .= '?';
  274. }
  275. $redirectUri .= sprintf(
  276. 'state=%s&code=%s',
  277. urlencode($this->session->get('oauth.state')),
  278. urlencode($code)
  279. );
  280. $this->session->remove('oauth.state');
  281. } else {
  282. $redirectUri = 'nc://login/server:' . $this->getServerPath() . '&user:' . urlencode($loginName) . '&password:' . urlencode($token);
  283. // Clear the token from the login here
  284. $this->tokenProvider->invalidateToken($sessionId);
  285. }
  286. $this->eventDispatcher->dispatchTyped(
  287. new AppPasswordCreatedEvent($generatedToken)
  288. );
  289. return new Http\RedirectResponse($redirectUri);
  290. }
  291. /**
  292. * @PublicPage
  293. */
  294. public function apptokenRedirect(string $stateToken, string $user, string $password): Response {
  295. if (!$this->isValidToken($stateToken)) {
  296. return $this->stateTokenForbiddenResponse();
  297. }
  298. try {
  299. $token = $this->tokenProvider->getToken($password);
  300. if ($token->getLoginName() !== $user) {
  301. throw new InvalidTokenException('login name does not match');
  302. }
  303. } catch (InvalidTokenException $e) {
  304. $response = new StandaloneTemplateResponse(
  305. $this->appName,
  306. '403',
  307. [
  308. 'message' => $this->l10n->t('Invalid app password'),
  309. ],
  310. 'guest'
  311. );
  312. $response->setStatus(Http::STATUS_FORBIDDEN);
  313. return $response;
  314. }
  315. $redirectUri = 'nc://login/server:' . $this->getServerPath() . '&user:' . urlencode($user) . '&password:' . urlencode($password);
  316. return new Http\RedirectResponse($redirectUri);
  317. }
  318. private function getServerPath(): string {
  319. $serverPostfix = '';
  320. if (str_contains($this->request->getRequestUri(), '/index.php')) {
  321. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/index.php'));
  322. } elseif (str_contains($this->request->getRequestUri(), '/login/flow')) {
  323. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/login/flow'));
  324. }
  325. $protocol = $this->request->getServerProtocol();
  326. if ($protocol !== "https") {
  327. $xForwardedProto = $this->request->getHeader('X-Forwarded-Proto');
  328. $xForwardedSSL = $this->request->getHeader('X-Forwarded-Ssl');
  329. if ($xForwardedProto === 'https' || $xForwardedSSL === 'on') {
  330. $protocol = 'https';
  331. }
  332. }
  333. return $protocol . "://" . $this->request->getServerHost() . $serverPostfix;
  334. }
  335. }