diff --git a/src/applications/auth/controller/login/PhabricatorLoginController.php b/src/applications/auth/controller/login/PhabricatorLoginController.php index f55cc98662..c9cc43d098 100644 --- a/src/applications/auth/controller/login/PhabricatorLoginController.php +++ b/src/applications/auth/controller/login/PhabricatorLoginController.php @@ -1,172 +1,181 @@ getRequest(); if ($request->getUser()->getPHID()) { // Kick the user out if they're already logged in. return id(new AphrontRedirectResponse())->setURI('/'); } + $next_uri = $this->getRequest()->getPath(); + if ($next_uri == '/login/') { + $next_uri = null; + } + $password_auth = PhabricatorEnv::getEnvConfig('auth.password-auth-enabled'); $forms = array(); $error_view = null; if ($password_auth) { $error = false; $username = $request->getCookie('phusr'); if ($request->isFormPost()) { $username = $request->getStr('username'); $user = id(new PhabricatorUser())->loadOneWhere( 'username = %s', $username); $okay = false; if ($user) { if ($user->comparePassword($request->getStr('password'))) { $session_key = $user->establishSession('web'); $request->setCookie('phusr', $user->getUsername()); $request->setCookie('phsid', $session_key); return id(new AphrontRedirectResponse()) ->setURI('/'); } } if (!$okay) { $request->clearCookie('phusr'); $request->clearCookie('phsid'); } $error = true; } if ($error) { $error_view = new AphrontErrorView(); $error_view->setTitle('Bad username/password.'); } $form = new AphrontFormView(); $form ->setUser($request->getUser()) ->setAction('/login/') + ->addHiddenInput('next', $next_uri) ->appendChild( id(new AphrontFormTextControl()) ->setLabel('Username/Email') ->setName('username') ->setValue($username)) ->appendChild( id(new AphrontFormPasswordControl()) ->setLabel('Password') ->setName('password') ->setCaption( ''. 'Forgot your password? / Email Login')) ->appendChild( id(new AphrontFormSubmitControl()) ->setValue('Login')); // $panel->setCreateButton('Register New Account', '/login/register/'); $forms['Phabricator Login'] = $form; } + $oauth_state = $next_uri; + $providers = array( PhabricatorOAuthProvider::PROVIDER_FACEBOOK, PhabricatorOAuthProvider::PROVIDER_GITHUB, ); foreach ($providers as $provider_key) { $provider = PhabricatorOAuthProvider::newProvider($provider_key); $enabled = $provider->isProviderEnabled(); if (!$enabled) { continue; } $auth_uri = $provider->getAuthURI(); $redirect_uri = $provider->getRedirectURI(); $client_id = $provider->getClientID(); $provider_name = $provider->getProviderName(); $minimum_scope = $provider->getMinimumScope(); // TODO: In theory we should use 'state' to prevent CSRF, but the total // effect of the CSRF attack is that an attacker can cause a user to login // to Phabricator if they're already logged into some OAuth provider. This // does not seem like the most severe threat in the world, and generating // CSRF for logged-out users is vaugely tricky. if ($provider->isProviderRegistrationEnabled()) { $title = "Login or Register with {$provider_name}"; $body = "Login or register for Phabricator using your ". "{$provider_name} account."; $button = "Login or Register with {$provider_name}"; } else { $title = "Login with {$provider_name}"; $body = "Login to your existing Phabricator account using your ". "{$provider_name} account.

You can not use ". "{$provider_name} to register a new account."; $button = "Login with {$provider_name}"; } $auth_form = new AphrontFormView(); $auth_form ->setAction($auth_uri) ->addHiddenInput('client_id', $client_id) ->addHiddenInput('redirect_uri', $redirect_uri) ->addHiddenInput('scope', $minimum_scope) + ->addHiddenInput('state', $oauth_state) ->setUser($request->getUser()) ->setMethod('GET') ->appendChild( '

'.$body.'

') ->appendChild( id(new AphrontFormSubmitControl()) ->setValue("{$button} \xC2\xBB")); $forms[$title] = $auth_form; } $panel = new AphrontPanelView(); $panel->setWidth(AphrontPanelView::WIDTH_FORM); foreach ($forms as $name => $form) { $panel->appendChild('

'.$name.'

'); $panel->appendChild($form); $panel->appendChild('
'); } return $this->buildStandardPageResponse( array( $error_view, $panel, ), array( 'title' => 'Login', )); } } diff --git a/src/applications/auth/controller/oauth/PhabricatorOAuthLoginController.php b/src/applications/auth/controller/oauth/PhabricatorOAuthLoginController.php index 87d6bb9668..6baf7fd6f4 100644 --- a/src/applications/auth/controller/oauth/PhabricatorOAuthLoginController.php +++ b/src/applications/auth/controller/oauth/PhabricatorOAuthLoginController.php @@ -1,313 +1,324 @@ provider = PhabricatorOAuthProvider::newProvider($data['provider']); } public function processRequest() { $current_user = $this->getRequest()->getUser(); $provider = $this->provider; if (!$provider->isProviderEnabled()) { return new Aphront400Response(); } $provider_name = $provider->getProviderName(); $provider_key = $provider->getProviderKey(); $request = $this->getRequest(); if ($request->getStr('error')) { $error_view = id(new PhabricatorOAuthFailureView()) ->setRequest($request); return $this->buildErrorResponse($error_view); } $error_response = $this->retrieveAccessToken($provider); if ($error_response) { return $error_response; } $userinfo_uri = new PhutilURI($provider->getUserInfoURI()); $userinfo_uri->setQueryParams( array( 'access_token' => $this->accessToken, )); $user_json = @file_get_contents($userinfo_uri); $user_data = json_decode($user_json, true); $provider->setUserData($user_data); $provider->setAccessToken($this->accessToken); $user_id = $provider->retrieveUserID(); $provider_key = $provider->getProviderKey(); $oauth_info = $this->retrieveOAuthInfo($provider); if ($current_user->getPHID()) { if ($oauth_info->getID()) { if ($oauth_info->getUserID() != $current_user->getID()) { $dialog = new AphrontDialogView(); $dialog->setUser($current_user); $dialog->setTitle('Already Linked to Another Account'); $dialog->appendChild( '

The '.$provider_name.' account you just authorized '. 'is already linked to another Phabricator account. Before you can '. 'associate your '.$provider_name.' account with this Phabriactor '. 'account, you must unlink it from the Phabricator account it is '. 'currently linked to.

'); $dialog->addCancelButton('/settings/page/'.$provider_key.'/'); return id(new AphrontDialogResponse())->setDialog($dialog); } else { return id(new AphrontRedirectResponse()) ->setURI('/settings/page/'.$provider_key.'/'); } } $existing_oauth = id(new PhabricatorUserOAuthInfo())->loadOneWhere( 'userID = %d AND oauthProvider = %s', $current_user->getID(), $provider_key); if ($existing_oauth) { $dialog = new AphrontDialogView(); $dialog->setUser($current_user); $dialog->setTitle('Already Linked to an Account From This Provider'); $dialog->appendChild( '

The account you are logged in with is already linked to a '. $provider_name.' account. Before you can link it to a different '. $provider_name.' account, you must unlink the old account.

'); $dialog->addCancelButton('/settings/page/'.$provider_key.'/'); return id(new AphrontDialogResponse())->setDialog($dialog); } if (!$request->isDialogFormPost()) { $dialog = new AphrontDialogView(); $dialog->setUser($current_user); $dialog->setTitle('Link '.$provider_name.' Account'); $dialog->appendChild( '

Link your '.$provider_name.' account to your Phabricator '. 'account?

'); $dialog->addHiddenInput('token', $provider->getAccessToken()); $dialog->addHiddenInput('expires', $oauth_info->getTokenExpires()); + $dialog->addHiddenInput('state', $this->oauthState); $dialog->addSubmitButton('Link Accounts'); $dialog->addCancelButton('/settings/page/'.$provider_key.'/'); return id(new AphrontDialogResponse())->setDialog($dialog); } $oauth_info->setUserID($current_user->getID()); $oauth_info->save(); return id(new AphrontRedirectResponse()) ->setURI('/settings/page/'.$provider_key.'/'); } + $next_uri = '/'; + if ($this->oauthState) { + // Make sure a blind redirect to evil.com is impossible. + $uri = new PhutilURI($this->oauthState); + $next_uri = $uri->getPath(); + } // Login with known auth. if ($oauth_info->getID()) { $known_user = id(new PhabricatorUser())->load($oauth_info->getUserID()); $request->getApplicationConfiguration()->willAuthenticateUserWithOAuth( $known_user, $oauth_info, $provider); $session_key = $known_user->establishSession('web'); $oauth_info->save(); $request->setCookie('phusr', $known_user->getUsername()); $request->setCookie('phsid', $session_key); return id(new AphrontRedirectResponse()) - ->setURI('/'); + ->setURI($next_uri); } $oauth_email = $provider->retrieveUserEmail(); if ($oauth_email) { $known_email = id(new PhabricatorUser()) ->loadOneWhere('email = %s', $oauth_email); if ($known_email) { $dialog = new AphrontDialogView(); $dialog->setUser($current_user); $dialog->setTitle('Already Linked to Another Account'); $dialog->appendChild( '

The '.$provider_name.' account you just authorized has an '. 'email address which is already in use by another Phabricator '. 'account. To link the accounts, log in to your Phabricator '. 'account and then go to Settings.

'); $dialog->addCancelButton('/login/'); return id(new AphrontDialogResponse())->setDialog($dialog); } } if (!$provider->isProviderRegistrationEnabled()) { $dialog = new AphrontDialogView(); $dialog->setUser($current_user); $dialog->setTitle('No Account Registration With '.$provider_name); $dialog->appendChild( '

You can not register a new account using '.$provider_name.'; '. 'you can only use your '.$provider_name.' account to log into an '. 'existing Phabricator account which you have registered through '. 'other means.

'); $dialog->addCancelButton('/login/'); return id(new AphrontDialogResponse())->setDialog($dialog); } $class = PhabricatorEnv::getEnvConfig('controller.oauth-registration'); PhutilSymbolLoader::loadClass($class); $controller = newv($class, array($this->getRequest())); $controller->setOAuthProvider($provider); $controller->setOAuthInfo($oauth_info); + $controller->setOAuthState($this->oauthState); return $this->delegateToController($controller); } private function buildErrorResponse(PhabricatorOAuthFailureView $view) { $provider = $this->provider; $provider_name = $provider->getProviderName(); $view->setOAuthProvider($provider); return $this->buildStandardPageResponse( $view, array( 'title' => $provider_name.' Auth Failed', )); } private function retrieveAccessToken(PhabricatorOAuthProvider $provider) { $request = $this->getRequest(); $token = $request->getStr('token'); if ($token) { $this->tokenExpires = $request->getInt('expires'); $this->accessToken = $token; + $this->oauthState = $request->getStr('state'); return null; } $client_id = $provider->getClientID(); $client_secret = $provider->getClientSecret(); $redirect_uri = $provider->getRedirectURI(); $auth_uri = $provider->getTokenURI(); $code = $request->getStr('code'); $query_data = array( 'client_id' => $client_id, 'client_secret' => $client_secret, 'redirect_uri' => $redirect_uri, 'code' => $code, ); $post_data = http_build_query($query_data); $post_length = strlen($post_data); $stream_context = stream_context_create( array( 'http' => array( 'method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n". "Content-Length: {$post_length}\r\n", 'content' => $post_data, ), )); $stream = fopen($auth_uri, 'r', false, $stream_context); $response = false; $meta = null; if ($stream) { $meta = stream_get_meta_data($stream); $response = stream_get_contents($stream); fclose($stream); } if ($response === false) { return $this->buildErrorResponse(new PhabricatorOAuthFailureView()); } $data = array(); parse_str($response, $data); $token = idx($data, 'access_token'); if (!$token) { return $this->buildErrorResponse(new PhabricatorOAuthFailureView()); } if (idx($data, 'expires')) { $this->tokenExpires = time() + $data['expires']; } $this->accessToken = $token; + $this->oauthState = $request->getStr('state'); return null; } private function retrieveOAuthInfo(PhabricatorOAuthProvider $provider) { $oauth_info = id(new PhabricatorUserOAuthInfo())->loadOneWhere( 'oauthProvider = %s and oauthUID = %s', $provider->getProviderKey(), $provider->retrieveUserID()); if (!$oauth_info) { $oauth_info = new PhabricatorUserOAuthInfo(); $oauth_info->setOAuthProvider($provider->getProviderKey()); $oauth_info->setOAuthUID($provider->retrieveUserID()); } $oauth_info->setAccountURI($provider->retrieveUserAccountURI()); $oauth_info->setAccountName($provider->retrieveUserAccountName()); $oauth_info->setToken($provider->getAccessToken()); $oauth_info->setTokenStatus(PhabricatorUserOAuthInfo::TOKEN_STATUS_GOOD); // If we have out-of-date expiration info, just clear it out. Then replace // it with good info if the provider gave it to us. $expires = $oauth_info->getTokenExpires(); if ($expires <= time()) { $expires = null; } if ($this->tokenExpires) { $expires = $this->tokenExpires; } $oauth_info->setTokenExpires($expires); return $oauth_info; } } diff --git a/src/applications/auth/controller/oauthregistration/base/PhabricatorOAuthRegistrationController.php b/src/applications/auth/controller/oauthregistration/base/PhabricatorOAuthRegistrationController.php index addbe914ee..ec90b91ed0 100644 --- a/src/applications/auth/controller/oauthregistration/base/PhabricatorOAuthRegistrationController.php +++ b/src/applications/auth/controller/oauthregistration/base/PhabricatorOAuthRegistrationController.php @@ -1,43 +1,53 @@ oauthInfo = $info; return $this; } final public function getOAuthInfo() { return $this->oauthInfo; } final public function setOAuthProvider($provider) { $this->oauthProvider = $provider; return $this; } final public function getOAuthProvider() { return $this->oauthProvider; } + final public function setOAuthState($state) { + $this->oauthState = $state; + return $this; + } + + final public function getOAuthState() { + return $this->oauthState; + } + } diff --git a/src/applications/auth/controller/oauthregistration/default/PhabricatorOAuthDefaultRegistrationController.php b/src/applications/auth/controller/oauthregistration/default/PhabricatorOAuthDefaultRegistrationController.php index a72604cc7f..816092c6dd 100644 --- a/src/applications/auth/controller/oauthregistration/default/PhabricatorOAuthDefaultRegistrationController.php +++ b/src/applications/auth/controller/oauthregistration/default/PhabricatorOAuthDefaultRegistrationController.php @@ -1,175 +1,176 @@ getOAuthProvider(); $oauth_info = $this->getOAuthInfo(); $request = $this->getRequest(); $errors = array(); $e_username = true; $e_email = true; $e_realname = true; $user = new PhabricatorUser(); $user->setUsername($provider->retrieveUserAccountName()); $user->setRealName($provider->retrieveUserRealName()); $user->setEmail($provider->retrieveUserEmail()); if ($request->isFormPost()) { $user->setUsername($request->getStr('username')); $username = $user->getUsername(); $matches = null; if (!strlen($user->getUsername())) { $e_username = 'Required'; $errors[] = 'Username is required.'; } else if (!preg_match('/^[a-zA-Z0-9]+$/', $username, $matches)) { $e_username = 'Invalid'; $errors[] = 'Username may only contain letters and numbers.'; } else { $e_username = null; } if ($user->getEmail() === null) { $user->setEmail($request->getStr('email')); if (!strlen($user->getEmail())) { $e_email = 'Required'; $errors[] = 'Email is required.'; } else { $e_email = null; } } if ($user->getRealName() === null) { $user->setRealName($request->getStr('realname')); if (!strlen($user->getStr('realname'))) { $e_realname = 'Required'; $errors[] = 'Real name is required.'; } else { $e_realname = null; } } if (!$errors) { $image = $provider->retrieveUserProfileImage(); if ($image) { $file = PhabricatorFile::newFromFileData( $image, array( 'name' => $provider->getProviderKey().'-profile.jpg' )); $user->setProfileImagePHID($file->getPHID()); } try { $user->save(); $oauth_info->setUserID($user->getID()); $oauth_info->save(); $session_key = $user->establishSession('web'); $request->setCookie('phusr', $user->getUsername()); $request->setCookie('phsid', $session_key); return id(new AphrontRedirectResponse())->setURI('/'); } catch (AphrontQueryDuplicateKeyException $exception) { $same_username = id(new PhabricatorUser())->loadOneWhere( 'userName = %s', $user->getUserName()); $same_email = id(new PhabricatorUser())->loadOneWhere( 'email = %s', $user->getEmail()); if ($same_username) { $e_username = 'Duplicate'; $errors[] = 'That username or email is not unique.'; } else if ($same_email) { $e_email = 'Duplicate'; $errors[] = 'That email is not unique.'; } else { throw $exception; } } } } $error_view = null; if ($errors) { $error_view = new AphrontErrorView(); $error_view->setTitle('Registration Failed'); $error_view->setErrors($errors); } $form = new AphrontFormView(); $form ->addHiddenInput('token', $provider->getAccessToken()) ->addHiddenInput('expires', $oauth_info->getTokenExpires()) + ->addHiddenInput('state', $this->getOAuthState()) ->setUser($request->getUser()) ->setAction($provider->getRedirectURI()) ->appendChild( id(new AphrontFormTextControl()) ->setLabel('Username') ->setName('username') ->setValue($user->getUsername()) ->setError($e_username)); if ($provider->retrieveUserEmail() === null) { $form->appendChild( id(new AphrontFormTextControl()) ->setLabel('Email') ->setName('email') ->setValue($request->getStr('email')) ->setError($e_email)); } if ($provider->retrieveUserRealName () === null) { $form->appendChild( id(new AphrontFormTextControl()) ->setLabel('Real Name') ->setName('realname') ->setValue($request->getStr('realname')) ->setError($e_realname)); } $form ->appendChild( id(new AphrontFormSubmitControl()) ->setValue('Create Account')); $panel = new AphrontPanelView(); $panel->setHeader('Create New Account'); $panel->setWidth(AphrontPanelView::WIDTH_FORM); $panel->appendChild($form); return $this->buildStandardPageResponse( array( $error_view, $panel, ), array( 'title' => 'Create New Account', )); } } diff --git a/src/applications/base/controller/base/PhabricatorController.php b/src/applications/base/controller/base/PhabricatorController.php index a05964173e..fdcc24e356 100644 --- a/src/applications/base/controller/base/PhabricatorController.php +++ b/src/applications/base/controller/base/PhabricatorController.php @@ -1,77 +1,78 @@ getRequest(); $user = new PhabricatorUser(); $phusr = $request->getCookie('phusr'); $phsid = $request->getCookie('phsid'); if ($phusr && $phsid) { $info = queryfx_one( $user->establishConnection('r'), 'SELECT u.* FROM %T u JOIN %T s ON u.phid = s.userPHID AND s.type = %s AND s.sessionKey = %s', $user->getTableName(), 'phabricator_session', 'web', $phsid); if ($info) { $user->loadFromArray($info); } } $request->setUser($user); if (PhabricatorEnv::getEnvConfig('darkconsole.enabled')) { if ($user->getConsoleEnabled() || PhabricatorEnv::getEnvConfig('darkconsole.always-on')) { $console = new DarkConsoleCore(); $request->getApplicationConfiguration()->setConsole($console); } } if ($this->shouldRequireLogin() && !$user->getPHID()) { - throw new AphrontRedirectException('/login/'); + $login_controller = new PhabricatorLoginController($request); + return $this->delegateToController($login_controller); } } public function buildStandardPageView() { $view = new PhabricatorStandardPageView(); $view->setRequest($this->getRequest()); return $view; } public function buildStandardPageResponse($view, array $data) { $page = $this->buildStandardPageView(); $page->appendChild($view); $response = new AphrontWebpageResponse(); $response->setContent($page->render()); return $response; } } diff --git a/src/applications/base/controller/base/__init__.php b/src/applications/base/controller/base/__init__.php index ebf030f26b..fa8ccfb02f 100644 --- a/src/applications/base/controller/base/__init__.php +++ b/src/applications/base/controller/base/__init__.php @@ -1,19 +1,19 @@ ', where '' ". "is one of 'development', 'production', or a custom environment."); } if (!function_exists('mysql_connect')) { phabricator_fatal_config_error( "The PHP MySQL extension is not installed. This extension is required."); } if (!isset($_REQUEST['__path__'])) { phabricator_fatal_config_error( "__path__ is not set. Your rewrite rules are not configured correctly."); } require_once dirname(dirname(__FILE__)).'/conf/__init_conf__.php'; $conf = phabricator_read_config_file($env); $conf['phabricator.env'] = $env; setup_aphront_basics(); phutil_require_module('phabricator', 'infrastructure/env'); PhabricatorEnv::setEnvConfig($conf); phutil_require_module('phabricator', 'aphront/console/plugin/xhprof/api'); DarkConsoleXHProfPluginAPI::hookProfiler(); phutil_require_module('phabricator', 'aphront/console/plugin/errorlog/api'); set_error_handler(array('DarkConsoleErrorLogPluginAPI', 'handleError')); set_exception_handler(array('DarkConsoleErrorLogPluginAPI', 'handleException')); foreach (PhabricatorEnv::getEnvConfig('load-libraries') as $library) { phutil_load_library($library); } $host = $_SERVER['HTTP_HOST']; $path = $_REQUEST['__path__']; switch ($host) { default: $config_key = 'aphront.default-application-configuration-class'; $config_class = PhabricatorEnv::getEnvConfig($config_key); PhutilSymbolLoader::loadClass($config_class); $application = newv($config_class, array()); break; } $application->setHost($host); $application->setPath($path); $application->willBuildRequest(); $request = $application->buildRequest(); $application->setRequest($request); list($controller, $uri_data) = $application->buildController(); try { - $controller->willBeginExecution(); - - $controller->willProcessRequest($uri_data); - $response = $controller->processRequest(); + $response = $controller->willBeginExecution(); + if (!$response) { + $controller->willProcessRequest($uri_data); + $response = $controller->processRequest(); + } } catch (AphrontRedirectException $ex) { $response = id(new AphrontRedirectResponse()) ->setURI($ex->getURI()); } catch (Exception $ex) { $response = $application->handleException($ex); } $response = $application->willSendResponse($response); $response->setRequest($request); $response_string = $response->buildResponseString(); $code = $response->getHTTPResponseCode(); if ($code != 200) { header("HTTP/1.0 {$code}"); } $headers = $response->getCacheHeaders(); $headers = array_merge($headers, $response->getHeaders()); foreach ($headers as $header) { list($header, $value) = $header; header("{$header}: {$value}"); } // TODO: This shouldn't be possible in a production-configured environment. if (isset($_REQUEST['__profile__']) && ($_REQUEST['__profile__'] == 'all')) { $profile = DarkConsoleXHProfPluginAPI::stopProfiler(); $profile = '
'. ''. '>>> View Profile <<<'. ''. '
'; if (strpos($response_string, '') !== false) { $response_string = str_replace( '', ''.$profile, $response_string); } else { echo $profile; } } echo $response_string; /** * @group aphront */ function setup_aphront_basics() { $aphront_root = dirname(dirname(__FILE__)); $libraries_root = dirname($aphront_root); $root = null; if (!empty($_SERVER['PHUTIL_LIBRARY_ROOT'])) { $root = $_SERVER['PHUTIL_LIBRARY_ROOT']; } ini_set('include_path', $libraries_root.':'.ini_get('include_path')); @include_once $root.'libphutil/src/__phutil_library_init__.php'; if (!@constant('__LIBPHUTIL__')) { echo "ERROR: Unable to load libphutil. Update your PHP 'include_path' to ". "include the parent directory of libphutil/.\n"; exit(1); } // Load Phabricator itself using the absolute path, so we never end up doing // anything surprising (loading index.php and libraries from different // directories). phutil_load_library($aphront_root.'/src'); phutil_load_library('arcanist/src'); } function __autoload($class_name) { PhutilSymbolLoader::loadClass($class_name); } function phabricator_fatal_config_error($msg) { header('Content-Type: text/plain', $replace = true, $http_error = 500); $error = "CONFIG ERROR: ".$msg."\n"; error_log($error); echo $error; die(); }