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