diff --git a/README.md b/README.md index 529454c..2adb8cf 100644 --- a/README.md +++ b/README.md @@ -80,11 +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. -Generate DKIM signing keys and add them to /etc/rspamd/local.d/arc.conf /etc/rspamd/local.d/dkim_signing.conf, then add the printed DNS records to your domain: -``` -rspamadm dkim_keygen -d YOUR_DOMAIN -s $(date +"%Y%m%d")-rsa -b 4096 -t rsa -k /var/lib/rspamd/dkim/YOUR_DOMAIN-rsa -rspamadm dkim_keygen -d YOUR_DOMAIN -s $(date +"%Y%m%d")-ed25519 -t ed25519 -k /var/lib/rspamd/dkim/YOUR_DOMAIN-ed25519 -``` +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. Create a password used for your TURN server and replace all `YOUR_SECRET` in `/etc/prosody/prosody.cfg.lua` with it. diff --git a/common_config.php b/common_config.php index 851fad9..cd2fa42 100644 --- a/common_config.php +++ b/common_config.php @@ -9,7 +9,7 @@ const DBHOST = 'localhost'; // Database host const DBUSER = 'postfix'; // Database user const DBPASS = 'YOUR_PASSWORD'; // Database password const DBNAME = 'postfix'; // Database -const DBVERSION = 9; // Database schema version +const DBVERSION = 10; // Database schema version const INACTIVITY_PERIOD_MONTHS = [1, 6, 12, 24]; // Allowed inactivity periods in months - don't forget to update get_inactivity_period_options on changes here and if an option is removed, you should also update accounts in the database mailbox table 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" @@ -126,6 +126,58 @@ function get_db_instance(): PDO return $db; } +function get_rsa_dkim_private_key_base64_der( string $private_key ): ?string +{ + $key = openssl_pkey_get_private( $private_key ); + if ( $key === false ) { + return null; + } + $details = openssl_pkey_get_details( $key ); + if ( ! is_array( $details ) || $details[ 'type' ] !== OPENSSL_KEYTYPE_RSA ) { + return null; + } + if ( ! openssl_pkey_export( $key, $normalized_key ) ) { + return null; + } + $encoded_key = preg_replace( '/-----BEGIN [^-]+-----|-----END [^-]+-----|\s+/', '', $normalized_key ); + if ( ! is_string( $encoded_key ) || $encoded_key === '' || base64_decode( $encoded_key, true ) === false ) { + return null; + } + return $encoded_key; +} + +function get_rsa_dkim_public_key_base64( string $private_key ): ?string +{ + $key = openssl_pkey_get_private( $private_key ); + if ( $key === false ) { + return null; + } + $details = openssl_pkey_get_details( $key ); + if ( ! is_array( $details ) || $details[ 'type' ] !== OPENSSL_KEYTYPE_RSA ) { + return null; + } + $encoded_key = preg_replace( '/-----BEGIN [^-]+-----|-----END [^-]+-----|\s+/', '', $details[ 'key' ] ); + if ( ! is_string( $encoded_key ) || $encoded_key === '' || base64_decode( $encoded_key, true ) === false ) { + return null; + } + return $encoded_key; +} + +function generate_rsa_dkim_key(): array +{ + $key = openssl_pkey_new( [ + 'private_key_type' => OPENSSL_KEYTYPE_RSA, + 'private_key_bits' => 4096, + ] ); + if ( $key === false || ! openssl_pkey_export( $key, $private_key ) ) { + throw new RuntimeException( 'Unable to generate RSA DKIM private key.' ); + } + return [ + 'key' => $private_key, + 'selector' => date( 'Ymd' ) . '-rsa', + ]; +} + function z_base32_encode( string $input ): string { $map = [ diff --git a/composer.json b/composer.json index 74b2518..00a1a05 100644 --- a/composer.json +++ b/composer.json @@ -3,6 +3,7 @@ "egulias/email-validator": "^4.0", "ext-mbstring": "*", "ext-pdo": "*", + "ext-openssl": "*", "ext-gnupg": "*", "ext-gettext": "*", "ext-intl": "*", diff --git a/etc/rspamd/local.d/arc.conf b/etc/rspamd/local.d/arc.conf index cf59e56..f7d0f6a 100644 --- a/etc/rspamd/local.d/arc.conf +++ b/etc/rspamd/local.d/arc.conf @@ -1,16 +1,4 @@ sign_authenticated = true; sign_local = true; -domain { - danwin1210.de { - selectors [ - { - path: "/var/lib/rspamd/dkim/danwin1210.de-rsa"; - selector: "20211204-rsa"; - }, - { - path: "/var/lib/rspamd/dkim/danwin1210.de-ed25519"; - selector: "20211204-ed25519"; - } - ] - } -} +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"; diff --git a/etc/rspamd/local.d/dkim_signing.conf b/etc/rspamd/local.d/dkim_signing.conf index b2bc2cd..24a88f6 100644 --- a/etc/rspamd/local.d/dkim_signing.conf +++ b/etc/rspamd/local.d/dkim_signing.conf @@ -5,17 +5,5 @@ 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"; -domain { - danwin1210.de { - selectors [ - { - path: "/var/lib/rspamd/dkim/danwin1210.de-rsa"; - selector: "20211204-rsa"; - }, - { - path: "/var/lib/rspamd/dkim/danwin1210.de-ed25519"; - selector: "20211204-ed25519"; - } - ] - } -} +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"; diff --git a/setup.php b/setup.php index cadd40f..3bb812d 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'] as $required_extension) { +foreach(['pdo_mysql', 'mbstring', 'pcre', 'gnupg', 'intl', 'openssl'] 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 ); } @@ -25,7 +25,7 @@ try{ } $createTableStatements = [ 'admin' => "CREATE TABLE IF NOT EXISTS `admin` (`username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `superadmin` tinyint(1) NOT NULL DEFAULT 0, `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, `password_hash_type` varchar(20) NOT NULL DEFAULT '{MD5-CRYPT}', `totp_secret` varchar(64) DEFAULT NULL, PRIMARY KEY (`username`), KEY `active` (`active`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", - 'domain' => "CREATE TABLE IF NOT EXISTS `domain` (`domain` varchar(255) NOT NULL, `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, PRIMARY KEY (`domain`), KEY `active` (`active`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", + 'domain' => "CREATE TABLE IF NOT EXISTS `domain` (`domain` varchar(255) NOT NULL, `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, `dkim_key` text NOT NULL DEFAULT '', `dkim_selector` varchar(20) NOT NULL DEFAULT '', PRIMARY KEY (`domain`), KEY `active` (`active`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'alias' => "CREATE TABLE IF NOT EXISTS `alias` (`address` varchar(255) NOT NULL, `goto` text NOT NULL, `domain` varchar(255) NOT NULL, `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, `enforce_tls_in` tinyint(1) NOT NULL DEFAULT 1, PRIMARY KEY (`address`), KEY `domain` (`domain`), KEY `active` (`active`), CONSTRAINT `alias_ibfk_1` FOREIGN KEY (`domain`) REFERENCES `domain` (`domain`) ON UPDATE CASCADE) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'alias_domain' => "CREATE TABLE IF NOT EXISTS `alias_domain` (`alias_domain` varchar(255) NOT NULL DEFAULT '', `target_domain` varchar(255) NOT NULL DEFAULT '', `created` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `modified` datetime NOT NULL DEFAULT '2000-01-01 00:00:00', `active` tinyint(1) NOT NULL DEFAULT 1, PRIMARY KEY (`alias_domain`), KEY `active` (`active`), KEY `target_domain` (`target_domain`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;", 'captcha' => "CREATE TABLE IF NOT EXISTS `captcha` (`id` bigint(20) NOT NULL AUTO_INCREMENT, `time` int(11) NOT NULL, `code` char(5) NOT NULL, PRIMARY KEY (`id`)) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;", @@ -110,6 +110,22 @@ try{ if ( $version < 9 ) { $db->exec( 'ALTER TABLE `mailbox` MODIFY COLUMN `feedback_id` char(15) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL;' ); } + if ( $version < 10 ) { + $stmt = $db->query( "SHOW COLUMNS FROM `domain` LIKE 'dkim_key';" ); + if ( ! $stmt->fetch() ) { + $db->exec( "ALTER TABLE `domain` ADD COLUMN `dkim_key` text NOT NULL DEFAULT '';" ); + } + $stmt = $db->query( "SHOW COLUMNS FROM `domain` LIKE 'dkim_selector';" ); + if ( ! $stmt->fetch() ) { + $db->exec( "ALTER TABLE `domain` ADD COLUMN `dkim_selector` varchar(20) NOT NULL DEFAULT '';" ); + } + $stmt = $db->query( "SELECT `domain` FROM `domain` WHERE `dkim_key` = '' OR `dkim_selector` = '';" ); + $update_dkim = $db->prepare( 'UPDATE `domain` SET `dkim_key` = ?, `dkim_selector` = ?, `modified` = NOW() WHERE `domain` = ?;' ); + while ( $domain = $stmt->fetch( PDO::FETCH_ASSOC ) ) { + $dkim = generate_rsa_dkim_key(); + $update_dkim->execute( [ $dkim[ 'key' ], $dkim[ 'selector' ], $domain[ 'domain' ] ] ); + } + } $db->beginTransaction(); $stmt=$db->prepare("UPDATE `settings` SET `value`=? WHERE `setting`='version';"); $stmt->execute([DBVERSION]); @@ -119,7 +135,7 @@ try{ } else { echo _('Database is already up-to-date.') . PHP_EOL; } - } catch(PDOException $e){ + }catch(PDOException | RuntimeException $e){ echo _('Error updating database:') . PHP_EOL; echo $e->getMessage() . PHP_EOL; if($db->inTransaction()){ @@ -141,12 +157,19 @@ try{ } } try { - $stmt = $db->prepare( 'INSERT IGNORE INTO `domain` (`domain`, `created`, `modified`) VALUES (?, NOW(), NOW())' ); - $stmt->execute( [ CLEARNET_SERVER ] ); - $stmt->execute( [ ONION_SERVER ] ); + $select_domain = $db->prepare( 'SELECT null FROM `domain` WHERE `domain` = ?;' ); + $insert_domain = $db->prepare( 'INSERT INTO `domain` (`domain`, `dkim_key`, `dkim_selector`, `created`, `modified`) VALUES (?, ?, ?, NOW(), NOW());' ); + foreach ( [ CLEARNET_SERVER, ONION_SERVER ] as $domain ) { + $select_domain->execute( [ $domain ] ); + $existing_domain = $select_domain->fetch( PDO::FETCH_ASSOC ); + if ( ! $existing_domain ) { + $dkim = generate_rsa_dkim_key(); + $insert_domain->execute( [ $domain, $dkim[ 'key' ], $dkim[ 'selector' ] ] ); + } + } $stmt = $db->prepare( 'INSERT IGNORE INTO `alias_domain` (`alias_domain`, `target_domain`, `created`, `modified`) VALUES (?, ?, NOW(), NOW())' ); $stmt->execute( [ ONION_SERVER, CLEARNET_SERVER ] ); -} catch( PDOException $e ) { +} catch( PDOException | RuntimeException $e ) { echo _('Error adding primary domain:') . PHP_EOL; echo $e->getMessage() . PHP_EOL; } diff --git a/www/admin.php b/www/admin.php index 8e6f543..bb9d90c 100644 --- a/www/admin.php +++ b/www/admin.php @@ -235,6 +235,27 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $msg .= ''; } } + } elseif ( $_POST[ 'action' ] === 'confirm_regenerate_dkim_key' && ! empty( $_POST[ 'domain' ] ) && $_SESSION[ 'email_admin_superadmin' ] ) { + $msg .= ''; + $msg .= '
'; + $msg .= ''; + $msg .= '
'; + } elseif ( $_POST[ 'action' ] === 'regenerate_dkim_key' && ! empty( $_POST[ 'domain' ] ) && $_SESSION[ 'email_admin_superadmin' ] ) { + $stmt = $db->prepare( 'SELECT null FROM domain WHERE domain = ?;' ); + $stmt->execute( [ $_POST[ 'domain' ] ] ); + if ( ! $stmt->fetch() ) { + $msg .= ''; + } else { + try { + $dkim = generate_rsa_dkim_key(); + $stmt = $db->prepare( 'UPDATE domain SET dkim_key = ?, dkim_selector = ?, modified = NOW() WHERE domain = ?;' ); + $stmt->execute( [ $dkim[ 'key' ], $dkim[ 'selector' ], $_POST[ 'domain' ] ] ); + $msg .= ''; + } catch ( RuntimeException $exception ) { + error_log( 'Failed to regenerate DKIM key for ' . $_POST[ 'domain' ] . ': ' . $exception->getMessage() ); + $msg .= ''; + } + } } elseif ( $_POST[ 'action' ] === 'save_edit_domain' && ! empty( $_POST[ 'domain' ] ) && $_SESSION[ 'email_admin_superadmin' ] ) { $stmt = $db->prepare( 'SELECT null FROM domain WHERE domain = ?;' ); $stmt->execute( [ $_POST[ 'domain' ] ] ); @@ -242,7 +263,7 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $msg .= ''; } else { $active = isset( $_POST[ 'active' ] ) ? 1 : 0; - $stmt = $db->prepare( 'UPDATE domain set active = ?, modified = NOW() WHERE domain = ?;' ); + $stmt = $db->prepare( 'UPDATE domain SET active = ?, modified = NOW() WHERE domain = ?;' ); $stmt->execute( [ $active, $_POST[ 'domain' ] ] ); $msg .= ''; } @@ -266,13 +287,22 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { $ascii_domain = idn_to_ascii($_POST['domain'], IDNA_NONTRANSITIONAL_TO_ASCII); $utf8_domain = idn_to_utf8($_POST['domain'], IDNA_NONTRANSITIONAL_TO_UNICODE); $active = isset( $_POST[ 'active' ] ) ? 1 : 0; - $stmt = $db->prepare( 'INSERT INTO domain (active, domain, created, modified) VALUES (?, ?, NOW(), NOW());' ); - $stmt->execute( [ $active, $utf8_domain ] ); - if($ascii_domain !== $utf8_domain){ - $stmt = $db->prepare( 'INSERT INTO alias_domain (active, alias_domain, target_domain, created, modified) VALUES (1, ?, ?, NOW(), NOW());' ); - $stmt->execute( [ $ascii_domain, $utf8_domain ] ); + $dkim = null; + try { + $dkim = generate_rsa_dkim_key(); + } catch ( RuntimeException $exception ) { + error_log( 'Failed to generate DKIM key for new domain ' . $utf8_domain . ': ' . $exception->getMessage() ); + $msg .= ''; + } + if ( $dkim !== null ) { + $stmt = $db->prepare( 'INSERT INTO domain (active, domain, dkim_key, dkim_selector, created, modified) VALUES (?, ?, ?, ?, NOW(), NOW());' ); + $stmt->execute( [ $active, $utf8_domain, $dkim[ 'key' ], $dkim[ 'selector' ] ] ); + if($ascii_domain !== $utf8_domain){ + $stmt = $db->prepare( 'INSERT INTO alias_domain (active, alias_domain, target_domain, created, modified) VALUES (1, ?, ?, NOW(), NOW());' ); + $stmt->execute( [ $ascii_domain, $utf8_domain ] ); + } + $msg .= ''; } - $msg .= ''; } } elseif ( $_POST[ 'action' ] === 'save_new_alias_domain' && ! empty( $_POST[ 'alias_domain' ] ) && $_SESSION[ 'email_admin_superadmin' ] ) { $stmt = $db->prepare( 'SELECT null FROM domain WHERE domain = ? UNION SELECT null FROM alias_domain WHERE alias_domain = ?;' ); @@ -523,7 +553,7 @@ if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { send_new_mailbox(); } elseif ( in_array( $_REQUEST[ 'action' ], [ 'edit_admin', 'save_edit_admin', 'start_admin_totp_setup', 'enable_admin_totp', 'disable_admin_totp' ], true ) ) { send_edit_admin(); - } elseif ( in_array( $_REQUEST[ 'action' ], [ 'edit_domain', 'save_edit_domain' ], true ) ) { + } elseif ( in_array( $_REQUEST[ 'action' ], [ 'edit_domain', 'save_edit_domain', 'regenerate_dkim_key' ], true ) ) { send_edit_domain(); } elseif ( in_array( $_REQUEST[ 'action' ], [ 'edit_alias_domain', 'save_edit_alias_domain' ], true ) && $_SESSION[ 'email_admin_superadmin' ] ) { send_edit_alias_domain(); @@ -829,7 +859,7 @@ function send_new_domain(): void function send_edit_domain(): void { $db = get_db_instance(); - $stmt = $db->prepare( 'SELECT domain, active FROM domain WHERE domain = ?;' ); + $stmt = $db->prepare( 'SELECT domain, active, dkim_key, dkim_selector FROM domain WHERE domain = ?;' ); $stmt->execute( [ $_POST[ 'domain' ] ] ); if ( $admin = $stmt->fetch( PDO::FETCH_ASSOC ) ) { ?> @@ -842,11 +872,37 @@ function send_edit_domain(): void value="1"> + +
+
+
+
+ +
+
+
+ + +
+
+
+ +
+
+ +
+
+
diff --git a/www/rspamd_dkim_keys.php b/www/rspamd_dkim_keys.php new file mode 100644 index 0000000..c235161 --- /dev/null +++ b/www/rspamd_dkim_keys.php @@ -0,0 +1,32 @@ +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'])) { + continue; // Skip domains without DKIM keys + } + $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" : '' );