1
0

ClientFlowLoginController.php 12 KB

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