diff --git a/config.inc.php b/config.inc.php index 7e404a91..762c33c2 100644 --- a/config.inc.php +++ b/config.inc.php @@ -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'; diff --git a/functions.inc.php b/functions.inc.php index c69f1969..413277b5 100644 --- a/functions.inc.php +++ b/functions.inc.php @@ -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: */ diff --git a/model/Login.php b/model/Login.php index 97575cfb..cdc2687c 100644 --- a/model/Login.php +++ b/model/Login.php @@ -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; } diff --git a/public/users/password-recover.php b/public/users/password-recover.php index dc73693b..ab0c0680 100644 --- a/public/users/password-recover.php +++ b/public/users/password-recover.php @@ -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); } diff --git a/tests/GetSiteUrlTest.php b/tests/GetSiteUrlTest.php index bb994eb8..3c8a531d 100644 --- a/tests/GetSiteUrlTest.php +++ b/tests/GetSiteUrlTest.php @@ -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(); + } } diff --git a/tests/LoginTest.php b/tests/LoginTest.php index 7d3d5cdf..6f52c57e 100644 --- a/tests/LoginTest.php +++ b/tests/LoginTest.php @@ -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); } } diff --git a/tests/PasswordRecoveryResponseTest.php b/tests/PasswordRecoveryResponseTest.php new file mode 100644 index 00000000..5aa30e26 --- /dev/null +++ b/tests/PasswordRecoveryResponseTest.php @@ -0,0 +1,14 @@ +assertStringNotContainsString('Location: password-change.php?username=', $controller); + $this->assertStringContainsString("flash_info(Config::Lang('pPassword_recovery_processed'))", $controller); + } +}