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