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