ClientFlowLoginController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. 'message' => $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->getServerPath(),
  189. 'oauthState' => $this->session->get('oauth.state'),
  190. ],
  191. 'guest'
  192. );
  193. }
  194. /**
  195. * @NoAdminRequired
  196. * @NoCSRFRequired
  197. * @NoSameSiteCookieRequired
  198. * @UseSession
  199. *
  200. * @param string $stateToken
  201. * @param string $clientIdentifier
  202. * @return TemplateResponse
  203. */
  204. public function grantPage($stateToken = '',
  205. $clientIdentifier = '') {
  206. if(!$this->isValidToken($stateToken)) {
  207. return $this->stateTokenForbiddenResponse();
  208. }
  209. $clientName = $this->getClientName();
  210. $client = null;
  211. if($clientIdentifier !== '') {
  212. $client = $this->clientMapper->getByIdentifier($clientIdentifier);
  213. $clientName = $client->getName();
  214. }
  215. return new TemplateResponse(
  216. $this->appName,
  217. 'loginflow/grant',
  218. [
  219. 'client' => $clientName,
  220. 'clientIdentifier' => $clientIdentifier,
  221. 'instanceName' => $this->defaults->getName(),
  222. 'urlGenerator' => $this->urlGenerator,
  223. 'stateToken' => $stateToken,
  224. 'serverHost' => $this->getServerPath(),
  225. 'oauthState' => $this->session->get('oauth.state'),
  226. ],
  227. 'guest'
  228. );
  229. }
  230. /**
  231. * @NoAdminRequired
  232. * @UseSession
  233. *
  234. * @param string $stateToken
  235. * @param string $clientIdentifier
  236. * @return Http\RedirectResponse|Response
  237. */
  238. public function generateAppPassword($stateToken,
  239. $clientIdentifier = '') {
  240. if(!$this->isValidToken($stateToken)) {
  241. $this->session->remove(self::stateName);
  242. return $this->stateTokenForbiddenResponse();
  243. }
  244. $this->session->remove(self::stateName);
  245. try {
  246. $sessionId = $this->session->getId();
  247. } catch (SessionNotAvailableException $ex) {
  248. $response = new Response();
  249. $response->setStatus(Http::STATUS_FORBIDDEN);
  250. return $response;
  251. }
  252. try {
  253. $sessionToken = $this->tokenProvider->getToken($sessionId);
  254. $loginName = $sessionToken->getLoginName();
  255. try {
  256. $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
  257. } catch (PasswordlessTokenException $ex) {
  258. $password = null;
  259. }
  260. } catch (InvalidTokenException $ex) {
  261. $response = new Response();
  262. $response->setStatus(Http::STATUS_FORBIDDEN);
  263. return $response;
  264. }
  265. $clientName = $this->getClientName();
  266. $client = false;
  267. if($clientIdentifier !== '') {
  268. $client = $this->clientMapper->getByIdentifier($clientIdentifier);
  269. $clientName = $client->getName();
  270. }
  271. $token = $this->random->generate(72, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
  272. $uid = $this->userSession->getUser()->getUID();
  273. $generatedToken = $this->tokenProvider->generateToken(
  274. $token,
  275. $uid,
  276. $loginName,
  277. $password,
  278. $clientName,
  279. IToken::PERMANENT_TOKEN,
  280. IToken::DO_NOT_REMEMBER
  281. );
  282. if($client) {
  283. $code = $this->random->generate(128, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
  284. $accessToken = new AccessToken();
  285. $accessToken->setClientId($client->getId());
  286. $accessToken->setEncryptedToken($this->crypto->encrypt($token, $code));
  287. $accessToken->setHashedCode(hash('sha512', $code));
  288. $accessToken->setTokenId($generatedToken->getId());
  289. $this->accessTokenMapper->insert($accessToken);
  290. $redirectUri = sprintf(
  291. '%s?state=%s&code=%s',
  292. $client->getRedirectUri(),
  293. urlencode($this->session->get('oauth.state')),
  294. urlencode($code)
  295. );
  296. $this->session->remove('oauth.state');
  297. } else {
  298. $redirectUri = 'nc://login/server:' . $this->getServerPath() . '&user:' . urlencode($loginName) . '&password:' . urlencode($token);
  299. // Clear the token from the login here
  300. $this->tokenProvider->invalidateToken($sessionId);
  301. }
  302. return new Http\RedirectResponse($redirectUri);
  303. }
  304. /**
  305. * @PublicPage
  306. */
  307. public function apptokenRedirect(string $stateToken, string $user, string $password) {
  308. if (!$this->isValidToken($stateToken)) {
  309. return $this->stateTokenForbiddenResponse();
  310. }
  311. $redirectUri = 'nc://login/server:' . $this->getServerPath() . '&user:' . urlencode($user) . '&password:' . urlencode($password);
  312. return new Http\RedirectResponse($redirectUri);
  313. }
  314. private function getServerPath(): string {
  315. $serverPostfix = '';
  316. if (strpos($this->request->getRequestUri(), '/index.php') !== false) {
  317. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/index.php'));
  318. } else if (strpos($this->request->getRequestUri(), '/login/flow') !== false) {
  319. $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/login/flow'));
  320. }
  321. $protocol = $this->request->getServerProtocol();
  322. if ($protocol !== "https") {
  323. $xForwardedProto = $this->request->getHeader('X-Forwarded-Proto');
  324. $xForwardedSSL = $this->request->getHeader('X-Forwarded-Ssl');
  325. if ($xForwardedProto === 'https' || $xForwardedSSL === 'on') {
  326. $protocol = 'https';
  327. }
  328. }
  329. return $protocol . "://" . $this->request->getServerHost() . $serverPostfix;
  330. }
  331. }