ClientFlowLoginController.php 11 KB

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