1
0

ClientFlowLoginController.php 12 KB

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