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