1 { pkgs, lib, config, system, ... }:
2 let inherit (builtins) toString toFile;
3 inherit (builtins.extraBuiltins) pass;
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;
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"
22 domainGroup = escapeGroup "${networking.domainBase}";
24 { target = "dovecot/${networking.domain}/dovecot-ldap.conf";
25 source = pkgs.writeText "dovecot-ldap.conf" ''
26 ${lib.optionalString dovecot2.debug ''
32 base = ou=posix,${openldap.domainSuffix}
35 # NOTE: sufficient for small systems and uses less resources.
41 #dn = cn=admin,${openldap.domainSuffix}
42 #dnpass = useless with sasl_mech=EXTERNAL
44 #auth_bind_userdn = cn=%n,ou=accounts,ou=posix,dc=${openldap.domainSuffix}
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},\
56 #homeDirectory=userdb_home
57 default_pass_scheme = CRYPT
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,\
68 # mailQuota=quota_rule=*:bytes=%$
71 iterate_attrs = =user=%{ldap:uid}@${networking.domain}
72 iterate_filter = (&(objectClass=posixAccount)(mailEnabled=TRUE))
76 dovecot-virtual = pkgs.writeTextFile {
77 name = "dovecot-virtual";
78 destination = "/pop3/INBOX/dovecot-virtual";
87 pkgs.stdenv.mkDerivation {
88 name = "sieve-rspamd-filter";
89 nativeBuildInputs = [ pkgs.makeWrapper ];
90 phases = [ "installPhase" ];
93 cat >$out/bin/learn-spam.sh <<EOF
95 exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd.sock learn_spam
97 cat >$out/bin/learn-ham.sh <<EOF
99 exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd.sock learn_ham
101 chmod +x $out/bin/*.sh
107 dovecot/autoconfig.nix
109 #services.postfix.mapFiles."transport-dovecot" =
110 # toFile "transport-dovecot"
112 # (lib.mapAttrsToList
113 # (dom: {...}: "${transportSubDomain}.${dom} lmtp:unix:private/dovecot-lmtp")
114 # dovecot2.domains));
116 security.dhparams = {
119 dovecot2 = {bits = 1024;};
120 nginx = {path = pass "servers/mermet/dh/nginx.pem";};
124 systemd.services.dovecot2 = {
128 "dovecot.${networking.domainBase}.key.pem-key.service"
130 restartTriggers = map (f: f.source) etc_dovecot;
133 "dovecot.${networking.domainBase}.key.pem" = {
134 text = pass "x509/${networking.domainBase}/key.pem";
135 user = dovecot2.user;
137 destDir = "/run/keys/";
138 permissions = "0400"; # WARNING: not enforced when deployment.storeKeysOnMachine = true
141 environment.etc = etc_dovecot;
142 users.users."${dovecot2.mailUser}".isSystemUser = true; # Fix nixpkgs
143 services.dovecot2 = {
146 mailUser = "dovemail";
147 mailGroup = "dovemail";
149 #pkgs.dovecot_antispam
150 pkgs.dovecot_pigeonhole
162 if currentdate :matches "year" "*" { set "year" "''${1}"; }
163 if currentdate :matches "month" "*" { set "month" "''${1}"; }
165 if exists "List-ID" {
166 if header :matches "List-ID" "*<*.*.*.*>*" {
168 set "domain" "''${4}";
170 elsif header :matches "List-ID" "*<*.*.*>*" {
172 set "domain" "''${3}";
174 fileinto :create "Listes+''${domain}+''${list}+''${year}+''${month}";
183 if header :contains "X-Spam-Level" "***" {
188 require ["fileinto","mailbox"];
190 if header :contains "X-Spam" "Yes" {
191 fileinto :create "INBOX.Junk";
203 if envelope :matches :detail "TO" "*" {
204 set "extension" "''${1}";
206 if not string :is "''${extension}" "" {
207 fileinto :create "Plus+''${extension}";
212 require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];
214 if environment :matches "imap.user" "*" {
215 set "username" "''${1}";
218 pipe :copy "learn-spam.sh" [ "''${username}" ];
221 require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];
223 if environment :matches "imap.mailbox" "*" {
224 set "mailbox" "''${1}";
227 if string "''${mailbox}" "Trash" {
231 if environment :matches "imap.user" "*" {
232 set "username" "''${1}";
235 pipe :copy "learn-ham.sh" [ "''${username}" ];
239 configFile = toString ( pkgs.writeText "dovecot.conf" ''
242 args = /etc/dovecot/${networking.domain}/dovecot-ldap.conf
243 default_fields = userdb_mail_access_groups=${domainGroup}
250 # NOTE: this userdb is only used by lda.
252 args = /etc/dovecot/${networking.domain}/dovecot-ldap.conf
253 default_fields = mail_access_groups=${domainGroup}
258 # driver = passwd-file
259 # args = scheme=crypt username_format=%n ${authDir}/%d/passwd
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
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
279 # NOTE: lowercase the username, help with LDAP?
280 auth_username_format = %Lu
281 ${lib.optionalString dovecot2.debug ''
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
294 log_timestamp = "%Y-%m-%d %H:%M:%S "
295 #maildir_copy_with_hardlinks = yes
297 # NOTE: here because protocol sieve {namespace inbox{}} does not seem to work.
303 separator = ${dirSep}
308 # NOTE: always listed in the LIST command.
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}
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 =
326 acl = vfile:/etc/dovecot/acl/global.d
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
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
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
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" ''
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.
409 Please remove some mails to make room for new ones.
413 # use some unprivileged user for executing the quota warnings
414 user = ${dovecot2.user}
415 unix_listener quota-warning {
419 #mail_max_userip_connections = 10
420 mail_plugins = $mail_plugins imap_acl imap_quota imap_sieve # antispam
426 special_use = \Drafts
437 mailbox "Sent Messages" {
447 separator = ${dirSep}
451 auth_socket_path = /var/run/dovecot/auth-userdb
452 hostname = ${networking.domain}
455 mail_plugins = $mail_plugins sieve
461 separator = ${dirSep}
463 postmaster_address = postmaster${extSep}dovecot${extSep}lda@${networking.domain}
464 syslog_facility = mail
467 #info_log_path = /tmp/dovecot-lmtp.log
468 mail_plugins = $mail_plugins sieve
474 separator = ${dirSep}
476 postmaster_address = postmaster${extSep}dovecot${extSep}lmtp@${networking.domain}
479 #mail_max_userip_connections = 10
481 # NOTE: used by ${dovecot-virtual}/pop3/INBOX/dovecot-virtual
486 separator = ${dirSep}
488 # Virtual namespace for the virtual INBOX.
489 # Use a global directory for dovecot-virtual files.
494 location = virtual:${dovecot-virtual}/pop3:INDEX=${stateDir}/index/%d/%n/POP3:LAYOUT=fs
496 separator = ${dirSep}
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
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
513 protocols = imap lmtp pop3 sieve
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}
525 # FIXME: may be user=dovecot-auth with LDAP?
527 unix_listener auth-userdb {
528 user = ${dovecot2.user}
529 group = ${dovecot2.group}
532 unix_listener /var/lib/postfix/queue/private/auth {
533 user = ${postfix.user}
534 group = ${postfix.group}
539 # Most of the memory goes to mmap()ing files.
540 # You may need to increase this limit if you have huge mailboxes.
545 #inet_listener imap {
546 # address = 127.0.0.1
550 inet_listener imaps {
559 inet_listener pop3s {
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
572 #${lib.concatMapStringsSep "\n"
574 # local_name mail.${dom} {
575 # #ssl_ca = <''${caPath}
576 # ssl_cert = <${x509.cert dom}
577 # ssl_key = <${x509.key dom}