]> Git — Sourcephile - sourcephile-nix.git/blob - hosts/mermet/dovecot.nix
nix: update input julm-nix
[sourcephile-nix.git] / hosts / mermet / dovecot.nix
1 { inputs, pkgs, lib, config, system, host, ... }:
2 let
3 inherit (builtins) toString toFile readFile;
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
9 # NOTE: nixpkgs' dovecot2.stateDir is currently not exported
10 stateDir = "/var/lib/dovecot";
11
12 sieve_pipe_bin_dir = pkgs.buildEnv {
13 name = "sieve_pipe_bin_dir";
14 pathsToLink = [ "/bin" ];
15 paths = [
16 learn-spam
17 learn-ham
18 ];
19 };
20 learn-spam = pkgs.writeShellScriptBin "learn-spam.sh" ''
21 exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd/learner.sock learn_spam
22 '';
23 learn-ham = pkgs.writeShellScriptBin "learn-ham.sh" ''
24 exec ${pkgs.rspamd}/bin/rspamc -h /run/rspamd/learner.sock learn_ham
25 '';
26
27 dovecot-virtual = pkgs.buildEnv {
28 name = "dovecot-virtual";
29 pathsToLink = [ "/" ];
30 paths = [
31 dovecot-virtual-all
32 dovecot-virtual-recents
33 ];
34 };
35 dovecot-virtual-all = pkgs.writeTextFile {
36 name = "dovecot-virtual-all";
37 destination = "/All/dovecot-virtual";
38 text = ''
39 *
40 all
41 '';
42 };
43 dovecot-virtual-recents = pkgs.writeTextFile {
44 name = "dovecot-virtual-recents";
45 destination = "/Recents/dovecot-virtual";
46 text = ''
47 *
48 all younger 172800
49 '';
50 };
51 dovecot-virtual-pop3 = pkgs.writeTextFile {
52 name = "dovecot-virtual-pop3";
53 destination = "/pop3/INBOX/dovecot-virtual";
54 text = ''
55 All
56 All+*
57 all
58 '';
59 };
60 in
61 {
62 imports = [
63 dovecot/sourcephile.fr.nix
64 dovecot/autogeree.net.nix
65 ];
66 environment.systemPackages = [
67 pkgs.dovecot_pigeonhole
68 ];
69 users.groups.acme.members = [ dovecot2.user ];
70 systemd.services.dovecot2 = {
71 after = [
72 "postfix.service"
73 "openldap.service"
74 ];
75 /*
76 preStart = ''
77 # SEE: http://wiki2.dovecot.org/SharedMailboxes/Permissions
78 install -D -d -m 0771 \
79 -o "${dovecot2.user}" \
80 -g "${dovecot2.group}" \
81 ${stateDir}/mail
82 '';
83 */
84 preStart = ''
85 ln -fns -t ${stateDir}/virtual/ \
86 ${dovecot-virtual-all}/All \
87 ${dovecot-virtual-recents}/Recents
88 '';
89 serviceConfig = {
90 #ExecStart = lib.mkForce "${pkgs.utillinux}/bin/setarch x86_64 --addr-no-randomize /bin/sh -c 'LD_PRELOAD=${pkgs.gcc-unwrapped.lib}/lib/libasan.so ${pkgs.dovecot}/sbin/dovecot -F'";
91 # Dovecot2 does not work with environment.memoryAllocator.provider="scudo"
92 # https://wiki.dovecot.org/Design/Memory
93 # Scudo ERROR: CHECK failed at /build/compiler-rt-7.1.0.src/lib/scudo/../sanitizer_common/sanitizer_allocator_primary64.h:
94 # 644 ((beg)) == ((address_range.MapOrDie(beg, size))) (4398046511092, 4398046507008)
95 BindReadOnlyPaths = [ "/dev/null:/etc/ld-nix.so.preload" ];
96 StateDirectory = ["dovecot/virtual"];
97 };
98 };
99 #users.users."${dovecot2.mailUser}".isSystemUser = true; # Fix nixpkgs
100 networking.nftables.ruleset = ''
101 table inet filter {
102 chain input-net {
103 tcp dport imaps counter accept comment "dovecot: IMAPS"
104 #tcp dport 995 counter accept comment "dovecot: POP3S"
105 tcp dport sieve counter accept comment "dovecot: Sieve"
106 }
107 }
108 '';
109 fileSystems."/var/lib/dovecot" = {
110 device = "rpool/var/mail";
111 fsType = "zfs";
112 };
113 services.sanoid.datasets."rpool/var/mail" = {
114 use_template = [ "snap" ];
115 daily = 7;
116 };
117 services.dovecot2 = {
118 enable = true;
119 modules = [
120 pkgs.dovecot_pigeonhole
121 pkgs.dovecot_fts_xapian
122 ];
123 enablePAM = false;
124 enableImap = true;
125 enableLmtp = true;
126 enablePop3 = false;
127 protocols = [ "sieve" ];
128 # If needed, may be overrided by userdb_mail= in passdb, or mail= in userdb
129 # Here INDEX and CONTROL are separated,
130 # it's not useful since there is no quota at the filesystem level
131 # it's just to let this possibility later on.
132 mailLocation = "sdbox:${stateDir}/home/%d/%n/mail:UTF-8:CONTROL=${stateDir}/control/%d/%n:INDEX=${stateDir}/index/%d/%n";
133 createMailUser = false;
134 mailUser = "";
135 mailGroup = "";
136 sslServerCert = null;
137 sieveScripts = {
138 global = dovecot/sieve/global;
139 };
140 extraConfig = ''
141 auth_verbose = no
142 auth_debug = no
143 mail_debug = no
144 verbose_ssl = no
145 log_timestamp = "%Y-%m-%d %H:%M:%S "
146
147 ssl = required
148 ssl_dh = <${inputs.secrets + "/openssl/dh.pem"}
149 ssl_cipher_list = HIGH:!LOW:!SSLv2:!EXP:!aNULL
150 ssl_prefer_server_ciphers = yes
151 ssl_cert = </var/lib/acme/${networking.domain}/fullchain.pem
152 ssl_key = </var/lib/acme/${networking.domain}/key.pem
153 #ssl_ca = <''${caPath}
154 #ssl_verify_client_cert = yes
155 # FIXME: change to TLSv1.3 when supported by K-9 Mail
156 ssl_min_protocol = TLSv1.2
157
158 listen = *
159 mail_home = ${stateDir}/home/%d/%n
160 # Read multiple mails in parallel, improves performance
161 mail_prefetch_count = 20
162 # Default VSZ (virtual memory size) limit for service processes. This is mainly
163 # intended to catch and kill processes that leak memory before they eat up everything.
164 # Increased for fts_xapian.
165 default_vsz_limit = 1G
166
167 # DOC: https://doc.dovecot.org/configuration_manual/authentication/authentication_mechanisms/
168 # DOC: https://ldapwiki.com/wiki/DIGEST-MD5
169 # The misunderstanding is the notion "password sent over the network in plain-text" is not secure,
170 # when in fact, storing the password in the directory server using a Salted SHA-2 hash
171 # and transmitting the clear text password over a secure connection
172 # is more secure than having the directory server store the password in clear text
173 # or in a reversible encryption scheme.
174 # Therefore, SASL with DIGEST-MD5 (or CRAM-MD5) should be avoided.
175 # Use doveadm pw -s SSHA
176 # or doveadm pw -s PBKDF2 -r 10000
177 # or slappasswd -o module-load=pw-pbkdf2 -h "{PBKDF2-SHA256}"
178 auth_mechanisms = plain login
179 auth_username_format = %Ln
180 service auth {
181 user = ${dovecot2.user}
182 # auth_socket_path points to this userdb socket by default. It's typically
183 # used by dovecot-lda, doveadm, possibly imap process, etc.
184 # Users that have access to this socket are able to get a list
185 # of all usernames and get results of everyone's userdb lookups.
186 unix_listener auth-userdb {
187 user = ${dovecot2.user}
188 group = ${dovecot2.group}
189 mode = 0660
190 }
191 unix_listener /var/lib/postfix/queue/private/auth {
192 user = ${postfix.user}
193 group = ${postfix.group}
194 mode = 0660
195 }
196 }
197 service auth-worker {
198 user = ${dovecot2.user}
199 }
200 auth_cache_verify_password_with_worker = yes
201 # SEE: http://wiki2.dovecot.org/Quota/FS
202 # NOTE: postfix does not supply a client cert.
203 auth_ssl_require_client_cert = no
204 #auth_ssl_username_from_cert = yes
205 # NOTE: lowercase the username, help with LDAP?
206 auth_username_format = %Lu
207 # NOTE: sync with LDAP's data.
208 first_valid_uid = 1000
209 disable_plaintext_auth = yes
210
211 userdb {
212 driver = ldap
213 # A different path than passdb's args enables non-blocking LDAP requests
214 args = ${pkgs.symlinkJoin {name="ldap"; paths=[./dovecot];}}/ldap.conf
215 default_fields =
216 override_fields =
217 }
218
219 # No dirty syncs for maildir: locations which may be used directly by neomutt
220 maildir_very_dirty_syncs = no
221 namespace Inbox {
222 type = private
223 inbox = yes
224 hidden = no
225 list = yes
226 prefix =
227 separator = +
228 }
229 namespace Shared {
230 type = shared
231 #list = children
232 # NOTE: always listed in the LIST command.
233 list = yes
234 # NOTE: how to access the other users' mailboxes.
235 # NOTE: %var expands to the logged in user's variable, while
236 # %%var expands to the other users' variables.
237 # NOTE: INDEX and CONTROL are shared, INDEXPVT is not.
238 location = sdbox:${stateDir}/home/%%d/%%n/${stateDir}/mail:UTF-8:CONTROL=${stateDir}/control/%%d/%%n/shared:INDEX=${stateDir}/index/%%d/%%n/shared:INDEXPVT=${stateDir}/index/%d/%n/shared/%%n
239 prefix = Partages+%%n+
240 separator = +
241 subscriptions = yes
242 }
243 mail_plugins = $mail_plugins virtual
244 namespace Virtual {
245 prefix = Virtual+
246 separator = +
247 hidden = no
248 list = yes
249 subscriptions = no
250 location = virtual:${dovecot-virtual}:UTF-8:INDEX=${stateDir}/index/%d/%n/virtual
251 }
252
253 mail_plugins = $mail_plugins acl
254 plugin {
255 acl = vfile:/etc/dovecot/acl/global
256 acl_anyone = allow
257 # NOTE: to let users LIST mailboxes shared by other users,
258 # Dovecot needs a shared mailbox dictionary.
259 # FIXME: %d not working with userdb ldap
260 acl_shared_dict = file:${stateDir}/acl/%d/acl.db
261 }
262
263 mail_plugins = $mail_plugins fts fts_xapian
264 plugin {
265 # WARNING: doveadm fts rescan is buggy, it will delete the index:
266 # https://dovecot.org/pipermail/dovecot/2019-February/114709.html
267 # If need be, use rather: doveadm index -u "*@sourcephile.fr" -q '*'
268 plugin = fts fts_xapian
269 fts = xapian
270 fts_autoindex = yes
271 fts_autoindex_exclude = \Junk
272 fts_autoindex_exclude2 = \Trash
273 fts_enforced = yes
274 # 2 and 20 are the NGram values for header fields, which means the
275 # keywords created for fields (To, Cc, ...) are between is 2 and 20 chars long.
276 # Full words are also added by default.
277 fts_xapian = partial=2 full=20 attachments=1 verbose=0
278 fts_languages = en fr
279 #fts_dovecot_fs = posix:prefix=%h/fts/
280 }
281
282 mail_plugins = $mail_plugins quota
283 plugin {
284 quota = maildir:User quota
285 quota_rule = *:storage=256M
286 quota_rule2 = Trash:storage=+64M
287 quota_max_mail_size = 20M
288 #quota_exceeded_message = </path/to/quota_exceeded_message.txt
289 quota_warning = storage=95%% quota-warning 95 %u
290 quota_warning2 = storage=80%% quota-warning 80 %u
291 quota_warning3 = -storage=100%% quota-warning below %u
292 }
293
294 protocol lda {
295 hostname = ${networking.domain}
296 mail_plugins = $mail_plugins sieve
297 postmaster_address = root+dovecot+lda@${networking.domain}
298 syslog_facility = mail
299 }
300 lda_mailbox_autocreate = yes
301 lda_mailbox_autosubscribe = yes
302
303 protocol lmtp {
304 mail_plugins = $mail_plugins sieve
305 postmaster_address = root+dovecot+lmtp@${networking.domain}
306 }
307 service lmtp {
308 process_min_avail = ${toString host.CPUs}
309 unix_listener /var/lib/postfix/queue/private/dovecot-lmtp {
310 user = ${postfix.user}
311 group = ${postfix.group}
312 mode = 0600
313 }
314 }
315 plugin {
316 # Let extension.sieve do the handling of the detail
317 #lmtp_save_to_detail_mailbox = yes
318 recipient_delimiter = ${postfix.recipientDelimiter}
319 }
320
321 service imap {
322 # Most of the memory goes to mmap()ing files.
323 # You may need to increase this limit if you have huge mailboxes.
324 #vsz_limit =
325 process_limit = 1024
326 }
327 service imap-login {
328 #inet_listener imap {
329 # address = 127.0.0.1
330 # port = 143
331 # ssl = no
332 #}
333 inet_listener imaps {
334 port = 993
335 ssl = yes
336 }
337 }
338 # Store METADATA information within user's HOME directory
339 mail_attribute_dict = file:%h/dovecot-attributes
340 # If you have Dovecot v2.2.8+ you may get a significant performance improvement with fetch-headers:
341 imapc_features = $imapc_features fetch-headers
342 protocol imap {
343 #mail_max_userip_connections = 10
344 mail_plugins = $mail_plugins imap_acl imap_quota imap_sieve virtual
345 imap_metadata = yes
346
347 # DOC: https://wiki.dovecot.org/MailboxSettings
348 # Due to a bug in Dovecot v2.2.30+ if special-use flags are used,
349 # SPECIAL-USE needs to be added to post-login CAPABILITY response as RFC 6154 mandates.
350 imap_capability = +SPECIAL-USE
351
352 namespace Inbox {
353 mailbox "Archives" {
354 auto = subscribe
355 special_use = \Archive
356 }
357 mailbox "Drafts" {
358 auto = no
359 special_use = \Drafts
360 }
361 mailbox "Brouillons" {
362 auto = subscribe
363 special_use = \Drafts
364 }
365 mailbox "Junk" {
366 auto = no
367 #autoexpunge = 30d
368 special_use = \Junk
369 }
370 mailbox "Spams" {
371 auto = no
372 special_use = \Junk
373 }
374 mailbox "Spam" {
375 auto = no
376 special_use = \Junk
377 }
378 mailbox "Pourriels" {
379 auto = no
380 special_use = \Junk
381 }
382 mailbox "Pourriel" {
383 auto = no
384 special_use = \Junk
385 }
386 mailbox "Sent" {
387 auto = no
388 special_use = \Sent
389 }
390 mailbox "Sent Items" {
391 auto = no
392 special_use = \Sent
393 }
394 mailbox "Sent Messages" {
395 auto = no
396 special_use = \Sent
397 }
398 mailbox "Envoyés" {
399 auto = no
400 special_use = \Sent
401 }
402 mailbox "Trash" {
403 auto = no
404 special_use = \Trash
405 #autoexpunge = 30d
406 }
407 mailbox "Corbeille" {
408 auto = no
409 special_use = \Trash
410 }
411 }
412 namespace Virtual {
413 mailbox All {
414 auto = no
415 comment = All messages from all mailboxes
416 # This flag is confused with \Archives by K9-Mail
417 special_use = \All
418 }
419 mailbox Recents {
420 auto = no
421 comment = All messages from all mailboxes, arrived in the past 48h
422 }
423 }
424 }
425 plugin {
426 sieve_plugins = sieve_imapsieve sieve_extprograms
427 sieve_global_extensions = +vnd.dovecot.environment +vnd.dovecot.pipe
428 #sieve_extensions = +editheader
429 sieve = file:~/sieve;active=~/active.sieve
430 sieve_default = file:${stateDir}/sieve/global/default.sieve
431 sieve_default_name = main
432 sieve_pipe_bin_dir = ${sieve_pipe_bin_dir}/bin
433 sieve_max_script_size = 1M
434 sieve_quota_max_scripts = 0
435 sieve_quota_max_storage = 10M
436 #sieve_spamtest_max_value = 10
437 #sieve_spamtest_status_header = X-Spam-Score
438 #sieve_spamtest_status_type = strlen
439 #sieve_user_log = ~/sieve.log
440 # Enables support for user Sieve scripts in IMAP
441 #imapsieve_url = sieve://mail.${networking.domain}:4190
442
443 # When a flag changes, spam or ham according to the \Junk or \NonJunk flags
444 imapsieve_mailbox1_name = *
445 imapsieve_mailbox1_causes = FLAG
446 imapsieve_mailbox1_before = file:${stateDir}/sieve/global/spam-or-ham.sieve
447
448 # From elsewhere to Junk folder
449 imapsieve_mailbox2_name = Pourriel
450 imapsieve_mailbox2_causes = COPY APPEND
451 imapsieve_mailbox2_before = file:${stateDir}/sieve/global/report-spam.sieve
452
453 # From Junk folder to elsewhere
454 imapsieve_mailbox3_name = *
455 imapsieve_mailbox3_from = Pourriel
456 imapsieve_mailbox3_causes = COPY
457 imapsieve_mailbox3_before = file:${stateDir}/sieve/global/report-ham.sieve
458 }
459 protocol sieve {
460 # Maximum number of ManageSieve connections allowed for a user from each IP address.
461 # NOTE: The username is compared case-sensitively.
462 mail_max_userip_connections = 10
463
464 # To fool ManageSieve clients that are focused on CMU's timesieved you can specify
465 # the IMPLEMENTATION capability that the dovecot reports to clients.
466 # For example: 'Cyrus timesieved v2.2.13'
467 managesieve_implementation_string = Dovecot Pigeonhole
468
469 # The maximum number of compile errors that are returned to the client upon script
470 # upload or script verification.
471 managesieve_max_compile_errors = 5
472
473 #mail_max_userip_connections = 10
474 #managesieve_implementation_string = Dovecot Pigeonhole
475 managesieve_max_compile_errors = 5
476 #managesieve_max_line_length = 65536
477 #managesieve_notify_capability = mailto
478 #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
479 }
480 service managesieve-login {
481 inet_listener sieve {
482 port = 4190
483 #ssl = yes
484 }
485
486 # Number of connections to handle before starting a new process. Typically
487 # the only useful values are 0 (unlimited) or 1. 1 is more secure, but 0
488 # is faster. <doc/wiki/LoginProcess.txt>
489 service_count = 1
490
491 # Number of processes to always keep waiting for more connections.
492 process_min_avail = 0
493
494 # If you set service_count=0, you probably need to grow this.
495 #vsz_limit = 64M
496 }
497
498 service quota-warning {
499 executable = script ${
500 pkgs.writeShellScript "quota-warning" ''
501 set -eu
502 PERCENT=$1
503 USER=$2
504 cat << EOF | ${pkgs.dovecot}/libexec/dovecot/dovecot-lda -d $USER -o
505 "plugin/quota=maildir:User quota:noenforcing"
506 From: root+docevot@${networking.domain}
507 Subject: [WARNING] your mailbox is now $PERCENT% full.
508
509 Please remove some mails to make room for new ones.
510 EOF
511 ''
512 }
513 # use some unprivileged user for executing the quota warnings
514 user = ${dovecot2.user}
515 unix_listener quota-warning {
516 }
517 }
518
519 protocol pop3 {
520 mail_plugins = $mail_plugins virtual
521 #mail_max_userip_connections = 10
522 # Virtual namespace for the virtual INBOX.
523 # Use a global directory for dovecot-virtual files.
524 #namespace Inbox {
525 # hidden = yes
526 # list = no
527 # location = virtual:''${dovecot-virtual-pop3}/pop3:INDEX=${stateDir}/index/%d/%n/virtual/pop3:LAYOUT=fs
528 # prefix = pop3+
529 #}
530 pop3_client_workarounds =
531 pop3_fast_size_lookups = yes
532 pop3_lock_session = yes
533 pop3_no_flag_updates = yes
534 # Use GUIDs to avoid accidental POP3 UIDL changes instead of IMAP UIDs.
535 pop3_uidl_format = %g
536 }
537 service pop3 {
538 process_limit = 1024
539 }
540 service pop3-login {
541 inet_listener pop3s {
542 port = 995
543 ssl = yes
544 }
545 }
546 '';
547 };
548 }