ClientFlowLoginController.php 11 KB

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