diff --git a/README.md b/README.md index 0d8c0c7..bb821dd 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ Each mailbox receives a unique 15-character Feedback Loop sender ID. Rspamd adds Google FBL reporting requires mail to be DKIM-signed by a domain verified in Google Postmaster Tools. Publish the sending IPs in SPF and ensure the IPs have valid PTR records; FBL reports apply only to Gmail recipients. -Configure DKIM signing maps by replacing the example hostname and token in `/etc/rspamd/local.d/arc.conf` and `/etc/rspamd/local.d/dkim_signing.conf` with the same hostname and token used for the other Rspamd maps. An RSA DKIM key is generated automatically when a domain is added. The domain editor shows the selector and public DNS TXT record to publish; regenerating the key changes the selector and requires updating that record. Private keys are stored in the database and should be protected accordingly. +Configure the DKIM signing map by replacing the example hostname and token in `/etc/rspamd/local.d/dkim_signing.conf` with the same hostname and token used for the other Rspamd maps. ARC/DKIM signing uses the local Redis instance (`127.0.0.1:6379`) via the `php-redis` extension, with Redis hashes `dkim_keys` and `dkim_selectors`; the installation script installs the extension. ARC signing is enabled for authenticated, local, and inbound messages, using the recipient's hosted domain for inbound ARC seals. The database-backed ARC hashes are synchronized during setup, when a domain is added/updated or a key is regenerated, and by the five-minute cron job. An RSA DKIM key is generated automatically when a domain is added. The domain editor shows the selector and public DNS TXT record to publish; regenerating the key changes the selector and requires updating that record. Private keys are stored in the database and Redis and should be protected accordingly. The authenticated-user ratelimit map is configured in `/etc/rspamd/custom_ratelimit.lua`; replace its example hostname and token with your map endpoint settings. Accounts registered within the last 14 days receive lower sending limits. A mailbox marked as trusted in the admin editor receives higher limits; other authenticated mailboxes receive the default limits. diff --git a/common_config.php b/common_config.php index 600a0d4..832188a 100644 --- a/common_config.php +++ b/common_config.php @@ -14,6 +14,8 @@ const INACTIVITY_PERIOD_MONTHS = [1, 6, 12, 24]; // Allowed inactivity periods i const DEFAULT_INACTIVITY_PERIOD = 12; // Default inactivity period in months const ALLOW_ACCOUNT_NEVER_DELETE = false; // Whether to allow users to set their inactivity period to "never delete" const RSPAMD_SETTINGS_MAP_TOKEN = 'CHANGE_ME_TO_A_LONG_RANDOM_SECRET'; // Token used to authenticate requests to the Rspamd settings map endpoint +const RSPAMD_REDIS_HOST = '127.0.0.1'; // Redis server used by Rspamd +const RSPAMD_REDIS_PORT = 6379; // Redis port used by Rspamd const SPAM_REJECT_SCORE_OPTIONS = [0, 5, 8, 10, 12, 15, 20, 25, 30]; // Allowed spam reject scores const DEFAULT_SPAM_REJECT_SCORE = 15; // Default spam reject score const CUSTOM_RSPAMD_SETTINGS = ''; // Custom Rspamd settings to be added to the Rspamd settings map diff --git a/composer.json b/composer.json index 00a1a05..b886f09 100644 --- a/composer.json +++ b/composer.json @@ -4,6 +4,7 @@ "ext-mbstring": "*", "ext-pdo": "*", "ext-openssl": "*", + "ext-redis": "*", "ext-gnupg": "*", "ext-gettext": "*", "ext-intl": "*", diff --git a/cron.php b/cron.php index 3c8347a..f2da814 100644 --- a/cron.php +++ b/cron.php @@ -4,6 +4,7 @@ if ( php_sapi_name() !== 'cli' ) { } require_once 'common_config.php'; +require_once 'tools/sync_rspamd_dkim_keys.php'; $db = get_db_instance(); try { $db_prosody = new PDO( 'mysql:host=' . DBHOST_PROSODY . ';dbname=' . DBNAME_PROSODY, DBUSER_PROSODY, DBPASS_PROSODY, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ] ); @@ -86,3 +87,11 @@ while ( $tmp = $stmt->fetch( PDO::FETCH_ASSOC ) ) { } // delete squirrelmail attachments older than an hour exec( 'find /var/local/squirrelmail/attach/ -type f -cmin +60 -delete' ); +try { + $count = sync_rspamd_dkim_keys( $db ); + echo sprintf( "Synchronized %d DKIM signing keys to Redis.\n", $count ); +} catch ( PDOException | RuntimeException $exception ) { + error_log( 'Failed to synchronize DKIM signing keys: ' . $exception->getMessage() ); + echo _('Error synchronizing DKIM signing keys:') . PHP_EOL; + echo $exception->getMessage() . PHP_EOL; +} diff --git a/etc/rspamd/local.d/arc.conf b/etc/rspamd/local.d/arc.conf index f7d0f6a..f130f04 100644 --- a/etc/rspamd/local.d/arc.conf +++ b/etc/rspamd/local.d/arc.conf @@ -1,4 +1,8 @@ sign_authenticated = true; sign_local = true; -signing_table = "https://mail.danwin1210.de/rspamd_dkim_keys.php?token=CHANGE_ME_TO_A_LONG_RANDOM_SECRET"; -key_table = "https://mail.danwin1210.de/rspamd_dkim_keys.php?token=CHANGE_ME_TO_A_LONG_RANDOM_SECRET"; +sign_inbound = true; +use_domain = "header"; +use_domain_sign_inbound = "recipient"; +use_redis = true; +key_prefix = "dkim_keys"; +selector_prefix = "dkim_selectors"; diff --git a/etc/rspamd/local.d/dkim_signing.conf b/etc/rspamd/local.d/dkim_signing.conf index 24a88f6..1f2832f 100644 --- a/etc/rspamd/local.d/dkim_signing.conf +++ b/etc/rspamd/local.d/dkim_signing.conf @@ -3,7 +3,7 @@ use_domain_sign_networks = "header"; use_domain_sign_local = "header"; allow_username_mismatch = true; allow_hdrfrom_mismatch = true; -try_fallback = false; sign_headers = "(o)from:(x)sender:(o)reply-to:(o)subject:(x)date:(x)message-id:(o)to:(o)cc:(x)mime-version:(x)content-type:(x)content-transfer-encoding:resent-to:resent-cc:resent-from:resent-sender:resent-message-id:(x)in-reply-to:(x)references:list-id:list-help:list-owner:list-unsubscribe:list-unsubscribe-post:list-subscribe:list-post:(x)openpgp:(x)autocrypt:feedback-id"; -signing_table = "https://mail.danwin1210.de/rspamd_dkim_keys.php?token=CHANGE_ME_TO_A_LONG_RANDOM_SECRET"; -key_table = "https://mail.danwin1210.de/rspamd_dkim_keys.php?token=CHANGE_ME_TO_A_LONG_RANDOM_SECRET"; +use_redis = true; +key_prefix = "dkim_keys"; +selector_prefix = "dkim_selectors"; diff --git a/install_binaries.sh b/install_binaries.sh index 2a1b24a..ac9b8fe 100755 --- a/install_binaries.sh +++ b/install_binaries.sh @@ -8,7 +8,7 @@ workingdir=$(pwd) # install all required packages DEBIAN_FRONTEND=noninteractive apt-get update -DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends install -y apt-transport-tor bash-completion bind9 ca-certificates clamav-daemon clamav-freshclam curl dovecot-imapd dovecot-lmtpd dovecot-managesieved dovecot-mysql dovecot-pop3d dovecot-sieve git gnupg haveged iptables libnginx-mod-http-brotli-filter libsasl2-modules locales locales-all logrotate lsb-release lua-dbi-mysql lua-event lua-unbound mariadb-server mercurial nano nginx openssl patch php8.2-cli php8.2-curl php8.2-fpm php8.2-gd php8.2-gmp php8.2-gnupg php8.2-imap php8.2-intl php8.2-mbstring php8.2-mysql php8.2-pspell php8.2-readline php8.2-tidy php8.2-uuid php8.2-xml php8.2-zip postfix postfix-mysql prosody redis rng-tools5 rspamd tor vim wget unzip wireguard wireguard-tools +DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends install -y apt-transport-tor bash-completion bind9 ca-certificates clamav-daemon clamav-freshclam curl dovecot-imapd dovecot-lmtpd dovecot-managesieved dovecot-mysql dovecot-pop3d dovecot-sieve git gnupg haveged iptables libnginx-mod-http-brotli-filter libsasl2-modules locales locales-all logrotate lsb-release lua-dbi-mysql lua-event lua-unbound mariadb-server mercurial nano nginx openssl patch php8.2-cli php8.2-curl php8.2-fpm php8.2-gd php8.2-gmp php8.2-gnupg php8.2-imap php8.2-intl php8.2-mbstring php8.2-mysql php8.2-pspell php8.2-readline php8.2-redis php8.2-tidy php8.2-uuid php8.2-xml php8.2-zip postfix postfix-mysql prosody redis rng-tools5 rspamd tor vim wget unzip wireguard wireguard-tools # install composer curl -sSL https://github.com/composer/composer/releases/download/2.8.3/composer.phar > /usr/bin/composer diff --git a/setup.php b/setup.php index e61385d..2c39290 100644 --- a/setup.php +++ b/setup.php @@ -3,7 +3,7 @@ if(!extension_loaded('gettext')){ die('The gettext extension of PHP is required. Please install it first.' . PHP_EOL); } require('common_config.php'); -foreach(['pdo_mysql', 'mbstring', 'pcre', 'gnupg', 'intl', 'openssl'] as $required_extension) { +foreach(['pdo_mysql', 'mbstring', 'pcre', 'gnupg', 'intl', 'openssl', 'redis'] as $required_extension) { if ( ! extension_loaded( $required_extension ) ) { die( sprintf( _( 'The %s extension of PHP is required. Please install it first.' ), $required_extension ) . PHP_EOL ); } diff --git a/tools/sync_rspamd_dkim_keys.php b/tools/sync_rspamd_dkim_keys.php new file mode 100644 index 0000000..6933034 --- /dev/null +++ b/tools/sync_rspamd_dkim_keys.php @@ -0,0 +1,75 @@ +query( "SELECT domain, dkim_key, dkim_selector FROM `domain` WHERE active = 1 ORDER BY domain;" ); + $domains = []; + while ( $domain = $stmt->fetch( PDO::FETCH_ASSOC ) ) { + if ( empty($domain[ 'dkim_key' ]) || empty($domain[ 'dkim_selector' ]) || str_ends_with($domain['domain'], '.onion') ) { + continue; + } + + $asciiDomain = idn_to_ascii( $domain[ 'domain' ], IDNA_NONTRANSITIONAL_TO_ASCII ); + if ( ! is_string( $asciiDomain ) || ! preg_match( '/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/iD', $asciiDomain ) ) { + throw new RuntimeException( 'Invalid domain configured for DKIM signing: ' . $domain[ 'domain' ] ); + } + $asciiDomain = strtolower( $asciiDomain ); + if ( isset( $domains[ $asciiDomain ] ) ) { + throw new RuntimeException( 'Duplicate ASCII domain configured for DKIM signing: ' . $asciiDomain ); + } + $privateKey = openssl_pkey_get_private( $domain[ 'dkim_key' ] ); + $keyDetails = $privateKey === false ? false : openssl_pkey_get_details( $privateKey ); + if ( ! preg_match( '/^[a-zA-Z0-9_-]+$/D', $domain[ 'dkim_selector' ] ) || $keyDetails === false || $keyDetails[ 'type' ] !== OPENSSL_KEYTYPE_RSA ) { + throw new RuntimeException( 'Invalid DKIM signing selector or private key for domain: ' . $asciiDomain ); + } + $domains[ $asciiDomain ] = [ + 'key' => $domain[ 'dkim_key' ], + 'selector' => $domain[ 'dkim_selector' ], + ]; + } + + $redis = new Redis(); + + try { + if ( ! $redis->connect( RSPAMD_REDIS_HOST, RSPAMD_REDIS_PORT, 3.0 ) ) { + throw new RuntimeException( 'Could not connect to Rspamd Redis.' ); + } + if ( ! $redis->setOption( Redis::OPT_READ_TIMEOUT, 5.0 ) ) { + throw new RuntimeException( 'Could not set the Redis read timeout.' ); + } + if ( $redis->multi() === false ) { + throw new RuntimeException( 'Redis did not start the DKIM key synchronization transaction.' ); + } + $redis->del( 'dkim_keys', 'dkim_selectors' ); + foreach ( $domains as $domain => $signingKey ) { + $redis->hSet( 'dkim_keys', $signingKey[ 'selector' ] . '.' . $domain, $signingKey[ 'key' ] ); + $redis->hSet( 'dkim_selectors', $domain, $signingKey[ 'selector' ] ); + } + $results = $redis->exec(); + if ( ! is_array( $results ) || count( $results ) !== 1 + ( count( $domains ) * 2 ) || array_filter( $results, 'is_int' ) !== $results ) { + throw new RuntimeException( 'Redis did not complete DKIM key synchronization.' ); + } + } catch ( RedisException $exception ) { + throw new RuntimeException( 'Failed to synchronize DKIM signing keys with Redis: ' . $exception->getMessage(), 0, $exception ); + } finally { + $redis->close(); + } + + return count( $domains ); +} + +if ( PHP_SAPI === 'cli' && realpath( $_SERVER[ 'SCRIPT_FILENAME' ] ?? '' ) === __FILE__ ) { + try { + $count = sync_rspamd_dkim_keys( get_db_instance() ); + echo sprintf( "Synchronized %d DKIM signing keys to Redis.\n", $count ); + } catch ( PDOException | RuntimeException $exception ) { + fwrite( STDERR, 'Failed to synchronize DKIM signing keys: ' . $exception->getMessage() . PHP_EOL ); + exit( 1 ); + } +} diff --git a/www/admin.php b/www/admin.php index 8096223..14e7a64 100644 --- a/www/admin.php +++ b/www/admin.php @@ -4,6 +4,7 @@ use Egulias\EmailValidator\EmailLexer; use Egulias\EmailValidator\EmailParser; require_once( '../common_config.php' ); +require_once( __DIR__ . '/../tools/sync_rspamd_dkim_keys.php' ); global $language, $dir, $locale; session_start(); if ( empty( $_SESSION[ 'csrf_token' ] ) ) { @@ -270,6 +271,7 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $stmt = $db->prepare( 'UPDATE domain SET dkim_key = ?, dkim_selector = ?, modified = NOW() WHERE domain = ?;' ); $stmt->execute( [ $dkim[ 'key' ], $dkim[ 'selector' ], $_POST[ 'domain' ] ] ); $msg .= ''; + $msg .= sync_admin_dkim_keys_alert(); } catch ( RuntimeException $exception ) { error_log( 'Failed to regenerate DKIM key for ' . $_POST[ 'domain' ] . ': ' . $exception->getMessage() ); $msg .= ''; @@ -285,8 +287,9 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $stmt = $db->prepare( 'UPDATE domain SET active = ?, modified = NOW() WHERE domain = ?;' ); $stmt->execute( [ $active, $_POST[ 'domain' ] ] ); $msg .= ''; + $msg .= sync_admin_dkim_keys_alert(); } - } elseif ( $_POST[ 'action' ] === 'save_edit_alis_domain' && ! empty( $_POST[ 'alias_domain' ] ) && $_SESSION[ 'email_admin_superadmin' ] ) { + } elseif ( $_POST[ 'action' ] === 'save_edit_alias_domain' && ! empty( $_POST[ 'alias_domain' ] ) && $_SESSION[ 'email_admin_superadmin' ] ) { $stmt = $db->prepare( 'SELECT null FROM alias_domain WHERE alias_domain = ?;' ); $stmt->execute( [ $_POST[ 'alias_domain' ] ] ); if ( ! $stmt->fetch() ) { @@ -321,6 +324,7 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $stmt->execute( [ $ascii_domain, $utf8_domain ] ); } $msg .= ''; + $msg .= sync_admin_dkim_keys_alert(); } } } elseif ( $_POST[ 'action' ] === 'save_new_alias_domain' && ! empty( $_POST[ 'alias_domain' ] ) && $_SESSION[ 'email_admin_superadmin' ] ) { @@ -598,6 +602,17 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { getMessage() ); + return ''; + } +} + function get_admin_list_page(): int { $page = isset( $_GET[ 'page' ] ) ? (int) $_GET[ 'page' ] : 1; diff --git a/www/rspamd_dkim_keys.php b/www/rspamd_dkim_keys.php deleted file mode 100644 index 1821813..0000000 --- a/www/rspamd_dkim_keys.php +++ /dev/null @@ -1,32 +0,0 @@ -query( "SELECT domain, dkim_key, dkim_selector FROM domain WHERE active = 1 ORDER BY domain;" ); -$map_entries = []; -while ( $domain = $stmt->fetch( PDO::FETCH_ASSOC ) ) { - if(empty($domain['dkim_key']) || str_ends_with($domain['domain'], '.onion')) { - continue; // Skip domains without DKIM keys or onion domains - } - $ascii_domain = idn_to_ascii( $domain[ 'domain' ], IDNA_NONTRANSITIONAL_TO_ASCII ); - $key = get_rsa_dkim_private_key_base64_der( $domain[ 'dkim_key' ] ); - if ( ! is_string( $ascii_domain ) || ! preg_match( '/^[a-z0-9.-]+$/iD', $ascii_domain ) || $key === null || ! preg_match( '/^[a-zA-Z0-9_-]+$/D', $domain[ 'dkim_selector' ] ) ) { - http_response_code( 500 ); - error_log( 'Invalid RSA DKIM key, selector, or domain configured for ' . $domain[ 'domain' ] ); - exit; - } - $ascii_domain = mb_strtolower( $ascii_domain ); - $map_entries[] = $ascii_domain . ' %:' . $domain[ 'dkim_selector' ] . ':' . $key; - $map_entries[] = '*@' . $ascii_domain . ' ' . $ascii_domain; -} - -echo implode( "\n", $map_entries ) . ( $map_entries ? "\n" : '' );