123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389 |
- <?php
- /**
- * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Daniel Kesselberg <mail@danielkesselberg.de>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Mario Danic <mario@lovelyhq.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author RussellAult <RussellAult@users.noreply.github.com>
- * @author Sergej Nikolaev <kinolaev@gmail.com>
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- */
- namespace OC\Core\Controller;
- use OC\Authentication\Events\AppPasswordCreatedEvent;
- use OC\Authentication\Exceptions\InvalidTokenException;
- use OC\Authentication\Exceptions\PasswordlessTokenException;
- use OC\Authentication\Token\IProvider;
- use OC\Authentication\Token\IToken;
- use OCA\OAuth2\Db\AccessToken;
- use OCA\OAuth2\Db\AccessTokenMapper;
- use OCA\OAuth2\Db\ClientMapper;
- use OCP\AppFramework\Controller;
- use OCP\AppFramework\Http;
- use OCP\AppFramework\Http\Attribute\UseSession;
- use OCP\AppFramework\Http\Response;
- use OCP\AppFramework\Http\StandaloneTemplateResponse;
- use OCP\Defaults;
- use OCP\EventDispatcher\IEventDispatcher;
- use OCP\IL10N;
- use OCP\IRequest;
- use OCP\ISession;
- use OCP\IURLGenerator;
- use OCP\IUser;
- use OCP\IUserSession;
- use OCP\Security\ICrypto;
- use OCP\Security\ISecureRandom;
- use OCP\Session\Exceptions\SessionNotAvailableException;
- class ClientFlowLoginController extends Controller {
- private IUserSession $userSession;
- private IL10N $l10n;
- private Defaults $defaults;
- private ISession $session;
- private IProvider $tokenProvider;
- private ISecureRandom $random;
- private IURLGenerator $urlGenerator;
- private ClientMapper $clientMapper;
- private AccessTokenMapper $accessTokenMapper;
- private ICrypto $crypto;
- private IEventDispatcher $eventDispatcher;
- public const STATE_NAME = 'client.flow.state.token';
- public function __construct(string $appName,
- IRequest $request,
- IUserSession $userSession,
- IL10N $l10n,
- Defaults $defaults,
- ISession $session,
- IProvider $tokenProvider,
- ISecureRandom $random,
- IURLGenerator $urlGenerator,
- ClientMapper $clientMapper,
- AccessTokenMapper $accessTokenMapper,
- ICrypto $crypto,
- IEventDispatcher $eventDispatcher) {
- parent::__construct($appName, $request);
- $this->userSession = $userSession;
- $this->l10n = $l10n;
- $this->defaults = $defaults;
- $this->session = $session;
- $this->tokenProvider = $tokenProvider;
- $this->random = $random;
- $this->urlGenerator = $urlGenerator;
- $this->clientMapper = $clientMapper;
- $this->accessTokenMapper = $accessTokenMapper;
- $this->crypto = $crypto;
- $this->eventDispatcher = $eventDispatcher;
- }
- private function getClientName(): string {
- $userAgent = $this->request->getHeader('USER_AGENT');
- return $userAgent !== '' ? $userAgent : 'unknown';
- }
- private function isValidToken(string $stateToken): bool {
- $currentToken = $this->session->get(self::STATE_NAME);
- if (!is_string($currentToken)) {
- return false;
- }
- return hash_equals($currentToken, $stateToken);
- }
- private function stateTokenForbiddenResponse(): StandaloneTemplateResponse {
- $response = new StandaloneTemplateResponse(
- $this->appName,
- '403',
- [
- 'message' => $this->l10n->t('State token does not match'),
- ],
- 'guest'
- );
- $response->setStatus(Http::STATUS_FORBIDDEN);
- return $response;
- }
- /**
- * @PublicPage
- * @NoCSRFRequired
- */
- #[UseSession]
- public function showAuthPickerPage(string $clientIdentifier = '', string $user = '', int $direct = 0): StandaloneTemplateResponse {
- $clientName = $this->getClientName();
- $client = null;
- if ($clientIdentifier !== '') {
- $client = $this->clientMapper->getByIdentifier($clientIdentifier);
- $clientName = $client->getName();
- }
- // No valid clientIdentifier given and no valid API Request (APIRequest header not set)
- $clientRequest = $this->request->getHeader('OCS-APIREQUEST');
- if ($clientRequest !== 'true' && $client === null) {
- return new StandaloneTemplateResponse(
- $this->appName,
- 'error',
- [
- 'errors' =>
- [
- [
- 'error' => 'Access Forbidden',
- 'hint' => 'Invalid request',
- ],
- ],
- ],
- 'guest'
- );
- }
- $stateToken = $this->random->generate(
- 64,
- ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS
- );
- $this->session->set(self::STATE_NAME, $stateToken);
- $csp = new Http\ContentSecurityPolicy();
- if ($client) {
- $csp->addAllowedFormActionDomain($client->getRedirectUri());
- } else {
- $csp->addAllowedFormActionDomain('nc://*');
- }
- $response = new StandaloneTemplateResponse(
- $this->appName,
- 'loginflow/authpicker',
- [
- 'client' => $clientName,
- 'clientIdentifier' => $clientIdentifier,
- 'instanceName' => $this->defaults->getName(),
- 'urlGenerator' => $this->urlGenerator,
- 'stateToken' => $stateToken,
- 'serverHost' => $this->getServerPath(),
- 'oauthState' => $this->session->get('oauth.state'),
- 'user' => $user,
- 'direct' => $direct,
- ],
- 'guest'
- );
- $response->setContentSecurityPolicy($csp);
- return $response;
- }
- /**
- * @NoAdminRequired
- * @NoCSRFRequired
- * @NoSameSiteCookieRequired
- */
- #[UseSession]
- public function grantPage(string $stateToken = '',
- string $clientIdentifier = '',
- int $direct = 0): StandaloneTemplateResponse {
- if (!$this->isValidToken($stateToken)) {
- return $this->stateTokenForbiddenResponse();
- }
- $clientName = $this->getClientName();
- $client = null;
- if ($clientIdentifier !== '') {
- $client = $this->clientMapper->getByIdentifier($clientIdentifier);
- $clientName = $client->getName();
- }
- $csp = new Http\ContentSecurityPolicy();
- if ($client) {
- $csp->addAllowedFormActionDomain($client->getRedirectUri());
- } else {
- $csp->addAllowedFormActionDomain('nc://*');
- }
- /** @var IUser $user */
- $user = $this->userSession->getUser();
- $response = new StandaloneTemplateResponse(
- $this->appName,
- 'loginflow/grant',
- [
- 'userId' => $user->getUID(),
- 'userDisplayName' => $user->getDisplayName(),
- 'client' => $clientName,
- 'clientIdentifier' => $clientIdentifier,
- 'instanceName' => $this->defaults->getName(),
- 'urlGenerator' => $this->urlGenerator,
- 'stateToken' => $stateToken,
- 'serverHost' => $this->getServerPath(),
- 'oauthState' => $this->session->get('oauth.state'),
- 'direct' => $direct,
- ],
- 'guest'
- );
- $response->setContentSecurityPolicy($csp);
- return $response;
- }
- /**
- * @NoAdminRequired
- *
- * @return Http\RedirectResponse|Response
- */
- #[UseSession]
- public function generateAppPassword(string $stateToken,
- string $clientIdentifier = '') {
- if (!$this->isValidToken($stateToken)) {
- $this->session->remove(self::STATE_NAME);
- return $this->stateTokenForbiddenResponse();
- }
- $this->session->remove(self::STATE_NAME);
- try {
- $sessionId = $this->session->getId();
- } catch (SessionNotAvailableException $ex) {
- $response = new Response();
- $response->setStatus(Http::STATUS_FORBIDDEN);
- return $response;
- }
- try {
- $sessionToken = $this->tokenProvider->getToken($sessionId);
- $loginName = $sessionToken->getLoginName();
- try {
- $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
- } catch (PasswordlessTokenException $ex) {
- $password = null;
- }
- } catch (InvalidTokenException $ex) {
- $response = new Response();
- $response->setStatus(Http::STATUS_FORBIDDEN);
- return $response;
- }
- $clientName = $this->getClientName();
- $client = false;
- if ($clientIdentifier !== '') {
- $client = $this->clientMapper->getByIdentifier($clientIdentifier);
- $clientName = $client->getName();
- }
- $token = $this->random->generate(72, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
- $uid = $this->userSession->getUser()->getUID();
- $generatedToken = $this->tokenProvider->generateToken(
- $token,
- $uid,
- $loginName,
- $password,
- $clientName,
- IToken::PERMANENT_TOKEN,
- IToken::DO_NOT_REMEMBER
- );
- if ($client) {
- $code = $this->random->generate(128, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
- $accessToken = new AccessToken();
- $accessToken->setClientId($client->getId());
- $accessToken->setEncryptedToken($this->crypto->encrypt($token, $code));
- $accessToken->setHashedCode(hash('sha512', $code));
- $accessToken->setTokenId($generatedToken->getId());
- $this->accessTokenMapper->insert($accessToken);
- $redirectUri = $client->getRedirectUri();
- if (parse_url($redirectUri, PHP_URL_QUERY)) {
- $redirectUri .= '&';
- } else {
- $redirectUri .= '?';
- }
- $redirectUri .= sprintf(
- 'state=%s&code=%s',
- urlencode($this->session->get('oauth.state')),
- urlencode($code)
- );
- $this->session->remove('oauth.state');
- } else {
- $redirectUri = 'nc://login/server:' . $this->getServerPath() . '&user:' . urlencode($loginName) . '&password:' . urlencode($token);
- // Clear the token from the login here
- $this->tokenProvider->invalidateToken($sessionId);
- }
- $this->eventDispatcher->dispatchTyped(
- new AppPasswordCreatedEvent($generatedToken)
- );
- return new Http\RedirectResponse($redirectUri);
- }
- /**
- * @PublicPage
- */
- public function apptokenRedirect(string $stateToken, string $user, string $password): Response {
- if (!$this->isValidToken($stateToken)) {
- return $this->stateTokenForbiddenResponse();
- }
- try {
- $token = $this->tokenProvider->getToken($password);
- if ($token->getLoginName() !== $user) {
- throw new InvalidTokenException('login name does not match');
- }
- } catch (InvalidTokenException $e) {
- $response = new StandaloneTemplateResponse(
- $this->appName,
- '403',
- [
- 'message' => $this->l10n->t('Invalid app password'),
- ],
- 'guest'
- );
- $response->setStatus(Http::STATUS_FORBIDDEN);
- return $response;
- }
- $redirectUri = 'nc://login/server:' . $this->getServerPath() . '&user:' . urlencode($user) . '&password:' . urlencode($password);
- return new Http\RedirectResponse($redirectUri);
- }
- private function getServerPath(): string {
- $serverPostfix = '';
- if (strpos($this->request->getRequestUri(), '/index.php') !== false) {
- $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/index.php'));
- } elseif (strpos($this->request->getRequestUri(), '/login/flow') !== false) {
- $serverPostfix = substr($this->request->getRequestUri(), 0, strpos($this->request->getRequestUri(), '/login/flow'));
- }
- $protocol = $this->request->getServerProtocol();
- if ($protocol !== "https") {
- $xForwardedProto = $this->request->getHeader('X-Forwarded-Proto');
- $xForwardedSSL = $this->request->getHeader('X-Forwarded-Ssl');
- if ($xForwardedProto === 'https' || $xForwardedSSL === 'on') {
- $protocol = 'https';
- }
- }
- return $protocol . "://" . $this->request->getServerHost() . $serverPostfix;
- }
- }
|