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