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