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