From ae85e51f6ed9deae15c8f850a3a3e2f11317a51c Mon Sep 17 00:00:00 2001 From: David Goodwin Date: Sat, 17 Oct 2026 09:27:59 +0100 Subject: [PATCH] Security fixes (master only) (#1165) Someone wishing to remain anonymous emailed @cboltz a number of security issues, summarised below. 1. fix sql injection bug in getPageBrowser - search keys bypass the field filter, due to 2a6f27c3 / #1127 2. when performing a password change, do not start the session before the new password has been validated for compexity etc - as things stand someone with a recovery code gets logged in even if their password gets rejected. Also invalid recovery code on failure. 3. broadcast-message.php was using smtp_mail() with incorrect args, and passing the SMTP password in as the mail body. - probably related to commit 7f1d78e and 42a664e9c29e66cc1a13c7f2037433d1f935aff9 4. a regular (non-admin) user could submit an arbitrary username in the POST data and create/edit a TOTP exception for another user or entire domain PR includes refactoring of the password change code (into PasswordChangeAttempt) to make it easier to test/verify. --- functions.inc.php | 67 ++++++-- model/MailboxHandler.php | 2 +- model/PFAHandler.php | 54 +++++-- model/PasswordChangeAttempt.php | 52 ++++++ model/TotpexceptionHandler.php | 12 +- public/broadcast-message.php | 4 +- public/edit.php | 4 + public/sendmail.php | 2 +- public/users/password-change.php | 48 ++---- public/users/password-recover.php | 8 +- tests/AliasHandlerTest.php | 43 +++++ tests/BuildSelectQueryTest.php | 238 ++++++++++++++++++++++++++++ tests/MailboxHandlerTest.php | 68 ++++++++ tests/PasswordChangeAttemptTest.php | 121 ++++++++++++++ tests/SmtpTest.php | 31 ++++ tests/TotpexceptionHandlerTest.php | 171 ++++++++++++++++++++ 16 files changed, 851 insertions(+), 74 deletions(-) create mode 100644 model/PasswordChangeAttempt.php create mode 100644 tests/BuildSelectQueryTest.php create mode 100644 tests/PasswordChangeAttemptTest.php create mode 100644 tests/TotpexceptionHandlerTest.php diff --git a/functions.inc.php b/functions.inc.php index 4f898dab..20cf188c 100644 --- a/functions.inc.php +++ b/functions.inc.php @@ -23,6 +23,27 @@ function authentication_mfa_incomplete(): bool return false; } +/** + * Returns the current user's login, if there is one - but unlike authentication_get_username() + * never redirects/exits. Use this where not being logged in is legitimate (e.g. db_log() during + * a password reset via recovery code). + * + * @return string|null username (e.g. foo@example.com), CLI, SETUP.PHP or null if nobody is logged in + */ +function authentication_get_username_if_known(): ?string +{ + if (defined('POSTFIXADMIN_CLI')) { + return 'CLI'; + } + + if (defined('POSTFIXADMIN_SETUP')) { + return 'SETUP.PHP'; + } + + $username = $_SESSION['sessid']['username'] ?? null; + return is_string($username) && $username !== '' ? $username : null; +} + /** * Action: Check if a session already exists, if not redirect to login.php. Returns current user's login. * @@ -1373,6 +1394,12 @@ function smtp_mail(string $to, string $from, string $subject_or_data, ?string $b $password = $CONF['admin_smtp_password'] ?? ''; $type = $CONF['smtp_type'] ?? 'starttls'; + // $to / $from end up in SMTP commands and headers - a CR or LF would allow injecting further commands/headers. + if (preg_match('/[\r\n]/', $to . $from)) { + error_log('smtp_mail(): refusing to send, to/from address contains a line break'); + return false; + } + // Building of SMTP payload if ($body === null) { // RAW MOD for Broadcast (broadcast-message.php) @@ -1382,7 +1409,7 @@ function smtp_mail(string $to, string $from, string $subject_or_data, ?string $b $maildata = "To: $to\r\n" . "From: $from\r\n" . - "Subject: " . encode_header($subject_or_data) . "\r\n" . + "Subject: " . encode_header(str_replace(["\r", "\n"], ' ', $subject_or_data)) . "\r\n" . "MIME-Version: 1.0\r\n" . "Date: " . date('r') . "\r\n" . "Content-Type: text/plain; charset=utf-8\r\n" . @@ -1442,7 +1469,7 @@ function smtp_mail(string $to, string $from, string $subject_or_data, ?string $b smtp_write($socket, "DATA\r\n"); smtp_require_response($socket, 354); - smtp_write($socket, $maildata . "\r\n.\r\n"); + smtp_write($socket, smtp_dot_stuff($maildata) . "\r\n.\r\n"); smtp_require_response($socket, 250); smtp_write($socket, "QUIT\r\n"); @@ -1481,6 +1508,27 @@ function smtp_require_response($socket, int $code): void } } +/** + * Prepare message data for the SMTP DATA phase (RFC 5321 section 4.5.2). + * + * Normalises all line endings to CRLF (so a bare CR or LF can't be used to smuggle an + * end-of-data sequence past us, but be interpreted as one by the server) and doubles a + * leading '.' on every line, so a line consisting of a single '.' in the body can't end + * DATA early and allow the caller to send their own SMTP commands. + * + * @param string $data message headers + body + * @return string + */ +function smtp_dot_stuff(string $data): string +{ + $data = preg_replace('/\r\n|\r|\n/', "\r\n", $data); + $data = preg_replace('/^\./m', '..', $data); + if (!is_string($data)) { + throw new \InvalidArgumentException("data passed into smtp_dot_stuff was invalid"); + } + return $data; +} + function smtp_write($socket, string $data): void { $remaining = $data; @@ -1521,17 +1569,6 @@ function smtp_get_admin_email(bool $fallback_to_loggedin_user = true) return "PasswordReset "; // this isn't good. } -/** - * smtp_get_admin_password - * Action: Get smtp password for admin email - * Call: smtp_get_admin_password - * @return string - admin smtp password - */ -function smtp_get_admin_password() -{ - return Config::read_string('admin_smtp_password'); -} - // // smtp_get_response @@ -2082,7 +2119,9 @@ function db_log(string $domain, string $action, string $data): bool $REMOTE_ADDR = getRemoteAddr(); - $username = authentication_get_username(); + // must not redirect to login.php - db_log() is also reached without a session, e.g. when + // resetting a forgotten password via password-change.php + $username = authentication_get_username_if_known() ?? 'unauthenticated'; if (Config::Lang("pViewlog_action_$action") == '') { throw new Exception("Invalid log action : $action"); // could do with something better? diff --git a/model/MailboxHandler.php b/model/MailboxHandler.php index d6fbf579..786c0660 100644 --- a/model/MailboxHandler.php +++ b/model/MailboxHandler.php @@ -557,7 +557,7 @@ class MailboxHandler extends PFAHandler $fSubject = Config::lang('pSendmail_subject_text'); $fBody = Config::read('welcome_text'); - if (!smtp_mail($fTo, $fFrom, $fSubject, $fBody)) { + if (!smtp_mail(to: $fTo, from: $fFrom, subject_or_data: $fSubject, body: $fBody)) { $this->errormsg[] = Config::lang_f('pSendmail_result_error', $this->id); return false; } diff --git a/model/PFAHandler.php b/model/PFAHandler.php index 82f0e6d9..5623b1ba 100644 --- a/model/PFAHandler.php +++ b/model/PFAHandler.php @@ -654,13 +654,13 @@ abstract class PFAHandler * helper function to build the inner part of the select query * can be used by read_from_db() and for generating the pagebrowser * - * @param array or string - condition (an array will be AND'ed using db_where_clause, a string will be directly used) + * @param array|string $condition - condition (an array will be AND'ed using db_where_clause, a string will be directly used) * (if you use a string, make sure it is correctly escaped!) * - WARNING: will be changed to array only in the future, with an option to include a raw string inside the array - * @param array searchmode - operators to use (=, <, >) if $condition is an array. Defaults to = if not specified for a field. + * @param array $searchmode - operators to use (=, <, >) if $condition is an array. Defaults to = if not specified for a field. * @return array - contains query parts */ - protected function build_select_query($condition, $searchmode) + protected function build_select_query($condition, array $searchmode): array { $select_cols = array(); @@ -757,10 +757,46 @@ abstract class PFAHandler */ public function getPagebrowser($condition, $searchmode) { + if (is_array($condition)) { + $condition = $this->filterSearchCondition($condition); + } $queryparts = $this->build_select_query($condition, $searchmode); return create_page_browser($this->label_field, $queryparts['from_where_order'], $queryparts['params'] ?? []); } + /** + * restrict a search condition array to fields the caller is allowed to search on. + * + * Used by getList() and getPagebrowser() to avoid information leaks / SQL injection via + * search parameter keys - $condition keys end up as raw SQL column names in + * db_where_clause(), so unknown keys must never reach build_select_query(). + * + * @param array $condition + * @return array - filtered condition + */ + protected function filterSearchCondition(array $condition): array + { + $real_condition = array(); + foreach ($condition as $key => $value) { + // skip password fields. + $type = $this->struct[$key]['type'] ?? null; + if ($type === 'pass') { + continue; + } + + # allow only access to fields the user can access to avoid information leaks via search parameters + if (isset($this->struct[$key]) && ($this->struct[$key]['display_in_list'] || $this->struct[$key]['display_in_form'])) { + $real_condition[$key] = $value; + } elseif (($key == '_') && count($this->searchfields)) { + # '_' is the simple-search box; build_select_query() expands it into a LIKE across $this->searchfields + $real_condition[$key] = $value; + } else { + $this->errormsg[] = "Ignoring unknown search field $key"; + } + } + return $real_condition; + } + /** * read_from_db * @@ -847,17 +883,7 @@ abstract class PFAHandler public function getList($condition, $searchmode = array(), $limit = -1, $offset = -1): bool { if (is_array($condition)) { - $real_condition = array(); - foreach ($condition as $key => $value) { - # allow only access to fields the user can access to avoid information leaks via search parameters - if (isset($this->struct[$key]) && ($this->struct[$key]['display_in_list'] || $this->struct[$key]['display_in_form'])) { - $real_condition[$key] = $value; - } elseif (($key == '_') && count($this->searchfields)) { - $real_condition[$key] = $value; - } else { - $this->errormsg[] = "Ignoring unknown search field $key"; - } - } + $real_condition = $this->filterSearchCondition($condition); } else { # warning: no sanity checks are applied if $condition is not an array! $real_condition = $condition; diff --git a/model/PasswordChangeAttempt.php b/model/PasswordChangeAttempt.php new file mode 100644 index 00000000..892eaacc --- /dev/null +++ b/model/PasswordChangeAttempt.php @@ -0,0 +1,52 @@ +checkPasswordRecoveryCode($username, $code)) { + return ['success' => false, 'errors' => [Config::lang('pPassword_code_text_error')]]; + } + + if ($totppf->usesTOTP($username) && !$totppf->checkUserTOTP($username, $totpCode)) { + return ['success' => false, 'errors' => [Config::lang('pTotp_failed')]]; + } + + if (!$handler->init($username)) { + return ['success' => false, 'errors' => $handler->errormsg]; + } + + $values = $handler->result; + $values['password'] = $password; + $values['password2'] = $password2; + + if (!($handler->set($values) && $handler->save())) { + return ['success' => false, 'errors' => $handler->errormsg]; + } + + $handler->wipePasswordRecoveryCode($username); + + // $handler->errormsg will most likely be an empty array + return ['success' => true, 'errors' => $handler->errormsg]; + } +} diff --git a/model/TotpexceptionHandler.php b/model/TotpexceptionHandler.php index f290bb18..800f388d 100644 --- a/model/TotpexceptionHandler.php +++ b/model/TotpexceptionHandler.php @@ -68,9 +68,13 @@ class TotpexceptionHandler extends PFAHandler 'create_button' => 'pTotp_exceptions_add', 'required_role' => 'admin', - 'listview' => 'list.php?table=totpexception', + 'listview' => 'totp-exceptions.php', 'early_init' => 0, - 'user_hardcoded_field' => 'username', + # deliberately no 'user_hardcoded_field' - users must not be able to use edit.php/list.php/delete.php + # for this handler, as that would bypass the current password check in users/totp-exceptions.php + # creating/editing via edit.php is disabled for everyone (incl. admins) for the same reason - + # totp-exceptions.php requires the current password before adding an exception. + 'disable_edit_form' => 1, ); } @@ -118,7 +122,7 @@ class TotpexceptionHandler extends PFAHandler if ($value === '') { if ($this->is_superadmin) { $this->values['username'] = null; - return true; + return false; # to avoid that set() overwrites $this->values[$field] with the raw (empty string) input } $this->errormsg[$field] = Config::Lang('pException_user_global_error'); return false; @@ -127,7 +131,7 @@ class TotpexceptionHandler extends PFAHandler // Users can only set exceptions for themselves if (!$this->is_admin) { $this->values['username'] = $this->username; - return true; + return false; # to avoid that set() overwrites $this->values[$field] with the raw (attacker-controlled) input } // Superadmins can set for anyone diff --git a/public/broadcast-message.php b/public/broadcast-message.php index 5e90a011..4db5ec4b 100644 --- a/public/broadcast-message.php +++ b/public/broadcast-message.php @@ -93,9 +93,9 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") { $fHeaders .= 'Date: ' . date('r', time()) . "\n"; $fHeaders .= 'Message-ID: <' . ((string)microtime(true)) . '-' . md5($smtp_from_email . $fTo) . "@{$serverName}>\n\n"; - $fHeaders .= $b_message; + $data = $fHeaders . $b_message; - if (!smtp_mail($fTo, $smtp_from_email, $fHeaders, smtp_get_admin_password())) { + if (!smtp_mail(to: $fTo, from: $smtp_from_email, subject_or_data: $data)) { flash_error(Config::lang_f('pSendmail_result_error', $fTo)); } else { flash_info(Config::lang_f('pSendmail_result_success', $fTo)); diff --git a/public/edit.php b/public/edit.php index 275b5689..5b4a8cff 100644 --- a/public/edit.php +++ b/public/edit.php @@ -62,6 +62,10 @@ if ($is_admin) { } } +if (!empty($formconf['disable_edit_form'])) { + throw new \InvalidArgumentException($handlerclass . ' can not be edited via edit.php'); +} + if ($new == 0 || $formconf['early_init']) { if (!$handler->init($edit)) { if (count($handler->errormsg) == 0) { diff --git a/public/sendmail.php b/public/sendmail.php index 85caca14..bf95e790 100644 --- a/public/sendmail.php +++ b/public/sendmail.php @@ -64,7 +64,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") { } if ($error != 1) { - if (!smtp_mail($fTo, $fFrom, $fSubject, $tBody)) { + if (!smtp_mail(to: $fTo, from: $fFrom, subject_or_data: $fSubject, body: $tBody)) { flash_error(Config::lang_f('pSendmail_result_error', $fTo)); } else { flash_info(Config::lang_f('pSendmail_result_success', $fTo)); diff --git a/public/users/password-change.php b/public/users/password-change.php index 62fddfd6..1fd8005b 100644 --- a/public/users/password-change.php +++ b/public/users/password-change.php @@ -72,41 +72,21 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { flash_error(Config::lang('pPassword_password_text_error')); } else { $handler = $context === 'admin' ? new AdminHandler() : new MailboxHandler(); - if (!$handler->checkPasswordRecoveryCode($tUsername, $tCode)) { - flash_error(Config::lang('pPassword_code_text_error')); + $totppf = new TotpPf($context === 'admin' ? 'admin' : 'mailbox', new Login($context === 'admin' ? 'admin' : 'mailbox')); + + $result = PasswordChangeAttempt::run($handler, $totppf, $tUsername, $tCode, safepost('fTOTP_code'), $fPassword, $fPassword2); + + if ($result['success']) { + // only reachable once the new password has actually been validated and + // persisted, and the recovery code invalidated - see security report on + // init_session() being called too early - https://github.com/postfixadmin/postfixadmin/pull/1165 + init_session($tUsername, $context === 'admin', true); + flash_info(Config::lang_f('pPassword_result_success', $tUsername)); + header('Location: main.php'); + exit(0); } else { - $totppf = new TotpPf($context === 'admin' ? 'admin' : 'mailbox', new Login($context === 'admin' ? 'admin' : 'mailbox')); - - if ($totppf->usesTOTP($tUsername)) { - $fTotp = safepost('fTOTP_code'); - - if (!$totppf->checkUserTOTP($tUsername, $fTotp)) { - flash_error(Config::lang('pTotp_failed')); - $error = true; - } - } - - if (!$error) { - init_session($tUsername, $context === 'admin', true); - - if (!$handler->init($tUsername)) { - flash_error($handler->errormsg); - } else { - $values = $handler->result; - $values['password'] = $fPassword; - $values['password2'] = $fPassword2; - - if ($handler->set($values) && $handler->save()) { - flash_info(Config::lang_f('pPassword_result_success', $tUsername)); - $handler->wipePasswordRecoveryCode($tUsername); - header('Location: main.php'); - exit(0); - } else { - foreach ($handler->errormsg as $msg) { - flash_error($msg); - } - } - } + foreach ($result['errors'] as $msg) { + flash_error($msg); } } } diff --git a/public/users/password-recover.php b/public/users/password-recover.php index ab0c0680..d74476b1 100644 --- a/public/users/password-recover.php +++ b/public/users/password-recover.php @@ -54,10 +54,10 @@ function sendCodebyEmail($to, $username, $code) } return smtp_mail( - $to, - smtp_get_admin_email(false), - Config::Lang('pPassword_welcome'), - Config::lang_f('pPassword_recovery_email_body', $url)); + to: $to, + from: smtp_get_admin_email(false), + subject_or_data: Config::Lang('pPassword_welcome'), + body: Config::lang_f('pPassword_recovery_email_body', $url)); } function sendCodebySMS($to, $username, $code) diff --git a/tests/AliasHandlerTest.php b/tests/AliasHandlerTest.php index f3a598d2..21c40d96 100644 --- a/tests/AliasHandlerTest.php +++ b/tests/AliasHandlerTest.php @@ -709,6 +709,49 @@ class AliasHandlerTest extends \PHPUnit\Framework\TestCase } + /** + * getPagebrowser() must apply the same search-field allow-list as getList(). + * Previously it passed $condition straight to build_select_query(), so an + * unknown search key ended up as a raw, unescaped SQL column name in the + * WHERE clause via db_where_clause() - i.e. SQL injection through the + * array key of $_GET['search'] in public/list.php. + */ + public function testGetPagebrowserRejectsUnknownSearchField() + { + $this->addDomain('example.com', 'admin'); + // addDomain() caps the domain at 11 aliases (4 of them defaults); lift the limit so we can add 15 more + db_query("UPDATE domain SET aliases = 0 WHERE domain = 'example.com'"); + + // need more than page_size (10) rows so the pagebrowser is actually populated + foreach (range(1, 15) as $i) { + $addr = "$i-test@example.com"; + $x = new AliasHandler(1, 'admin', true); + $this->assertTrue($x->init($addr)); + $x->set([ + 'localpart' => explode('@', $addr)[0], + 'domain' => 'example.com', + 'active' => 1, + 'address' => $addr, + 'goto' => ['dest@example.com'], + ]); + $this->assertTrue($x->save(), json_encode($x->errormsg)); + } + + $malicious_key = '1); DROP TABLE alias; --'; + + $x = new AliasHandler(0, 'admin', true); + $withMaliciousKey = $x->getPagebrowser([$malicious_key => 'irrelevant'], []); + $this->assertEquals(["Ignoring unknown search field $malicious_key"], $x->errormsg); + + $y = new AliasHandler(0, 'admin', true); + $withoutCondition = $y->getPagebrowser([], []); + + // the unknown key must be dropped entirely (never reach SQL), so the + // result is identical to not having supplied it at all. + $this->assertNotEmpty($withMaliciousKey); + $this->assertEquals($withoutCondition, $withMaliciousKey); + } + /** * delete-inactive.php enumerates the inactive aliases and deletes each one * through its handler. Verify that removes only the inactive aliases and diff --git a/tests/BuildSelectQueryTest.php b/tests/BuildSelectQueryTest.php new file mode 100644 index 00000000..777a8e9d --- /dev/null +++ b/tests/BuildSelectQueryTest.php @@ -0,0 +1,238 @@ +build_select_query($condition, $searchmode); + } +} + +class BuildSelectQueryTest extends \PHPUnit\Framework\TestCase +{ + protected function setUp(): void + { + $_SESSION = [ + 'sessid' => [ + 'roles' => ['global-admin'], + ], + ]; + parent::setUp(); + + db_insert('domain', ['domain' => 'example.com', 'description' => 'test', 'transport' => 'foo', 'active' => 1, 'backupmx' => 0]); + db_insert('domain_admins', ['username' => 'admin', 'domain' => 'example.com', 'created' => '2020-01-01', 'active' => 1], ['created'], true); + + $this->addMailbox('alice@example.com', 'Alice Aardvark', 1, 100); + $this->addMailbox('bob@example.com', 'Bob Builder', 0, 200); + // a legitimate value that happens to look like a SQL injection payload + $this->addMailbox('evil@example.com', "x' OR '1'='1", 1, 300, "x' OR '1'='1"); + } + + protected function tearDown(): void + { + db_query('DELETE FROM mailbox'); + db_query('DELETE FROM domain_admins'); + db_query('DELETE FROM domain'); + $_SESSION = []; + parent::tearDown(); + } + + private function addMailbox(string $username, string $name, int $active, int $quota, string $password = 'x'): void + { + [$local_part] = explode('@', $username); + db_insert('mailbox', [ + 'username' => $username, + 'password' => $password, + 'name' => $name, + 'maildir' => 'example.com/' . $local_part . '/', + 'local_part' => $local_part, + 'domain' => 'example.com', + 'active' => $active, + 'quota' => $quota, + ]); + } + + private function newHandler(): BuildSelectQueryTestHandler + { + return new BuildSelectQueryTestHandler(0, 'admin', true); + } + + /** + * run a condition/searchmode through build_select_query() and execute the resulting query + * @return array [queryparts, rows] + */ + private function runQuery(array $condition, array $searchmode = []): array + { + $queryparts = $this->newHandler()->callBuildSelectQuery($condition, $searchmode); + $rows = db_query_all($queryparts['select_cols'] . $queryparts['from_where_order'], $queryparts['params']); + return [$queryparts, $rows]; + } + + public function testReturnsExpectedArrayShape() + { + $queryparts = $this->newHandler()->callBuildSelectQuery(['username' => 'alice@example.com'], []); + + $this->assertArrayHasKey('select_cols', $queryparts); + $this->assertArrayHasKey('from_where_order', $queryparts); + $this->assertArrayHasKey('params', $queryparts); + + // every :placeholder referenced in the query must have a matching bound param, and vice versa + preg_match_all('/:([a-zA-Z0-9_]+)/', $queryparts['from_where_order'], $matches); + $this->assertEqualsCanonicalizing(array_unique($matches[1]), array_keys($queryparts['params'])); + } + + public function testDefaultOperatorIsEquality() + { + [$queryparts, $rows] = $this->runQuery(['username' => 'alice@example.com']); + + $this->assertStringContainsString('username= :_wh_username', $queryparts['from_where_order']); + $this->assertEquals('alice@example.com', $queryparts['params']['_wh_username']); + $this->assertCount(1, $rows); + $this->assertEquals('alice@example.com', $rows[0]['username']); + } + + public function testContSearchmodeMatchesSubstring() + { + [, $rows] = $this->runQuery(['name' => 'Aardvark'], ['name' => 'CONT']); + + $this->assertCount(1, $rows); + $this->assertEquals('alice@example.com', $rows[0]['username']); + } + + public function testLikeSearchmodeUsesValueVerbatim() + { + // LIKE (unlike CONT) does not add wildcards automatically - the caller supplies them + [, $rows] = $this->runQuery(['name' => '%Build%'], ['name' => 'LIKE']); + + $this->assertCount(1, $rows); + $this->assertEquals('bob@example.com', $rows[0]['username']); + } + + public function testComparisonOperatorFiltersNumerically() + { + [, $rows] = $this->runQuery(['quota' => 150], ['quota' => '>']); + + $usernames = array_column($rows, 'username'); + sort($usernames); + $this->assertEquals(['bob@example.com', 'evil@example.com'], $usernames); + } + + public function testNullOperatorProducesIsNullWithoutBoundParam() + { + $queryparts = $this->newHandler()->callBuildSelectQuery(['name' => ''], ['name' => 'NULL']); + + $this->assertStringContainsString('name IS NULL', $queryparts['from_where_order']); + $this->assertArrayNotHasKey('_wh_name', $queryparts['params']); + } + + public function testNotNullOperatorProducesIsNotNullWithoutBoundParam() + { + $queryparts = $this->newHandler()->callBuildSelectQuery(['name' => ''], ['name' => 'NOTNULL']); + + $this->assertStringContainsString('name IS NOT NULL', $queryparts['from_where_order']); + $this->assertArrayNotHasKey('_wh_name', $queryparts['params']); + } + + public function testSimpleSearchExpandsAcrossSearchfields() + { + // MailboxHandler::$searchfields = ['username'] - '_' should LIKE-match against it + [$queryparts, $rows] = $this->runQuery(['_' => 'bob']); + + $this->assertStringContainsString('username LIKE :_search_username', $queryparts['from_where_order']); + $this->assertEquals('%bob%', $queryparts['params']['_search_username']); + $this->assertCount(1, $rows); + $this->assertEquals('bob@example.com', $rows[0]['username']); + } + + public function testStringConditionIsUsedVerbatim() + { + $queryparts = $this->newHandler()->callBuildSelectQuery('1=1', []); + + $this->assertStringContainsString('WHERE ( 1=1 )', $queryparts['from_where_order']); + // domain_field scoping still applies on top of the raw string condition + $this->assertEquals(['_in_0_0' => 'example.com'], $queryparts['params']); + } + + public function testDomainFieldRestrictsToAllowedDomains() + { + $queryparts = $this->newHandler()->callBuildSelectQuery([], []); + + $this->assertStringContainsString('domain IN (:_in_0_0)', $queryparts['from_where_order']); + $this->assertEquals('example.com', $queryparts['params']['_in_0_0']); + } + + /** + * A 'select'-aliased struct field (here: MailboxHandler's password2, aliased from + * 'password as password2') must be filtered in HAVING, not WHERE - db_where_clause() + * cannot put a condition on a computed column into the WHERE clause. + * Structural-only: some databases (SQLite among them) reject a HAVING clause with no + * GROUP BY/aggregate, so this does not execute the query - only inspects the SQL shape. + */ + public function testAliasedSelectFieldIsFilteredInHavingNotWhere() + { + $queryparts = $this->newHandler()->callBuildSelectQuery(['password2' => 'x'], []); + + $this->assertStringContainsString('HAVING ( password2= :_wh_password2 )', $queryparts['from_where_order']); + $this->assertEquals('x', $queryparts['params']['_wh_password2']); + // must not also appear as a plain WHERE condition + $this->assertStringNotContainsString('AND ( password2', $queryparts['from_where_order']); + } + + /** + * SQL injection safety (1/3): a value containing quotes/SQL syntax is legitimate data + * and must be matched literally, not interpreted as SQL. + */ + public function testValueContainingQuotesIsTreatedAsLiteralData() + { + $payload = "x' OR '1'='1"; + + [$queryparts, $rows] = $this->runQuery(['name' => $payload]); + + $this->assertStringNotContainsString($payload, $queryparts['from_where_order'], 'the raw value must never be concatenated into the query text'); + $this->assertCount(1, $rows, 'must match only the row whose name literally equals the payload'); + $this->assertEquals('evil@example.com', $rows[0]['username']); + } + + /** + * SQL injection safety (2/3): a classic tautology payload as a search VALUE must not + * widen the result set - it is just a literal string to compare against. + */ + public function testTautologyPayloadAsValueMatchesNothing() + { + [, $rows] = $this->runQuery(['name' => "nomatch' OR '1'='1"]); + + $this->assertCount(0, $rows); + } + + /** + * SQL injection safety (3/3): a destructive payload as a search VALUE must not be + * executed - the mailbox table must be untouched afterwards. + */ + public function testDestructivePayloadAsValueDoesNotExecute() + { + [, $rows] = $this->runQuery(['name' => "x'; DROP TABLE mailbox; --"]); + + $this->assertCount(0, $rows); + $count = db_query_all('SELECT COUNT(*) as c FROM mailbox'); + $this->assertEquals(3, $count[0]['c'], 'mailbox table must survive the attempted injection intact'); + } +} diff --git a/tests/MailboxHandlerTest.php b/tests/MailboxHandlerTest.php index 1e270054..f33db92f 100644 --- a/tests/MailboxHandlerTest.php +++ b/tests/MailboxHandlerTest.php @@ -363,6 +363,74 @@ EOF; $this->assertJsonStringEqualsJsonString($args_1, json_encode($args[1])); } + + /** + * Search conditions on password ('pass' type) fields must be ignored by getList() / getPagebrowser(). + * Otherwise an admin could use search parameters (e.g. ?search[password]=...&searchmode[password]=LIKE) + * as an oracle to recover password hashes one character at a time. + */ + public function testSearchOnPasswordFieldIsIgnored() + { + // Fake being an admin. + $_SESSION = [ + 'sessid' => [ + 'roles' => ['global-admin'] + ] + ]; + + // insert directly rather than via DomainHandler/MailboxHandler to avoid DNS checks on the domain + db_insert('domain', [ + 'domain' => 'example.com', + 'description' => 'test domain', + 'aliases' => 10, + 'mailboxes' => 10, + 'maxquota' => 100, + 'quota' => 100, + 'transport' => 'virtual', + 'backupmx' => 0, + 'active' => 1, + ]); + db_insert('domain_admins', ['username' => 'admin', 'domain' => 'example.com', 'created' => '2020-01-01', 'active' => 1], ['created'], true); + + $hash = '{SHA512-CRYPT}$6$somesalt$notarealhash'; + db_insert('mailbox', [ + 'username' => 'pwsearch@example.com', + 'password' => $hash, + 'name' => 'test person', + 'maildir' => 'example.com/pwsearch/', + 'quota' => 0, + 'local_part' => 'pwsearch', + 'domain' => 'example.com', + 'active' => 1, + ]); + + // exact match on a value that is definitely not the hash - if the condition were applied, nothing would be returned. + $x = new MailboxHandler(0, 'admin', true); + $this->assertTrue($x->getList(['password' => 'not-the-hash'])); + $this->assertEquals(['pwsearch@example.com'], array_keys($x->result())); + + // LIKE prefix search (the oracle case) - a wrong prefix must not filter anything out either. + $wrongPrefix = 'x%'; + $x = new MailboxHandler(0, 'admin', true); + $this->assertTrue($x->getList(['password' => $wrongPrefix], ['password' => 'LIKE'])); + $this->assertEquals(['pwsearch@example.com'], array_keys($x->result())); + + // password2 is also a 'pass' field. + $x = new MailboxHandler(0, 'admin', true); + $this->assertTrue($x->getList(['password2' => 'whatever'])); + $this->assertEquals(['pwsearch@example.com'], array_keys($x->result())); + + // getPagebrowser() shares the same filtering - the result must be identical to an unfiltered call. + $x = new MailboxHandler(0, 'admin', true); + $withPassword = $x->getPagebrowser(['password' => $wrongPrefix], ['password' => 'LIKE']); + $y = new MailboxHandler(0, 'admin', true); + $this->assertEquals($y->getPagebrowser([], []), $withPassword); + + // non-password fields must still be filterable. + $x = new MailboxHandler(0, 'admin', true); + $this->assertTrue($x->getList(['name' => 'nobody by this name'])); + $this->assertEmpty($x->result()); + } } /* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */ diff --git a/tests/PasswordChangeAttemptTest.php b/tests/PasswordChangeAttemptTest.php new file mode 100644 index 00000000..7ff4f7ca --- /dev/null +++ b/tests/PasswordChangeAttemptTest.php @@ -0,0 +1,121 @@ +createMock(MailboxHandler::class); + } + + private function totpPf(bool $usesTotp = false): TotpPf + { + $totppf = $this->createMock(TotpPf::class); + $totppf->method('usesTOTP')->willReturn($usesTotp); + return $totppf; + } + + /** + * run() only makes sense for the two PFAHandler subclasses that represent an + * account with a login/recovery code. Enforced via the MailboxHandler|AdminHandler + * parameter type, so any other PFAHandler subclass - e.g. AliasHandler, which has + * no concept of a recovery code or a password to save - must be rejected by PHP's + * own type check before run() does anything. + */ + public function testHandlerMustBeMailboxOrAdminHandler(): void + { + $this->expectException(\TypeError::class); + + /** @phpstan-ignore-next-line intentionally wrong type, to prove it is rejected */ + PasswordChangeAttempt::run($this->createMock(AliasHandler::class), $this->totpPf(), 'bob', 'code', '', 'newpass', 'newpass'); + } + + public function testWrongRecoveryCodeFailsWithoutTouchingTheHandlerFurther(): void + { + $handler = $this->mailboxHandler(); + $handler->method('checkPasswordRecoveryCode')->willReturn(false); + $handler->expects($this->never())->method('init'); + $handler->expects($this->never())->method('wipePasswordRecoveryCode'); + + $result = PasswordChangeAttempt::run($handler, $this->totpPf(), 'bob', 'wrong-code', '', 'newpass', 'newpass'); + + $this->assertFalse($result['success']); + $this->assertEquals([Config::lang('pPassword_code_text_error')], $result['errors']); + } + + public function testWrongTotpCodeFailsWithoutSavingThePassword(): void + { + $handler = $this->mailboxHandler(); + $handler->method('checkPasswordRecoveryCode')->willReturn(true); + $handler->expects($this->never())->method('init'); + $handler->expects($this->never())->method('wipePasswordRecoveryCode'); + + $totppf = $this->totpPf(true); + $totppf->method('checkUserTOTP')->willReturn(false); + + $result = PasswordChangeAttempt::run($handler, $totppf, 'bob', 'code', 'wrong-totp', 'newpass', 'newpass'); + + $this->assertFalse($result['success']); + $this->assertEquals([Config::lang('pTotp_failed')], $result['errors']); + } + + /** + * The bug: a failing save() (e.g. new password fails complexity rules) must not + * wipe the recovery code - otherwise it stays usable for another attempt, and the + * caller would previously have already created an authenticated session for it. + */ + public function testFailedSaveDoesNotWipeRecoveryCode(): void + { + $handler = $this->mailboxHandler(); + $handler->method('checkPasswordRecoveryCode')->willReturn(true); + $handler->method('init')->willReturn(true); + $handler->result = ['username' => 'bob']; + $handler->method('set')->willReturn(true); + $handler->method('save')->willReturn(false); + $handler->errormsg = ['password does not meet the rules']; + $handler->expects($this->never())->method('wipePasswordRecoveryCode'); + + $result = PasswordChangeAttempt::run($handler, $this->totpPf(), 'bob', 'code', '', 'bad', 'bad'); + + $this->assertFalse($result['success']); + $this->assertEquals(['password does not meet the rules'], $result['errors']); + } + + public function testHandlerInitFailureIsReportedWithoutWipingTheCode(): void + { + $handler = $this->mailboxHandler(); + $handler->method('checkPasswordRecoveryCode')->willReturn(true); + $handler->method('init')->willReturn(false); + $handler->errormsg = ['no such user']; + $handler->expects($this->never())->method('wipePasswordRecoveryCode'); + $handler->expects($this->never())->method('set'); + + $result = PasswordChangeAttempt::run($handler, $this->totpPf(), 'bob', 'code', '', 'newpass', 'newpass'); + + $this->assertFalse($result['success']); + $this->assertEquals(['no such user'], $result['errors']); + } + + public function testSuccessfulChangeWipesTheRecoveryCodeExactlyOnce(): void + { + $handler = $this->mailboxHandler(); + $handler->method('checkPasswordRecoveryCode')->willReturn(true); + $handler->method('init')->willReturn(true); + $handler->result = ['username' => 'bob']; + $handler->method('set')->willReturn(true); + $handler->method('save')->willReturn(true); + $handler->expects($this->once())->method('wipePasswordRecoveryCode')->with('bob'); + + $result = PasswordChangeAttempt::run($handler, $this->totpPf(), 'bob', 'code', '', 'newpass', 'newpass'); + + $this->assertTrue($result['success']); + $this->assertEquals([], $result['errors']); + } +} diff --git a/tests/SmtpTest.php b/tests/SmtpTest.php index 9c6cf15f..3bb6c9e7 100644 --- a/tests/SmtpTest.php +++ b/tests/SmtpTest.php @@ -34,6 +34,37 @@ class SmtpTest extends TestCase smtp_write($stream, "EHLO example.com\r\n"); } + + public function testDotStuffDoublesLeadingDots(): void + { + $this->assertEquals("hello\r\n..\r\n..foo\r\nbar.", smtp_dot_stuff("hello\r\n.\r\n.foo\r\nbar.")); + $this->assertEquals("..start", smtp_dot_stuff(".start")); + } + + /** + * A domain admin could previously end DATA with a lone "." line in sendmail.php's body + * and follow it with their own SMTP commands. + */ + public function testDotStuffPreventsEndOfDataInjection(): void + { + $body = "hi\r\n.\r\nMAIL FROM:\r\nRCPT TO:\r\nDATA\r\n"; + $this->assertStringNotContainsString("\r\n.\r\n", smtp_dot_stuff($body)); + } + + /** + * Bare LF / CR must not survive, otherwise "\n.\n" might be treated as end-of-data by a lenient server. + */ + public function testDotStuffNormalisesLineEndings(): void + { + $this->assertEquals("a\r\n..\r\nb\r\n..\r\nc", smtp_dot_stuff("a\n.\nb\r.\rc")); + } + + public function testSmtpMailRefusesLineBreaksInAddresses(): void + { + $this->assertFalse(@smtp_mail("victim@example.com\r\nRCPT TO:", 'admin@example.com', 'subject', 'body')); + $this->assertFalse(@smtp_mail('victim@example.com', "admin@example.com\nBcc: x@example.com", 'subject', 'body')); + } + public static function smtpAuthenticationCases(): array { $cases = []; diff --git a/tests/TotpexceptionHandlerTest.php b/tests/TotpexceptionHandlerTest.php new file mode 100644 index 00000000..13dfd084 --- /dev/null +++ b/tests/TotpexceptionHandlerTest.php @@ -0,0 +1,171 @@ + ['roles' => ['global-admin']]]; + } + + private function asAdmin(): void + { + $_SESSION = ['sessid' => ['roles' => ['admin']]]; + } + + private function asUser(): void + { + $_SESSION = ['sessid' => ['roles' => ['user']]]; + } + + private function addDomain(string $domain, string $adminUsername): void + { + $this->asSuperadmin(); + + $dh = new DomainHandler(1, $adminUsername, true); + $dh->init($domain); + $ret = $dh->set([ + 'domain' => $domain, + 'description' => 'test domain', + 'aliases' => 10, + 'mailboxes' => 10, + 'active' => 1, + 'backupmx' => 0, + 'default_aliases' => 0, + ]); + $this->assertTrue($ret, json_encode($dh->errormsg)); + $this->assertTrue($dh->save()); + + db_insert('domain_admins', ['username' => $adminUsername, 'domain' => $domain, 'active' => 1], ['created'], true); + } + + /** + * @return array the 'username' column of every stored totp_exception_address row + */ + private function storedUsernames(): array + { + $rows = db_query_all('SELECT username FROM totp_exception_address'); + return array_column($rows, 'username'); + } + + public function testSuperadminCreatingGlobalExceptionNormalisesEmptyUsernameToNull(): void + { + $this->asSuperadmin(); + + $handler = new TotpexceptionHandler(1, '', 1); + $this->assertTrue($handler->init('')); + + $this->assertTrue($handler->set([ + 'username' => '', + 'ip' => '10.0.0.1', + 'description' => 'global exception', + ]), json_encode($handler->errormsg)); + $this->assertTrue($handler->save(), json_encode($handler->errormsg)); + + $this->assertSame([null], $this->storedUsernames()); + } + + public function testUserCannotCreateExceptionForAnotherUser(): void + { + $this->asUser(); + + // alice is logged in, but tries to submit bob's username. + $handler = new TotpexceptionHandler(1, 'alice@example.com', 0); + $this->assertTrue($handler->init('')); + + $this->assertTrue($handler->set([ + 'username' => 'bob@example.com', + 'ip' => '10.0.0.2', + 'description' => 'attempted takeover', + ]), json_encode($handler->errormsg)); + $this->assertTrue($handler->save(), json_encode($handler->errormsg)); + + // the stored row must be scoped to alice, never to the submitted (attacker-controlled) value. + $this->assertSame(['alice@example.com'], $this->storedUsernames()); + } + + public function testUserCanCreateExceptionForSelf(): void + { + $this->asUser(); + + $handler = new TotpexceptionHandler(1, 'alice@example.com', 0); + $this->assertTrue($handler->init('')); + + $this->assertTrue($handler->set([ + 'username' => 'alice@example.com', + 'ip' => '10.0.0.3', + 'description' => 'own exception', + ]), json_encode($handler->errormsg)); + $this->assertTrue($handler->save(), json_encode($handler->errormsg)); + + $this->assertSame(['alice@example.com'], $this->storedUsernames()); + } + + public function testUserCannotCreateGlobalException(): void + { + $this->asUser(); + + $handler = new TotpexceptionHandler(1, 'alice@example.com', 0); + $this->assertTrue($handler->init('')); + + $this->assertFalse($handler->set([ + 'username' => '', + 'ip' => '10.0.0.4', + 'description' => 'global attempt', + ])); + $this->assertArrayHasKey('username', $handler->errormsg); + $this->assertEmpty($this->storedUsernames()); + } + + public function testSuperadminCanCreateExceptionForAnyUsername(): void + { + $this->asSuperadmin(); + + $handler = new TotpexceptionHandler(1, '', 1); + $this->assertTrue($handler->init('')); + + $this->assertTrue($handler->set([ + 'username' => 'someone@example.com', + 'ip' => '10.0.0.5', + 'description' => 'superadmin set', + ]), json_encode($handler->errormsg)); + $this->assertTrue($handler->save(), json_encode($handler->errormsg)); + + $this->assertSame(['someone@example.com'], $this->storedUsernames()); + } + + /** + * Users must add TOTP exceptions via users/totp-exceptions.php, which requires them to re-enter + * their password. If user_hardcoded_field were set, edit.php would let them bypass that. + */ + public function testNotAvailableToUsersViaGenericEditForm(): void + { + $this->asUser(); + + $handler = new TotpexceptionHandler(1, 'user@example.com', false); + $formconf = $handler->webformConfig(); + + $this->assertEmpty($formconf['user_hardcoded_field'] ?? null); + $this->assertEquals('admin', $formconf['required_role']); + } + + /** + * Admins (incl. superadmins) must also add TOTP exceptions via totp-exceptions.php, which requires the current password. + */ + public function testGenericEditFormIsDisabledForAdmins(): void + { + $this->asAdmin(); + + $handler = new TotpexceptionHandler(1, 'admin@example.com', true); + $this->assertNotEmpty($handler->webformConfig()['disable_edit_form']); + } +}