fixes, prometheus, lots of stuff
[distro-setup] / mail-setup
1 #!/bin/bash
2 # * intro
3 # Copyright (C) 2019 Ian Kelling
4 # SPDX-License-Identifier: AGPL-3.0-or-later
5
6 # todo: handle errors like this:
7 # Mar 02 12:44:26 kw systemd[1]: exim4.service: Found left-over process 68210 (exim4) in control group while starting unit. Ignoring.
8 # Mar 02 12:44:26 kw systemd[1]: This usually indicates unclean termination of a previous run, or service implementation deficiencies.
9
10 # todo: harden dovecot. need to do some research. one way is for it to only listen on a wireguard vpn interface, so only clients that are on the vpn can access it.
11 # todo: consider hardening cups listening on 0.0.0.0
12 # todo: stop/disable local apache, and rpc.mountd, and kdeconnect when not in use.
13 # todo: check that spamd and unbound only listen locally.
14
15 # todo: hosts should only allow external mail that is authed and
16 # destined for backup route. it is a minor issue since traffic is
17 # limited to the wghole network.
18
19 # todo: emailing info@amnimal.ninja produces a bounce, user doesn't exist
20 # instead of a simple rejection like it should.
21
22 # todo: run mailping test after running, or otherwise
23 # clear out terminal alert
24
25 # todo: reinstall bk with bigger filesystem
26
27 # todo: on bk, dont send email if mailvpn is not up
28
29 # todo: mailtest-check should check on bk too
30
31 # todo: disable postgrey
32
33 # todo: in testforward-check, we should also look
34
35 # todo: test that bounces dont help create valid mailtest-check
36
37 # todo: move mail stuff in distro-end into this file
38
39 # todo: consider rotating dkim & publishing key so every past email I sent
40 # isnt necessarily signed
41
42 # todo: consider how to get clamav out of Debian-exim group
43 # so it cant read/write the whole mail spool, for better
44 # security.
45
46 # todo: create a cronjob to update or warn on expiring dnssec keys
47
48 # todo: we should test failed mail daily or so
49 # failed cronjob, failed sysd-log-once,
50 # a local bounce from a cronjob, a local bounce
51 # to a bad remote address, perhaps a local failure
52 # when the sending daemon is down.
53 # And send an alert email if no alerts have been sent
54 # in 2 or 3 days or something. todo, test cron mail on li.
55
56 # todo: look at mailinabox extra dns records, note these changelogs:
57 # - An MTA-STS policy for incoming mail is now published (in DNS and over HTTPS) when the primary hostname and email address domain both have a signed TLS certificate installed, allowing senders to know that an encrypted connection should be enforced.
58 # - The per-IP connection limit to the IMAP server has been doubled to allow more devices to connect at once, especially with multiple users behind a NAT.
59 #
60
61 # todo: mailtest-check failure on remote hosts is not going to alert me.
62 # sort that out.
63 # todo: test mail failure as well as success.
64 #
65 # todo: validate that mailtest-check is doing dnsbl checks.
66
67 # background: I want to run exim in a network namespace so it can send
68 # and receive through a vpn. This is needed so it can do ipv6, because
69 # outside the namespace if we dont have ipv6, to send ipv6 through the
70 # vpn, we have to send all our ipv6 through the vpn. I did this for a
71 # long time, it was fine, but it causes various pains, like increased
72 # latency, increased recaptcha because my ip is from a data center, just
73 # various issues I dont want on all the time. The problem with the
74 # namespace is that all kinds of programs want to invoke exim, but they
75 # wont be in the namespace. I could replace exim with a wrapper that
76 # jumps into the namespace, i tried that, it works fine. One remaining
77 # problem was that I would have needed to hook into exim upgrades to
78 # move exim and replace it with my wrapper script. Also, my script to
79 # join the namespace is not super reliable because it uses a pgrep.
80 # Instead, I should have created a systemd service for a process that
81 # will never die and just writes its pid somewhere convenient.
82 # That implementation
83 # is below here:
84 #
85 # sudoers:
86 # user ALL=(ALL) /usr/sbin/exim4
87 #
88 # move exim4 to eximian, use this script for exim4:
89 #
90 # #!/bin/bash
91 # if ip a show veth1-mail &>/dev/null; then
92 # /usr/sbin/eximian "$@"
93 # exit
94 # fi
95 # dosudo=false
96 # if [[ $USER && $USER != root ]]; then
97 # dosudo=true
98 # fi
99 # pid=$(pgrep -f "/usr/sbin/openvpn .* --config /etc/openvpn/.*mail.conf")
100 # if $dosudo; then
101 # sudo nsenter -t $pid -n -m sudo -u $USER /usr/sbin/eximian "$@"
102 # else
103 # nsenter -t $pid -n -m /usr/sbin/eximian "$@"
104 # fi
105 # ## end script
106 #
107 # an alternate solution: there is a small setguid program for
108 # network namespaces in my bookmarks.
109 #
110 # However, the solution I went with is: have 2 exim
111 # configs. A nonstandard location for the daemon that runs
112 # in the namespace. For all other invocations, it uses
113 # the default config location, which is altered to be
114 # in a smarthost config which sends mail to the deaemon.
115 #
116 # I have a bash function, enn to invoke exim like the daemon is running.
117 # and mailbash to just enter its network namespace.
118
119 if [ -z "$BASH_VERSION" ]; then echo "error: shell is not bash" >&2; exit 1; fi
120
121 shopt -s nullglob
122
123 if [[ -s /usr/local/lib/err ]]; then
124 source /usr/local/lib/err
125 elif [[ -s /a/bin/errhandle/err ]]; then
126 source /a/bin/errhandle/err
127 else
128 err "no err tracing script found"
129 fi
130 source /a/bin/distro-functions/src/identify-distros
131 source /a/bin/distro-functions/src/package-manager-abstractions
132
133 # has nextcloud_admin_pass in it
134 f=/p/c/machine_specific/$HOSTNAME/mail
135 if [[ -e $f ]]; then
136 # shellcheck source=/p/c/machine_specific/bk/mail
137 source $f
138 fi
139
140
141 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
142
143 # note, this is hardcoded in /etc/exim4/conf.d/main/000_local
144 u=$(id -nu 1000)
145
146
147 usage() {
148 cat <<EOF
149 Usage: ${0##*/} anything_here_to_debug
150 Setup exim4 & dovecot & related things
151
152 -h|--help Print help and exit.
153 EOF
154 exit $1
155 }
156
157 # debug output if we pass any arg
158 if (( $# )); then
159 set -x
160 fi
161
162
163 ####### instructions for icedove #####
164 # Incoming mail server: mail.iankelling.org, port 143, username iank, connection security starttls, authentication method normal password,
165 # then click advanced so it accepts it.
166 # we could also just use 127.0.0.1 with no ssl
167 #
168 # hamburger -> preferences -> preferences -> advanced tab -> config editor button -> security.ssl.enable_ocsp_must_staple = false
169 # background: dovecot does not yet have ocsp stapling support
170 # reference: https://community.letsencrypt.org/t/simple-guide-using-lets-encrypt-ssl-certs-with-dovecot/2921
171 #
172 # for phone, k9mail, fdroid, same thing but username alerts, pass in ivy-pass.
173 # also, bk.b8.nz for secondary alerts, username is iank. same alerts pass.
174 # fetching mail settings: folder poll frequency 10 minutes.
175 # account settings, fetching mail, push folders: All. Then disable the persistent notification.
176 #######
177
178
179 # * perstent password instructions
180 # Note: for cert cron, we need to manually run first to accept known_hosts
181
182 # # exim passwords:
183 # # for hosts which have all private files I just use the same user
184 # # for other hosts, each one get\'s their own password.
185 # # for generating secure pass, and storing for server too:
186 # f=$(mktemp)
187 # host=tp
188 # apg -m 50 -x 70 -n 1 -a 1 -M CLN >$f
189 # s sed -i "/^$host:/d" /p/c/filesystem/etc/exim4/passwd
190 # echo "$host:$(mkpasswd -m sha-512 -s <$f)" >>/p/c/filesystem/etc/exim4/passwd
191 # #reference: exim4_passwd_client(5)
192 # dir=/p/c/machine_specific/$host/filesystem/etc/exim4
193 # mkdir -p $dir
194 # echo "mail.iankelling.org:$host:$(<$f)" > $dir/passwd.client
195 # # then run this script
196
197 # # dovecot password, i just need 1 as I\'m the only user
198 # mkdir /p/c/filesystem/etc/dovecot
199 # echo "iank:$(doveadm pw -s SHA512-CRYPT)::::::" >>/p/c/filesystem/etc/dovecot/users
200
201 ####### end perstent password instructions ######
202
203
204 # * dkim dns
205 # # Remove 1 level of comments in this section, set the domain var
206 # # for the domain you are setting up, then run this and copy dns settings
207 # # into dns.
208 # domain=iankelling.org
209 # c /p/c/filesystem/etc/exim4
210 # # this has several bugs addressed in comments, but it was helpful
211 # # https://debian-administration.org/article/718/DKIM-signing_outgoing_mail_with_exim4
212
213 # openssl genrsa -out $domain-private.pem 2048
214 # # Then, to get the public key strings to put in bind:
215
216 # # selector is needed for having multiple keys for one domain.
217 # # I dun do that, so just use a static one: li
218 # # Debadmin page does not have v=, fastmail does, and this
219 # # says it\'s recommended in 3.6.1, default is DKIM1 anyways.
220 # # https://www.ietf.org/rfc/rfc6376.txt
221 # # Join and print all but first and last line.
222 # # last line: swap hold & pattern, remove newlines, print.
223 # # lines 2+: append to hold space
224 # echo "bind txt record: remember to truncate $domain so its relative to the bind zone"
225 # cat <<EOF
226 # a._domainkey.$domain TXT (
227 # "v=DKIM1\059 k=rsa\059 p=$(openssl rsa -in $domain-private.pem -pubout |&sed -rn '${x;s/\n//g;s/^(.*)(.{240}$)/\1"\n"\2/p};3,$H')" )
228 # EOF
229 # # sed explanation: skip the first few lines, then put them into the hold space, then
230 # # on the last line, back to the patern space, remove the newlines, then add a newline
231 # # at the last char - 240, because bind txt records need strings <=255 chars,
232 # # other dkim stuff at the begining is is 25 chars, and the pubkey is 393, so this
233 # # leaves us a bit of extra room at the end and a bunch at the beginning.
234
235 # # selector was also put into /etc/exim4/conf.d/main/000_local,
236
237 # * dmarc dns
238
239 # # 2017-02 dmarc policies:
240 # # host -t txt _dmarc.gmail.com
241 # # yahoo: p=reject, hotmail: p=none, gmail: p=none, fastmail none for legacy reasons
242 # # there were articles claiming gmail would be changing
243 # # to p=reject, in early 2017, which didn\'t happen. I see no sources on them. It\'s
244 # # expected to cause problems
245 # # with a few old mailing lists, copying theirs for now.
246 #
247 # echo "dmarc dns, name: _dmarc value: v=DMARC1; p=none; rua=mailto:mailauth-reports@$domain"
248
249 # * other dns
250
251 # # 2017-02 spf policies:
252 # # host -t txt lists.fedoraproject.org
253 # # google ~all, hotmail ~all, yahoo: ?all, fastmail ?all, outlook ~all
254 # # i include fastmail\'s settings, per their instructions,
255 # # and follow their policy. In mail in a box, or similar instructions,
256 # # I\'ve seen recommended to not use a restrictive policy.
257
258 # # to check if dns has updated, you do
259 # host -a mesmtp._domainkey.$domain
260
261 # # mx records,
262 # # setting it to iankelling.org would work the same, but this
263 # # is more flexible, I could change where mail.iankelling.org pointed.
264 # cat <<'EOF'
265 # mx records, 2 records each, for * and empty domain
266 # pri 10 mail.iankelling.org
267 # EOF
268
269 # # dnssec
270 # from brc2, run dnsecgen then dsign, update named.local.conf, publish keys to registrar
271
272 # * functions & constants
273
274 pre="${0##*/}:"
275 m() { printf "$pre %s\n" "$*"; "$@"; }
276 e() { printf "$pre %s\n" "$*"; }
277 err() { printf "$pre %s\n" "$*" >&2; exit 1; }
278
279 reload=false
280 # This file is so if we fail in the middle and rerun, we dont lose state
281 if [[ -e /var/local/mail-setup-reload ]]; then
282 reload=true
283 fi
284 i() { # install file
285 local tmp tmpdir dest="$1"
286 local base="${dest##*/}"
287 local dir="${dest%/*}"
288 if [[ $dir != "$base" ]]; then
289 mkdir -p ${dest%/*}
290 fi
291 ir=false # i result
292 tmpdir=$(mktemp -d)
293 cat >$tmpdir/"$base"
294 tmp=$(rsync -ic $tmpdir/"$base" "$dest")
295 if [[ $tmp ]]; then
296 printf "%s\n" "$tmp"
297 ir=true
298 if [[ $dest == /etc/systemd/system/* ]]; then
299 touch /var/local/mail-setup-reload
300 reload=true
301 fi
302 fi
303 rm -rf $tmpdir
304 }
305 setini() {
306 key="$1" value="$2" section="$3"
307 file="/etc/radicale/config"
308 sed -ri "/ *\[$section\]/,/^ *\[[^]]+\]/{/^\s*${key}[[:space:]=]/d};/ *\[$section\]/a $key = $value" "$file"
309 }
310 soff () {
311 for service; do
312 # ignore services that dont exist
313 if systemctl cat $service &>/dev/null; then
314 m systemctl disable --now $service
315 fi
316 done
317 }
318 sre() {
319 for service; do
320 m systemctl restart $service
321 m systemctl enable $service;
322 done
323 }
324 mailhost() {
325 [[ $HOSTNAME == "$MAIL_HOST" ]]
326 }
327 e() { printf "%s\n" "$*"; }
328 reifactive() {
329 for service; do
330 if systemctl is-active $service >/dev/null; then
331 m systemctl restart $service
332 fi
333 done
334 }
335 stopifactive() {
336 for service; do
337 if systemctl is-active $service >/dev/null; then
338 m systemctl stop $service
339 fi
340 done
341 }
342
343 mxhost=mx.iankelling.org
344 mxport=587
345 forward=$u@$mxhost
346
347 # old setup. left as comment for example
348 # mxhost=mail.messagingengine.com
349 # mxport=587
350 # forward=ian@iankelling.org
351
352 smarthost="$mxhost::$mxport"
353 uhome=$(eval echo ~$u)
354
355 # Somehow on one machine, a file got written with 664 perms.
356 # just being defensive here.
357 umask 0022
358
359 source /a/bin/bash_unpublished/source-state
360 if [[ ! $MAIL_HOST ]]; then
361 err "\$MAIL_HOST not set"
362 fi
363
364 bhost_t=false
365 case $HOSTNAME in
366 $MAIL_HOST) : ;;
367 kd|frodo|x2|x3|kw|sy|bo)
368 bhost_t=true
369 ;;
370 esac
371
372
373 # * Install universal packages
374
375
376 # installs epanicclean iptables-exim ip6tables-exim
377 /a/bin/ds/install-my-scripts
378
379 if [[ $(debian-codename-compat) == bionic ]]; then
380 cat >/etc/apt/preferences.d/spamassassin <<'EOF'
381 Package: spamassassin sa-compile spamc
382 Pin: release n=focal,o=Ubuntu
383 Pin-Priority: 500
384 EOF
385 fi
386
387 # light version of exim does not have sasl auth support.
388 pi-nostart exim4 exim4-daemon-heavy spamassassin openvpn unbound clamav-daemon wireguard
389
390 # note: pyzor debian readme says you need to run some initialization command
391 # but its outdated.
392 pi spf-tools-perl p0f postgrey pyzor razor jq moreutils certbot fail2ban
393 # bad packages that sometimes get automatically installed
394 pu openresolv resolvconf
395
396 soff openvpn
397
398
399 if [[ $(debian-codename) == etiona ]]; then
400 # ip6tables stopped loading on boot. openvpn has reduced capability set,
401 # so running iptables as part of openvpn startup wont work. This should do it.
402 pi iptables-persistent
403 cat >/etc/iptables/rules.v6 <<'EOF'
404 *mangle
405 COMMIT
406 *nat
407 COMMIT
408 EOF
409 # load it now.
410 m ip6tables -S >/dev/null
411 fi
412
413 # our nostart pi fails to avoid enabling
414
415
416 # * Mail clean cronjob
417
418 i /etc/systemd/system/mailclean.timer <<'EOF'
419 [Unit]
420 Description=Run mailclean daily
421
422 [Timer]
423 OnCalendar=monthly
424
425 [Install]
426 WantedBy=timers.target
427 EOF
428
429 i /etc/systemd/system/mailclean.service <<EOF
430 [Unit]
431 Description=Delete and archive old mail files
432 After=multi-user.target
433
434 [Service]
435 User=$u
436 Type=oneshot
437 ExecStart=/usr/local/bin/sysd-mail-once mailclean /a/bin/distro-setup/mailclean
438 EOF
439
440 # * postgrey
441
442
443 i /etc/default/postgrey <<'EOF'
444 POSTGREY_OPTS="--exim --unix=/var/run/postgrey/postgrey.sock --retry-window=4 --max-age=60"
445 EOF
446
447 # * clamav
448
449 m usermod -a -G Debian-exim clamav
450
451 i /etc/systemd/system/clamav-daemon.service.d/fix.conf <<EOF
452 [Service]
453 ExecStartPre=-/bin/mkdir /var/run/clamav
454 ExecStartPre=/bin/chown clamav /var/run/clamav
455 EOF
456
457 # * mail vpn config
458
459 # old.
460 #vpnser=mailvpn.service
461 # todo: this hangs if it cant resolv the endpoint. we
462 # want it to just retry in the background.
463 vpnser=wg-quick@wgmail.service
464
465 case $HOSTNAME in
466 $MAIL_HOST)
467 rsync -aiSAX --chown=root:root --chmod=g-s /p/c/filesystem/etc/wireguard/ /etc/wireguard
468 bindpaths="/etc/127.0.0.1-resolv:/run/systemd/resolve /etc/basic-nsswitch:/etc/resolved-nsswitch:norbind"
469 ;;&
470 bk)
471 bindpaths="/etc/10.173.8.1-resolv:/etc/127.0.0.1-resolv"
472 ;;&
473 *)
474 d=/p/c/machine_specific/$HOSTNAME/filesystem/etc/wireguard/
475 if [[ -d $d ]]; then
476 rsync -aiSAX --chown=root:root --chmod=g-s $d /etc/wireguard
477 fi
478 ;;
479 esac
480
481 case $HOSTNAME in
482 li) : ;;
483 *)
484 i /etc/systemd/system/wg-quick@wgmail.service.d/override.conf <<EOF
485 [Unit]
486 Requires=mailnn.service
487 After=network.target mailnn.service
488 JoinsNamespaceOf=mailnn.service
489 BindsTo=mailnn.service
490 StartLimitIntervalSec=0
491
492 [Service]
493 PrivateNetwork=true
494 # i dont think we need any of these, but it doesnt hurt to stay consistent
495 BindPaths=$bindpaths
496
497 Restart=on-failure
498 RestartSec=20
499 EOF
500 ;;
501 esac
502
503
504 # https://selivan.github.io/2017/12/30/systemd-serice-always-restart.html
505 i /etc/systemd/system/mailvpn.service <<EOF
506 [Unit]
507 Description=OpenVPN tunnel for mail
508 After=syslog.target network-online.target mailnn.service
509 Wants=network-online.target
510 Documentation=man:openvpn(8)
511 Documentation=https://community.openvpn.net/openvpn/wiki/Openvpn24ManPage
512 Documentation=https://community.openvpn.net/openvpn/wiki/HOWTO
513 # needed to continually restatr
514 JoinsNamespaceOf=mailnn.service
515 BindsTo=mailnn.service
516 StartLimitIntervalSec=0
517
518 [Service]
519 Type=notify
520 RuntimeDirectory=openvpn-client
521 RuntimeDirectoryMode=0710
522 WorkingDirectory=/etc/openvpn/client
523 ExecStart=/usr/sbin/openvpn --suppress-timestamps --nobind --config /etc/openvpn/client/mail.conf
524 #CapabilityBoundingSet=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SYS_CHROOT CAP_DAC_OVERRIDE
525 LimitNPROC=10
526 # DeviceAllow=/dev/null rw
527 # DeviceAllow=/dev/net/tun rw
528 PrivateNetwork=true
529 # in the network namespace, we cant connect to systemd-resolved on 127.0.0.53,
530 # because of
531 # https://unix.stackexchange.com/questions/445782/how-to-allow-systemd-resolved-to-listen-to-an-interface-other-than-loopback
532 # there is a workaround there, but i dont think its really worth it,
533 # the mail server is fine with a static dns anyways.
534 # This thread is also interesting,
535 # https://github.com/slingamn/namespaced-openvpn/issues/7
536 # todo: the iptables rule at the bottom could be useful to prevent
537 # dns from leaking in my network namespaced vpn.
538 # I also like the idea of patching systemd-resolved so it
539 # will listen on other interfaces, but its not worth my time.
540 BindPaths=$bindpaths
541 Restart=always
542 # time to sleep before restarting a service
543 RestartSec=20
544
545 [Install]
546 WantedBy=multi-user.target
547 EOF
548
549 i /etc/systemd/system/mailnnroute.service <<'EOF'
550 [Unit]
551 Description=Network routing for mailnn
552 After=syslog.target network-online.target mailnn.service
553 Wants=network-online.target
554 JoinsNamespaceOf=mailnn.service
555 BindsTo=mailnn.service
556 StartLimitIntervalSec=0
557
558 [Service]
559 Type=simple
560 RemainAfterExit=true
561 PrivateNetwork=true
562 ExecStart=/usr/bin/flock -w 20 /tmp/newns.flock /a/bin/newns/newns -n 10.173.8 start mail
563 ExecStop=/usr/bin/flock -w 20 /tmp/newns.flock /a/bin/newns/newns stop mail
564 Restart=always
565 RestartSec=20
566
567
568 [Install]
569 WantedBy=multi-user.target
570 EOF
571
572 #
573 i /etc/systemd/system/mailnn.service <<'EOF'
574 [Unit]
575 Description=Network Namespace for mail vpn service that will live forever and cant fail
576 After=syslog.target network-online.target
577 Wants=network-online.target
578
579 [Service]
580 Type=simple
581 PrivateNetwork=true
582 ExecStart=/bin/sleep infinity
583
584 [Install]
585 WantedBy=multi-user.target
586 EOF
587
588 i /etc/systemd/system/mailbindwatchdog.service <<EOF
589 [Unit]
590 Description=Watchdog to restart services relying on systemd-resolved dir
591 After=syslog.target network-online.target
592 Wants=network-online.target
593 BindsTo=mailnn.service
594
595 [Service]
596 Type=simple
597 ExecStart=/usr/local/bin/mailbindwatchdog $vpnser ${nn_progs[@]} unbound.service radicale.service
598 Restart=always
599 # time to sleep before restarting a service
600 RestartSec=10
601
602 [Install]
603 WantedBy=multi-user.target
604 EOF
605
606
607
608 # old service name
609 rm -fv /etc/systemd/system/openvpn-client-mail@.service
610
611 # We use a local unbound because systemd-resolved wont accept our
612 # request, it will only listen to 127.0.0.53 in the main network
613 # namespace, and rejected feature requests to change that (although I
614 # could change the code and recompile), but anyways, that could answer
615 # with things specific to the lan that aren't applicable in this
616 # namespace, and since unbound is a recursive resolver, it means we just
617 # use our own ip against dnsbl rate limits.
618 #
619 # If we ever notice this change, chattr +i on it
620 # trust-ad is used in t10+, glibc 2.31
621
622 i /etc/127.0.0.1-resolv/stub-resolv.conf <<'EOF'
623 nameserver 127.0.0.1
624 options edns0 trust-ad
625 EOF
626
627 i /etc/127.0.0.53-resolv/stub-resolv.conf <<'EOF'
628 nameserver 127.0.0.53
629 options edns0 trust-ad
630 EOF
631
632
633 i /etc/10.173.8.1-resolv/stub-resolv.conf <<'EOF'
634 nameserver 10.173.8.1
635 options edns0 trust-ad
636 EOF
637
638 # this is just a bug fix for trisquel.
639 f=/etc/apparmor.d/usr.sbin.unbound
640 line="/usr/sbin/unbound flags=(attach_disconnected) {"
641 if ! grep -qFx "$line" $f; then
642 badline="/usr/sbin/unbound {"
643 if ! grep -qFx "$badline" $f; then
644 err expected line in $f not found
645 fi
646 sed -i "s,^$badline$,$line," $f
647 if systemctl is-active apparmor &>/dev/null; then
648 m systemctl reload apparmor
649 fi
650 fi
651
652 # note: anything added to nn_progs needs corresponding rm
653 # down below in the host switch
654 nn_progs=(exim4)
655 if mailhost; then
656 # Note dovecots lmtp doesnt need to be in the same nn to accept delivery.
657 # Its in the nn so remote clients can connect to it.
658 nn_progs+=(spamassassin dovecot)
659 fi
660
661 case $HOSTNAME in
662 $MAIL_HOST)
663 # todo, should this be after vpn service
664 i /etc/systemd/system/unbound.service.d/nn.conf <<EOF
665 [Unit]
666 After=mailnn.service
667 JoinsNamespaceOf=mailnn.service
668 BindsTo=mailnn.service
669 StartLimitIntervalSec=0
670
671 [Service]
672 PrivateNetwork=true
673 # note the nsswitch bind is actually not needed for bk, but
674 # its the same file so it does no harm.
675 BindPaths=$bindpaths
676
677 Restart=always
678 RestartSec=20
679 EOF
680
681 # sooo, there are a few ways to get traffic from the mail network
682 # namespace to go over the wghole.
683 #
684 #1: unify the mail vpn and wghole
685 # into 1 network. this seems simple and logical, so I'm doing it.
686 # One general downside is tying things together, if I need to mess
687 # with one thing, it breaks the other. Oh well for now.
688 #
689 # 2. We can route 10.5.3.0/24 out of the mail nn and nat it into wghole.
690 #
691 # 3. We can setup the routing to happen on li, which seemed like I
692 # just needed to add 10.8.0.4/24 to AllowedIPs in at least the
693 # wghole clients, but I think that is kind of hacky and breaks ipv4
694 # routing within the mailvpn, it happened to work just because exim
695 # prefers ipv6 and that was also available in the mailvpn.
696 #
697 # 4. Put the hole interface into the mail network namespace. This
698 # doesn't work if the mail vpn is wg. For openvpn, it bypasses the
699 # vpn routing and establishes a direct connection. I only use the
700 # hole vpn for randomish things, it should be fine to join the mail
701 # nn for that. There should be some way to fix the routing issue
702 # by doing manual routing, but that doesn't seem like a good use of time.
703 # relevant:
704 # https://www.wireguard.com/netns/#
705 #
706 # for wireguard debugging
707 # echo module wireguard +p > /sys/kernel/debug/dynamic_debug/control
708 # dmesg -w
709
710 ;;&
711 $MAIL_HOST|bk)
712 for unit in ${nn_progs[@]}; do
713 i /etc/systemd/system/$unit.service.d/nn.conf <<EOF
714 [Unit]
715 # commented for old openvpn
716 Requires=$vpnser
717 After=network.target mailnn.service $vpnser
718 JoinsNamespaceOf=mailnn.service
719 BindsTo=mailnn.service
720 StartLimitIntervalSec=0
721
722 [Service]
723 PrivateNetwork=true
724 # note the nsswitch bind is actually not needed for bk, but
725 # its the same file so it does no harm.
726 BindPaths=$bindpaths
727
728 Restart=always
729 RestartSec=20
730 EOF
731 done
732 ;;
733 *)
734 for unit in exim4 spamassassin dovecot unbound; do
735 f=/etc/systemd/system/$unit.service.d/nn.conf
736 if [[ -s $f ]]; then
737 rm -fv $f
738 reload=true
739 fi
740 done
741 ;;
742 esac
743
744 # * spamassassin config
745 i /etc/sysctl.d/80-iank-mail.conf <<'EOF'
746 # see exim spec
747 net.netfilter.nf_conntrack_tcp_timeout_close_wait = 120
748 EOF
749 if $ir; then
750 m sysctl -p
751 fi
752
753 i /etc/spamassassin/mylocal.cf <<'EOF'
754 # this is mylocal.cf because the normal local.cf has a bunch of upstream stuff i dont want to mess with
755
756 # /usr/share/doc/exim4-base/README.Debian.gz:
757 # SpamAssassin's default report should not be used in a add_header
758 # statement since it contains empty lines. (This triggers e.g. Amavis'
759 # warning "BAD HEADER SECTION, Improper folded header field made up
760 # entirely of whitespace".) This is a safe, terse alternative:
761 clear_report_template
762 report (_SCORE_ / _REQD_ requ) _TESTSSCORES(,)_ autolearn=_AUTOLEARN
763 uridnsbl_skip_domain iankelling.org
764 uridnsbl_skip_domain amnimal.ninja
765 uridnsbl_skip_domain expertpathologyreview.com
766 uridnsbl_skip_domain zroe.org
767 EOF
768
769 # 2020-10-19 remove old file. remove this when all hosts updated
770 rm -fv /etc/systemd/system/spamddnsfix.{timer,service}
771
772 i /etc/default/spamassassin <<'EOF'
773 # defaults plus debugging flags for an issue im having
774 OPTIONS="--create-prefs --max-children 5 --helper-home-dir"
775 PIDFILE="/var/run/spamd.pid"
776 # my additions
777 NICE="--nicelevel 15"
778 CRON=1
779 EOF
780 ##### end spamassassin config
781
782
783 # * Update mail cert
784 if [[ -e /p/c/filesystem ]]; then
785 # note, man openvpn implies we could just call mail-route on vpn startup/shutdown with
786 # systemd, buuut it can remake the tun device unexpectedly, i got this in the log
787 # after my internet was down for a bit:
788 # NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.
789 m /a/exe/vpn-mk-client-cert -b mailclient -n mail li.iankelling.org
790 fi
791 case $HOSTNAME in
792 bk)
793 if [[ ! -e /etc/openvpn/client/mail.conf ]]; then
794 echo "$0: error: first, on a system with /p/c/filesystem, run mail-setup, or the vpn-mk-client-cert line above this err" 2>&2
795 exit 1
796 fi
797 ;;
798 esac
799
800 m rsync -aiSAX --chown=root:root --chmod=g-s /a/bin/ds/mail-cert-cron /usr/local/bin
801
802 i /etc/systemd/system/mailcert.service <<'EOF'
803 [Unit]
804 Description=Mail cert rsync
805 After=multi-user.target
806
807 [Service]
808 Type=oneshot
809 ExecStart=/usr/local/bin/sysd-mail-once mailcert /usr/local/bin/mail-cert-cron
810 EOF
811 i /etc/systemd/system/mailcert.timer <<'EOF'
812 [Unit]
813 Description=Run mail-cert once a day
814
815 [Timer]
816 OnCalendar=daily
817
818 [Install]
819 WantedBy=timers.target
820 EOF
821
822
823 wghost=${HOSTNAME}wg.b8.nz
824 if $bhost_t && [[ ! -e /etc/exim4/certs/$wghost/privkey.pem ]]; then
825 certbot -n --manual-public-ip-logging-ok --eff-email --agree-tos -m letsencrypt@iankelling.org \
826 certonly --manual --preferred-challenges=dns \
827 --manual-auth-hook /a/bin/ds/le-dns-challenge \
828 --manual-cleanup-hook /a/bin/ds/le-dns-challenge-cleanup \
829 --deploy-hook /a/bin/ds/le-exim-deploy -d $wghost
830 fi
831
832 # * fail2ban
833
834 # todo: test that these configs actually work, eg run
835 # s iptables-exim -S
836 # and see someone is banned.
837
838 sed 's/^ *before *= *iptables-common.conf/before = iptables-common-exim.conf/' \
839 /etc/fail2ban/action.d/iptables-multiport.conf| i /etc/fail2ban/action.d/iptables-exim.conf
840 i /etc/fail2ban/action.d/iptables-common-exim.conf <<'EOF'
841 # iank: same as iptables-common, except iptables is iptables-exim, ip6tables is ip6tables-exim
842
843 # Fail2Ban configuration file
844 #
845 # Author: Daniel Black
846 #
847 # This is a included configuration file and includes the definitions for the iptables
848 # used in all iptables based actions by default.
849 #
850 # The user can override the defaults in iptables-common.local
851 #
852 # Modified: Alexander Koeppe <format_c@online.de>, Serg G. Brester <serg.brester@sebres.de>
853 # made config file IPv6 capable (see new section Init?family=inet6)
854
855 [INCLUDES]
856
857 after = iptables-blocktype.local
858 iptables-common.local
859 # iptables-blocktype.local is obsolete
860
861 [Definition]
862
863 # Option: actionflush
864 # Notes.: command executed once to flush IPS, by shutdown (resp. by stop of the jail or this action)
865 # Values: CMD
866 #
867 actionflush = <iptables> -F f2b-<name>
868
869
870 [Init]
871
872 # Option: chain
873 # Notes specifies the iptables chain to which the Fail2Ban rules should be
874 # added
875 # Values: STRING Default: INPUT
876 chain = INPUT
877
878 # Default name of the chain
879 #
880 name = default
881
882 # Option: port
883 # Notes.: specifies port to monitor
884 # Values: [ NUM | STRING ] Default:
885 #
886 port = ssh
887
888 # Option: protocol
889 # Notes.: internally used by config reader for interpolations.
890 # Values: [ tcp | udp | icmp | all ] Default: tcp
891 #
892 protocol = tcp
893
894 # Option: blocktype
895 # Note: This is what the action does with rules. This can be any jump target
896 # as per the iptables man page (section 8). Common values are DROP
897 # REJECT, REJECT --reject-with icmp-port-unreachable
898 # Values: STRING
899 blocktype = REJECT --reject-with icmp-port-unreachable
900
901 # Option: returntype
902 # Note: This is the default rule on "actionstart". This should be RETURN
903 # in all (blocking) actions, except REJECT in allowing actions.
904 # Values: STRING
905 returntype = RETURN
906
907 # Option: lockingopt
908 # Notes.: Option was introduced to iptables to prevent multiple instances from
909 # running concurrently and causing irratic behavior. -w was introduced
910 # in iptables 1.4.20, so might be absent on older systems
911 # See https://github.com/fail2ban/fail2ban/issues/1122
912 # Values: STRING
913 lockingopt = -w
914
915 # Option: iptables
916 # Notes.: Actual command to be executed, including common to all calls options
917 # Values: STRING
918 iptables = /usr/local/bin/iptables-exim <lockingopt>
919
920
921 [Init?family=inet6]
922
923 # Option: blocktype (ipv6)
924 # Note: This is what the action does with rules. This can be any jump target
925 # as per the iptables man page (section 8). Common values are DROP
926 # REJECT, REJECT --reject-with icmp6-port-unreachable
927 # Values: STRING
928 blocktype = REJECT --reject-with icmp6-port-unreachable
929
930 # Option: iptables (ipv6)
931 # Notes.: Actual command to be executed, including common to all calls options
932 # Values: STRING
933 iptables = /usr/local/bin/ip6tables-exim <lockingopt>
934 EOF
935
936 i /etc/fail2ban/jail.d/exim.local <<'EOF'
937 [exim]
938 enabled = true
939 port = 25,587
940 filter = exim
941 banaction = iptables-exim
942 EOF
943 if $ir; then
944 m systemctl restart fail2ban
945 fi
946
947 # * common exim4 config
948
949
950 ## old, not using forward files anymore
951 rm -fv $uhome/.forward /root/.forward
952
953
954 # Make all system users be aliases. preventative
955 # prevents things like cron mail for user without alias
956 awk 'BEGIN { FS = ":" } ; $6 !~ /^\/home/ || $7 ~ /\/nologin$/ { print $1 }' /etc/passwd| while read -r user; do
957 if [[ ! $user ]]; then
958 continue
959 fi
960 if ! grep -q "^$user:" /etc/aliases; then
961 echo "$user: root" |m tee -a /etc/aliases
962 fi
963 done
964
965
966 awk 'BEGIN { FS = ":" } ; $6 ~ /^\/home/ && $7 !~ /\/nologin$/ { print $1 }' /etc/passwd| while read -r user; do
967 case $HOSTNAME in
968 $MAIL_HOST)
969 sed -i "/^user:/d" /etc/aliases
970 ;;
971 *)
972 if ! grep -q "^$user:" /etc/aliases; then
973 echo "$user: root" |m tee -a /etc/aliases
974 fi
975 ;;
976 esac
977 done
978
979 if ! grep -q "^ncsoft:" /etc/aliases; then
980 echo "ncsoft: graceq2323@gmail.com" |m tee -a /etc/aliases
981 fi
982
983
984
985 m gpasswd -a iank adm #needed for reading logs
986
987 ### make local bounces go to normal maildir
988 # local mail that bounces goes to /Maildir or /root/Maildir
989 dirs=(/m/md/bounces/{cur,tmp,new})
990 m mkdir -p ${dirs[@]}
991 m chown iank:iank /m /m/md
992 m ln -sfT /m/md /m/iank
993 m chmod 771 /m /m/md
994 m chown -R $u:Debian-exim /m/md/bounces
995 m chmod 775 ${dirs[@]}
996 m usermod -a -G Debian-exim $u
997 for d in /Maildir /root/Maildir; do
998 if [[ ! -L $d ]]; then
999 m rm -rf $d
1000 fi
1001 m ln -sf -T /m/md/bounces $d
1002 done
1003
1004 # dkim, client passwd file
1005 files=(/p/c/machine_specific/$HOSTNAME/filesystem/etc/exim4/*)
1006 f=/p/c/filesystem/etc/exim4/passwd.client
1007 if [[ -e $f ]]; then
1008 files+=($f)
1009 fi
1010 if (( ${#files[@]} )); then
1011 m rsync -ahhi --chown=root:Debian-exim --chmod=0640 \
1012 ${files[@]} /etc/exim4
1013 fi
1014
1015 # By default, only 10 days of logs are kept. increase that.
1016 # And dont compress, I look back at logs too often and
1017 # dont need the annoyance of decompressing them all the time.
1018 m sed -ri '/^\s*compress\s*$/d;s/^(\s*rotate\s).*/\11000/' /etc/logrotate.d/exim4-base
1019 files=(/var/log/exim4/*.gz)
1020 if (( ${#files[@]} )); then
1021 gunzip ${files[@]}
1022 fi
1023
1024 ## disabled. not using .forward files, but this is still interesting
1025 ## for reference.
1026 # ## https://blog.dhampir.no/content/make-exim4-on-debian-respect-forward-and-etcaliases-when-using-a-smarthost
1027 # # i only need .forwards, so just doing that one.
1028 # cd /etc/exim4/conf.d/router
1029 # b=userforward_higher_priority
1030 # # replace the router name so it is unique
1031 # sed -r s/^\\S+:/$b:/ 600_exim4-config_userforward >175_$b
1032 rm -fv /etc/exim4/conf.d/router/175_userforward_higher_priority
1033
1034 # todo, consider 'separate' in etc/exim4.conf, could it help on busy systems?
1035
1036 # alerts is basically the postmaster address
1037 m sed -i --follow-symlinks -f - /etc/aliases <<EOF
1038 \$a root: alerts@iankelling.org
1039 /^root:/d
1040 EOF
1041
1042 cat >/etc/exim4/conf.d/rewrite/34_iank_rewriting <<'EOF'
1043 ncsoft@zroe.org graceq2323@gmail.com hE
1044 EOF
1045
1046 # old name
1047 rm -fv /etc/exim4/conf.d/retry/37_retry
1048
1049 cat >/etc/exim4/conf.d/retry/17_retry <<'EOF'
1050 # Retry fast for my own domains
1051 iankelling.org * F,1d,10m;F,14d,1h
1052 amnimal.ninja * F,1d,10m;F,14d,1h
1053 expertpathologyreview.com * F,1d,10m;F,14d,1h
1054 je.b8.nz * F,1d,10m;F,14d,1h
1055 zroe.org * F,1d,10m;F,14d,1h
1056 eximbackup.b8.nz * F,1d,4m;F,14d,1h
1057
1058 # The spec says the target domain will be used for temporary host errors,
1059 # but i've found that isn't correct, the hostname is required
1060 # at least sometimes.
1061 nn.b8.nz * F,1d,4m;F,14d,1h
1062 defaultnn.b8.nz * F,1d,4m;F,14d,1h
1063 mx.iankelling.org * F,1d,4m;F,14d,1h
1064 bk.b8.nz * F,1d,4m;F,14d,1h
1065 eggs.gnu.org * F,1d,4m;F,14d,1h
1066 mail.fsf.org * F,1d,15m;F,14d,1h
1067 EOF
1068
1069
1070 rm -vf /etc/exim4/conf.d/main/000_localmacros # old filename
1071
1072 # separate file so without quoted EOF for convenience
1073 cat >/etc/exim4/conf.d/main/000_local2 <<EOF
1074 # normally empty, I set this so I can set the envelope address
1075 # when doing mail redelivery to invoke filters. Also allows
1076 # me exiqgrep and stuff.
1077 MAIN_TRUSTED_GROUPS = $u
1078 EOF
1079
1080 cat >/etc/exim4/conf.d/main/000_local <<'EOF'
1081 MAIN_TLS_ENABLE = true
1082
1083 # require tls connections for all smarthosts
1084 REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS = *
1085
1086 # debian exim config added this in 2016 or so?
1087 # it's part of the smtp spec, to limit lines to 998 chars
1088 # but a fair amount of legit mail does not adhere to it. I don't think
1089 # this should be default, like it says in
1090 # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=828801
1091 # todo: the bug for introducing this was about headers, but
1092 # the fix maybe is for all lines? one says gmail rejects, the
1093 # other says gmail does not reject. figure out and open a new bug.
1094 IGNORE_SMTP_LINE_LENGTH_LIMIT = true
1095
1096 # more verbose logs
1097 MAIN_LOG_SELECTOR = +all
1098
1099 # Based on spec, seems like a good idea to be nice.
1100 smtp_return_error_details = true
1101
1102 # default is 10. when exim has been down for a bit, fsf mailserver
1103 # will do a big send in one connection, then exim decides to put
1104 # the messages in the queue instead of delivering them, to avoid
1105 # spawning too many delivery processes. This is the same as the
1106 # fsfs value. And the corresponding one for how many messages
1107 # to send out in 1 connection remote_max_parallel = 256
1108 smtp_accept_queue_per_connection = 500
1109
1110
1111 DKIM_CANON = relaxed
1112 DKIM_SELECTOR = li
1113
1114 # from comments in
1115 # https://debian-administration.org/article/718/DKIM-signing_outgoing_mail_with_exim4
1116 # and its best for this to align https://tools.ietf.org/html/rfc7489#page-8
1117 # There could be some circumstance when the
1118 # from: isnt our domain, but the envelope sender is
1119 # and so still want to sign, but I cant think of any case.
1120 DKIM_DOMAIN = ${lc:${domain:$rh_from:}}
1121 # The file is based on the outgoing domain-name in the from-header.
1122 # sign if key exists
1123 DKIM_PRIVATE_KEY = ${if exists{/etc/exim4/${dkim_domain}-private.pem} {/etc/exim4/${dkim_domain}-private.pem}}
1124
1125 # most of the ones that gmail seems to use.
1126 # Exim has horrible default of signing unincluded
1127 # list- headers since they got mentioned in an
1128 # rfc, but this messes up mailing lists, like gnu/debian which want to
1129 # keep your dkim signature intact but add list- headers.
1130 DKIM_SIGN_HEADERS = mime-version:in-reply-to:references:from:date:subject:to
1131
1132 domainlist local_hostnames = ! je.b8.nz : ! bk.b8.nz : *.b8.nz : b8.nz
1133
1134 hostlist iank_trusted = <; \\
1135 # veth0
1136 10.173.8.1 ; \\
1137 # li li_ip6
1138 72.14.176.105 ; 2600:3c00::f03c:91ff:fe6d:baf8 ; \\
1139 # li_vpn_net li_vpn_net_ip6s
1140 10.8.0.0/24; 2600:3c00:e000:280::/64 ; 2600:3c00:e002:3800::/56 ; \\
1141 # bk bk_ip6
1142 85.119.83.50 ; 2001:ba8:1f1:f0c9::2 ; \\
1143 # je je_ipv6
1144 85.119.82.128 ; 2001:ba8:1f1:f09d::2 ; \\
1145 # fsf_mit_net fsf_mit_net_ip6 fsf_net fsf_net_ip6 fsf_office_net
1146 18.4.89.0/24 ; 2603:3005:71a:2e00::/64 ; 209.51.188.0/24 ; 2001:470:142::/48 ; 74.94.156.208/28
1147
1148
1149 # this is the default delay_warning_condition, plus matching on local_domains.
1150 # If I have some problem with my local system that causes delayed delivery,
1151 # I dont want to send warnings out to non-local domains.
1152 delay_warning_condition = ${if or {\
1153 { !eq{$h_list-id:$h_list-post:$h_list-subscribe:}{} }\
1154 { match{$h_precedence:}{(?i)bulk|list|junk} }\
1155 { match{$h_auto-submitted:}{(?i)auto-generated|auto-replied} }\
1156 { match_domain{$domain}{+local_domains} }\
1157 } {no}{yes}}
1158
1159
1160 EOF
1161
1162 rm -fv /etc/exim4/rcpt_local_acl # old path
1163
1164 i /etc/exim4/conf.d/local_deny_exceptions_acl <<'EOF'
1165 # This acl already exists in rcpt, this just makes it more widespread.
1166 # See the comment there for its rationale. The reason it needs to be
1167 # more widespread is that I've turned on sender verification, but cron
1168 # emails can fail sender verification since I may be in a network that
1169 # doesn't have my local dns.
1170 accept
1171 authenticated = *
1172
1173 # i setup a local programs smtp to mail.iankelling.org, this
1174 # skips sender verification for it.
1175 accept
1176 hosts = 10.173.8.1
1177 EOF
1178
1179 rm -fv /etc/exim4/data_local_acl # old path
1180 i /etc/exim4/conf.d/data_local_acl <<'EOF'
1181 # Except for the "condition =", this was
1182 # a comment in the check_data acl. The comment about this not
1183 # being suitable has been changed in newer exim versions. The only thing
1184 # related I found was to
1185 # add the condition =, cuz spamassassin has problems with big
1186 # messages and spammers don't bother with big messages,
1187 # but I've increased the size from 10k
1188 # suggested in official docs, and 100k in the wiki example because
1189 # those docs are rather old and I see a 110k spam message
1190 # pretty quickly looking through my spam folder.
1191
1192 warn
1193 !hosts = +iank_trusted
1194 remove_header = X-Spam_score: X-Spam_score_int : X-Spam_bar : X-Spam_report
1195
1196 warn
1197 !hosts = +iank_trusted
1198 condition = ${if < {$message_size}{5000K}}
1199 spam = Debian-exim:true
1200 add_header = X-Spam_score_int: $spam_score_int
1201 add_header = X-Spam_score: $spam_score
1202 add_header = X-Spam_bar: $spam_bar
1203 add_header = X-Spam_report: $spam_report
1204 add_header = X-Spam_action: $spam_action
1205
1206 warn
1207 condition = ${if def:malware_name}
1208 remove_header = Subject:
1209 add_header = Subject: [Clamav warning: $malware_name] $h_subject
1210 log_message = heuristic malware warning: $malware_name
1211
1212 #accept
1213 # spf = pass:fail:softfail:none:neutral:permerror:temperror
1214 # dmarc_status = reject:quarantine
1215 # add_header = Reply-to: dmarctest@iankelling.org
1216
1217 EOF
1218
1219 i /etc/exim4/conf.d/router/900_exim4-config_local_user <<'EOF'
1220 ### router/900_exim4-config_local_user
1221 #################################
1222
1223 # This router matches local user mailboxes. If the router fails, the error
1224 # message is "Unknown user".
1225 local_user:
1226 debug_print = "R: local_user for $local_part@$domain"
1227 driver = accept
1228 domains = +local_domains
1229 # ian: default file except where mentioned.
1230 # ian: commented this. I get all local parts. for bk, an rcpt
1231 # check handles checking with dovecot, and the only router
1232 # after this is root.
1233 # local_parts = ! root
1234 transport = LOCAL_DELIVERY
1235 cannot_route_message = Unknown user
1236 # ian: added for + addressing.
1237 local_part_suffix = +*
1238 local_part_suffix_optional
1239 EOF
1240 i /etc/exim4/conf.d/transport/30_exim4-config_dovecot_lmtp <<'EOF'
1241 dovecot_lmtp:
1242 driver = lmtp
1243 socket = /var/run/dovecot/lmtp
1244 #maximum number of deliveries per batch, default 1
1245 batch_max = 200
1246 envelope_to_add
1247 EOF
1248
1249 i /etc/exim4/conf.d/transport/30_remote_smtp_vpn <<'EOF'
1250 # same as debians 30_exim4-config_remote_smtp, but
1251 # with interface added at the end.
1252
1253 remote_smtp_vpn:
1254 debug_print = "T: remote_smtp_vpn for $local_part@$domain"
1255 driver = smtp
1256 .ifndef IGNORE_SMTP_LINE_LENGTH_LIMIT
1257 message_size_limit = ${if > {$max_received_linelength}{998} {1}{0}}
1258 .endif
1259 .ifdef REMOTE_SMTP_HOSTS_AVOID_TLS
1260 hosts_avoid_tls = REMOTE_SMTP_HOSTS_AVOID_TLS
1261 .endif
1262 .ifdef REMOTE_SMTP_HEADERS_REWRITE
1263 headers_rewrite = REMOTE_SMTP_HEADERS_REWRITE
1264 .endif
1265 .ifdef REMOTE_SMTP_RETURN_PATH
1266 return_path = REMOTE_SMTP_RETURN_PATH
1267 .endif
1268 .ifdef REMOTE_SMTP_HELO_DATA
1269 helo_data=REMOTE_SMTP_HELO_DATA
1270 .endif
1271 .ifdef DKIM_DOMAIN
1272 dkim_domain = DKIM_DOMAIN
1273 .endif
1274 .ifdef DKIM_SELECTOR
1275 dkim_selector = DKIM_SELECTOR
1276 .endif
1277 .ifdef DKIM_PRIVATE_KEY
1278 dkim_private_key = DKIM_PRIVATE_KEY
1279 .endif
1280 .ifdef DKIM_CANON
1281 dkim_canon = DKIM_CANON
1282 .endif
1283 .ifdef DKIM_STRICT
1284 dkim_strict = DKIM_STRICT
1285 .endif
1286 .ifdef DKIM_SIGN_HEADERS
1287 dkim_sign_headers = DKIM_SIGN_HEADERS
1288 .endif
1289 .ifdef TLS_DH_MIN_BITS
1290 tls_dh_min_bits = TLS_DH_MIN_BITS
1291 .endif
1292 .ifdef REMOTE_SMTP_TLS_CERTIFICATE
1293 tls_certificate = REMOTE_SMTP_TLS_CERTIFICATE
1294 .endif
1295 .ifdef REMOTE_SMTP_PRIVATEKEY
1296 tls_privatekey = REMOTE_SMTP_PRIVATEKEY
1297 .endif
1298 .ifdef REMOTE_SMTP_HOSTS_REQUIRE_TLS
1299 hosts_require_tls = REMOTE_SMTP_HOSTS_REQUIRE_TLS
1300 .endif
1301 .ifdef REMOTE_SMTP_TRANSPORTS_HEADERS_REMOVE
1302 headers_remove = REMOTE_SMTP_TRANSPORTS_HEADERS_REMOVE
1303 .endif
1304 interface = <; 10.8.0.4 ; 2600:3c00:e002:3800::4
1305 EOF
1306
1307 i /etc/exim4/conf.d/transport/30_smarthost_dkim <<'EOF'
1308 # ian: this is remote_smtp_smarthost plus the dkim parts from remote_smtp
1309
1310 smarthost_dkim:
1311 debug_print = "T: remote_smtp_smarthost for $local_part@$domain"
1312 driver = smtp
1313 multi_domain
1314 .ifndef IGNORE_SMTP_LINE_LENGTH_LIMIT
1315 message_size_limit = ${if > {$max_received_linelength}{998} {1}{0}}
1316 .endif
1317 hosts_try_auth = <; ${if exists{CONFDIR/passwd.client} \
1318 {\
1319 ${lookup{$host}nwildlsearch{CONFDIR/passwd.client}{$host_address}}\
1320 }\
1321 {} \
1322 }
1323 .ifdef REMOTE_SMTP_SMARTHOST_HOSTS_AVOID_TLS
1324 hosts_avoid_tls = REMOTE_SMTP_SMARTHOST_HOSTS_AVOID_TLS
1325 .endif
1326 .ifdef REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS
1327 hosts_require_tls = REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS
1328 .endif
1329 .ifdef REMOTE_SMTP_SMARTHOST_TLS_VERIFY_CERTIFICATES
1330 tls_verify_certificates = REMOTE_SMTP_SMARTHOST_TLS_VERIFY_CERTIFICATES
1331 .endif
1332 .ifdef REMOTE_SMTP_SMARTHOST_TLS_VERIFY_HOSTS
1333 tls_verify_hosts = REMOTE_SMTP_SMARTHOST_TLS_VERIFY_HOST
1334 .endif
1335 .ifdef REMOTE_SMTP_HEADERS_REWRITE
1336 headers_rewrite = REMOTE_SMTP_HEADERS_REWRITE
1337 .endif
1338 .ifdef REMOTE_SMTP_RETURN_PATH
1339 return_path = REMOTE_SMTP_RETURN_PATH
1340 .endif
1341 .ifdef REMOTE_SMTP_HELO_DATA
1342 helo_data=REMOTE_SMTP_HELO_DATA
1343 .endif
1344 .ifdef TLS_DH_MIN_BITS
1345 tls_dh_min_bits = TLS_DH_MIN_BITS
1346 .endif
1347 .ifdef REMOTE_SMTP_SMARTHOST_TLS_CERTIFICATE
1348 tls_certificate = REMOTE_SMTP_SMARTHOST_TLS_CERTIFICATE
1349 .endif
1350 .ifdef REMOTE_SMTP_SMARTHOST_PRIVATEKEY
1351 tls_privatekey = REMOTE_SMTP_SMARTHOST_PRIVATEKEY
1352 .endif
1353 .ifdef REMOTE_SMTP_TRANSPORTS_HEADERS_REMOVE
1354 headers_remove = REMOTE_SMTP_TRANSPORTS_HEADERS_REMOVE
1355 .endif
1356 .ifdef DKIM_DOMAIN
1357 dkim_domain = DKIM_DOMAIN
1358 .endif
1359 .ifdef DKIM_SELECTOR
1360 dkim_selector = DKIM_SELECTOR
1361 .endif
1362 .ifdef DKIM_PRIVATE_KEY
1363 dkim_private_key = DKIM_PRIVATE_KEY
1364 .endif
1365 .ifdef DKIM_CANON
1366 dkim_canon = DKIM_CANON
1367 .endif
1368 .ifdef DKIM_STRICT
1369 dkim_strict = DKIM_STRICT
1370 .endif
1371 .ifdef DKIM_SIGN_HEADERS
1372 dkim_sign_headers = DKIM_SIGN_HEADERS
1373 .endif
1374 EOF
1375
1376
1377 cat >/etc/exim4/update-exim4.conf.conf <<'EOF'
1378 # default stuff, i havent checked if its needed
1379 dc_minimaldns='false'
1380 dc_relay_nets=''
1381 CFILEMODE='644'
1382 dc_use_split_config='true'
1383 dc_mailname_in_oh='true'
1384 EOF
1385
1386
1387 # * radicale
1388 if mailhost; then
1389 if ! mountpoint /o; then
1390 echo "error /o is not a mountpoint" >&2
1391 exit 1
1392 fi
1393
1394 # davx/davdroid setup instructions at the bottom
1395
1396 # main docs:
1397 # http://radicale.org/user_documentation/
1398 # https://davdroid.bitfire.at/configuration/
1399
1400 # note on debugging: if radicale can't bind to the address,
1401 # in the log it just says "Starting Radicale". If you run
1402 # it in the foreground, it will give more info. Background
1403 # plus debug does not help.
1404 # sudo -u radicale radicale -D -f
1405
1406 # created password file with:
1407 # htpasswd -c /p/c/machine_specific/li/filesystem/etc/caldav-htpasswd
1408 # chmod 640 /p/c/machine_specific/li/filesystem/etc/caldav-htpasswd
1409 # # setup chgrp www-data in ./conflink
1410
1411 pi-nostart radicale
1412
1413 i /etc/systemd/system/radicale.service.d/override.conf <<EOF
1414 [Unit]
1415 # this unit is configured to start and stop whenever
1416 # $vpnser does
1417
1418 After=network.target network-online.target mailnn.service $vpnser
1419 BindsTo=$vpnser
1420
1421 Wants=network-online.target
1422 JoinsNamespaceOf=mailnn.service
1423 StartLimitIntervalSec=0
1424
1425 [Service]
1426 PrivateNetwork=true
1427 BindPaths=$bindpaths
1428 Restart=always
1429 # time to sleep before restarting a service
1430 RestartSec=20
1431
1432 [Install]
1433 # for openvpn
1434 RequiredBy=$vpnser
1435 EOF
1436
1437
1438 # use persistent uid/gid
1439 IFS=:; read -r _ _ uid _ < <(getent passwd radicale ); unset IFS
1440 IFS=:; read -r _ _ gid _ < <(getent group radicale ); unset IFS
1441 if [[ $uid != 609 ]]; then
1442 m systemctl stop radicale ||:
1443 m usermod -u 609 radicale
1444 m groupmod -g 609 radicale
1445 m usermod -g 609 radicale
1446 fi
1447 m find /o/radicale -xdev -exec chown -h 609 {} +
1448 m find /o/radicale -xdev -exec chgrp -h 609 {} +
1449
1450
1451 # I moved /var/lib/radicale after it's initialization.
1452 # I did a sudo -u radicale git init in the collections subfolder
1453 # after it gets created, per the git docs.
1454 m /a/exe/lnf -T /o/radicale /var/lib/radicale
1455
1456 # from https://www.williamjbowman.com/blog/2015/07/24/setting-up-webdav-caldav-and-carddav-servers/
1457
1458 # more config is for li in distro-end
1459
1460 # coment in this file says this is needed for it to run on startup
1461 sed -ri 's/^\s*#+\s*(ENABLE_RADICALE\s*=\s*yes\s*)/\1/' /etc/default/radicale
1462
1463 # comments say default is 0.0.0.0:5232
1464 m setini hosts 10.8.0.4:5232 server
1465 # https://radicale.org/2.1.html
1466 m setini type http_x_remote_user auth
1467
1468
1469 # disable power management feature, set to 240 min sync interval,
1470 # so it shouldn't be bad.
1471
1472 # davdroid from f-druid.
1473 # login with url and user name
1474 # url https://cal.iankelling.org/ian
1475 # username ian
1476 # pass, see password manager for radicale
1477 #
1478 # add account dialog:
1479 #
1480 # set account name as ian@iankelling.org, per help text below the
1481 # field.
1482 #
1483 # switch to groups are per-contact categories,
1484 # per https://davdroid.bitfire.at/configuration/radicale/
1485 #
1486 #
1487 # After setting up account, I added one address book, named
1488 # ianaddr. calender was already created, named ian. checked boxes under
1489 # both. synced.
1490 #
1491 # To restore from old phone to new phone, I wiped all data out, then copied over the newly created files. I think
1492 #
1493 # ignorable background info:
1494 #
1495 # opentasks uses the calendar file.
1496 #
1497 # The address book I created got a uuid as a name for the file. Note
1498 # the .props file says if it's a calendar or addressbook.
1499 #
1500 # When debugging, tailed /var/log/radicale/radicale.log and apache log,
1501 # both show the requests happening. Without creating the address book,
1502 # after creating a contact, a sync would delete it.
1503 #
1504 # Address books correspond to .props files in the radicale dir.
1505 #
1506 # Some background is here,
1507 # https://davdroid.bitfire.at/faq/entry/cant-manage-groups-on-device/
1508 # which shows separate vcard option is from rfc 6350, the other is 2426,
1509 # radicale page says it implements the former not the latter,
1510 # which conflicts with the documentation of which to select, but whatever.
1511 # http://radicale.org/technical_choices/
1512 # https://davdroid.bitfire.at/faq/entry/cant-manage-groups-on-device/
1513 #
1514 # Note, url above says only cayanogenmod 13+ and omnirom can manage groups.
1515
1516 # Note, radicale had built-in git support to track changes, but they
1517 # removed it in 2.0.
1518
1519 fi
1520
1521 # * dovecot
1522
1523 # ** $MAIL_HOST|bk|je)
1524 case $HOSTNAME in
1525 $MAIL_HOST|bk|je)
1526 # based on a little google and package search, just the dovecot
1527 # packages we need instead of dovecot-common.
1528 #
1529 # dovecot-lmtpd is for exim to deliver to dovecot instead of maildir
1530 # directly. The reason to do this is to use dovecot\'s sieve, which
1531 # can generally do more than exims filters (a few things less) and
1532 # sieve has the benefit of being supported in postfix and
1533 # proprietary/weird environments, so there is more examples on the
1534 # internet.
1535 pi-nostart dovecot-core dovecot-imapd dovecot-sieve dovecot-lmtpd dovecot-sqlite sqlite3
1536
1537 for f in /p/c{/machine_specific/$HOSTNAME,}/filesystem/etc/dovecot/users; do
1538 if [[ -e $f ]]; then
1539 m rsync -ahhi --chown=root:dovecot --chmod=0640 $f /etc/dovecot/
1540 break
1541 fi
1542 done
1543 for f in /p/c/subdir_files/sieve/*sieve /a/bin/ds/subdir_files/sieve/*sieve; do
1544 m sudo -u $u /a/exe/lnf -v -T $f $uhome/sieve/${f##*/}
1545 done
1546
1547 # https://wiki.dovecot.org/SSL/DovecotConfiguration
1548 i /etc/dovecot/dhparam <<'EOF'
1549 -----BEGIN DH PARAMETERS-----
1550 MIIBCAKCAQEAoleil6SBxGqQKk7j0y2vV3Oklv6XupZKn7PkPv485QuFeFagifeS
1551 A+Jz6Wquqk5zhGyCu63Hp4wzGs4TyQqoLjkaWL6Ra/Bw3g3ofPEzMGEsV1Qdqde4
1552 jorwiwtr2i9E6TXQp0noT/7VFeHulIkayTeW8JulINdMHs+oLylv16McGCIrxbkM
1553 8D1PuO0TP/CNDs2QbRvJ1RjY3CeGpxMhrSHVgBCUMwnA2cvz3bYjI7UMYMMDPNrE
1554 PLrwsYzXGGCdJsO2vsmmqqgLsZiapYJlUNjfiyWLt7E2H6WzkNB3VIhIPfLqFDPK
1555 xioE3sYKdjOt+p6mlg3l8+OLtODEFPHDqwIBAg==
1556 -----END DH PARAMETERS-----
1557 EOF
1558 {
1559 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
1560 cat <<'EOF'
1561 ssl_cert = </etc/exim4/fullchain.pem
1562 ssl_key = </etc/exim4/privkey.pem
1563 EOF
1564 else
1565 cat <<'EOF'
1566 ssl_cert = </etc/exim4/exim.crt
1567 ssl_key = </etc/exim4/exim.key
1568 EOF
1569 fi
1570 cat <<'EOF'
1571 # https://ssl-config.mozilla.org
1572 ssl = required
1573 # this is the same as the certbot list, in my cert cronjob, I check if that has changed upstream.
1574 ssl_cipher_list = ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
1575 ssl_protocols = TLSv1.2
1576 ssl_prefer_server_ciphers = no
1577
1578 protocol lmtp {
1579 #per https://wiki2.dovecot.org/Pigeonhole/Sieve/Configuration
1580 # default is just $mail_plugins
1581 mail_plugins = $mail_plugins sieve
1582 }
1583 EOF
1584 if dpkg --compare-versions $(dpkg-query -f='${Version}\n' --show dovecot-core) ge 1:2.3; then
1585 cat <<EOF
1586 ssl_dh = </etc/dovecot/dhparam
1587 EOF
1588 fi
1589 } >/etc/dovecot/local.conf
1590
1591 ;;&
1592
1593 # ** $MAIL_HOST)
1594 $MAIL_HOST)
1595 # If we changed 90-sieve.conf and removed the active part of the
1596 # sieve option, we wouldn\'t need this, but I\'d rather not modify a
1597 # default config if not needed. This won\'t work as a symlink in /a/c
1598 # unfortunately.
1599 m sudo -u $u /a/exe/lnf -T sieve/main.sieve $uhome/.dovecot.sieve
1600
1601 if [[ ! -e $uhome/sieve/personal.sieve ]]; then
1602 m touch $uhome/sieve/personal{,end}{,test}.sieve
1603 fi
1604
1605 rm -fv /etc/dovecot/conf.d/20-lmtp.conf # file from prev version
1606 cat >>/etc/dovecot/local.conf <<EOF
1607 # simple password file based login
1608 !include conf.d/auth-passwdfile.conf.ext
1609
1610 # ian: %u is used for alerts user vs iank
1611 mail_location = maildir:/m/%u:LAYOUT=fs:INBOX=/m/%u/INBOX
1612 mail_uid = $u
1613 mail_gid = $u
1614
1615 protocol lmtp {
1616 # For a normal setup with exim, we need something like this, which
1617 # removes the domain part
1618 # auth_username_format = %Ln
1619 #
1620 # or else # Exim says something like
1621 # "LMTP error after RCPT ... 550 ... User doesn't exist someuser@somedomain"
1622 # Dovecot verbose log says something like
1623 # "auth-worker(9048): passwd(someuser@somedomain): unknown user"
1624 # reference: http://wiki.dovecot.org/LMTP/Exim
1625 #
1626 # However, I use this to direct all mail to the same inbox.
1627 # A normal way to do this, which I did at first is to have
1628 # a router in exim almost at the end, eg 950,
1629 #local_catchall:
1630 # debug_print = "R: catchall for \$local_part@\$domain"
1631 # driver = redirect
1632 # domains = +local_domains
1633 # data = $u
1634 # based on
1635 # http://blog.alteholz.eu/2015/04/exim4-and-catchall-email-address/
1636 # with superflous options removed.
1637 # However, this causes the envelope to be rewritten,
1638 # which makes filtering into mailboxes a little less robust or more complicated,
1639 # so I've done it this way instead. it also requires
1640 # modifying the local router in exim.
1641 auth_username_format = $u
1642 }
1643 EOF
1644 ;;&
1645 # ** bk|je)
1646 bk|je)
1647 chown -R mail.mail /m/md
1648
1649 f=/etc/dovecot/conf.d/10-auth.conf
1650 if [[ -e $f ]]; then
1651 mv $f $f-iank-disabled
1652 fi
1653
1654 cat >>/etc/dovecot/local.conf <<EOF
1655 !include /etc/dovecot/local.conf.ext
1656
1657 # for debugging info, uncomment these.
1658 # logs go to syslog and to /var/log/mail.log
1659 #auth_verbose=yes
1660 #mail_debug=yes
1661
1662
1663 protocol lmtp {
1664 # This downcases the localpart. default is case sensitive.
1665 # case sensitive local part will miss out on valid email when some person or system
1666 # mistakenly capitalizes things.
1667 auth_username_format = %Lu
1668 }
1669
1670 # make 147 only listen on localhost, plan to use for nextcloud.
1671 # copied from mailinabox
1672 service imap-login {
1673 inet_listener imap {
1674 address = 127.0.0.1
1675 }
1676 }
1677 # https://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_dovecot_authenticator.html
1678 service auth {
1679 unix_listener auth-client {
1680 user = Debian-exim
1681 group = Debian-exim
1682 }
1683 }
1684
1685
1686 plugin {
1687 sieve_before = /etc/dovecot/sieve-spam.sieve
1688 # from mailinabox
1689 sieve = /m/sieve/%d/%n.sieve
1690 sieve_dir = /m/sieve/%d/%n
1691 }
1692
1693
1694 # all taken from mailinabox.
1695 mail_location = maildir:/m/md/%d/%n
1696 # meh, ok.
1697 mail_privileged_group = mail
1698 # By default Dovecot allows users to log in only with UID numbers 500 and above. mail is 8
1699 first_valid_uid = 1
1700
1701 # todo: test these changes in the universal config
1702 # mailboxes taken from mailinabox but removed
1703 # settings duplicate to defaults
1704 namespace inbox {
1705 mailbox INBOX {
1706 auto = subscribe
1707 }
1708 mailbox Spam {
1709 special_use = \Junk
1710 auto = subscribe
1711 }
1712 mailbox Drafts {
1713 auto = subscribe
1714 }
1715 mailbox Sent {
1716 auto = subscribe
1717 }
1718 mailbox Trash {
1719 auto = subscribe
1720 }
1721 mailbox Archive {
1722 special_use = \Archive
1723 auto = subscribe
1724 }
1725 }
1726 auth_mechanisms = plain login
1727 EOF
1728
1729 i /etc/dovecot/sieve-spam.sieve <<'EOF'
1730 require ["regex", "fileinto", "imap4flags"];
1731
1732 if allof (header :regex "X-Spam-Status" "^Yes") {
1733 fileinto "Spam";
1734 stop;
1735 }
1736 EOF
1737
1738 i /etc/dovecot/local.conf.ext <<'EOF'
1739 passdb {
1740 driver = sql
1741 args = /etc/dovecot/dovecot-sql.conf.ext
1742 }
1743 userdb {
1744 driver = sql
1745 args = /etc/dovecot/dovecot-sql.conf.ext
1746 }
1747
1748 EOF
1749
1750 i /etc/dovecot/dovecot-sql.conf.ext <<'EOF'
1751 # from mailinabox
1752 driver = sqlite
1753 connect = /m/rc/users.sqlite
1754 default_pass_scheme = SHA512-CRYPT
1755 password_query = SELECT email as user, password FROM users WHERE email='%u';
1756 user_query = SELECT email AS user, "mail" as uid, "mail" as gid, "/m/md/%d/%n" as home FROM users WHERE email='%u';
1757 iterate_query = SELECT email AS user FROM users;
1758 EOF
1759 m chmod 0600 /etc/dovecot/dovecot-sql.conf.ext # per Dovecot instructions
1760
1761 # db needs to be in a www-data writable directory
1762 db=/m/rc/users.sqlite
1763 if [[ ! -s $db ]]; then
1764 m mkdir -p /m/rc
1765 m sqlite3 $db <<'EOF'
1766 CREATE TABLE users (
1767 id INTEGER PRIMARY KEY AUTOINCREMENT,
1768 email TEXT NOT NULL UNIQUE,
1769 password TEXT NOT NULL,
1770 extra,
1771 privileges TEXT NOT NULL DEFAULT '');
1772 EOF
1773 fi
1774 # example of adding a user:
1775 # hash: doveadm pw -s SHA512-CRYPT -p passhere
1776 # sqlite3 /m/rc/users.sqlite <<'EOF'
1777 #insert into users (email, password) values ('testignore@bk.b8.nz', 'hash');
1778 #EOF
1779 # update users set password = 'hash' where email = 'testignore@bk.b8.nz';
1780
1781 # this should be at the end since it requires a valid dovecot config
1782 m sievec /etc/dovecot/sieve-spam.sieve
1783 ;;&
1784 # ** bk)
1785 bk)
1786 # roundcube uses this
1787 mkdir -p /m/sieve
1788 chown mail.mail /m/sieve
1789 m pi dovecot-managesieved
1790 ;;
1791 esac
1792
1793 # * thunderbird autoconfig setup
1794
1795 bkdomains=(expertpathologyreview.com amnimal.ninja)
1796 if [[ $HOSTNAME == bk ]]; then
1797 for domain in ${bkdomains[@]}; do
1798 m /a/exe/web-conf apache2 autoconfig.$domain
1799 dir=/var/www/autoconfig.$domain/html/mail
1800 m mkdir -p $dir
1801 # taken from mailinabox
1802 i $dir/config-v1.1.xml <<EOF
1803 <?xml version="1.0" encoding="UTF-8"?>
1804 <clientConfig version="1.1">
1805 <emailProvider id="$domain">
1806 <domain>$domain</domain>
1807
1808 <displayName>$domain Mail</displayName>
1809 <displayShortName>$domain</displayShortName>
1810
1811 <incomingServer type="imap">
1812 <hostname>mail2.iankelling.org</hostname>
1813 <port>993</port>
1814 <socketType>SSL</socketType>
1815 <username>%EMAILADDRESS%</username>
1816 <authentication>password-cleartext</authentication>
1817 </incomingServer>
1818
1819 <outgoingServer type="smtp">
1820 <hostname>mail2.iankelling.org</hostname>
1821 <port>587</port>
1822 <socketType>STARTTLS</socketType>
1823 <username>%EMAILADDRESS%</username>
1824 <authentication>password-cleartext</authentication>
1825 <addThisServer>true</addThisServer>
1826 <useGlobalPreferredServer>false</useGlobalPreferredServer>
1827 </outgoingServer>
1828
1829 <documentation url="https://$domain/">
1830 <descr lang="en">$domain website.</descr>
1831 </documentation>
1832 </emailProvider>
1833
1834 <webMail>
1835 <loginPage url="https://$domain/roundcube" />
1836 <loginPageInfo url="https://$domain/roundcube" >
1837 <username>%EMAILADDRESS%</username>
1838 <usernameField id="rcmloginuser" name="_user" />
1839 <passwordField id="rcmloginpwd" name="_pass" />
1840 <loginButton id="rcmloginsubmit" />
1841 </loginPageInfo>
1842 </webMail>
1843 <clientConfigUpdate url="https://autoconfig.$domain/mail/config-v1.1.xml" />
1844 </clientConfig>
1845 EOF
1846 done
1847 fi
1848
1849 # * roundcube setup
1850
1851 if [[ $HOSTNAME == bk ]]; then
1852
1853 # zip according to /installer
1854 # which requires adding a line to /usr/local/lib/roundcubemail/config/config.inc.php
1855 # $config['enable_installer'] = true;
1856 pi roundcube roundcube-sqlite3 php-zip apache2 php-fpm
1857
1858 ### begin composer install
1859 # https://getcomposer.org/doc/faqs/how-to-install-composer-programmatically.md
1860 # cd $(mktemp -d)
1861 # sum="$(wget -q -O - https://composer.github.io/installer.sig)"
1862 # m php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
1863 # if [[ $sum != $(php -r "echo hash_file('sha384', 'composer-setup.php');") ]]; then
1864 # echo 'ERROR: Invalid composer installer checksum' >&2
1865 # rm -fv composer-setup.php
1866 # exit 1
1867 # fi
1868 # m php composer-setup.php --quiet
1869 # rm -fv composer-setup.php
1870 # m mv composer.phar /usr/local/bin
1871
1872 # the above method gets composer2, carddav plugin at least doesnt work with that
1873 # yet, it was just released 10-24-2020.
1874 m cd /usr/local/bin
1875 m wget -nv -N https://getcomposer.org/composer-1.phar
1876 chmod +x composer-1.phar
1877 ### end composer install
1878
1879 rcdirs=(/usr/local/lib/rcexpertpath /usr/local/lib/rcninja)
1880 ncdirs=(/var/www/ncninja)
1881 ncdirs=(/var/www/ncexpertpath /var/www/ncninja)
1882 # point debian cronjob to our local install, preventing daily cron error
1883
1884 # debian's cronjob will fail, remove both paths it uses just to be sure
1885 rm -fv /usr/share/roundcube/bin/cleandb.sh /etc/cron.d/roundcube-core
1886
1887 #### begin dl roundcube
1888 # note, im r2e subbed to https://github.com/roundcube/roundcubemail/releases.atom
1889 v=1.4.13; f=roundcubemail-$v-complete.tar.gz
1890 cd /a/opt
1891 if [[ -e $f ]]; then
1892 timestamp=$(stat -c %Y $f)
1893 else
1894 timestamp=0
1895 fi
1896 m wget -nv -N https://github.com/roundcube/roundcubemail/releases/download/$v/$f
1897 new_timestamp=$(stat -c %Y $f)
1898 for rcdir in ${rcdirs[@]}; do
1899 if [[ $timestamp != "$new_timestamp" || ! -e "$rcdir/config/secret" ]]; then
1900 m tar -C /usr/local/lib --no-same-owner -zxf $f
1901 m rm -rf $rcdir
1902 m mv /usr/local/lib/roundcubemail-$v $rcdir
1903 fi
1904 done
1905 #### end dl roundcube
1906
1907 for ((i=0; i < ${#bkdomains[@]}; i++)); do
1908 domain=${bkdomains[i]}
1909 rcdir=${rcdirs[i]}
1910 rcbase=${rcdir##*/}
1911 ncdir=${ncdirs[i]}
1912
1913 # copied from debians cronjob
1914 i /etc/cron.d/$rcbase <<EOF
1915 # Roundcube database cleaning: finally removes all records that are
1916 # marked as deleted.
1917 0 5 * * * www-data $rcdir/bin/cleandb.sh >/dev/null
1918 EOF
1919
1920 m /a/exe/web-conf - apache2 $domain <<EOF
1921 Alias /roundcube $rcdir
1922 ### begin roundcube settings
1923 # taken from /etc/apache2/conf-available/roundcube.conf version 1.4.8+dfsg.1-1~bpo10+1
1924 <Directory $rcdir/>
1925 Options +FollowSymLinks
1926 # This is needed to parse $rcdir/.htaccess.
1927 AllowOverride All
1928 Require all granted
1929 </Directory>
1930 # Protecting basic directories:
1931 <Directory $rcdir/config>
1932 Options -FollowSymLinks
1933 AllowOverride None
1934 </Directory>
1935 ### end roundcube settings
1936
1937
1938 ### begin nextcloud settings
1939 Alias /nextcloud "$ncdir/"
1940 <Directory $ncdir/>
1941 Require all granted
1942 AllowOverride All
1943 Options FollowSymLinks MultiViews
1944
1945 <IfModule mod_dav.c>
1946 Dav off
1947 </IfModule>
1948
1949 </Directory>
1950
1951 # based on install checker, links to
1952 # https://docs.nextcloud.com/server/19/admin_manual/issues/general_troubleshooting.html#service-discovery
1953 # their example was a bit wrong, I figured it out by adding
1954 # LogLevel warn rewrite:trace5
1955 # then watching the apache logs
1956
1957 RewriteEngine on
1958 RewriteRule ^/\.well-known/host-meta /nextcloud/public.php?service=host-meta [QSA,L]
1959 RewriteRule ^/\.well-known/host-meta\.json /nextcloud/public.php?service=host-meta-json [QSA,L]
1960 RewriteRule ^/\.well-known/webfinger /nextcloud/public.php?service=webfinger [QSA,L]
1961 RewriteRule ^/\.well-known/carddav /nextcloud/remote.php/dav/ [R=301,L]
1962 RewriteRule ^/\.well-known/caldav /nextcloud/remote.php/dav/ [R=301,L]
1963 ### end nextcloud settings
1964 EOF
1965 if [[ ! -e $rcdir/config/secret ]]; then
1966 base64 </dev/urandom | head -c24 >$rcdir/config/secret || [[ $? == 141 || ${PIPESTATUS[0]} == 32 ]]
1967 fi
1968 secret=$(cat $rcdir/config/secret)
1969
1970 rclogdir=/var/log/$rcbase
1971 rctmpdir=/var/tmp/$rcbase
1972 rcdb=/m/rc/$rcbase.sqlite
1973 # config from mailinabox
1974 i $rcdir/config/config.inc.php <<EOF
1975 <?php
1976 \$config = array();
1977 # debian creates this for us
1978 \$config['log_dir'] = '$rclogdir/';
1979 # debian also creates a temp dir, but it is under its install dir,
1980 # seems better to have our own.
1981 \$config['temp_dir'] = '$rctmpdir/';
1982 \$config['db_dsnw'] = 'sqlite:///$rcdb?mode=0640';
1983 \$config['default_host'] = 'ssl://localhost';
1984 \$config['default_port'] = 993;
1985 \$config['imap_conn_options'] = array(
1986 'ssl' => array(
1987 'verify_peer' => false,
1988 'verify_peer_name' => false,
1989 ),
1990 );
1991 \$config['imap_timeout'] = 15;
1992 \$config['smtp_server'] = 'tls://127.0.0.1';
1993 \$config['smtp_conn_options'] = array(
1994 'ssl' => array(
1995 'verify_peer' => false,
1996 'verify_peer_name' => false,
1997 ),
1998 );
1999 \$config['product_name'] = 'webmail';
2000 \$config['des_key'] = '$secret';
2001 \$config['plugins'] = array('archive', 'zipdownload', 'password', 'managesieve', 'jqueryui', 'carddav', 'html5_notifier');
2002 \$config['skin'] = 'elastic';
2003 \$config['login_autocomplete'] = 2;
2004 \$config['password_charset'] = 'UTF-8';
2005 \$config['junk_mbox'] = 'Spam';
2006 # disable builtin addressbook
2007 \$config['address_book_type'] = '';
2008 ?>
2009 EOF
2010
2011 m mkdir -p $rclogdir
2012 m chmod 750 $rclogdir
2013 m chown www-data:adm $rclogdir
2014 # note: subscribed to updates:
2015 # r2e add rcmcarddav https://github.com/blind-coder/rcmcarddav/commits/master.atom ian@iankelling.org
2016 # r2e add roundcube https://github.com/roundcube/roundcubemail/releases.atom ian@iankelling.org
2017 m mkdir -p $rctmpdir /m/rc
2018 m chown -R www-data.www-data $rctmpdir /m/rc
2019 m chmod 750 $rctmpdir
2020 # Ensure the log file monitored by fail2ban exists, or else fail2ban can't start.
2021 # todo: check for other mailinabox things
2022 m sudo -u www-data touch $rclogdir/errors.log
2023
2024 #### begin carddav install
2025 # This is the official roundcube carddav repo.
2026 # Install doc suggests downloading with composer, but that
2027 # didnt work, it said some ldap package for roundcube was missing,
2028 # but I dont want to download some extra ldap thing.
2029 # https://github.com/blind-coder/rcmcarddav/blob/master/doc/INSTALL.md
2030 verf=$rcdir/plugins/carddav/myversion
2031 upgrade=false
2032 install=false
2033 v=4.0.0
2034 if [[ -e $verf ]]; then
2035 if [[ $(cat $verf) != "$v" ]]; then
2036 install=true
2037 upgrade=true
2038 fi
2039 else
2040 install=true
2041 fi
2042 if $install; then
2043 m rm -rf $rcdir/plugins/carddav
2044 tmpd=$(mktemp -d)
2045 m wget -nv -O $tmpd/t.tgz https://github.com/blind-coder/rcmcarddav/releases/download/v$v/carddav-v$v.tgz
2046 cd $rcdir/plugins
2047 tar xzf $tmpd/t.tgz
2048 rm -rf $tmpd
2049 m chown -R www-data:www-data $rcdir/plugins/carddav
2050 m cd $rcdir/plugins/carddav
2051 if $upgrade; then
2052 m sudo -u www-data composer-1.phar update --no-dev
2053 else
2054 m sudo -u www-data composer-1.phar install --no-dev
2055 fi
2056 m chown -R root:root $rcdir/plugins/carddav
2057 echo $v >$verf
2058 fi
2059
2060 # So, strangely, this worked in initial testing, but then
2061 # on first run it wouldn't show the existing contacts until
2062 # I went into the carddav settings and did "force immediate sync",
2063 # which seemed to fix things. Note, some of these settings
2064 # get initalized per/addressbook in the db, then need changing
2065 # there or through the settings menu.
2066
2067 # About categories, see https://www.davx5.com/tested-with/nextcloud
2068 # https://github.com/blind-coder/rcmcarddav/blob/master/doc/GROUPS.md
2069 i $rcdir/plugins/carddav/config.inc.php <<EOF;
2070 <?php
2071 \$prefs['_GLOBAL']['hide_preferences'] = false;
2072 \$prefs['davserver'] = array(
2073 # name in the UI is kind of dumb. This is just something short that seems to fit ok.
2074 'name' => 'Main',
2075 'username' => '%u', // login username
2076 'password' => '%p', // login password
2077 'url' => 'https://$domain/nextcloud/remote.php/dav/addressbooks/users/%u/contacts',
2078 'active' => true,
2079 'readonly' => false,
2080 'refresh_time' => '00:10:00',
2081 'fixed' => array('username','password'),
2082 'use_categories' => false,
2083 'hide' => false,
2084 );
2085 ?>
2086 EOF
2087 #### end carddav install
2088
2089 cd $rcdir/plugins
2090 if [[ ! -d html5_notifier ]]; then
2091 m git clone https://github.com/stremlau/html5_notifier
2092 fi
2093 cd $rcdir/plugins/html5_notifier
2094 m git pull --rebase
2095
2096 # todo: try out roundcube plugins: thunderbird labels
2097
2098 # Password changing plugin settings
2099 cat $rcdir/plugins/password/config.inc.php.dist - >$rcdir/plugins/password/config.inc.php <<'EOF'
2100 # following are from mailinabox
2101 $config['password_minimum_length'] = 8;
2102 $config['password_db_dsn'] = 'sqlite:////m/rc/users.sqlite';
2103 $config['password_query'] = 'UPDATE users SET password=%D WHERE email=%u';
2104 $config['password_dovecotpw'] = '/usr/bin/doveadm pw';
2105 $config['password_dovecotpw_method'] = 'SHA512-CRYPT';
2106 $config['password_dovecotpw_with_method'] = true;
2107 EOF
2108 # so PHP can use doveadm, for the password changing plugin
2109 m usermod -a -G dovecot www-data
2110 m usermod -a -G mail $u
2111
2112 # so php can update passwords
2113 m chown www-data:dovecot /m/rc/users.sqlite
2114 m chmod 664 /m/rc/users.sqlite
2115
2116 # Run Roundcube database migration script (database is created if it does not exist)
2117 m $rcdir/bin/updatedb.sh --dir $rcdir/SQL --package roundcube
2118 m chown www-data:www-data $rcdb
2119 m chmod 664 $rcdb
2120 done # end loop over domains and rcdirs
2121
2122 ### begin php setup for rc ###
2123 # Enable PHP modules.
2124 m phpenmod -v php mcrypt imap
2125 # dpkg says this is required
2126 m a2enmod proxy_fcgi setenvif
2127 fpm=$(dpkg-query -s php-fpm | sed -nr 's/^Depends:.* (php[^ ]*-fpm)( .*|$)/\1/p') # eg: php7.4-fpm
2128 phpver=$(dpkg-query -s php-fpm | sed -nr 's/^Depends:.* php([^ ]*)-fpm( .*|$)/\1/p')
2129 m a2enconf $fpm
2130 # 3 useless guides on php fpm fcgi debian 10 later, i figure out from reading
2131 # /etc/apache2/conf-enabled/php7.3-fpm.conf
2132 m a2dismod php$phpver
2133 # according to /install, we should set date.timezone,
2134 # but that is dumb, the system already has the right zone in
2135 # $rclogdir/errors.log
2136 # todo: consider other settings in
2137 # /a/opt/mailinabox/setup/nextcloud.sh
2138 i /etc/php/$phpver/cli/conf.d/30-local.ini <<'EOF'
2139 apc.enable_cli = 1
2140 EOF
2141
2142 i /etc/php/$phpver/fpm/conf.d/30-local.ini <<'EOF'
2143 date.timezone = "America/New_York"
2144 # for nextcloud
2145 upload_max_filesize = 2000M
2146 post_max_size = 2000M
2147 # install checker, nextcloud/settings/admin/overview
2148 memory_limit = 512M
2149 EOF
2150 m systemctl restart $fpm
2151 # dunno if reload/restart is needed
2152 m systemctl reload apache2
2153 # note bk backups are defined in crontab outside this file
2154 ### end php setup for rc ###
2155
2156 fi # end roundcube setup
2157
2158 # * nextcloud setup
2159
2160 if [[ $HOSTNAME == bk ]]; then
2161 # from install checker, nextcloud/settings/admin/overview and
2162 # https://docs.nextcloud.com/server/19/admin_manual/installation/source_installation.html
2163 # curl from the web installer requirement, but i switched to cli
2164 # it recommends php-file info, but that is part of php7.3-common, already got installed
2165 # with roundcube.
2166 m pi php-curl php-bz2 php-gmp php-bcmath php-imagick php-apcu
2167
2168 # https://docs.nextcloud.com/server/19/admin_manual/installation/source_installation.html
2169 cat >/etc/php/$phpver/fpm/pool.d/localwww.conf <<'EOF'
2170 [www]
2171 clear_env = no
2172 EOF
2173
2174 for ((i=0; i < ${#bkdomains[@]}; i++)); do
2175 domain=${bkdomains[i]}
2176 ncdir=${ncdirs[i]}
2177 ncbase=${ncdir##*/}
2178 m cd /var/www
2179 if [[ ! -e $ncdir/index.php ]]; then
2180 # if we wanted to only install a specific version, use something like
2181 # file=latest-22.zip
2182 file=latest.zip
2183 m wget -nv -N https://download.nextcloud.com/server/releases/$file
2184 m rm -rf nextcloud
2185 m unzip -q $file
2186 m rm -f $file
2187 m chown -R www-data.www-data nextcloud
2188 m mv nextcloud $ncdir
2189 m cd $ncdir
2190 m sudo -u www-data php occ maintenance:install --database sqlite --admin-user iank --admin-pass $nextcloud_admin_pass
2191 fi
2192 # note, strange this happend where updater did not increment the version var,
2193 # mine was stuck on 20. I manually updated it.
2194 m cd $ncdir/config
2195 if [[ ! -e config.php-orig ]]; then
2196 m cp -a config.php config.php-orig
2197 fi
2198 cat config.php-orig - >tmp.php <<EOF
2199 # https://docs.nextcloud.com/server/19/admin_manual/configuration_server/email_configuration.html
2200 \$CONFIG["mail_smtpmode"] = "sendmail";
2201 \$CONFIG["mail_smtphost"] = "127.0.0.1";
2202 \$CONFIG["mail_smtpport"] = 25;
2203 \$CONFIG["mail_smtptimeout"] = 10;
2204 \$CONFIG["mail_smtpsecure"] = "";
2205 \$CONFIG["mail_smtpauth"] = false;
2206 \$CONFIG["mail_smtpauthtype"] = "LOGIN";
2207 \$CONFIG["mail_smtpname"] = "";
2208 \$CONFIG["mail_smtppassword"] = "";
2209 \$CONFIG["mail_domain"] = "$domain";
2210
2211 # https://github.com/nextcloud/user_external#readme
2212 # plus mailinabox example
2213 #\$CONFIG['user_backends'] = array(array('class' => 'OC_User_IMAP','arguments' => array('127.0.0.1', 143, null),),);
2214
2215
2216 # based on installer check
2217 # https://docs.nextcloud.com/server/19/admin_manual/configuration_server/caching_configuration.html
2218 \$CONFIG['memcache.local'] = '\OC\Memcache\APCu';
2219
2220 \$CONFIG['overwrite.cli.url'] = 'https://$domain/nextcloud';
2221 \$CONFIG['htaccess.RewriteBase'] = '/nextcloud';
2222 \$CONFIG['trusted_domains'] = array (
2223 0 => '$domain',
2224 );
2225 #\$CONFIG[''] = '';
2226 fwrite(STDOUT, "<?php\n\\\$CONFIG = ");
2227 var_export(\$CONFIG);
2228 fwrite(STDOUT, ";\n");
2229 EOF
2230 m php tmp.php >config.php
2231 m rm tmp.php
2232 m sudo -u www-data php $ncdir/occ maintenance:update:htaccess
2233 list=$(sudo -u www-data php $ncdir/occ --output=json_pretty app:list)
2234 # user_external not compaible with nc 23
2235 for app in contacts calendar; do
2236 if [[ $(printf "%s\n" "$list"| jq ".enabled.$app") == null ]]; then
2237 m sudo -u www-data php $ncdir/occ app:install $app
2238 fi
2239 done
2240 i /etc/systemd/system/$ncbase.service <<EOF
2241 [Unit]
2242 Description=ncup $ncbase
2243 After=multi-user.target
2244
2245 [Service]
2246 Type=oneshot
2247 ExecStart=/usr/local/bin/ncup $ncbase
2248 User=www-data
2249 IOSchedulingClass=idle
2250 CPUSchedulingPolicy=idle
2251 EOF
2252 i /etc/systemd/system/$ncbase.timer <<EOF
2253 [Unit]
2254 Description=ncup $ncbase timer
2255
2256 [Timer]
2257 OnCalendar=Daily
2258
2259 [Install]
2260 WantedBy=timers.target
2261 EOF
2262 systemctl enable --now $ncbase.timer
2263 i /usr/local/bin/ncup <<'EOFOUTER'
2264 #!/bin/bash
2265 if ! test "$BASH_VERSION"; then echo "error: shell is not bash" >&2; exit 1; fi
2266 shopt -s inherit_errexit 2>/dev/null ||: # ignore fail in bash < 4.4
2267 set -eE -o pipefail
2268 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" exit status: $?, PIPESTATUS: ${PIPESTATUS[*]}" >&2' ERR
2269
2270 ncbase=$1
2271 if ! php /var/www/$ncbase/updater/updater.phar -n; then
2272 echo failed nextcloud update for $ncbase >&2
2273 /sbin/exim -t <<EOF
2274 To: alerts@iankelling.org
2275 From: root@$(hostname -f)
2276 Subject: failed nextcloud update for $ncbase
2277
2278 For logs, run: jr -u $ncbase
2279 EOF
2280 fi
2281 EOFOUTER
2282
2283 mkdir -p /var/www/cron-errors
2284 chown www-data.www-data /var/www/cron-errors
2285 i /etc/cron.d/$ncbase <<EOF
2286 PATH=/sbin:/usr/sbin:/usr/bin:/bin:/usr/local/bin
2287 SHELL=/bin/bash
2288 # https://docs.nextcloud.com/server/20/admin_manual/configuration_server/background_jobs_configuration.html
2289 */5 * * * * www-data php -f $ncdir/cron.php --define apc.enable_cli=1 |& log-once nccron
2290 EOF
2291
2292 done
2293 fi
2294
2295
2296 # * exim host conditional config
2297
2298 # ** exim certs
2299
2300 all_dirs=(/p/c/filesystem)
2301 for x in /p/c/machine_specific/*.hosts /a/bin/ds/machine_specific/*.hosts; do
2302 if grep -qxF $HOSTNAME $x; then all_dirs+=( ${x%.hosts} ); fi
2303 done
2304 files=()
2305 for d in ${all_dirs[@]}; do
2306 f=$d/etc/exim4/passwd
2307 if [[ -e $f ]]; then
2308 files+=($f)
2309 fi
2310 tmp=($d/etc/exim4/*.pem)
2311 if (( ${#tmp[@]} )); then
2312 files+=(${tmp[@]})
2313 fi
2314 done
2315
2316 if (( ${#files[@]} )); then
2317 sudo rsync -ahhi --chown=root:Debian-exim --chmod=0640 ${files[@]} /etc/exim4/
2318 fi
2319
2320
2321 # ** exim: auth
2322
2323 case $HOSTNAME in
2324 bk|je)
2325 # avoid accepting mail for invalid users
2326 # https://wiki.dovecot.org/LMTP/Exim
2327 cat >>/etc/exim4/conf.d/rcpt_local_acl <<'EOF'
2328 deny
2329 message = invalid recipient
2330 domains = +local_domains
2331 !verify = recipient/callout=no_cache
2332 EOF
2333 i /etc/exim4/conf.d/auth/29_exim4-config_auth <<'EOF'
2334 dovecot_plain:
2335 driver = dovecot
2336 public_name = PLAIN
2337 server_socket = /var/run/dovecot/auth-client
2338 server_set_id = $auth1
2339 EOF
2340 ;;
2341 esac
2342 if $bhost_t; then
2343 i /etc/exim4/conf.d/auth/29_exim4-config_auth <<'EOF'
2344 # from 30_exim4-config_examples
2345 plain_server:
2346 driver = plaintext
2347 public_name = PLAIN
2348 server_condition = "${if crypteq{$auth3}{${extract{1}{:}{${lookup{$auth2}lsearch{CONFDIR/passwd}{$value}{*:*}}}}}{1}{0}}"
2349 server_set_id = $auth2
2350 server_prompts = :
2351 .ifndef AUTH_SERVER_ALLOW_NOTLS_PASSWORDS
2352 server_advertise_condition = ${if eq{$tls_in_cipher}{}{}{*}}
2353 .endif
2354 EOF
2355 fi
2356
2357 # ** exim: main daemon use non-default config file
2358 case $HOSTNAME in
2359 bk|$MAIL_HOST)
2360 # to see the default comments in /etc/default/exim4:
2361 # s update-exim4defaults --force --init
2362 # which will overwrite any existing file
2363 i /etc/default/exim4 <<'EOF'
2364 QUEUERUNNER='combined'
2365 QUEUEINTERVAL='30m'
2366 COMMONOPTIONS='-C /etc/exim4/my.conf'
2367 UPEX4OPTS='-o /etc/exim4/my.conf'
2368 #E4BCD_PANICLOG_NOISE='exim user lost privilege for using -C option'
2369 EOF
2370 chown Debian-exim:Debian-exim /usr/sbin/exim4
2371 # needs guid set in order to become Debian-exim
2372 chmod g+s,u+s /usr/sbin/exim4
2373 i /etc/exim4/trusted_configs <<'EOF'
2374 /etc/exim4/my.conf
2375 EOF
2376 ;;
2377 *)
2378 # default file
2379 i /etc/default/exim4 <<'EOF'
2380 QUEUERUNNER='combined'
2381 QUEUEINTERVAL='30m'
2382 EOF
2383 ;;
2384 esac
2385
2386 # ** exim non-root
2387
2388 case $HOSTNAME in
2389 bk|je|li)
2390 # no reason to expect it to ever be there.
2391 rm -fv /etc/systemd/system/exim4.service.d/nonroot.conf
2392 ;;
2393 *)
2394 dirs=()
2395 for d in /d /m /media /mnt /nocow /o /p /q; do
2396 if [[ -d $d ]]; then
2397 dirs+=($d)
2398 fi
2399 done
2400 i /etc/systemd/system/exim4.service.d/nonroot.conf <<EOF
2401 [Service]
2402 # see 56.2 Root privilege in exim spec
2403 AmbientCapabilities=CAP_NET_BIND_SERVICE
2404 # https://www.redhat.com/sysadmin/mastering-systemd
2405 # things that seem good and reasonabl.e
2406 PrivateTmp=yes
2407 ProtectHome=yes
2408 # note, in t10 systemd, if one of these is an sshfs mountpoint,
2409 # this whole setting doesnt work. tried it with a newer systemd 250 though
2410 # an nspawn, and it worked there.
2411 InaccessiblePaths=${dirs[@]}
2412 NoNewPrivileges=yes
2413 ProtectSystem=yes
2414
2415 # when we get newer systemd
2416 #ProtectDevices=yes
2417 EOF
2418 i /etc/exim4/conf.d/main/000_local-noroot <<'EOF'
2419 # see 56.2 Root privilege in exim spec
2420 deliver_drop_privilege = true
2421 EOF
2422 files=(
2423 300_exim4-config_real_local
2424 600_exim4-config_userforward
2425 700_exim4-config_procmail
2426 800_exim4-config_maildrop
2427 mmm_mail4root
2428 )
2429 for f in ${files[@]}; do
2430 echo "# iank: removed due to running nonroot"|i /etc/exim4/conf.d/router/$f
2431 done
2432 ;;
2433 esac
2434
2435 case $HOSTNAME in
2436
2437 # ** $MAIL_HOST|bk|je)
2438 $MAIL_HOST|bk|je)
2439
2440 echo|i /etc/exim4/conf.d/router/870_backup_local
2441
2442 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
2443 # note: some things we don't set that are here by default because they are unused.
2444 dc_local_interfaces=''
2445 dc_eximconfig_configtype='internet'
2446 dc_localdelivery='dovecot_lmtp'
2447 EOF
2448 cat >>/etc/exim4/conf.d/main/000_local <<EOF
2449 # recommended if dns is expected to work
2450 CHECK_RCPT_VERIFY_SENDER = true
2451 # default config comment says: If you enable this, you might reject legitimate mail,
2452 # but eggs has had this a long time, so that seems unlikely.
2453 CHECK_RCPT_SPF = true
2454 CHECK_RCPT_REVERSE_DNS = true
2455 CHECK_MAIL_HELO_ISSUED = true
2456
2457 # enable 587 in addition to the default 25, so that
2458 # i can send mail where port 25 is firewalled by isp
2459 daemon_smtp_ports = 25 : 587
2460 # default of 25, can get stuck when catching up on mail
2461 smtp_accept_max = 400
2462 smtp_accept_reserve = 100
2463 smtp_reserve_hosts = +iank_trusted
2464
2465 # options exim has to avoid having to alter the default config files
2466 CHECK_RCPT_LOCAL_ACL_FILE = /etc/exim4/conf.d/rcpt_local_acl
2467 CHECK_DATA_LOCAL_ACL_FILE = /etc/exim4/conf.d/data_local_acl
2468 LOCAL_DENY_EXCEPTIONS_LOCAL_ACL_FILE = /etc/exim4/conf.d/local_deny_exceptions_acl
2469 # testing dmarc
2470 #dmarc_tld_file = /etc/public_suffix_list.dat
2471 EOF
2472 ;;&
2473
2474 # ** $MAIL_HOST|bk)
2475 $MAIL_HOST|bk)
2476
2477 cat >>/etc/exim4/conf.d/main/000_local <<EOF
2478 # je.b8.nz will run out of memory with freshclam
2479 av_scanner = clamd:/var/run/clamav/clamd.ctl
2480 EOF
2481
2482 cat >> /etc/exim4/conf.d/data_local_acl <<'EOF'
2483 deny
2484 malware = */defer_ok
2485 !condition = ${if match {$malware_name}{\N^Heuristic\N}}
2486 message = This message was detected as possible malware ($malware_name).
2487 EOF
2488
2489 cat >/etc/exim4/conf.d/main/000_local-nn <<EOF
2490 # MAIN_HARDCODE_PRIMARY_HOSTNAME might mess up the
2491 # smarthost config type, not sure.
2492 # failing message on mail-tester.com:
2493 # We check if there is a server (A Record) behind your hostname kd.
2494 # You may want to publish a DNS record (A type) for the hostname kd or use a different hostname in your mail software
2495 # https://serverfault.com/questions/46545/how-do-i-change-exim4s-primary-hostname-on-a-debian-box
2496 # and this one seemed appropriate from grepping config.
2497 # I originally set this to li.iankelling.org, but then ended up with errors when li tried to send
2498 # mail to kd, so this should basically be a name that no host has as their
2499 # canonical hostname since the actual host sits behind a nat and changes.
2500 MAIN_HARDCODE_PRIMARY_HOSTNAME = mail.iankelling.org
2501 # I used this to avoid sender verification, didnt work but it still
2502 # makes sense based on the spec.
2503 hosts_treat_as_local = defaultnn.b8.nz
2504
2505 # Outside nn, we get the default cert location from a debian macro,
2506 # and the cert file is put in place by a certbot hook.
2507 MAIN_TLS_CERTIFICATE = /etc/exim4/fullchain.pem
2508 MAIN_TLS_PRIVATEKEY = /etc/exim4/privkey.pem
2509 EOF
2510
2511 i /etc/exim4/conf.d/router/190_exim4-config_fsfsmarthost <<'EOF'
2512 gnusmarthost:
2513 debug_print = "R: smarthost for $local_part@$domain"
2514 driver = manualroute
2515 domains = ! +local_domains
2516 # send most mail through eggs, helps fsfs sender reputation.
2517 # uncomment and optionally move to 188 file to send through my own servers again
2518 senders = *@gnu.org
2519 transport = smarthost_dkim
2520 route_list = * fencepost.gnu.org::587 byname
2521 host_find_failed = ignore
2522 same_domain_copy_routing = yes
2523 no_more
2524 EOF
2525
2526 /a/exe/cedit defaultnn /etc/hosts <<'EOF' || [[ $? == 1 ]]
2527 10.173.8.1 defaultnn.b8.nz
2528 EOF
2529 ;;&
2530 # ** $MAIL_HOST)
2531 $MAIL_HOST)
2532
2533 i /etc/exim4/conf.d/router/195_dnslookup_vpn <<'EOF'
2534 # copied from /etc/exim4/conf.d/router/200_exim4-config_primary, but
2535 # use vpn transport. lower priority so it overrides the default route.
2536 # Use this in case our vpn fails, we dont send anything without it.
2537 .ifdef DCconfig_internet
2538 dnslookup_vpn:
2539 debug_print = "R: dnslookup for $local_part@$domain"
2540 driver = dnslookup
2541 domains = ! +local_domains
2542 transport = remote_smtp_vpn
2543 same_domain_copy_routing = yes
2544 ignore_target_hosts = <; 0.0.0.0 ; 127.0.0.0/8 ; 192.168.0.0/16 ; 172.16.0.0/12 ; 10.0.0.0/8 ; 169.254.0.0/16 ; 255.255.255.255 ; ::/128 ; ::1/128 ; fc00::/7 ; fe80::/10 ; 100::/64
2545 no_more
2546 .endif
2547 EOF
2548
2549
2550 # note on backups: I used to do an automatic sshfs and restricted
2551 # permissions to a specific directory on the remote server, /bu/mnt,
2552 # which required using a dedicated user, but realized smtp will be
2553 # more reliable and less fuss. If I ever need that again, see the
2554 # history of this file, and bum in brc2.
2555
2556 i /etc/exim4/conf.d/router/890_backup_copy <<EOF
2557 ### router/900_exim4-config_local_user
2558 #################################
2559
2560 # todo, it would be nice to save sent email too,
2561 # but its not so important, they still exist in my head
2562
2563 backup_redir:
2564 driver = redirect
2565 domains = +local_domains
2566 # b is just an arbirary short string
2567 data = b@eximbackup.b8.nz
2568 # note, to test this, i could temporarily allow testignore.
2569 # alerts avoids potential mail loop. root is already
2570 # redirected earlier, so that is just being overly cautious.
2571 local_parts = ! root : ! testignore : ! alerts
2572 unseen = true
2573
2574 backup_copy:
2575 driver = manualroute
2576 domains = eximbackup.b8.nz
2577 transport = backup_remote
2578 ignore_target_hosts = ${HOSTNAME}wg.b8.nz
2579 # note changes here also require change in passwd.client
2580 route_list = * eximbackup.b8.nz
2581 same_domain_copy_routing = yes
2582 errors_to = alerts@iankelling.org
2583 no_more
2584 EOF
2585
2586
2587 i /etc/exim4/conf.d/transport/30_backup_remote <<'EOF'
2588 backup_remote:
2589 driver = smtp
2590 multi_domain
2591 .ifndef IGNORE_SMTP_LINE_LENGTH_LIMIT
2592 message_size_limit = ${if > {$max_received_linelength}{998} {1}{0}}
2593 .endif
2594 hosts_require_auth = *
2595 hosts_try_auth = *
2596 envelope_to_add
2597 # manual return path because we want it to be the envelope sender
2598 # we got not the one we are using in this smtp transport
2599 headers_add = "Return-path: $sender_address"
2600 .ifdef REMOTE_SMTP_SMARTHOST_HOSTS_AVOID_TLS
2601 hosts_avoid_tls = REMOTE_SMTP_SMARTHOST_HOSTS_AVOID_TLS
2602 .endif
2603 .ifdef REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS
2604 hosts_require_tls = REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS
2605 .endif
2606 .ifdef REMOTE_SMTP_SMARTHOST_TLS_VERIFY_CERTIFICATES
2607 tls_verify_certificates = REMOTE_SMTP_SMARTHOST_TLS_VERIFY_CERTIFICATES
2608 .endif
2609 .ifdef REMOTE_SMTP_SMARTHOST_TLS_VERIFY_HOSTS
2610 tls_verify_hosts = REMOTE_SMTP_SMARTHOST_TLS_VERIFY_HOST
2611 .endif
2612 .ifdef REMOTE_SMTP_HEADERS_REWRITE
2613 headers_rewrite = REMOTE_SMTP_HEADERS_REWRITE
2614 .endif
2615 .ifdef REMOTE_SMTP_HELO_DATA
2616 helo_data=REMOTE_SMTP_HELO_DATA
2617 .endif
2618 .ifdef TLS_DH_MIN_BITS
2619 tls_dh_min_bits = TLS_DH_MIN_BITS
2620 .endif
2621 .ifdef REMOTE_SMTP_SMARTHOST_TLS_CERTIFICATE
2622 tls_certificate = REMOTE_SMTP_SMARTHOST_TLS_CERTIFICATE
2623 .endif
2624 .ifdef REMOTE_SMTP_SMARTHOST_PRIVATEKEY
2625 tls_privatekey = REMOTE_SMTP_SMARTHOST_PRIVATEKEY
2626 .endif
2627 .ifdef REMOTE_SMTP_TRANSPORTS_HEADERS_REMOVE
2628 headers_remove = REMOTE_SMTP_TRANSPORTS_HEADERS_REMOVE
2629 .endif
2630 EOF
2631
2632
2633 # this avoids some error. i cant remember what. todo:
2634 # test it out and document why/if its needed.
2635 # i /etc/exim4/host_local_deny_exceptions <<'EOF'
2636 # mail.fsf.org
2637 # *.posteo.de
2638 # EOF
2639
2640 # cron email from smarthost hosts will automatically be to
2641 # USER@FQDN. I redirect that to alerts@, on the smarthosts, but in
2642 # case that doesn't work, we still want to accept that mail, but not
2643 # from any host except the smarthosts. local_hostnames and this rule
2644 # is for that purpose.
2645 i /etc/exim4/conf.d/rcpt_local_acl <<'EOF'
2646 deny
2647 !authenticated = *
2648 domains = +local_hostnames
2649 message = no relay
2650 EOF
2651 echo|i /etc/exim4/conf.d/router/880_universal_forward
2652
2653 # for iank@fsf.org, i have mail.fsf.org forward it to fsf@iankelling.org.
2654 # and also have mail.iankelling.org whitelisted as a relay domain.
2655 # I could avoid that if I changed this to submit to 587 with a
2656 # password like a standard mua.
2657 i /etc/exim4/conf.d/router/188_exim4-config_smarthost <<'EOF'
2658 # ian: copied from /etc/exim4/conf.d/router/200_exim4-config_primary, and added senders = and
2659 # replaced DCsmarthost with hostname
2660 fsfsmarthost:
2661 debug_print = "R: smarthost for $local_part@$domain"
2662 driver = manualroute
2663 domains = ! +local_domains
2664 senders = *@fsf.org
2665 transport = remote_smtp_smarthost
2666 route_list = * mail.fsf.org::587 byname
2667 host_find_failed = ignore
2668 same_domain_copy_routing = yes
2669 no_more
2670
2671 posteosmarthost:
2672 debug_print = "R: smarthost for $local_part@$domain"
2673 driver = manualroute
2674 domains = ! +local_domains
2675 senders = *@posteo.net
2676 transport = remote_smtp_smarthost
2677 route_list = * posteo.de::587 byname
2678 host_find_failed = ignore
2679 same_domain_copy_routing = yes
2680 no_more
2681
2682 EOF
2683
2684 # Greping /etc/exim4, unqualified mails this would end up as
2685 # a return path, so it should go somewhere we will see.
2686 # The debconf output about mailname is as follows:
2687 # The 'mail name' is the domain name used to 'qualify' mail addresses without a domain
2688 # name.
2689 # This name will also be used by other programs. It should be the single, fully
2690 # qualified domain name (FQDN).
2691 # Thus, if a mail address on the local host is foo@example.org, the correct value for
2692 # this option would be example.org.
2693 # This name won\'t appear on From: lines of outgoing messages if rewriting is enabled.
2694 echo iankelling.org > /etc/mailname
2695
2696
2697 # mail.iankelling.org so local imap clients can connect with tls and
2698 # when they happen to not be local.
2699 # todo: this should be 10.8.0.4
2700
2701 /a/exe/cedit nn /etc/hosts <<'EOF' || [[ $? == 1 ]]
2702 # note: i put nn.b8.nz into bind for good measure
2703 10.173.8.2 nn.b8.nz mx.iankelling.org
2704 EOF
2705
2706 # note: systemd-resolved will consult /etc/hosts, dnsmasq wont. this assumes
2707 # weve configured this file in dnsmasq if we are using it.
2708 /a/exe/cedit mail /etc/dnsmasq-servers.conf <<'EOF' || [[ $? == 1 ]]
2709 server=/mx.iankelling.org/127.0.1.1
2710 EOF
2711 # I used to use debconf-set-selections + dpkg-reconfigure,
2712 # which then updates this file
2713 # but the process is slower than updating it directly and then I want to set other things in
2714 # update-exim4.conf.conf, so there's no point.
2715 # The file is documented in man update-exim4.conf,
2716 # except the man page is not perfect, read the bash script to be sure about things.
2717
2718 # The debconf questions output is additional documentation that is not
2719 # easily accessible, but super long, along with the initial default comment in this
2720 # file, so I've saved that into ./mail-notes.conf.
2721 #
2722 # # TODO: remove mx.iankelling.org once systems get updated mail-setup from jan 2022
2723 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
2724 # man page: is used to build the local_domains list, together with "localhost"
2725 # this is duplicated in a later router.
2726 dc_other_hostnames='iankelling.org;zroe.org;r2e.iankelling.org;mx.iankelling.org;!je.b8.nz;!bk.b8.nz;*.b8.nz;b8.nz'
2727 EOF
2728
2729
2730 # dmarc. not used currently
2731 f=/etc/cron.daily/refresh-dmarc-tld-file
2732 cat >$f <<'EOF'
2733 #!/bin/bash
2734 cd /etc
2735 wget -q -N https://publicsuffix.org/list/public_suffix_list.dat
2736 EOF
2737 m chmod 755 $f
2738
2739 ;;
2740 # ** bk
2741 ## we use this host to monitor MAIL_HOST and host a mail server for someone
2742 bk)
2743
2744 echo|i /etc/exim4/conf.d/rcpt_local_acl
2745 echo|i /etc/exim4/conf.d/router/880_universal_forward
2746
2747 /a/exe/cedit nn /etc/hosts <<'EOF' || [[ $? == 1 ]]
2748 10.173.8.2 nn.b8.nz
2749 EOF
2750
2751 sed -r -f - /etc/init.d/exim4 <<'EOF' | i /etc/init.d/exim4in
2752 s,/etc/default/exim4,/etc/default/exim4in,g
2753 s,/run/exim4/exim.pid,/run/exim4/eximin.pid,g
2754 s,(^[ #]*Provides:).*,\1 exim4in,
2755 s,(^[ #]*NAME=).*,\1"exim4in",
2756 EOF
2757 chmod +x /etc/init.d/exim4in
2758 i /etc/systemd/system/exim4in.service.d/alwaysrestart.conf <<'EOF'
2759 [Unit]
2760 # needed to continually restart
2761 StartLimitIntervalSec=0
2762
2763 [Service]
2764 Restart=always
2765 # time to sleep before restarting a service
2766 RestartSec=20
2767 EOF
2768
2769 i /etc/default/exim4in <<'EOF'
2770 # defaults but no queue runner and alternate config dir
2771 QUEUERUNNER='no'
2772 COMMONOPTIONS='-oP /run/exim4/eximin.pid'
2773 UPEX4OPTS='-d /etc/myexim4'
2774 EOF
2775
2776 echo bk.b8.nz > /etc/mailname
2777 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
2778 # man page: is used to build the local_domains list, together with "localhost"
2779 dc_other_hostnames='amnimal.ninja;expertpathologyreview.com;bk.b8.nz'
2780 EOF
2781
2782 ;;
2783 # ** je
2784 je)
2785 echo je.b8.nz > /etc/mailname
2786 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
2787 dc_other_hostnames='je.b8.nz'
2788 EOF
2789 echo|i /etc/exim4/conf.d/router/188_exim4-config_smarthost
2790 echo|i /etc/exim4/conf.d/router/190_exim4-config_fsfsmarthost
2791 echo|i /etc/exim4/conf.d/rcpt_local_acl
2792 echo|i /etc/exim4/conf.d/router/880_universal_forward
2793 ;;
2794 # ** not MAIL_HOST|bk|je
2795 *)
2796 # this one should be removed for all non mail hosts, but
2797 # bk and je never become mail_host
2798 echo|i /etc/exim4/conf.d/router/195_dnslookup_vpn
2799
2800 echo|i /etc/exim4/conf.d/router/188_exim4-config_smarthost
2801 echo|i /etc/exim4/conf.d/router/190_exim4-config_fsfsmarthost
2802 echo|i /etc/exim4/conf.d/rcpt_local_acl
2803 echo|i /etc/exim4/conf.d/router/890_backup_copy
2804 echo|i /etc/exim4/conf.d/main/000_local-nn
2805
2806
2807 if $bhost_t; then
2808 cat >>/etc/exim4/conf.d/main/000_local <<EOF
2809 MAIN_TLS_CERTIFICATE = /etc/exim4/certs/$wghost/fullchain.pem
2810 MAIN_TLS_PRIVATEKEY = /etc/exim4/certs/$wghost/privkey.pem
2811 # so we can maintiain the originals of the backups.
2812 # we wouldnt want this if we were dealing with any other
2813 # local deliveries, but we sent all others to the smarthost
2814 # which then strips the headers.
2815 envelope_to_remove = false
2816 return_path_remove = false
2817 EOF
2818 fi
2819
2820 # catches things like cronjob email
2821 i /etc/exim4/conf.d/router/880_universal_forward <<'EOF'
2822 universal_forward:
2823 driver = redirect
2824 domains = +local_domains
2825 data = alerts@iankelling.org
2826 EOF
2827
2828
2829 for unit in ${nn_progs[@]}; do
2830 f=/etc/systemd/system/$unit.service.d/nn.conf
2831 rm -fv $f
2832 done
2833
2834 # dont i dont care if defaultnn section gets left, it wont
2835 # get used.
2836 echo | /a/exe/cedit nn /etc/hosts || [[ $? == 1 ]]
2837 echo | /a/exe/cedit mail /etc/dnsmasq-servers.conf || [[ $? == 1 ]]
2838
2839
2840 if $bhost_t; then
2841 install -d /bu
2842 install -d -g Debian-exim -o Debian-exim -m 771 /bu/md
2843 if [[ -e /bu/md/cur && $(stat -c %u /bu/md/cur) == 1000 ]]; then
2844 chown -R Debian-exim:Debian-exim /bu/md
2845 fi
2846 i /etc/exim4/conf.d/transport/30_backup_maildir <<EOF
2847 # modified debian maildir transport
2848 backup_maildir:
2849 driver = appendfile
2850 directory = /bu/md
2851 delivery_date_add
2852 # note, no return path or envelope added
2853 maildir_format
2854 directory_mode = 0700
2855 mode = 0644
2856 mode_fail_narrower = false
2857 EOF
2858
2859 i /etc/exim4/conf.d/router/870_backup_local <<'EOF'
2860 ### router/900_exim4-config_local_user
2861 #################################
2862
2863 backup_local:
2864 debug_print = "R: local_user for $local_part@$domain"
2865 driver = accept
2866 domains = eximbackup.b8.nz
2867 transport = backup_maildir
2868 EOF
2869
2870 # Bind to wghole to receive mailbackup.
2871 wgholeip=$(sed -rn 's/^ *Address *= *([^/]+).*/\1/p' /etc/wireguard/wghole.conf)
2872 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
2873 dc_other_hostnames='eximbackup.b8.nz'
2874 dc_local_interfaces='127.0.0.1;::1;$wgholeip'
2875 EOF
2876
2877 # wghole & thus exim will fail to start without internet connectivity.
2878 i /etc/systemd/system/exim4.service.d/backup.conf <<'EOF'
2879 [Unit]
2880 StartLimitIntervalSec=0
2881
2882 [Service]
2883 Restart=always
2884 RestartSec=20
2885 EOF
2886
2887 else
2888 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
2889 # Note: If theres like a temporary problem where mail gets sent to
2890 # one of these hosts, if exim isnt listening, it will be a temporary error
2891 # instead of a permanent 5xx.
2892 dc_local_interfaces='127.0.0.1;::1'
2893 EOF
2894 rm -fv /etc/systemd/system/exim4.service.d/backup.conf
2895 fi
2896 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
2897 dc_eximconfig_configtype='smarthost'
2898 dc_smarthost='$smarthost'
2899 EOF
2900
2901 hostname -f |i /etc/mailname
2902 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
2903 # The manpage incorrectly states this will do header rewriting, but
2904 # that only happens if we have dc_hide_mailname is set.
2905 dc_readhost='iankelling.org'
2906 # Only used in case of bounces.
2907 dc_localdelivery='maildir_home'
2908 EOF
2909 ;;
2910 esac
2911
2912
2913
2914
2915 # ** $MAILHOST|bk, things that belong at the end
2916 case $HOSTNAME in
2917 $MAIL_HOST|bk)
2918 # config for the non-nn exim
2919 m rsync -ra --delete /etc/exim4/ /etc/myexim4
2920 # If we ever wanted to have a separate spool,
2921 # we could do it like this.
2922 # cat >>/etc/exim4/conf.d/main/000_local-nn <<'EOF'
2923 # spool_directory = /var/spool/myexim4
2924 # EOF
2925 cat >>/etc/myexim4/update-exim4.conf.conf <<'EOF'
2926 dc_eximconfig_configtype='smarthost'
2927 dc_smarthost='nn.b8.nz'
2928 EOF
2929 ;;&
2930 bk)
2931
2932 # config for the non-nn exim
2933 cat >/etc/myexim4/conf.d/main/000_local-nn <<'EOF'
2934 MAIN_HARDCODE_PRIMARY_HOSTNAME = mail2.iankelling.org
2935 EOF
2936 ;;
2937 $MAIL_HOST)
2938 # for bk, we have a exim4in.service that will do this for us.
2939 m update-exim4.conf -d /etc/myexim4
2940 ;;
2941 esac
2942
2943 # * spool dir setup
2944
2945 # ** bind mount setup
2946 # put spool dir in directory that spans multiple distros.
2947 # based on http://www.postfix.org/qmgr.8.html and my notes in gnus
2948 #
2949 dir=/nocow/exim4
2950 sdir=/var/spool/exim4
2951 # we only do this if our system has $dir
2952
2953 # this used to do a symlink, but, in the boot logs, /nocow would get mounted succesfully,
2954 # about 2 seconds later, exim starts, and immediately puts into paniclog:
2955 # honVi-0000u3-82 Failed to create directory "/var/spool/exim4/input": No such file or directory
2956 # so, im trying a bind mount to get rid of that.
2957 if [[ -e /nocow ]]; then
2958 if ! grep -Fx "/nocow/exim4 /var/spool/exim4 none bind 0 0" /etc/fstab; then
2959 echo "/nocow/exim4 /var/spool/exim4 none bind 0 0" >>/etc/fstab
2960 fi
2961 i /etc/systemd/system/exim4.service.d/override.conf <<'EOF'
2962 [Unit]
2963 # without local-fs on exim, we get these kind of errors in paniclog on shutdown:
2964 # Failed to create spool file /var/spool/exim4//input//1jCLxz-0008V4-V9-D: Permission denied
2965 After=local-fs.target
2966 EOF
2967 if ! mountpoint -q $sdir; then
2968 stopifactive exim4 exim4in
2969 if [[ -L $sdir ]]; then
2970 m rm $sdir
2971 fi
2972 if [[ ! -e $dir && -d $sdir ]]; then
2973 m mv $sdir $dir
2974 fi
2975 if [[ ! -d $sdir ]]; then
2976 m mkdir $sdir
2977 m chmod 000 $sdir # only want it to be used when its mounted
2978 fi
2979 m mount $sdir
2980 fi
2981 fi
2982
2983
2984
2985 # ** exim/spool uid setup
2986 # i have the spool directory be common to distro multi-boot, so
2987 # we need the uid to be the same. 608 cuz it's kind of in the middle
2988 # of the free system uids.
2989 IFS=:; read -r _ _ uid _ < <(getent passwd Debian-exim ||:) ||:; unset IFS
2990 IFS=:; read -r _ _ gid _ < <(getent group Debian-exim ||:) ||:; unset IFS
2991 if [[ ! $uid ]]; then
2992 # from /var/lib/dpkg/info/exim4-base.postinst, plus uid and gid options
2993 m adduser --uid 608 --system --group --quiet --home /var/spool/exim4 \
2994 --no-create-home --disabled-login --force-badname Debian-exim
2995 elif [[ $uid != 608 ]]; then
2996 stopifactive exim4 exim4in
2997 m usermod -u 608 Debian-exim
2998 m groupmod -g 608 Debian-exim
2999 m usermod -g 608 Debian-exim
3000 m find / /nocow -xdev -path ./var/tmp -prune -o -uid $uid -execdir chown -h 608 {} +
3001 m find / /nocow -xdev -path ./var/tmp -prune -o -gid $gid -execdir chgrp -h 608 {} +
3002 fi
3003
3004 # * start / stop services
3005
3006 reifactive dnsmasq nscd
3007
3008 if $reload; then
3009 m systemctl daemon-reload
3010 fi
3011
3012 m systemctl --now enable epanicclean
3013
3014 case $HOSTNAME in
3015 je)
3016 /a/exe/web-conf apache2 je.b8.nz
3017 ;;
3018 bk)
3019 /a/exe/web-conf apache2 mail2.iankelling.org
3020 ;;
3021 esac
3022
3023 m /a/bin/ds/mail-cert-cron -1
3024 sre mailcert.timer
3025
3026 case $HOSTNAME in
3027 bk)
3028 # todo, this should be done in distro-begin
3029 soff systemd-resolved
3030 ln -sf 127.0.0.1-resolv/stub-resolv.conf /etc/resolv.conf
3031 ;;&
3032 $MAIL_HOST|bk)
3033 m systemctl --now enable mailnn mailnnroute
3034 ;;&
3035 $MAIL_HOST)
3036 # we use dns to start wg
3037 if $reload; then
3038 sre unbound
3039 else
3040 m systemctl --now enable unbound
3041 fi
3042 ;;&
3043 $MAIL_HOST|bk)
3044 # If these have changes, id rather manually restart it, id rather
3045 # not restart and cause temporary errors
3046 if $reload; then
3047 sre $vpnser
3048 else
3049 m systemctl --now enable $vpnser
3050 fi
3051 if ! systemctl is-active clamav-daemon >/dev/null; then
3052 m systemctl --now enable clamav-daemon
3053 out=$(rsync -aiSAX --chown=root:root --chmod=g-s /a/bin/ds/filesystem/etc/systemd/system/epanicclean.service /etc/systemd/system)
3054 if [[ $out ]]; then
3055 reload=true
3056 fi
3057
3058 # note, this will cause paniclog entries because it takes like 45
3059 # seconds for clamav to start, i use ./epanic-clean to remove
3060 # them.
3061 fi
3062 ;;&
3063 $MAIL_HOST|bk|je)
3064 # start spamassassin/dovecot before exim.
3065 sre dovecot spamassassin
3066 # need to wait a bit before restarting exim, else I
3067 # get a paniclog entry like: spam acl condition: all spamd servers failed
3068 sleep 3
3069 m systemctl --now enable mailclean.timer
3070 ;;&
3071 $MAIL_HOST)
3072 # < 2.1 (eg: in t9), uses a different data format which required manual
3073 # migration. dont start if we are running an old version.
3074 if dpkg --compare-versions $(dpkg -s radicale | awk '$1 == "Version:" { print $2 }') ge 2.1; then
3075 m systemctl --now enable radicale
3076 fi
3077 ;;&
3078 esac
3079
3080 # last use of $reload happens in previous block
3081 rm -f /var/local/mail-setup-reload
3082
3083
3084 case $HOSTNAME in
3085 $MAIL_HOST|bk|je) : ;;
3086 *)
3087 soff radicale mailclean.timer dovecot spamassassin $vpnser mailnn clamav-daemon
3088 ;;
3089 esac
3090
3091 sre exim4
3092
3093 case $HOSTNAME in
3094 $MAIL_HOST)
3095 m systemctl --now enable mailbindwatchdog
3096 ;;
3097 *)
3098 soff mailbindwatchdog
3099 ;;
3100 esac
3101
3102
3103 case $HOSTNAME in
3104 bk) sre exim4in ;;
3105 esac
3106
3107 # * mail monitoring / testing
3108
3109 # note, to test clamav, send an email with body that only contains
3110 # https://en.wikipedia.org/wiki/EICAR_test_file
3111 # which set malware_name to Eicar-Signature
3112 case $HOSTNAME in
3113 $MAIL_HOST|bk|je)
3114 # note: cronjob "ian" also does some important monitoring
3115 # todo: this will sometimes cause an alert because mailtest-check will run
3116 # before we have setup network namespace and spamassassin
3117 cat >/etc/cron.d/mailtest <<EOF
3118 SHELL=/bin/bash
3119 PATH=/usr/bin:/bin:/usr/local/bin
3120 MAILTO=daylerts@iankelling.org
3121 */5 * * * * $u send-test-forward |& log-once send-test-forward
3122 */10 * * * * root chmod -R g+rw /m/md/bounces |& log-once -1 bounces-chmod
3123 */5 * * * * root timeout 290 mailtest-check slow |& log-once -4 mailtest-check
3124 # if a bounce happened yesterday, dont let it slip through the cracks
3125 8 1 * * * root export MAILTO=alerts@iankelling.org; awk '\$5 == "**"' /var/log/exim4/mainlog.1
3126 EOF
3127 m sudo rsync -ahhi --chown=root:root --chmod=0755 \
3128 /b/ds/mailtest-check /b/ds/check-remote-mailqs /usr/local/bin/
3129 ;;&
3130 $MAIL_HOST)
3131 test_froms=(ian@iankelling.org z@zroe.org iank@gnu.org)
3132 test_to="testignore@expertpathologyreview.com, testignore@je.b8.nz, testignore@amnimal.ninja, jtuttle@gnu.org"
3133
3134 cat >>/etc/cron.d/mailtest <<EOF
3135 0 13 * * * root echo "1pm alert. You are not in the matrix."
3136 2 * * * * root check-remote-mailqs |& log-once check-remote-mailqs
3137 EOF
3138 ;;&
3139 bk)
3140 test_froms=(testignore@expertpathologyreview.com testignore@amnimal.ninja)
3141 test_to="testignore@iankelling.org, testignore@zroe.org, testignore@je.b8.nz"
3142 ;;&
3143 je)
3144 test_froms=(testignore@je.b8.nz)
3145 test_to="testignore@iankelling.org, testignore@zroe.org, testignore@expertpathologyreview.com, testignore@amnimal.ninja"
3146 ;;&
3147 $MAIL_HOST|bk|je)
3148 cat >/usr/local/bin/send-test-forward <<'EOF'
3149 #!/bin/bash
3150 olds=(
3151 $(/sbin/exiqgrep -o 260 -i -r '^(testignore@(iankelling\.org|zroe\.org|expertpathologyreview\.com|amnimal\.ninja|je\.b8\.nz)|jtuttle@gnu\.org)$')
3152 )
3153 if (( ${#olds[@]} )); then
3154 /sbin/exim -Mrm "${olds[@]}" >/dev/null
3155 fi
3156 EOF
3157 for test_from in ${test_froms[@]}; do
3158 cat >>/usr/local/bin/send-test-forward <<EOFOUTER
3159 /usr/sbin/exim -f $test_from -t <<EOF
3160 From: $test_from
3161 To: $test_to
3162 Subject: test \$(date +%Y-%m-%dT%H:%M:%S%z) \$(date +%s)
3163
3164 /usr/local/bin/send-test-forward
3165 EOF
3166 EOFOUTER
3167 done
3168 m chmod +x /usr/local/bin/send-test-forward
3169 ;;
3170 *)
3171 rm -fv /etc/cron.d/mailtest
3172 ;;
3173 esac
3174
3175
3176
3177 # * misc
3178 m sudo -u $u mkdir -p /home/$u/.cache
3179 set -- /m/mucache /home/$u/.cache/mu /m/.mu /home/$u/.mu
3180 while (($#)); do
3181 target=$1
3182 f=$2
3183 shift 2
3184 if [[ ! -L $f ]]; then
3185 if [[ -e $f ]]; then
3186 rm -rf $f
3187 fi
3188 m sudo -u $u ln -sf -T $target $f
3189 fi
3190 done
3191
3192
3193 # /etc/alias setup is debian specific, and exim postinst script sets up
3194 # an /etc/alias from root to the postmaster, based on the question
3195 # exim4-config exim4/dc_postmaster, as long as there exists an entry for
3196 # root, or there was no preexisting aliases file. postfix won\'t set up
3197 # a root to $postmaster alias if it\'s already installed. Easiest to
3198 # just set it ourselves.
3199
3200 # debconf question for postmaster:
3201 # Mail for the 'postmaster', 'root', and other system accounts needs to be redirected
3202 # to the user account of the actual system administrator.
3203 # If this value is left empty, such mail will be saved in /var/mail/mail, which is not
3204 # recommended.
3205 # Note that postmaster\'s mail should be read on the system to which it is directed,
3206 # rather than being forwarded elsewhere, so (at least one of) the users listed here
3207 # should not redirect their mail off this machine. A 'real-' prefix can be used to
3208 # force local delivery.
3209 # Multiple user names need to be separated by spaces.
3210 # Root and postmaster mail recipient:
3211
3212 m exit 0
3213 :
3214
3215 # Local Variables:
3216 # eval: (outline-minor-mode)
3217 # outline-regexp: "\\( *\\)# [*]\\{1,8\\} "
3218 # End:
3219 # this is combined with defining outline-level in init.el