1 { lib, pkgs, config, nodes, ... }:
3 config = lib.mkIf config.myServices.mail.enable {
4 myServices.chatonsProperties.hostings.mx-backup = {
5 file.datetime = "2022-08-22T01:00:00";
8 description = "Serveur e-mail secondaire";
9 logo = "https://www.postfix.org/favicon.ico";
10 website = "https://mail.immae.eu/";
12 status.description = "OK";
13 registration.load = "OPEN";
14 install.type = "PACKAGE";
18 website = "http://www.postfix.org/";
19 license.url = "http://postfix.mirrors.ovh.net/postfix-release/LICENSE";
20 license.name = "Eclipse Public license (EPL 2.0) and IBM Public License (IPL 1.0)";
21 version = pkgs.postfix.version;
22 source.url = "http://www.postfix.org/download.html";
26 "postfix/mysql_alias_maps" = {
27 user = config.services.postfix.user;
28 group = config.services.postfix.group;
31 # We need to specify that option to trigger ssl connection
33 user = ${config.myEnv.mail.postfix.mysql.user}
34 password = ${config.myEnv.mail.postfix.mysql.password}
35 hosts = unix:${config.myEnv.mail.postfix.mysql.socket}
36 dbname = ${config.myEnv.mail.postfix.mysql.database}
37 query = SELECT DISTINCT destination
40 ((regex = 1 AND '%s' REGEXP CONCAT('^',source,'$') ) OR (regex = 0 AND source = '%s'))
45 FROM forwardings_blacklisted
48 SELECT 'devnull@immae.eu'
49 FROM forwardings_blacklisted
53 "postfix/ldap_mailboxes" = {
54 user = config.services.postfix.user;
55 group = config.services.postfix.group;
58 server_host = ldaps://${config.myEnv.mail.dovecot.ldap.host}:636
59 search_base = ${config.myEnv.mail.dovecot.ldap.base}
60 query_filter = ${config.myEnv.mail.dovecot.ldap.postfix_mailbox_filter}
61 bind_dn = ${config.myEnv.mail.dovecot.ldap.dn}
62 bind_pw = ${config.myEnv.mail.dovecot.ldap.password}
63 result_attribute = immaePostfixAddress
68 "postfix/mysql_sender_login_maps" = {
69 user = config.services.postfix.user;
70 group = config.services.postfix.group;
73 # We need to specify that option to trigger ssl connection
75 user = ${config.myEnv.mail.postfix.mysql.user}
76 password = ${config.myEnv.mail.postfix.mysql.password}
77 hosts = unix:${config.myEnv.mail.postfix.mysql.socket}
78 dbname = ${config.myEnv.mail.postfix.mysql.database}
79 query = SELECT DISTINCT destination
83 (regex = 1 AND CONCAT(SUBSTRING_INDEX('%u', '+', 1), '@%d') REGEXP CONCAT('^',source,'$') )
85 (regex = 0 AND source = CONCAT(SUBSTRING_INDEX('%u', '+', 1), '@%d'))
88 UNION SELECT CONCAT(SUBSTRING_INDEX('%u', '+', 1), '@%d') AS destination
91 "postfix/mysql_sender_relays_maps" = {
92 user = config.services.postfix.user;
93 group = config.services.postfix.group;
96 # We need to specify that option to trigger ssl connection
98 user = ${config.myEnv.mail.postfix.mysql.user}
99 password = ${config.myEnv.mail.postfix.mysql.password}
100 hosts = unix:${config.myEnv.mail.postfix.mysql.socket}
101 dbname = ${config.myEnv.mail.postfix.mysql.database}
102 # INSERT INTO sender_relays
103 # (`from`, owner, relay, login, password, regex, active)
105 # ( 'sender@otherhost.org'
106 # , 'me@mail.immae.eu'
107 # , '[otherhost.org]:587'
109 # , AES_ENCRYPT('otherhostpassword', '${config.myEnv.mail.postfix.mysql.password_encrypt}')
113 query = SELECT DISTINCT `owner`
116 ((regex = 1 AND '%s' REGEXP CONCAT('^',`from`,'$') ) OR (regex = 0 AND `from` = '%s'))
120 "postfix/mysql_sender_relays_hosts" = {
121 user = config.services.postfix.user;
122 group = config.services.postfix.group;
123 permissions = "0440";
125 # We need to specify that option to trigger ssl connection
126 tls_ciphers = TLSv1.2
127 user = ${config.myEnv.mail.postfix.mysql.user}
128 password = ${config.myEnv.mail.postfix.mysql.password}
129 hosts = unix:${config.myEnv.mail.postfix.mysql.socket}
130 dbname = ${config.myEnv.mail.postfix.mysql.database}
132 query = SELECT DISTINCT relay
135 ((regex = 1 AND '%s' REGEXP CONCAT('^',`from`,'$') ) OR (regex = 0 AND `from` = '%s'))
139 "postfix/mysql_sender_relays_creds" = {
140 user = config.services.postfix.user;
141 group = config.services.postfix.group;
142 permissions = "0440";
144 # We need to specify that option to trigger ssl connection
145 tls_ciphers = TLSv1.2
146 user = ${config.myEnv.mail.postfix.mysql.user}
147 password = ${config.myEnv.mail.postfix.mysql.password}
148 hosts = unix:${config.myEnv.mail.postfix.mysql.socket}
149 dbname = ${config.myEnv.mail.postfix.mysql.database}
151 query = SELECT DISTINCT CONCAT(`login`, ':', AES_DECRYPT(`password`, '${config.myEnv.mail.postfix.mysql.password_encrypt}'))
154 ((regex = 1 AND '%s' REGEXP CONCAT('^',`from`,'$') ) OR (regex = 0 AND `from` = '%s'))
158 "postfix/ldap_ejabberd_users_immae_fr" = {
159 user = config.services.postfix.user;
160 group = config.services.postfix.group;
161 permissions = "0440";
163 server_host = ldaps://${config.myEnv.jabber.ldap.host}:636
164 search_base = ${config.myEnv.jabber.ldap.base}
165 query_filter = ${config.myEnv.jabber.postfix_user_filter}
167 bind_dn = ${config.myEnv.jabber.ldap.dn}
168 bind_pw = ${config.myEnv.jabber.ldap.password}
169 result_attribute = immaeXmppUid
170 result_format = ejabberd@localhost
174 } // lib.mapAttrs' (name: v: lib.nameValuePair "postfix/scripts/${name}-env" {
175 user = "postfixscripts";
177 permissions = "0400";
178 text = builtins.toJSON v.env;
179 }) config.myEnv.mail.scripts;
181 networking.firewall.allowedTCPPorts = [ 25 465 587 ];
183 users.users.postfixscripts = {
185 uid = config.ids.uids.postfixscripts;
186 description = "Postfix scripts user";
188 users.users."${config.services.postfix.user}".extraGroups = [ "keys" ];
189 services.filesWatcher.postfix = {
192 config.secrets.fullPaths."postfix/mysql_alias_maps"
193 config.secrets.fullPaths."postfix/ldap_mailboxes"
194 config.secrets.fullPaths."postfix/mysql_sender_login_maps"
195 config.secrets.fullPaths."postfix/ldap_ejabberd_users_immae_fr"
200 toScript = name: script: pkgs.writeScript name ''
201 #! ${pkgs.stdenv.shell}
202 mail=$(${pkgs.coreutils}/bin/cat -)
203 output=$(echo "$mail" | ${script} 2>&1)
206 if [ "$ret" != "0" ]; then
208 | ${pkgs.procmail}/bin/formail -i "X-Return-Code: $ret" \
209 | /run/wrappers/bin/sendmail -i scripts_error+${name}@mail.immae.eu
211 messageId=$(echo "$mail" | ${pkgs.procmail}/bin/formail -x "Message-Id:")
212 repeat=$(echo "$mail" | ${pkgs.procmail}/bin/formail -X "From:" -X "Received:")
214 ${pkgs.coreutils}/bin/cat <<EOF | /run/wrappers/bin/sendmail -i scripts_error+${name}@mail.immae.eu
216 To: scripts_error+${name}@mail.immae.eu
217 Subject: Log from script error
218 Content-Type: text/plain; charset="UTF-8"
219 Content-Transfer-Encoding: 8bit
220 References:$messageId
232 scripts = lib.attrsets.mapAttrs (n: v:
234 (builtins.getFlake "git+${v.src.url}?rev=${v.src.rev}"
235 #(builtins.fetchGit { url = v.src.url; ref = "master"; rev = v.src.rev; })
236 ).outputs.envToScript.x86_64-linux
237 config.secrets.fullPaths."postfix/scripts/${n}-env"
239 ) config.myEnv.mail.scripts // {
240 testmail = pkgs.writeScript "testmail" ''
241 #! ${pkgs.stdenv.shell}
242 ${pkgs.coreutils}/bin/touch \
243 "/var/lib/naemon/checks/email/$(${pkgs.procmail}/bin/formail -x To: | ${pkgs.coreutils}/bin/tr -d ' <>')"
246 in builtins.concatStringsSep "\n" (lib.attrsets.mapAttrsToList (n: v: ''${n}: "|${v}"'') scripts);
249 name = n: i: "relay_${n}_${toString i}";
250 pair = n: i: m: lib.attrsets.nameValuePair (name n i) (
252 then pkgs.writeText (name n i) m.content
255 pairs = n: v: lib.imap1 (i: m: pair n i m) v.recipient_maps;
256 in lib.attrsets.filterAttrs (k: v: v != null) (
257 lib.attrsets.listToAttrs (lib.flatten (
258 lib.attrsets.mapAttrsToList pairs config.myEnv.mail.postfix.backup_domains
261 relay_restrictions = lib.attrsets.filterAttrs (k: v: v != null) (
262 lib.attrsets.mapAttrs' (n: v:
263 lib.attrsets.nameValuePair "recipient_access_${n}" (
264 if lib.attrsets.hasAttr "relay_restrictions" v
265 then pkgs.writeText "recipient_access_${n}" v.relay_restrictions
268 ) config.myEnv.mail.postfix.backup_domains
272 cfg = config.myEnv.monitoring.email_check.eldiron;
273 address = "${cfg.mail_address}@${cfg.mail_domain}";
274 in pkgs.writeText "postfix-virtual" (
275 builtins.concatStringsSep "\n" (
276 ["${address} testmail@localhost"] ++
277 lib.attrsets.mapAttrsToList (
278 n: v: lib.optionalString v.external ''
279 script_${n}@mail.immae.eu ${n}@localhost, scripts@mail.immae.eu
281 ) config.myEnv.mail.scripts
286 host_sender_login = with lib.attrsets; let
287 addresses = zipAttrs (lib.flatten (mapAttrsToList
288 (n: v: (map (e: { "${e}" = "${n}@immae.eu"; }) v.emails)) config.myEnv.servers));
289 joined = builtins.concatStringsSep ",";
290 in pkgs.writeText "host-sender-login"
291 (builtins.concatStringsSep "\n" (mapAttrsToList (n: v: "${n} ${joined v}") addresses));
294 recipient_maps // relay_restrictions // virtual_map // sasl_access;
296 ### postfix module overrides
297 readme_directory = "${pkgs.postfix}/share/postfix/doc";
298 smtp_tls_CAfile = lib.mkForce "";
299 smtp_tls_cert_file = lib.mkForce "";
300 smtp_tls_key_file = lib.mkForce "";
302 message_size_limit = "1073741824"; # Don't put 0 here, it's not equivalent to "unlimited"
303 mailbox_size_limit = "1073741825"; # Workaround, local delivered mails should all go through scripts
304 alias_database = "\$alias_maps";
306 ### Aliases scripts user
307 default_privs = "postfixscripts";
309 ### Virtual mailboxes config
310 virtual_alias_maps = [
311 "hash:/etc/postfix/virtual"
312 "mysql:${config.secrets.fullPaths."postfix/mysql_alias_maps"}"
313 "ldap:${config.secrets.fullPaths."postfix/ldap_ejabberd_users_immae_fr"}"
315 virtual_mailbox_domains = config.myEnv.mail.postfix.additional_mailbox_domains
316 ++ lib.remove null (lib.flatten (map
319 then "${e.domain}${lib.optionalString (e.domain != "") "."}${zone.name}"
322 (zone.withEmail or [])
324 config.myEnv.dns.masterZones
326 virtual_mailbox_maps = [
327 "ldap:${config.secrets.fullPaths."postfix/ldap_mailboxes"}"
329 dovecot_destination_recipient_limit = "1";
330 virtual_transport = "dovecot";
333 relay_domains = lib.flatten (lib.attrsets.mapAttrsToList (n: v: v.domains or []) config.myEnv.mail.postfix.backup_domains);
334 relay_recipient_maps = lib.flatten (lib.attrsets.mapAttrsToList (n: v:
335 lib.imap1 (i: m: "${m.type}:/etc/postfix/relay_${n}_${toString i}") v.recipient_maps
336 ) config.myEnv.mail.postfix.backup_domains);
337 smtpd_relay_restrictions = [
338 "defer_unauth_destination"
339 ] ++ lib.flatten (lib.attrsets.mapAttrsToList (n: v:
340 if lib.attrsets.hasAttr "relay_restrictions" v
341 then [ "check_recipient_access hash:/etc/postfix/recipient_access_${n}" ]
343 ) config.myEnv.mail.postfix.backup_domains);
345 ### Additional smtpd configuration
346 smtpd_tls_received_header = "yes";
347 smtpd_tls_loglevel = "1";
349 ### Email sending configuration
350 smtp_tls_security_level = "may";
351 smtp_tls_loglevel = "1";
353 ### Force ip bind for smtp
354 smtp_bind_address = builtins.head config.hostEnv.ips.main.ip4;
355 smtp_bind_address6 = builtins.head config.hostEnv.ips.main.ip6;
357 # Use some relays when authorized senders are not myself
358 smtp_sasl_mechanism_filter = "plain,login"; # GSSAPI Not correctly supported by postfix
359 smtp_sasl_auth_enable = "yes";
360 smtp_sasl_password_maps =
361 "mysql:${config.secrets.fullPaths."postfix/mysql_sender_relays_creds"}";
362 smtp_sasl_security_options = "noanonymous";
363 smtp_sender_dependent_authentication = "yes";
364 sender_dependent_relayhost_maps =
365 "mysql:${config.secrets.fullPaths."postfix/mysql_sender_relays_hosts"}";
367 ### opendkim, opendmarc, openarc milters
368 non_smtpd_milters = [
369 "unix:${config.myServices.mail.milters.sockets.opendkim}"
372 "unix:${config.myServices.mail.milters.sockets.opendkim}"
373 "unix:${config.myServices.mail.milters.sockets.openarc}"
374 "unix:${config.myServices.mail.milters.sockets.opendmarc}"
378 smtpd_use_tls = true;
379 smtpd_tls_chain_files = builtins.concatStringsSep "," [ "/var/lib/acme/mail/full.pem" "/var/lib/acme/mail-rsa/full.pem" ];
381 maximal_queue_lifetime = "6w";
382 bounce_queue_lifetime = "6w";
386 enableSubmission = true;
387 submissionOptions = {
388 # Don’t use "long form", only commas (cf
389 # http://www.postfix.org/master.5.html long form is not handled
390 # well by the submission function)
391 smtpd_tls_security_level = "encrypt";
392 smtpd_sasl_auth_enable = "yes";
393 smtpd_tls_auth_only = "yes";
394 smtpd_sasl_tls_security_options = "noanonymous";
395 smtpd_sasl_type = "dovecot";
396 smtpd_sasl_path = "private/auth";
397 smtpd_reject_unlisted_recipient = "no";
398 smtpd_client_restrictions = "permit_sasl_authenticated,reject";
399 smtpd_relay_restrictions = "permit_sasl_authenticated,reject";
400 # Refuse to send e-mails with a From that is not handled
401 smtpd_sender_restrictions =
402 "reject_sender_login_mismatch,reject_unlisted_sender,permit_sasl_authenticated,reject";
403 smtpd_sender_login_maps = builtins.concatStringsSep "," [
404 "hash:/etc/postfix/host_sender_login"
405 "mysql:${config.secrets.fullPaths."postfix/mysql_sender_relays_maps"}"
406 "mysql:${config.secrets.fullPaths."postfix/mysql_sender_login_maps"}"
408 smtpd_recipient_restrictions = "permit_sasl_authenticated,reject";
409 milter_macro_daemon_name = "ORIGINATING";
410 smtpd_milters = builtins.concatStringsSep "," [
411 # FIXME: put it back when opensmtpd is upgraded and able to
412 # rewrite the from header
413 #"unix:/run/milter_verify_from/verify_from.sock"
414 "unix:${config.myServices.mail.milters.sockets.opendkim}"
417 destination = ["localhost"];
418 # This needs to reverse DNS
419 hostname = config.hostEnv.fqdn;
421 recipientDelimiter = "+";
427 args = ["-o" "smtpd_tls_wrappermode=yes" ] ++ (let
428 mkKeyVal = opt: val: [ "-o" (opt + "=" + val) ];
429 in lib.concatLists (lib.mapAttrsToList mkKeyVal config.services.postfix.submissionOptions)
438 # rspamd could be used as a milter, but then it cannot apply
439 # its checks "per user" (milter is not yet dispatched to
440 # users), so we wrap dovecot-lda inside rspamc per recipient
442 rspamc_dovecot = pkgs.writeScriptBin "rspamc_dovecot" ''
443 #! ${pkgs.stdenv.shell}
446 original_recipient="$2"
449 ${pkgs.coreutils}/bin/cat - | \
450 ${pkgs.rspamd}/bin/rspamc -h ${config.myServices.mail.rspamd.sockets.worker-controller} -c bayes -d "$user" --mime | \
451 ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -f "$sender" -a "$original_recipient" -d "$user"
452 if echo ''${PIPESTATUS[@]} | ${pkgs.gnugrep}/bin/grep -qE '^[0 ]+$'; then
455 # src/global/sys_exits.h to retry
460 "flags=ODRhu" "user=vhost:vhost"
461 "argv=${rspamc_dovecot}/bin/rspamc_dovecot \${sender} \${original_recipient} \${user}@\${nexthop}"
466 security.acme.certs."mail" = {
468 systemctl restart postfix.service
470 extraDomainNames = [ "smtp.immae.eu" ];
472 security.acme.certs."mail-rsa" = {
474 systemctl restart postfix.service
476 extraDomainNames = [ "smtp.immae.eu" ];
478 system.activationScripts.testmail = {
481 allCfg = config.myEnv.monitoring.email_check;
482 cfg = allCfg.eldiron;
483 reverseTargets = builtins.attrNames (lib.attrsets.filterAttrs (k: v: builtins.elem "eldiron" v.targets) allCfg);
484 to_email = cfg': host':
485 let sep = if lib.strings.hasInfix "+" cfg'.mail_address then "_" else "+";
486 in "${cfg'.mail_address}${sep}${host'}@${cfg'.mail_domain}";
487 mails_to_receive = builtins.concatStringsSep " " (map (to_email cfg) reverseTargets);
489 install -m 0555 -o postfixscripts -g keys -d /var/lib/naemon/checks/email
490 for f in ${mails_to_receive}; do
491 if [ ! -f /var/lib/naemon/checks/email/$f ]; then
492 install -m 0644 -o postfixscripts -g keys /dev/null -T /var/lib/naemon/checks/email/$f
493 touch -m -d @0 /var/lib/naemon/checks/email/$f
498 systemd.services.postfix.serviceConfig.Slice = "mail.slice";