ClientFlowLoginController.php 12 KB

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