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