1
0
Fork 0
mirror of https://we.phorge.it/source/phorge.git synced 2024-12-19 03:50:54 +01:00

Make password reset emails use one-time tokens

Summary:
Ref T4398. This code hadn't been touched in a while and had a few crufty bits.

**One Time Resets**: Currently, password reset (and similar links) are valid for about 48 hours, but we always use one token to generate them (it's bound to the account). This isn't horrible, but it could be better, and it produces a lot of false positives on HackerOne.

Instead, use TemporaryTokens to make each link one-time only and good for no more than 24 hours.

**Coupling of Email Verification and One-Time Login**: Currently, one-time login links ("password reset links") are tightly bound to an email address, and using a link verifies that email address.

This is convenient for "Welcome" emails, so the user doesn't need to go through two rounds of checking email in order to login, then very their email, then actually get access to Phabricator.

However, for other types of these links (like those generated by `bin/auth recover`) there's no need to do any email verification.

Instead, make the email verification part optional, and use it on welcome links but not other types of links.

**Message Customization**: These links can come out of several workflows: welcome, password reset, username change, or `bin/auth recover`. Add a hint to the URI so the text on the page can be customized a bit to help users through the workflow.

**Reset Emails Going to Main Account Email**: Previously, we would send password reset email to the user's primary account email. However, since we verify email coming from reset links this isn't correct and could allow a user to verify an email without actually controlling it.

Since the user needs a real account in the first place this does not seem useful on its own, but might be a component in some other attack. The user might also no longer have access to their primary account, in which case this wouldn't be wrong, but would not be very useful.

Mitigate this in two ways:

  - First, send to the actual email address the user entered, not the primary account email address.
  - Second, don't let these links verify emails: they're just login links. This primarily makes it more difficult for an attacker to add someone else's email to their account, send them a reset link, get them to login and implicitly verify the email by not reading very carefully, and then figure out something interesting to do (there's currently no followup attack here, but allowing this does seem undesirable).

**Password Reset Without Old Password**: After a user logs in via email, we send them to the password settings panel (if passwords are enabled) with a code that lets them set a new password without knowing the old one.

Previously, this code was static and based on the email address. Instead, issue a one-time code.

**Jump Into Hisec**: Normally, when a user who has multi-factor auth on their account logs in, we prompt them for factors but don't put them in high security. You usually don't want to go do high-security stuff immediately after login, and it would be confusing and annoying if normal logins gave you a "YOU ARE IN HIGH SECURITY" alert bubble.

However, if we're taking you to the password reset screen, we //do// want to put the user in high security, since that screen requires high security. If we don't do this, the user gets two factor prompts in a row.

To accomplish this, we set a cookie when we know we're sending the user into a high security workflow. This cookie makes login finalization upgrade all the way from "partial" to "high security", instead of stopping halfway at "normal". This is safe because the user has just passed a factor check; the only reason we don't normally do this is to reduce annoyance.

**Some UI Cleanup**: Some of this was using really old UI. Modernize it a bit.

Test Plan:
  - **One Time Resets**
    - Used a reset link.
    - Tried to reuse a reset link, got denied.
    - Verified each link is different.
  - **Coupling of Email Verification and One-Time Login**
    - Verified that `bin/auth`, password reset, and username change links do not have an email verifying URI component.
    - Tried to tack one on, got denied.
    - Used the welcome email link to login + verify.
    - Tried to mutate the URI to not verify, or verify something else: got denied.
  - **Message Customization**
    - Viewed messages on the different workflows. They seemed OK.
  - **Reset Emails Going to Main Account Email**
    - Sent password reset email to non-primary email.
    - Received email at specified address.
    - Verified it does not verify the address.
  - **Password Reset Without Old Password**
    - Reset password without knowledge of old one after email reset.
    - Tried to do that without a key, got denied.
    - Tried to reuse a key, got denied.
  - **Jump Into Hisec**
    - Logged in with MFA user, got factor'd, jumped directly into hisec.
    - Logged in with non-MFA user, no factors, normal password reset.
  - **Some UI Cleanup**
    - Viewed new UI.
  - **Misc**
    - Created accounts, logged in with welcome link, got verified.
    - Changed a username, used link to log back in.

Reviewers: btrahan

Reviewed By: btrahan

Subscribers: epriestley

Maniphest Tasks: T4398

Differential Revision: https://secure.phabricator.com/D9252
This commit is contained in:
epriestley 2014-05-22 10:41:00 -07:00
parent 5e7b316fbe
commit f1534e6feb
11 changed files with 411 additions and 227 deletions

View file

@ -1249,6 +1249,7 @@ phutil_register_library_map(array(
'PhabricatorAuthNeedsApprovalController' => 'applications/auth/controller/PhabricatorAuthNeedsApprovalController.php', 'PhabricatorAuthNeedsApprovalController' => 'applications/auth/controller/PhabricatorAuthNeedsApprovalController.php',
'PhabricatorAuthNewController' => 'applications/auth/controller/config/PhabricatorAuthNewController.php', 'PhabricatorAuthNewController' => 'applications/auth/controller/config/PhabricatorAuthNewController.php',
'PhabricatorAuthOldOAuthRedirectController' => 'applications/auth/controller/PhabricatorAuthOldOAuthRedirectController.php', 'PhabricatorAuthOldOAuthRedirectController' => 'applications/auth/controller/PhabricatorAuthOldOAuthRedirectController.php',
'PhabricatorAuthOneTimeLoginController' => 'applications/auth/controller/PhabricatorAuthOneTimeLoginController.php',
'PhabricatorAuthPHIDTypeAuthFactor' => 'applications/auth/phid/PhabricatorAuthPHIDTypeAuthFactor.php', 'PhabricatorAuthPHIDTypeAuthFactor' => 'applications/auth/phid/PhabricatorAuthPHIDTypeAuthFactor.php',
'PhabricatorAuthProvider' => 'applications/auth/provider/PhabricatorAuthProvider.php', 'PhabricatorAuthProvider' => 'applications/auth/provider/PhabricatorAuthProvider.php',
'PhabricatorAuthProviderConfig' => 'applications/auth/storage/PhabricatorAuthProviderConfig.php', 'PhabricatorAuthProviderConfig' => 'applications/auth/storage/PhabricatorAuthProviderConfig.php',
@ -1525,7 +1526,6 @@ phutil_register_library_map(array(
'PhabricatorEdgeTestCase' => 'infrastructure/edges/__tests__/PhabricatorEdgeTestCase.php', 'PhabricatorEdgeTestCase' => 'infrastructure/edges/__tests__/PhabricatorEdgeTestCase.php',
'PhabricatorEditor' => 'infrastructure/PhabricatorEditor.php', 'PhabricatorEditor' => 'infrastructure/PhabricatorEditor.php',
'PhabricatorEmailLoginController' => 'applications/auth/controller/PhabricatorEmailLoginController.php', 'PhabricatorEmailLoginController' => 'applications/auth/controller/PhabricatorEmailLoginController.php',
'PhabricatorEmailTokenController' => 'applications/auth/controller/PhabricatorEmailTokenController.php',
'PhabricatorEmailVerificationController' => 'applications/auth/controller/PhabricatorEmailVerificationController.php', 'PhabricatorEmailVerificationController' => 'applications/auth/controller/PhabricatorEmailVerificationController.php',
'PhabricatorEmptyQueryException' => 'infrastructure/query/PhabricatorEmptyQueryException.php', 'PhabricatorEmptyQueryException' => 'infrastructure/query/PhabricatorEmptyQueryException.php',
'PhabricatorEnglishTranslation' => 'infrastructure/internationalization/translation/PhabricatorEnglishTranslation.php', 'PhabricatorEnglishTranslation' => 'infrastructure/internationalization/translation/PhabricatorEnglishTranslation.php',
@ -4011,6 +4011,7 @@ phutil_register_library_map(array(
'PhabricatorAuthNeedsApprovalController' => 'PhabricatorAuthController', 'PhabricatorAuthNeedsApprovalController' => 'PhabricatorAuthController',
'PhabricatorAuthNewController' => 'PhabricatorAuthProviderConfigController', 'PhabricatorAuthNewController' => 'PhabricatorAuthProviderConfigController',
'PhabricatorAuthOldOAuthRedirectController' => 'PhabricatorAuthController', 'PhabricatorAuthOldOAuthRedirectController' => 'PhabricatorAuthController',
'PhabricatorAuthOneTimeLoginController' => 'PhabricatorAuthController',
'PhabricatorAuthPHIDTypeAuthFactor' => 'PhabricatorPHIDType', 'PhabricatorAuthPHIDTypeAuthFactor' => 'PhabricatorPHIDType',
'PhabricatorAuthProviderConfig' => 'PhabricatorAuthProviderConfig' =>
array( array(
@ -4325,7 +4326,6 @@ phutil_register_library_map(array(
'PhabricatorEdgeTestCase' => 'PhabricatorTestCase', 'PhabricatorEdgeTestCase' => 'PhabricatorTestCase',
'PhabricatorEditor' => 'Phobject', 'PhabricatorEditor' => 'Phobject',
'PhabricatorEmailLoginController' => 'PhabricatorAuthController', 'PhabricatorEmailLoginController' => 'PhabricatorAuthController',
'PhabricatorEmailTokenController' => 'PhabricatorAuthController',
'PhabricatorEmailVerificationController' => 'PhabricatorAuthController', 'PhabricatorEmailVerificationController' => 'PhabricatorAuthController',
'PhabricatorEmptyQueryException' => 'Exception', 'PhabricatorEmptyQueryException' => 'Exception',
'PhabricatorEnglishTranslation' => 'PhabricatorBaseEnglishTranslation', 'PhabricatorEnglishTranslation' => 'PhabricatorBaseEnglishTranslation',

View file

@ -101,7 +101,11 @@ final class PhabricatorApplicationAuth extends PhabricatorApplication {
'/login/' => array( '/login/' => array(
'' => 'PhabricatorAuthStartController', '' => 'PhabricatorAuthStartController',
'email/' => 'PhabricatorEmailLoginController', 'email/' => 'PhabricatorEmailLoginController',
'etoken/(?P<token>\w+)/' => 'PhabricatorEmailTokenController', 'once/'.
'(?P<type>[^/]+)/'.
'(?P<id>\d+)/'.
'(?P<key>[^/]+)/'.
'(?:(?P<emailID>\d+)/)?' => 'PhabricatorAuthOneTimeLoginController',
'refresh/' => 'PhabricatorRefreshCSRFController', 'refresh/' => 'PhabricatorRefreshCSRFController',
'mustverify/' => 'PhabricatorMustVerifyEmailController', 'mustverify/' => 'PhabricatorMustVerifyEmailController',
), ),

View file

@ -49,6 +49,14 @@ final class PhabricatorCookies extends Phobject {
const COOKIE_NEXTURI = 'next_uri'; const COOKIE_NEXTURI = 'next_uri';
/**
* Stores a hint that the user should be moved directly into high security
* after upgrading a partial login session. This is used during password
* recovery to avoid a double-prompt.
*/
const COOKIE_HISEC = 'jump_to_hisec';
/* -( Client ID Cookie )--------------------------------------------------- */ /* -( Client ID Cookie )--------------------------------------------------- */
@ -125,7 +133,7 @@ final class PhabricatorCookies extends Phobject {
*/ */
public static function getNextURICookie(AphrontRequest $request) { public static function getNextURICookie(AphrontRequest $request) {
$cookie_value = $request->getCookie(self::COOKIE_NEXTURI); $cookie_value = $request->getCookie(self::COOKIE_NEXTURI);
list($set_at, $next_uri) = self::parseNExtURICookie($cookie_value); list($set_at, $next_uri) = self::parseNextURICookie($cookie_value);
return $next_uri; return $next_uri;
} }

View file

@ -24,11 +24,19 @@ final class PhabricatorAuthFinishController
$engine = new PhabricatorAuthSessionEngine(); $engine = new PhabricatorAuthSessionEngine();
// If this cookie is set, the user is headed into a high security area
// after login (normally because of a password reset) so if they are
// able to pass the checkpoint we just want to put their account directly
// into high security mode, rather than prompt them again for the same
// set of credentials.
$jump_into_hisec = $request->getCookie(PhabricatorCookies::COOKIE_HISEC);
try { try {
$token = $engine->requireHighSecuritySession( $token = $engine->requireHighSecuritySession(
$viewer, $viewer,
$request, $request,
'/logout/'); '/logout/',
$jump_into_hisec);
} catch (PhabricatorAuthHighSecurityRequiredException $ex) { } catch (PhabricatorAuthHighSecurityRequiredException $ex) {
$form = id(new PhabricatorAuthSessionEngine())->renderHighSecurityForm( $form = id(new PhabricatorAuthSessionEngine())->renderHighSecurityForm(
$ex->getFactors(), $ex->getFactors(),
@ -60,6 +68,7 @@ final class PhabricatorAuthFinishController
$next = PhabricatorCookies::getNextURICookie($request); $next = PhabricatorCookies::getNextURICookie($request);
$request->clearCookie(PhabricatorCookies::COOKIE_NEXTURI); $request->clearCookie(PhabricatorCookies::COOKIE_NEXTURI);
$request->clearCookie(PhabricatorCookies::COOKIE_HISEC);
if (!PhabricatorEnv::isValidLocalWebResource($next)) { if (!PhabricatorEnv::isValidLocalWebResource($next)) {
$next = '/'; $next = '/';

View file

@ -0,0 +1,199 @@
<?php
final class PhabricatorAuthOneTimeLoginController
extends PhabricatorAuthController {
private $id;
private $key;
private $emailID;
private $linkType;
public function shouldRequireLogin() {
return false;
}
public function willProcessRequest(array $data) {
$this->linkType = $data['type'];
$this->id = $data['id'];
$this->key = $data['key'];
$this->emailID = idx($data, 'emailID');
}
public function processRequest() {
$request = $this->getRequest();
if ($request->getUser()->isLoggedIn()) {
return $this->renderError(
pht('You are already logged in.'));
}
$target_user = id(new PhabricatorPeopleQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withIDs(array($this->id))
->executeOne();
if (!$target_user) {
return new Aphront404Response();
}
// NOTE: As a convenience to users, these one-time login URIs may also
// be associated with an email address which will be verified when the
// URI is used.
// This improves the new user experience for users receiving "Welcome"
// emails on installs that require verification: if we did not verify the
// email, they'd immediately get roadblocked with a "Verify Your Email"
// error and have to go back to their email account, wait for a
// "Verification" email, and then click that link to actually get access to
// their account. This is hugely unwieldy, and if the link was only sent
// to the user's email in the first place we can safely verify it as a
// side effect of login.
// The email hashed into the URI so users can't verify some email they
// do not own by doing this:
//
// - Add some address you do not own;
// - request a password reset;
// - change the URI in the email to the address you don't own;
// - login via the email link; and
// - get a "verified" address you don't control.
$target_email = null;
if ($this->emailID) {
$target_email = id(new PhabricatorUserEmail())->loadOneWhere(
'userPHID = %s AND id = %d',
$target_user->getPHID(),
$this->emailID);
if (!$target_email) {
return new Aphront404Response();
}
}
$engine = new PhabricatorAuthSessionEngine();
$token = $engine->loadOneTimeLoginKey(
$target_user,
$target_email,
$this->key);
if (!$token) {
return $this->newDialog()
->setTitle(pht('Unable to Login'))
->setShortTitle(pht('Login Failure'))
->appendParagraph(
pht(
'The login link you clicked is invalid, out of date, or has '.
'already been used.'))
->appendParagraph(
pht(
'Make sure you are copy-and-pasting the entire link into '.
'your browser. Login links are only valid for 24 hours, and '.
'can only be used once.'))
->appendParagraph(
pht('You can try again, or request a new link via email.'))
->addCancelButton('/login/email/', pht('Send Another Email'));
}
if ($request->isFormPost()) {
// If we have an email bound into this URI, verify email so that clicking
// the link in the "Welcome" email is good enough, without requiring users
// to go through a second round of email verification.
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
// Nuke the token so that this URI is one-time only.
$token->delete();
if ($target_email) {
$target_user->openTransaction();
$target_email->setIsVerified(1);
$target_email->save();
// If this was the user's primary email address, also mark their
// account as verified.
$primary_email = $target_user->loadPrimaryEmail();
if ($primary_email->getID() == $target_email->getID()) {
$target_user->setIsEmailVerified(1);
$target_user->save();
}
$target_user->saveTransaction();
}
unset($unguarded);
$next = '/';
if (!PhabricatorAuthProviderPassword::getPasswordProvider()) {
$next = '/settings/panel/external/';
} else if (PhabricatorEnv::getEnvConfig('account.editable')) {
// We're going to let the user reset their password without knowing
// the old one. Generate a one-time token for that.
$key = Filesystem::readRandomCharacters(16);
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
id(new PhabricatorAuthTemporaryToken())
->setObjectPHID($target_user->getPHID())
->setTokenType(
PhabricatorAuthSessionEngine::PASSWORD_TEMPORARY_TOKEN_TYPE)
->setTokenExpires(time() + phutil_units('1 hour in seconds'))
->setTokenCode(PhabricatorHash::digest($key))
->save();
unset($unguarded);
$next = (string)id(new PhutilURI('/settings/panel/password/'))
->setQueryParams(
array(
'key' => $key,
));
$request->setTemporaryCookie(PhabricatorCookies::COOKIE_HISEC, 'yes');
}
PhabricatorCookies::setNextURICookie($request, $next, $force = true);
return $this->loginUser($target_user);
}
// NOTE: We need to CSRF here so attackers can't generate an email link,
// then log a user in to an account they control via sneaky invisible
// form submissions.
switch ($this->linkType) {
case PhabricatorAuthSessionEngine::ONETIME_WELCOME:
$title = pht('Welcome to Phabricator');
break;
case PhabricatorAuthSessionEngine::ONETIME_RECOVER:
$title = pht('Account Recovery');
break;
case PhabricatorAuthSessionEngine::ONETIME_USERNAME:
case PhabricatorAuthSessionEngine::ONETIME_RESET:
default:
$title = pht('Login to Phabricator');
break;
}
$body = array();
$body[] = pht(
'Use the button below to log in as: %s',
phutil_tag('strong', array(), $target_user->getUsername()));
if ($target_email && !$target_email->getIsVerified()) {
$body[] = pht(
'Logging in will verify %s as an email address you own.',
phutil_tag('strong', array(), $target_email->getAddress()));
}
$body[] = pht(
'After logging in you should set a password for your account, or '.
'link your account to an external account that you can use to '.
'authenticate in the future.');
$dialog = $this->newDialog()
->setTitle($title)
->addSubmitButton(pht('Login (%s)', $target_user->getUsername()))
->addCancelButton('/');
foreach ($body as $paragraph) {
$dialog->appendParagraph($paragraph);
}
return id(new AphrontDialogResponse())->setDialog($dialog);
}
}

View file

@ -59,7 +59,12 @@ final class PhabricatorEmailLoginController
} }
if (!$errors) { if (!$errors) {
$uri = $target_user->getEmailLoginURI($target_email); $engine = new PhabricatorAuthSessionEngine();
$uri = $engine->getOneTimeLoginURI(
$target_user,
null,
PhabricatorAuthSessionEngine::ONETIME_RESET);
if ($is_serious) { if ($is_serious) {
$body = <<<EOBODY $body = <<<EOBODY
You can use this link to reset your Phabricator password: You can use this link to reset your Phabricator password:
@ -87,24 +92,18 @@ EOBODY;
// mail if they have the "don't send me email about my own actions" // mail if they have the "don't send me email about my own actions"
// preference set. // preference set.
$mail = new PhabricatorMetaMTAMail(); $mail = id(new PhabricatorMetaMTAMail())
$mail->setSubject('[Phabricator] Password Reset'); ->setSubject(pht('[Phabricator] Password Reset'))
$mail->addTos( ->addRawTos(array($target_email->getAddress()))
array( ->setBody($body)
$target_user->getPHID(), ->saveAndSend();
));
$mail->setBody($body);
$mail->saveAndSend();
$view = new AphrontRequestFailureView(); return $this->newDialog()
$view->setHeader(pht('Check Your Email')); ->setTitle(pht('Check Your Email'))
$view->appendChild(phutil_tag('p', array(), pht( ->setShortTitle(pht('Email Sent'))
'An email has been sent with a link you can use to login.'))); ->appendParagraph(
return $this->buildStandardPageResponse( pht('An email has been sent with a link you can use to login.'))
$view, ->addCancelButton('/', pht('Done'));
array(
'title' => pht('Email Sent'),
));
} }
} }

View file

@ -1,128 +0,0 @@
<?php
final class PhabricatorEmailTokenController
extends PhabricatorAuthController {
private $token;
public function shouldRequireLogin() {
return false;
}
public function willProcessRequest(array $data) {
$this->token = $data['token'];
}
public function processRequest() {
$request = $this->getRequest();
if ($request->getUser()->isLoggedIn()) {
return $this->renderError(
pht('You are already logged in.'));
}
$token = $this->token;
$email = $request->getStr('email');
$target_email = id(new PhabricatorUserEmail())->loadOneWhere(
'address = %s',
$email);
$target_user = null;
if ($target_email) {
$target_user = id(new PhabricatorUser())->loadOneWhere(
'phid = %s',
$target_email->getUserPHID());
}
// NOTE: We need to bind verification to **addresses**, not **users**,
// because we verify addresses when they're used to login this way, and if
// we have a user-based verification you can:
//
// - Add some address you do not own;
// - request a password reset;
// - change the URI in the email to the address you don't own;
// - login via the email link; and
// - get a "verified" address you don't control.
if (!$target_email ||
!$target_user ||
!$target_user->validateEmailToken($target_email, $token)) {
$view = new AphrontRequestFailureView();
$view->setHeader(pht('Unable to Login'));
$view->appendChild(phutil_tag('p', array(), pht(
'The authentication information in the link you clicked is '.
'invalid or out of date. Make sure you are copy-and-pasting the '.
'entire link into your browser. You can try again, or request '.
'a new email.')));
$view->appendChild(phutil_tag_div(
'aphront-failure-continue',
phutil_tag(
'a',
array('class' => 'button', 'href' => '/login/email/'),
pht('Send Another Email'))));
return $this->buildStandardPageResponse(
$view,
array(
'title' => pht('Login Failure'),
));
}
if ($request->isFormPost()) {
// Verify email so that clicking the link in the "Welcome" email is good
// enough, without requiring users to go through a second round of email
// verification.
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$target_email->setIsVerified(1);
$target_email->save();
unset($unguarded);
$next = '/';
if (!PhabricatorAuthProviderPassword::getPasswordProvider()) {
$next = '/settings/panel/external/';
} else if (PhabricatorEnv::getEnvConfig('account.editable')) {
$next = (string)id(new PhutilURI('/settings/panel/password/'))
->setQueryParams(
array(
'token' => $token,
'email' => $email,
));
}
PhabricatorCookies::setNextURICookie($request, $next, $force = true);
return $this->loginUser($target_user);
}
// NOTE: We need to CSRF here so attackers can't generate an email link,
// then log a user in to an account they control via sneaky invisible
// form submissions.
// TODO: Since users can arrive here either through password reset or
// through welcome emails, it might be nice to include the workflow type
// in the URI or query params so we can tailor the messaging. Right now,
// it has to be generic enough to make sense in either workflow, which
// leaves it feeling a little awkward.
$dialog = id(new AphrontDialogView())
->setUser($request->getUser())
->setTitle(pht('Login to Phabricator'))
->addHiddenInput('email', $email)
->appendParagraph(
pht(
'Use the button below to log in as: %s',
phutil_tag('strong', array(), $email)))
->appendParagraph(
pht(
'After logging in you should set a password for your account, or '.
'link your account to an external account that you can use to '.
'authenticate in the future.'))
->addSubmitButton(pht('Login (%s)', $email))
->addCancelButton('/');
return id(new AphrontDialogResponse())->setDialog($dialog);
}
}

View file

@ -6,6 +6,7 @@
* @task new Creating Sessions * @task new Creating Sessions
* @task hisec High Security * @task hisec High Security
* @task partial Partial Sessions * @task partial Partial Sessions
* @task onetime One Time Login URIs
*/ */
final class PhabricatorAuthSessionEngine extends Phobject { final class PhabricatorAuthSessionEngine extends Phobject {
@ -38,6 +39,23 @@ final class PhabricatorAuthSessionEngine extends Phobject {
const KIND_UNKNOWN = '?'; const KIND_UNKNOWN = '?';
/**
* Temporary tokens for one time logins.
*/
const ONETIME_TEMPORARY_TOKEN_TYPE = 'login:onetime';
/**
* Temporary tokens for password recovery after one time login.
*/
const PASSWORD_TEMPORARY_TOKEN_TYPE = 'login:password';
const ONETIME_RECOVER = 'recover';
const ONETIME_RESET = 'reset';
const ONETIME_WELCOME = 'welcome';
const ONETIME_USERNAME = 'rename';
/** /**
* Get the session kind (e.g., anonymous, user, external account) from a * Get the session kind (e.g., anonymous, user, external account) from a
* session token. Returns a `KIND_` constant. * session token. Returns a `KIND_` constant.
@ -245,13 +263,17 @@ final class PhabricatorAuthSessionEngine extends Phobject {
* @param PhabricatorUser User whose session needs to be in high security. * @param PhabricatorUser User whose session needs to be in high security.
* @param AphrontReqeust Current request. * @param AphrontReqeust Current request.
* @param string URI to return the user to if they cancel. * @param string URI to return the user to if they cancel.
* @param bool True to jump partial sessions directly into high
* security instead of just upgrading them to full
* sessions.
* @return PhabricatorAuthHighSecurityToken Security token. * @return PhabricatorAuthHighSecurityToken Security token.
* @task hisec * @task hisec
*/ */
public function requireHighSecuritySession( public function requireHighSecuritySession(
PhabricatorUser $viewer, PhabricatorUser $viewer,
AphrontRequest $request, AphrontRequest $request,
$cancel_uri) { $cancel_uri,
$jump_into_hisec = false) {
if (!$viewer->hasSession()) { if (!$viewer->hasSession()) {
throw new Exception( throw new Exception(
@ -320,9 +342,10 @@ final class PhabricatorAuthSessionEngine extends Phobject {
new PhabricatorAuthTryFactorAction(), new PhabricatorAuthTryFactorAction(),
-1); -1);
if ($session->getIsPartial()) { if ($session->getIsPartial() && !$jump_into_hisec) {
// If we have a partial session, just issue a token without // If we have a partial session and are not jumping directly into
// putting it in high security mode. // hisec, just issue a token without putting it in high security
// mode.
return $this->issueHighSecurityToken($session, true); return $this->issueHighSecurityToken($session, true);
} }
@ -459,6 +482,7 @@ final class PhabricatorAuthSessionEngine extends Phobject {
* @task partial * @task partial
*/ */
public function upgradePartialSession(PhabricatorUser $viewer) { public function upgradePartialSession(PhabricatorUser $viewer) {
if (!$viewer->hasSession()) { if (!$viewer->hasSession()) {
throw new Exception( throw new Exception(
pht('Upgrading partial session of user with no session!')); pht('Upgrading partial session of user with no session!'));
@ -486,7 +510,112 @@ final class PhabricatorAuthSessionEngine extends Phobject {
PhabricatorUserLog::ACTION_LOGIN_FULL); PhabricatorUserLog::ACTION_LOGIN_FULL);
$log->save(); $log->save();
unset($unguarded); unset($unguarded);
}
/* -( One Time Login URIs )------------------------------------------------ */
/**
* Retrieve a temporary, one-time URI which can log in to an account.
*
* These URIs are used for password recovery and to regain access to accounts
* which users have been locked out of.
*
* @param PhabricatorUser User to generate a URI for.
* @param PhabricatorUserEmail Optionally, email to verify when
* link is used.
* @param string Optional context string for the URI. This is purely cosmetic
* and used only to customize workflow and error messages.
* @return string Login URI.
* @task onetime
*/
public function getOneTimeLoginURI(
PhabricatorUser $user,
PhabricatorUserEmail $email = null,
$type = self::ONETIME_RESET) {
$key = Filesystem::readRandomCharacters(32);
$key_hash = $this->getOneTimeLoginKeyHash($user, $email, $key);
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
id(new PhabricatorAuthTemporaryToken())
->setObjectPHID($user->getPHID())
->setTokenType(self::ONETIME_TEMPORARY_TOKEN_TYPE)
->setTokenExpires(time() + phutil_units('1 day in seconds'))
->setTokenCode($key_hash)
->save();
unset($unguarded);
$uri = '/login/once/'.$type.'/'.$user->getID().'/'.$key.'/';
if ($email) {
$uri = $uri.$email->getID().'/';
}
try {
$uri = PhabricatorEnv::getProductionURI($uri);
} catch (Exception $ex) {
// If a user runs `bin/auth recover` before configuring the base URI,
// just show the path. We don't have any way to figure out the domain.
// See T4132.
}
return $uri;
}
/**
* Load the temporary token associated with a given one-time login key.
*
* @param PhabricatorUser User to load the token for.
* @param PhabricatorUserEmail Optionally, email to verify when
* link is used.
* @param string Key user is presenting as a valid one-time login key.
* @return PhabricatorAuthTemporaryToken|null Token, if one exists.
* @task onetime
*/
public function loadOneTimeLoginKey(
PhabricatorUser $user,
PhabricatorUserEmail $email = null,
$key = null) {
$key_hash = $this->getOneTimeLoginKeyHash($user, $email, $key);
return id(new PhabricatorAuthTemporaryTokenQuery())
->setViewer($user)
->withObjectPHIDs(array($user->getPHID()))
->withTokenTypes(array(self::ONETIME_TEMPORARY_TOKEN_TYPE))
->withTokenCodes(array($key_hash))
->withExpired(false)
->executeOne();
}
/**
* Hash a one-time login key for storage as a temporary token.
*
* @param PhabricatorUser User this key is for.
* @param PhabricatorUserEmail Optionally, email to verify when
* link is used.
* @param string The one time login key.
* @return string Hash of the key.
* task onetime
*/
private function getOneTimeLoginKeyHash(
PhabricatorUser $user,
PhabricatorUserEmail $email = null,
$key = null) {
$parts = array(
$key,
$user->getAccountSecret(),
);
if ($email) {
$parts[] = $email->getVerificationCode();
}
return PhabricatorHash::digest(implode(':', $parts));
} }
} }

View file

@ -69,6 +69,12 @@ final class PhabricatorAuthManagementRecoverWorkflow
$can_recover)); $can_recover));
} }
$engine = new PhabricatorAuthSessionEngine();
$onetime_uri = $engine->getOneTimeLoginURI(
$user,
null,
PhabricatorAuthSessionEngine::ONETIME_RECOVER);
$console = PhutilConsole::getConsole(); $console = PhutilConsole::getConsole();
$console->writeOut( $console->writeOut(
pht( pht(
@ -76,7 +82,7 @@ final class PhabricatorAuthManagementRecoverWorkflow
'interface:', 'interface:',
$username)); $username));
$console->writeOut("\n\n"); $console->writeOut("\n\n");
$console->writeOut(" %s", $user->getEmailLoginURI()); $console->writeOut(' %s', $onetime_uri);
$console->writeOut("\n\n"); $console->writeOut("\n\n");
$console->writeOut( $console->writeOut(
pht( pht(

View file

@ -342,60 +342,6 @@ final class PhabricatorUser
return substr(PhabricatorHash::digest($vec), 0, $len); return substr(PhabricatorHash::digest($vec), 0, $len);
} }
private function generateEmailToken(
PhabricatorUserEmail $email,
$offset = 0) {
$key = implode(
'-',
array(
PhabricatorEnv::getEnvConfig('phabricator.csrf-key'),
$this->getPHID(),
$email->getVerificationCode(),
));
return $this->generateToken(
time() + ($offset * self::EMAIL_CYCLE_FREQUENCY),
self::EMAIL_CYCLE_FREQUENCY,
$key,
self::EMAIL_TOKEN_LENGTH);
}
public function validateEmailToken(
PhabricatorUserEmail $email,
$token) {
for ($ii = -1; $ii <= 1; $ii++) {
$valid = $this->generateEmailToken($email, $ii);
if ($token == $valid) {
return true;
}
}
return false;
}
public function getEmailLoginURI(PhabricatorUserEmail $email = null) {
if (!$email) {
$email = $this->loadPrimaryEmail();
if (!$email) {
throw new Exception("User has no primary email!");
}
}
$token = $this->generateEmailToken($email);
$uri = '/login/etoken/'.$token.'/';
try {
$uri = PhabricatorEnv::getProductionURI($uri);
} catch (Exception $ex) {
// If a user runs `bin/auth recover` before configuring the base URI,
// just show the path. We don't have any way to figure out the domain.
// See T4132.
}
$uri = new PhutilURI($uri);
return $uri->alter('email', $email->getAddress());
}
public function attachUserProfile(PhabricatorUserProfile $profile) { public function attachUserProfile(PhabricatorUserProfile $profile) {
$this->profile = $profile; $this->profile = $profile;
return $this; return $this;
@ -567,7 +513,12 @@ final class PhabricatorUser
$base_uri = PhabricatorEnv::getProductionURI('/'); $base_uri = PhabricatorEnv::getProductionURI('/');
$uri = $this->getEmailLoginURI(); $engine = new PhabricatorAuthSessionEngine();
$uri = $engine->getOneTimeLoginURI(
$this,
$this->loadPrimaryEmail(),
PhabricatorAuthSessionEngine::ONETIME_WELCOME);
$body = <<<EOBODY $body = <<<EOBODY
Welcome to Phabricator! Welcome to Phabricator!
@ -611,7 +562,11 @@ EOBODY;
$password_instructions = null; $password_instructions = null;
if (PhabricatorAuthProviderPassword::getPasswordProvider()) { if (PhabricatorAuthProviderPassword::getPasswordProvider()) {
$uri = $this->getEmailLoginURI(); $engine = new PhabricatorAuthSessionEngine();
$uri = $engine->getOneTimeLoginURI(
$this,
null,
PhabricatorAuthSessionEngine::ONETIME_USERNAME);
$password_instructions = <<<EOTXT $password_instructions = <<<EOTXT
If you use a password to login, you'll need to reset it before you can login If you use a password to login, you'll need to reset it before you can login
again. You can reset your password by following this link: again. You can reset your password by following this link:

View file

@ -47,17 +47,17 @@ final class PhabricatorSettingsPanelPassword
// either by providing the old password or by carrying a token to // either by providing the old password or by carrying a token to
// the workflow from a password reset email. // the workflow from a password reset email.
$token = $request->getStr('token'); $key = $request->getStr('key');
$token = null;
$valid_token = false; if ($key) {
if ($token) { $token = id(new PhabricatorAuthTemporaryTokenQuery())
$email_address = $request->getStr('email'); ->setViewer($user)
$email = id(new PhabricatorUserEmail())->loadOneWhere( ->withObjectPHIDs(array($user->getPHID()))
'address = %s', ->withTokenTypes(
$email_address); array(PhabricatorAuthSessionEngine::PASSWORD_TEMPORARY_TOKEN_TYPE))
if ($email) { ->withTokenCodes(array(PhabricatorHash::digest($key)))
$valid_token = $user->validateEmailToken($email, $token); ->withExpired(false)
} ->executeOne();
} }
$e_old = true; $e_old = true;
@ -66,7 +66,7 @@ final class PhabricatorSettingsPanelPassword
$errors = array(); $errors = array();
if ($request->isFormPost()) { if ($request->isFormPost()) {
if (!$valid_token) { if (!$token) {
$envelope = new PhutilOpaqueEnvelope($request->getStr('old_pw')); $envelope = new PhutilOpaqueEnvelope($request->getStr('old_pw'));
if (!$user->comparePassword($envelope)) { if (!$user->comparePassword($envelope)) {
$errors[] = pht('The old password you entered is incorrect.'); $errors[] = pht('The old password you entered is incorrect.');
@ -105,7 +105,10 @@ final class PhabricatorSettingsPanelPassword
unset($unguarded); unset($unguarded);
if ($valid_token) { if ($token) {
// Destroy the token.
$token->delete();
// If this is a password set/reset, kick the user to the home page // If this is a password set/reset, kick the user to the home page
// after we update their account. // after we update their account.
$next = '/'; $next = '/';
@ -135,9 +138,9 @@ final class PhabricatorSettingsPanelPassword
$form = new AphrontFormView(); $form = new AphrontFormView();
$form $form
->setUser($user) ->setUser($user)
->addHiddenInput('token', $token); ->addHiddenInput('key', $key);
if (!$valid_token) { if (!$token) {
$form->appendChild( $form->appendChild(
id(new AphrontFormPasswordControl()) id(new AphrontFormPasswordControl())
->setLabel(pht('Old Password')) ->setLabel(pht('Old Password'))