You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ClientFlowLoginController.php 10KB

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