ClientFlowLoginController.php 11 KB

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