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