1
0
Fork 0
mirror of https://we.phorge.it/source/phorge.git synced 2024-12-18 11:30:55 +01:00

Add "temporary tokens" to auth, for SMS codes, TOTP codes, reset codes, etc

Summary:
Ref T4398. We have several auth-related systems which require (or are improved by) the ability to hand out one-time codes which expire after a short period of time.

In particular, these are:

  - SMS multi-factor: we need to be able to hand out one-time codes for this in order to prove the user has the phone.
  - Password reset emails: we use a time-based rotating token right now, but we could improve this with a one-time token, so once you reset your password the link is dead.
  - TOTP auth: we don't need to verify/invalidate keys, but can improve security by doing so.

This adds a generic one-time code storage table, and strengthens the TOTP enrollment process by using it. Specifically, you can no longer edit the enrollment form (the one with a QR code) to force your own key as the TOTP key: only keys Phabricator generated are accepted. This has no practical security impact, but generally helps raise the barrier potential attackers face.

Followup changes will use this for reset emails, then implement SMS multi-factor.

Test Plan:
  - Enrolled in TOTP multi-factor auth.
  - Submitted an error in the form, saw the same key presented.
  - Edited the form with web tools to provide a different key, saw it reject and the server generate an alternate.
  - Change the expiration to 5 seconds instead of 1 hour, submitted the form over and over again, saw it cycle the key after 5 seconds.
  - Looked at the database and saw the tokens I expected.
  - Ran the GC and saw all the 5-second expiry tokens get cleaned up.

Reviewers: btrahan

Reviewed By: btrahan

Subscribers: epriestley

Maniphest Tasks: T4398

Differential Revision: https://secure.phabricator.com/D9217
This commit is contained in:
epriestley 2014-05-20 11:43:45 -07:00
parent f0147fd8ad
commit cac61980f9
6 changed files with 222 additions and 5 deletions

View file

@ -0,0 +1,11 @@
CREATE TABLE {$NAMESPACE}_auth.auth_temporarytoken (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
objectPHID VARCHAR(64) NOT NULL COLLATE utf8_bin,
tokenType VARCHAR(64) NOT NULL COLLATE utf8_bin,
tokenExpires INT UNSIGNED NOT NULL,
tokenCode VARCHAR(64) NOT NULL COLLATE utf8_bin,
UNIQUE KEY `key_token` (objectPHID, tokenType, tokenCode),
KEY `key_expires` (tokenExpires)
) ENGINE=InnoDB, COLLATE utf8_general_ci;

View file

@ -1279,6 +1279,9 @@ phutil_register_library_map(array(
'PhabricatorAuthSessionGarbageCollector' => 'applications/auth/garbagecollector/PhabricatorAuthSessionGarbageCollector.php',
'PhabricatorAuthSessionQuery' => 'applications/auth/query/PhabricatorAuthSessionQuery.php',
'PhabricatorAuthStartController' => 'applications/auth/controller/PhabricatorAuthStartController.php',
'PhabricatorAuthTemporaryToken' => 'applications/auth/storage/PhabricatorAuthTemporaryToken.php',
'PhabricatorAuthTemporaryTokenGarbageCollector' => 'applications/auth/garbagecollector/PhabricatorAuthTemporaryTokenGarbageCollector.php',
'PhabricatorAuthTemporaryTokenQuery' => 'applications/auth/query/PhabricatorAuthTemporaryTokenQuery.php',
'PhabricatorAuthTerminateSessionController' => 'applications/auth/controller/PhabricatorAuthTerminateSessionController.php',
'PhabricatorAuthTryFactorAction' => 'applications/auth/action/PhabricatorAuthTryFactorAction.php',
'PhabricatorAuthUnlinkController' => 'applications/auth/controller/PhabricatorAuthUnlinkController.php',
@ -4045,6 +4048,13 @@ phutil_register_library_map(array(
'PhabricatorAuthSessionGarbageCollector' => 'PhabricatorGarbageCollector',
'PhabricatorAuthSessionQuery' => 'PhabricatorCursorPagedPolicyAwareQuery',
'PhabricatorAuthStartController' => 'PhabricatorAuthController',
'PhabricatorAuthTemporaryToken' =>
array(
0 => 'PhabricatorAuthDAO',
1 => 'PhabricatorPolicyInterface',
),
'PhabricatorAuthTemporaryTokenGarbageCollector' => 'PhabricatorGarbageCollector',
'PhabricatorAuthTemporaryTokenQuery' => 'PhabricatorCursorPagedPolicyAwareQuery',
'PhabricatorAuthTerminateSessionController' => 'PhabricatorAuthController',
'PhabricatorAuthTryFactorAction' => 'PhabricatorSystemAction',
'PhabricatorAuthUnlinkController' => 'PhabricatorAuthController',

View file

@ -2,6 +2,8 @@
final class PhabricatorAuthFactorTOTP extends PhabricatorAuthFactor {
const TEMPORARY_TOKEN_TYPE = 'mfa:totp:key';
public function getFactorKey() {
return 'totp';
}
@ -23,13 +25,42 @@ final class PhabricatorAuthFactorTOTP extends PhabricatorAuthFactor {
PhabricatorUser $user) {
$key = $request->getStr('totpkey');
if (strlen($key)) {
// If the user is providing a key, make sure it's a key we generated.
// This raises the barrier to theoretical attacks where an attacker might
// provide a known key (such attacks are already prevented by CSRF, but
// this is a second barrier to overcome).
// (We store and verify the hash of the key, not the key itself, to limit
// how useful the data in the table is to an attacker.)
$temporary_token = id(new PhabricatorAuthTemporaryTokenQuery())
->setViewer($user)
->withObjectPHIDs(array($user->getPHID()))
->withTokenTypes(array(self::TEMPORARY_TOKEN_TYPE))
->withExpired(false)
->withTokenCodes(array(PhabricatorHash::digest($key)))
->executeOne();
if (!$temporary_token) {
// If we don't have a matching token, regenerate the key below.
$key = null;
}
}
if (!strlen($key)) {
// TODO: When the user submits a key, we should require that it be
// one we generated for them, so there's no way an attacker can ever
// force a key they control onto an account. However, it's clumsy to
// do this right now. Once we have one-time tokens for SMS and email,
// we should be able to put it on that infrastructure.
$key = self::generateNewTOTPKey();
// Mark this key as one we generated, so the user is allowed to submit
// a response for it.
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
id(new PhabricatorAuthTemporaryToken())
->setObjectPHID($user->getPHID())
->setTokenType(self::TEMPORARY_TOKEN_TYPE)
->setTokenExpires(time() + phutil_units('1 hour in seconds'))
->setTokenCode(PhabricatorHash::digest($key))
->save();
unset($unguarded);
}
$code = $request->getStr('totpcode');

View file

@ -0,0 +1,18 @@
<?php
final class PhabricatorAuthTemporaryTokenGarbageCollector
extends PhabricatorGarbageCollector {
public function collectGarbage() {
$session_table = new PhabricatorAuthTemporaryToken();
$conn_w = $session_table->establishConnection('w');
queryfx(
$conn_w,
'DELETE FROM %T WHERE tokenExpires <= UNIX_TIMESTAMP() LIMIT 100',
$session_table->getTableName());
return ($conn_w->getAffectedRows() == 100);
}
}

View file

@ -0,0 +1,106 @@
<?php
final class PhabricatorAuthTemporaryTokenQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $objectPHIDs;
private $tokenTypes;
private $expired;
private $tokenCodes;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withObjectPHIDs(array $object_phids) {
$this->objectPHIDs = $object_phids;
return $this;
}
public function withTokenTypes(array $types) {
$this->tokenTypes = $types;
return $this;
}
public function withExpired($expired) {
$this->expired = $expired;
return $this;
}
public function withTokenCodes(array $codes) {
$this->tokenCodes = $codes;
return $this;
}
protected function loadPage() {
$table = new PhabricatorAuthTemporaryToken();
$conn_r = $table->establishConnection('r');
$data = queryfx_all(
$conn_r,
'SELECT * FROM %T %Q %Q %Q',
$table->getTableName(),
$this->buildWhereClause($conn_r),
$this->buildOrderClause($conn_r),
$this->buildLimitClause($conn_r));
return $table->loadAllFromArray($data);
}
protected function buildWhereClause(AphrontDatabaseConnection $conn_r) {
$where = array();
if ($this->ids !== null) {
$where[] = qsprintf(
$conn_r,
'id IN (%Ld)',
$this->ids);
}
if ($this->objectPHIDs !== null) {
$where[] = qsprintf(
$conn_r,
'objectPHID IN (%Ls)',
$this->objectPHIDs);
}
if ($this->tokenTypes !== null) {
$where[] = qsprintf(
$conn_r,
'tokenType IN (%Ls)',
$this->tokenTypes);
}
if ($this->expired !== null) {
if ($this->expired) {
$where[] = qsprintf(
$conn_r,
'tokenExpires <= %d',
time());
} else {
$where[] = qsprintf(
$conn_r,
'tokenExpires > %d',
time());
}
}
if ($this->tokenCodes !== null) {
$where[] = qsprintf(
$conn_r,
'tokenCode IN (%Ls)',
$this->tokenCodes);
}
$where[] = $this->buildPagingClause($conn_r);
return $this->formatWhereClause($where);
}
public function getQueryApplicationClass() {
return 'PhabricatorApplicationAuth';
}
}

View file

@ -0,0 +1,41 @@
<?php
final class PhabricatorAuthTemporaryToken extends PhabricatorAuthDAO
implements PhabricatorPolicyInterface {
protected $objectPHID;
protected $tokenType;
protected $tokenExpires;
protected $tokenCode;
public function getConfiguration() {
return array(
self::CONFIG_TIMESTAMPS => false,
) + parent::getConfiguration();
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
// We're just implement this interface to get access to the standard
// query infrastructure.
return PhabricatorPolicies::getMostOpenPolicy();
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
public function describeAutomaticCapability($capability) {
return null;
}
}