]> git.immae.eu Git - perso/Immae/Config/Nix.git/blame - modules/private/mail/postfix.nix
Use attrs for secrets instead of lists
[perso/Immae/Config/Nix.git] / modules / private / mail / postfix.nix
CommitLineData
71a2425e 1{ lib, pkgs, config, nodes, ... }:
a929614f 2{
8415083e 3 config = lib.mkIf config.myServices.mail.enable {
d2e703c5 4 services.duplyBackup.profiles.mail.excludeFile = ''
8415083e
IB
5 + /var/lib/postfix
6 '';
4c4652aa
IB
7 secrets.keys = {
8 "postfix/mysql_alias_maps" = {
8415083e
IB
9 user = config.services.postfix.user;
10 group = config.services.postfix.group;
11 permissions = "0440";
12 text = ''
13 # We need to specify that option to trigger ssl connection
14 tls_ciphers = TLSv1.2
ab8f306d
IB
15 user = ${config.myEnv.mail.postfix.mysql.user}
16 password = ${config.myEnv.mail.postfix.mysql.password}
17 hosts = unix:${config.myEnv.mail.postfix.mysql.socket}
18 dbname = ${config.myEnv.mail.postfix.mysql.database}
8415083e 19 query = SELECT DISTINCT destination
418a4ed7 20 FROM forwardings
8415083e
IB
21 WHERE
22 ((regex = 1 AND '%s' REGEXP CONCAT('^',source,'$') ) OR (regex = 0 AND source = '%s'))
23 AND active = 1
24 AND '%s' NOT IN
25 (
26 SELECT source
27 FROM forwardings_blacklisted
28 WHERE source = '%s'
29 ) UNION
30 SELECT 'devnull@immae.eu'
a929614f
IB
31 FROM forwardings_blacklisted
32 WHERE source = '%s'
8415083e 33 '';
4c4652aa
IB
34 };
35 "postfix/ldap_mailboxes" = {
8415083e
IB
36 user = config.services.postfix.user;
37 group = config.services.postfix.group;
38 permissions = "0440";
39 text = ''
22b4bd78
IB
40 server_host = ldaps://${config.myEnv.mail.dovecot.ldap.host}:636
41 search_base = ${config.myEnv.mail.dovecot.ldap.base}
42 query_filter = ${config.myEnv.mail.dovecot.ldap.postfix_mailbox_filter}
43 bind_dn = ${config.myEnv.mail.dovecot.ldap.dn}
44 bind_pw = ${config.myEnv.mail.dovecot.ldap.password}
45 result_attribute = immaePostfixAddress
46 result_format = dummy
47 version = 3
a929614f 48 '';
4c4652aa
IB
49 };
50 "postfix/mysql_sender_login_maps" = {
8415083e
IB
51 user = config.services.postfix.user;
52 group = config.services.postfix.group;
53 permissions = "0440";
54 text = ''
55 # We need to specify that option to trigger ssl connection
56 tls_ciphers = TLSv1.2
ab8f306d
IB
57 user = ${config.myEnv.mail.postfix.mysql.user}
58 password = ${config.myEnv.mail.postfix.mysql.password}
59 hosts = unix:${config.myEnv.mail.postfix.mysql.socket}
60 dbname = ${config.myEnv.mail.postfix.mysql.database}
8415083e 61 query = SELECT DISTINCT destination
418a4ed7 62 FROM forwardings
8415083e 63 WHERE
d8c20bc3
IB
64 (
65 (regex = 1 AND CONCAT(SUBSTRING_INDEX('%u', '+', 1), '@%d') REGEXP CONCAT('^',source,'$') )
66 OR
67 (regex = 0 AND source = CONCAT(SUBSTRING_INDEX('%u', '+', 1), '@%d'))
68 )
8415083e 69 AND active = 1
d8c20bc3 70 UNION SELECT CONCAT(SUBSTRING_INDEX('%u', '+', 1), '@%d') AS destination
8415083e 71 '';
4c4652aa
IB
72 };
73 "postfix/mysql_sender_relays_maps" = {
87a8bffd
IB
74 user = config.services.postfix.user;
75 group = config.services.postfix.group;
76 permissions = "0440";
77 text = ''
78 # We need to specify that option to trigger ssl connection
79 tls_ciphers = TLSv1.2
80 user = ${config.myEnv.mail.postfix.mysql.user}
81 password = ${config.myEnv.mail.postfix.mysql.password}
82 hosts = unix:${config.myEnv.mail.postfix.mysql.socket}
83 dbname = ${config.myEnv.mail.postfix.mysql.database}
84 # INSERT INTO sender_relays
85 # (`from`, owner, relay, login, password, regex, active)
86 # VALUES
87 # ( 'sender@otherhost.org'
88 # , 'me@mail.immae.eu'
89 # , '[otherhost.org]:587'
90 # , 'otherhostlogin'
91 # , AES_ENCRYPT('otherhostpassword', '${config.myEnv.mail.postfix.mysql.password_encrypt}')
92 # , '0'
93 # , '1');
94
95 query = SELECT DISTINCT `owner`
96 FROM sender_relays
97 WHERE
98 ((regex = 1 AND '%s' REGEXP CONCAT('^',`from`,'$') ) OR (regex = 0 AND `from` = '%s'))
99 AND active = 1
100 '';
4c4652aa
IB
101 };
102 "postfix/mysql_sender_relays_hosts" = {
87a8bffd
IB
103 user = config.services.postfix.user;
104 group = config.services.postfix.group;
105 permissions = "0440";
106 text = ''
107 # We need to specify that option to trigger ssl connection
108 tls_ciphers = TLSv1.2
109 user = ${config.myEnv.mail.postfix.mysql.user}
110 password = ${config.myEnv.mail.postfix.mysql.password}
111 hosts = unix:${config.myEnv.mail.postfix.mysql.socket}
112 dbname = ${config.myEnv.mail.postfix.mysql.database}
113
114 query = SELECT DISTINCT relay
115 FROM sender_relays
116 WHERE
117 ((regex = 1 AND '%s' REGEXP CONCAT('^',`from`,'$') ) OR (regex = 0 AND `from` = '%s'))
118 AND active = 1
119 '';
4c4652aa
IB
120 };
121 "postfix/mysql_sender_relays_creds" = {
87a8bffd
IB
122 user = config.services.postfix.user;
123 group = config.services.postfix.group;
124 permissions = "0440";
125 text = ''
126 # We need to specify that option to trigger ssl connection
127 tls_ciphers = TLSv1.2
128 user = ${config.myEnv.mail.postfix.mysql.user}
129 password = ${config.myEnv.mail.postfix.mysql.password}
130 hosts = unix:${config.myEnv.mail.postfix.mysql.socket}
131 dbname = ${config.myEnv.mail.postfix.mysql.database}
132
133 query = SELECT DISTINCT CONCAT(`login`, ':', AES_DECRYPT(`password`, '${config.myEnv.mail.postfix.mysql.password_encrypt}'))
134 FROM sender_relays
135 WHERE
136 ((regex = 1 AND '%s' REGEXP CONCAT('^',`from`,'$') ) OR (regex = 0 AND `from` = '%s'))
137 AND active = 1
138 '';
4c4652aa
IB
139 };
140 "postfix/ldap_ejabberd_users_immae_fr" = {
5b53d86f
IB
141 user = config.services.postfix.user;
142 group = config.services.postfix.group;
143 permissions = "0440";
144 text = ''
145 server_host = ldaps://${config.myEnv.jabber.ldap.host}:636
146 search_base = ${config.myEnv.jabber.ldap.base}
147 query_filter = ${config.myEnv.jabber.postfix_user_filter}
148 domain = immae.fr
149 bind_dn = ${config.myEnv.jabber.ldap.dn}
150 bind_pw = ${config.myEnv.jabber.ldap.password}
151 result_attribute = immaeXmppUid
152 result_format = ejabberd@localhost
153 version = 3
154 '';
4c4652aa
IB
155 };
156 } // lib.mapAttrs' (name: v: lib.nameValuePair "postfix/scripts/${name}-env" {
31d99b75
IB
157 user = "postfixscripts";
158 group = "root";
159 permissions = "0400";
160 text = builtins.toJSON v.env;
4c4652aa 161 }) config.myEnv.mail.scripts;
a929614f 162
8415083e 163 networking.firewall.allowedTCPPorts = [ 25 465 587 ];
a929614f 164
31d99b75
IB
165 users.users.postfixscripts = {
166 group = "keys";
167 uid = config.ids.uids.postfixscripts;
168 description = "Postfix scripts user";
169 };
8415083e
IB
170 users.users."${config.services.postfix.user}".extraGroups = [ "keys" ];
171 services.filesWatcher.postfix = {
172 restart = true;
173 paths = [
174 config.secrets.fullPaths."postfix/mysql_alias_maps"
22b4bd78 175 config.secrets.fullPaths."postfix/ldap_mailboxes"
8415083e 176 config.secrets.fullPaths."postfix/mysql_sender_login_maps"
5b53d86f 177 config.secrets.fullPaths."postfix/ldap_ejabberd_users_immae_fr"
8415083e
IB
178 ];
179 };
180 services.postfix = {
2a61e9da
IB
181 extraAliases = let
182 toScript = name: script: pkgs.writeScript name ''
183 #! ${pkgs.stdenv.shell}
184 mail=$(${pkgs.coreutils}/bin/cat -)
185 output=$(echo "$mail" | ${script} 2>&1)
186 ret=$?
187
188 if [ "$ret" != "0" ]; then
189 echo "$mail" \
190 | ${pkgs.procmail}/bin/formail -i "X-Return-Code: $ret" \
191 | /run/wrappers/bin/sendmail -i scripts_error+${name}@mail.immae.eu
192
193 messageId=$(echo "$mail" | ${pkgs.procmail}/bin/formail -x "Message-Id:")
194 repeat=$(echo "$mail" | ${pkgs.procmail}/bin/formail -X "From:" -X "Received:")
195
196 ${pkgs.coreutils}/bin/cat <<EOF | /run/wrappers/bin/sendmail -i scripts_error+${name}@mail.immae.eu
197 $repeat
198 To: scripts_error+${name}@mail.immae.eu
199 Subject: Log from script error
200 Content-Type: text/plain; charset="UTF-8"
201 Content-Transfer-Encoding: 8bit
202 References:$messageId
203 MIME-Version: 1.0
204 X-Return-Code: $ret
205
206 Error code: $ret
207 Output of message:
208 --------------
209 $output
210 --------------
211 EOF
212 fi
213 '';
214 scripts = lib.attrsets.mapAttrs (n: v:
da30ae4f 215 toScript n (pkgs.callPackage (builtins.fetchGit { url = v.src.url; ref = "master"; rev = v.src.rev; }) { scriptEnv = config.secrets.fullPaths."postfix/scripts/${n}-env"; })
71a2425e
IB
216 ) config.myEnv.mail.scripts // {
217 testmail = pkgs.writeScript "testmail" ''
218 #! ${pkgs.stdenv.shell}
219 ${pkgs.coreutils}/bin/touch \
220 "/var/lib/naemon/checks/email/$(${pkgs.procmail}/bin/formail -x To: | ${pkgs.coreutils}/bin/tr -d ' <>')"
221 '';
222 };
2a61e9da 223 in builtins.concatStringsSep "\n" (lib.attrsets.mapAttrsToList (n: v: ''${n}: "|${v}"'') scripts);
8415083e
IB
224 mapFiles = let
225 recipient_maps = let
226 name = n: i: "relay_${n}_${toString i}";
227 pair = n: i: m: lib.attrsets.nameValuePair (name n i) (
228 if m.type == "hash"
229 then pkgs.writeText (name n i) m.content
04b2ab97 230 else null
8415083e
IB
231 );
232 pairs = n: v: lib.imap1 (i: m: pair n i m) v.recipient_maps;
233 in lib.attrsets.filterAttrs (k: v: v != null) (
234 lib.attrsets.listToAttrs (lib.flatten (
ab8f306d 235 lib.attrsets.mapAttrsToList pairs config.myEnv.mail.postfix.backup_domains
8415083e
IB
236 ))
237 );
238 relay_restrictions = lib.attrsets.filterAttrs (k: v: v != null) (
239 lib.attrsets.mapAttrs' (n: v:
240 lib.attrsets.nameValuePair "recipient_access_${n}" (
241 if lib.attrsets.hasAttr "relay_restrictions" v
242 then pkgs.writeText "recipient_access_${n}" v.relay_restrictions
243 else null
244 )
ab8f306d 245 ) config.myEnv.mail.postfix.backup_domains
8415083e 246 );
2a61e9da 247 virtual_map = {
71a2425e
IB
248 virtual = let
249 cfg = config.myEnv.monitoring.email_check.eldiron;
250 address = "${cfg.mail_address}@${cfg.mail_domain}";
251 in pkgs.writeText "postfix-virtual" (
2a61e9da 252 builtins.concatStringsSep "\n" (
71a2425e 253 ["${address} testmail@localhost"] ++
2a61e9da 254 lib.attrsets.mapAttrsToList (
5b53d86f 255 n: v: lib.optionalString v.external ''
2a61e9da
IB
256 script_${n}@mail.immae.eu ${n}@localhost, scripts@mail.immae.eu
257 ''
ab8f306d 258 ) config.myEnv.mail.scripts
2a61e9da
IB
259 )
260 );
261 };
deca5e9b 262 sasl_access = {
ef0a9217
IB
263 host_sender_login = with lib.attrsets; let
264 addresses = zipAttrs (lib.flatten (mapAttrsToList
265 (n: v: (map (e: { "${e}" = "${n}@immae.eu"; }) v.emails)) config.myEnv.servers));
266 joined = builtins.concatStringsSep ",";
267 in pkgs.writeText "host-sender-login"
268 (builtins.concatStringsSep "\n" (mapAttrsToList (n: v: "${n} ${joined v}") addresses));
deca5e9b 269 };
8415083e 270 in
deca5e9b 271 recipient_maps // relay_restrictions // virtual_map // sasl_access;
8415083e
IB
272 config = {
273 ### postfix module overrides
274 readme_directory = "${pkgs.postfix}/share/postfix/doc";
275 smtp_tls_CAfile = lib.mkForce "";
276 smtp_tls_cert_file = lib.mkForce "";
277 smtp_tls_key_file = lib.mkForce "";
a929614f 278
8415083e 279 message_size_limit = "1073741824"; # Don't put 0 here, it's not equivalent to "unlimited"
2a61e9da 280 mailbox_size_limit = "1073741825"; # Workaround, local delivered mails should all go through scripts
8415083e 281 alias_database = "\$alias_maps";
a929614f 282
31d99b75
IB
283 ### Aliases scripts user
284 default_privs = "postfixscripts";
285
8415083e 286 ### Virtual mailboxes config
418a4ed7
IB
287 virtual_alias_maps = [
288 "hash:/etc/postfix/virtual"
289 "mysql:${config.secrets.fullPaths."postfix/mysql_alias_maps"}"
290 "ldap:${config.secrets.fullPaths."postfix/ldap_ejabberd_users_immae_fr"}"
291 ];
ab8f306d 292 virtual_mailbox_domains = config.myEnv.mail.postfix.additional_mailbox_domains
ccb8bab4 293 ++ lib.remove null (lib.flatten (map
8415083e
IB
294 (zone: map
295 (e: if e.receive
296 then "${e.domain}${lib.optionalString (e.domain != "") "."}${zone.name}"
297 else null
298 )
299 (zone.withEmail or [])
a929614f 300 )
ab8f306d 301 config.myEnv.dns.masterZones
ccb8bab4 302 ));
418a4ed7 303 virtual_mailbox_maps = [
22b4bd78 304 "ldap:${config.secrets.fullPaths."postfix/ldap_mailboxes"}"
418a4ed7 305 ];
8415083e
IB
306 dovecot_destination_recipient_limit = "1";
307 virtual_transport = "dovecot";
a929614f 308
8415083e 309 ### Relay domains
ab8f306d 310 relay_domains = lib.flatten (lib.attrsets.mapAttrsToList (n: v: v.domains or []) config.myEnv.mail.postfix.backup_domains);
8415083e
IB
311 relay_recipient_maps = lib.flatten (lib.attrsets.mapAttrsToList (n: v:
312 lib.imap1 (i: m: "${m.type}:/etc/postfix/relay_${n}_${toString i}") v.recipient_maps
ab8f306d 313 ) config.myEnv.mail.postfix.backup_domains);
8415083e 314 smtpd_relay_restrictions = [
8415083e
IB
315 "defer_unauth_destination"
316 ] ++ lib.flatten (lib.attrsets.mapAttrsToList (n: v:
317 if lib.attrsets.hasAttr "relay_restrictions" v
318 then [ "check_recipient_access hash:/etc/postfix/recipient_access_${n}" ]
319 else []
ab8f306d 320 ) config.myEnv.mail.postfix.backup_domains);
a929614f 321
8415083e
IB
322 ### Additional smtpd configuration
323 smtpd_tls_received_header = "yes";
324 smtpd_tls_loglevel = "1";
a929614f 325
8415083e
IB
326 ### Email sending configuration
327 smtp_tls_security_level = "may";
328 smtp_tls_loglevel = "1";
a929614f 329
8415083e 330 ### Force ip bind for smtp
619e4f46
IB
331 smtp_bind_address = config.hostEnv.ips.main.ip4;
332 smtp_bind_address6 = builtins.head config.hostEnv.ips.main.ip6;
a929614f 333
87a8bffd
IB
334 # Use some relays when authorized senders are not myself
335 smtp_sasl_mechanism_filter = "plain,login"; # GSSAPI Not correctly supported by postfix
336 smtp_sasl_auth_enable = "yes";
337 smtp_sasl_password_maps =
338 "mysql:${config.secrets.fullPaths."postfix/mysql_sender_relays_creds"}";
339 smtp_sasl_security_options = "noanonymous";
340 smtp_sender_dependent_authentication = "yes";
341 sender_dependent_relayhost_maps =
342 "mysql:${config.secrets.fullPaths."postfix/mysql_sender_relays_hosts"}";
a929614f 343
8415083e
IB
344 ### opendkim, opendmarc, openarc milters
345 non_smtpd_milters = [
346 "unix:${config.myServices.mail.milters.sockets.opendkim}"
8415083e
IB
347 ];
348 smtpd_milters = [
349 "unix:${config.myServices.mail.milters.sockets.opendkim}"
8415083e 350 "unix:${config.myServices.mail.milters.sockets.openarc}"
619e4f46 351 "unix:${config.myServices.mail.milters.sockets.opendmarc}"
a929614f 352 ];
5153eb54
IB
353
354 smtp_use_tls = true;
355 smtpd_use_tls = true;
356 smtpd_tls_chain_files = builtins.concatStringsSep "," [ "/var/lib/acme/mail/full.pem" "/var/lib/acme/mail-rsa/full.pem" ];
6ea94404
IB
357
358 maximal_queue_lifetime = "6w";
359 bounce_queue_lifetime = "6w";
a929614f 360 };
8415083e
IB
361 enable = true;
362 enableSmtp = true;
363 enableSubmission = true;
364 submissionOptions = {
87a8bffd
IB
365 # Don’t use "long form", only commas (cf
366 # http://www.postfix.org/master.5.html long form is not handled
367 # well by the submission function)
8415083e
IB
368 smtpd_tls_security_level = "encrypt";
369 smtpd_sasl_auth_enable = "yes";
370 smtpd_tls_auth_only = "yes";
371 smtpd_sasl_tls_security_options = "noanonymous";
372 smtpd_sasl_type = "dovecot";
373 smtpd_sasl_path = "private/auth";
374 smtpd_reject_unlisted_recipient = "no";
375 smtpd_client_restrictions = "permit_sasl_authenticated,reject";
619e4f46 376 smtpd_relay_restrictions = "permit_sasl_authenticated,reject";
8415083e
IB
377 # Refuse to send e-mails with a From that is not handled
378 smtpd_sender_restrictions =
379 "reject_sender_login_mismatch,reject_unlisted_sender,permit_sasl_authenticated,reject";
87a8bffd
IB
380 smtpd_sender_login_maps = builtins.concatStringsSep "," [
381 "hash:/etc/postfix/host_sender_login"
382 "mysql:${config.secrets.fullPaths."postfix/mysql_sender_relays_maps"}"
383 "mysql:${config.secrets.fullPaths."postfix/mysql_sender_login_maps"}"
384 ];
8415083e
IB
385 smtpd_recipient_restrictions = "permit_sasl_authenticated,reject";
386 milter_macro_daemon_name = "ORIGINATING";
45730653
IB
387 smtpd_milters = builtins.concatStringsSep "," [
388 # FIXME: put it back when opensmtpd is upgraded and able to
389 # rewrite the from header
390 #"unix:/run/milter_verify_from/verify_from.sock"
391 "unix:${config.myServices.mail.milters.sockets.opendkim}"
392 ];
8415083e 393 };
8415083e
IB
394 destination = ["localhost"];
395 # This needs to reverse DNS
619e4f46 396 hostname = config.hostEnv.fqdn;
8415083e 397 setSendmail = true;
8415083e
IB
398 recipientDelimiter = "+";
399 masterConfig = {
400 submissions = {
401 type = "inet";
402 private = false;
403 command = "smtpd";
404 args = ["-o" "smtpd_tls_wrappermode=yes" ] ++ (let
405 mkKeyVal = opt: val: [ "-o" (opt + "=" + val) ];
406 in lib.concatLists (lib.mapAttrsToList mkKeyVal config.services.postfix.submissionOptions)
407 );
408 };
409 dovecot = {
410 type = "unix";
411 privileged = true;
412 chroot = false;
413 command = "pipe";
414 args = let
415 # rspamd could be used as a milter, but then it cannot apply
416 # its checks "per user" (milter is not yet dispatched to
417 # users), so we wrap dovecot-lda inside rspamc per recipient
418 # here.
dc6d3af9
IB
419 rspamc_dovecot = pkgs.writeScriptBin "rspamc_dovecot" ''
420 #! ${pkgs.stdenv.shell}
421 sender="$1"
422 original_recipient="$2"
423 user="$3"
424
425 ${pkgs.coreutils}/bin/cat - | \
426 (${pkgs.rspamd}/bin/rspamc -h ${config.myServices.mail.rspamd.sockets.worker-controller} -c bayes -d "$user" --mime || true) | \
427 ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -f "$sender" -a "$original_recipient" -d "$user"
428 '';
8415083e 429 in [
fb7611c1 430 "flags=ODRhu" "user=vhost:vhost"
dc6d3af9 431 "argv=${rspamc_dovecot}/bin/rspamc_dovecot \${sender} \${original_recipient} \${user}@\${nexthop}"
8415083e
IB
432 ];
433 };
434 };
a929614f 435 };
5400b9b6 436 security.acme.certs."mail" = {
8415083e
IB
437 postRun = ''
438 systemctl restart postfix.service
439 '';
440 extraDomains = {
514f9ec3
IB
441 "smtp.immae.eu" = null;
442 };
443 };
444 security.acme.certs."mail-rsa" = {
445 postRun = ''
446 systemctl restart postfix.service
447 '';
448 extraDomains = {
8415083e
IB
449 "smtp.immae.eu" = null;
450 };
a929614f 451 };
71a2425e
IB
452 system.activationScripts.testmail = {
453 deps = [ "users" ];
454 text = let
455 allCfg = config.myEnv.monitoring.email_check;
456 cfg = allCfg.eldiron;
457 reverseTargets = builtins.attrNames (lib.attrsets.filterAttrs (k: v: builtins.elem "eldiron" v.targets) allCfg);
458 to_email = cfg': host':
459 let sep = if lib.strings.hasInfix "+" cfg'.mail_address then "_" else "+";
460 in "${cfg'.mail_address}${sep}${host'}@${cfg'.mail_domain}";
461 mails_to_receive = builtins.concatStringsSep " " (map (to_email cfg) reverseTargets);
462 in ''
31d99b75 463 install -m 0555 -o postfixscripts -g keys -d /var/lib/naemon/checks/email
71a2425e
IB
464 for f in ${mails_to_receive}; do
465 if [ ! -f /var/lib/naemon/checks/email/$f ]; then
31d99b75 466 install -m 0644 -o postfixscripts -g keys /dev/null -T /var/lib/naemon/checks/email/$f
71a2425e
IB
467 touch -m -d @0 /var/lib/naemon/checks/email/$f
468 fi
469 done
470 '';
471 };
850adcf4 472 systemd.services.postfix.serviceConfig.Slice = "mail.slice";
a929614f
IB
473 };
474}