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