]> git.immae.eu Git - perso/Immae/Config/Nix.git/blame - modules/private/mail/postfix.nix
Add status page for monitoring host
[perso/Immae/Config/Nix.git] / modules / private / mail / postfix.nix
CommitLineData
ab8f306d 1{ lib, pkgs, config, ... }:
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 };
8415083e 189 in
2a61e9da 190 recipient_maps // relay_restrictions // virtual_map;
8415083e
IB
191 config = {
192 ### postfix module overrides
193 readme_directory = "${pkgs.postfix}/share/postfix/doc";
194 smtp_tls_CAfile = lib.mkForce "";
195 smtp_tls_cert_file = lib.mkForce "";
196 smtp_tls_key_file = lib.mkForce "";
a929614f 197
8415083e 198 message_size_limit = "1073741824"; # Don't put 0 here, it's not equivalent to "unlimited"
2a61e9da 199 mailbox_size_limit = "1073741825"; # Workaround, local delivered mails should all go through scripts
8415083e 200 alias_database = "\$alias_maps";
a929614f 201
8415083e 202 ### Virtual mailboxes config
5b53d86f 203 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 204 virtual_mailbox_domains = config.myEnv.mail.postfix.additional_mailbox_domains
8415083e
IB
205 ++ lib.remove "localhost.immae.eu" (lib.remove null (lib.flatten (map
206 (zone: map
207 (e: if e.receive
208 then "${e.domain}${lib.optionalString (e.domain != "") "."}${zone.name}"
209 else null
210 )
211 (zone.withEmail or [])
a929614f 212 )
ab8f306d 213 config.myEnv.dns.masterZones
8415083e
IB
214 )));
215 virtual_mailbox_maps = "mysql:${config.secrets.fullPaths."postfix/mysql_mailbox_maps"}";
216 dovecot_destination_recipient_limit = "1";
217 virtual_transport = "dovecot";
a929614f 218
8415083e 219 ### Relay domains
ab8f306d 220 relay_domains = lib.flatten (lib.attrsets.mapAttrsToList (n: v: v.domains or []) config.myEnv.mail.postfix.backup_domains);
8415083e
IB
221 relay_recipient_maps = lib.flatten (lib.attrsets.mapAttrsToList (n: v:
222 lib.imap1 (i: m: "${m.type}:/etc/postfix/relay_${n}_${toString i}") v.recipient_maps
ab8f306d 223 ) config.myEnv.mail.postfix.backup_domains);
8415083e
IB
224 smtpd_relay_restrictions = [
225 "permit_mynetworks"
226 "permit_sasl_authenticated"
227 "defer_unauth_destination"
228 ] ++ lib.flatten (lib.attrsets.mapAttrsToList (n: v:
229 if lib.attrsets.hasAttr "relay_restrictions" v
230 then [ "check_recipient_access hash:/etc/postfix/recipient_access_${n}" ]
231 else []
ab8f306d 232 ) config.myEnv.mail.postfix.backup_domains);
a929614f 233
8415083e
IB
234 ### Additional smtpd configuration
235 smtpd_tls_received_header = "yes";
236 smtpd_tls_loglevel = "1";
a929614f 237
8415083e
IB
238 ### Email sending configuration
239 smtp_tls_security_level = "may";
240 smtp_tls_loglevel = "1";
a929614f 241
8415083e 242 ### Force ip bind for smtp
ab8f306d
IB
243 smtp_bind_address = config.myEnv.servers.eldiron.ips.main.ip4;
244 smtp_bind_address6 = builtins.head config.myEnv.servers.eldiron.ips.main.ip6;
a929614f 245
8415083e
IB
246 # #Unneeded if postfix can only send e-mail from "self" domains
247 # #smtp_sasl_auth_enable = "yes";
248 # #smtp_sasl_password_maps = "hash:/etc/postfix/relay_creds";
249 # #smtp_sasl_security_options = "noanonymous";
250 # #smtp_sender_dependent_authentication = "yes";
251 # #sender_dependent_relayhost_maps = "hash:/etc/postfix/sender_relay";
a929614f 252
8415083e
IB
253 ### opendkim, opendmarc, openarc milters
254 non_smtpd_milters = [
255 "unix:${config.myServices.mail.milters.sockets.opendkim}"
256 "unix:${config.myServices.mail.milters.sockets.opendmarc}"
257 "unix:${config.myServices.mail.milters.sockets.openarc}"
258 ];
259 smtpd_milters = [
260 "unix:${config.myServices.mail.milters.sockets.opendkim}"
261 "unix:${config.myServices.mail.milters.sockets.opendmarc}"
262 "unix:${config.myServices.mail.milters.sockets.openarc}"
a929614f
IB
263 ];
264 };
8415083e
IB
265 enable = true;
266 enableSmtp = true;
267 enableSubmission = true;
268 submissionOptions = {
269 smtpd_tls_security_level = "encrypt";
270 smtpd_sasl_auth_enable = "yes";
271 smtpd_tls_auth_only = "yes";
272 smtpd_sasl_tls_security_options = "noanonymous";
273 smtpd_sasl_type = "dovecot";
274 smtpd_sasl_path = "private/auth";
275 smtpd_reject_unlisted_recipient = "no";
276 smtpd_client_restrictions = "permit_sasl_authenticated,reject";
277 # Refuse to send e-mails with a From that is not handled
278 smtpd_sender_restrictions =
279 "reject_sender_login_mismatch,reject_unlisted_sender,permit_sasl_authenticated,reject";
280 smtpd_sender_login_maps = "mysql:${config.secrets.fullPaths."postfix/mysql_sender_login_maps"}";
281 smtpd_recipient_restrictions = "permit_sasl_authenticated,reject";
282 milter_macro_daemon_name = "ORIGINATING";
283 smtpd_milters = "unix:${config.myServices.mail.milters.sockets.opendkim}";
284 };
285 # FIXME: Mail adressed to localhost.immae.eu will still have mx-1 as
286 # prioritized MX, which provokes "mail for localhost.immae.eu loops
287 # back to myself" errors. This transport entry forces to push
288 # e-mails to its right destination.
289 transport = ''
290 localhost.immae.eu smtp:[immae.eu]:25
291 '';
292 destination = ["localhost"];
293 # This needs to reverse DNS
294 hostname = "eldiron.immae.eu";
295 setSendmail = true;
296 sslCert = "/var/lib/acme/mail/fullchain.pem";
297 sslKey = "/var/lib/acme/mail/key.pem";
298 recipientDelimiter = "+";
299 masterConfig = {
300 submissions = {
301 type = "inet";
302 private = false;
303 command = "smtpd";
304 args = ["-o" "smtpd_tls_wrappermode=yes" ] ++ (let
305 mkKeyVal = opt: val: [ "-o" (opt + "=" + val) ];
306 in lib.concatLists (lib.mapAttrsToList mkKeyVal config.services.postfix.submissionOptions)
307 );
308 };
309 dovecot = {
310 type = "unix";
311 privileged = true;
312 chroot = false;
313 command = "pipe";
314 args = let
315 # rspamd could be used as a milter, but then it cannot apply
316 # its checks "per user" (milter is not yet dispatched to
317 # users), so we wrap dovecot-lda inside rspamc per recipient
318 # here.
dc6d3af9
IB
319 rspamc_dovecot = pkgs.writeScriptBin "rspamc_dovecot" ''
320 #! ${pkgs.stdenv.shell}
321 sender="$1"
322 original_recipient="$2"
323 user="$3"
324
325 ${pkgs.coreutils}/bin/cat - | \
326 (${pkgs.rspamd}/bin/rspamc -h ${config.myServices.mail.rspamd.sockets.worker-controller} -c bayes -d "$user" --mime || true) | \
327 ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -f "$sender" -a "$original_recipient" -d "$user"
328 '';
8415083e
IB
329 in [
330 "flags=DRhu" "user=vhost:vhost"
dc6d3af9 331 "argv=${rspamc_dovecot}/bin/rspamc_dovecot \${sender} \${original_recipient} \${user}@\${nexthop}"
8415083e
IB
332 ];
333 };
334 };
a929614f 335 };
8415083e
IB
336 security.acme.certs."mail" = {
337 postRun = ''
338 systemctl restart postfix.service
339 '';
340 extraDomains = {
341 "smtp.immae.eu" = null;
342 };
a929614f
IB
343 };
344 };
345}