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