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