Escape security lists and make template escaping opt-outs explicit (#1172)

fixes potential XSS issue with TOTP exception lists (which need escaping, see also #1185). 

refactors Template escaping to use TemplateEscape enum (rather than the previous boolean).

thanks @TrapoSAMA
This commit is contained in:
Rodrigo Cortés Cano authored and GitHub committed 2026-11-01 10:41:54 +00:00
1 parent 06e3af5fe0
commit 3feeb081af
22 files changed
+415 -58

No files matched your search

+3
View File
@@ -10,6 +10,9 @@ Changes in 'master' (not in a release yet) (20XX/XX/XX)
--------------------------
- Use the concise Spanish "MX de respaldo" label for Backup MX in domain lists and forms.
- Escape stored application-password and TOTP-exception list values. (see #1172, thanks @TrapoSAMA)
- Require explicit TemplateEscape modes instead of boolean template escaping arguments. (see #1172, thanks @TrapoSAMA)
- Treat recipient_delimiter as a set of alternative characters, matching Postfix behavior (see #1143, thanks @MatzeKitt).
- Allow mailbox users to edit their own display name in the users/ interface when enabled globally or for selected domains; apply the same name validation to administrative mailbox creation and editing (see #1176, thanks @pvdv and @TrapoSAMA).
- Invalidate XML-RPC authorization when web authentication replaces the session, and reject pending MFA sessions.
+9
View File
@@ -0,0 +1,9 @@
# Template output escaping
`$smarty->assign($key, $value)` escapes strings recursively for HTML output by default, using `TemplateEscape::HTML`. Keep this default unless you have very good reasons to disable escaping. Never disable escaping for user-supplied text, including nested list values.
When a value intentionally contains HTML that is already safe for its output context, use `$smarty->assign($key, $value, TemplateEscape::RAW)`. RAW does not validate or sanitise HTML. JSON, JavaScript, URLs and commands need their own context-specific encoding before any intentional HTML-escaping opt-out; the enum does not implement those encoders.
The third argument is named `sanitise` and accepts only `TemplateEscape::HTML` or `TemplateEscape::RAW`. Boolean arguments, strings and other values throw `TypeError` before any template assignment. There is no intermediate deprecation stage. Replace legacy `true` with the default or `TemplateEscape::HTML`; review each legacy `false` call and remove its opt-out when HTML escaping is appropriate, otherwise use `TemplateEscape::RAW` only for values already safe in their output context. Apply the same migration to dynamically computed mode arguments in integrations.
The existing `RAW_` template variables remain available for compatibility. They contain the original assigned values and do not provide output-context encoding. The enum requires PHP 8.1 or newer and is supported by master's PHP >=8.2 requirement; this API change must not be copied to the PHP 7.4 branch.
+3 -3
View File
@@ -122,12 +122,12 @@ class PFASmarty
/**
* @param string $key
* @param mixed $value
* @param bool $sanitise
* @param TemplateEscape $sanitise Output escaping mode; RAW requires data safe for its output context.
*/
public function assign($key, $value, $sanitise = true)
public function assign(string $key, mixed $value, TemplateEscape $sanitise = TemplateEscape::HTML)
{
$this->template->assign("RAW_$key", $value);
if ($sanitise == false) {
if ($sanitise === TemplateEscape::RAW) {
return $this->template->assign($key, $value);
}
$clean = $this->sanitise($value);
+8
View File
@@ -0,0 +1,8 @@
<?php
/** Output escaping modes accepted by PFASmarty. */
enum TemplateEscape: string
{
case HTML = 'html';
case RAW = 'raw';
}
+2 -2
View File
@@ -239,9 +239,9 @@ foreach ($form_fields as $key => $_) {
} else {
$fielderror[$key] = '';
}
$sanitise = true;
$sanitise = TemplateEscape::HTML;
if (isset($form_fields[$key]['type']) && $form_fields[$key]['type'] == 'html') {
$sanitise = false;
$sanitise = TemplateEscape::RAW;
}
if (isset($values[$key])) {
+2 -5
View File
@@ -404,9 +404,6 @@ $pagination_mailbox = page_browser_pagination(
);
// this is why we need a proper template layer.
$fDomain = htmlentities($fDomain, ENT_QUOTES);
if (empty($_GET['domain'])) {
$_GET['domain'] = '';
}
@@ -416,7 +413,7 @@ $smarty->assign('domain_selected', $fDomain);
$smarty->assign('pagination_alias', $pagination_alias);
$smarty->assign('pagination_mailbox', $pagination_mailbox);
$smarty->assign('fDomain', $fDomain, false);
$smarty->assign('fDomain', $fDomain);
$smarty->assign('search', $search);
@@ -444,7 +441,7 @@ if ($password_expiration_never_label === '') {
}
$smarty->assign('password_expiration_on_label', $password_expiration_on_label);
$smarty->assign('password_expiration_never_label', $password_expiration_never_label);
$smarty->assign('gen_show_status_mailbox', $gen_show_status_mailbox, false);
$smarty->assign('gen_show_status_mailbox', $gen_show_status_mailbox, TemplateEscape::RAW);
$smarty->assign('boolconf_used_quotas', Config::bool('used_quotas'));
$smarty->assign('divide_quota', $divide_quota);
$smarty->assign('tCanAddMailbox', $tCanAddMailbox);
+1 -1
View File
@@ -62,7 +62,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") {
$smarty->assign('pTOPT_code_text', $error);
$smarty->assign('smarty_template', 'login-mfa');
$smarty->assign('language_selector', language_selector(), false);
$smarty->assign('language_selector', language_selector(), TemplateEscape::RAW);
$smarty->assign('forgotten_password_reset', Config::bool('forgotten_admin_password_reset'));
$smarty->display('index.tpl');
+1 -1
View File
@@ -106,7 +106,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") {
session_start();
}
$smarty->assign('language_selector', language_selector(), false);
$smarty->assign('language_selector', language_selector(), TemplateEscape::RAW);
$smarty->assign('smarty_template', 'login');
$smarty->assign('logintype', 'admin');
$smarty->assign('forgotten_password_reset', Config::bool('forgotten_admin_password_reset'));
+1 -7
View File
@@ -32,9 +32,6 @@ $smarty = PFASmarty::getInstance();
$smarty->configureTheme($smarty->getRelPath());
$username = authentication_get_username();
$pPassword_text = "";
$pUser_text = '';
$pUser = '';
// check if app-passwords are enabled
if (Config::bool('app_passwords') === false) {
@@ -112,10 +109,7 @@ foreach ($passwords as $n => $pass) {
$smarty->assign('SESSID_USERNAME', $username);
$smarty->assign('pPassword_text', $pPassword_text, false);
$smarty->assign('pUser_text', $pUser_text, false);
$smarty->assign('pUser', $pUser, false);
$smarty->assign('pPasswords', $passwords, false);
$smarty->assign('pPasswords', $passwords);
$smarty->assign('smarty_template', 'app-passwords');
$smarty->display('index.tpl');
+1 -1
View File
@@ -46,7 +46,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") {
$smarty->assign('logintype', 'user');
$smarty->assign('smarty_template', 'login-mfa');
$smarty->assign('language_selector', language_selector(), false);
$smarty->assign('language_selector', language_selector(), TemplateEscape::RAW);
$smarty->assign('forgotten_password_reset', Config::bool('forgotten_admin_password_reset'));
$smarty->display('index.tpl');
+1 -1
View File
@@ -83,7 +83,7 @@ if ($error) {
flash_error($error);
}
$smarty->assign('language_selector', language_selector(), false);
$smarty->assign('language_selector', language_selector(), TemplateEscape::RAW);
$smarty->assign('smarty_template', 'login');
$smarty->assign('logintype', 'user');
$smarty->assign('forgotten_password_reset', Config::read('forgotten_user_password_reset') && !Config::read('mailbox_postpassword_script'));
+1 -1
View File
@@ -95,7 +95,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$totppf = new TotpPf($context === 'admin' ? 'admin' : 'mailbox', new Login($context === 'admin' ? 'admin' : 'mailbox'));
$tTotpRequired = $totppf->usesTOTP($tUsername);
$smarty->assign('tTotpRequired', $tTotpRequired);
$smarty->assign('language_selector', language_selector(), false);
$smarty->assign('language_selector', language_selector(), TemplateEscape::RAW);
$smarty->assign('tUsername', $tUsername);
$smarty->assign('tCode', $tCode);
$smarty->assign('smarty_template', 'password-change');
+1 -1
View File
@@ -119,7 +119,7 @@ if ($_SERVER['REQUEST_METHOD'] === "POST") {
flash_info(Config::Lang('pPassword_recovery_processed'));
}
$smarty->assign('language_selector', language_selector(), false);
$smarty->assign('language_selector', language_selector(), TemplateEscape::RAW);
$smarty->assign('smarty_template', 'password-recover');
$smarty->display('index.tpl');
+2 -2
View File
@@ -87,8 +87,8 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") {
}
$smarty->assign('SESSID_USERNAME', $username);
$smarty->assign('pPassword_password_current_text', $pPassword_password_current_text, false);
$smarty->assign('pPassword_password_text', $pPassword_password_text, false);
$smarty->assign('pPassword_password_current_text', $pPassword_password_current_text);
$smarty->assign('pPassword_password_text', $pPassword_password_text);
$smarty->assign('smarty_template', 'password');
$smarty->display('index.tpl');
+1 -8
View File
@@ -34,9 +34,6 @@ $smarty->configureTheme($smarty->getRelPath());
$username = authentication_get_username();
list($_, $domain) = explode('@', $username);
$pPassword_text = "";
$pUser_text = '';
$pUser = '';
$username = authentication_get_username();
@@ -126,11 +123,7 @@ foreach ($exceptions as $n => $ex) {
$smarty->assign('SESSID_USERNAME', $username);
$smarty->assign('pPassword_text', $pPassword_text, false);
$smarty->assign('pUser_text', $pUser_text, false);
$smarty->assign('pUser', $pUser, false);
#$smarty->assign('', $, false);
$smarty->assign('pExceptions', $exceptions, false);
$smarty->assign('pExceptions', $exceptions);
$smarty->assign('smarty_template', 'totp-exceptions');
$smarty->display('index.tpl');
+3 -14
View File
@@ -34,13 +34,6 @@ authentication_require_role($required_role);
$username = authentication_get_username();
$pPassword_password_current_text = "";
$pTOTP_now = "";
$pPassword_password_text = "";
// these get shown if there's an error.
$pTOTP_secret_text = '';
$pTOTP_code_text = '';
// check if totp is enabled
if (Config::bool('totp') === false) {
@@ -122,13 +115,9 @@ list($pTOTP_secret, $pQR_raw) = $totppf->generate($username);
$smarty->assign('SESSID_USERNAME', $username);
$smarty->assign('admin', $admin);
$smarty->assign('pPassword_password_current_text', $pPassword_password_current_text, false);
$smarty->assign('pTOTP_code_text', $pTOTP_code_text, false);
$smarty->assign('pTOTP_secret_text', $pTOTP_secret_text, false);
$smarty->assign('pPassword_password_text', $pPassword_password_text, false);
$smarty->assign('pQR_raw', $pQR_raw, false);
$smarty->assign('pTOTP_secret', $pTOTP_secret, false);
$smarty->assign('pTOTP_now', $pTOTP_now, false);
$smarty->assign('pPassword_password_current_text', $pPassword_password_current_text);
$smarty->assign('pQR_raw', $pQR_raw);
$smarty->assign('pTOTP_secret', $pTOTP_secret);
$smarty->assign('smarty_template', 'totp');
$smarty->display('index.tpl');
+1 -2
View File
@@ -3,13 +3,12 @@
<div class="card-header"><h4>{$PALANG.pApp_passwords_welcome}</h4></div>
<div class="card-body enable-asterisk">
{CSRF_Token}
<div class="mb-3 {if $pPassword_text}is-invalid{/if}">
<div class="mb-3">
<label class="col-md-2"
for="fPassword_current">{$PALANG.pPassword_password_current}:</label>
<div class="col-md-6 col-sm-8">
<input class="form-control" type="password" name="fPassword_current" id="fPassword_current"/>
</div>
<span class="form-text">{$pPassword_text}</span>
</div>
<div class="mb-3">
<label class="col-md-2" for="fAppDesc">{$PALANG.pTotp_exceptions_description}
+3 -6
View File
@@ -4,18 +4,15 @@
<div class="card-header"><h4>{$PALANG.pTotp_exceptions_welcome}</h4></div>
<div class="card-body enable-asterisk">
{CSRF_Token}
<div class="mb-3 {if $pPassword_text}is-invalid{/if}">
<div class="mb-3">
<label class="col-md-2 col-sm-2"
for="fPassword_current">{$PALANG.pPassword_password_current}:</label>
<div class="col-md-6 col-sm-8"><input class="form-control" type="password" name="fPassword_current"
id="fPassword_current"/></div>
<span class="form-text">{$pPassword_text}</span>
</div>
<div class="mb-3 {if $pUser_text}is-invalid{/if}">
<div class="mb-3">
<label class="col-md-2 col-sm-2" for="fUser">{$PALANG.pTotp_exceptions_user}:</label>
<div class="col-md-6 col-sm-8"><input class="form-control" type="input" name="fUser" id="fUser"
value="{$pUser}"/></div>
<span class="form-text">{$pUser_text}</span>
<div class="col-md-6 col-sm-8"><input class="form-control" type="input" name="fUser" id="fUser"/></div>
</div>
<div class="mb-3">
<label class="col-md-2 col-sm-2" for="fIp">{$PALANG.pTotp_exceptions_address}:</label>
+2 -3
View File
@@ -34,19 +34,18 @@
id="fPassword_current"/></div>
<span class="form-text">{$pPassword_password_current_text}</span>
</div>
<div class="mb-3 {if $pTOTP_secret_text}is-invalid{/if}">
<div class="mb-3">
<label class="col-md-2" for="fTOTP_secret">{$PALANG.pTOTP_secret}:</label>
<div class="col-md-6 col-sm-8">
<img src="data:image/png;base64, {$pQR_raw}"/>{$pTOTP_secret}
<input type="hidden" name="fTOTP_secret" value="{$pTOTP_secret}"/>
</div>
</div>
<div class="mb-3 {if $pTOTP_code_text}is-invalid{/if}">
<div class="mb-3">
<label class="col-md-2" for="fTOTP_code">{$PALANG.pTOTP_code}:</label>
<div class="col-md-6 col-sm-8"><input id="fTOTP_code" class="form-control" type="text"
name="fTOTP_code" size="6" inputmode="numeric"
autocomplete="one-time-code"/>
<span class="text-warning">{$pTOTP_code_text}</span> <!-- error text -->
<span class="form-text">{$PALANG.pTOTP_code_text}</span>
</div>
+69
View File
@@ -0,0 +1,69 @@
<?php
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class PFASmartyEscapingTest extends TestCase
{
public static function modes(): array
{
return [
'default' => [null, true],
'explicit HTML' => [TemplateEscape::HTML, true],
'explicit RAW' => [TemplateEscape::RAW, false],
];
}
#[DataProvider('modes')]
public function testAssignmentEscapingAndRawCompatibility(?TemplateEscape $mode, bool $escaped): void
{
$smarty = PFASmarty::getInstance();
$value = ['nested' => ['text' => '<b>R&D</b>']];
if ($mode === null) {
$smarty->assign('escaping_test', $value);
} else {
$smarty->assign('escaping_test', $value, $mode);
}
self::assertSame(($escaped ? '&lt;b&gt;R&amp;D&lt;/b&gt;' : '<b>R&D</b>') . '|<b>R&D</b>', $this->renderValue());
}
public static function invalidModes(): array
{
return [
'false' => [false],
'true' => [true],
'null' => [null],
'zero' => [0],
'empty string' => [''],
'HTML string' => ['html'],
'RAW string' => ['raw'],
'old constant value' => ['no_escaping'],
'array' => [[]],
];
}
#[DataProvider('invalidModes')]
public function testInvalidModeIsRejectedBeforeAssignment(mixed $mode): void
{
$smarty = PFASmarty::getInstance();
$smarty->assign('escaping_test', ['nested' => ['text' => '<b>original</b>']]);
try {
$smarty->assign('escaping_test', ['nested' => ['text' => 'replacement']], $mode);
self::fail('An invalid mode must throw TypeError');
} catch (TypeError $error) {
self::assertStringContainsString('TemplateEscape', $error->getMessage());
}
self::assertSame('&lt;b&gt;original&lt;/b&gt;|<b>original</b>', $this->renderValue());
}
private function renderValue(): string
{
ob_start();
try {
PFASmarty::getInstance()->display('string:{$escaping_test.nested.text}|{$RAW_escaping_test.nested.text}');
return (string)ob_get_contents();
} finally {
ob_end_clean();
}
}
}
+257
View File
@@ -0,0 +1,257 @@
<?php
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class SecurityListOutputTest extends TestCase
{
private const USERNAME = 'test@security-list-http.example.com';
private const DOMAIN = 'security-list-http.example.com';
private string $directory;
private string $url;
private string $cookie = '';
private $server;
protected function setUp(): void
{
self::assertSame(1, db_insert('domain', [
'domain' => self::DOMAIN, 'description' => 'Security output HTTP test', 'transport' => 'virtual',
]));
$descriptions = self::descriptions();
foreach ($descriptions as $index => $description) {
self::assertSame(1, db_insert('mailbox_app_password', [
'username' => self::USERNAME, 'description' => $description, 'password_hash' => 'fixture-unused',
], []));
self::assertSame(1, db_insert('totp_exception_address', [
'username' => self::USERNAME, 'description' => $description, 'ip' => '192.0.2.' . ($index + 1),
], []));
}
self::assertSame(1, db_insert('totp_exception_address', [
'username' => self::DOMAIN, 'description' => 'Domain exception', 'ip' => '192.0.2.10',
], []));
$this->directory = sys_get_temp_dir() . '/pfa-security-list-' . bin2hex(random_bytes(6));
self::assertTrue(mkdir($this->directory));
$config = Config::getInstance()->getAll();
$config['totp'] = 'YES';
$config['app_passwords'] = 'YES';
$config['default_language'] = 'en';
$config['language_hook'] = '';
$config['domain_dns_status_check'] = 0;
// Other tests may leave callable rules that cannot be transferred through JSON.
$config['password_validation'] = ['/.{5}/' => 'password_too_short 5'];
file_put_contents($this->directory . '/config.json', json_encode($config, JSON_THROW_ON_ERROR));
$socket = stream_socket_server('tcp://127.0.0.1:0');
self::assertIsResource($socket);
$address = stream_socket_get_name($socket, false);
fclose($socket);
$this->url = 'http://' . $address;
$command = [PHP_BINARY];
if (php_ini_loaded_file()) {
array_push($command, '-c', php_ini_loaded_file());
}
array_push($command, '-d', 'session.save_path=' . $this->directory, '-d', 'log_errors=1', '-d', 'error_log=' . $this->directory . '/error.log', '-S', $address, __DIR__ . '/fixtures/security-list-http-router.php');
$env = getenv();
$env['PFA_SECURITY_LIST_TEST_CONFIG'] = $this->directory . '/config.json';
$this->server = proc_open($command, [0 => ['pipe', 'r'], 1 => ['file', $this->directory . '/server.log', 'a'], 2 => ['file', $this->directory . '/server.log', 'a']], $pipes, dirname(__DIR__), $env);
self::assertIsResource($this->server);
fclose($pipes[0]);
for ($attempt = 0; $attempt < 100; $attempt++) {
$ready = @stream_socket_client('tcp://' . $address, $errno, $error, 0.1);
if ($ready !== false) {
fclose($ready);
return;
}
usleep(50000);
}
self::fail('PHP HTTP server did not start: ' . file_get_contents($this->directory . '/server.log'));
}
protected function tearDown(): void
{
if (is_resource($this->server)) {
proc_terminate($this->server);
proc_close($this->server);
}
foreach (['mailbox_app_password', 'totp_exception_address'] as $table) {
db_execute('DELETE FROM ' . table_by_key($table) . ' WHERE username = :username OR username = :domain', [
'username' => self::USERNAME, 'domain' => self::DOMAIN,
]);
}
db_delete('mailbox', 'username', self::USERNAME);
db_delete('domain_admins', 'username', 'admin@' . self::DOMAIN);
db_delete('domain', 'domain', self::DOMAIN);
if (isset($this->directory) && is_dir($this->directory)) {
foreach (new DirectoryIterator($this->directory) as $file) {
if (!$file->isDot()) {
unlink($file->getPathname());
}
}
rmdir($this->directory);
}
}
public static function pages(): array
{
return [
'mailbox application passwords' => ['/users/app-passwords.php', 'user', 2, 0],
'global-admin application passwords' => ['/app-passwords.php', 'global-admin', 2, 0],
'mailbox TOTP exceptions' => ['/users/totp-exceptions.php', 'user', 3, 1],
'global-admin TOTP exceptions' => ['/totp-exceptions.php', 'global-admin', 3, 0],
];
}
#[DataProvider('pages')]
public function testStoredListValuesRenderAsText(string $path, string $role, int $descriptionColumn, int $disabled): void
{
[$status] = $this->request('/__session?role=' . $role);
self::assertSame(200, $status);
[$status, $html] = $this->request($path);
self::assertSame(200, $status, $html);
$document = new DOMDocument();
$previousErrors = libxml_use_internal_errors(true);
try {
$document->loadHTML('<?xml encoding="UTF-8">' . $html);
} finally {
libxml_clear_errors();
libxml_use_internal_errors($previousErrors);
}
$xpath = new DOMXPath($document);
self::assertSame(0, $xpath->query('//*[@data-security-fixture]')->length);
$rows = $xpath->query('//table[@id="mailbox_table"]/tr[td]');
$descriptions = [];
foreach ($rows as $row) {
$descriptions[] = $xpath->query('./td[' . $descriptionColumn . ']', $row)->item(0)->textContent;
}
foreach (self::descriptions() as $description) {
self::assertContains(html_entity_decode($description, ENT_QUOTES, 'UTF-8'), $descriptions);
}
self::assertSame($disabled, $xpath->query('//table[@id="mailbox_table"]//button[@disabled]')->length);
self::assertSame($rows->length, $xpath->query('//table[@id="mailbox_table"]//input[@name="CSRF_Token"]')->length);
self::assertStringNotContainsString('&amp;lt;tag&amp;gt;', $html);
}
public static function forms(): array
{
return [
'password' => ['/users/password.php', 2],
'TOTP' => ['/users/totp.php', 1],
];
}
#[DataProvider('forms')]
public function testFormErrorsRenderTranslatedText(string $path, int $errorCount): void
{
[$status] = $this->request('/__session?role=user');
self::assertSame(200, $status);
[$status, $html] = $this->request($path);
self::assertSame(200, $status, $html);
self::assertSame(1, preg_match('/name=["\']CSRF_Token["\'][^>]*value=["\']([^"\']+)/', $html, $match));
[$status, $html] = $this->request($path, [
'CSRF_Token' => $match[1], 'fPassword_current' => 'incorrect-fixture-password',
'fPassword' => '', 'fPassword2' => '', 'fTOTP_code' => '', 'fTOTP_secret' => '',
]);
self::assertSame(200, $status, $html);
self::assertStringContainsString('Invalid &lt;password&gt; &amp; current', $html);
self::assertStringNotContainsString('<password>', $html);
self::assertSame($errorCount, substr_count($html, 'mb-3 is-invalid'));
if ($errorCount === 2) {
self::assertStringContainsString('Invalid &lt;password&gt; &amp; new', $html);
}
}
public function testTotpQrAndSecretRemainUsable(): void
{
$this->request('/__session?role=user');
[$status, $html] = $this->request('/users/totp.php');
self::assertSame(200, $status, $html);
self::assertSame(1, preg_match('/data:image\/png;base64, ([A-Za-z0-9+\/=]+)"/', $html, $qr));
$png = base64_decode($qr[1], true);
self::assertNotFalse($png);
self::assertStringStartsWith("\x89PNG\r\n\x1a\n", $png);
self::assertSame(1, preg_match('/name="fTOTP_secret" value="([A-Z2-7]+)"/', $html, $secret));
self::assertStringContainsString('/>' . $secret[1], $html);
self::assertStringNotContainsString('is-invalid', $html);
}
public function testDomainSelectionPreservesAuthorisation(): void
{
self::assertSame(1, db_insert('domain_admins', [
'username' => 'admin@' . self::DOMAIN, 'domain' => self::DOMAIN, 'active' => true,
], ['created']));
$this->request('/__session?role=global-admin');
[$status, $html] = $this->request('/list-virtual.php', ['fDomain' => self::DOMAIN]);
self::assertSame(200, $status, $html);
self::assertStringContainsString(self::DOMAIN . ' :</h4>', $html);
[$status] = $this->request('/list-virtual.php', ['fDomain' => '<img src=x onerror="alert(1)">']);
self::assertSame(302, $status);
}
public static function editorRoles(): array
{
return ['domain admin' => ['admin'], 'global admin' => ['global-admin']];
}
#[DataProvider('editorRoles')]
public function testGenericEditorEscapesTextAndPreservesHtml(string $role): void
{
$name = 'R&D <b>name</b> "quoted"';
self::assertSame(1, db_insert('domain_admins', [
'username' => 'admin@' . self::DOMAIN, 'domain' => self::DOMAIN, 'active' => true,
], ['created']));
self::assertSame(1, db_insert('mailbox', [
'username' => self::USERNAME, 'password' => 'fixture-unused', 'name' => $name,
'maildir' => self::DOMAIN . '/test/', 'local_part' => 'test', 'domain' => self::DOMAIN,
'active' => true, 'totp_secret' => 'JBSWY3DPEHPK3PXP',
]));
$this->request('/__session?role=' . $role);
$path = '/edit.php?table=mailbox&edit=' . urlencode(self::USERNAME);
[$status, $html] = $this->request($path);
self::assertSame(200, $status, $html);
self::assertStringContainsString('R&amp;D &lt;b&gt;name&lt;/b&gt; &quot;quoted&quot;', $html);
self::assertStringContainsString('<button type="submit" name="reset_totp"', $html);
self::assertStringNotContainsString('&lt;button', $html);
self::assertSame(1, preg_match('/name=["\']CSRF_Token["\'][^>]*value=["\']([^"\']+)/', $html, $token));
$editedName = 'Changed <b>text</b> & "quoted"';
// Invalid quota prevents writes; the read-only HTML field takes its default assignment path.
[$status, $html] = $this->request($path, [
'table' => 'mailbox', 'edit' => self::USERNAME, 'CSRF_Token' => $token[1],
'value' => ['name' => $editedName, 'quota' => '-999'],
]);
self::assertSame(200, $status, $html);
self::assertStringContainsString('Changed &lt;b&gt;text&lt;/b&gt; &amp; &quot;quoted&quot;', $html);
self::assertStringNotContainsString('name="reset_totp"', $html);
self::assertSame($name, db_query_one('SELECT name FROM ' . table_by_key('mailbox') . ' WHERE username = ?', [self::USERNAME])['name']);
[$status, $html] = $this->request('/edit.php?table=mailbox&domain=' . self::DOMAIN);
self::assertSame(200, $status, $html);
self::assertStringContainsString('name="value[name]"', $html);
self::assertStringNotContainsString('name="reset_totp"', $html);
}
private static function descriptions(): array
{
return [
'<img data-security-fixture="injected" src=x onerror="alert(1)">',
"R&D \"quoted\" 'text' <tag> UTF-8: \u{00F1}",
'Legacy &lt;tag&gt; &amp; text',
];
}
private function request(string $path, ?array $data = null): array
{
$options = ['ignore_errors' => true, 'follow_location' => 0, 'timeout' => 10,
'header' => "Cookie: {$this->cookie}\r\n"];
if ($data !== null) {
$options['method'] = 'POST';
$options['header'] .= "Content-Type: application/x-www-form-urlencoded\r\n";
$options['content'] = http_build_query($data);
}
$body = file_get_contents($this->url . $path, false, stream_context_create(['http' => $options]));
self::assertNotFalse($body);
foreach ($http_response_header as $header) {
if (preg_match('/^Set-Cookie: (postfixadmin_session=[^;]+)/i', $header, $match)) {
$this->cookie = $match[1];
}
}
return [(int)explode(' ', $http_response_header[0])[1], $body];
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
// Test-only router: never place this fixture in the public document root.
if (PHP_SAPI !== 'cli-server' || !getenv('PFA_SECURITY_LIST_TEST_CONFIG')) {
http_response_code(404);
exit;
}
define('PHPUNIT_TEST', true);
require dirname(__DIR__, 2) . '/vendor/autoload.php';
$CONF = array_replace($CONF, json_decode(file_get_contents(getenv('PFA_SECURITY_LIST_TEST_CONFIG')), true, 512, JSON_THROW_ON_ERROR));
require dirname(__DIR__, 2) . '/public/common.php';
// Exercise plain-text translations containing characters that need HTML escaping.
$PALANG['pPassword_password_current_text_error'] = 'Invalid <password> & current';
$PALANG['pPassword_password_text_error'] = 'Invalid <password> & new';
Config::write('__LANG', $PALANG);
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($path === '/__session') {
$globalAdmin = ($_GET['role'] ?? '') === 'global-admin';
$admin = $globalAdmin || ($_GET['role'] ?? '') === 'admin';
init_session($admin ? 'admin@security-list-http.example.com' : 'test@security-list-http.example.com', $admin, true);
if ($globalAdmin) {
$_SESSION['sessid']['roles'][] = 'global-admin';
}
echo 'Session ready';
} else {
$pages = [
'/users/password.php' => 'password.php',
'/users/totp.php' => 'totp.php',
'/list-virtual.php' => 'list-virtual.php',
'/edit.php' => 'edit.php',
'/app-passwords.php' => 'app-passwords.php',
'/users/app-passwords.php' => 'app-passwords.php',
'/totp-exceptions.php' => 'totp-exceptions.php',
'/users/totp-exceptions.php' => 'totp-exceptions.php',
];
if (!isset($pages[$path])) {
http_response_code(404);
exit;
}
// Both public aliases and user routes execute these complete controllers.
chdir(dirname(__DIR__, 2) . (in_array($path, ['/list-virtual.php', '/edit.php'], true) ? '/public' : '/public/users'));
require $pages[$path];
}