various email improvements
[distro-setup] / mail-setup
1 #!/bin/bash
2 set -x
3
4 # Copyright (C) 2016 Ian Kelling
5
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9
10 # http://www.apache.org/licenses/LICENSE-2.0
11
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17
18 # todo: make quick backups of maildir, or deliver to multiple hosts.
19
20 set -eE -o pipefail
21 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
22
23 [[ $EUID == 0 ]] || exec sudo -E "$BASH_SOURCE" "$@"
24 if [[ ! $SUDO_USER ]]; then
25 echo "$0: error: requires running as nonroot or sudo"
26 exit 1
27 fi
28 u=$SUDO_USER
29
30
31 usage() {
32 cat <<EOF
33 Usage: ${0##*/}
34 Setup exim4 & dovecot & related things
35
36 The minimal assumption we have is that /etc/mailpass exists
37
38
39 -h|--help Print help and exit.
40 EOF
41 exit $1
42 }
43
44
45
46 ####### instructions for icedove #####
47 # Incoming mail server: mail.iankelling.org, port 143, username iank, connection security starttls, authentication method normal password
48 # we could also just use 127.0.0.1 with no ssl, but todo: disable that in dovecot, so mail is secure from local programs.
49 #
50 # hamburger -> preferences -> preferences -> advanced tab -> config editor button -> security.ssl.enable_ocsp_must_staple = false
51 # background: ovecot does not yet have ocsp stapling support
52 # reference: https://community.letsencrypt.org/t/simple-guide-using-lets-encrypt-ssl-certs-with-dovecot/2921
53 #
54 # for phone, same thing but username alerts, pass in ivy-pass.
55 #######
56
57
58 ####### begin perstent password instructions ######
59 # # exim passwords:
60 # # for hosts which have all private files I just use the same user
61 # # for other hosts, each one get\'s their own password.
62 # # for generating secure pass, and storing for server too:
63 # # user=USUALLY_SAME_AS_HOSTNAME
64 # user=li
65 # f=$(mktemp)
66 # apg -m 50 -x 70 -n 1 -a 1 -M CLN >$f
67 # s sed -i "/^$user:/d" /p/c/filesystem/etc/exim4/passwd
68 # echo "$user:$(mkpasswd -m sha-512 -s <$f)" >>/p/c/filesystem/etc/exim4/passwd
69 # echo "mail.iankelling.org 587 $user:$(<$f)" >> /p/c/machine_specific/$user/filesystem/etc/mailpass
70 # # then run this script, or part of it which uses /etc/mailpass
71
72 # # dovecot password, i just need 1 as I\'m the only user
73 # mkdir /p/c/filesystem/etc/dovecot
74 # echo "iank:$(doveadm pw -s ssha256)::::::" >>/p/c/filesystem/etc/dovecot/users
75 # conflink
76
77
78
79 # # for ad-hoc testing of some random new host sending mail:
80 # user=li # client host username & hostname
81 # f=$(mktemp)
82 # apg -m 50 -x 70 -n 1 -a 1 -M CLN >$f
83 # s sed -i "/^$user:/d" /etc/exim4/passwd
84 # echo "$user:$(mkpasswd -m sha-512 -s <$f)" | s tee -a /etc/exim4/passwd
85 # echo "mail.iankelling.org:$user:$(<$f)" | ssh root@$user dd of=/etc/exim4/passwd.client
86 ####### end perstent password instructions ######
87
88
89 ####### begin persistent dkim/dns instructions #########
90 # # Remove 1 level of comments in this section, set the domain var
91 # # for the domain you are setting up, then run this and copy dns settings
92 # # into dns.
93 # domain=iankelling.org
94 # c /p/c/filesystem/etc/exim4
95 # # this has several bugs addressed in comments, but it was helpful
96 # # https://debian-administration.org/article/718/DKIM-signing_outgoing_mail_with_exim4
97
98 # openssl genrsa -out $domain-private.pem 2048 -outform PEM
99 # openssl rsa -in $domain-private.pem -out $domain.pem -pubout -outform PEM
100 # # selector is needed for having multiple keys for one domain.
101 # # I dun do that, so just use a static one: li
102 # echo "txt record name: li._domainkey.$domain"
103 # # Debadmin page does not have v=, fastmail does, and this
104 # # says it\'s recommended in 3.6.1, default is DKIM1 anyways.
105 # # https://www.ietf.org/rfc/rfc6376.txt
106 # # Join and print all but first and last line.
107 # # last line: swap hold & pattern, remove newlines, print.
108 # # lines 2+: append to hold space
109 # echo "txt record contents:"
110 # echo "v=DKIM1; k=rsa; p=$(sed -n '${x;s/\n//gp};2,$H' $domain.pem)"
111 # chmod 644 $domain.pem
112 # chmod 640 $domain-private.pem
113 # # in conflink, we chown these to group debian
114 # conflink
115 # # selector was also put into /etc/exim4/conf.d/main/000_localmacros,
116 # # via the mail-setup scripts
117
118 # # 2017-02 dmarc policies:
119 # # host -t txt _dmarc.gmail.com
120 # # yahoo: p=reject, hotmail: p=none, gmail: p=none, fastmail none for legacy reasons
121 # # there were articles claiming gmail would be changing
122 # # to p=reject, in early 2017, which didn\'t happen. I see no sources on them. It\'s
123 # # expected to cause problems
124 # # with a few old mailing lists, copying theirs for now.
125 #
126 # echo "dmarc dns, name: _dmarc value: v=DMARC1; p=none; rua=mailto:mailauth-reports@$domain"
127
128 # # 2017-02 spf policies:
129 # # host -t txt lists.fedoraproject.org
130 # # google ~all, hotmail ~all, yahoo: ?all, fastmail ?all, outlook ~all
131 # # i include fastmail\'s settings, per their instructions,
132 # # and follow their policy. In mail in a box, or similar instructions,
133 # # I\'ve seen recommended to not use a restrictive policy.
134 # echo "spf dns: name is empty, value: v=spf1 a include:spf.messagingengine.com ?all"
135
136 # # to check if dns has updated, you do
137 # host -a mesmtp._domainkey.$domain
138
139 # # mx records,
140 # # setting it to iankelling.org would work the same, but this
141 # # is more flexible, I could change where mail.iankelling.org pointed.
142 # cat <<'EOF'
143 # mx records, 2 records each, for * and empty domain
144 # pri 10 mail.iankelling.org
145 # pri 20 in1-smtp.messagingengine.com
146 # pri 30 in2-smtp.messagingengine.com
147 # EOF
148 ####### end persistent dkim instructions #########
149
150
151 # misc exim notes:
152 # useful exim docs:
153 # /usr/share/doc/exim4-base/README.Debian.gz
154 # /usr/share/doc/exim4-base/spec.txt.gz
155
156 # routers, transports, and authenticators are sections, and you define
157 # driver instances in those sections, and the manual calls them driver
158 # types but there is also a more specific "type" of driver, which is specified
159 # with the driver = some_module setting in the driver.
160
161 # the driver option must precede and private options (options that are
162 # specific to that driver), so follow example of putting it at beginning.
163
164 # The full list of option settings for any particular driver instance,
165 # including all the defaulted values, can be extracted by making use of
166 # the -bP command line option.
167 # exim -bP config_file to see what config file it used
168 # exim -bP config to see
169
170 # exim clear out message queue. as root:
171 # adapted from somewhere on stackoverflow.
172 # ser stop exim4; sleep 1; exim -bp | exiqgrep -i | xargs exim -Mrm; ser start exim4
173
174 # fastmail has changed their smtp server, but the old one still works,
175 # I see no reason to bother changing.
176 # New one is smtp.fastmail.com
177
178 # test delivery & rewrite settings:
179 #exim4 -bt iank@localhost
180
181
182 postconfin() {
183 local MAPFILE
184 mapfile -t
185 local s
186 postconf -ev "${MAPFILE[@]}"
187 }
188 e() { printf "%s\n" "$*"; }
189 pi() { # package install
190 local s f
191 if dpkg -s -- "$@" &> /dev/null; then
192 return 0;
193 fi;
194 while fuser /var/lib/dpkg/lock &>/dev/null; do sleep 1; done
195 f=/var/cache/apt/pkgcache.bin;
196 if [[ ! -r $f ]] || (( $(( $(date +%s) - $(stat -c %Y $f ) )) > 60*60*12 )); then
197 apt-get update
198 fi
199 apt-get -y install --purge --auto-remove "$@"
200 }
201
202 postmaster=alerts
203 mxhost=mail.iankelling.org
204 mxport=587
205 forward=$u@$mxhost
206
207 # old setup. left as comment for example
208 # mxhost=mail.messagingengine.com
209 # mxport=587
210 # forward=ian@iankelling.org
211
212 smarthost="$mxhost::$mxport" # exim
213
214 # trisquel 8 = openvpn, debian stretch = openvpn-client
215 vpn_ser=openvpn-client
216 if [[ ! -e /lib/systemd/system/openvpn-client@.service ]]; then
217 vpn_ser=openvpn
218 fi
219
220 if [[ $HOSTNAME == $MAIL_HOST ]]; then
221 # afaik, these will get ignored because they are routing to my own
222 # machine, but rm them is safer
223 rm -f $(eval echo ~$u)/.forward /root/.forward
224 else
225 # this can\'t be a symlink and has permission restrictions
226 # it might work in /etc/aliases, but this seems more proper.
227 install -m 644 {-o,-g}$u <(e $forward) $(eval echo ~$u)/.forward
228 fi
229
230
231 pi openvpn
232
233 if [[ -e /p/c/filesystem ]]; then
234 # allow failure of these commands when our internet is down, they are likely not needed,
235 # we check that a valid cert is there already.
236 # to put the hostname in the known hosts
237 if ! ssh -o StrictHostKeyChecking=no root@li.iankelling.org :; then
238 # This just causes failure if our cert is going to expire in the next 30 days.
239 # Certs I generate last 10 years.
240 openssl x509 -checkend $(( 60 * 60 * 24 * 30 )) -noout -in /etc/openvpn/mail.crt
241 else
242 # note, man openvpn implies we could just call mail-route on vpn startup/shutdown with
243 # systemd, buuut it can remake the tun device unexpectedly, i got this in the log
244 # after my internet was down for a bit:
245 # NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.
246 /a/exe/vpn-mk-client-cert -b mail -n mail -s /b/ds/mail-route li.iankelling.org
247 fi
248 fi
249
250 cat >/etc/systemd/system/offlineimapsync.timer <<'EOF'
251 [Unit]
252 Description=Run offlineimap-sync once every min
253
254 [Timer]
255 OnCalendar=*:0/1
256
257 [Install]
258 WantedBy=timers.target
259 EOF
260
261 cat >/etc/systemd/system/offlineimapsync.service <<EOF
262 [Unit]
263 Description=Offlineimap sync
264 After=multi-user.target
265
266 [Service]
267 User=$u
268 Type=oneshot
269 ExecStart=/a/bin/log-quiet/sysd-mail-once offlineimap-sync /a/bin/distro-setup/offlineimap-sync
270 EOF
271
272 cat >/etc/systemd/system/mailclean.timer <<'EOF'
273 [Unit]
274 Description=Run mailclean daily
275
276 [Timer]
277 OnCalendar=monthly
278
279 [Install]
280 WantedBy=timers.target
281 EOF
282
283 cat >/etc/systemd/system/mailclean.service <<EOF
284 [Unit]
285 Description=Delete and archive old mail files
286 After=multi-user.target
287
288 [Service]
289 User=$u
290 Type=oneshot
291 ExecStart=/a/bin/log-quiet/sysd-mail-once mailclean /a/bin/distro-setup/mailclean
292 EOF
293
294 systemctl daemon-reload
295
296 # wording of question from dpkg-reconfigure exim4-config
297 # 1. internet site; mail is sent and received directly using SMTP
298 # 2. mail sent by smarthost; received via SMTP or fetchmail
299 # 3. mail sent by smarthost; no local mail
300 # 4. local delivery only; not on a network
301 # 5. no configuration at this time
302 #
303 # Note, I have used option 2 in the past for receiving mail
304 # from lan hosts, sending external mail via another smtp server.
305 #
306 # Note, other than configtype, we could set all the options in
307 # both types of configs without harm, they would either be
308 # ignored or be disabled by other settings, but the default
309 # local_interfaces definitely makes things more secure.
310
311 # most of these settings get translated into settings
312 # in /etc/exim4/update-exim4.conf.conf
313 # how /etc/exim4/update-exim4.conf.conf translates into actual exim settings is
314 # documented in man update-exim4.conf, which outputs to the config that
315 # exim actually reads. except the man page is not perfect, for example,
316 # it doesn't document that it sets
317 # DCconfig_${dc_eximconfig_configtype}" "1"
318 # which is a line from update-exim4.conf, which is a relatively short bash script.
319 # mailname setting sets /etc/mailname
320
321 debconf-set-selections <<EOF
322 exim4-config exim4/use_split_config boolean true
323 EOF
324
325 source /a/bin/bash_unpublished/source-semi-priv
326 mkdir -p /etc/exim4/conf.d/{main,transport,auth,router}
327
328 cat >/etc/exim4/rcpt_local_acl <<'EOF'
329 # Only hosts we control send to mail.iankelling.org, so make sure
330 # they are all authed.
331 # Note, if we wanted authed senders for all domains,
332 # we could make this condition in acl_check_mail
333 deny
334 message = ian trusted domain recepient but no auth
335 !authenticated = *
336 domains = mail.iankelling.org
337 EOF
338 cat >/etc/exim4/data_local_acl <<'EOF'
339 # Except for the "condition =", this was
340 # a comment in the check_data acl. The comment about this not
341 # being suitable is mostly bs. The only thing related I found was to
342 # add the condition =, cuz spamassassin has problems with big
343 # messages and spammers don't bother with big messages,
344 # but I've increased the size from 10k
345 # suggested in official docs, and 100k in the wiki example because
346 # those docs are rather old and I see a 110k spam message
347 # pretty quickly looking through my spam folder.
348 warn
349 condition = ${if < {$message_size}{2000K}}
350 spam = Debian-exim:true
351 add_header = X-Spam_score: $spam_score\n\
352 X-Spam_score_int: $spam_score_int\n\
353 X-Spam_bar: $spam_bar\n\
354 X-Spam_report: $spam_report
355
356 EOF
357 cat >/etc/exim4/conf.d/auth/29_exim4-config_auth <<'EOF'
358 # from 30_exim4-config_examples
359
360 plain_server:
361 driver = plaintext
362 public_name = PLAIN
363 server_condition = "${if crypteq{$auth3}{${extract{1}{:}{${lookup{$auth2}lsearch{CONFDIR/passwd}{$value}{*:*}}}}}{1}{0}}"
364 server_set_id = $auth2
365 server_prompts = :
366 .ifndef AUTH_SERVER_ALLOW_NOTLS_PASSWORDS
367 server_advertise_condition = ${if eq{$tls_in_cipher}{}{}{*}}
368 .endif
369 EOF
370
371 cat >/etc/exim4/conf.d/router/900_exim4-config_local_user <<'EOF'
372 ### router/900_exim4-config_local_user
373 #################################
374
375 # This router matches local user mailboxes. If the router fails, the error
376 # message is "Unknown user".
377
378 local_user:
379 debug_print = "R: local_user for $local_part@$domain"
380 driver = accept
381 domains = +local_domains
382 # ian: commented this, in conjunction with a dovecot lmtp
383 # change so I get mail for all users.
384 # check_local_user
385 local_parts = ! root
386 transport = LOCAL_DELIVERY
387 cannot_route_message = Unknown user
388 EOF
389 cat >/etc/exim4/conf.d/transport/30_exim4-config_dovecot_lmtp <<'EOF'
390 dovecot_lmtp:
391 driver = lmtp
392 socket = /var/run/dovecot/lmtp
393 #maximum number of deliveries per batch, default 1
394 batch_max = 200
395 EOF
396
397 cat >/etc/exim4/conf.d/router/190_exim4-config_fsfsmarthost <<'EOF'
398 # smarthost for fsf mail
399 # ian: copied from /etc/exim4/conf.d/router/200_exim4-config_primary, and added senders = and
400 # replaced DCsmarthost with mail.fsf.org
401 fsfsmarthost:
402 debug_print = "R: smarthost for $local_part@$domain"
403 driver = manualroute
404 domains = ! +local_domains
405 senders = *@fsf.org
406 transport = remote_smtp_smarthost
407 route_list = * mail.fsf.org byname
408 host_find_failed = ignore
409 same_domain_copy_routing = yes
410 no_more
411 EOF
412
413
414 #### begin mail cert setup ###
415 f=/usr/local/bin/mail-cert-cron
416 cat >$f <<'EOF'
417 set -eE -o pipefail
418 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
419
420 [[ $EUID == 0 ]] || exec sudo "$BASH_SOURCE" "$@"
421
422 f=/a/bin/bash_unpublished/source-semi-priv
423 if [[ -e $f ]]; then
424 source $f
425 fi
426 if [[ $HOSTNAME == $MAIL_HOST ]]; then
427 local_mx=mail.iankelling.org
428 rsync_common="rsync -ogtL --chown=root:Debian-exim --chmod=640 root@li.iankelling.org:/etc/letsencrypt/live/$local_mx/"
429 ${rsync_common}fullchain.pem /etc/exim4/exim.crt
430 ret=$?
431 ${rsync_common}privkey.pem /etc/exim4/exim.key
432 new_ret=$?
433 if [[ $ret != $new_ret ]]; then
434 echo "$0: error: differing rsync returns, $ret, $new_ret"
435 exit 1
436 fi
437 fi
438 if [[ $new_ret != 0 ]]; then
439 if ! openssl x509 -checkend $(( 60 * 60 * 24 * 3 )) -noout -in /etc/exim4/exim.crt; then
440 echo "$0: error!: cert rsync failed and it will expire in less than 3 days"
441 exit 1
442 fi
443 fi
444 exit 0
445 EOF
446 chmod 755 $f
447
448 cat >/etc/systemd/system/mailcert.service <<'EOF'
449 [Unit]
450 Description=Mail cert rsync
451 After=multi-user.target
452
453 [Service]
454 Type=oneshot
455 ExecStart=/a/bin/log-quiet/sysd-mail-once mailcert /usr/local/bin/mail-cert-cron
456 EOF
457
458 cat >/etc/systemd/system/mailcert.timer <<'EOF'
459 [Unit]
460 Description=Run mail-cert once a day
461
462 [Timer]
463 OnCalendar=daily
464
465 [Install]
466 WantedBy=timers.target
467 EOF
468 systemctl daemon-reload
469 systemctl start mailcert
470 systemctl restart mailcert.timer
471 systemctl enable mailcert.timer
472
473 ##### end mailcert setup #####
474
475
476
477 if [[ $HOSTNAME == $MAIL_HOST ]]; then
478
479 # mail.iankelling.org so local imap clients can connect with tls and
480 # when they happen to not be local.
481 sed -ri -f - /etc/hosts <<'EOF'
482 /^127\.0\.1\.1.* mail\.iankelling\.org\b/q
483 /^127\.0\.1\.1 /s/ *$/ mail.iankelling.org/
484 EOF
485 /a/exe/cedit mail /etc/dnsmasq-servers.conf <<'EOF' || [[ $? == 1 ]]
486 server=/mail.iankelling.org/127.0.1.1
487 EOF
488 systemctl reload dnsmasq
489
490 debconf-set-selections <<EOF
491 # Mail Server configuration
492 # -------------------------
493
494 # Please select the mail server configuration type that best meets your needs.
495
496 # Systems with dynamic IP addresses, including dialup systems, should generally be
497 # configured to send outgoing mail to another machine, called a 'smarthost' for
498 # delivery because many receiving systems on the Internet block incoming mail from
499 # dynamic IP addresses as spam protection.
500
501 # A system with a dynamic IP address can receive its own mail, or local delivery can be
502 # disabled entirely (except mail for root and postmaster).
503
504 # 1. internet site; mail is sent and received directly using SMTP
505 # 2. mail sent by smarthost; received via SMTP or fetchmail
506 # 3. mail sent by smarthost; no local mail
507 # 4. local delivery only; not on a network
508 # 5. no configuration at this time
509
510 # General type of mail configuration: 1
511 exim4-config exim4/dc_eximconfig_configtype select internet site; mail is sent and received directly using SMTP
512
513
514
515 # The 'mail name' is the domain name used to 'qualify' mail addresses without a domain
516 # name.
517
518 # This name will also be used by other programs. It should be the single, fully
519 # qualified domain name (FQDN).
520
521 # Thus, if a mail address on the local host is foo@example.org, the correct value for
522 # this option would be example.org.
523
524 # This name won\'t appear on From: lines of outgoing messages if rewriting is enabled.
525
526 # System mail name:
527 # iank: see comment elsewhere on mailname
528 exim4-config exim4/mailname string mail.iankelling.org
529
530
531
532
533 # Please enter a semicolon-separated list of recipient domains for which this machine
534 # should consider itself the final destination. These domains are commonly called
535 # 'local domains'. The local hostname (kd.lan) and 'localhost' are always added
536 # to the list given here.
537
538 # By default all local domains will be treated identically. If both a.example and
539 # b.example are local domains, acc@a.example and acc@b.example will be delivered to the
540 # same final destination. If different domain names should be treated differently, it
541 # is necessary to edit the config files afterwards.
542
543 # Other destinations for which mail is accepted:
544 # iank.bid is for testing
545 # mail.iankelling.org is for machines i own
546 exim4-config exim4/dc_other_hostnames string *.iankelling.org;iankelling.org;*iank.bid;iank.bid;*zroe.org;zroe.org;*.b8.nz;b8.nz
547
548
549
550
551 # Please enter a semicolon-separated list of IP addresses. The Exim SMTP listener
552 # daemon will listen on all IP addresses listed here.
553
554 # An empty value will cause Exim to listen for connections on all available network
555 # interfaces.
556
557 # If this system only receives mail directly from local services (and not from other
558 # hosts), it is suggested to prohibit external connections to the local Exim daemon.
559 # Such services include e-mail programs (MUAs) which talk to localhost only as well as
560 # fetchmail. External connections are impossible when 127.0.0.1 is entered here, as
561 # this will disable listening on public network interfaces.
562
563 # IP-addresses to listen on for incoming SMTP connections:
564 exim4-config exim4/dc_local_interfaces string
565
566
567
568
569 # Mail for the 'postmaster', 'root', and other system accounts needs to be redirected
570 # to the user account of the actual system administrator.
571
572 # If this value is left empty, such mail will be saved in /var/mail/mail, which is not
573 # recommended.
574
575 # Note that postmaster\'s mail should be read on the system to which it is directed,
576 # rather than being forwarded elsewhere, so (at least one of) the users listed here
577 # should not redirect their mail off this machine. A 'real-' prefix can be used to
578 # force local delivery.
579
580 # Multiple user names need to be separated by spaces.
581
582 # Root and postmaster mail recipient:
583 exim4-config exim4/dc_postmaster string $postmaster
584
585
586
587 # Exim is able to store locally delivered email in different formats. The most commonly
588 # used ones are mbox and Maildir. mbox uses a single file for the complete mail folder
589 # stored in /var/mail/. With Maildir format every single message is stored in a
590 # separate file in ~/Maildir/.
591
592 # Please note that most mail tools in Debian expect the local delivery method to be
593 # mbox in their default.
594
595 # 1. mbox format in /var/mail/ 2. Maildir format in home directory
596
597 # Delivery method for local mail: 2
598 exim4-config exim4/dc_localdelivery select Maildir format in home directory
599 EOF
600 echo mail.iankelling.org > /etc/mailname
601
602 # MAIN_HARDCODE_PRIMARY_HOSTNAME might mess up the
603 # smarthost config type, not sure. all other settings
604 # would be unused in that config type.
605 rm -f /etc/exim4/conf.d/main/000_localmacros # old filename
606 cat >/etc/exim4/conf.d/main/000_local <<EOF
607 # enable 587 in addition to the default 25, so that
608 # i can send mail where port 25 is firewalled by isp
609 daemon_smtp_ports = 25 : 587
610 # i don't have ipv6 setup for my vpn tunnel yet.
611 disable_ipv6 = true
612
613 MAIN_TLS_ENABLE = true
614
615 DKIM_CANON = relaxed
616 DKIM_SELECTOR = li
617
618 # from comments in
619 # https://debian-administration.org/article/718/DKIM-signing_outgoing_mail_with_exim4
620
621 # The file is based on the outgoing domain-name in the from-header.
622 DKIM_DOMAIN = \${lc:\${domain:\$h_from:}}
623 # sign if key exists
624 DKIM_PRIVATE_KEY= \${if exists{/etc/exim4/\${dkim_domain}-private.pem} {/etc/exim4/\${dkim_domain}-private.pem}}
625
626
627 # failing message on mail-tester.com:
628 # We check if there is a server (A Record) behind your hostname kd.
629 # You may want to publish a DNS record (A type) for the hostname kd or use a different hostname in your mail software
630 # https://serverfault.com/questions/46545/how-do-i-change-exim4s-primary-hostname-on-a-debian-box
631 # and this one seemed appropriate from grepping config.
632 # I originally set this to li.iankelling.org, but then ended up with errors when li tried to send
633 # mail to kd, so this should basically be a name that no host has as their
634 # canonical hostname since the actual host sits behind a nat and changes.
635 # Seems logical for this to be the same as mailname.
636 MAIN_HARDCODE_PRIMARY_HOSTNAME = mail.iankelling.org
637
638 # normally empty, I set this so I can set the envelope address
639 # when doing mail redelivery to invoke filters
640 MAIN_TRUSTED_GROUPS = $u
641
642 LOCAL_DELIVERY = dovecot_lmtp
643
644 # options exim has to avoid having to alter the default config files
645 CHECK_RCPT_LOCAL_ACL_FILE = /etc/exim4/rcpt_local_acl
646 CHECK_DATA_LOCAL_ACL_FILE = /etc/exim4/data_local_acl
647
648 # debian exim config added this in 2016 or so?
649 # it's part of the smtp spec, to limit lines to 998 chars
650 # but a fair amount of legit mail does not adhere to it. I don't think
651 # this should be default, like it says in
652 # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=828801
653 # todo: the bug for introducing this was about headers, but
654 # the fix maybe is for all lines? one says gmail rejects, the
655 # other says gmail does not reject. figure out and open a new bug.
656 IGNORE_SMTP_LINE_LENGTH_LIMIT = true
657
658 # most of the ones that gmail seems to use.
659 # Exim has horrible default of signing unincluded
660 # list- headers since they got mentioned in an
661 # rfc, but this messes up mailing lists, like gnu/debian which want to
662 # keep your dkim signature intact but add list- headers.
663 DKIM_SIGN_HEADERS = mime-version:in-reply-to:references:from:date:subject:to
664
665 # recommended if dns is expected to work
666 CHECK_RCPT_VERIFY_SENDER = true
667 # seems like a good idea
668 CHECK_DATA_VERIFY_HEADER_SENDER = true
669 CHECK_RCPT_SPF = true
670 CHECK_RCPT_REVERSE_DNS = true
671 CHECK_MAIL_HELO_ISSUED = true
672 EOF
673
674
675 ####### begin dovecot setup ########
676 # based on a little google and package search, just the dovecot
677 # packages we need instead of dovecot-common.
678 #
679 # dovecot-lmtpd is for exim to deliver to dovecot instead of maildir
680 # directly. The reason to do this is to use dovecot\'s sieve, which
681 # has extensions that allow it to be almost equivalent to exim\'s
682 # filter capabilities, some ways probably better, some worse, and
683 # sieve has the benefit of being supported in postfix and
684 # proprietary/weird environments, so there is more examples on the
685 # internet. I was torn about whether to do this or not, meh.
686 pi dovecot-core dovecot-imapd dovecot-sieve dovecot-lmtpd
687
688 # if we changed 90-sieve.conf and removed the active part of the
689 # sieve option, we wouldn\'t need this, but I\'d rather not modify a
690 # default config if not needed. This won\'t work as a symlink in /a/c
691 # unfortunately.
692 sudo -u $u /a/exe/lnf -T sieve/main.sieve $(eval echo ~$u)/.dovecot.sieve
693
694 # we set this later in local.conf
695 sed -ri -f - /etc/dovecot/conf.d/10-mail.conf <<'EOF'
696 /^\s*mail_location\s*=/d
697 EOF
698
699 cat >/etc/dovecot/conf.d/20-lmtp.conf <<EOF
700 protocol lmtp {
701 #per https://wiki2.dovecot.org/Pigeonhole/Sieve/Configuration
702 mail_plugins = \$mail_plugins sieve
703 # default was
704 #mail_plugins = \$mail_plugins
705
706 # For a normal setup with exim, we need something like this, which
707 # removes the domain part
708 # auth_username_format = %Ln
709 #
710 # or else # Exim says something like
711 # "LMTP error after RCPT ... 550 ... User doesn't exist someuser@somedomain"
712 # Dovecot verbose log says something like
713 # "auth-worker(9048): passwd(someuser@somedomain): unknown user"
714 # reference: http://wiki.dovecot.org/LMTP/Exim
715 #
716 # However, I use this to direct all mail to the same inbox.
717 # A normal way to do this, which I did at first is to have
718 # a router in exim almost at the end, eg 950,
719 #local_catchall:
720 # debug_print = "R: catchall for \$local_part@\$domain"
721 # driver = redirect
722 # domains = +local_domains
723 # data = $u
724 # based on
725 # http://blog.alteholz.eu/2015/04/exim4-and-catchall-email-address/
726 # with superflous options removed.
727 # However, this causes the envelope to be rewritten,
728 # which makes filtering into mailboxes a little less robust or more complicated,
729 # so I've done it this way instead. it also requires
730 # modifying the local router in exim.
731 auth_username_format = $u
732 }
733
734 EOF
735
736
737 cat >/etc/dovecot/local.conf <<'EOF'
738 # so I can use a different login that my shell login for mail. this is
739 # worth doing solely for the reason that if this login is compromised,
740 # it won't also compromise my shell password.
741 !include conf.d/auth-passwdfile.conf.ext
742
743 # settings derived from wiki and 10-ssl.conf
744 ssl = required
745 ssl_cert = </etc/exim4/exim.crt
746 ssl_key = </etc/exim4/exim.key
747 # https://github.com/certbot/certbot/raw/master/certbot-apache/certbot_apache/options-ssl-apache.conf
748 # in my cert cronjob, I check if that has changed upstream.
749 ssl_cipher_list = ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS
750
751 # ian: added this, more secure, per google etc
752 ssl_prefer_server_ciphers = yes
753
754
755 mail_location = maildir:/m/%u:LAYOUT=fs:INBOX=/m/%u/INBOX
756 mail_uid = iank
757 mail_gid = iank
758
759 # for debugging info, uncomment these.
760 # logs go to syslog and to /var/log/mail.log
761 # auth_verbose=yes
762 #mail_debug=yes
763 EOF
764 ####### end dovecot setup ########
765
766 # https://selivan.github.io/2017/12/30/systemd-serice-always-restart.html
767 d=/etc/systemd/system/openvpn@mail
768 mkdir -p $d
769 cat >$d/override.conf <<'EOF'
770 [Service]
771 Restart=always
772 # time to sleep before restarting a service
773 RestartSec=1
774
775 [Unit]
776 # StartLimitIntervalSec in recent systemd versions
777 StartLimitInterval=0
778 EOF
779
780 systemctl enable offlineimapsync.timer
781 systemctl start offlineimapsync.timer
782 systemctl enable mailclean.timer
783 systemctl start mailclean.timer
784 systemctl restart $vpn_ser@mail
785 systemctl enable $vpn_ser@mail
786 systemctl enable dovecot
787 systemctl restart dovecot
788
789 else # $HOSTNAME != $MAIL_HOST
790 # remove mail. 2 lines to properly remove whitespace
791 sed -ri -f - /etc/hosts <<'EOF'
792 s#^(127\.0\.1\.1 .*) +mail\.iankelling\.org$#\1#
793 s#^(127\.0\.1\.1 .*)mail\.iankelling\.org +(.*)#\1\2#
794 EOF
795
796 echo | /a/exe/cedit mail /etc/dnsmasq-servers.conf || [[ $? == 1 ]]
797 systemctl reload dnsmasq
798
799 systemctl disable offlineimapsync.timer &>/dev/null ||:
800 systemctl stop offlineimapsync.timer &>/dev/null ||:
801 systemctl disable mailclean.timer &>/dev/null ||:
802 systemctl stop mailclean.timer &>/dev/null ||:
803 systemctl disable $vpn_ser@mail
804 systemctl stop $vpn_ser@mail
805 systemctl disable dovecot ||:
806 systemctl stop dovecot ||:
807 #
808 #
809 # would only exist because I wrote it i the previous condition,
810 # it\'s not part of exim
811 rm -f /etc/exim4/conf.d/main/000_localmacros
812 debconf-set-selections <<EOF
813 exim4-config exim4/dc_eximconfig_configtype select mail sent by smarthost; no local mail
814 exim4-config exim4/dc_smarthost string $smarthost
815 # afaik, on dpkg-reconfigure noninteractive, this sets /etc/mailname if it does not exist.
816 # if it does exist, it immediately changes the value to whats in /etc/mailname.
817 # So, I don't think there's any point in setting it, but might as well since
818 # ignoring what I set here is brain dead and might change.
819 exim4-config exim4/mailname string $(hostname -f)
820 EOF
821 hostname -f > /etc/mailname
822
823 fi # end $HOSTNAME != $MAIL_HOST
824
825 # if we already have it installed, need to reconfigure, without being prompted
826 if dpkg -s exim4-config &>/dev/null; then
827 # gotta remove this, otherwise the set-selections are completely
828 # ignored. It woulda been nice if this was documented somewhere!
829 rm -f /etc/exim4/update-exim4.conf.conf
830 while fuser /var/lib/dpkg/lock &>/dev/null; do sleep 1; done
831 dpkg-reconfigure -u -fnoninteractive exim4-config
832 fi
833
834 # i have the spool directory be common to distro multi-boot, so
835 # we need the uid to be the same. 608 cuz it's kind of in the middle
836 # of the free system uids.
837 IFS=:; read _ _ uid _ < <(getent passwd Debian-exim ||:) ||:; unset IFS
838 IFS=:; read _ _ gid _ < <(getent group Debian-exim ||:) ||:; unset IFS
839 if [[ ! $uid ]]; then
840 # from /var/lib/dpkg/info/exim4-base.postinst, plus uid and gid options
841 adduser --uid 608 --system --group --quiet --home /var/spool/exim4 \
842 --no-create-home --disabled-login --force-badname Debian-exim
843 elif [[ $uid != 608 ]]; then
844 systemctl stop exim4 ||:
845 usermod -u 608 Debian-exim
846 groupmod -g 608 Debian-exim
847 usermod -g 608 Debian-exim
848 find / /nocow -xdev -uid $uid -exec chown -h 608 {} +
849 find / /nocow -xdev -gid $gid -exec chgrp -h 608 {} +
850 fi
851
852
853 # light version of exim does not have sasl auth support.
854 pi exim4-daemon-heavy spamassassin spf-tools-perl
855
856
857
858 ##### begin spamassassin config
859 systemctl enable spamassassin
860 # per readme.debian
861 sed -i '/^\s*CRON\s*=/d' /etc/default/spamassassin
862 e CRON=1 >>/etc/default/spamassassin
863 # just noticed this in the config file, seems like a good idea.
864 sed -i '/^\s*NICE\s*=/d' /etc/default/spamassassin
865 e 'NICE="--nicelevel 15"' >>/etc/default/spamassassin
866 systemctl start spamassassin
867 systemctl reload spamassassin
868
869 cat >/etc/systemd/system/spamddnsfix.service <<'EOF'
870 [Unit]
871 Description=spamd dns bug fix cronjob
872
873 [Service]
874 Type=oneshot
875 ExecStart=/a/bin/distro-setup/spamd-dns-fix
876 EOF
877 # 2017-09, debian closed the bug on this saying upstream had fixed it.
878 # remove this when i\'m using the newer package, ie, debian 10, or maybe
879 # ubuntu 18.04.
880 cat >/etc/systemd/system/spamddnsfix.timer <<'EOF'
881 [Unit]
882 Description=run spamd bug fix script every 10 minutes
883
884 [Timer]
885 OnActiveSec=60
886 # the script looks back 9 minutes into the journal,
887 # it takes a second to run,
888 # so lets run every 9 minutes and 10 seconds.
889 OnUnitActiveSec=550
890
891 [Install]
892 WantedBy=timers.target
893 EOF
894 systemctl daemon-reload
895 systemctl restart spamddnsfix.timer
896 systemctl enable spamddnsfix.timer
897 #
898 ##### end spamassassin config
899
900
901
902
903
904 # https://blog.dhampir.no/content/make-exim4-on-debian-respect-forward-and-etcaliases-when-using-a-smarthost
905 # i only need .forwards, so just doing that one.
906 cd /etc/exim4/conf.d/router
907 b=userforward_higher_priority
908 # replace the router name so it is unique
909 sed -r s/^\\S+:/$b:/ 600_exim4-config_userforward >175_$b
910
911 # begin setup passwd.client
912 f=/etc/exim4/passwd.client
913 rm -f /etc/exim4/passwd.client
914 install -m 640 -g Debian-exim /dev/null $f
915 cat /etc/mailpass| while read -r domain port pass; do
916 # reference: exim4_passwd_client(5)
917 printf "%s:%s\n" "$domain" "$pass" >>$f
918 done
919 # end setup passwd.client
920
921 # by default, only 10 days of logs are kept. increase that.
922 sed -ri 's/^(\s*rotate\s).*/\11000/' /etc/logrotate.d/exim4-base
923
924 systemctl restart exim4
925
926 # /etc/alias setup is debian specific, and
927 # exim config sets up an /etc/alias from root to the postmaster, which i
928 # config to ian, as long as there exists an entry for root, or there was
929 # no preexisting aliases file. based on the postinst file. postfix
930 # won\'t set up a root to $postmaster alias if it\'s already installed.
931 # Since postfix is not the greatest, just set it ourselves.
932 if [[ $postmaster != root ]]; then
933 sed -i --follow-symlinks -f - /etc/aliases <<EOF
934 \$a root: $postmaster
935 /^root:/d
936 EOF
937 newaliases
938 fi
939
940 # put spool dir in directory that spans multiple distros.
941 # based on http://www.postfix.org/qmgr.8.html and my notes in gnus
942 #
943 # todo: I\'m suspicious of uids for Debian-exim being the same across
944 # distros. It would be good to test this.
945 dir=/nocow/exim4
946 sdir=/var/spool/exim4
947 # we only do this if our system has $dir
948
949 # this used to do a symlink, but, in the boot logs, /nocow would get mounted succesfully,
950 # about 2 seconds later, exim starts, and immediately puts into paniclog:
951 # honVi-0000u3-82 Failed to create directory "/var/spool/exim4/input": No such file or directory
952 # so, im trying a bind mount to get rid of that.
953 if [[ -e /nocow ]]; then
954 if ! grep -Fx "/nocow/exim4 /var/spool/exim4 none bind 0 0" /etc/fstab; then
955 echo "/nocow/exim4 /var/spool/exim4 none bind 0 0" >> /etc/fstab
956 fi
957 if ! mountpoint -q $sdir; then
958 systemctl stop exim4
959 if [[ -L $sdir ]]; then
960 rm $sdir
961 fi
962 if [[ ! -e $dir && -d $sdir ]]; then
963 mv $sdir $dir
964 fi
965 if [[ ! -d $sdir ]]; then
966 mkdir $sdir
967 chmod 000 $sdir # only want it to be used when its mounted
968 fi
969 mount $sdir
970 fi
971 fi
972
973 systemctl restart exim4
974 systemctl enable exim4
975
976 # MAIL_HOST also does radicale, and easier to start and stop it here
977 # for when MAIL_HOST changes, so radicale gets the synced files and
978 # does not stop us from remounting /o.
979 if dpkg -s radicale &>/dev/null; then
980 if [[ $HOSTNAME == $MAIL_HOST ]]; then
981 systemctl restart radicale
982 systemctl enable radicale
983 if [[ -e /etc/logrotate.d/radicale.disabled ]]; then
984 mv /etc/logrotate.d/radicale{.disabled,}
985 fi
986 else
987 systemctl stop radicale
988 systemctl disable radicale
989 # weekly logrotate tries to restart radicale even if it's a disabled service in flidas.
990 if [[ -e /etc/logrotate.d/radicale ]]; then
991 mv /etc/logrotate.d/radicale{,.disabled}
992 fi
993 fi
994 fi
995 exit 0
996 :