]> git.immae.eu Git - perso/Immae/Config/Nix.git/blame - modules/private/mail/postfix.nix
Add backup directory for oldies
[perso/Immae/Config/Nix.git] / modules / private / mail / postfix.nix
CommitLineData
deca5e9b 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 '';
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 }
5b53d86f
IB
83 {
84 dest = "postfix/ldap_ejabberd_users_immae_fr";
85 user = config.services.postfix.user;
86 group = config.services.postfix.group;
87 permissions = "0440";
88 text = ''
89 server_host = ldaps://${config.myEnv.jabber.ldap.host}:636
90 search_base = ${config.myEnv.jabber.ldap.base}
91 query_filter = ${config.myEnv.jabber.postfix_user_filter}
92 domain = immae.fr
93 bind_dn = ${config.myEnv.jabber.ldap.dn}
94 bind_pw = ${config.myEnv.jabber.ldap.password}
95 result_attribute = immaeXmppUid
96 result_format = ejabberd@localhost
97 version = 3
98 '';
99 }
8415083e 100 ];
a929614f 101
8415083e 102 networking.firewall.allowedTCPPorts = [ 25 465 587 ];
a929614f 103
8415083e
IB
104 nixpkgs.overlays = [ (self: super: {
105 postfix = super.postfix.override { withMySQL = true; };
106 }) ];
107 users.users."${config.services.postfix.user}".extraGroups = [ "keys" ];
108 services.filesWatcher.postfix = {
109 restart = true;
110 paths = [
111 config.secrets.fullPaths."postfix/mysql_alias_maps"
112 config.secrets.fullPaths."postfix/mysql_mailbox_maps"
113 config.secrets.fullPaths."postfix/mysql_sender_login_maps"
5b53d86f 114 config.secrets.fullPaths."postfix/ldap_ejabberd_users_immae_fr"
8415083e
IB
115 ];
116 };
117 services.postfix = {
2a61e9da
IB
118 extraAliases = let
119 toScript = name: script: pkgs.writeScript name ''
120 #! ${pkgs.stdenv.shell}
121 mail=$(${pkgs.coreutils}/bin/cat -)
122 output=$(echo "$mail" | ${script} 2>&1)
123 ret=$?
124
125 if [ "$ret" != "0" ]; then
126 echo "$mail" \
127 | ${pkgs.procmail}/bin/formail -i "X-Return-Code: $ret" \
128 | /run/wrappers/bin/sendmail -i scripts_error+${name}@mail.immae.eu
129
130 messageId=$(echo "$mail" | ${pkgs.procmail}/bin/formail -x "Message-Id:")
131 repeat=$(echo "$mail" | ${pkgs.procmail}/bin/formail -X "From:" -X "Received:")
132
133 ${pkgs.coreutils}/bin/cat <<EOF | /run/wrappers/bin/sendmail -i scripts_error+${name}@mail.immae.eu
134 $repeat
135 To: scripts_error+${name}@mail.immae.eu
136 Subject: Log from script error
137 Content-Type: text/plain; charset="UTF-8"
138 Content-Transfer-Encoding: 8bit
139 References:$messageId
140 MIME-Version: 1.0
141 X-Return-Code: $ret
142
143 Error code: $ret
144 Output of message:
145 --------------
146 $output
147 --------------
148 EOF
149 fi
150 '';
151 scripts = lib.attrsets.mapAttrs (n: v:
152 toScript n (pkgs.callPackage (builtins.fetchGit { url = v.src.url; ref = "master"; rev = v.src.rev; }) { scriptEnv = v.env; })
ab8f306d 153 ) config.myEnv.mail.scripts;
2a61e9da 154 in builtins.concatStringsSep "\n" (lib.attrsets.mapAttrsToList (n: v: ''${n}: "|${v}"'') scripts);
8415083e
IB
155 mapFiles = let
156 recipient_maps = let
157 name = n: i: "relay_${n}_${toString i}";
158 pair = n: i: m: lib.attrsets.nameValuePair (name n i) (
159 if m.type == "hash"
160 then pkgs.writeText (name n i) m.content
04b2ab97 161 else null
8415083e
IB
162 );
163 pairs = n: v: lib.imap1 (i: m: pair n i m) v.recipient_maps;
164 in lib.attrsets.filterAttrs (k: v: v != null) (
165 lib.attrsets.listToAttrs (lib.flatten (
ab8f306d 166 lib.attrsets.mapAttrsToList pairs config.myEnv.mail.postfix.backup_domains
8415083e
IB
167 ))
168 );
169 relay_restrictions = lib.attrsets.filterAttrs (k: v: v != null) (
170 lib.attrsets.mapAttrs' (n: v:
171 lib.attrsets.nameValuePair "recipient_access_${n}" (
172 if lib.attrsets.hasAttr "relay_restrictions" v
173 then pkgs.writeText "recipient_access_${n}" v.relay_restrictions
174 else null
175 )
ab8f306d 176 ) config.myEnv.mail.postfix.backup_domains
8415083e 177 );
2a61e9da
IB
178 virtual_map = {
179 virtual = pkgs.writeText "postfix-virtual" (
180 builtins.concatStringsSep "\n" (
181 lib.attrsets.mapAttrsToList (
5b53d86f 182 n: v: lib.optionalString v.external ''
2a61e9da
IB
183 script_${n}@mail.immae.eu ${n}@localhost, scripts@mail.immae.eu
184 ''
ab8f306d 185 ) config.myEnv.mail.scripts
2a61e9da
IB
186 )
187 );
188 };
deca5e9b
IB
189 sasl_access = {
190 host_sender_login = pkgs.writeText "host-sender-login"
191 (builtins.concatStringsSep "\n" (lib.flatten (lib.attrsets.mapAttrsToList
192 (n: v: (map (e: "${e} ${n}@immae.eu") v.emails)) config.myEnv.servers)));
193 host_dummy_mailboxes = pkgs.writeText "host-virtual-mailbox"
194 (builtins.concatStringsSep "\n" (lib.attrsets.mapAttrsToList (n: v: "${n}@immae.eu dummy") nodes));
195 };
8415083e 196 in
deca5e9b 197 recipient_maps // relay_restrictions // virtual_map // sasl_access;
8415083e
IB
198 config = {
199 ### postfix module overrides
200 readme_directory = "${pkgs.postfix}/share/postfix/doc";
201 smtp_tls_CAfile = lib.mkForce "";
202 smtp_tls_cert_file = lib.mkForce "";
203 smtp_tls_key_file = lib.mkForce "";
a929614f 204
8415083e 205 message_size_limit = "1073741824"; # Don't put 0 here, it's not equivalent to "unlimited"
2a61e9da 206 mailbox_size_limit = "1073741825"; # Workaround, local delivered mails should all go through scripts
8415083e 207 alias_database = "\$alias_maps";
a929614f 208
8415083e 209 ### Virtual mailboxes config
5b53d86f 210 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 211 virtual_mailbox_domains = config.myEnv.mail.postfix.additional_mailbox_domains
8415083e
IB
212 ++ lib.remove "localhost.immae.eu" (lib.remove null (lib.flatten (map
213 (zone: map
214 (e: if e.receive
215 then "${e.domain}${lib.optionalString (e.domain != "") "."}${zone.name}"
216 else null
217 )
218 (zone.withEmail or [])
a929614f 219 )
ab8f306d 220 config.myEnv.dns.masterZones
8415083e 221 )));
deca5e9b 222 virtual_mailbox_maps = "hash:/etc/postfix/host_dummy_mailboxes mysql:${config.secrets.fullPaths."postfix/mysql_mailbox_maps"}";
8415083e
IB
223 dovecot_destination_recipient_limit = "1";
224 virtual_transport = "dovecot";
a929614f 225
8415083e 226 ### Relay domains
ab8f306d 227 relay_domains = lib.flatten (lib.attrsets.mapAttrsToList (n: v: v.domains or []) config.myEnv.mail.postfix.backup_domains);
8415083e
IB
228 relay_recipient_maps = lib.flatten (lib.attrsets.mapAttrsToList (n: v:
229 lib.imap1 (i: m: "${m.type}:/etc/postfix/relay_${n}_${toString i}") v.recipient_maps
ab8f306d 230 ) config.myEnv.mail.postfix.backup_domains);
8415083e
IB
231 smtpd_relay_restrictions = [
232 "permit_mynetworks"
233 "permit_sasl_authenticated"
234 "defer_unauth_destination"
235 ] ++ lib.flatten (lib.attrsets.mapAttrsToList (n: v:
236 if lib.attrsets.hasAttr "relay_restrictions" v
237 then [ "check_recipient_access hash:/etc/postfix/recipient_access_${n}" ]
238 else []
ab8f306d 239 ) config.myEnv.mail.postfix.backup_domains);
a929614f 240
8415083e
IB
241 ### Additional smtpd configuration
242 smtpd_tls_received_header = "yes";
243 smtpd_tls_loglevel = "1";
a929614f 244
8415083e
IB
245 ### Email sending configuration
246 smtp_tls_security_level = "may";
247 smtp_tls_loglevel = "1";
a929614f 248
8415083e 249 ### Force ip bind for smtp
ab8f306d
IB
250 smtp_bind_address = config.myEnv.servers.eldiron.ips.main.ip4;
251 smtp_bind_address6 = builtins.head config.myEnv.servers.eldiron.ips.main.ip6;
a929614f 252
8415083e
IB
253 # #Unneeded if postfix can only send e-mail from "self" domains
254 # #smtp_sasl_auth_enable = "yes";
255 # #smtp_sasl_password_maps = "hash:/etc/postfix/relay_creds";
256 # #smtp_sasl_security_options = "noanonymous";
257 # #smtp_sender_dependent_authentication = "yes";
258 # #sender_dependent_relayhost_maps = "hash:/etc/postfix/sender_relay";
a929614f 259
8415083e
IB
260 ### opendkim, opendmarc, openarc milters
261 non_smtpd_milters = [
262 "unix:${config.myServices.mail.milters.sockets.opendkim}"
263 "unix:${config.myServices.mail.milters.sockets.opendmarc}"
264 "unix:${config.myServices.mail.milters.sockets.openarc}"
265 ];
266 smtpd_milters = [
267 "unix:${config.myServices.mail.milters.sockets.opendkim}"
268 "unix:${config.myServices.mail.milters.sockets.opendmarc}"
269 "unix:${config.myServices.mail.milters.sockets.openarc}"
a929614f
IB
270 ];
271 };
8415083e
IB
272 enable = true;
273 enableSmtp = true;
274 enableSubmission = true;
275 submissionOptions = {
276 smtpd_tls_security_level = "encrypt";
277 smtpd_sasl_auth_enable = "yes";
278 smtpd_tls_auth_only = "yes";
279 smtpd_sasl_tls_security_options = "noanonymous";
280 smtpd_sasl_type = "dovecot";
281 smtpd_sasl_path = "private/auth";
282 smtpd_reject_unlisted_recipient = "no";
283 smtpd_client_restrictions = "permit_sasl_authenticated,reject";
284 # Refuse to send e-mails with a From that is not handled
285 smtpd_sender_restrictions =
286 "reject_sender_login_mismatch,reject_unlisted_sender,permit_sasl_authenticated,reject";
deca5e9b 287 smtpd_sender_login_maps = "hash:/etc/postfix/host_sender_login,mysql:${config.secrets.fullPaths."postfix/mysql_sender_login_maps"}";
8415083e
IB
288 smtpd_recipient_restrictions = "permit_sasl_authenticated,reject";
289 milter_macro_daemon_name = "ORIGINATING";
290 smtpd_milters = "unix:${config.myServices.mail.milters.sockets.opendkim}";
291 };
292 # FIXME: Mail adressed to localhost.immae.eu will still have mx-1 as
293 # prioritized MX, which provokes "mail for localhost.immae.eu loops
294 # back to myself" errors. This transport entry forces to push
295 # e-mails to its right destination.
296 transport = ''
297 localhost.immae.eu smtp:[immae.eu]:25
298 '';
299 destination = ["localhost"];
300 # This needs to reverse DNS
301 hostname = "eldiron.immae.eu";
302 setSendmail = true;
303 sslCert = "/var/lib/acme/mail/fullchain.pem";
304 sslKey = "/var/lib/acme/mail/key.pem";
305 recipientDelimiter = "+";
306 masterConfig = {
307 submissions = {
308 type = "inet";
309 private = false;
310 command = "smtpd";
311 args = ["-o" "smtpd_tls_wrappermode=yes" ] ++ (let
312 mkKeyVal = opt: val: [ "-o" (opt + "=" + val) ];
313 in lib.concatLists (lib.mapAttrsToList mkKeyVal config.services.postfix.submissionOptions)
314 );
315 };
316 dovecot = {
317 type = "unix";
318 privileged = true;
319 chroot = false;
320 command = "pipe";
321 args = let
322 # rspamd could be used as a milter, but then it cannot apply
323 # its checks "per user" (milter is not yet dispatched to
324 # users), so we wrap dovecot-lda inside rspamc per recipient
325 # here.
dc6d3af9
IB
326 rspamc_dovecot = pkgs.writeScriptBin "rspamc_dovecot" ''
327 #! ${pkgs.stdenv.shell}
328 sender="$1"
329 original_recipient="$2"
330 user="$3"
331
332 ${pkgs.coreutils}/bin/cat - | \
333 (${pkgs.rspamd}/bin/rspamc -h ${config.myServices.mail.rspamd.sockets.worker-controller} -c bayes -d "$user" --mime || true) | \
334 ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -f "$sender" -a "$original_recipient" -d "$user"
335 '';
8415083e
IB
336 in [
337 "flags=DRhu" "user=vhost:vhost"
dc6d3af9 338 "argv=${rspamc_dovecot}/bin/rspamc_dovecot \${sender} \${original_recipient} \${user}@\${nexthop}"
8415083e
IB
339 ];
340 };
341 };
a929614f 342 };
8415083e
IB
343 security.acme.certs."mail" = {
344 postRun = ''
345 systemctl restart postfix.service
346 '';
347 extraDomains = {
348 "smtp.immae.eu" = null;
349 };
a929614f
IB
350 };
351 };
352}