]> Git — Sourcephile - sourcephile-nix.git/blob - servers/mermet/dovecot.nix
mermet: add rspamd
[sourcephile-nix.git] / servers / mermet / dovecot.nix
1 { pkgs, lib, config, system, ... }:
2 let inherit (builtins) toString toFile;
3 inherit (builtins.extraBuiltins) pass;
4 inherit (lib) types;
5 inherit (pkgs.lib) loadFile unlines unlinesAttrs unlinesValues unwords;
6 inherit (config) networking;
7 inherit (config.services) dovecot2 postfix openldap;
8 when = x: y: if x == null then "" else y;
9 extSep = postfix.recipientDelimiter;
10 dirSep = extSep;
11 # NOTE: nixpkgs' dovecot2.stateDir is currently not exported
12 stateDir = "/var/lib/dovecot";
13 mailDir = "${stateDir}/mail";
14 sieveDir = "${stateDir}/sieve";
15 authDir = "${stateDir}/auth";
16 authUser = dovecot2.mailUser; # TODO: php_roundcube
17 authGroup = dovecot2.mailGroup; # TODO: php_roundcube
18 escapeGroup = lib.stringAsChars (c: if "a"<=c && c<="z"
19 || "0"<=c && c<="9"
20 || c=="-"
21 then c else "_");
22 domainGroup = escapeGroup "${networking.domainBase}";
23 etc_dovecot = [
24 { target = "dovecot/${networking.domain}/dovecot-ldap.conf";
25 source = pkgs.writeText "dovecot-ldap.conf" ''
26 ${lib.optionalString dovecot2.debug ''
27 debug_level = 1
28 ''}
29
30 # LDAP database
31 uris = ldapi://
32 base = ou=posix,${openldap.domainSuffix}
33 scope = subtree
34 deref = never
35 # NOTE: sufficient for small systems and uses less resources.
36 blocking = no
37
38 # LDAP auth
39 sasl_bind = yes
40 sasl_mech = EXTERNAL
41 #dn = cn=admin,${openldap.domainSuffix}
42 #dnpass = useless with sasl_mech=EXTERNAL
43 auth_bind = no
44 #auth_bind_userdn = cn=%n,ou=accounts,ou=posix,dc=${openldap.domainSuffix}
45
46 # dovecot passdb query
47 # DOC: http://wiki2.dovecot.org/PasswordDatabase/ExtraFields
48 pass_filter = (&(objectClass=posixAccount)(uid=%n)(mailEnabled=TRUE))
49 # TODO: userdb_quota_rule=*:storage=
50 pass_attrs = userPassword=password,\
51 uidNumber=userdb_uid,\
52 gidNumber=userdb_gid,\
53 mailGroupMember=userdb_mail_access_groups=${domainGroup},\
54 quotaBytes=userdb_quota_rule=*:bytes=%{ldap:quotaBytes},\
55 =user=%n@%d
56 #homeDirectory=userdb_home
57 default_pass_scheme = CRYPT
58
59 # dovecot userdb query
60 # DOC: http://wiki2.dovecot.org/UserDatabase/ExtraFields
61 user_filter = (&(objectClass=posixAccount)(uid=%n)(mailEnabled=TRUE))
62 #user_filter = (&(objectClass=inetOrgPerson)(uid=%n))
63 #user_attrs = homeDirectory=home,uidNumber=uid,gidNumber=gid
64 #user_attrs = mailHomeDirectory=home,\
65 # mailStorageDirectory=mail,\
66 # mailUidNumber=uid,\
67 # mailGidNumber=gid,\
68 # mailQuota=quota_rule=*:bytes=%$
69
70 # doveadm user query
71 iterate_attrs = =user=%{ldap:uid}@${networking.domain}
72 iterate_filter = (&(objectClass=posixAccount)(mailEnabled=TRUE))
73 '';
74 }
75 ];
76 dovecot-virtual = pkgs.writeTextFile {
77 name = "dovecot-virtual";
78 destination = "/pop3/INBOX/dovecot-virtual";
79 text = ''
80 all
81 all+*
82 all
83 '';
84 };
85
86 sieve-rspamd-filter =
87 pkgs.stdenv.mkDerivation {
88 name = "sieve-rspamd-filter";
89 nativeBuildInputs = [ pkgs.makeWrapper ];
90 phases = [ "installPhase" ];
91 installPhase = ''
92 mkdir -p $out/bin
93 cat >$out/bin/learn-spam.sh <<EOF
94 #!/bin/sh
95 exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd.sock learn_spam
96 EOF
97 cat >$out/bin/learn-ham.sh <<EOF
98 #!/bin/sh
99 exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd.sock learn_ham
100 EOF
101 chmod +x $out/bin/*.sh
102 '';
103 };
104 in
105 {
106 imports = [
107 dovecot/autoconfig.nix
108 ];
109 #services.postfix.mapFiles."transport-dovecot" =
110 # toFile "transport-dovecot"
111 # (unlines
112 # (lib.mapAttrsToList
113 # (dom: {...}: "${transportSubDomain}.${dom} lmtp:unix:private/dovecot-lmtp")
114 # dovecot2.domains));
115 /*
116 security.dhparams = {
117 enable = true;
118 params = {
119 dovecot2 = {bits = 1024;};
120 nginx = {path = pass "servers/mermet/dh/nginx.pem";};
121 };
122 };
123 */
124 systemd.services.dovecot2 = {
125 after = [
126 "postfix.service"
127 "openldap.service"
128 "dovecot.${networking.domainBase}.key.pem-key.service"
129 ];
130 restartTriggers = map (f: f.source) etc_dovecot;
131 };
132 deployment.keys = {
133 "dovecot.${networking.domainBase}.key.pem" = {
134 text = pass "x509/${networking.domainBase}/key.pem";
135 user = dovecot2.user;
136 group = "root";
137 destDir = "/run/keys/";
138 permissions = "0400"; # WARNING: not enforced when deployment.storeKeysOnMachine = true
139 };
140 };
141 environment.etc = etc_dovecot;
142 users.users."${dovecot2.mailUser}".isSystemUser = true; # Fix nixpkgs
143 services.dovecot2 = {
144 enable = true;
145 debug = true;
146 mailUser = "dovemail";
147 mailGroup = "dovemail";
148 modules = [
149 #pkgs.dovecot_antispam
150 pkgs.dovecot_pigeonhole
151 ];
152 sieves = {
153 global = {
154 list = ''
155 require
156 [ "date"
157 , "fileinto"
158 , "mailbox"
159 , "variables"
160 ];
161
162 if currentdate :matches "year" "*" { set "year" "''${1}"; }
163 if currentdate :matches "month" "*" { set "month" "''${1}"; }
164
165 if exists "List-ID" {
166 if header :matches "List-ID" "*<*.*.*.*>*" {
167 set "list" "''${2}";
168 set "domain" "''${4}";
169 }
170 elsif header :matches "List-ID" "*<*.*.*>*" {
171 set "list" "''${2}";
172 set "domain" "''${3}";
173 }
174 fileinto :create "Listes+''${domain}+''${list}+''${year}+''${month}";
175 stop;
176 }
177 '';
178 spam = ''
179 require
180 [ "imap4flags"
181 ];
182
183 if header :contains "X-Spam-Level" "***" {
184 addflag "Junk";
185 }
186 '';
187 /*
188 require ["fileinto","mailbox"];
189
190 if header :contains "X-Spam" "Yes" {
191 fileinto :create "INBOX.Junk";
192 stop;
193 }
194 */
195 extension = ''
196 require
197 [ "envelope"
198 , "fileinto"
199 , "mailbox"
200 , "subaddress"
201 , "variables"
202 ];
203 if envelope :matches :detail "TO" "*" {
204 set "extension" "''${1}";
205 }
206 if not string :is "''${extension}" "" {
207 fileinto :create "Plus+''${extension}";
208 stop;
209 }
210 '';
211 report-spam = ''
212 require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];
213
214 if environment :matches "imap.user" "*" {
215 set "username" "''${1}";
216 }
217
218 pipe :copy "learn-spam.sh" [ "''${username}" ];
219 '';
220 report-ham = ''
221 require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];
222
223 if environment :matches "imap.mailbox" "*" {
224 set "mailbox" "''${1}";
225 }
226
227 if string "''${mailbox}" "Trash" {
228 stop;
229 }
230
231 if environment :matches "imap.user" "*" {
232 set "username" "''${1}";
233 }
234
235 pipe :copy "learn-ham.sh" [ "''${username}" ];
236 '';
237 };
238 };
239 configFile = toString ( pkgs.writeText "dovecot.conf" ''
240 passdb {
241 driver = ldap
242 args = /etc/dovecot/${networking.domain}/dovecot-ldap.conf
243 default_fields = userdb_mail_access_groups=${domainGroup}
244 override_fields =
245 }
246 userdb {
247 driver = prefetch
248 }
249 userdb {
250 # NOTE: this userdb is only used by lda.
251 driver = ldap
252 args = /etc/dovecot/${networking.domain}/dovecot-ldap.conf
253 default_fields = mail_access_groups=${domainGroup}
254 override_fields =
255 skip = found
256 }
257 #passdb {
258 # driver = passwd-file
259 # args = scheme=crypt username_format=%n ${authDir}/%d/passwd
260 #}
261 #userdb {
262 # # NOTE: this userdb is only used by lda.
263 # driver = passwd-file
264 # args = username_format=%n ${authDir}/%d/passwd
265 # #default_fields = home=${mailDir}/%d/%n
266 # skip = found
267 #}
268 # NOTE: if needed, may be overrided by userdb_mail
269 mail_home = ${mailDir}/%d/%n
270 # NOTE: if needed, may be overrided by userdb_mail
271 # NOTE: INDEX and CONTROL are on a partition without quota, as explain in the doc.
272 # SEE: http://wiki2.dovecot.org/Quota/FS
273 mail_location = maildir:${mailDir}/%d/%n/Maildir:LAYOUT=fs:INDEX=${stateDir}/index/%d/%n:INDEXPVT=${stateDir}/index/%d/%n:CONTROL=${stateDir}/control/%d/%n
274 auth_mechanisms = plain login
275 # NOTE: postfix does not supply a client cert.
276 auth_ssl_require_client_cert = no
277 #auth_ssl_username_from_cert = yes
278 auth_verbose = yes
279 # NOTE: lowercase the username, help with LDAP?
280 auth_username_format = %Lu
281 ${lib.optionalString dovecot2.debug ''
282 auth_debug = yes
283 mail_debug = yes
284 verbose_ssl = yes
285 ''}
286 default_internal_user = ${dovecot2.user}
287 default_internal_group = ${dovecot2.group}
288 disable_plaintext_auth = yes
289 # NOTE: sync with LDAP's data.
290 first_valid_uid = 1000
291 lda_mailbox_autocreate = yes
292 lda_mailbox_autosubscribe = yes
293 listen = *
294 log_timestamp = "%Y-%m-%d %H:%M:%S "
295 #maildir_copy_with_hardlinks = yes
296 namespace inbox {
297 # NOTE: here because protocol sieve {namespace inbox{}} does not seem to work.
298 type = private
299 inbox = yes
300 location =
301 list = yes
302 prefix =
303 separator = ${dirSep}
304 }
305 namespace {
306 type = shared
307 #list = children
308 # NOTE: always listed in the LIST command.
309 list = yes
310 # NOTE: how to access the other users' mailboxes.
311 # NOTE: %var expands to the logged in user's variable, while
312 # %%var expands to the other users' variables.
313 # NOTE: INDEX and CONTROL are shared, INDEXPVT is not.
314 location = maildir:${mailDir}/%%d/%%n/Maildir:LAYOUT=fs:INDEX=${stateDir}/index/%%d/%%n/Shared:INDEXPVT=${stateDir}/index/%d/%n/Shared/%%n:CONTROL=${stateDir}/control/%d/%n/Shared
315 prefix = Partages+%%n+
316 separator = ${dirSep}
317 subscriptions = yes
318 }
319 mail_plugins = $mail_plugins acl quota virtual
320 #mail_uid = ${dovecot2.mailUser}
321 #mail_gid = ${dovecot2.mailGroup}
322 # NOTE: each user has a dedicated (uid,gid) pair
323 #mail_privileged_group = mail
324 #mail_access_groups =
325 plugin {
326 acl = vfile:/etc/dovecot/acl/global.d
327 acl_anyone = allow
328 # NOTE: to let users LIST mailboxes shared by other users,
329 # Dovecot needs a shared mailbox dictionary.
330 # FIXME: %d not working with userdb ldap
331 acl_shared_dict = file:${stateDir}/acl/%d/acl.db
332 ## NOTE: pour offlineimap
333 ##antispam_allow_append_to_spam = yes
334 #antispam_backend = pipe
335 ##antispam_crm_args = -u;${mailDir}/%d/.crm114;/usr/share/crm114/mailfilter.crm
336 #antispam_crm_args = -u;${mailDir}/crm114;/usr/share/crm114/mailfilter.crm
337 #antispam_crm_binary = /usr/bin/crm
338 #antispam_debug_target = syslog
339 ##antispam_crm_env = HOME=%h;USER=%u
340 #antispam_ham_keywords = NonJunk
341 #antispam_pipe_program = /usr/bin/crm
342 #antispam_pipe_program_args = -u;${mailDir}/crm114;/usr/share/crm114/mailfilter.crm;--stats_only;--force
343 #antispam_pipe_program_notspam_arg = --learnnonspam
344 #antispam_pipe_program_spam_arg = --learnspam
345 #antispam_pipe_program_unlearn_spam_args = --unlearn;--learnspam
346 #antispam_pipe_program_unlearn_notspam_args = --unlearn;--learnnonspam
347 #antispam_pipe_tmpdir = ${mailDir}/crm114/tmp
348 #antispam_signature = X-CRM114-CacheID
349 #antispam_signature_missing = move
350 #antispam_spam = Junk
351 #antispam_spam_keywords = Junk
352 #antispam_trash = Trash
353 #antispam_unsure = Unsure
354 #antispam_verbose_debug = 0
355 quota = maildir:User quota
356 quota_rule = *:storage=256M
357 quota_rule2 = Trash:storage=+64M
358 quota_max_mail_size = 20M
359 #quota_exceeded_message = </path/to/quota_exceeded_message.txt
360 quota_warning = storage=95%% quota-warning 95 %u
361 quota_warning2 = storage=80%% quota-warning 80 %u
362 quota_warning3 = -storage=100%% quota-warning below %u
363 recipient_delimiter = ${extSep}
364 sieve = file:${mailDir}/%d/%n/sieve;active=${mailDir}/%d/%n/sieve/main.sieve
365 #sieve_default = file:${mailDir}/%u/default.sieve
366 #sieve_default_name = default
367 sieve_after = ${sieveDir}/after.d/
368 sieve_before = ${sieveDir}/before.d/
369 sieve_dir = ${mailDir}/%d/%n/sieve/
370 #sieve_extensions = +spamtest +spamtestplus
371 sieve_global_dir = ${sieveDir}/global.d/
372 sieve_max_script_size = 1M
373 sieve_quota_max_scripts = 0
374 sieve_quota_max_storage = 10M
375 sieve_spamtest_max_value = 10
376 sieve_spamtest_status_header = X-Spam-Score
377 sieve_spamtest_status_type = strlen
378 sieve_user_log = /var/log/dovecot/%d/sieve.%n.log
379
380 sieve_plugins = sieve_imapsieve sieve_extprograms
381 sieve_pipe_bin_dir = ${sieve-rspamd-filter}/bin
382 sieve_global_extensions = +vnd.dovecot.pipe +vnd.dovecot.environment
383 # From elsewhere to Spam folder
384 imapsieve_mailbox1_name = Spam
385 imapsieve_mailbox1_causes = COPY
386 imapsieve_mailbox1_before = file:${sieveDir}/global.d/report-spam.sieve
387
388 # From Spam folder to elsewhere
389 imapsieve_mailbox2_name = *
390 imapsieve_mailbox2_from = Spam
391 imapsieve_mailbox2_causes = COPY
392 imapsieve_mailbox2_before = file:${sieveDir}/global.d/report-ham.sieve
393 }
394 # If you have Dovecot v2.2.8+ you may get a significant performance improvement with fetch-headers:
395 imapc_features = $imapc_features fetch-headers
396 # Read multiple mails in parallel, improves performance
397 mail_prefetch_count = 20
398 service quota-warning {
399 executable = script ${
400 pkgs.writeScript "quota-warning" ''
401 #!/bin/sh -eu
402 PERCENT=$1
403 USER=$2
404 cat << EOF | ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -d $USER -o
405 "plugin/quota=maildir:User quota:noenforcing"
406 From: postmaster@${networking.domain}
407 Subject: [WARNING] your mailbox is now $PERCENT% full.
408
409 Please remove some mails to make room for new ones.
410 EOF
411 ''
412 }
413 # use some unprivileged user for executing the quota warnings
414 user = ${dovecot2.user}
415 unix_listener quota-warning {
416 }
417 }
418 protocol imap {
419 #mail_max_userip_connections = 10
420 mail_plugins = $mail_plugins imap_acl imap_quota imap_sieve # antispam
421 namespace inbox {
422 inbox = yes
423 location =
424 list = yes
425 mailbox Drafts {
426 special_use = \Drafts
427 }
428 mailbox Junk {
429 special_use = \Junk
430 auto = subscribe
431 #autoexpunge = 30d
432 }
433 mailbox Sent {
434 special_use = \Sent
435 auto = subscribe
436 }
437 mailbox "Sent Messages" {
438 special_use = \Sent
439 auto = subscribe
440 }
441 mailbox Trash {
442 special_use = \Trash
443 auto = subscribe
444 #autoexpunge = 30d
445 }
446 prefix =
447 separator = ${dirSep}
448 }
449 }
450 protocol lda {
451 auth_socket_path = /var/run/dovecot/auth-userdb
452 hostname = ${networking.domain}
453 info_log_path =
454 log_path =
455 mail_plugins = $mail_plugins sieve
456 namespace inbox {
457 inbox = yes
458 location =
459 list = yes
460 prefix =
461 separator = ${dirSep}
462 }
463 postmaster_address = postmaster${extSep}dovecot${extSep}lda@${networking.domain}
464 syslog_facility = mail
465 }
466 protocol lmtp {
467 #info_log_path = /tmp/dovecot-lmtp.log
468 mail_plugins = $mail_plugins sieve
469 namespace inbox {
470 inbox = yes
471 location =
472 list = yes
473 prefix =
474 separator = ${dirSep}
475 }
476 postmaster_address = postmaster${extSep}dovecot${extSep}lmtp@${networking.domain}
477 }
478 protocol pop3 {
479 #mail_max_userip_connections = 10
480 namespace all {
481 # NOTE: used by ${dovecot-virtual}/pop3/INBOX/dovecot-virtual
482 hidden = yes
483 list = no
484 location =
485 prefix = all+
486 separator = ${dirSep}
487 }
488 # Virtual namespace for the virtual INBOX.
489 # Use a global directory for dovecot-virtual files.
490 namespace inbox {
491 inbox = yes
492 hidden = yes
493 list = no
494 location = virtual:${dovecot-virtual}/pop3:INDEX=${stateDir}/index/%d/%n/POP3:LAYOUT=fs
495 prefix = pop3+
496 separator = ${dirSep}
497 }
498 pop3_client_workarounds =
499 pop3_fast_size_lookups = yes
500 pop3_lock_session = yes
501 pop3_no_flag_updates = yes
502 # Use GUIDs to avoid accidental POP3 UIDL changes instead of IMAP UIDs.
503 pop3_uidl_format = %g
504 }
505 protocol sieve {
506 #mail_max_userip_connections = 10
507 #managesieve_implementation_string = Dovecot Pigeonhole
508 managesieve_max_compile_errors = 5
509 #managesieve_max_line_length = 65536
510 #managesieve_notify_capability = mailto
511 #managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date ihave
512 }
513 protocols = imap lmtp pop3 sieve
514 service lmtp {
515 #executable = lmtp -L
516 process_min_avail = 2
517 unix_listener /var/lib/postfix/queue/private/dovecot-lmtp {
518 user = ${postfix.user}
519 group = ${postfix.group}
520 mode = 0600
521 }
522 #user = mail
523 }
524 service auth {
525 # FIXME: may be user=dovecot-auth with LDAP?
526 user = root
527 unix_listener auth-userdb {
528 user = ${dovecot2.user}
529 group = ${dovecot2.group}
530 mode = 0660
531 }
532 unix_listener /var/lib/postfix/queue/private/auth {
533 user = ${postfix.user}
534 group = ${postfix.group}
535 mode = 0660
536 }
537 }
538 service imap {
539 # Most of the memory goes to mmap()ing files.
540 # You may need to increase this limit if you have huge mailboxes.
541 #vsz_limit =
542 process_limit = 1024
543 }
544 service imap-login {
545 #inet_listener imap {
546 # address = 127.0.0.1
547 # port = 143
548 # ssl = no
549 #}
550 inet_listener imaps {
551 port = 993
552 ssl = yes
553 }
554 }
555 service pop3 {
556 process_limit = 1024
557 }
558 service pop3-login {
559 inet_listener pop3s {
560 port = 995
561 ssl = yes
562 }
563 }
564 ssl = required
565 ssl_dh = <${../../../sec/openssl/dh.pem}
566 ssl_cipher_list = HIGH:!LOW:!SSLv2:!EXP:!aNULL
567 ssl_cert = <${loadFile (../../../sec + "/openssl/${networking.domainBase}/cert.self-signed.pem")}
568 ssl_key = </run/keys/dovecot.${networking.domainBase}.key.pem
569 #ssl_ca = <''${caPath}
570 #ssl_verify_client_cert = yes
571 '' );
572 #${lib.concatMapStringsSep "\n"
573 # (dom: ''
574 # local_name mail.${dom} {
575 # #ssl_ca = <''${caPath}
576 # ssl_cert = <${x509.cert dom}
577 # ssl_key = <${x509.key dom}
578 # }
579 # '')
580 # dovecot2.domains
581 #}
582 };
583 }