fixes and refactor
[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 echo "no err tracing script found"
139 exit 1
140 fi
141 source /a/bin/distro-functions/src/identify-distros
142 source /a/bin/distro-functions/src/package-manager-abstractions
143
144 # has nextcloud_admin_pass in it
145 f=/p/c/machine_specific/$HOSTNAME/mail
146 if [[ -e $f ]]; then
147 # shellcheck source=/p/c/machine_specific/bk/mail
148 source $f
149 fi
150
151
152 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
153
154 # note, this is hardcoded in /etc/exim4/conf.d/main/000_local
155 u=$(id -nu 1000)
156
157
158 usage() {
159 cat <<EOF
160 Usage: ${0##*/} anything_here_to_debug
161 Setup exim4 & dovecot & related things
162
163 -h|--help Print help and exit.
164 EOF
165 exit $1
166 }
167
168 # debug output if we pass any arg
169 if (( $# )); then
170 set -x
171 fi
172
173
174 ####### instructions for icedove #####
175 # Incoming mail server: mail.iankelling.org, port 143, username iank, connection security starttls, authentication method normal password,
176 # then click advanced so it accepts it.
177 # we could also just use 127.0.0.1 with no ssl
178 #
179 # hamburger -> preferences -> preferences -> advanced tab -> config editor button -> security.ssl.enable_ocsp_must_staple = false
180 # background: dovecot does not yet have ocsp stapling support
181 # reference: https://community.letsencrypt.org/t/simple-guide-using-lets-encrypt-ssl-certs-with-dovecot/2921
182 #
183 # for phone, k9mail, fdroid, same thing but username alerts, pass in ivy-pass.
184 # also, bk.b8.nz for secondary alerts, username is iank. same alerts pass.
185 # fetching mail settings: folder poll frequency 10 minutes.
186 # account settings, fetching mail, push folders: All. Then disable the persistent notification.
187 #######
188
189
190 # * perstent password instructions
191 # Note: for cert cron, we need to manually run first to accept known_hosts
192
193 # # exim passwords:
194 # # for hosts which have all private files I just use the same user
195 # # for other hosts, each one get\'s their own password.
196 # # for generating secure pass, and storing for server too:
197 # f=$(mktemp)
198 # host=tp
199 # apg -m 50 -x 70 -n 1 -a 1 -M CLN >$f
200 # s sed -i "/^$host:/d" /p/c/filesystem/etc/exim4/passwd
201 # echo "$host:$(mkpasswd -m sha-512 -s <$f)" >>/p/c/filesystem/etc/exim4/passwd
202 # #reference: exim4_passwd_client(5)
203 # dir=/p/c/machine_specific/$host/filesystem/etc/exim4
204 # mkdir -p $dir
205 # echo "mail.iankelling.org:$host:$(<$f)" > $dir/passwd.client
206 # # then run this script
207
208 # # dovecot password, i just need 1 as I\'m the only user
209 # mkdir /p/c/filesystem/etc/dovecot
210 # echo "iank:$(doveadm pw -s SHA512-CRYPT)::::::" >>/p/c/filesystem/etc/dovecot/users
211
212 ####### end perstent password instructions ######
213
214
215 # * dkim dns
216 # # Remove 1 level of comments in this section, set the domain var
217 # # for the domain you are setting up, then run this and copy dns settings
218 # # into dns.
219 # domain=iankelling.org
220 # c /p/c/filesystem/etc/exim4
221 # # this has several bugs addressed in comments, but it was helpful
222 # # https://debian-administration.org/article/718/DKIM-signing_outgoing_mail_with_exim4
223
224 # openssl genrsa -out $domain-private.pem 2048
225 # # Then, to get the public key strings to put in bind:
226
227 # # selector is needed for having multiple keys for one domain.
228 # # I dun do that, so just use a static one: li
229 # # Debadmin page does not have v=, fastmail does, and this
230 # # says it\'s recommended in 3.6.1, default is DKIM1 anyways.
231 # # https://www.ietf.org/rfc/rfc6376.txt
232 # # Join and print all but first and last line.
233 # # last line: swap hold & pattern, remove newlines, print.
234 # # lines 2+: append to hold space
235 # echo "bind txt record: remember to truncate $domain so its relative to the bind zone"
236 # cat <<EOF
237 # a._domainkey.$domain TXT (
238 # "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')" )
239 # EOF
240 # # sed explanation: skip the first few lines, then put them into the hold space, then
241 # # on the last line, back to the patern space, remove the newlines, then add a newline
242 # # at the last char - 240, because bind txt records need strings <=255 chars,
243 # # other dkim stuff at the begining is is 25 chars, and the pubkey is 393, so this
244 # # leaves us a bit of extra room at the end and a bunch at the beginning.
245
246 # # selector was also put into /etc/exim4/conf.d/main/000_local,
247
248 # * dmarc dns
249
250 # # 2017-02 dmarc policies:
251 # # host -t txt _dmarc.gmail.com
252 # # yahoo: p=reject, hotmail: p=none, gmail: p=none, fastmail none for legacy reasons
253 # # there were articles claiming gmail would be changing
254 # # to p=reject, in early 2017, which didn\'t happen. I see no sources on them. It\'s
255 # # expected to cause problems
256 # # with a few old mailing lists, copying theirs for now.
257 #
258 # echo "dmarc dns, name: _dmarc value: v=DMARC1; p=none; rua=mailto:mailauth-reports@$domain"
259
260 # * other dns
261
262 # # 2017-02 spf policies:
263 # # host -t txt lists.fedoraproject.org
264 # # google ~all, hotmail ~all, yahoo: ?all, fastmail ?all, outlook ~all
265 # # i include fastmail\'s settings, per their instructions,
266 # # and follow their policy. In mail in a box, or similar instructions,
267 # # I\'ve seen recommended to not use a restrictive policy.
268
269 # # to check if dns has updated, you do
270 # host -a mesmtp._domainkey.$domain
271
272 # # mx records,
273 # # setting it to iankelling.org would work the same, but this
274 # # is more flexible, I could change where mail.iankelling.org pointed.
275 # cat <<'EOF'
276 # mx records, 2 records each, for * and empty domain
277 # pri 10 mail.iankelling.org
278 # EOF
279
280 # # dnssec
281 # from brc2, run dnsecgen then dsign, update named.local.conf, publish keys to registrar
282
283 # * functions & constants
284
285 pre="${0##*/}:"
286 m() { printf "$pre %s\n" "$*"; "$@"; }
287 e() { printf "$pre %s\n" "$*"; }
288 err() { printf "$pre %s\n" "$*" >&2; exit 1; }
289
290 reload=false
291 # This file is so if we fail in the middle and rerun, we dont lose state
292 if [[ -e /var/local/mail-setup-reload ]]; then
293 reload=true
294 fi
295 u() { # update file. note: duplicated in brc
296 local tmp tmpdir dest="$1"
297 local base="${dest##*/}"
298 local dir="${dest%/*}"
299 if [[ $dir != "$base" ]]; then
300 # dest has a directory component
301 mkdir -p "$dir"
302 fi
303 ur=false # u result
304 tmpdir=$(mktemp -d)
305 cat >$tmpdir/"$base"
306 tmp=$(rsync -ic $tmpdir/"$base" "$dest")
307 if [[ $tmp ]]; then
308 printf "%s\n" "$tmp"
309 ur=true
310 if [[ $dest == /etc/systemd/system/* ]]; then
311 touch /var/local/mail-setup-reload
312 reload=true
313 fi
314 fi
315 rm -rf $tmpdir
316 }
317 setini() {
318 key="$1" value="$2" section="$3"
319 file="/etc/radicale/config"
320 sed -ri "/ *\[$section\]/,/^ *\[[^]]+\]/{/^\s*${key}[[:space:]=]/d};/ *\[$section\]/a $key = $value" "$file"
321 }
322 soff () {
323 for service; do
324 # ignore services that dont exist
325 if systemctl cat $service &>/dev/null; then
326 m systemctl disable --now $service
327 fi
328 done
329 }
330 sre() {
331 for service; do
332 m systemctl restart $service
333 m systemctl enable $service;
334 done
335 }
336 mailhost() {
337 [[ $HOSTNAME == "$MAIL_HOST" ]]
338 }
339 e() { printf "%s\n" "$*"; }
340 reifactive() {
341 for service; do
342 if systemctl is-active $service >/dev/null; then
343 m systemctl restart $service
344 fi
345 done
346 }
347 stopifactive() {
348 for service; do
349 if systemctl is-active $service >/dev/null; then
350 m systemctl stop $service
351 fi
352 done
353 }
354
355 mxhost=mx.iankelling.org
356 mxport=587
357
358 # old setup. left as comment for example
359 # mxhost=mail.messagingengine.com
360 # mxport=587
361 # forward=ian@iankelling.org
362
363 smarthost="$mxhost::$mxport"
364 uhome=$(eval echo ~$u)
365
366 # Somehow on one machine, a file got written with 664 perms.
367 # just being defensive here.
368 umask 0022
369
370 source /a/bin/bash_unpublished/source-state
371 if [[ ! $MAIL_HOST ]]; then
372 err "\$MAIL_HOST not set"
373 fi
374
375 bhost_t=false
376 case $HOSTNAME in
377 $MAIL_HOST) : ;;
378 kd|frodo|x2|x3|kw|sy|bo)
379 bhost_t=true
380 ;;
381 esac
382
383
384 # * Install universal packages
385
386
387 # installs epanicclean iptables-exim ip6tables-exim
388 /a/bin/ds/install-my-scripts
389
390 if [[ $(debian-codename-compat) == bionic ]]; then
391 cat >/etc/apt/preferences.d/spamassassin <<'EOF'
392 Package: spamassassin sa-compile spamc
393 Pin: release n=focal,o=Ubuntu
394 Pin-Priority: 500
395 EOF
396 fi
397
398 # light version of exim does not have sasl auth support.
399 # note: for bitfolk hosts, unbound has important config with conflink.
400 pi-nostart exim4 exim4-daemon-heavy spamassassin unbound clamav-daemon wireguard
401
402 # note: pyzor debian readme says you need to run some initialization command
403 # but its outdated.
404 pi spf-tools-perl p0f postgrey pyzor razor jq moreutils certbot fail2ban
405 case $HOSTNAME in
406 je) : ;;
407 # not included due to using wireguard: openvpn
408 *) pi wget git unzip iptables ;;
409 esac
410 # bad packages that sometimes get automatically installed
411 pu openresolv resolvconf
412
413 soff openvpn
414
415
416 if [[ $(debian-codename) == etiona ]]; then
417 # ip6tables stopped loading on boot. openvpn has reduced capability set,
418 # so running iptables as part of openvpn startup wont work. This should do it.
419 pi iptables-persistent
420 cat >/etc/iptables/rules.v6 <<'EOF'
421 *mangle
422 COMMIT
423 *nat
424 COMMIT
425 EOF
426 # load it now.
427 m ip6tables -S >/dev/null
428 fi
429
430 # our nostart pi fails to avoid enabling
431
432
433 # * Mail clean cronjob
434
435 u /etc/systemd/system/mailclean.timer <<'EOF'
436 [Unit]
437 Description=Run mailclean daily
438
439 [Timer]
440 OnCalendar=monthly
441
442 [Install]
443 WantedBy=timers.target
444 EOF
445
446 u /etc/systemd/system/mailclean.service <<EOF
447 [Unit]
448 Description=Delete and archive old mail files
449 After=multi-user.target
450
451 [Service]
452 User=$u
453 Type=oneshot
454 ExecStart=/usr/local/bin/sysd-mail-once mailclean /a/bin/distro-setup/mailclean
455 EOF
456
457 # * postgrey
458
459
460 u /etc/default/postgrey <<'EOF'
461 POSTGREY_OPTS="--exim --unix=/var/run/postgrey/postgrey.sock --retry-window=4 --max-age=60"
462 EOF
463
464 # * clamav
465
466 m usermod -a -G Debian-exim clamav
467
468 u /etc/systemd/system/clamav-daemon.service.d/fix.conf <<EOF
469 [Service]
470 ExecStartPre=-/bin/mkdir -p /var/run/clamav
471 ExecStartPre=/bin/chown clamav /var/run/clamav
472 EOF
473
474 # * mail vpn config
475
476 # old.
477 #vpnser=mailvpn.service
478 # note: this hangs if it cant resolv the endpoint. we
479 # want it to just retry in the background. i just use a static ip instead.
480 #
481 # Note: at least on t10, on reboot, the service fails to come up according to systemd, but
482 # in reality it is up and working, then it tries to restart infinitely, and fails
483 # because it detects that the interface exists.
484 #
485 # failing output:
486 #
487 # Aug 02 21:59:27 sy wg-quick[2092]: [#] sysctl -q net.ipv4.conf.all.src_valid_mark=1
488 # Aug 02 21:59:27 sy wg-quick[2248]: [#] iptables-restore -n
489 # 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?
490 # Aug 02 21:59:27 sy wg-quick[2259]: [#] iptables-restore -n
491 # 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?
492 # Aug 02 21:59:27 sy systemd[1]: wg-quick@wgmail.service: Main process exited, code=exited, status=4/NOPERMISSION
493
494
495 # successful output.
496 # Aug 03 14:12:47 sy wg-quick[711336]: [#] sysctl -q net.ipv4.conf.all.src_valid_mark=1
497 # Aug 03 14:12:47 sy wg-quick[711384]: [#] iptables-restore -n
498 # Aug 03 14:12:47 sy wg-quick[711336]: [#] ping -w10 -c1 10.8.0.1 ||:
499 # Aug 03 14:12:47 sy wg-quick[711389]: PING 10.8.0.1 (10.8.0.1) 56(84) bytes of data.
500 # 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
501 # Aug 03 14:12:47 sy wg-quick[711389]: --- 10.8.0.1 ping statistics ---
502 # Aug 03 14:12:47 sy wg-quick[711389]: 1 packets transmitted, 1 received, 0% packet loss, time 0ms
503 # Aug 03 14:12:47 sy wg-quick[711389]: rtt min/avg/max/mdev = 72.993/72.993/72.993/0.000 ms
504 # Aug 03 14:12:47 sy systemd[1]: Finished WireGuard via wg-quick(8) for wgmail.
505 # Aug 02 21:59:27 sy systemd[1]: wg-quick@wgmail.service: Failed with result 'exit-code'.
506 # Aug 02 21:59:27 sy systemd[1]: Failed to start WireGuard via wg-quick(8) for wgmail.
507 # Aug 02 21:59:47 sy systemd[1]: wg-quick@wgmail.service: Scheduled restart job, restart counter is at 1.
508 # Aug 02 21:59:47 sy systemd[1]: Stopped WireGuard via wg-quick(8) for wgmail.
509 # Aug 02 21:59:47 sy systemd[1]: Starting WireGuard via wg-quick(8) for wgmail...
510 # Aug 02 21:59:47 sy wg-quick[3424]: wg-quick: `wgmail' already exists
511 # Aug 02 21:59:47 sy systemd[1]: wg-quick@wgmail.service: Main process exited, code=exited, status=1/FAILURE
512 # Aug 02 21:59:47 sy systemd[1]: wg-quick@wgmail.service: Failed with result 'exit-code'.
513 # Aug 02 21:59:47 sy systemd[1]: Failed to start WireGuard via wg-quick(8) for wgmail.
514
515
516 # According to iptables -S and iptables -t nat -S,
517 # there are no modifications to iptables rules on a succsfull run,
518 # and
519
520 vpnser=wg-quick@wgmail.service
521
522 case $HOSTNAME in
523 $MAIL_HOST)
524 rsync -aiSAX --chown=root:root --chmod=g-s /p/c/filesystem/etc/wireguard/ /etc/wireguard
525 bindpaths="/etc/127.0.0.1-resolv:/run/systemd/resolve /etc/basic-nsswitch:/etc/resolved-nsswitch:norbind"
526 ;;&
527 bk)
528 bindpaths="/etc/10.173.8.1-resolv:/etc/127.0.0.1-resolv"
529 ;;&
530 *)
531 d=/p/c/machine_specific/$HOSTNAME/filesystem/etc/wireguard/
532 if [[ -d $d ]]; then
533 rsync -aiSAX --chown=root:root --chmod=g-s $d /etc/wireguard
534 fi
535 ;;
536 esac
537
538 case $HOSTNAME in
539 li) : ;;
540 *)
541 u /etc/systemd/system/wg-quick@wgmail.service.d/override.conf <<EOF
542 [Unit]
543 Requires=mailnn.service
544 JoinsNamespaceOf=mailnn.service
545 BindsTo=mailnn.service
546 StartLimitIntervalSec=0
547
548 [Service]
549 PrivateNetwork=true
550 # i dont think we need any of these, but it doesnt hurt to stay consistent
551 BindPaths=$bindpaths
552
553 Restart=on-failure
554 RestartSec=20
555 EOF
556 ;;
557 esac
558
559
560 # https://selivan.github.io/2017/12/30/systemd-serice-always-restart.html
561 u /etc/systemd/system/mailvpn.service <<EOF
562 [Unit]
563 Description=OpenVPN tunnel for mail
564 After=syslog.target network-online.target mailnn.service
565 Wants=network-online.target
566 Documentation=man:openvpn(8)
567 Documentation=https://community.openvpn.net/openvpn/wiki/Openvpn24ManPage
568 Documentation=https://community.openvpn.net/openvpn/wiki/HOWTO
569 # needed to continually restatr
570 JoinsNamespaceOf=mailnn.service
571 BindsTo=mailnn.service
572 StartLimitIntervalSec=0
573
574 [Service]
575 Type=notify
576 RuntimeDirectory=openvpn-client
577 RuntimeDirectoryMode=0710
578 WorkingDirectory=/etc/openvpn/client
579 ExecStart=/usr/sbin/openvpn --suppress-timestamps --nobind --config /etc/openvpn/client/mail.conf
580 #CapabilityBoundingSet=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SYS_CHROOT CAP_DAC_OVERRIDE
581 LimitNPROC=10
582 # DeviceAllow=/dev/null rw
583 # DeviceAllow=/dev/net/tun rw
584 PrivateNetwork=true
585 # in the network namespace, we cant connect to systemd-resolved on 127.0.0.53,
586 # because of
587 # https://unix.stackexchange.com/questions/445782/how-to-allow-systemd-resolved-to-listen-to-an-interface-other-than-loopback
588 # there is a workaround there, but i dont think its really worth it,
589 # the mail server is fine with a static dns anyways.
590 # This thread is also interesting,
591 # https://github.com/slingamn/namespaced-openvpn/issues/7
592 # todo: the iptables rule at the bottom could be useful to prevent
593 # dns from leaking in my network namespaced vpn.
594 # I also like the idea of patching systemd-resolved so it
595 # will listen on other interfaces, but its not worth my time.
596 BindPaths=$bindpaths
597 Restart=always
598 # time to sleep before restarting a service
599 RestartSec=20
600
601 [Install]
602 WantedBy=multi-user.target
603 EOF
604
605 u /etc/systemd/system/mailnnroute.service <<'EOF'
606 [Unit]
607 Description=Network routing for mailnn
608 After=syslog.target network-online.target mailnn.service
609 Wants=network-online.target
610 JoinsNamespaceOf=mailnn.service
611 BindsTo=mailnn.service
612 StartLimitIntervalSec=0
613
614 [Service]
615 Type=simple
616 RemainAfterExit=true
617 PrivateNetwork=true
618 ExecStart=/usr/bin/flock -w 20 /tmp/newns.flock /a/bin/newns/newns -n 10.173.8 start mail
619 ExecStop=/usr/bin/flock -w 20 /tmp/newns.flock /a/bin/newns/newns stop mail
620 Restart=always
621 RestartSec=20
622
623
624 [Install]
625 WantedBy=multi-user.target
626 EOF
627
628 #
629 u /etc/systemd/system/mailnn.service <<'EOF'
630 [Unit]
631 Description=Network Namespace for mail vpn service that will live forever and cant fail
632 After=syslog.target network-online.target
633 Wants=network-online.target
634
635 [Service]
636 Type=simple
637 PrivateNetwork=true
638 ExecStart=/bin/sleep infinity
639
640 [Install]
641 WantedBy=multi-user.target
642 EOF
643
644 u /etc/systemd/system/mailbindwatchdog.service <<EOF
645 [Unit]
646 Description=Watchdog to restart services relying on systemd-resolved dir
647 After=syslog.target network-online.target
648 Wants=network-online.target
649 BindsTo=mailnn.service
650
651 [Service]
652 Type=simple
653 ExecStart=/usr/local/bin/mailbindwatchdog $vpnser ${nn_progs[@]} unbound.service radicale.service
654 Restart=always
655 # time to sleep before restarting a service
656 RestartSec=10
657
658 [Install]
659 WantedBy=multi-user.target
660 EOF
661
662
663
664 # old service name
665 rm -fv /etc/systemd/system/openvpn-client-mail@.service
666
667 # We use a local unbound because systemd-resolved wont accept our
668 # request, it will only listen to 127.0.0.53 in the main network
669 # namespace, and rejected feature requests to change that (although I
670 # could change the code and recompile), but anyways, that could answer
671 # with things specific to the lan that aren't applicable in this
672 # namespace, and since unbound is a recursive resolver, it means we just
673 # use our own ip against dnsbl rate limits.
674 #
675 # If we ever notice this change, chattr +i on it
676 # trust-ad is used in t10+, glibc 2.31
677
678 u /etc/127.0.0.1-resolv/stub-resolv.conf <<'EOF'
679 nameserver 127.0.0.1
680 options edns0 trust-ad
681 EOF
682
683 u /etc/127.0.0.53-resolv/stub-resolv.conf <<'EOF'
684 nameserver 127.0.0.53
685 options edns0 trust-ad
686 EOF
687
688
689 u /etc/10.173.8.1-resolv/stub-resolv.conf <<'EOF'
690 nameserver 10.173.8.1
691 options edns0 trust-ad
692 EOF
693
694 # this is just a bug fix for trisquel.
695 f=/etc/apparmor.d/usr.sbin.unbound
696 line="/usr/sbin/unbound flags=(attach_disconnected) {"
697 if ! grep -qFx "$line" $f; then
698 badline="/usr/sbin/unbound {"
699 if ! grep -qFx "$badline" $f; then
700 err expected line in $f not found
701 fi
702 sed -i "s,^$badline$,$line," $f
703 if systemctl is-active apparmor &>/dev/null; then
704 m systemctl reload apparmor
705 fi
706 fi
707
708 # note: anything added to nn_progs needs corresponding rm
709 # down below in the host switch
710 nn_progs=(exim4)
711 if mailhost; then
712 # Note dovecots lmtp doesnt need to be in the same nn to accept delivery.
713 # Its in the nn so remote clients can connect to it.
714 nn_progs+=(spamassassin dovecot)
715 fi
716
717 case $HOSTNAME in
718 $MAIL_HOST)
719 # todo, should this be after vpn service
720 u /etc/systemd/system/unbound.service.d/nn.conf <<EOF
721 [Unit]
722 After=mailnn.service
723 JoinsNamespaceOf=mailnn.service
724 BindsTo=mailnn.service
725 StartLimitIntervalSec=0
726
727 [Service]
728 PrivateNetwork=true
729 # note the nsswitch bind is actually not needed for bk, but
730 # its the same file so it does no harm.
731 BindPaths=$bindpaths
732
733 Restart=always
734 RestartSec=20
735 EOF
736
737 # sooo, there are a few ways to get traffic from the mail network
738 # namespace to go over the wghole.
739 #
740 #1: unify the mail vpn and wghole
741 # into 1 network. this seems simple and logical, so I'm doing it.
742 # One general downside is tying things together, if I need to mess
743 # with one thing, it breaks the other. Oh well for now.
744 #
745 # 2. We can route 10.5.3.0/24 out of the mail nn and nat it into wghole.
746 #
747 # 3. We can setup the routing to happen on li, which seemed like I
748 # just needed to add 10.8.0.4/24 to AllowedIPs in at least the
749 # wghole clients, but I think that is kind of hacky and breaks ipv4
750 # routing within the mailvpn, it happened to work just because exim
751 # prefers ipv6 and that was also available in the mailvpn.
752 #
753 # 4. Put the hole interface into the mail network namespace. This
754 # doesn't work if the mail vpn is wg. For openvpn, it bypasses the
755 # vpn routing and establishes a direct connection. I only use the
756 # hole vpn for randomish things, it should be fine to join the mail
757 # nn for that. There should be some way to fix the routing issue
758 # by doing manual routing, but that doesn't seem like a good use of time.
759 # relevant:
760 # https://www.wireguard.com/netns/#
761 #
762 # for wireguard debugging
763 # echo module wireguard +p > /sys/kernel/debug/dynamic_debug/control
764 # dmesg -w
765
766 ;;&
767 $MAIL_HOST|bk)
768 for unit in ${nn_progs[@]}; do
769 u /etc/systemd/system/$unit.service.d/nn.conf <<EOF
770 [Unit]
771
772 # Wants appears better than requires because with requires,
773 # if the vpnser fails to start, this service won't get run at
774 # all, even if the vpnser starts on an automatic restart.
775
776 Wants=$vpnser
777 After=network.target mailnn.service $vpnser
778 JoinsNamespaceOf=mailnn.service
779 BindsTo=mailnn.service
780 StartLimitIntervalSec=0
781
782 [Service]
783 PrivateNetwork=true
784 # note the nsswitch bind is actually not needed for bk, but
785 # its the same file so it does no harm.
786 BindPaths=$bindpaths
787
788 Restart=always
789 RestartSec=20
790 EOF
791 done
792 ;;
793 *)
794 for unit in exim4 spamassassin dovecot unbound; do
795 f=/etc/systemd/system/$unit.service.d/nn.conf
796 if [[ -s $f ]]; then
797 rm -fv $f
798 reload=true
799 fi
800 done
801 ;;
802 esac
803
804 # * wghole (another mail vpn)
805
806 if $bhost_t; then
807 u /etc/systemd/system/wg-quick@wghole.service.d/override.conf <<'EOF'
808 [Unit]
809 StartLimitIntervalSec=0
810
811 [Service]
812 Restart=on-failure
813 RestartSec=20
814 EOF
815 fi
816
817 # * spamassassin config
818 u /etc/sysctl.d/80-iank-mail.conf <<'EOF'
819 # see exim spec
820 net.netfilter.nf_conntrack_tcp_timeout_close_wait = 120
821 EOF
822 if $ur; then
823 m sysctl -p
824 fi
825
826 u /etc/spamassassin/mylocal.cf <<'EOF'
827 # this is mylocal.cf because the normal local.cf has a bunch of upstream stuff i dont want to mess with
828
829 # /usr/share/doc/exim4-base/README.Debian.gz:
830 # SpamAssassin's default report should not be used in a add_header
831 # statement since it contains empty lines. (This triggers e.g. Amavis'
832 # warning "BAD HEADER SECTION, Improper folded header field made up
833 # entirely of whitespace".) This is a safe, terse alternative:
834 clear_report_template
835 report (_SCORE_ / _REQD_ requ) _TESTSSCORES(,)_ autolearn=_AUTOLEARN
836 uridnsbl_skip_domain iankelling.org
837 uridnsbl_skip_domain amnimal.ninja
838 uridnsbl_skip_domain expertpathologyreview.com
839 uridnsbl_skip_domain zroe.org
840 EOF
841
842 # 2020-10-19 remove old file. remove this when all hosts updated
843 rm -fv /etc/systemd/system/spamddnsfix.{timer,service}
844
845 u /etc/default/spamassassin <<'EOF'
846 # defaults plus debugging flags for an issue im having
847 OPTIONS="--create-prefs --max-children 5 --helper-home-dir"
848 PIDFILE="/var/run/spamd.pid"
849 # my additions
850 NICE="--nicelevel 15"
851 CRON=1
852 EOF
853 ##### end spamassassin config
854
855
856 # * Update mail cert
857
858
859 ## needed only for openvpn mail vpn.
860 # if [[ -e /p/c/filesystem ]]; then
861 # # note, man openvpn implies we could just call mail-route on vpn startup/shutdown with
862 # # systemd, buuut it can remake the tun device unexpectedly, i got this in the log
863 # # after my internet was down for a bit:
864 # # NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.
865 # m /a/exe/vpn-mk-client-cert -b mailclient -n mail li.iankelling.org
866 # fi
867
868 # With openvpn, I didn't get around to persisting the openvpn
869 # cert/configs into /p/c/machine_specific/bk, so I had this case to
870 # manually get the cert. However, we aren't using openvpn anymore, so it
871 # is commented out.
872 #
873 # case $HOSTNAME in
874 # bk)
875 # if [[ ! -e /etc/openvpn/client/mail.conf ]]; then
876 # 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
877 # exit 1
878 # fi
879 # ;;
880 # esac
881
882 m rsync -aiSAX --chown=root:root --chmod=g-s /a/bin/ds/mail-cert-cron /usr/local/bin
883
884 u /etc/systemd/system/mailcert.service <<'EOF'
885 [Unit]
886 Description=Mail cert rsync
887 After=multi-user.target
888
889 [Service]
890 Type=oneshot
891 ExecStart=/usr/local/bin/sysd-mail-once mailcert /usr/local/bin/mail-cert-cron
892 EOF
893 u /etc/systemd/system/mailcert.timer <<'EOF'
894 [Unit]
895 Description=Run mail-cert once a day
896
897 [Timer]
898 OnCalendar=daily
899
900 [Install]
901 WantedBy=timers.target
902 EOF
903
904
905 wghost=${HOSTNAME}wg.b8.nz
906 if $bhost_t && [[ ! -e /etc/exim4/certs/$wghost/privkey.pem ]]; then
907 certbot -n --manual-public-ip-logging-ok --eff-email --agree-tos -m letsencrypt@iankelling.org \
908 certonly --manual --preferred-challenges=dns \
909 --manual-auth-hook /a/bin/ds/le-dns-challenge \
910 --manual-cleanup-hook /a/bin/ds/le-dns-challenge-cleanup \
911 --deploy-hook /a/bin/ds/le-exim-deploy -d $wghost
912 fi
913
914 # * fail2ban
915
916 # todo: test that these configs actually work, eg run
917 # s iptables-exim -S
918 # and see someone is banned.
919
920 sed 's/^ *before *= *iptables-common.conf/before = iptables-common-exim.conf/' \
921 /etc/fail2ban/action.d/iptables-multiport.conf| i /etc/fail2ban/action.d/iptables-exim.conf
922 u /etc/fail2ban/action.d/iptables-common-exim.conf <<'EOF'
923 # iank: same as iptables-common, except iptables is iptables-exim, ip6tables is ip6tables-exim
924
925 # Fail2Ban configuration file
926 #
927 # Author: Daniel Black
928 #
929 # This is a included configuration file and includes the definitions for the iptables
930 # used in all iptables based actions by default.
931 #
932 # The user can override the defaults in iptables-common.local
933 #
934 # Modified: Alexander Koeppe <format_c@online.de>, Serg G. Brester <serg.brester@sebres.de>
935 # made config file IPv6 capable (see new section Init?family=inet6)
936
937 [INCLUDES]
938
939 after = iptables-blocktype.local
940 iptables-common.local
941 # iptables-blocktype.local is obsolete
942
943 [Definition]
944
945 # Option: actionflush
946 # Notes.: command executed once to flush IPS, by shutdown (resp. by stop of the jail or this action)
947 # Values: CMD
948 #
949 actionflush = <iptables> -F f2b-<name>
950
951
952 [Init]
953
954 # Option: chain
955 # Notes specifies the iptables chain to which the Fail2Ban rules should be
956 # added
957 # Values: STRING Default: INPUT
958 chain = INPUT
959
960 # Default name of the chain
961 #
962 name = default
963
964 # Option: port
965 # Notes.: specifies port to monitor
966 # Values: [ NUM | STRING ] Default:
967 #
968 port = ssh
969
970 # Option: protocol
971 # Notes.: internally used by config reader for interpolations.
972 # Values: [ tcp | udp | icmp | all ] Default: tcp
973 #
974 protocol = tcp
975
976 # Option: blocktype
977 # Note: This is what the action does with rules. This can be any jump target
978 # as per the iptables man page (section 8). Common values are DROP
979 # REJECT, REJECT --reject-with icmp-port-unreachable
980 # Values: STRING
981 blocktype = REJECT --reject-with icmp-port-unreachable
982
983 # Option: returntype
984 # Note: This is the default rule on "actionstart". This should be RETURN
985 # in all (blocking) actions, except REJECT in allowing actions.
986 # Values: STRING
987 returntype = RETURN
988
989 # Option: lockingopt
990 # Notes.: Option was introduced to iptables to prevent multiple instances from
991 # running concurrently and causing irratic behavior. -w was introduced
992 # in iptables 1.4.20, so might be absent on older systems
993 # See https://github.com/fail2ban/fail2ban/issues/1122
994 # Values: STRING
995 lockingopt = -w
996
997 # Option: iptables
998 # Notes.: Actual command to be executed, including common to all calls options
999 # Values: STRING
1000 iptables = /usr/local/bin/iptables-exim <lockingopt>
1001
1002
1003 [Init?family=inet6]
1004
1005 # Option: blocktype (ipv6)
1006 # Note: This is what the action does with rules. This can be any jump target
1007 # as per the iptables man page (section 8). Common values are DROP
1008 # REJECT, REJECT --reject-with icmp6-port-unreachable
1009 # Values: STRING
1010 blocktype = REJECT --reject-with icmp6-port-unreachable
1011
1012 # Option: iptables (ipv6)
1013 # Notes.: Actual command to be executed, including common to all calls options
1014 # Values: STRING
1015 iptables = /usr/local/bin/ip6tables-exim <lockingopt>
1016 EOF
1017
1018 u /etc/fail2ban/jail.d/exim.local <<'EOF'
1019 [exim]
1020 enabled = true
1021 port = 25,587
1022 filter = exim
1023 banaction = iptables-exim
1024
1025 # 209.51.188.13 = mail.fsf.org
1026 # 2001:470:142::13 = mail.fsf.org
1027 # 209.51.188.92 = eggs.gnu.org
1028 # 2001:470:142:3::10 = eggs.gnu.org
1029 # 72.14.176.105 2600:3c00:e000:280::2 = mail.iankelling.org
1030 # 10.173.8.1 = non-nn net
1031 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
1032 EOF
1033 if $ur; then
1034 m systemctl restart fail2ban
1035 fi
1036
1037 # * common exim4 config
1038
1039
1040 ## old, not using forward files anymore
1041 rm -fv $uhome/.forward /root/.forward
1042
1043
1044 # Make all system users be aliases. preventative
1045 # prevents things like cron mail for user without alias
1046 awk 'BEGIN { FS = ":" } ; $6 !~ /^\/home/ || $7 ~ /\/nologin$/ { print $1 }' /etc/passwd| while read -r user; do
1047 if [[ ! $user ]]; then
1048 continue
1049 fi
1050 if ! grep -q "^$user:" /etc/aliases; then
1051 echo "$user: root" |m tee -a /etc/aliases
1052 fi
1053 done
1054
1055
1056 awk 'BEGIN { FS = ":" } ; $6 ~ /^\/home/ && $7 !~ /\/nologin$/ { print $1 }' /etc/passwd| while read -r user; do
1057 case $HOSTNAME in
1058 $MAIL_HOST)
1059 sed -i "/^user:/d" /etc/aliases
1060 ;;
1061 *)
1062 if ! grep -q "^$user:" /etc/aliases; then
1063 echo "$user: root" |m tee -a /etc/aliases
1064 fi
1065 ;;
1066 esac
1067 done
1068
1069
1070 . /a/bin/bash_unpublished/priv-mail-setup
1071
1072
1073 m gpasswd -a iank adm #needed for reading logs
1074
1075 ### make local bounces go to normal maildir
1076 # local mail that bounces goes to /Maildir or /root/Maildir
1077 dirs=(/m/md/bounces/{cur,tmp,new})
1078 m mkdir -p ${dirs[@]}
1079 m chown iank:iank /m /m/md
1080 m ln -sfT /m/md /m/iank
1081 m chmod 771 /m /m/md
1082 m chown -R $u:Debian-exim /m/md/bounces
1083 m chmod 775 ${dirs[@]}
1084 m usermod -a -G Debian-exim $u
1085 for d in /Maildir /root/Maildir; do
1086 if [[ ! -L $d ]]; then
1087 m rm -rf $d
1088 fi
1089 m ln -sf -T /m/md/bounces $d
1090 done
1091
1092 # dkim, client passwd file
1093 files=(/p/c/machine_specific/$HOSTNAME/filesystem/etc/exim4/*)
1094 f=/p/c/filesystem/etc/exim4/passwd.client
1095 if [[ -e $f ]]; then
1096 files+=($f)
1097 fi
1098 if (( ${#files[@]} )); then
1099 m rsync -ahhi --chown=root:Debian-exim --chmod=0640 \
1100 ${files[@]} /etc/exim4
1101 fi
1102
1103 # By default, only 10 days of logs are kept. increase that.
1104 # And dont compress, I look back at logs too often and
1105 # dont need the annoyance of decompressing them all the time.
1106 m sed -ri '/^\s*compress\s*$/d;s/^(\s*rotate\s).*/\11000/' /etc/logrotate.d/exim4-base
1107 files=(/var/log/exim4/*.gz)
1108 if (( ${#files[@]} )); then
1109 gunzip ${files[@]}
1110 fi
1111
1112 ## disabled. not using .forward files, but this is still interesting
1113 ## for reference.
1114 # ## https://blog.dhampir.no/content/make-exim4-on-debian-respect-forward-and-etcaliases-when-using-a-smarthost
1115 # # i only need .forwards, so just doing that one.
1116 # cd /etc/exim4/conf.d/router
1117 # b=userforward_higher_priority
1118 # # replace the router name so it is unique
1119 # sed -r s/^\\S+:/$b:/ 600_exim4-config_userforward >175_$b
1120 rm -fv /etc/exim4/conf.d/router/175_userforward_higher_priority
1121
1122 # todo, consider 'separate' in etc/exim4.conf, could it help on busy systems?
1123
1124 # alerts is basically the postmaster address
1125 m sed -i --follow-symlinks -f - /etc/aliases <<EOF
1126 \$a root: alerts@iankelling.org
1127 /^root:/d
1128 EOF
1129
1130 cat >/etc/exim4/conf.d/rewrite/34_iank_rewriting <<'EOF'
1131 ncsoft@zroe.org graceq2323@gmail.com hE
1132 EOF
1133
1134 # old name
1135 rm -fv /etc/exim4/conf.d/retry/37_retry
1136
1137 cat >/etc/exim4/conf.d/retry/17_retry <<'EOF'
1138 # Retry fast for my own domains
1139 iankelling.org * F,1d,4m;F,14d,1h
1140 amnimal.ninja * F,1d,4m;F,14d,1h
1141 expertpathologyreview.com * F,1d,4m;F,14d,1h
1142 je.b8.nz * F,1d,4m;F,14d,1h
1143 zroe.org * F,1d,4m;F,14d,1h
1144 eximbackup.b8.nz * F,1d,4m;F,14d,1h
1145
1146 # The spec says the target domain will be used for temporary host errors,
1147 # but i've found that isn't correct, the hostname is required
1148 # at least sometimes.
1149 nn.b8.nz * F,1d,4m;F,14d,1h
1150 defaultnn.b8.nz * F,1d,4m;F,14d,1h
1151 mx.iankelling.org * F,1d,4m;F,14d,1h
1152 bk.b8.nz * F,1d,4m;F,14d,1h
1153 eggs.gnu.org * F,1d,4m;F,14d,1h
1154 fencepost.gnu.org * F,1d,4m;F,14d,1h
1155
1156 # afaik our retry doesnt need this, but just using everything
1157 mx.amnimal.ninja * F,1d,4m;F,14d,1h
1158 mx.expertpathologyreview.com * F,1d,4m;F,14d,1h
1159
1160
1161 mail.fsf.org * F,1d,15m;F,14d,1h
1162 EOF
1163
1164
1165 rm -vf /etc/exim4/conf.d/main/000_localmacros # old filename
1166
1167 # separate file so without quoted EOF for convenience
1168 cat >/etc/exim4/conf.d/main/000_local2 <<EOF
1169 # normally empty, I set this so I can set the envelope address
1170 # when doing mail redelivery to invoke filters. Also allows
1171 # me exiqgrep and stuff.
1172 MAIN_TRUSTED_GROUPS = $u
1173 EOF
1174
1175 cd /etc/exim4
1176 {
1177 for f in *-private.pem; do
1178 echo ${f%-private.pem}
1179 done
1180 } | i /etc/exim4/conf.d/my-dkim-domains
1181
1182 if grep -Fq REMOTE_SMTP_SMARTHOST_TLS_VERIFY_HOSTS \
1183 /etc/exim4/conf.d/transport/10_exim4-config_transport-macros; then
1184 cat >/etc/exim4/conf.d/transport/11_iank <<'EOF'
1185 # This unsets the default macro defined in on t11 in
1186 # /etc/exim4/conf.d/transport/10_exim4-config_transport-macros
1187 # It seems like a very odd choice that this has become
1188 # the default in t11. Normal smarthost clients use username/password
1189 # auth. Oh well.
1190 REMOTE_SMTP_SMARTHOST_TLS_VERIFY_HOSTS ==
1191 EOF
1192 else
1193 rm -f /etc/exim4/conf.d/transport/11_iank
1194 fi
1195
1196 cat >/etc/exim4/conf.d/main/000_local <<'EOF'
1197 MAIN_TLS_ENABLE = true
1198
1199 # require tls connections for all smarthosts
1200 REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS = *
1201
1202 # debian exim config added this in 2016 or so?
1203 # it's part of the smtp spec, to limit lines to 998 chars
1204 # but a fair amount of legit mail does not adhere to it. I don't think
1205 # this should be default, like it says in
1206 # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=828801
1207 # todo: the bug for introducing this was about headers, but
1208 # the fix maybe is for all lines? one says gmail rejects, the
1209 # other says gmail does not reject. figure out and open a new bug.
1210 IGNORE_SMTP_LINE_LENGTH_LIMIT = true
1211
1212 # more verbose logs. used to use +all, but made it less for more efficiency.
1213 MAIN_LOG_SELECTOR = -tls_cipher -tls_certificate_verified +pid +received_recipients +received_sender +sender_on_delivery +return_path_on_delivery +msg_id_created +subject +address_rewrite +smtp_confirmation
1214
1215 # Based on spec, seems like a good idea to be nice.
1216 smtp_return_error_details = true
1217
1218 # default is 10. when exim has been down for a bit, fsf mailserver
1219 # will do a big send in one connection, then exim decides to put
1220 # the messages in the queue instead of delivering them, to avoid
1221 # spawning too many delivery processes. This is the same as the
1222 # fsfs value. And the corresponding one for how many messages
1223 # to send out in 1 connection remote_max_parallel = 256
1224 smtp_accept_queue_per_connection = 500
1225
1226
1227 DKIM_CANON = relaxed
1228 DKIM_SELECTOR = li
1229
1230
1231 # The file is based on the outgoing domain-name in the from-header.
1232 # sign if key exists
1233 DKIM_PRIVATE_KEY = ${if exists{/etc/exim4/${dkim_domain}-private.pem} {/etc/exim4/${dkim_domain}-private.pem}}
1234
1235 # most of the ones that gmail seems to use.
1236 # Exim has horrible default of signing unincluded
1237 # list- headers since they got mentioned in an
1238 # rfc, but this messes up mailing lists, like gnu/debian which want to
1239 # keep your dkim signature intact but add list- headers.
1240 DKIM_SIGN_HEADERS = mime-version:in-reply-to:references:from:date:subject:to
1241
1242 domainlist local_hostnames = ! je.b8.nz : ! bk.b8.nz : *.b8.nz : b8.nz
1243
1244 hostlist iank_trusted = <; \
1245 # veth0
1246 10.173.8.1 ; \
1247 # li li_ip6
1248 72.14.176.105 ; 2600:3c00::f03c:91ff:fe6d:baf8 ; \
1249 # li_vpn_net li_vpn_net_ip6s
1250 10.8.0.0/24; 2600:3c00:e000:280::/64 ; 2600:3c00:e002:3800::/56 ; \
1251 # bk bk_ip6
1252 85.119.83.50 ; 2001:ba8:1f1:f0c9::2 ; \
1253 # je je_ipv6
1254 85.119.82.128 ; 2001:ba8:1f1:f09d::2 ; \
1255 # fsf_mit_net fsf_mit_net_ip6 fsf_net fsf_net_ip6 fsf_office_net
1256 18.4.89.0/24 ; 2603:3005:71a:2e00::/64 ; 209.51.188.0/24 ; 2001:470:142::/48 ; 74.94.156.208/28
1257
1258
1259 # this is the default delay_warning_condition, plus matching on local_domains.
1260 # If I have some problem with my local system that causes delayed delivery,
1261 # I dont want to send warnings out to non-local domains.
1262 delay_warning_condition = ${if or {\
1263 { !eq{$h_list-id:$h_list-post:$h_list-subscribe:}{} }\
1264 { match{$h_precedence:}{(?i)bulk|list|junk} }\
1265 { match{$h_auto-submitted:}{(?i)auto-generated|auto-replied} }\
1266 { match_domain{$domain}{+local_domains} }\
1267 } {no}{yes}}
1268
1269
1270 # enable 587 in addition to the default 25, so that
1271 # i can send mail where port 25 is firewalled by isp
1272 daemon_smtp_ports = 25 : 587
1273 # default of 25, can get stuck when catching up on mail
1274 smtp_accept_max = 400
1275 smtp_accept_reserve = 100
1276 smtp_reserve_hosts = +iank_trusted
1277
1278 # Rules that make receiving more liberal should be on backup hosts
1279 # so that we dont reject mail accepted by MAIL_HOST
1280 LOCAL_DENY_EXCEPTIONS_LOCAL_ACL_FILE = /etc/exim4/conf.d/local_deny_exceptions_acl
1281 EOF
1282
1283 if dpkg --compare-versions "$(dpkg-query -f='${Version}\n' --show exim4)" ge 4.94; then
1284 cat >>/etc/exim4/conf.d/main/000_local <<'EOF'
1285 # In t11, we cant do the old anymore because this is tainted data used in a file lookup.
1286 # /usr/share/doc/exim4/NEWS.Debian.gz suggests to use lookups to untaint data.
1287 DKIM_DOMAIN = ${lookup {${domain:$rh_from:}}lsearch,ret=key{/etc/exim4/conf.d/my-dkim-domains}}
1288 EOF
1289 else
1290 cat >>/etc/exim4/conf.d/main/000_local <<'EOF'
1291 # From comments in
1292 # https://debian-administration.org/article/718/DKIM-signing_outgoing_mail_with_exim4
1293 # and its best for this to align https://tools.ietf.org/html/rfc7489#page-8
1294 # There could be some circumstance when the
1295 # from: isnt our domain, but the envelope sender is
1296 # and so still want to sign, but I cant think of any case.
1297 DKIM_DOMAIN = ${lc:${domain:$rh_from:}}
1298 EOF
1299 fi
1300
1301 rm -fv /etc/exim4/rcpt_local_acl # old path
1302
1303 u /etc/exim4/conf.d/local_deny_exceptions_acl <<'EOF'
1304 # This acl already exists in rcpt, this just makes it more widespread.
1305 # See the comment there for its rationale. The reason it needs to be
1306 # more widespread is that I've turned on sender verification, but cron
1307 # emails can fail sender verification since I may be in a network that
1308 # doesn't have my local dns.
1309 accept
1310 authenticated = *
1311
1312 # i setup a local programs smtp to mail.iankelling.org, this
1313 # skips sender verification for it.
1314 accept
1315 hosts = 10.173.8.1
1316 EOF
1317
1318 rm -fv /etc/exim4/data_local_acl # old path
1319
1320 u /etc/exim4/conf.d/data_local_acl <<'EOF'
1321 # Except for the "condition =", this was
1322 # a comment in the check_data acl. The comment about this not
1323 # being suitable has been changed in newer exim versions. The only thing
1324 # related I found was to
1325 # add the condition =, cuz spamassassin has problems with big
1326 # messages and spammers don't bother with big messages,
1327 # but I've increased the size from 10k
1328 # suggested in official docs, and 100k in the wiki example because
1329 # those docs are rather old and I see a 110k spam message
1330 # pretty quickly looking through my spam folder.
1331
1332 warn
1333 !hosts = +iank_trusted
1334 remove_header = X-Spam_score: X-Spam_score_int : X-Spam_bar : X-Spam_report
1335
1336 warn
1337 !hosts = +iank_trusted
1338 # Smarthosts connect with residential ips and thus get flagged as spam if we do a spam check.
1339 !authenticated = plain_server:login_server
1340 condition = ${if < {$message_size}{5000K}}
1341 spam = Debian-exim:true
1342 add_header = X-Spam_score_int: $spam_score_int
1343 add_header = X-Spam_score: $spam_score
1344 add_header = X-Spam_bar: $spam_bar
1345 add_header = X-Spam_report: $spam_report
1346 add_header = X-Spam_action: $spam_action
1347
1348
1349 #accept
1350 # spf = pass:fail:softfail:none:neutral:permerror:temperror
1351 # dmarc_status = reject:quarantine
1352 # add_header = Reply-to: dmarctest@iankelling.org
1353
1354 EOF
1355
1356
1357 # old file
1358 rm -fv /etc/exim4/conf.d/router/8{8,9}0_backup_copy \
1359 /etc/exim4/conf.d/router/865_backup_redir \
1360 /etc/exim4/conf.d/router/870_backup_local
1361
1362 # It is important for this to exist everywhere except in MAIL_HOST
1363 # non-nn config. Previously, just had it in the nn-config on MAIL_HOST,
1364 # but that is a problem if we change mail host and still have something
1365 # in the queue which was destined for this router, but hosts were
1366 # unreachable, the routers will be reevaluated on the next retry.
1367 u /etc/exim4/conf.d/router/170_backup_copy <<EOF
1368 ### router/900_exim4-config_local_user
1369 #################################
1370
1371 backup_copy:
1372 driver = manualroute
1373 domains = eximbackup.b8.nz
1374 transport = backup_remote
1375 ignore_target_hosts = ${HOSTNAME}wg.b8.nz
1376 # note changes here also require change in passwd.client
1377 route_list = * eximbackup.b8.nz
1378 same_domain_copy_routing = yes
1379 errors_to = alerts@iankelling.org
1380 no_more
1381 EOF
1382
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 u /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 u /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 u /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 u /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 u /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 u /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 u /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 u /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 u /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 u /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 u /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 u /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 u $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 u /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 u $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 u $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 u /etc/php/$phpver/cli/conf.d/30-local.ini <<'EOF'
2481 apc.enable_cli = 1
2482 EOF
2483
2484 u /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 u /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 u /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 u /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 u /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 u /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 u /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 u /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 u /etc/exim4/trusted_configs <<'EOF'
2749 /etc/exim4/my.conf
2750 EOF
2751 ;;
2752 *)
2753 # default file
2754 u /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 u /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 u /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/165_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 u /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 u /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 u /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 u /etc/exim4/conf.d/router/161_backup_redir_nn <<'EOF'
2939 backup_redir_nn:
2940 driver = redirect
2941 # b is just an arbirary short string
2942 data = b@eximbackup.b8.nz
2943 condition = ${if !bool{${lookup{$local_part@$domain}lsearch{/etc/exim4/ignore-sent}{true}}}}
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 u /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 u /etc/exim4/conf.d/rcpt_local_acl <<'EOF'
2967 deny
2968 !authenticated = *
2969 domains = +local_hostnames
2970 message = no relay
2971
2972 # for testing bounce behavior
2973 #deny
2974 # senders = testlist-bounces+test=zroe.org@fsf.org
2975 # message = iank-bounce
2976 EOF
2977 echo|i /etc/exim4/conf.d/router/880_universal_forward
2978
2979
2980 cat >>/etc/exim4/conf.d/main/000_local <<EOF
2981 MAILDIR_HOME_MAILDIR_LOCATION = /m/md/Sent
2982 EOF
2983
2984
2985 u /etc/exim4/conf.d/router/186_sentarchive_nn <<'EOF'
2986 # ian: save a copy of sent mail. i thought of other ways to
2987 # do this, for example, to only save sent mail that is not sent
2988 # from my mail client which saves a copy by default, but in the
2989 # end, it seems simplest to turn that off. We want to save
2990 # external mail sent by smarthosts.
2991 sentarchive_nn:
2992 driver = redirect
2993 domains = ! +local_domains
2994 condition = ${if !bool{${lookup{$local_part@$domain}lsearch{/etc/exim4/ignore-sent}{true}}}}
2995 data = vojdedIdNejyebni@b8.nz
2996 unseen
2997 EOF
2998
2999
3000 # for iank@fsf.org, i have mail.fsf.org forward it to fsf@iankelling.org.
3001 # and also have mail.iankelling.org whitelisted as a relay domain.
3002 # I could avoid that if I changed this to submit to 587 with a
3003 # password like a standard mua.
3004 u /etc/exim4/conf.d/router/188_exim4-config_smarthost <<'EOF'
3005 # ian: copied from /etc/exim4/conf.d/router/200_exim4-config_primary, and added senders = and
3006 # replaced DCsmarthost with hostname
3007 fsfsmarthost:
3008 debug_print = "R: smarthost for $local_part@$domain"
3009 driver = manualroute
3010 domains = ! +local_domains
3011 senders = *@fsf.org
3012 transport = remote_smtp_smarthost
3013 route_list = * mail.fsf.org::587 byname
3014 host_find_failed = ignore
3015 same_domain_copy_routing = yes
3016 no_more
3017
3018 posteosmarthost:
3019 debug_print = "R: smarthost for $local_part@$domain"
3020 driver = manualroute
3021 domains = ! +local_domains
3022 senders = *@posteo.net
3023 transport = remote_smtp_smarthost
3024 route_list = * posteo.de::587 byname
3025 host_find_failed = ignore
3026 same_domain_copy_routing = yes
3027 no_more
3028 EOF
3029
3030 # Greping /etc/exim4, unqualified mails this would end up as
3031 # a return path, so it should go somewhere we will see.
3032 # The debconf output about mailname is as follows:
3033 # The 'mail name' is the domain name used to 'qualify' mail addresses without a domain
3034 # name.
3035 # This name will also be used by other programs. It should be the single, fully
3036 # qualified domain name (FQDN).
3037 # Thus, if a mail address on the local host is foo@example.org, the correct value for
3038 # this option would be example.org.
3039 # This name won\'t appear on From: lines of outgoing messages if rewriting is enabled.
3040 echo iankelling.org > /etc/mailname
3041
3042
3043 # mail.iankelling.org so local imap clients can connect with tls and
3044 # when they happen to not be local.
3045 # todo: this should be 10.8.0.4
3046
3047 /a/exe/cedit nn /etc/hosts <<'EOF' || [[ $? == 1 ]]
3048 # note: i put nn.b8.nz into bind for good measure
3049 10.173.8.2 nn.b8.nz mx.iankelling.org
3050 EOF
3051
3052 # note: systemd-resolved will consult /etc/hosts, dnsmasq wont. this assumes
3053 # weve configured this file in dnsmasq if we are using it.
3054 /a/exe/cedit mail /etc/dnsmasq-servers.conf <<'EOF' || [[ $? == 1 ]]
3055 server=/mx.iankelling.org/127.0.1.1
3056 EOF
3057 # I used to use debconf-set-selections + dpkg-reconfigure,
3058 # which then updates this file
3059 # but the process is slower than updating it directly and then I want to set other things in
3060 # update-exim4.conf.conf, so there's no point.
3061 # The file is documented in man update-exim4.conf,
3062 # except the man page is not perfect, read the bash script to be sure about things.
3063
3064 # The debconf questions output is additional documentation that is not
3065 # easily accessible, but super long, along with the initial default comment in this
3066 # file, so I've saved that into ./mail-notes.conf.
3067 #
3068 # # TODO: remove mx.iankelling.org once systems get updated mail-setup from jan 2022
3069 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
3070 # man page: is used to build the local_domains list, together with "localhost"
3071 # this is duplicated in a later router.
3072 dc_other_hostnames='iankelling.org;zroe.org;r2e.iankelling.org;mx.iankelling.org;!je.b8.nz;!bk.b8.nz;*.b8.nz;b8.nz'
3073 EOF
3074
3075
3076 # dmarc. not used currently
3077 f=/etc/cron.daily/refresh-dmarc-tld-file
3078 cat >$f <<'EOF'
3079 #!/bin/bash
3080 cd /etc
3081 wget -q -N https://publicsuffix.org/list/public_suffix_list.dat
3082 EOF
3083 m chmod 755 $f
3084
3085 ;;
3086 # ** bk
3087 ## we use this host to monitor MAIL_HOST and host a mail server for someone
3088 bk)
3089
3090
3091 /a/exe/cedit nn /etc/hosts <<'EOF' || [[ $? == 1 ]]
3092 10.173.8.2 nn.b8.nz
3093 EOF
3094
3095 sed -r -f - /etc/init.d/exim4 <<'EOF' | i /etc/init.d/exim4in
3096 s,/etc/default/exim4,/etc/default/exim4in,g
3097 s,/run/exim4/exim.pid,/run/exim4/eximin.pid,g
3098 s,(^[ #]*Provides:).*,\1 exim4in,
3099 s,(^[ #]*NAME=).*,\1"exim4in",
3100 EOF
3101 chmod +x /etc/init.d/exim4in
3102 u /etc/systemd/system/exim4in.service.d/alwaysrestart.conf <<'EOF'
3103 [Unit]
3104 # needed to continually restart
3105 StartLimitIntervalSec=0
3106
3107 [Service]
3108 Restart=always
3109 # time to sleep before restarting a service
3110 RestartSec=20
3111 EOF
3112
3113 u /etc/default/exim4in <<'EOF'
3114 # defaults but no queue runner and alternate config dir
3115 QUEUERUNNER='no'
3116 COMMONOPTIONS='-oP /run/exim4/eximin.pid'
3117 UPEX4OPTS='-d /etc/myexim4'
3118 EOF
3119
3120 echo bk.b8.nz > /etc/mailname
3121 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
3122 # man page: is used to build the local_domains list, together with "localhost"
3123 dc_other_hostnames='amnimal.ninja;expertpathologyreview.com;bk.b8.nz'
3124 EOF
3125
3126 ;;
3127 # ** je
3128 je)
3129 echo je.b8.nz > /etc/mailname
3130 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
3131 dc_other_hostnames='je.b8.nz'
3132 EOF
3133 ;;
3134 # ** not MAIL_HOST|bk|je
3135 *)
3136 # this one should be removed for all non mail hosts, but
3137 # bk and je never become mail_host
3138 echo|i /etc/exim4/conf.d/router/195_dnslookup_vpn
3139 echo|i /etc/exim4/conf.d/router/160_backup_redir
3140 echo|i /etc/exim4/conf.d/router/161_backup_redir_nn
3141 echo|i /etc/exim4/conf.d/router/185_sentarchive
3142 echo|i /etc/exim4/conf.d/router/186_sentarchive_nn
3143 echo|i /etc/exim4/conf.d/router/188_exim4-config_smarthost
3144 echo|i /etc/exim4/conf.d/router/190_exim4-config_fsfsmarthost
3145 echo|i /etc/exim4/conf.d/rcpt_local_acl
3146 echo|i /etc/exim4/conf.d/main/000_local-nn
3147 echo|i /etc/exim4/conf.d/clamav_data_acl
3148
3149
3150 if $bhost_t; then
3151 cat >>/etc/exim4/conf.d/main/000_local <<EOF
3152 MAIN_TLS_CERTIFICATE = /etc/exim4/certs/$wghost/fullchain.pem
3153 MAIN_TLS_PRIVATEKEY = /etc/exim4/certs/$wghost/privkey.pem
3154 # so we can maintiain the originals of the backups.
3155 # we wouldnt want this if we were dealing with any other
3156 # local deliveries, but we sent all others to the smarthost
3157 # which then strips the headers.
3158 envelope_to_remove = false
3159 return_path_remove = false
3160 EOF
3161 fi
3162
3163 # catches things like cronjob email
3164 u /etc/exim4/conf.d/router/880_universal_forward <<'EOF'
3165 universal_forward:
3166 driver = redirect
3167 domains = +local_domains
3168 data = alerts@iankelling.org
3169 EOF
3170
3171
3172 for unit in ${nn_progs[@]}; do
3173 f=/etc/systemd/system/$unit.service.d/nn.conf
3174 rm -fv $f
3175 done
3176
3177 # dont i dont care if defaultnn section gets left, it wont
3178 # get used.
3179 echo | /a/exe/cedit nn /etc/hosts || [[ $? == 1 ]]
3180 echo | /a/exe/cedit mail /etc/dnsmasq-servers.conf || [[ $? == 1 ]]
3181
3182 # note: condition duplicated at else
3183 if $bhost_t; then
3184 install -d /bu
3185 install -d -g Debian-exim -o Debian-exim -m 771 /bu/md
3186 if [[ -e /bu/md/cur && $(stat -c %u /bu/md/cur) == 1000 ]]; then
3187 chown -R Debian-exim:Debian-exim /bu/md
3188 fi
3189 u /etc/exim4/conf.d/transport/30_backup_maildir <<EOF
3190 # modified debian maildir transport
3191 backup_maildir:
3192 driver = appendfile
3193 directory = /bu/md
3194 delivery_date_add
3195 # note, no return path or envelope added
3196 maildir_format
3197 directory_mode = 0700
3198 mode = 0644
3199 mode_fail_narrower = false
3200 EOF
3201
3202 u /etc/exim4/conf.d/router/165_backup_local <<'EOF'
3203 ### router/900_exim4-config_local_user
3204 #################################
3205
3206 backup_local:
3207 debug_print = "R: local_user for $local_part@$domain"
3208 driver = accept
3209 domains = eximbackup.b8.nz
3210 transport = backup_maildir
3211 EOF
3212
3213 # Bind to wghole to receive mailbackup.
3214 wgholeip=$(sed -rn 's/^ *Address *= *([^/]+).*/\1/p' /etc/wireguard/wghole.conf)
3215 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
3216 dc_other_hostnames='eximbackup.b8.nz'
3217 dc_local_interfaces='127.0.0.1;::1;$wgholeip'
3218 EOF
3219
3220 # wghole & thus exim will fail to start without internet connectivity.
3221 u /etc/systemd/system/exim4.service.d/backup.conf <<'EOF'
3222 [Unit]
3223 StartLimitIntervalSec=0
3224
3225 [Service]
3226 Restart=always
3227 RestartSec=20
3228 EOF
3229
3230 else # if $bhost_t; then
3231 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
3232 # Note: If theres like a temporary problem where mail gets sent to
3233 # one of these hosts, if exim isnt listening, it will be a temporary error
3234 # instead of a permanent 5xx.
3235 dc_local_interfaces='127.0.0.1;::1'
3236 EOF
3237 rm -fv /etc/systemd/system/exim4.service.d/backup.conf
3238 fi
3239 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
3240 dc_eximconfig_configtype='smarthost'
3241 dc_smarthost='$smarthost'
3242 EOF
3243
3244 hostname -f |i /etc/mailname
3245 cat >>/etc/exim4/update-exim4.conf.conf <<EOF
3246 # The manpage incorrectly states this will do header rewriting, but
3247 # that only happens if we have dc_hide_mailname is set.
3248 dc_readhost='iankelling.org'
3249 # Only used in case of bounces.
3250 dc_localdelivery='maildir_home'
3251 EOF
3252 ;;
3253 esac
3254
3255
3256
3257
3258 # ** $MAILHOST|bk, things that belong at the end
3259 case $HOSTNAME in
3260 $MAIL_HOST|bk)
3261 # config for the non-nn exim. note, it uses not default dir, but we
3262 # generate that into the default config file
3263 m rsync -ra --delete --delete-excluded \
3264 --exclude=/conf.d/router/161_backup_redir_nn \
3265 --exclude=/conf.d/router/186_sentarchive_nn \
3266 --exclude=/conf.d/main/000_local-nn /etc/exim4/ /etc/myexim4
3267 cat >>/etc/myexim4/conf.d/main/000_local <<'EOF'
3268 # this makes it easier to see which exim is doing what
3269 log_file_path = /var/log/exim4/my%s
3270 EOF
3271
3272
3273
3274 cat >/etc/logrotate.d/myexim <<'EOF'
3275 /var/log/exim4/mymain /var/log/exim4/myreject {
3276 daily
3277 missingok
3278 rotate 1000
3279 delaycompress
3280 notifempty
3281 nocreate
3282 }
3283 /var/log/exim4/mypanic {
3284 size 10M
3285 missingok
3286 rotate 10
3287 compress
3288 delaycompress
3289 notifempty
3290 nocreate
3291 }
3292 EOF
3293
3294 # If we ever wanted to have a separate spool,
3295 # we could do it like this.
3296 # cat >>/etc/exim4/conf.d/main/000_local-nn <<'EOF'
3297 # spool_directory = /var/spool/myexim4
3298 # EOF
3299 cat >>/etc/myexim4/update-exim4.conf.conf <<'EOF'
3300 dc_eximconfig_configtype='smarthost'
3301 dc_smarthost='nn.b8.nz'
3302 EOF
3303 ;;&
3304 bk)
3305
3306 # config for the non-nn exim
3307 cat >>/etc/myexim4/conf.d/main/000_local <<'EOF'
3308 MAIN_HARDCODE_PRIMARY_HOSTNAME = mail2.iankelling.org
3309 EOF
3310 ;;
3311 $MAIL_HOST)
3312
3313
3314 u /etc/myexim4/conf.d/router/185_sentarchive <<'EOF'
3315 sentarchive:
3316 driver = redirect
3317 domains = ! +local_domains
3318 senders = <; *@fsf.org ; *@posteo.net
3319 condition = ${if !bool{${lookup{$local_part@$domain}lsearch{/etc/exim4/ignore-sent}{true}}}}
3320 data = vojdedIdNejyebni@b8.nz
3321 unseen
3322 EOF
3323
3324
3325 u /etc/myexim4/conf.d/router/160_backup_redir <<'EOF'
3326 backup_redir:
3327 driver = redirect
3328 # i dont email myself from my own machine much, so lets ignore that.
3329 domains = ! +local_domains
3330 senders = <; *@fsf.org ; *@posteo.net
3331 condition = ${if !bool{${lookup{$local_part@$domain}lsearch{/etc/exim4/ignore-sent}{true}}}}
3332 # b is just an arbirary short string
3333 data = b@eximbackup.b8.nz
3334 # note, to test this, i could temporarily allow testignore.
3335 # alerts avoids potential mail loop.
3336 local_parts = ! root : ! testignore : ! alerts : ! daylert
3337 unseen = true
3338 errors_to = alerts@iankelling.org
3339 EOF
3340
3341
3342
3343 # for bk, we have a exim4in.service that will do this for us.
3344 m update-exim4.conf -d /etc/myexim4
3345 ;;
3346 esac
3347
3348 # * spool dir setup
3349
3350 # ** bind mount setup
3351 # put spool dir in directory that spans multiple distros.
3352 # based on http://www.postfix.org/qmgr.8.html and my notes in gnus
3353 #
3354 dir=/nocow/exim4
3355 sdir=/var/spool/exim4
3356 # we only do this if our system has $dir
3357
3358 # this used to do a symlink, but, in the boot logs, /nocow would get mounted succesfully,
3359 # about 2 seconds later, exim starts, and immediately puts into paniclog:
3360 # honVi-0000u3-82 Failed to create directory "/var/spool/exim4/input": No such file or directory
3361 # so, im trying a bind mount to get rid of that.
3362 if [[ -e /nocow ]]; then
3363 if ! grep -Fx "/nocow/exim4 /var/spool/exim4 none bind 0 0" /etc/fstab; then
3364 echo "/nocow/exim4 /var/spool/exim4 none bind 0 0" >>/etc/fstab
3365 fi
3366 u /etc/systemd/system/exim4.service.d/override.conf <<'EOF'
3367 [Unit]
3368 # without local-fs on exim, we get these kind of errors in paniclog on shutdown:
3369 # Failed to create spool file /var/spool/exim4//input//1jCLxz-0008V4-V9-D: Permission denied
3370 After=local-fs.target
3371
3372 [Service]
3373 ExecStartPre=/usr/local/bin/exim-nn-iptables
3374 EOF
3375 if ! mountpoint -q $sdir; then
3376 stopifactive exim4 exim4in
3377 if [[ -L $sdir ]]; then
3378 m rm $sdir
3379 fi
3380 if [[ ! -e $dir && -d $sdir ]]; then
3381 m mv $sdir $dir
3382 fi
3383 if [[ ! -d $sdir ]]; then
3384 m mkdir $sdir
3385 m chmod 000 $sdir # only want it to be used when its mounted
3386 fi
3387 m mount $sdir
3388 fi
3389 fi
3390
3391
3392
3393 # ** exim/spool uid setup
3394 # i have the spool directory be common to distro multi-boot, so
3395 # we need the uid to be the same. 608 cuz it's kind of in the middle
3396 # of the free system uids.
3397 IFS=:; read -r _ _ uid _ < <(getent passwd Debian-exim ||:) ||:; unset IFS
3398 IFS=:; read -r _ _ gid _ < <(getent group Debian-exim ||:) ||:; unset IFS
3399 if [[ ! $uid ]]; then
3400 # from /var/lib/dpkg/info/exim4-base.postinst, plus uid and gid options
3401 m adduser --uid 608 --system --group --quiet --home /var/spool/exim4 \
3402 --no-create-home --disabled-login --force-badname Debian-exim
3403 elif [[ $uid != 608 ]]; then
3404 stopifactive exim4 exim4in
3405 m usermod -u 608 Debian-exim
3406 m groupmod -g 608 Debian-exim
3407 m usermod -g 608 Debian-exim
3408 m find / /nocow -xdev -path ./var/tmp -prune -o -uid $uid -execdir chown -h 608 {} +
3409 m find / /nocow -xdev -path ./var/tmp -prune -o -gid $gid -execdir chgrp -h 608 {} +
3410 fi
3411
3412 # * start / stop services
3413
3414 reifactive dnsmasq nscd
3415
3416 if $reload; then
3417 m systemctl daemon-reload
3418 fi
3419
3420 # checking bhost_t is redundant, but could help us catch errors.
3421 if $bhost_t || [[ -e /etc/wireguard/wghole.conf ]]; then
3422 # todo: in mail-setup, we have a static list of backup hosts, not *y
3423 m systemctl --now enable wg-quick@wghole
3424 fi
3425
3426 sysd-prom-fail-install epanicclean
3427 m systemctl --now enable epanicclean
3428
3429 case $HOSTNAME in
3430 je)
3431 /a/exe/web-conf apache2 je.b8.nz
3432 ;;
3433 bk)
3434 /a/exe/web-conf apache2 mail2.iankelling.org
3435 ;;
3436 esac
3437
3438 m /a/bin/ds/mail-cert-cron -1
3439 sre mailcert.timer
3440
3441 case $HOSTNAME in
3442 $MAIL_HOST|bk)
3443 m systemctl --now enable mailnn mailnnroute
3444 ;;&
3445 $MAIL_HOST)
3446 # we use dns to start wg
3447 if $reload; then
3448 sre unbound
3449 else
3450 m systemctl --now enable unbound
3451 fi
3452 ;;&
3453 $MAIL_HOST|bk)
3454 # If these have changes, id rather manually restart it, id rather
3455 # not restart and cause temporary errors
3456 if $reload; then
3457 sre $vpnser
3458 else
3459 m systemctl --now enable $vpnser
3460 fi
3461 if ! systemctl is-active clamav-daemon >/dev/null; then
3462 m systemctl --now enable clamav-daemon
3463 out=$(rsync -aiSAX --chown=root:root --chmod=g-s /a/bin/ds/filesystem/etc/systemd/system/epanicclean.service /etc/systemd/system)
3464 if [[ $out ]]; then
3465 reload=true
3466 fi
3467
3468 # note, this will cause paniclog entries because it takes like 45
3469 # seconds for clamav to start, i use ./epanic-clean to remove
3470 # them.
3471 fi
3472 ;;&
3473 $MAIL_HOST|bk|je)
3474 # start spamassassin/dovecot before exim.
3475 sre dovecot spamassassin
3476 # need to wait a bit before restarting exim, else I
3477 # get a paniclog entry like: spam acl condition: all spamd servers failed
3478 sleep 3
3479 m systemctl --now enable mailclean.timer
3480 ;;&
3481 $MAIL_HOST)
3482 # < 2.1 (eg: in t9), uses a different data format which required manual
3483 # migration. dont start if we are running an old version.
3484 if dpkg --compare-versions "$(dpkg -s radicale | awk '$1 == "Version:" { print $2 }')" ge 2.1; then
3485 m systemctl --now enable radicale
3486 fi
3487 ;;&
3488 esac
3489
3490 # for debugging dns issues
3491 case $HOSTNAME in
3492 je|bk)
3493 systemctl enable --now logrotate-fast.timer
3494 ;;
3495 esac
3496
3497 # last use of $reload happens in previous block
3498 rm -f /var/local/mail-setup-reload
3499
3500
3501 case $HOSTNAME in
3502 $MAIL_HOST|bk|je|li)
3503 # on li, these are never started, except $vpnser
3504 :
3505 ;;
3506 *)
3507 soff radicale mailclean.timer dovecot spamassassin $vpnser mailnn clamav-daemon
3508 ;;
3509 esac
3510
3511 sre exim4
3512
3513 case $HOSTNAME in
3514 $MAIL_HOST)
3515 m systemctl --now enable mailbindwatchdog
3516 ;;
3517 *)
3518 soff mailbindwatchdog
3519 ;;
3520 esac
3521
3522
3523 case $HOSTNAME in
3524 bk) sre exim4in ;;
3525 esac
3526
3527 # * mail monitoring / testing
3528
3529 # note, to test clamav, send an email with body that only contains
3530 # https://en.wikipedia.org/wiki/EICAR_test_file
3531 # which set malware_name to Eicar-Signature
3532 case $HOSTNAME in
3533 $MAIL_HOST|bk|je)
3534 # note: cronjob "ian" also does some important monitoring
3535 # todo: this will sometimes cause an alert because mailtest-check will run
3536 # before we have setup network namespace and spamassassin
3537 u /etc/cron.d/mailtest <<EOF
3538 SHELL=/bin/bash
3539 PATH=/usr/bin:/bin:/usr/local/bin
3540 MAILTO=daylert@iankelling.org
3541 */5 * * * * $u send-test-forward |& log-once send-test-forward
3542 */10 * * * * root chmod -R g+rw /m/md/bounces |& log-once -1 bounces-chmod
3543 # if a bounce happened yesterday, dont let it slip through the cracks
3544 8 1 * * * root export MAILTO=alerts@iankelling.org; [[ -s /var/log/exim4/mainlog.1 ]] && awk '\$5 == "**"' /var/log/exim4/mainlog.1
3545 EOF
3546
3547
3548 m sudo rsync -ahhi --chown=root:root --chmod=0755 \
3549 /b/ds/mailtest-check /b/ds/check-remote-mailqs /usr/local/bin/
3550 u /etc/systemd/system/mailtest-check.service <<'EOF'
3551 [Unit]
3552 Description=mailtest-check
3553 After=local-fs.target
3554 StartLimitIntervalSec=0
3555
3556 [Service]
3557 Type=simple
3558 ExecStart=/usr/local/bin/mailtest-check slow
3559 Restart=always
3560 RestartSec=60
3561
3562 [Install]
3563 WantedBy=graphical.target
3564 EOF
3565 sysd-prom-fail-install mailtest-check
3566 sre mailtest-check
3567 ;;&
3568 $MAIL_HOST)
3569 test_froms=(ian@iankelling.org z@zroe.org iank@gnu.org)
3570 test_tos=(testignore@expertpathologyreview.com testignore@je.b8.nz testignore@amnimal.ninja jtuttle@gnu.org)
3571
3572 cat >>/etc/cron.d/mailtest <<EOF
3573 # 10 am friday
3574 0 10 * * 5 root echo "weekly alert. You are not in the matrix."
3575 2 * * * * root check-remote-mailqs |& log-once check-remote-mailqs
3576 EOF
3577 ;;&
3578 bk)
3579 test_froms=(testignore@amnimal.ninja testignore@expertpathologyreview.com)
3580 test_tos=(testignore@iankelling.org testignore@je.b8.nz)
3581 # We dont need to send from different addresses to the same
3582 # address. this breaks down our nice elegant logic of building up
3583 # froms and tos , so I just handle expertpath in a special case
3584 # below and set the to: to be testignore@zroe.org. If we did sent
3585 # that way, it would also mess up our mailtest-check logic that
3586 # finds which messages to check.
3587 # for example: from testignore@amnimal.ninja to: testignore@iankelling.org testignore@zroe.org
3588 # that would become 2 messages and we'd only check 1.
3589 ;;&
3590 je)
3591 test_froms=(testignore@je.b8.nz)
3592 test_tos=(testignore@iankelling.org testignore@zroe.org testignore@expertpathologyreview.com testignore@amnimal.ninja)
3593 ;;&
3594 $MAIL_HOST|bk|je)
3595
3596 # Dont put these test messages into the sent folder or else it will
3597 # overwhelm it, plus i dont want to save a copy at all.
3598 # Plus addresses we generally want to ignore.
3599 u /etc/exim4/ignore-sent <<EOF
3600 $(printf "%s\n" ${test_tos[@]})
3601 vojdedIdNejyebni@b8.nz
3602 b@eximbackup.b8.nz
3603 EOF
3604
3605 cat >/usr/local/bin/send-test-forward <<'EOF'
3606 #!/bin/bash
3607 # we remove from the queue older than 4.3 minutes since we send every 5 minutes.
3608 olds=(
3609 $(/usr/sbin/exiqgrep -o 260 -i -r '^(testignore@(iankelling\.org|zroe\.org|expertpathologyreview\.com|amnimal\.ninja|je\.b8\.nz)|jtuttle@gnu\.org)$')
3610 )
3611 if (( ${#olds[@]} )); then
3612 /usr/sbin/exim -Mrm "${olds[@]}" >/dev/null
3613 fi
3614 EOF
3615 for test_from in ${test_froms[@]}; do
3616
3617 test_to=${test_tos[0]}
3618 for t in ${test_tos[@]:1}; do
3619 test_to+=", $t"
3620 done
3621 case $test_from in
3622 testignore@expertpathologyreview.com)
3623 test_to=testignore@zroe.org
3624 ;;
3625 esac
3626
3627 cat >>/usr/local/bin/send-test-forward <<EOFOUTER
3628 /usr/sbin/exim -odf -f $test_from -t <<EOF
3629 From: $test_from
3630 To: $test_to
3631 Subject: test \$(date +%Y-%m-%dT%H:%M:%S%z) \$EPOCHSECONDS
3632
3633 /usr/local/bin/send-test-forward
3634 EOF
3635 EOFOUTER
3636 done
3637 m chmod +x /usr/local/bin/send-test-forward
3638 ;;
3639 *)
3640 soff mailtest-check.service
3641 rm -fv /etc/cron.d/mailtest \
3642 /var/lib/prometheus/node-exporter/mailtest-check.prom* \
3643 /var/local/cron-errors/check-remote-mailqs*
3644 ;;
3645 esac
3646
3647
3648
3649 # * misc
3650 m sudo -u $u mkdir -p /home/$u/.cache
3651 set -- /m/mucache /home/$u/.cache/mu /m/.mu /home/$u/.mu
3652 while (($#)); do
3653 target=$1
3654 f=$2
3655 shift 2
3656 if [[ ! -L $f ]]; then
3657 if [[ -e $f ]]; then
3658 rm -rf $f
3659 fi
3660 m sudo -u $u ln -sf -T $target $f
3661 fi
3662 done
3663
3664
3665 # /etc/alias setup is debian specific, and exim postinst script sets up
3666 # an /etc/alias from root to the postmaster, based on the question
3667 # exim4-config exim4/dc_postmaster, as long as there exists an entry for
3668 # root, or there was no preexisting aliases file. postfix won\'t set up
3669 # a root to $postmaster alias if it\'s already installed. Easiest to
3670 # just set it ourselves.
3671
3672 # debconf question for postmaster:
3673 # Mail for the 'postmaster', 'root', and other system accounts needs to be redirected
3674 # to the user account of the actual system administrator.
3675 # If this value is left empty, such mail will be saved in /var/mail/mail, which is not
3676 # recommended.
3677 # Note that postmaster\'s mail should be read on the system to which it is directed,
3678 # rather than being forwarded elsewhere, so (at least one of) the users listed here
3679 # should not redirect their mail off this machine. A 'real-' prefix can be used to
3680 # force local delivery.
3681 # Multiple user names need to be separated by spaces.
3682 # Root and postmaster mail recipient:
3683
3684 m exit 0
3685 :
3686
3687 # Local Variables:
3688 # eval: (outline-minor-mode)
3689 # outline-regexp: "\\( *\\)# [*]\\{1,8\\} "
3690 # End:
3691 # this is combined with defining outline-level in init.el