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