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";
86 learn-spam = pkgs.writeShellScriptBin "learn-spam.sh" ''
87 exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd/learner.sock learn_spam
89 learn-ham = pkgs.writeShellScriptBin "learn-ham.sh" ''
90 exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd/learner.sock learn_ham
92 sieve_pipe_bin_dir = pkgs.buildEnv {
93 name = "sieve_pipe_bin_dir";
94 pathsToLink = [ "/bin" ];
103 dovecot/autoconfig.nix
105 #services.postfix.mapFiles."transport-dovecot" =
106 # toFile "transport-dovecot"
108 # (lib.mapAttrsToList
109 # (dom: {...}: "${transportSubDomain}.${dom} lmtp:unix:private/dovecot-lmtp")
110 # dovecot2.domains));
111 systemd.services.dovecot2 = {
115 "dovecot.${networking.domainBase}.key.pem-key.service"
117 restartTriggers = map (f: f.source) etc_dovecot;
120 "dovecot.${networking.domainBase}.key.pem" = {
121 text = pass "x509/${networking.domainBase}/key.pem";
122 user = dovecot2.user;
124 destDir = "/run/keys/";
125 permissions = "0400"; # WARNING: not enforced when deployment.storeKeysOnMachine = true
128 environment.etc = etc_dovecot;
129 users.users."${dovecot2.mailUser}".isSystemUser = true; # Fix nixpkgs
130 services.dovecot2 = {
133 mailUser = "dovemail";
134 mailGroup = "dovemail";
136 #pkgs.dovecot_antispam
137 pkgs.dovecot_pigeonhole
149 if currentdate :matches "year" "*" { set "year" "''${1}"; }
150 if currentdate :matches "month" "*" { set "month" "''${1}"; }
152 if exists "List-ID" {
153 if header :matches "List-ID" "*<*.*.*.*>*" {
155 set "domain" "''${4}";
157 elsif header :matches "List-ID" "*<*.*.*>*" {
159 set "domain" "''${3}";
161 fileinto :create "Listes+''${domain}+''${list}+''${year}+''${month}";
166 require [ "imap4flags" ];
168 if header :contains "X-Spam-Level" "***" {
173 require ["fileinto","mailbox"];
175 if header :contains "X-Spam" "Yes" {
176 fileinto :create "INBOX.Junk";
188 if envelope :matches :detail "TO" "*" {
189 set "extension" "''${1}";
191 if not string :is "''${extension}" "" {
192 fileinto :create "Plus+''${extension}";
197 require ["vnd.dovecot.pipe", "copy", "imapsieve", "variables", "imap4flags", "environment"];
199 if environment :is "imap.changedflags" "Junk" {
200 if hasflag :is "Junk" {
201 pipe :copy :try "learn-spam.sh";
202 } elsif not hasflag :is "Junk" {
203 pipe :copy :try "learn-ham.sh";
208 require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];
210 if environment :matches "imap.user" "*" {
211 set "username" "''${1}";
214 pipe :copy :try "learn-spam.sh" [ "''${username}" ];
217 require ["vnd.dovecot.pipe", "copy", "imapsieve", "environment", "variables"];
219 if environment :matches "imap.mailbox" "*" {
220 set "mailbox" "''${1}";
223 if string "''${mailbox}" "Trash" {
227 if environment :matches "imap.user" "*" {
228 set "username" "''${1}";
231 pipe :copy :try "learn-ham.sh" [ "''${username}" ];
235 configFile = toString ( pkgs.writeText "dovecot.conf" ''
238 args = /etc/dovecot/${networking.domain}/dovecot-ldap.conf
239 default_fields = userdb_mail_access_groups=${domainGroup}
246 # NOTE: this userdb is only used by lda.
248 args = /etc/dovecot/${networking.domain}/dovecot-ldap.conf
249 default_fields = mail_access_groups=${domainGroup}
254 # driver = passwd-file
255 # args = scheme=crypt username_format=%n ${authDir}/%d/passwd
258 # # NOTE: this userdb is only used by lda.
259 # driver = passwd-file
260 # args = username_format=%n ${authDir}/%d/passwd
261 # #default_fields = home=${mailDir}/%d/%n
264 # Store METADATA information within user's HOME directory
265 mail_attribute_dict = file:%h/dovecot-attributes
266 # If needed, may be overrided by userdb_mail
267 mail_home = ${mailDir}/%d/%n
268 # NOTE: if needed, may be overrided by userdb_mail
269 # NOTE: INDEX and CONTROL are on a partition without quota, as explain in the doc.
270 # SEE: http://wiki2.dovecot.org/Quota/FS
271 mail_location = maildir:${mailDir}/%d/%n/mail.d:LAYOUT=fs:INDEX=${stateDir}/index/%d/%n:INDEXPVT=${stateDir}/index/%d/%n:CONTROL=${stateDir}/control/%d/%n
272 auth_mechanisms = plain login
273 # NOTE: postfix does not supply a client cert.
274 auth_ssl_require_client_cert = no
275 #auth_ssl_username_from_cert = yes
277 # NOTE: lowercase the username, help with LDAP?
278 auth_username_format = %Lu
279 ${lib.optionalString dovecot2.debug ''
284 default_internal_user = ${dovecot2.user}
285 default_internal_group = ${dovecot2.group}
286 disable_plaintext_auth = yes
287 # NOTE: sync with LDAP's data.
288 first_valid_uid = 1000
289 lda_mailbox_autocreate = yes
290 lda_mailbox_autosubscribe = yes
292 log_timestamp = "%Y-%m-%d %H:%M:%S "
293 #maildir_copy_with_hardlinks = yes
295 # NOTE: here because protocol sieve {namespace inbox{}} does not seem to work.
301 separator = ${dirSep}
306 # NOTE: always listed in the LIST command.
308 # NOTE: how to access the other users' mailboxes.
309 # NOTE: %var expands to the logged in user's variable, while
310 # %%var expands to the other users' variables.
311 # NOTE: INDEX and CONTROL are shared, INDEXPVT is not.
312 location = maildir:${mailDir}/%%d/%%n/mail.d:LAYOUT=fs:INDEX=${stateDir}/index/%%d/%%n/Shared:INDEXPVT=${stateDir}/index/%d/%n/Shared/%%n:CONTROL=${stateDir}/control/%d/%n/Shared
313 prefix = Partages+%%n+
314 separator = ${dirSep}
317 mail_plugins = $mail_plugins acl quota virtual
318 #mail_uid = ${dovecot2.mailUser}
319 #mail_gid = ${dovecot2.mailGroup}
320 # NOTE: each user has a dedicated (uid,gid) pair
321 #mail_privileged_group = mail
322 #mail_access_groups =
324 acl = vfile:/etc/dovecot/acl/global.d
326 # NOTE: to let users LIST mailboxes shared by other users,
327 # Dovecot needs a shared mailbox dictionary.
328 # FIXME: %d not working with userdb ldap
329 acl_shared_dict = file:${stateDir}/acl/%d/acl.db
330 ## NOTE: pour offlineimap
331 ##antispam_allow_append_to_spam = yes
332 #antispam_backend = pipe
333 ##antispam_crm_args = -u;${mailDir}/%d/.crm114;/usr/share/crm114/mailfilter.crm
334 #antispam_crm_args = -u;${mailDir}/crm114;/usr/share/crm114/mailfilter.crm
335 #antispam_crm_binary = /usr/bin/crm
336 #antispam_debug_target = syslog
337 ##antispam_crm_env = HOME=%h;USER=%u
338 #antispam_ham_keywords = NonJunk
339 #antispam_pipe_program = /usr/bin/crm
340 #antispam_pipe_program_args = -u;${mailDir}/crm114;/usr/share/crm114/mailfilter.crm;--stats_only;--force
341 #antispam_pipe_program_notspam_arg = --learnnonspam
342 #antispam_pipe_program_spam_arg = --learnspam
343 #antispam_pipe_program_unlearn_spam_args = --unlearn;--learnspam
344 #antispam_pipe_program_unlearn_notspam_args = --unlearn;--learnnonspam
345 #antispam_pipe_tmpdir = ${mailDir}/crm114/tmp
346 #antispam_signature = X-CRM114-CacheID
347 #antispam_signature_missing = move
348 #antispam_spam = Junk
349 #antispam_spam_keywords = Junk
350 #antispam_trash = Trash
351 #antispam_unsure = Unsure
352 #antispam_verbose_debug = 0
353 quota = maildir:User quota
354 quota_rule = *:storage=256M
355 quota_rule2 = Trash:storage=+64M
356 quota_max_mail_size = 20M
357 #quota_exceeded_message = </path/to/quota_exceeded_message.txt
358 quota_warning = storage=95%% quota-warning 95 %u
359 quota_warning2 = storage=80%% quota-warning 80 %u
360 quota_warning3 = -storage=100%% quota-warning below %u
361 recipient_delimiter = ${extSep}
362 #sieve_default = file:${mailDir}/%u/default.sieve
363 #sieve_default_name = default
364 sieve_after = ${sieveDir}/after.d/
365 sieve_before = ${sieveDir}/before.d/
366 sieve = file:~/sieve.d;active=~/sieve
367 #sieve_extensions = +spamtest +spamtestplus
368 sieve_global = ${sieveDir}/global.d/
369 sieve_max_script_size = 1M
370 sieve_quota_max_scripts = 0
371 sieve_quota_max_storage = 10M
372 sieve_spamtest_max_value = 10
373 sieve_spamtest_status_header = X-Spam-Score
374 sieve_spamtest_status_type = strlen
375 sieve_user_log = /var/log/dovecot/%d/sieve.%n.log
377 sieve_plugins = sieve_imapsieve sieve_extprograms
378 sieve_pipe_bin_dir = ${sieve_pipe_bin_dir}/bin
379 sieve_global_extensions = +vnd.dovecot.pipe +vnd.dovecot.environment
380 # Enables support for user Sieve scripts in IMAP
381 #imapsieve_url = sieve://mail.${networking.domain}:4190
383 # When a flag changes, spam or ham according to the \Junk or \NonJunk flags
384 imapsieve_mailbox1_name = *
385 imapsieve_mailbox1_causes = FLAG
386 imapsieve_mailbox1_before = file:${sieveDir}/global.d/spam-or-ham.sieve
388 # From elsewhere to Junk folder
389 imapsieve_mailbox2_name = Pourriel
390 imapsieve_mailbox2_causes = COPY APPEND
391 imapsieve_mailbox2_before = file:${sieveDir}/global.d/report-spam.sieve
393 # From Junk folder to elsewhere
394 imapsieve_mailbox3_name = *
395 imapsieve_mailbox3_from = Pourriel
396 imapsieve_mailbox3_causes = COPY
397 imapsieve_mailbox3_before = file:${sieveDir}/global.d/report-ham.sieve
399 # If you have Dovecot v2.2.8+ you may get a significant performance improvement with fetch-headers:
400 imapc_features = $imapc_features fetch-headers
401 # Read multiple mails in parallel, improves performance
402 mail_prefetch_count = 20
403 service quota-warning {
404 executable = script ${
405 pkgs.writeScript "quota-warning" ''
409 cat << EOF | ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -d $USER -o
410 "plugin/quota=maildir:User quota:noenforcing"
411 From: postmaster@${networking.domain}
412 Subject: [WARNING] your mailbox is now $PERCENT% full.
414 Please remove some mails to make room for new ones.
418 # use some unprivileged user for executing the quota warnings
419 user = ${dovecot2.user}
420 unix_listener quota-warning {
424 #mail_max_userip_connections = 10
425 mail_plugins = $mail_plugins imap_acl imap_quota imap_sieve # antispam
426 # DOC: https://wiki.dovecot.org/MailboxSettings
427 # Due to a bug in Dovecot v2.2.30+ if special-use flags are used,
428 # SPECIAL-USE needs to be added to post-login CAPABILITY response as RFC 6154 mandates.
429 imap_capability = +SPECIAL-USE
435 separator = ${dirSep}
438 special_use = \Archive
442 special_use = \Archive
446 special_use = \Drafts
448 mailbox "Brouillons" {
450 special_use = \Drafts
465 mailbox "Pourriels" {
477 mailbox "Sent Items" {
481 mailbox "Sent Messages" {
494 mailbox "Corbeille" {
501 auth_socket_path = /var/run/dovecot/auth-userdb
502 hostname = ${networking.domain}
505 mail_plugins = $mail_plugins sieve
511 separator = ${dirSep}
513 postmaster_address = postmaster${extSep}dovecot${extSep}lda@${networking.domain}
514 syslog_facility = mail
517 #info_log_path = /tmp/dovecot-lmtp.log
518 mail_plugins = $mail_plugins sieve
524 separator = ${dirSep}
526 postmaster_address = postmaster${extSep}dovecot${extSep}lmtp@${networking.domain}
529 #mail_max_userip_connections = 10
531 # NOTE: used by ${dovecot-virtual}/pop3/INBOX/dovecot-virtual
536 separator = ${dirSep}
538 # Virtual namespace for the virtual INBOX.
539 # Use a global directory for dovecot-virtual files.
544 location = virtual:${dovecot-virtual}/pop3:INDEX=${stateDir}/index/%d/%n/POP3:LAYOUT=fs
546 separator = ${dirSep}
548 pop3_client_workarounds =
549 pop3_fast_size_lookups = yes
550 pop3_lock_session = yes
551 pop3_no_flag_updates = yes
552 # Use GUIDs to avoid accidental POP3 UIDL changes instead of IMAP UIDs.
553 pop3_uidl_format = %g
556 #mail_max_userip_connections = 10
557 #managesieve_implementation_string = Dovecot Pigeonhole
558 managesieve_max_compile_errors = 5
559 #managesieve_max_line_length = 65536
560 #managesieve_notify_capability = mailto
561 #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
563 # DOC: https://wiki2.dovecot.org/Pigeonhole/ManageSieve/Configuration
565 # Maximum number of ManageSieve connections allowed for a user from each IP address.
566 # NOTE: The username is compared case-sensitively.
567 mail_max_userip_connections = 10
569 # To fool ManageSieve clients that are focused on CMU's timesieved you can specify
570 # the IMPLEMENTATION capability that the dovecot reports to clients.
571 # For example: 'Cyrus timsieved v2.2.13'
572 managesieve_implementation_string = Dovecot Pigeonhole
574 # The maximum number of compile errors that are returned to the client upon script
575 # upload or script verification.
576 managesieve_max_compile_errors = 5
578 protocols = imap lmtp pop3 sieve
580 #executable = lmtp -L
581 process_min_avail = 2
582 unix_listener /var/lib/postfix/queue/private/dovecot-lmtp {
583 user = ${postfix.user}
584 group = ${postfix.group}
590 # FIXME: may be user=dovecot-auth with LDAP?
592 unix_listener auth-userdb {
593 user = ${dovecot2.user}
594 group = ${dovecot2.group}
597 unix_listener /var/lib/postfix/queue/private/auth {
598 user = ${postfix.user}
599 group = ${postfix.group}
604 # Most of the memory goes to mmap()ing files.
605 # You may need to increase this limit if you have huge mailboxes.
610 #inet_listener imap {
611 # address = 127.0.0.1
615 inet_listener imaps {
624 inet_listener pop3s {
629 service managesieve-login {
630 inet_listener sieve {
635 # Number of connections to handle before starting a new process. Typically
636 # the only useful values are 0 (unlimited) or 1. 1 is more secure, but 0
637 # is faster. <doc/wiki/LoginProcess.txt>
640 # Number of processes to always keep waiting for more connections.
641 process_min_avail = 0
643 # If you set service_count=0, you probably need to grow this.
647 ssl_dh = <${../../../sec/openssl/dh.pem}
648 ssl_cipher_list = HIGH:!LOW:!SSLv2:!EXP:!aNULL
649 ssl_cert = <${loadFile (../../../sec + "/openssl/${networking.domainBase}/cert.self-signed.pem")}
650 ssl_key = </run/keys/dovecot.${networking.domainBase}.key.pem
651 #ssl_ca = <''${caPath}
652 #ssl_verify_client_cert = yes
654 #${lib.concatMapStringsSep "\n"
656 # local_name mail.${dom} {
657 # #ssl_ca = <''${caPath}
658 # ssl_cert = <${x509.cert dom}
659 # ssl_key = <${x509.key dom}