Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ClientFlowLoginController.php 12KB

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