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