various fixes and improvements
[distro-setup] / mail-setup
1 #!/bin/bash
2 # -*- eval: (outline-minor-mode); -*-
3 # * intro
4 # Copyright (C) 2019 Ian Kelling
5 # SPDX-License-Identifier: AGPL-3.0-or-later
6
7 if [ -z "$BASH_VERSION" ]; then echo "error: shell is not bash" >&2; exit 1; fi
8
9 pre="${0##*/}:"
10 m() { printf "$pre %s\n" "$*"; "$@"; }
11 e() { printf "$pre %s\n" "$*"; }
12 err() { echo "[$(date +'%Y-%m-%d %H:%M:%S%z')]: $0: $*" >&2; }
13
14 shopt -s nullglob
15
16 if [[ -s /usr/local/lib/err ]]; then
17 source /usr/local/lib/err
18 elif [[ -s /a/bin/errhandle/err ]]; then
19 source /a/bin/errhandle/err
20 else
21 err "no err tracing script found"
22 exit 1
23 fi
24
25 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
26 if [[ ! $SUDO_USER ]]; then
27 echo "$0: error: requires running as nonroot or sudo"
28 exit 1
29 fi
30 u=$SUDO_USER
31
32
33 usage() {
34 cat <<EOF
35 Usage: ${0##*/}
36 Setup exim4 & dovecot & related things
37
38 -h|--help Print help and exit.
39 EOF
40 exit $1
41 }
42
43
44
45 ####### instructions for icedove #####
46 # Incoming mail server: mail.iankelling.org, port 143, username iank, connection security starttls, authentication method normal password
47 # we could also just use 127.0.0.1 with no ssl, but todo: disable that in dovecot, so mail is secure from local programs.
48 #
49 # hamburger -> preferences -> preferences -> advanced tab -> config editor button -> security.ssl.enable_ocsp_must_staple = false
50 # background: ovecot does not yet have ocsp stapling support
51 # reference: https://community.letsencrypt.org/t/simple-guide-using-lets-encrypt-ssl-certs-with-dovecot/2921
52 #
53 # for phone, k9mail, same thing but username alerts, pass in ivy-pass.
54 # also, l2.b8.nz for secondary alerts
55 # fetching mail settings: folder poll frequency 10 minutes
56 #######
57
58
59 # * perstent password instructions
60 # # exim passwords:
61 # # for hosts which have all private files I just use the same user
62 # # for other hosts, each one get\'s their own password.
63 # # for generating secure pass, and storing for server too:
64 # f=$(mktemp)
65 # I use $HOSTNAME as username
66 # apg -m 50 -x 70 -n 1 -a 1 -M CLN >$f
67 # s sed -i "/^$HOSTNAME:/d" /p/c/filesystem/etc/exim4/passwd
68 # echo "$HOSTNAME:$(mkpasswd -m sha-512 -s <$f)" >>/p/c/filesystem/etc/exim4/passwd
69 # reference: exim4_passwd_client(5)
70 # echo "mail.iankelling.org:$HOSTNAME:$(<$f)" > /p/c/machine_specific/$HOSTNAME/filesystem/etc/exim4/passwd.client
71 # # then run this script
72
73 # # dovecot password, i just need 1 as I\'m the only user
74 # mkdir /p/c/filesystem/etc/dovecot
75 # echo "iank:$(doveadm pw -s ssha256)::::::" >>/p/c/filesystem/etc/dovecot/users
76
77 ####### end perstent password instructions ######
78
79
80 # * persistent dkim/dns instructions
81 # # Remove 1 level of comments in this section, set the domain var
82 # # for the domain you are setting up, then run this and copy dns settings
83 # # into dns.
84 # domain=iankelling.org
85 # c /p/c/filesystem/etc/exim4
86 # # this has several bugs addressed in comments, but it was helpful
87 # # https://debian-administration.org/article/718/DKIM-signing_outgoing_mail_with_exim4
88
89 # openssl genrsa -out $domain-private.pem 2048 -outform PEM
90 # openssl rsa -in $domain-private.pem -out $domain.pem -pubout -outform PEM
91 # # selector is needed for having multiple keys for one domain.
92 # # I dun do that, so just use a static one: li
93 # echo "txt record name: li._domainkey.$domain"
94 # # Debadmin page does not have v=, fastmail does, and this
95 # # says it\'s recommended in 3.6.1, default is DKIM1 anyways.
96 # # https://www.ietf.org/rfc/rfc6376.txt
97 # # Join and print all but first and last line.
98 # # last line: swap hold & pattern, remove newlines, print.
99 # # lines 2+: append to hold space
100 # echo "txt record contents:"
101 # echo "v=DKIM1; k=rsa; p=$(sed -n '${x;s/\n//gp};2,$H' $domain.pem)"
102 # # selector was also put into /etc/exim4/conf.d/main/000_local,
103
104 # # 2017-02 dmarc policies:
105 # # host -t txt _dmarc.gmail.com
106 # # yahoo: p=reject, hotmail: p=none, gmail: p=none, fastmail none for legacy reasons
107 # # there were articles claiming gmail would be changing
108 # # to p=reject, in early 2017, which didn\'t happen. I see no sources on them. It\'s
109 # # expected to cause problems
110 # # with a few old mailing lists, copying theirs for now.
111 #
112 # echo "dmarc dns, name: _dmarc value: v=DMARC1; p=none; rua=mailto:mailauth-reports@$domain"
113
114 # # 2017-02 spf policies:
115 # # host -t txt lists.fedoraproject.org
116 # # google ~all, hotmail ~all, yahoo: ?all, fastmail ?all, outlook ~all
117 # # i include fastmail\'s settings, per their instructions,
118 # # and follow their policy. In mail in a box, or similar instructions,
119 # # I\'ve seen recommended to not use a restrictive policy.
120
121 # # to check if dns has updated, you do
122 # host -a mesmtp._domainkey.$domain
123
124 # # mx records,
125 # # setting it to iankelling.org would work the same, but this
126 # # is more flexible, I could change where mail.iankelling.org pointed.
127 # cat <<'EOF'
128 # mx records, 2 records each, for * and empty domain
129 # pri 10 mail.iankelling.org
130 # EOF
131 ####### end persistent dkim instructions #########
132
133
134 # * functions constants
135 e() { printf "%s\n" "$*"; }
136 pi() { # package install without starting daemons
137 local f
138 if dpkg -s -- "$@" &> /dev/null; then
139 return 0;
140 fi;
141 while fuser /var/lib/dpkg/lock &>/dev/null; do sleep 1; done
142 f=/var/cache/apt/pkgcache.bin;
143 if [[ ! -r $f ]] || (( $(( $(date +%s) - $(stat -c %Y $f ) )) > 60*60*12 )); then
144 m apt-get update
145 fi
146 f=/usr/sbin/policy-rc.d
147 dd of=$f 2>/dev/null <<EOF
148 #!/bin/sh
149 exit 101
150 EOF
151 chmod +x $f
152 ret=
153 DEBIAN_FRONTEND=noninteractive m apt-get -y install --purge --auto-remove "$@" || ret=$?
154 rm $f
155 if [[ $ret ]]; then
156 err-exit $ret "failed apt-get install above"
157 fi
158 }
159
160 postmaster=alerts
161 mxhost=mail.iankelling.org
162 mxport=587
163 forward=$u@$mxhost
164
165 # old setup. left as comment for example
166 # mxhost=mail.messagingengine.com
167 # mxport=587
168 # forward=ian@iankelling.org
169
170 smarthost="$mxhost::$mxport"
171
172 ## * Install packages
173 # light version of exim does not have sasl auth support.
174 pi exim4-daemon-heavy spamassassin spf-tools-perl openvpn dnsmasq
175
176 # trisquel 8 = openvpn, debian stretch = openvpn-client
177 vpn_ser=openvpn-client
178 if [[ ! -e /lib/systemd/system/openvpn-client@.service ]]; then
179 vpn_ser=openvpn
180 fi
181
182 uhome=$(eval echo ~$u)
183 ### * user forward file
184
185 case $HOSTNAME in
186 $MAIL_HOST|l2)
187 # afaik, these will get ignored on MAIL_HOST because they are routing to my own
188 # machine, but rm them is safer
189 rm -fv $uhome/.forward /root/.forward
190 ;;
191 *)
192 # this can\'t be a symlink and has permission restrictions
193 # it might work in /etc/aliases, but this seems more proper.
194 e setting $uhome/.forward to $forward
195 install -m 644 {-o,-g}$u <(e $forward) $uhome/.forward
196 ;;
197 esac
198
199 # * Mail clean cronjob
200
201 cat >/etc/systemd/system/mailclean.timer <<'EOF'
202 [Unit]
203 Description=Run mailclean daily
204
205 [Timer]
206 OnCalendar=monthly
207
208 [Install]
209 WantedBy=timers.target
210 EOF
211
212 cat >/etc/systemd/system/mailclean.service <<EOF
213 [Unit]
214 Description=Delete and archive old mail files
215 After=multi-user.target
216
217 [Service]
218 User=$u
219 Type=oneshot
220 ExecStart=/a/bin/log-quiet/sysd-mail-once mailclean /a/bin/distro-setup/mailclean
221 EOF
222
223 systemctl daemon-reload
224
225
226 # * spamassassin
227
228 if [[ $HOSTNAME != "$MAIL_HOST" ]]; then
229 m systemctl stop spamassassin
230 m systemctl disable spamassassin
231 else
232
233 # per readme.debian
234 sed -i '/^\s*CRON\s*=/d' /etc/default/spamassassin
235 e CRON=1 >>/etc/default/spamassassin
236 # just noticed this in the config file, seems like a good idea.
237 sed -i '/^\s*NICE\s*=/d' /etc/default/spamassassin
238 e 'NICE="--nicelevel 15"' >>/etc/default/spamassassin
239
240 m systemctl enable spamassassin
241 m systemctl start spamassassin
242 m systemctl reload spamassassin
243
244 cat >/etc/systemd/system/spamddnsfix.service <<'EOF'
245 [Unit]
246 Description=spamd dns bug fix cronjob
247
248 [Service]
249 Type=oneshot
250 ExecStart=/a/bin/distro-setup/spamd-dns-fix
251 EOF
252 # 2017-09, debian closed the bug on this saying upstream had fixed it.
253 # remove this when i\'m using the newer package, ie, debian 10, or maybe
254 # ubuntu 18.04.
255 cat >/etc/systemd/system/spamddnsfix.timer <<'EOF'
256 [Unit]
257 Description=run spamd bug fix script every 10 minutes
258
259 [Timer]
260 OnActiveSec=60
261 # the script looks back 9 minutes into the journal,
262 # it takes a second to run,
263 # so lets run every 9 minutes and 10 seconds.
264 OnUnitActiveSec=550
265
266 [Install]
267 WantedBy=timers.target
268 EOF
269 m systemctl daemon-reload
270 m systemctl restart spamddnsfix.timer
271 m systemctl enable spamddnsfix.timer
272
273 fi # [[ $HOSTNAME != "$MAIL_HOST" ]]
274 ##### end spamassassin config
275
276
277 # * Update mail cert
278 if [[ -e /p/c/filesystem ]]; then
279 # allow failure of these commands when our internet is down, they are likely not needed,
280 # we check that a valid cert is there already.
281 # to put the hostname in the known hosts
282 if ! ssh -o StrictHostKeyChecking=no root@li.iankelling.org :; then
283 # This just causes failure if our cert is going to expire in the next 30 days.
284 # Certs I generate last 10 years.
285 openssl x509 -checkend $(( 60 * 60 * 24 * 30 )) -noout -in /etc/openvpn/mail.crt
286 else
287 # note, man openvpn implies we could just call mail-route on vpn startup/shutdown with
288 # systemd, buuut it can remake the tun device unexpectedly, i got this in the log
289 # after my internet was down for a bit:
290 # NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.
291 m /a/exe/vpn-mk-client-cert -b mail -n mail -s /b/ds/mail-route li.iankelling.org
292 fi
293 fi
294
295
296
297 f=/usr/local/bin/mail-cert-cron
298 cat >$f <<'EOF'
299 #!/bin/bash
300 set -eE -o pipefail
301 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
302
303 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
304
305 f=/a/bin/bash_unpublished/source-state
306 if [[ -e $f ]]; then
307 source $f
308 fi
309 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
310 local_mx=mail.iankelling.org
311 rsync_common="rsync -ogtL --chown=root:Debian-exim --chmod=640 root@li.iankelling.org:/etc/letsencrypt/live/$local_mx/"
312 ${rsync_common}fullchain.pem /etc/exim4/exim.crt
313 ret=$?
314 ${rsync_common}privkey.pem /etc/exim4/exim.key
315 new_ret=$?
316 if [[ $ret != $new_ret ]]; then
317 echo "$0: error: differing rsync returns, $ret, $new_ret"
318 exit 1
319 fi
320 fi
321 if [[ $new_ret != 0 ]]; then
322 if ! openssl x509 -checkend $(( 60 * 60 * 24 * 3 )) -noout -in /etc/exim4/exim.crt; then
323 echo "$0: error!: cert rsync failed and it will expire in less than 3 days"
324 exit 1
325 fi
326 fi
327 exit 0
328 EOF
329 m chmod 755 $f
330
331 cat >/etc/systemd/system/mailcert.service <<'EOF'
332 [Unit]
333 Description=Mail cert rsync
334 After=multi-user.target
335
336 [Service]
337 Type=oneshot
338 ExecStart=/a/bin/log-quiet/sysd-mail-once mailcert /usr/local/bin/mail-cert-cron
339 EOF
340
341 cat >/etc/systemd/system/mailcert.timer <<'EOF'
342 [Unit]
343 Description=Run mail-cert once a day
344
345 [Timer]
346 OnCalendar=daily
347
348 [Install]
349 WantedBy=timers.target
350 EOF
351 m systemctl daemon-reload
352 m systemctl start mailcert
353 m systemctl restart mailcert.timer
354 m systemctl enable mailcert.timer
355
356
357
358 # * common exim4 config
359 source /a/bin/bash_unpublished/source-state
360
361 m sudo gpasswd -a iank adm #needed for reading logs
362
363
364 ### make local bounces go to normal maildir
365 # local mail that bounces goes to /Maildir or /root/Maildir
366 dirs=(/m/md/bounces/{cur,tmp,new})
367 m mkdir -p ${dirs[@]}
368 m chown iank:iank /m /m/md
369 m ln -sfT /m/md /m/iank
370 m chmod 700 /m /m/md
371 m chown -R $u:Debian-exim /m/md/bounces
372 m chmod 775 ${dirs[@]}
373 m usermod -a -G Debian-exim $u
374 for d in /Maildir /root/Maildir; do
375 if [[ ! -L $d ]]; then
376 m rm -rf $d
377 fi
378 m ln -sf -T /m/md/bounces $d
379 done
380
381
382 # by default, only 10 days of logs are kept. increase that.
383 m sed -ri 's/^(\s*rotate\s).*/\11000/' /etc/logrotate.d/exim4-base
384
385
386 ## https://blog.dhampir.no/content/make-exim4-on-debian-respect-forward-and-etcaliases-when-using-a-smarthost
387 # i only need .forwards, so just doing that one.
388 cd /etc/exim4/conf.d/router
389 b=userforward_higher_priority
390 # replace the router name so it is unique
391 sed -r s/^\\S+:/$b:/ 600_exim4-config_userforward >175_$b
392
393
394 rm -vf /etc/exim4/conf.d/main/000_localmacros # old filename
395 cat >/etc/exim4/conf.d/main/000_local <<EOF
396 MAIN_TLS_ENABLE = true
397
398 # debian exim config added this in 2016 or so?
399 # it's part of the smtp spec, to limit lines to 998 chars
400 # but a fair amount of legit mail does not adhere to it. I don't think
401 # this should be default, like it says in
402 # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=828801
403 # todo: the bug for introducing this was about headers, but
404 # the fix maybe is for all lines? one says gmail rejects, the
405 # other says gmail does not reject. figure out and open a new bug.
406 IGNORE_SMTP_LINE_LENGTH_LIMIT = true
407
408 # more verbose logs
409 MAIN_LOG_SELECTOR = +all
410
411
412 # normally empty, I set this so I can set the envelope address
413 # when doing mail redelivery to invoke filters. Also allows
414 # me exiqgrep and stuff.
415 MAIN_TRUSTED_GROUPS = $u
416
417 # default is 10. when exim has been down for a bit, fsf mailserver
418 # will do a big send in one connection, then exim decides to put
419 # the messages in the queue instead of delivering them, to avoid
420 # spawning too many delivery processes. Pretty sure my system
421 # can handle a lot more, but lets go with this.
422 smtp_accept_queue_per_connection = 100
423
424
425 DKIM_CANON = relaxed
426 DKIM_SELECTOR = li
427
428 # from comments in
429 # https://debian-administration.org/article/718/DKIM-signing_outgoing_mail_with_exim4
430
431 # The file is based on the outgoing domain-name in the from-header.
432 DKIM_DOMAIN = \${lc:\${domain:\$h_from:}}
433 # sign if key exists
434 DKIM_PRIVATE_KEY= \${if exists{/etc/exim4/\${dkim_domain}-private.pem} {/etc/exim4/\${dkim_domain}-private.pem}}
435
436 # most of the ones that gmail seems to use.
437 # Exim has horrible default of signing unincluded
438 # list- headers since they got mentioned in an
439 # rfc, but this messes up mailing lists, like gnu/debian which want to
440 # keep your dkim signature intact but add list- headers.
441 DKIM_SIGN_HEADERS = mime-version:in-reply-to:references:from:date:subject:to
442 EOF
443
444 rm -fv /etc/exim4/rcpt_local_acl # old path
445 cat >/etc/exim4/conf.d/rcpt_local_acl <<'EOF'
446 # Only hosts we control send to @mail.iankelling.org, so make sure
447 # they are all authed.
448 # Note, if we wanted authed senders for all domains,
449 # we could make this condition in acl_check_mail
450 deny
451 message = ian trusted domain recepient but no auth
452 !authenticated = *
453 domains = mail.iankelling.org
454 EOF
455 rm -fv /etc/exim4/data_local_acl # old path
456 cat >/etc/exim4/conf.d/data_local_acl <<'EOF'
457 # Except for the "condition =", this was
458 # a comment in the check_data acl. The comment about this not
459 # being suitable is mostly bs. The only thing related I found was to
460 # add the condition =, cuz spamassassin has problems with big
461 # messages and spammers don't bother with big messages,
462 # but I've increased the size from 10k
463 # suggested in official docs, and 100k in the wiki example because
464 # those docs are rather old and I see a 110k spam message
465 # pretty quickly looking through my spam folder.
466 warn
467 condition = ${if < {$message_size}{2000K}}
468 spam = Debian-exim:true
469 add_header = X-Spam_score: $spam_score\n\
470 X-Spam_score_int: $spam_score_int\n\
471 X-Spam_bar: $spam_bar\n\
472 X-Spam_report: $spam_report
473
474 #accept
475 # spf = pass:fail:softfail:none:neutral:permerror:temperror
476 # dmarc_status = reject:quarantine
477 # add_header = Reply-to: dmarctest@iankelling.org
478
479 EOF
480 cat >/etc/exim4/conf.d/auth/29_exim4-config_auth <<'EOF'
481 # from 30_exim4-config_examples
482
483 plain_server:
484 driver = plaintext
485 public_name = PLAIN
486 server_condition = "${if crypteq{$auth3}{${extract{1}{:}{${lookup{$auth2}lsearch{CONFDIR/passwd}{$value}{*:*}}}}}{1}{0}}"
487 server_set_id = $auth2
488 server_prompts = :
489 .ifndef AUTH_SERVER_ALLOW_NOTLS_PASSWORDS
490 server_advertise_condition = ${if eq{$tls_in_cipher}{}{}{*}}
491 .endif
492 EOF
493
494 cat >/etc/exim4/conf.d/router/900_exim4-config_local_user <<'EOF'
495 ### router/900_exim4-config_local_user
496 #################################
497
498 # This router matches local user mailboxes. If the router fails, the error
499 # message is "Unknown user".
500
501 local_user:
502 debug_print = "R: local_user for $local_part@$domain"
503 driver = accept
504 domains = +local_domains
505 # ian: commented this, in conjunction with a dovecot lmtp
506 # change so I get mail for all users.
507 # check_local_user
508 local_parts = ! root
509 transport = LOCAL_DELIVERY
510 cannot_route_message = Unknown user
511 EOF
512 cat >/etc/exim4/conf.d/transport/30_exim4-config_dovecot_lmtp <<'EOF'
513 dovecot_lmtp:
514 driver = lmtp
515 socket = /var/run/dovecot/lmtp
516 #maximum number of deliveries per batch, default 1
517 batch_max = 200
518 EOF
519
520 cat >/etc/exim4/host_local_deny_exceptions <<'EOF'
521 mail.fsf.org
522 *.posteo.de
523 EOF
524
525 cat >/etc/exim4/conf.d/router/190_exim4-config_fsfsmarthost <<'EOF'
526 # smarthost for fsf mail
527 # ian: copied from /etc/exim4/conf.d/router/200_exim4-config_primary, and added senders = and
528 # replaced DCsmarthost with mail.fsf.org
529 fsfsmarthost:
530 debug_print = "R: smarthost for $local_part@$domain"
531 driver = manualroute
532 domains = ! +local_domains
533 senders = *@fsf.org
534 transport = remote_smtp_smarthost
535 route_list = * mail.fsf.org byname
536 host_find_failed = ignore
537 same_domain_copy_routing = yes
538 no_more
539 EOF
540
541
542 cat >/etc/exim4/update-exim4.conf.conf <<'EOF'
543 # default stuff, i havent checked if its needed
544 dc_minimaldns='false'
545 dc_relay_nets=''
546 CFILEMODE='644'
547 dc_use_split_config='true'
548 dc_local_interfaces=''
549 dc_mailname_in_oh='true'
550 EOF
551
552
553 # ** dovecot
554 dovecot-setup() {
555 # based on a little google and package search, just the dovecot
556 # packages we need instead of dovecot-common.
557 #
558 # dovecot-lmtpd is for exim to deliver to dovecot instead of maildir
559 # directly. The reason to do this is to use dovecot\'s sieve, which
560 # has extensions that allow it to be almost equivalent to exim\'s
561 # filter capabilities, some ways probably better, some worse, and
562 # sieve has the benefit of being supported in postfix and
563 # proprietary/weird environments, so there is more examples on the
564 # internet. I was torn about whether to do this or not, meh.
565 pi dovecot-core dovecot-imapd dovecot-sieve dovecot-lmtpd
566
567 for f in /p/c{/machine_specific/$HOSTNAME,}/filesystem/etc/dovecot/users; do
568 e $f
569 if [[ -e $f ]]; then
570 m sudo rsync -ahhi --chown=root:dovecot --chmod=0640 $f /etc/dovecot/
571 break
572 fi
573 done
574 for f in /p/c/subdir_files/sieve/*sieve /a/c/subdir_files/sieve/*sieve; do
575 m sudo -u $u /a/exe/lnf -T $f $uhome/sieve/${f##*/}
576 done
577 # If we changed 90-sieve.conf and removed the active part of the
578 # sieve option, we wouldn\'t need this, but I\'d rather not modify a
579 # default config if not needed. This won\'t work as a symlink in /a/c
580 # unfortunately.
581 if [[ -e $uhome/sieve/personal.sieve ]]; then
582 m sudo -u $u /a/exe/lnf -T sieve/main.sieve $uhome/.dovecot.sieve
583 fi
584
585 # we set this later in local.conf
586 sed -ri -f - /etc/dovecot/conf.d/10-mail.conf <<'EOF'
587 /^\s*mail_location\s*=/d
588 EOF
589
590 cat >/etc/dovecot/conf.d/20-lmtp.conf <<EOF
591 protocol lmtp {
592 #per https://wiki2.dovecot.org/Pigeonhole/Sieve/Configuration
593 mail_plugins = \$mail_plugins sieve
594 # default was
595 #mail_plugins = \$mail_plugins
596
597 # For a normal setup with exim, we need something like this, which
598 # removes the domain part
599 # auth_username_format = %Ln
600 #
601 # or else # Exim says something like
602 # "LMTP error after RCPT ... 550 ... User doesn't exist someuser@somedomain"
603 # Dovecot verbose log says something like
604 # "auth-worker(9048): passwd(someuser@somedomain): unknown user"
605 # reference: http://wiki.dovecot.org/LMTP/Exim
606 #
607 # However, I use this to direct all mail to the same inbox.
608 # A normal way to do this, which I did at first is to have
609 # a router in exim almost at the end, eg 950,
610 #local_catchall:
611 # debug_print = "R: catchall for \$local_part@\$domain"
612 # driver = redirect
613 # domains = +local_domains
614 # data = $u
615 # based on
616 # http://blog.alteholz.eu/2015/04/exim4-and-catchall-email-address/
617 # with superflous options removed.
618 # However, this causes the envelope to be rewritten,
619 # which makes filtering into mailboxes a little less robust or more complicated,
620 # so I've done it this way instead. it also requires
621 # modifying the local router in exim.
622 auth_username_format = $u
623 }
624
625 EOF
626
627
628 cat >/etc/dovecot/local.conf <<EOF
629 # so I can use a different login that my shell login for mail. this is
630 # worth doing solely for the reason that if this login is compromised,
631 # it won't also compromise my shell password.
632 !include conf.d/auth-passwdfile.conf.ext
633
634 # settings derived from wiki and 10-ssl.conf
635 ssl = required
636 ssl_cert = </etc/exim4/exim.crt
637 ssl_key = </etc/exim4/exim.key
638 # https://github.com/certbot/certbot/raw/master/certbot-apache/certbot_apache/options-ssl-apache.conf
639 # in my cert cronjob, I check if that has changed upstream.
640 ssl_cipher_list = ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS
641
642 # ian: added this, more secure, per google etc
643 ssl_prefer_server_ciphers = yes
644
645 # ian: %u is used for alerts user vs iank
646 mail_location = maildir:/m/%u:LAYOUT=fs:INBOX=/m/%u/INBOX
647 mail_uid = $u
648 mail_gid = $u
649
650 # for debugging info, uncomment these.
651 # logs go to syslog and to /var/log/mail.log
652 # auth_verbose=yes
653 #mail_debug=yes
654 EOF
655 ####### end dovecot-setup ########
656 }
657
658
659
660 # * if MAIL_HOST
661 case $HOSTNAME in
662 $MAIL_HOST)
663 dovecot-setup
664
665 # ** exim
666
667 sudo rsync -ahhi --chown=root:Debian-exim --chmod=0640 \
668 /p/c/filesystem/etc/exim4/passwd /p/c/filesystem/etc/exim4/*.pem /etc/exim4/
669
670
671 # mail.iankelling.org so local imap clients can connect with tls and
672 # when they happen to not be local.
673 sed -ri -f - /etc/hosts <<'EOF'
674 /^127\.0\.1\.1.* mail\.iankelling\.org\b/{p;d}
675 /^127\.0\.1\.1 /s/ *$/ mail.iankelling.org/
676 EOF
677 /a/exe/cedit mail /etc/dnsmasq-servers.conf <<'EOF' || [[ $? == 1 ]]
678 server=/mail.iankelling.org/127.0.1.1
679 EOF
680 if systemctl is-active dnsmasq >/dev/null; then
681 m systemctl restart dnsmasq
682 m nscd -i hosts
683 fi
684
685 # I used to use debconf-set-selections + dpkg-reconfigure,
686 # which then updates this file
687 # but the process is slower than updating it directly and then I want to set other things in
688 # update-exim4.conf.conf, so there's no point.
689 # The file is documented in man update-exim4.conf,
690 # except the man page is not perfect, read the bash script to be sure about things.
691
692 # The debconf questions output is additional documentation that is not
693 # easily accessible, but super long, along with the initial default comment in this
694 # file, so I've saved that into ./mail-notes.conf.
695
696 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
697 # note: some things we don't set that are here by default because they are unused.
698
699 dc_eximconfig_configtype='internet'
700
701 # man page: is used to build the local_domains list, together with "localhost"
702 # iank.bid is for testing
703 # mail.iankelling.org is for machines i own
704 dc_other_hostnames='*.iankelling.org;iankelling.org;*iank.bid;iank.bid;*zroe.org;zroe.org;*.b8.nz;b8.nz'
705
706 # from man page:
707 # Is a list of domains for which we accept mail from anywhere on the Internet but which are not delivered locally, e.g.
708 # because this machine serves as secondary MX for these domains. Sets MAIN_RELAY_TO_DOMAINS.
709 # todo: we should not accept from anywhere, only the mx for fsf.
710 dc_relay_domains='*.fsf.org;fsf.org'
711 dc_localdelivery='dovecot_lmtp'
712 EOF
713
714
715 # the debconf output about mailname is as follows:
716 # The 'mail name' is the domain name used to 'qualify' mail addresses without a domain
717 # name.
718 # This name will also be used by other programs. It should be the single, fully
719 # qualified domain name (FQDN).
720 # Thus, if a mail address on the local host is foo@example.org, the correct value for
721 # this option would be example.org.
722 # This name won\'t appear on From: lines of outgoing messages if rewriting is enabled.
723
724 echo mail.iankelling.org > /etc/mailname
725
726 # MAIN_HARDCODE_PRIMARY_HOSTNAME might mess up the
727 # smarthost config type, not sure. all other settings
728 # would be unused in that config type.
729 cat >>/etc/exim4/conf.d/main/000_local <<EOF
730 # enable 587 in addition to the default 25, so that
731 # i can send mail where port 25 is firewalled by isp
732 daemon_smtp_ports = 25 : 587
733
734
735
736 # failing message on mail-tester.com:
737 # We check if there is a server (A Record) behind your hostname kd.
738 # You may want to publish a DNS record (A type) for the hostname kd or use a different hostname in your mail software
739 # https://serverfault.com/questions/46545/how-do-i-change-exim4s-primary-hostname-on-a-debian-box
740 # and this one seemed appropriate from grepping config.
741 # I originally set this to li.iankelling.org, but then ended up with errors when li tried to send
742 # mail to kd, so this should basically be a name that no host has as their
743 # canonical hostname since the actual host sits behind a nat and changes.
744 # Seems logical for this to be the same as mailname.
745 MAIN_HARDCODE_PRIMARY_HOSTNAME = mail.iankelling.org
746
747 # options exim has to avoid having to alter the default config files
748 CHECK_RCPT_LOCAL_ACL_FILE = /etc/exim4/conf.d/rcpt_local_acl
749 CHECK_DATA_LOCAL_ACL_FILE = /etc/exim4/conf.d/data_local_acl
750
751
752 # recommended if dns is expected to work
753 CHECK_RCPT_VERIFY_SENDER = true
754 # seems like a good idea
755 CHECK_DATA_VERIFY_HEADER_SENDER = true
756 CHECK_RCPT_SPF = true
757 CHECK_RCPT_REVERSE_DNS = true
758 CHECK_MAIL_HELO_ISSUED = true
759
760 # testing dmarc
761 #dmarc_tld_file = /etc/public_suffix_list.dat
762 EOF
763
764 f=/etc/cron.daily/refresh-dmarc-tld-file
765 cat >$f <<'EOF'
766 #!/bin/bash
767 cd /etc
768 wget -q -N https://publicsuffix.org/list/public_suffix_list.dat
769 EOF
770 m chmod 755 $f
771
772 sed -i --follow-symlinks -f - /etc/aliases <<EOF
773 \$a root: $postmaster
774 /^root:/d
775 EOF
776
777
778 # https://selivan.github.io/2017/12/30/systemd-serice-always-restart.html
779 d=/etc/systemd/system/openvpn@mail.service.d
780 m mkdir -p $d
781 cat >$d/override.conf <<'EOF'
782 [Service]
783 Restart=always
784 # time to sleep before restarting a service
785 RestartSec=1
786
787 [Unit]
788 # StartLimitIntervalSec in recent systemd versions
789 StartLimitInterval=0
790 EOF
791 if ! systemctl cat openvpn@mail.service|grep -xF StartLimitInterval=0 &>/dev/null; then
792 # needed for the above config to go into effect
793 m systemctl daemon-reexec
794 fi
795
796
797 m systemctl enable mailclean.timer
798 m systemctl start mailclean.timer
799 m systemctl restart $vpn_ser@mail
800 m systemctl enable $vpn_ser@mail
801 m systemctl enable dovecot
802 m systemctl restart dovecot
803 ;;
804 # * not MAIL_HOST
805 *) # $HOSTNAME != $MAIL_HOST
806 # remove mail. 2 lines to properly remove whitespace
807 sed -ri -f - /etc/hosts <<'EOF'
808 s#^(127\.0\.1\.1 .*) +mail\.iankelling\.org$#\1#
809 s#^(127\.0\.1\.1 .*)mail\.iankelling\.org +(.*)#\1\2#
810 EOF
811
812 echo | /a/exe/cedit mail /etc/dnsmasq-servers.conf || [[ $? == 1 ]]
813 if systemctl is-active dnsmasq >/dev/null; then
814 m nscd -i hosts
815 m systemctl restart dnsmasq # reload does not ensure new config is used
816 fi
817
818 m systemctl disable mailclean.timer &>/dev/null ||:
819 m systemctl stop mailclean.timer &>/dev/null ||:
820 m systemctl disable $vpn_ser@mail
821 m systemctl stop $vpn_ser@mail
822 #
823 #
824 # would only exist because I wrote it i the previous condition,
825 # it\'s not part of exim
826 rm -fv /etc/exim4/conf.d/main/000_localmacros
827 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
828 dc_eximconfig_configtype='smarthost'
829 dc_smarthost='$smarthost'
830 # The manpage incorrectly states this will do header rewriting, but
831 # that only happens if we have dc_hide_mailname is set.
832 dc_readhost='iankelling.org'
833 EOF
834
835 hostname -f >/etc/mailname
836
837 f=/p/c/filesystem/etc/exim4/passwd.client
838 if [[ ! -e $f ]]; then
839 f=/p/c/machine_specific/$HOSTNAME/filesystem/etc/exim4/passwd.client
840 fi
841 m sudo rsync -ahhi --chown=root:Debian-exim --chmod=0640 $f /etc/exim4/
842
843 ;;&
844 ## we use this host to monitor MAIL_HOST
845 l2)
846 dovecot-setup
847 m systemctl enable dovecot
848 m systemctl restart dovecot
849 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
850 # man page: is used to build the local_domains list, together with "localhost"
851 # mail.iankelling.org is for machines i own
852 dc_other_hostnames='l2.b8.nz'
853 dc_localdelivery='dovecot_lmtp'
854 EOF
855 # This ends up at alerts mailbox on MAIL_HOST, but using a user that doesn't exist elsewhere
856 # is no good.
857 sed -i --follow-symlinks -f - /etc/aliases <<EOF
858 \$a root: iank
859 /^root:/d
860 EOF
861 ;;
862 # not l2 and not MAIL_HOST
863 *)
864
865
866 # This ends up at alerts mailbox on MAIL_HOST, but using a user that doesn't exist elsewhere
867 # is no good.
868 sed -i --follow-symlinks -f - /etc/aliases <<EOF
869 \$a root: root@mail.iankelling.org
870 /^root:/d
871 EOF
872 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
873 # Only used in case of bounces.
874 dc_localdelivery='maildir_home'
875 EOF
876 m systemctl disable dovecot ||:
877 m systemctl stop dovecot ||:
878 ;;
879 esac # end $HOSTNAME != $MAIL_HOST
880
881 # * spool dir setup
882
883 # ** bind mount setup
884 # put spool dir in directory that spans multiple distros.
885 # based on http://www.postfix.org/qmgr.8.html and my notes in gnus
886 #
887 # todo: I\'m suspicious of uids for Debian-exim being the same across
888 # distros. It would be good to test this.
889 dir=/nocow/exim4
890 sdir=/var/spool/exim4
891 # we only do this if our system has $dir
892
893 # this used to do a symlink, but, in the boot logs, /nocow would get mounted succesfully,
894 # about 2 seconds later, exim starts, and immediately puts into paniclog:
895 # honVi-0000u3-82 Failed to create directory "/var/spool/exim4/input": No such file or directory
896 # so, im trying a bind mount to get rid of that.
897 if [[ -e /nocow ]]; then
898 if ! grep -Fx "/nocow/exim4 /var/spool/exim4 none bind 0 0" /etc/fstab; then
899 echo "/nocow/exim4 /var/spool/exim4 none bind 0 0" >>/etc/fstab
900 fi
901 if ! mountpoint -q $sdir; then
902 m systemctl stop exim4
903 if [[ -L $sdir ]]; then
904 m rm $sdir
905 fi
906 if [[ ! -e $dir && -d $sdir ]]; then
907 m mv $sdir $dir
908 fi
909 if [[ ! -d $sdir ]]; then
910 m mkdir $sdir
911 m chmod 000 $sdir # only want it to be used when its mounted
912 fi
913 m mount $sdir
914 fi
915 fi
916
917
918
919 # ** exim/spool uid setup
920 # i have the spool directory be common to distro multi-boot, so
921 # we need the uid to be the same. 608 cuz it's kind of in the middle
922 # of the free system uids.
923 IFS=:; read -r _ _ uid _ < <(getent passwd Debian-exim ||:) ||:; unset IFS
924 IFS=:; read -r _ _ gid _ < <(getent group Debian-exim ||:) ||:; unset IFS
925 if [[ ! $uid ]]; then
926 # from /var/lib/dpkg/info/exim4-base.postinst, plus uid and gid options
927 m adduser --uid 608 --system --group --quiet --home /var/spool/exim4 \
928 --no-create-home --disabled-login --force-badname Debian-exim
929 elif [[ $uid != 608 ]]; then
930 m systemctl stop exim4 ||:
931 m usermod -u 608 Debian-exim
932 m groupmod -g 608 Debian-exim
933 m usermod -g 608 Debian-exim
934 m find / /nocow -xdev -uid $uid -exec chown -h 608 {} +
935 m find / /nocow -xdev -gid $gid -exec chgrp -h 608 {} +
936 fi
937
938
939
940
941 # * reload exim
942
943 if systemctl is-active exim4 >/dev/null; then
944 m systemctl reload exim4
945 else
946 m systemctl start exim4
947 fi
948
949
950 # * mail monitoring / testing
951
952 case $HOSTNAME in
953 $MAIL_HOST|l2)
954 # note: cronjob "ian" also does some important monitoring
955 cat >/etc/cron.d/mailtest <<EOF
956 SHELL=/bin/bash
957 PATH=/usr/bin:/bin:/usr/local/bin
958 */5 * * * * $u send-test-forward |& log-once send-test-forward
959 */10 * * * * root chmod -R g+rw /m/md/bounces |& log-once -1 bounces-chmod
960 EOF
961 ;;&
962 $MAIL_HOST)
963 test_from=ian@iankelling.org
964 test_to=iank@posteo.de
965
966 cat >>/etc/cron.d/mailtest <<EOF
967 */5 * * * * $u mailtest-check |& log-once -1 mailtest-check
968 2 * * * * $u check-remote-mailqs |& log-once check-remote-mailqs
969 EOF
970 m sudo rsync -ahhi --chown=root:root --chmod=0755 \
971 /b/ds/mailtest-check /b/ds/check-remote-mailqs /usr/local/bin/
972 ;;&
973 l2)
974 test_from=iank@l2.b8.nz
975 test_to=testignore@iankelling.org
976 ;;&
977 $MAIL_HOST|l2)
978 cat >/usr/local/bin/send-test-forward <<EOFOUTER
979 #!/bin/bash
980 /usr/sbin/exim -t <<EOF
981 From: $test_from
982 To: $test_to
983 Subject: primary_test \$(date +%s) \$(date +%Y-%m-%dT%H:%M:%S%z)
984
985 eom
986 EOF
987 EOFOUTER
988 m chmod +x /usr/local/bin/send-test-forward
989 ;;
990 *)
991 rm -fv /etc/cron.d/mailtest
992 ;;
993 esac
994
995
996
997 # * misc
998 m sudo -u $u ln -sf -T /m/.mu /home/$u/.mu
999
1000
1001 # /etc/alias setup is debian specific, and exim postinst script sets up
1002 # an /etc/alias from root to the postmaster, based on the question
1003 # exim4-config exim4/dc_postmaster, as long as there exists an entry for
1004 # root, or there was no preexisting aliases file. postfix won\'t set up
1005 # a root to $postmaster alias if it\'s already installed. Easiest to
1006 # just set it ourselves.
1007
1008 # debconf question for postmaster:
1009 # Mail for the 'postmaster', 'root', and other system accounts needs to be redirected
1010 # to the user account of the actual system administrator.
1011 # If this value is left empty, such mail will be saved in /var/mail/mail, which is not
1012 # recommended.
1013 # Note that postmaster\'s mail should be read on the system to which it is directed,
1014 # rather than being forwarded elsewhere, so (at least one of) the users listed here
1015 # should not redirect their mail off this machine. A 'real-' prefix can be used to
1016 # force local delivery.
1017 # Multiple user names need to be separated by spaces.
1018 # Root and postmaster mail recipient:
1019
1020
1021 exit 0
1022 :