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