Harden password recovery requests (#1130)

Require a validated canonical site_url for recovery links, keep responses uniform, and persist a five-minute per-account request limit.

The token update is atomic across supported database engines and performs the same password hashing work for unknown accounts.

Refs #1128

thanks @TrapoSAMA
This commit is contained in:
Rodrigo Cortés Cano authored and GitHub committed 2026-08-29 14:55:49 +01:00
1 parent 314a3242c9
commit e638095d58
7 files changed
+109 -26

No files matched your search

+3 -2
View File
@@ -798,8 +798,9 @@ $CONF['xmlrpc_enabled'] = false;
//More details in Password_Expiration.md
$CONF['password_expiration'] = 'NO';
// If defined, use this rather than trying to construct it from $_SERVER parameters.
// used in (at least) password-recover.php.
// Canonical public URL for PostfixAdmin, including its path and a trailing slash.
// This must be configured when email-based password recovery is enabled because
// recovery links must not be constructed from untrusted HTTP request headers.
$CONF['site_url'] = null;
$CONF['version'] = '4.0.1';
+24
View File
@@ -2483,4 +2483,28 @@ function getSiteUrl(array $server = []): string
return $https . '://' . $server['HTTP_HOST'] . $uri;
}
/**
* Return the configured canonical URL used in password-recovery messages.
*
* Request headers are deliberately not used here because recovery links carry
* a credential and must not depend on an untrusted Host value.
*/
function getPasswordRecoverySiteUrl(): string
{
$url = Config::read_string('site_url');
$parts = parse_url($url);
if ($url === '' || !is_array($parts) || empty($parts['host']) ||
!isset($parts['scheme']) || !in_array(strtolower($parts['scheme']), ['http', 'https'], true) ||
isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])) {
throw new RuntimeException("A valid canonical site_url is required for password recovery");
}
if (!str_ends_with($url, '/')) {
$url .= '/';
}
return $url;
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
+17 -17
View File
@@ -60,27 +60,27 @@ class Login
*/
public function generatePasswordRecoveryCode(string $username)
{
$sql = "SELECT count(1) FROM {$this->key_table} WHERE username = :username AND active = :active";
$token = generate_password();
$token_hash = pacrypt($token);
$token_validity = date('Y-m-d H:i:s', strtotime('+1 hour'));
$cooldown = date('Y-m-d H:i:s', strtotime('+55 minutes'));
$now = db_sqlite() ? "datetime('now')" : 'now()';
$active = true;
$sql = "UPDATE {$this->key_table}
SET token = :token, token_validity = :token_validity, modified = $now
WHERE username = :username AND active = :active
AND (token IS NULL OR token = '' OR token_validity <= :cooldown)";
$values = [
$updatedRows = db_execute($sql, [
'token' => $token_hash,
'token_validity' => $token_validity,
'username' => $username,
'active' => $active,
];
'active' => true,
'cooldown' => $cooldown,
]);
$result = db_query_one($sql, $values);
if ($result) {
$token = generate_password();
$updatedRows = db_update($this->table, 'username', $username, array(
'token' => pacrypt($token),
'token_validity' => date("Y-m-d H:i:s", strtotime('+ 1 hour')),
));
if ($updatedRows == 1) {
return $token;
}
if ($updatedRows == 1) {
return $token;
}
return false;
}
+8 -7
View File
@@ -46,7 +46,12 @@ if ($context === 'admin' && !Config::read('forgotten_admin_password_reset') ||
function sendCodebyEmail($to, $username, $code)
{
$url = getSiteUrl($_SERVER) . 'password-change.php?username=' . urlencode($username) . '&code=' . $code;
try {
$url = getPasswordRecoverySiteUrl() . 'password-change.php?username=' . urlencode($username) . '&code=' . $code;
} catch (RuntimeException $e) {
error_log(__FILE__ . ' - ' . $e->getMessage());
return false;
}
return smtp_mail(
$to,
@@ -97,19 +102,15 @@ if ($_SERVER['REQUEST_METHOD'] === "POST") {
error_log(__FILE__ . " - No mechanism configured for password-recovery.");
}
if ($email_other || $phone) {
header("Location: password-change.php?username=" . urlencode($username));
exit(0);
}
}
// throttle password reset requests to prevent brute force attack
$elapsed_time = (int)(microtime(true) - $start_time);
$elapsed_time = microtime(true) - $start_time;
// we try to make sure the entire operation takes 2s
if ($elapsed_time < 2.0) {
// php 7.4+ should support underscores in numeric literals
$sleep = 2_000_000 - ($elapsed_time * 1_000_000);
$sleep = (int)((2.0 - $elapsed_time) * 1_000_000.0);
if ($sleep > 0) {
usleep($sleep);
}
+29
View File
@@ -56,4 +56,33 @@ class GetSiteUrlTest extends \PHPUnit\Framework\TestCase
$this->assertEquals('http://example.org/', getSiteUrl($server));
}
public function testPasswordRecoveryRequiresCanonicalUrl(): void
{
$config = Config::getInstance()->getAll();
$config['site_url'] = null;
Config::getInstance()->setAll($config);
$this->expectException(RuntimeException::class);
getPasswordRecoverySiteUrl();
}
public function testPasswordRecoveryUsesConfiguredUrlOnly(): void
{
$config = Config::getInstance()->getAll();
$config['site_url'] = 'https://example.com/postfixadmin';
Config::getInstance()->setAll($config);
$this->assertSame('https://example.com/postfixadmin/', getPasswordRecoverySiteUrl());
}
public function testPasswordRecoveryRejectsUrlCredentials(): void
{
$config = Config::getInstance()->getAll();
$config['site_url'] = 'https://user:password@example.com/postfixadmin/';
Config::getInstance()->setAll($config);
$this->expectException(RuntimeException::class);
getPasswordRecoverySiteUrl();
}
}
+14
View File
@@ -267,5 +267,19 @@ class LoginTest extends \PHPUnit\Framework\TestCase
$this->assertNotNull($row);
$this->assertNotEmpty($row['token']);
$this->assertNotEmpty($row['token_validity']);
$this->assertFalse($login->generatePasswordRecoveryCode('test@example.com'));
db_execute(
"UPDATE " . table_by_key('mailbox') . " SET token_validity = :validity WHERE username = :username",
[
'validity' => date('Y-m-d H:i:s', strtotime('+54 minutes')),
'username' => 'test@example.com',
]
);
$replacement = $login->generatePasswordRecoveryCode('test@example.com');
$this->assertIsString($replacement);
$this->assertNotSame($token, $replacement);
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
use PHPUnit\Framework\TestCase;
class PasswordRecoveryResponseTest extends TestCase
{
public function testRecoveryRequestDoesNotRevealDeliveryAvailability(): void
{
$controller = file_get_contents(__DIR__ . '/../public/users/password-recover.php');
$this->assertStringNotContainsString('Location: password-change.php?username=', $controller);
$this->assertStringContainsString("flash_info(Config::Lang('pPassword_recovery_processed'))", $controller);
}
}