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