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