Files
postfixadmin/tests/TotpPfTest.php
T
Rodrigo Cortés Cano d92137719d Require reauthentication for TOTP removal (#1129)
- require a completed user or admin role before opening TOTP management
- remove TOTP through the existing password-verifying change path
- keep configured post-change hooks active when a secret is removed
- add regression coverage proving an invalid password cannot remove the stored secret

This is the first focused change for #1128.

thanks @TrapoSAMA
2026-09-02 20:23:26 +01:00

304 lines
13 KiB
PHP

<?php
use PHPUnit\Framework\TestCase;
class TotpPfTest extends TestCase
{
public function setUp(): void
{
global $CONF;
Config::write('encrypt', 'md5'); // need something stable and non-salted for this test.
$CONF['encrypt'] = 'md5';
db_execute("INSERT INTO domain(domain, description, transport) values ('example.com', 'test', 'foo')", [], true);
db_execute(
"INSERT INTO mailbox(username, password, name, maildir, local_part, domain, active) VALUES(:username, :password, :name, :maildir, :local_part, :domain, :active)",
[
'username' => 'test@example.com',
'password' => pacrypt('foobar'),
'name' => 'test user',
'maildir' => '/foo/bar',
'local_part' => 'test',
'domain' => 'example.com',
'active' => true,
]);
parent::setUp(); // TODO: Change the autogenerated stub
}
public function tearDown(): void
{
$this->cleanUp();
parent::tearDown(); // TODO: Change the autogenerated stub
}
private function cleanUp()
{
db_query('DELETE FROM alias');
db_query('DELETE FROM alias_domain');
db_query('DELETE FROM mailbox');
db_query('DELETE FROM domain_admins');
db_query('DELETE FROM admin');
db_query('DELETE FROM domain');
db_query('DELETE FROM totp_exception_address');
db_query('DELETE FROM mailbox_app_password');
unset($_SESSION['sessid']);
}
public function testBasicTotpStuff()
{
$x = new TotpPf('mailbox', new Login('mailbox'));
$array = $x->generate('test@example.com');
$this->assertIsArray($array);
$this->assertIsString($array[0]);
$this->assertIsString($array[1]);
$y = $x->checkUserTOTP('test@example.com', '123456');
$z = $x->checkTOTP('asdf', 'fakecode');
$this->assertFalse($y);
$this->assertFalse($z);
$totp = \OTPHP\TOTP::create('asdf');
$currentCode = $totp->now();
$this->assertNotEmpty($totp);
$this->assertTrue($x->checkTOTP('asdf', $currentCode));
$this->assertNotEmpty($currentCode);
}
public function testPasswordOnlyLoginRejectsAccountsUsingTotp(): void
{
global $CONF;
Config::write('totp', 'YES');
$CONF['totp'] = 'YES';
$totp = new TotpPf('mailbox', new Login('mailbox'));
$this->assertTrue($totp->passwordOnlyLogin('test@example.com', 'foobar'));
db_execute(
'UPDATE mailbox SET totp_secret = :secret WHERE username = :username',
['username' => 'test@example.com', 'secret' => 'existing-secret']
);
$this->assertFalse($totp->passwordOnlyLogin('test@example.com', 'foobar'));
$this->assertFalse($totp->passwordOnlyLogin('test@example.com', 'incorrect-password'));
}
public function testTotpRemovalRequiresCurrentPassword(): void
{
$totp = new TotpPf('mailbox', new Login('mailbox'));
db_execute(
'UPDATE mailbox SET totp_secret = :secret WHERE username = :username',
['username' => 'test@example.com', 'secret' => 'existing-secret']
);
try {
$totp->changeTOTP_secret('test@example.com', null, 'incorrect-password');
$this->fail('Removing TOTP with an invalid password must fail');
} catch (\Exception $e) {
$this->assertSame(Config::Lang('pPassword_password_current_text_error'), $e->getMessage());
}
$row = db_query_one(
'SELECT totp_secret FROM mailbox WHERE username = :username',
['username' => 'test@example.com']
);
$this->assertSame('existing-secret', $row['totp_secret']);
$this->assertTrue($totp->changeTOTP_secret('test@example.com', null, 'foobar'));
$row = db_query_one(
'SELECT totp_secret FROM mailbox WHERE username = :username',
['username' => 'test@example.com']
);
$this->assertNull($row['totp_secret']);
}
public function testDbOperations()
{
$x = new TotpPf('mailbox', new Login('mailbox'));
$this->assertNull($x->getException(1));
$this->assertTrue($x->addException('test@example.com', 'foobar', '1.2.3.4', 'another.test@example.com', 'test'));
}
/**
* Regression test for #1012: global admins with both 'admin' and 'global-admin'
* roles must not be downgraded to regular admin permissions.
*/
public function testGlobalAdminNotDowngradedInAddException()
{
// Set up a second domain that the admin does NOT manage
db_execute("INSERT INTO domain(domain, description, transport) values ('other.org', 'other domain', 'foo')", [], true);
db_execute(
"INSERT INTO admin(username, password, superadmin, active) VALUES(:username, :password, :superadmin, :active)",
[
'username' => 'admin@example.com',
'password' => pacrypt('adminpass'),
'superadmin' => true,
'active' => true,
]
);
db_execute(
"INSERT INTO domain_admins(username, domain, active) VALUES(:username, :domain, :active)",
[
'username' => 'admin@example.com',
'domain' => 'example.com',
'active' => true,
]
);
// Simulate global admin session (has BOTH roles, like real login)
$_SESSION['sessid'] = [
'username' => 'admin@example.com',
'roles' => ['admin', 'global-admin'],
];
$x = new TotpPf('admin', new Login('admin'));
// Global admin should be able to add exception for a domain they don't explicitly manage
$this->assertTrue(
$x->addException('admin@example.com', 'adminpass', '10.0.0.1', 'user@other.org', 'cross-domain test'),
'Global admin should be able to add TOTP exception for any domain'
);
}
/**
* Verify regular admin cannot add exception for domains they don't manage.
*/
public function testRegularAdminRestrictedToDomains()
{
db_execute("INSERT INTO domain(domain, description, transport) values ('other.org', 'other domain', 'foo')", [], true);
db_execute(
"INSERT INTO admin(username, password, superadmin, active) VALUES(:username, :password, :superadmin, :active)",
[
'username' => 'admin@example.com',
'password' => pacrypt('adminpass'),
'superadmin' => false,
'active' => true,
]
);
db_execute(
"INSERT INTO domain_admins(username, domain, active) VALUES(:username, :domain, :active)",
[
'username' => 'admin@example.com',
'domain' => 'example.com',
'active' => true,
]
);
// Regular admin - only 'admin' role, NOT 'global-admin'
$_SESSION['sessid'] = [
'username' => 'admin@example.com',
'roles' => ['admin'],
];
$x = new TotpPf('admin', new Login('admin'));
// Regular admin should NOT be able to add exception for unmanaged domain
$this->expectException(\Exception::class);
$x->addException('admin@example.com', 'adminpass', '10.0.0.2', 'user@other.org', 'should fail');
}
public function testDovecotQuery()
{
db_execute(
"INSERT INTO mailbox(username, password, name, maildir, local_part, domain, active) VALUES(:username, :password, :name, :maildir, :local_part, :domain, :active)",
[
'username' => 'test2@example.com',
'password' => pacrypt('foobar2'),
'name' => 'test2 user',
'maildir' => '/foo/bar2',
'local_part' => 'test2',
'domain' => 'example.com',
'active' => true,
]);
db_execute('INSERT INTO mailbox_app_password (username, description, password_hash) VALUES (:username, :description, :password_hash)', ['username' => 'test@example.com', 'description' => 'test foobar', 'password_hash' => pacrypt('foobar-app')]);
db_execute('INSERT INTO mailbox_app_password (username, description, password_hash) VALUES (:username, :description, :password_hash)', ['username' => 'test@example.com', 'description' => 'test foobar234', 'password_hash' => pacrypt('foobar234')]);
db_execute('INSERT INTO totp_exception_address (ip, username, description) VALUES (:ip, :username, :description)', ['ip' => '4.3.2.1', 'username' => 'test@example.com', 'description' => 'test 4.3.2.1']);
db_execute('INSERT INTO totp_exception_address (ip, username, description) VALUES (:ip, :username, :description)', ['ip' => '4.3.2.2', 'username' => 'test@example.com', 'description' => 'test 4.3.2.2']);
db_execute('INSERT INTO totp_exception_address (ip, username, description) VALUES (:ip, :username, :description)', ['ip' => '4.3.2.2', 'username' => 'test2@example.com', 'description' => 'test2 4.3.2.2']);
$checkIt = function (string $username, string $plain_password, string $ip, string $auth_type): bool {
$sql = /* @lang SQL */
<<<EOF
SELECT
m.username AS user,
m.password AS password,
CASE
WHEN m.username IS NOT NULL AND m.password = :password_hash AND (m.totp_secret IS NULL OR te.username IS NOT NULL) THEN 'mailbox_auth'
WHEN app.username IS NOT NULL AND app.password_hash = :password_hash THEN 'app_password_auth'
ELSE NULL
END AS auth_type
FROM
(SELECT :username AS search_username, :password_hash AS search_password, :client_ip AS client_ip) AS params
LEFT JOIN
mailbox m ON m.username = params.search_username AND m.active = :active
LEFT JOIN
mailbox_app_password app ON app.username = params.search_username AND app.password_hash = params.search_password
LEFT JOIN
totp_exception_address te ON te.username = params.search_username AND te.ip = params.client_ip
WHERE
(
m.username IS NOT NULL AND
m.password = params.search_password AND
(m.totp_secret IS NULL OR te.username IS NOT NULL)
)
OR (app.username IS NOT NULL AND app.password_hash = params.search_password)
LIMIT 1;
EOF;
$rows = db_query_all($sql, $values = [
'username' => $username,
'password_hash' => pacrypt($plain_password),
'client_ip' => $ip,
'active' => true,
]);
if (count($rows) != 1) {
//echo __FILE__ . " - FAIL " . count($rows) . " from " . json_encode($values);
return false;
}
$row = $rows[0];
$success = $row['user'] == $username && $row['auth_type'] == $auth_type;
//echo json_encode(['params' => $params, 'result' => $row]) . "\n";
return $success;
};
// ensure totp_secret is empty.
db_execute('UPDATE mailbox SET totp_secret = :secret WHERE username = :username', ['username' => 'test@example.com', 'secret' => null]);
$this->assertTrue($checkIt("test@example.com", "foobar", "irrelevant", "mailbox_auth"), "should auth on mailbox ");
$this->assertTrue($checkIt("test@example.com", "foobar-app", "irrelevant", "app_password_auth"), "should auth on mailbox_app_password");
$this->assertFalse($checkIt("test@example.com", "foobar-app-invalid", "irrelevant", "app_password_auth"), "should auth on mailbox_app_password");
$this->assertFalse($checkIt("test3@example.com", "foobar-app-invalid", "irrelevant", "app_password_auth"), "test3@example.com is an invalid user");
// let's turn 2fa support on for mailbox.
db_execute('UPDATE mailbox SET totp_secret = :secret WHERE username = :username', ['username' => 'test@example.com', 'secret' => 'something-not-empty']);
$this->assertTrue($checkIt("test@example.com", "foobar-app", "irrelevant", "app_password_auth"), "should work as 4.3.2.1 has an app password.");
$this->assertFalse($checkIt("test@example.com", "foobar", "irrelevant", "mailbox_auth"), "user has totp_secret, so should not work on standard auth");
// now see if the exception addresses work with 2fa.
$this->assertTrue($checkIt("test@example.com", "foobar", "4.3.2.1", "mailbox_auth"), "user has totp_secret, but client_ip is exceptional");
$this->assertFalse($checkIt("test@example.com", "foobar", "4.4.4.4", "mailbox_auth"), "user has totp_secret, but client_ip is not exceptional");
}
}