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