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