[Web][Postfix][Dovecot] Mail policies: compare addresses like Postfix, close bypasses via alias forms, temporary aliases, Sieve and cross-domain groups

This commit is contained in:
FreddleSpl0it committed 2026-11-07 17:51:27 +01:00
1 parent 4484cfcd42
commit 46c9ec90b0
22 files changed
+614 -141

No files matched your search

+5 -1
View File
@@ -2432,6 +2432,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) {
if ($address != $is_now['address']) {
// Send-as grants of groups follow the address
\Mailcow\MailboxGroup\MailboxGroupModule::fromGlobals()->api->addressRenamed($is_now['address'], $address);
\Mailcow\MailPolicy\MailPolicyModule::fromGlobals()->api->addressRenamed($is_now['address'], $address);
}
}
$_SESSION['return'][] = array(
@@ -3295,7 +3296,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) {
'mailbox_group_imap_grant' => ['owner'],
'mailbox_group_sogo_grant' => ['owner'],
'mailbox_group_sogo_acl' => ['c_uid'],
'mailbox_group_subscription' => ['username', 'owner']
'mailbox_group_subscription' => ['username', 'owner'],
'mail_policy_member' => ['username']
];
foreach ($tables as $table => $columns) {
foreach ($columns as $column) {
@@ -3311,6 +3313,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) {
\Mailcow\Imapsync\ImapsyncModule::fromGlobals()->sources->onAccountRenamed($old_username, $new_username);
// Group memberships and send-as grants follow, group aliases are rebuilt
\Mailcow\MailboxGroup\MailboxGroupModule::fromGlobals()->hooks->onMailboxRenamed($old_username, $new_username);
// Address entries of mail policies follow
\Mailcow\MailPolicy\MailPolicyModule::fromGlobals()->api->addressRenamed($old_username, $new_username);
// Update c_uid, c_name and mail in _sogo_static_view table
$pdo->prepare("UPDATE _sogo_static_view SET c_uid = :new_username, c_name = :new_username2, mail = :new_username3 WHERE c_uid = :old_username")
+6 -5
View File
@@ -500,11 +500,11 @@ function init_db_schema()
"description" => "VARCHAR(255) NOT NULL DEFAULT ''",
// all, internal or list; the entries are JSON lists of addresses, domains and group:<id>
"send_mode" => "VARCHAR(16) NOT NULL DEFAULT 'all'",
"send_allow" => "TEXT NOT NULL",
"send_block" => "TEXT NOT NULL",
"send_allow" => "MEDIUMTEXT NOT NULL",
"send_block" => "MEDIUMTEXT NOT NULL",
"receive_mode" => "VARCHAR(16) NOT NULL DEFAULT 'all'",
"receive_allow" => "TEXT NOT NULL",
"receive_block" => "TEXT NOT NULL",
"receive_allow" => "MEDIUMTEXT NOT NULL",
"receive_block" => "MEDIUMTEXT NOT NULL",
"reject_text" => "VARCHAR(255) NOT NULL DEFAULT ''",
"created" => "DATETIME(0) NOT NULL DEFAULT NOW(0)",
"modified" => "DATETIME ON UPDATE CURRENT_TIMESTAMP",
@@ -783,7 +783,8 @@ function init_db_schema()
"group_id" => array("group_id")
),
"key" => array(
"domain" => array("domain")
"domain" => array("domain"),
"internal" => array("internal", "active")
),
"fkey" => array(
"fk_alias_mailbox_group" => array(
@@ -75,10 +75,16 @@ class MailPolicyApiController
}
}
/** Answer for the Postfix policy service: DUNNO or the rejection */
public function check(string $sender, string $recipient, string $login, int $port): string
/** functions.mailbox.inc.php: a mailbox or alias was renamed */
public function addressRenamed(string $old, string $new): void
{
return $this->engine->check($sender, $recipient, $login, $port)->action();
$this->policies->addressRenamed($old, $new);
}
/** Answer for the Postfix policy service: DUNNO or the rejection */
public function check(string $sender, string $recipient, string $login, int $port, string $helo = ''): string
{
return $this->engine->check($sender, $recipient, $login, $port, $helo)->action();
}
/**
@@ -5,13 +5,15 @@ declare(strict_types=1);
namespace Mailcow\MailPolicy\Model;
/**
* Result of the policy check for one recipient: allowed, or refused by the send or receive part of a policy.
* Result of the policy check for one recipient: allowed, refused by the send or receive part of a policy, or refused
* because the recipient is written in a form the check cannot follow (routing through another address).
*/
class Decision
{
private const TEXT = [
'send' => 'Sending to this recipient is not allowed by the mail policy of the sender',
'receive' => 'This recipient does not accept mail from this sender',
'address' => 'This form of the recipient address is not allowed by the mail policy',
];
private function __construct(public readonly bool $allowed, public readonly string $side = '', public readonly ?Policy $policy = null)
@@ -23,16 +25,27 @@ class Decision
return new self(true);
}
/** $side send or receive */
public static function deny(string $side, Policy $policy): self
/** $side send or receive; without $policy the default text is used */
public static function deny(string $side, ?Policy $policy = null): self
{
return new self(false, $side, $policy);
}
/** The recipient routes through another address (user%domain, domain!user, a second @) */
public static function routedAddress(): self
{
return new self(false, 'address');
}
/** Text of the rejection: the text of the policy or the default */
public function text(): string
{
return ($this->policy !== null && $this->policy->rejectText !== '') ? $this->policy->rejectText : (self::TEXT[$this->side] ?? '');
return ($this->policy !== null && $this->policy->rejectText !== '') ? $this->policy->rejectText : self::defaultText($this->side);
}
public static function defaultText(string $side): string
{
return self::TEXT[$side] ?? '';
}
/** Answer for the Postfix policy protocol */
@@ -8,8 +8,8 @@ use Mailcow\Core\Repository;
use Mailcow\MailPolicy\Model\Policy;
/**
* Read-only lookups of the policy check: mailboxes, alias domains, groups and the active policies of a mailbox
* or group. Addresses are passed in lower case.
* Read-only lookups of the policy check: mailboxes, aliases, alias domains, groups and the active policies of a
* mailbox or group. Addresses are passed in lower case.
*/
class LookupRepository extends Repository
{
@@ -29,13 +29,33 @@ class LookupRepository extends Repository
return is_string($target) ? strtolower($target) : null;
}
/** A domain or alias domain of this mailcow */
/** A domain or alias domain Postfix delivers itself (as mysql_virtual_domains_maps.cf: active, no backup MX) */
public function isLocalDomain(string $domain): bool
{
return (bool)$this->query("SELECT 1 FROM `domain` WHERE `domain` = :d1 UNION SELECT 1 FROM `alias_domain` WHERE `alias_domain` = :d2",
return (bool)$this->query("SELECT 1 FROM `alias_domain` WHERE `alias_domain` = :d1 AND `active` = '1'
UNION SELECT 1 FROM `domain` WHERE `domain` = :d2 AND `active` = '1' AND `backupmx` = '0'",
['d1' => $domain, 'd2' => $domain])->fetchColumn();
}
/**
* Stored spelling of a mailbox, alias or temporary alias address. MySQL compares without case and accents, so
* Postfix delivers mail for chéf@ to chef@.
*/
public function storedAddress(string $address): ?string
{
$stored = $this->query("SELECT `username` FROM `mailbox` WHERE `username` = :a1 UNION SELECT `address` FROM `alias` WHERE `address` = :a2
UNION SELECT `address` FROM `spamalias` WHERE `address` = :a3 LIMIT 1", ['a1' => $address, 'a2' => $address, 'a3' => $address])->fetchColumn();
return is_string($stored) ? strtolower($stored) : null;
}
/** Stored spelling of a domain or alias domain, see storedAddress() */
public function storedDomain(string $domain): ?string
{
$stored = $this->query("SELECT `domain` FROM `domain` WHERE `domain` = :d1 UNION SELECT `alias_domain` FROM `alias_domain` WHERE `alias_domain` = :d2 LIMIT 1",
['d1' => $domain, 'd2' => $domain])->fetchColumn();
return is_string($stored) ? strtolower($stored) : null;
}
/** Active group with this distribution address */
public function groupByAddress(string $address): ?int
{
@@ -49,29 +69,59 @@ class LookupRepository extends Repository
return is_string($address) && $address !== '' ? strtolower($address) : null;
}
/** Member of an active group */
public function isGroupMember(int $groupId, string $username): bool
{
return (bool)$this->query("SELECT 1 FROM `mailbox_group_member` WHERE `group_id` = :id AND `username` = :username",
return (bool)$this->query("SELECT 1 FROM `mailbox_group_member` `gm` JOIN `mailbox_group` `g` ON `g`.`id` = `gm`.`group_id`
WHERE `gm`.`group_id` = :id AND `gm`.`username` = :username AND `g`.`active` = '1'",
['id' => $groupId, 'username' => $username])->fetchColumn();
}
/** Domain of an active alias that only accepts mail from its own domain (alias and group flag `internal`) */
public function internalAlias(string $address): ?string
/**
* What Postfix' virtual alias maps find for this key, in their order: an alias (also the own alias of a mailbox
* and the alias of a group address) or a temporary alias.
*
* @return array{kind: string, domain?: string, internal?: bool, owner?: string}|null
*/
public function aliasTarget(string $address): ?array
{
$domain = $this->query("SELECT `domain` FROM `alias` WHERE `address` = :address AND `internal` = '1' AND `active` = '1'",
$alias = $this->query("SELECT `domain`, `internal` FROM `alias` WHERE `address` = :address AND `active` IN ('1', '2')",
['address' => $address])->fetch();
if (is_array($alias)) {
return ['kind' => 'alias', 'domain' => strtolower((string)$alias['domain']), 'internal' => $alias['internal'] == '1'];
}
$owner = $this->query("SELECT `goto` FROM `spamalias` WHERE `address` = :address AND (`validity` >= UNIX_TIMESTAMP() OR `permanent` != 0)",
['address' => $address])->fetchColumn();
return is_string($domain) ? strtolower($domain) : null;
return is_string($owner) ? ['kind' => 'temporary', 'owner' => strtolower($owner)] : null;
}
/** @return Policy[] active policies of the mailbox: assigned to it or to an active group it is a member of */
/** An active catch-all alias of the domain has the internal flag (applies to the whole domain) */
public function internalCatchAll(string $domain): bool
{
return (bool)$this->query("SELECT 1 FROM `alias` WHERE `address` = :address AND `internal` = '1' AND `active` IN ('1', '2')",
['address' => '@' . $domain])->fetchColumn();
}
/** An active policy with members restricts sending */
public function hasSendRules(): bool
{
return (bool)$this->query("SELECT 1 FROM `mail_policy` `p` JOIN `mail_policy_member` `pm` ON `pm`.`policy_id` = `p`.`id`
WHERE `p`.`active` = '1' AND (`p`.`send_mode` != 'all' OR `p`.`send_block` != '[]') LIMIT 1")->fetchColumn();
}
/**
* @return Policy[] active policies of the mailbox: assigned to it or to an active group it is a member of; only
* policies of its own domain, so a group with members of other domains cannot restrict them
*/
public function policiesForMailbox(string $username): array
{
return $this->policies("SELECT DISTINCT `p`.* FROM `mail_policy` `p`
JOIN `mail_policy_member` `pm` ON `pm`.`policy_id` = `p`.`id`
WHERE `p`.`active` = '1' AND (`pm`.`username` = :u1 OR `pm`.`group_id` IN (
JOIN `mailbox` `m` ON `m`.`username` = :u1 AND `m`.`domain` = `p`.`domain`
WHERE `p`.`active` = '1' AND (`pm`.`username` = :u2 OR `pm`.`group_id` IN (
SELECT `gm`.`group_id` FROM `mailbox_group_member` `gm` JOIN `mailbox_group` `g` ON `g`.`id` = `gm`.`group_id`
WHERE `gm`.`username` = :u2 AND `g`.`active` = '1'))
ORDER BY `p`.`id`", ['u1' => $username, 'u2' => $username]);
WHERE `gm`.`username` = :u3 AND `g`.`active` = '1'))
ORDER BY `p`.`id`", ['u1' => $username, 'u2' => $username, 'u3' => $username]);
}
/** @return Policy[] active policies assigned to the group */
@@ -78,6 +78,26 @@ class PolicyRepository extends Repository
$this->query("DELETE FROM `mail_policy` WHERE `id` = :id", ['id' => $id]);
}
/** Address entries of all lists follow a renamed mailbox or alias */
public function renameAddress(string $old, string $new): void
{
$this->transaction(function () use ($old, $new): void {
$columns = ['send_allow', 'send_block', 'receive_allow', 'receive_block'];
foreach ($this->query("SELECT `id`, `" . implode('`, `', $columns) . "` FROM `mail_policy`")->fetchAll() as $row) {
$changed = [];
foreach ($columns as $column) {
$entries = json_decode((string)$row[$column], true);
if (is_array($entries) && in_array($old, $entries, true)) {
$changed[$column] = json_encode(array_values(array_unique(array_map(fn(string $entry): string => ($entry === $old) ? $new : $entry, $entries))));
}
}
if ($changed !== []) {
$this->updateRow('mail_policy', (int)$row['id'], $changed);
}
}
});
}
/** A primary domain (policies never belong to alias domains) */
public function isDomain(string $domain): bool
{
@@ -12,14 +12,23 @@ use Mailcow\MailPolicy\Repository\LookupRepository;
* Policy check of one recipient, asked by Postfix at RCPT TO (data/conf/rspamd/dynmaps/mailpolicy.php).
*
* Send part: the policies of the logged-in mailbox (assigned to it or to its groups) and of the mailbox the
* sender address belongs to. Receive part: the policies of the addressed mailbox (+tag and alias domains
* resolved), of the addressed group and the `internal` flag of the addressed alias or group. Mail sent to an
* alias or group reaches its members without their own policies. Every policy must allow the mail.
* sender address belongs to. Receive part: what Postfix delivers the recipient to, looked up in the order of its
* virtual alias maps (address, address without +tag, mailbox of an alias domain): the policies of the mailbox, of
* the group address or of the owner of a temporary alias, and the `internal` flag of the alias (a catch-all alias
* with the flag covers its whole domain). Mail sent to an alias or group reaches its members without their own
* policies. Every policy must allow the mail.
*
* Internal: a recipient in the domain of the policy or one of its alias domains; a sender logged in with a
* mailbox of that domain. Entries of a local domain or address count for logged-in senders only, so they cannot
* be forged; external entries are compared with the envelope sender. Dovecot submits Sieve redirects and
* vacation replies of a mailbox without login on port 588: they count as sent by that mailbox.
* be forged; block entries also match the envelope sender. External entries are compared with the envelope sender.
* Addresses are compared the way Postfix finds them: lower case, without trailing dot, in their stored spelling
* (MySQL ignores accents). Recipients routed through localhost (user%domain@localhost, domain!user@localhost,
* user@domain@localhost) are refused, Postfix would deliver them to the routed address.
*
* Dovecot submits Sieve redirects, vacation replies and notifications on port 588 without login, SOGo sends
* reminders with a service login: mail with the address of a mailbox counts as sent by that mailbox. Other mail of
* these services (bounces redirected with the null sender, Sieve rejects) has no known sender: it is checked like
* mail from outside and does not leave the mailcow while any policy restricts sending. Quota warnings pass.
*/
class PolicyEngine
{
@@ -27,27 +36,49 @@ class PolicyEngine
private const INTERNAL_PORTS = [590, 591];
/** Submission of SOGo and Dovecot, without login reachable from mailcow's own network only */
private const SERVICE_PORT = 588;
/** Domain of the Dovecot master login of mailcow's services (SOGo reminders) */
private const SERVICE_LOGIN_DOMAIN = 'mailcow.local';
/** HELO of the quota warning copies of Dovecot (quota_notify.py), configured by admins */
private const QUOTA_HELO = 'quotanotification';
/** Recipient without domain every server accepts (RFC 5321) */
private const POSTMASTER = 'postmaster';
/** Postfix delivers these destinations itself (mydestination), user%domain and domain!user route from there */
private const LOCAL_DESTINATIONS = ['localhost', 'localhost.localdomain'];
/** Lookups of the current check */
private array $cache = [];
public function __construct(private LookupRepository $lookup)
{
}
/** $login: SASL username, '' if not logged in; $port: smtpd port of the request, 0 if unknown */
public function check(string $sender, string $recipient, string $login, int $port = 0): Decision
/** $login: SASL username, '' if not logged in; $port: smtpd port of the request, 0 if unknown; $helo: HELO name */
public function check(string $sender, string $recipient, string $login, int $port = 0, string $helo = ''): Decision
{
$sender = self::address($sender);
$this->cache = [];
$recipient = self::address($recipient);
$login = self::address($login);
if (in_array($port, self::INTERNAL_PORTS, true) || $recipient === '') {
if (in_array($port, self::INTERNAL_PORTS, true) || $recipient === '' || $recipient === self::POSTMASTER) {
return Decision::allow();
}
$account = ($login !== '') ? $this->lookup->mailbox($login) : null;
if ($login === '' && $port === self::SERVICE_PORT) {
// Sieve redirects and vacation replies use the address of the mailbox, other mail of mailcow passes
$account = $this->lookup->mailbox($this->resolve(self::untagged($sender)));
if ($account === null) {
if (self::isRouted($recipient)) {
return Decision::routedAddress();
}
$recipient = $this->stored($recipient);
$sender = $this->stored(self::address($sender));
$login = self::address($login);
$serviceLogin = self::domainOf($login) === self::SERVICE_LOGIN_DOMAIN;
$account = null;
if ($login !== '' && !$serviceLogin) {
$account = $this->cached('mailbox', $login);
} elseif ($serviceLogin || $port === self::SERVICE_PORT) {
if ($port === self::SERVICE_PORT && !$serviceLogin && strtolower($helo) === self::QUOTA_HELO) {
return Decision::allow();
}
// without a mailbox sender the sending mailbox is unknown
$account = $this->senderMailbox($sender);
if ($account === null && !$this->cached('isLocalDomain', self::domainOf($recipient)) && $this->lookup->hasSendRules()) {
return Decision::deny('send');
}
}
foreach ($this->sendingPolicies($account, $sender) as $policy) {
if (!$this->allows($policy->sendMode, $policy->sendAllow, $policy->sendBlock, $this->isInternalRecipient($recipient, $policy->domain),
@@ -58,18 +89,18 @@ class PolicyEngine
foreach ($this->receivingPolicies($recipient) as $policy) {
if (!$this->allows($policy->receiveMode, $policy->receiveAllow, $policy->receiveBlock,
$account !== null && $account['domain'] === $policy->domain,
fn(string $entry): bool => $this->senderMatches($entry, $sender, $account))) {
fn(string $entry, bool $block): bool => $this->senderMatches($entry, $sender, $account, $block))) {
return Decision::deny('receive', $policy);
}
}
return Decision::allow();
}
/** Blocked entries first; then the mode decides */
/** Blocked entries first; then the mode decides. $matches($entry, $block) */
private function allows(string $mode, array $allow, array $block, bool $internal, callable $matches): bool
{
foreach ($block as $entry) {
if ($matches($entry)) {
if ($matches($entry, true)) {
return false;
}
}
@@ -83,13 +114,19 @@ class PolicyEngine
private function any(array $entries, callable $matches): bool
{
foreach ($entries as $entry) {
if ($matches($entry)) {
if ($matches($entry, false)) {
return true;
}
}
return false;
}
/** @return array{username: string, domain: string}|null mailbox of the sender address */
private function senderMailbox(string $sender): ?array
{
return str_contains($sender, '@') ? $this->cached('mailbox', $this->resolve(self::untagged($sender))) : null;
}
/** @return Policy[] of the logged-in mailbox and of the mailbox it sends as */
private function sendingPolicies(?array $account, string $sender): array
{
@@ -97,36 +134,65 @@ class PolicyEngine
return [];
}
$policies = $this->lookup->policiesForMailbox($account['username']);
$sentAs = $this->lookup->mailbox($this->resolve(self::untagged($sender)));
$sentAs = $this->senderMailbox($sender);
if ($sentAs !== null && $sentAs['username'] !== $account['username']) {
$policies = array_merge($policies, $this->lookup->policiesForMailbox($sentAs['username']));
}
return self::unique($policies);
}
/** @return Policy[] of the addressed mailbox, group and internal alias */
/** @return Policy[] of what Postfix delivers the recipient to, see the class comment */
private function receivingPolicies(string $recipient): array
{
$address = $this->resolve(self::untagged($recipient));
$policies = [];
if ($this->lookup->mailbox($address) !== null) {
$policies = $this->lookup->policiesForMailbox($address);
// the address, then without +tag; an alias domain maps to the mailbox in its target domain and Postfix
// looks up the result again with the +tag
[$address, $target] = $this->aliasTarget([$recipient, self::untagged($recipient)]);
$resolved = $this->resolve($recipient);
if ($target === null && $resolved !== $recipient) {
[$address, $target] = $this->aliasTarget([$resolved, self::untagged($resolved)]);
}
$address ??= self::untagged($resolved);
if (($target['kind'] ?? '') === 'temporary') {
$address = $target['owner'];
}
$policies = ($this->cached('mailbox', $address) !== null) ? $this->lookup->policiesForMailbox($address) : [];
$group = $this->lookup->groupByAddress($address);
if ($group !== null) {
$policies = array_merge($policies, $this->lookup->policiesForGroup($group));
}
$aliasDomain = $this->lookup->internalAlias($address);
if ($aliasDomain !== null) {
// the `internal` flag of an alias or group: only senders of its domain
$internal = new Policy();
$internal->domain = $aliasDomain;
$internal->receiveMode = 'internal';
$policies[] = $internal;
// the `internal` flag of an alias or group: only senders of its domain
if (!empty($target['internal'])) {
$policies[] = $this->internalRule($target['domain']);
}
foreach (array_unique([self::domainOf($recipient), $this->resolveDomain(self::domainOf($recipient))]) as $domain) {
if ($this->lookup->internalCatchAll($domain)) {
$policies[] = $this->internalRule($domain);
}
}
return self::unique($policies);
}
/** @return array{0: ?string, 1: ?array} the first key Postfix' virtual alias maps find, with what they find */
private function aliasTarget(array $keys): array
{
foreach (array_unique($keys) as $key) {
$target = $this->lookup->aliasTarget($key);
if ($target !== null) {
return [$key, $target];
}
}
return [null, null];
}
/** Receive rule of the `internal` flag */
private function internalRule(string $domain): Policy
{
$policy = new Policy();
$policy->domain = $this->resolveDomain($domain);
$policy->receiveMode = 'internal';
return $policy;
}
private function isInternalRecipient(string $recipient, string $domain): bool
{
return $this->resolveDomain(self::domainOf($recipient)) === $domain;
@@ -137,8 +203,8 @@ class PolicyEngine
$address = $this->resolve(self::untagged($recipient));
if (str_starts_with($entry, 'group:')) {
$id = (int)substr($entry, 6);
return $this->lookup->groupAddress($id) === $address
|| ($this->lookup->mailbox($address) !== null && $this->lookup->isGroupMember($id, $address));
return $this->cached('groupAddress', $id) === $address
|| ($this->cached('mailbox', $address) !== null && $this->cached('isGroupMember', $id, $address));
}
if (str_contains($entry, '@')) {
return $this->resolve($entry) === $address;
@@ -146,35 +212,69 @@ class PolicyEngine
return $this->resolveDomain(self::domainOf($address)) === $this->resolveDomain($entry);
}
private function senderMatches(string $entry, string $sender, ?array $account): bool
/** $block: a block entry, which also matches the envelope sender (refusing a forged sender is no risk) */
private function senderMatches(string $entry, string $sender, ?array $account, bool $block): bool
{
$address = $this->resolve(self::untagged($sender));
// the sender address of a local entry only counts when logged in: Postfix checked that the login may use it
$useAddress = $account !== null || $block;
if (str_starts_with($entry, 'group:')) {
$id = (int)substr($entry, 6);
return $account !== null && ($this->lookup->isGroupMember($id, $account['username']) || $this->lookup->groupAddress($id) === $address);
return ($account !== null && $this->cached('isGroupMember', $id, $account['username']))
|| ($useAddress && ($this->cached('groupAddress', $id) === $address
|| ($this->cached('mailbox', $address) !== null && $this->cached('isGroupMember', $id, $address))));
}
if (str_contains($entry, '@')) {
// a local address only for a logged-in sender (Postfix checked that the login may use it)
return $this->lookup->isLocalDomain(self::domainOf($entry))
? $account !== null && ($account['username'] === $this->resolve($entry) || $address === $this->resolve($entry))
return $this->cached('isLocalDomain', self::domainOf($entry))
? ($account !== null && $account['username'] === $this->resolve($entry)) || ($useAddress && $address === $this->resolve($entry))
: self::untagged($sender) === $entry;
}
return $this->lookup->isLocalDomain($entry)
? $account !== null && ($account['domain'] === $this->resolveDomain($entry) || $this->resolveDomain(self::domainOf($address)) === $this->resolveDomain($entry))
return $this->cached('isLocalDomain', $entry)
? ($account !== null && $account['domain'] === $this->resolveDomain($entry))
|| ($useAddress && $this->resolveDomain(self::domainOf($address)) === $this->resolveDomain($entry))
: self::domainOf($sender) === $entry;
}
/**
* Stored spelling of an address of this mailcow: Postfix finds chéf@ as chef@ (MySQL ignores accents). Only
* addresses with non-ASCII characters can differ, as they are already in lower case.
*/
private function stored(string $address): string
{
if (!preg_match('/[\x80-\xff]/', $address) || !str_contains($address, '@')) {
return $address;
}
foreach (array_unique([$address, self::untagged($address)]) as $key) {
$stored = $this->cached('storedAddress', $key);
if ($stored !== null) {
return $stored;
}
}
$domain = $this->cached('storedDomain', self::domainOf($address));
return ($domain === null) ? $address : substr($address, 0, strrpos($address, '@') + 1) . $domain;
}
/** Address in an alias domain as the address in its target domain */
private function resolve(string $address): string
{
$domain = self::domainOf($address);
$target = ($domain !== '') ? $this->lookup->aliasDomainTarget($domain) : null;
$target = ($domain !== '') ? $this->cached('aliasDomainTarget', $domain) : null;
return ($target === null) ? $address : substr($address, 0, strrpos($address, '@') + 1) . $target;
}
private function resolveDomain(string $domain): string
{
return ($domain === '') ? '' : ($this->lookup->aliasDomainTarget($domain) ?? $domain);
return ($domain === '') ? '' : ($this->cached('aliasDomainTarget', $domain) ?? $domain);
}
/** A lookup, done once per check: long lists ask the same domains and groups again */
private function cached(string $method, int|string ...$args): mixed
{
$key = $method . "\0" . implode("\0", $args);
if (!array_key_exists($key, $this->cache)) {
$this->cache[$key] = $this->lookup->$method(...$args);
}
return $this->cache[$key];
}
/** @param Policy[] $policies @return Policy[] without repeated policies */
@@ -182,16 +282,32 @@ class PolicyEngine
{
$unique = [];
foreach ($policies as $policy) {
$unique[$policy->id ?? spl_object_id($policy)] = $policy;
$unique[$policy->id ?? 'internal:' . $policy->domain] = $policy;
}
return array_values($unique);
}
/** Lower case address without angle brackets; '' unless local@domain */
/** Lower case, without angle brackets, quotes and trailing dot of the domain, as Postfix resolves it; '' = null sender */
private static function address(string $value): string
{
$value = strtolower(trim($value, " \t\r\n<>"));
return preg_match('/^[^@\s,<>]+@[^@\s,<>]+$/', $value) ? $value : '';
$at = strrpos($value, '@');
return ($at === false) ? $value : str_replace('"', '', substr($value, 0, $at)) . '@' . rtrim(substr($value, $at + 1), '.');
}
/**
* Postfix would deliver the recipient elsewhere: no domain, or routing through a local destination
* (localhost, the IP of the server) with %, ! or a second @ in the local part
*/
private static function isRouted(string $address): bool
{
$at = strrpos($address, '@');
if ($at === false || $at === 0 || $at === strlen($address) - 1) {
return true;
}
$domain = substr($address, $at + 1);
return (in_array($domain, self::LOCAL_DESTINATIONS, true) || str_starts_with($domain, '['))
&& strpbrk(substr($address, 0, $at), '@%!') !== false;
}
private static function untagged(string $address): string
@@ -8,6 +8,7 @@ use Mailcow\Core\AccessDenied;
use Mailcow\Core\Context;
use Mailcow\Core\Input;
use Mailcow\Core\UserError;
use Mailcow\MailPolicy\Model\Decision;
use Mailcow\MailPolicy\Model\Policy;
use Mailcow\MailPolicy\Repository\PolicyRepository;
@@ -17,7 +18,8 @@ use Mailcow\MailPolicy\Repository\PolicyRepository;
* Read: admins all policies (also read-only API keys); domain admins with the `mail_policies` ACL the policies
* of their domains.
* Edit: admins; domain admins with the ACL for policies of their domains. A policy is assigned to mailboxes and
* groups of its own domain; `group:<id>` entries name groups the editor may access.
* groups of its own domain; `group:<id>` entries name groups of that domain. Groups need the `mailbox_groups`
* ACL as well: without it a domain admin sees no groups and keeps the group entries and assignments.
*/
class PolicyService
{
@@ -94,10 +96,21 @@ class PolicyService
return $policy;
}
/** Address entries of the lists follow a renamed mailbox or alias; called after the rename, without permission check */
public function addressRenamed(string $old, string $new): void
{
$this->repo->renameAddress(strtolower($old), strtolower($new));
}
/** @return array[] id, name, domain, address of the groups in these domains (choices of the forms) */
public function groupChoices(array $domains): array
{
return $this->canRead() ? $this->repo->groupsIn($domains) : [];
return ($this->canRead() && $this->canUseGroups()) ? $this->repo->groupsIn($domains) : [];
}
private function canUseGroups(): bool
{
return $this->context->hasAdminRights() || $this->context->hasAcl('mailbox_groups');
}
/**
@@ -116,21 +129,23 @@ class PolicyService
if (($sender !== '' && !filter_var($sender, FILTER_VALIDATE_EMAIL)) || !filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
throw new UserError('mail_policy_test_invalid');
}
// domain admins test mail of their domains
if (!$this->context->hasAdminRights() && !$this->context->canAccessDomain(self::domainOf($sender))
&& !$this->context->canAccessDomain(self::domainOf($recipient))) {
// domain admins test mail of their domains; a sender of another domain counts as not logged in
$ownSender = $this->context->hasAdminRights() || $this->context->canAccessDomain(self::domainOf($sender));
if (!$ownSender && !$this->context->canAccessDomain(self::domainOf($recipient))) {
throw new AccessDenied();
}
$login = ($loggedIn && $this->repo->mailboxDomain($sender) !== null) ? $sender : '';
$login = ($loggedIn && $ownSender && $this->repo->mailboxDomain($sender) !== null) ? $sender : '';
$decision = $this->engine->check($sender, $recipient, $login);
$policy = $decision->policy;
$hidden = $policy !== null && $policy->id !== null && !$this->visible($policy);
return [
'allowed' => (int)$decision->allowed,
'side' => $decision->side,
'policy' => ($policy !== null && $policy->id !== null && $this->visible($policy)) ? $policy->name : null,
'policy' => ($policy !== null && $policy->id !== null && !$hidden) ? $policy->name : null,
'internal_alias' => (int)($policy !== null && $policy->id === null),
'logged_in' => (int)($login !== ''),
'text' => $decision->allowed ? '' : $decision->text(),
// the text of a policy of another domain stays hidden
'text' => $decision->allowed ? '' : ($hidden ? Decision::defaultText($decision->side) : $decision->text()),
];
}
@@ -189,17 +204,26 @@ class PolicyService
$policy->$property = in_array($mode, Policy::MODES, true) ? $mode : throw new UserError('mail_policy_mode_invalid');
}
}
$groupAccess = $this->canUseGroups();
foreach (self::LISTS as $key => $property) {
// the UI sends the groups of a list separately (<list>_groups); the API may name them as group:<id>
if (array_key_exists($key, $input) || array_key_exists($key . '_groups', $input)) {
$entries = array_key_exists($key, $input) ? self::values($input[$key])
: array_filter($policy->$property, fn(string $entry): bool => !str_starts_with($entry, 'group:'));
if (array_key_exists($key . '_groups', $input)) {
$entries = array_filter($entries, fn(string $entry): bool => !str_starts_with(strtolower($entry), 'group:'));
$entries = array_merge($entries, array_map(fn(string $id): string => 'group:' . $id, self::values($input[$key . '_groups'])));
}
$policy->$property = $this->entries(array_values($entries));
if (!array_key_exists($key, $input) && !array_key_exists($key . '_groups', $input)) {
continue;
}
$entries = array_key_exists($key, $input) ? self::values($input[$key]) : self::withoutGroups($policy->$property);
$kept = [];
if (!$groupAccess) {
// without access to groups the group entries stay (also when sent back unchanged); the form shows no group choices
$kept = array_values(array_diff($policy->$property, self::withoutGroups($policy->$property)));
$entries = array_values(array_diff(array_map('strtolower', $entries), $kept));
} elseif (array_key_exists($key . '_groups', $input)) {
$entries = array_merge(self::withoutGroups($entries), array_map(fn(string $id): string => 'group:' . $id, self::values($input[$key . '_groups'])));
}
$entries = array_values(array_unique(array_merge($this->entries($entries, $policy->domain, $groupAccess), $kept)));
if (count($entries) > self::MAX_ENTRIES) {
throw new UserError('mail_policy_entries_exceeded', [self::MAX_ENTRIES]);
}
$policy->$property = $entries;
}
if (array_key_exists('reject_text', $input)) {
$text = Input::text($input['reject_text']);
@@ -213,7 +237,7 @@ class PolicyService
}
if (array_key_exists('mailboxes', $input)) {
$policy->mailboxes = [];
foreach (self::values($input['mailboxes']) as $username) {
foreach (self::limited($input['mailboxes']) as $username) {
$username = strtolower($username);
if ($this->repo->mailboxDomain($username) !== $policy->domain) {
throw new UserError('mail_policy_member_invalid', [htmlspecialchars($username)]);
@@ -222,9 +246,19 @@ class PolicyService
}
$policy->mailboxes = array_values($policy->mailboxes);
}
if (array_key_exists('groups', $input)) {
// without access to groups the assignments stay; only sending them back unchanged is accepted
if (array_key_exists('groups', $input) && !$groupAccess && self::values($input['groups']) !== []) {
$sent = array_map('intval', self::values($input['groups']));
$stored = $policy->groups;
sort($sent);
sort($stored);
if (array_values(array_unique($sent)) !== $stored) {
throw new AccessDenied();
}
}
if (array_key_exists('groups', $input) && $groupAccess) {
$policy->groups = [];
foreach (self::values($input['groups']) as $value) {
foreach (self::limited($input['groups']) as $value) {
$id = Input::intInRange($value, 1, PHP_INT_MAX);
if ($id === null || $this->repo->groupDomain($id) !== $policy->domain) {
throw new UserError('mail_policy_member_invalid', [htmlspecialchars($value)]);
@@ -236,20 +270,20 @@ class PolicyService
}
/**
* Entries of a list: addresses, domains (a leading @ is dropped) and group:<id>, lower case, without repeats.
* Entries of a list: addresses, domains (a leading @ is dropped) and group:<id> of a group of the policy's
* domain, lower case, without repeats.
*
* @param string[] $values
* @return string[]
* @throws UserError
*/
private function entries(mixed $value): array
private function entries(array $values, string $domain, bool $groupAccess): array
{
$entries = [];
foreach (self::values($value) as $entry) {
$entry = strtolower($entry);
foreach (self::limited(array_map('strtolower', $values)) as $entry) {
if (str_starts_with($entry, 'group:')) {
$id = Input::intInRange(substr($entry, 6), 1, PHP_INT_MAX);
$domain = ($id === null) ? null : $this->repo->groupDomain($id);
if ($domain === null || (!$this->context->hasAdminRights() && !$this->context->canAccessDomain($domain))) {
if (!$groupAccess || $id === null || $this->repo->groupDomain($id) !== $domain) {
throw new UserError('mail_policy_entry_invalid', [htmlspecialchars($entry)]);
}
$entry = 'group:' . $id;
@@ -265,10 +299,28 @@ class PolicyService
}
$entries[$entry] = $entry;
}
if (count($entries) > self::MAX_ENTRIES) {
return array_values($entries);
}
/**
* Values of a list field without repeats, at most MAX_ENTRIES (checked before anything is looked up)
*
* @return string[]
* @throws UserError
*/
private static function limited(mixed $value): array
{
$values = array_values(array_unique(self::values($value)));
if (count($values) > self::MAX_ENTRIES) {
throw new UserError('mail_policy_entries_exceeded', [self::MAX_ENTRIES]);
}
return array_values($entries);
return $values;
}
/** @return string[] entries without group:<id> */
private static function withoutGroups(array $entries): array
{
return array_values(array_filter($entries, fn(string $entry): bool => !str_starts_with(strtolower($entry), 'group:')));
}
/**