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