own mailserver, lots of improvements
[distro-setup] / mail-setup
1 #!/bin/bash -l
2 # Copyright (C) 2016 Ian Kelling
3
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 set -eE -o pipefail
17 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
18
19 ####### begin perstent password instructions ######
20 # # exim passwords:
21 # # for hosts which have all private files I just use the same user
22 # # for other hosts, each one get's their own password.
23 # # for generating secure pass, and storing for server too:
24 # # user=USUALLY_SAME_AS_HOSTNAME
25 # user=li
26 # f=$(mktemp)
27 # apg -m 50 -x 70 -n 1 -a 1 -M CLN >$f
28 # s sed -i "/^$user:/d" /p/c/filesystem/etc/exim4/passwd
29 # echo "$user:$(mkpasswd -m sha-512 -s <$f)" >>/p/c/filesystem/etc/exim4/passwd
30 # echo "mail.iankelling.org:$user:$(<$f)" >> /p/c/machine_specific/$user/filesystem/etc/mailpass
31 # # then run this script, or part of it which uses /etc/mailpass
32
33 # # dovecot password, i just need 1 as I'm the only user
34 # mkdir /p/c/filesystem/etc/dovecot
35 # echo "ian:$(doveadm pw -s ssha256)::::::" >/p/c/filesystem/etc/dovecot/users
36 # conflink
37
38
39
40 # # for ad-hoc testing of some random new host sending mail:
41 # user=li # client host username & hostname
42 # f=$(mktemp)
43 # apg -m 50 -x 70 -n 1 -a 1 -M CLN >$f
44 # s sed -i "/^$user:/d" /etc/exim4/passwd
45 # echo "$user:$(mkpasswd -m sha-512 -s <$f)" | s tee -a /etc/exim4/passwd
46 # echo "mail.iankelling.org:$user:$(<$f)" | ssh root@$user dd of=/etc/exim4/passwd.client
47 ####### end perstent password instructions ######
48
49
50 ####### begin persistent dkim/dns instructions #########
51 # # Remove 1 level of comments in this section, set the domain var
52 # # for the domain you are setting up, then run this and copy dns settings
53 # # into dns.
54 # domain=iankelling.org
55 # c /p/c/filesystem/etc/exim4
56 # # this has several bugs addressed in comments, but it was helpful
57 # # https://debian-administration.org/article/718/DKIM-signing_outgoing_mail_with_exim4
58
59 # openssl genrsa -out $domain-private.pem 2048 -outform PEM
60 # openssl rsa -in $domain-private.pem -out $domain.pem -pubout -outform PEM
61 # # selector is needed for having multiple keys for one domain.
62 # # I dun do that, so just use a static one: li
63 # echo "txt record name: li._domainkey.$domain"
64 # # Debadmin page does not have v=, fastmail does, and this
65 # # says it's recommended in 3.6.1, default is DKIM1 anyways.
66 # # https://www.ietf.org/rfc/rfc6376.txt
67 # # Join and print all but first and last line.
68 # # last line: swap hold & pattern, remove newlines, print.
69 # # lines 2+: append to hold space
70 # echo "txt record contents:"
71 # echo "v=DKIM1; k=rsa; p=$(sed -n '${x;s/\n//gp};2,$H' $domain.pem)"
72 # chmod 644 $domain.pem
73 # chmod 640 $domain-private.pem
74 # # in conflink, we chown these to group debian
75 # conflink
76 # # selector was also put into /etc/exim4/conf.d/main/000_localmacros,
77 # # via the mail-setup scripts
78
79 # # 2017-02 dmarc policies:
80 # # yahoo: p=reject, hotmail: p=none, gmail: p=none, fastmail none for legacy reasons
81 # # gmail will be changing to p=reject, which is expected to cause problems
82 # # with a few old mailing lists, copying theirs for now.
83 # echo "dmarc dns, name: _dmarc value: v=DMARC1; p=none; rua=mailto:mailauth-reports@$domain"
84
85 # # 2017-02 spf policies:
86 # # google ~all, hotmail -all, yahoo: ?all, fastmail ?all
87 # # i include fastmail's settings, per their instructions,
88 # # and follow their policy. In mail in a box, or similar instructions,
89 # # I've seen recommended to not use a restrictive policy.
90 # echo "spf dns: name is empty, value: v=spf1 a include:spf.messagingengine.com ?all"
91
92 # # to check if dns has updated, you do
93 # host -a mesmtp._domainkey.$domain
94
95 # # mx records,
96 # # setting it to iankelling.org would work the same, but this
97 # # is more flexible, I could change where mail.iankelling.org pointed.
98 # cat <<'EOF'
99 # mx records, 2 records each, for * and empty domain
100 # pri 10 mail.iankelling.org
101 # pri 20 in1-smtp.messagingengine.com
102 # pri 30 in2-smtp.messagingengine.com
103 # EOF
104 ####### end persistent dkim instructions #########
105
106
107 # misc exim notes:
108 # useful exim docs:
109 # /usr/share/doc/exim4-base/README.Debian.gz
110 # /usr/share/doc/exim4-base/spec.txt.gz
111
112 # routers, transports, and authenticators are sections, and you define
113 # driver instances in those sections, and the manual calls them driver
114 # types but there is also a more specific "type" of driver, which is specified
115 # with the driver = some_module setting in the driver.
116
117 # the driver option must precede and private options (options that are
118 # specific to that driver), so follow example of putting it at beginning.
119
120 # The full list of option settings for any particular driver instance,
121 # including all the defaulted values, can be extracted by making use of
122 # the -bP command line option.
123
124 # exim clear out message queue. as root:
125 # adapted from somewhere on stackoverflow.
126 # ser stop exim4; sleep 1; exim -bp | exiqgrep -i | xargs exim -Mrm; ser start exim4
127
128 # fastmail has changed their smtp server, but the old one still works,
129 # I see no reason to bother changing.
130 # New one is smtp.fastmail.com
131
132 # test delivery & rewrite settings:
133 #exim4 -bt ian@localhost
134
135
136 type=$1
137 postfix() { [[ $type == postfix ]]; }
138 exim() { [[ $type == exim4 ]]; }
139 if ! exim && ! postfix; then
140 echo "$1: error: expected exim4 or postfix as first arg"
141 exit 1
142 fi
143
144
145 local_mx=mail.iankelling.org
146
147 host=$local_mx
148 relayhost="[$host]:25" # postfix
149 smarthost="$host::25" # exim
150
151
152 # this was for when I used the exim config type
153 # "mail sent by smarthost; received via SMTP or fetchmail"
154 # if [[ $HOSTNAME == $MAIL_HOST ]]; then
155 # host=mail.messagingengine.com
156 # relayhost="[$host]:587" # postfix
157 # smarthost="$host::587" # exim
158 # fi
159
160 forward=ian@$local_mx
161
162
163 # background: This also works instead of ~/.forward
164 # s sed -i --follow-symlinks '/^root/d' /etc/aliases ||:
165 #echo "root: $HOSTNAME@$SOME_DOMAIN" | s tee -a /etc/aliases
166 # this can't be a symlink and has permission restrictions
167 # it might work in /etc/aliases, but this seems more proper.
168 e $forward > ~/.forward
169 e $forward | s tee /root/.forward
170 # exim log complains about 664 permissions.
171 s chmod 644 ~/.forward /root/.forward
172
173
174 # offlineimap uses this too, it is much easier to use one location than to
175 # condition it's config and postfix's config
176 case $distro in
177 fedora) s lnf -T ca-certificates.crt /etc/ssl/ca-bundle.trust.crt ;;
178 *) :
179 esac
180
181 if postfix; then
182 # dunno why, but debian installed postfix with builddep emacs
183 # but I will just explicitly install it here since
184 # I use it for sending mail in emacs.
185 if isdeb; then
186 s debconf-set-selections <<EOF
187 postfix postfix/main_mailer_type select Satellite system
188 postfix postfix/mailname string $HOSTNAME
189 postfix postfix/relayhost string $relayhost
190 EOF
191
192 pi postfix
193 else
194 pi postfix
195 # Settings from reading the output when installing on debian,
196 # then seeing which were different in a default install on arch.
197 # I assume the same works for fedora.
198 postconfin <<EOF
199 mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
200 mailbox_size_limit = 0
201 relayhost = $relayhost
202 inet_interfaces = loopback-only
203 EOF
204
205 s systemctl enable postfix
206 s systemctl start postfix
207 fi
208 # i'm assuming mail just won't work on systems without the sasl_passwd.
209 postconfin <<'EOF'
210 smtp_sasl_auth_enable = yes
211 smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
212 smtp_sasl_security_options = noanonymous
213 smtp_tls_security_level = secure
214 message_size_limit = 20480000
215 smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
216 inet_protocols = ipv4
217 EOF
218 # msg_size_limit: I ran into a log file not sending cuz of size. double from 10 to 20 meg limit
219 # inet_protocols: without this, postfix tries an ipv6 lookup then gives
220 # up and fails. snippet from syslog: type=AAAA: Host not found, try again
221
222
223 f=/etc/postfix/sasl_passwd
224 s rm -f $f
225 s touch $f
226 s chmod 600 $f
227 s cat /etc/mailpass| while read -r domain port pass; do
228 # format: domain port user:pass
229 # mailpass is just a name i made up, since postfix and
230 # exim both use a slightly crazy format to translate to
231 # each other, it\'s easier to use my own format.
232 printf "[%s]:%s %s" "$domain" "$port" "${pass/@/#}" | s tee -a $f >/dev/null
233 done
234 s postmap hash:/etc/postfix/sasl_passwd
235 s service postfix reload
236
237 else # exim. has debian specific stuff for now
238
239
240 # wording of question from dpkg-reconfigure exim4-config
241 # 1. internet site; mail is sent and received directly using SMTP
242 # 2. mail sent by smarthost; received via SMTP or fetchmail
243 # 3. mail sent by smarthost; no local mail
244 # 4. local delivery only; not on a network
245 # 5. no configuration at this time
246 #
247 # Note, I have used option 2 in the past for receiving mail
248 # from lan hosts, sending external mail via another smtp server.
249 #
250 # Note, other than configtype, we could set all the options in
251 # both types of configs without harm, they would either be
252 # ignored or be disabled by other settings, but the default
253 # local_interfaces definitely makes things more secure.
254
255 # most of these settings get translated into settings
256 # in /etc/exim4/update-exim4.conf.conf
257 # mailname setting sets /etc/mailname
258
259 s debconf-set-selections <<EOF
260 exim4-config exim4/use_split_config boolean true
261 EOF
262
263 source /a/bin/bash_unpublished/source-semi-priv
264 exim_main_dir=/etc/exim4/conf.d/main
265 s mkdir -p exim_main_dir
266 if [[ $HOSTNAME == $MAIL_HOST ]]; then
267 # afaik, these will get ignored, routing to my own machine, but rm
268 # them to make me feel better.
269 s rm -f ~/.forward /root/.forward
270
271 s debconf-set-selections <<EOF
272 # Mail Server configuration
273 # -------------------------
274
275 # Please select the mail server configuration type that best meets your needs.
276
277 # Systems with dynamic IP addresses, including dialup systems, should generally be
278 # configured to send outgoing mail to another machine, called a 'smarthost' for
279 # delivery because many receiving systems on the Internet block incoming mail from
280 # dynamic IP addresses as spam protection.
281
282 # A system with a dynamic IP address can receive its own mail, or local delivery can be
283 # disabled entirely (except mail for root and postmaster).
284
285 # 1. internet site; mail is sent and received directly using SMTP
286 # 2. mail sent by smarthost; received via SMTP or fetchmail
287 # 3. mail sent by smarthost; no local mail
288 # 4. local delivery only; not on a network
289 # 5. no configuration at this time
290
291 # General type of mail configuration: 1
292 exim4-config exim4/dc_eximconfig_configtype select internet site; mail is sent and received directly using SMTP
293
294
295
296 # The 'mail name' is the domain name used to 'qualify' mail addresses without a domain
297 # name.
298
299 # This name will also be used by other programs. It should be the single, fully
300 # qualified domain name (FQDN).
301
302 # Thus, if a mail address on the local host is foo@example.org, the correct value for
303 # this option would be example.org.
304
305 # This name won't appear on From: lines of outgoing messages if rewriting is enabled.
306
307 # System mail name:
308 exim4-config exim4/mailname string li.iankelling.org
309
310
311
312
313 # Please enter a semicolon-separated list of recipient domains for which this machine
314 # should consider itself the final destination. These domains are commonly called
315 # 'local domains'. The local hostname (treetowl.lan) and 'localhost' are always added
316 # to the list given here.
317
318 # By default all local domains will be treated identically. If both a.example and
319 # b.example are local domains, acc@a.example and acc@b.example will be delivered to the
320 # same final destination. If different domain names should be treated differently, it
321 # is necessary to edit the config files afterwards.
322
323 # Other destinations for which mail is accepted:
324 # iank.bid is for testing
325 # mail.iankelling.org is for machines i own
326 exim4-config exim4/dc_other_hostnames string mail.iankelling.org;iank.bid;iankelling.org;zroe.org
327
328
329
330
331 # Please enter a semicolon-separated list of IP addresses. The Exim SMTP listener
332 # daemon will listen on all IP addresses listed here.
333
334 # An empty value will cause Exim to listen for connections on all available network
335 # interfaces.
336
337 # If this system only receives mail directly from local services (and not from other
338 # hosts), it is suggested to prohibit external connections to the local Exim daemon.
339 # Such services include e-mail programs (MUAs) which talk to localhost only as well as
340 # fetchmail. External connections are impossible when 127.0.0.1 is entered here, as
341 # this will disable listening on public network interfaces.
342
343 # IP-addresses to listen on for incoming SMTP connections:
344 exim4-config exim4/dc_local_interfaces string
345
346
347
348
349 # Mail for the 'postmaster', 'root', and other system accounts needs to be redirected
350 # to the user account of the actual system administrator.
351
352 # If this value is left empty, such mail will be saved in /var/mail/mail, which is not
353 # recommended.
354
355 # Note that postmaster's mail should be read on the system to which it is directed,
356 # rather than being forwarded elsewhere, so (at least one of) the users listed here
357 # should not redirect their mail off this machine. A 'real-' prefix can be used to
358 # force local delivery.
359
360 # Multiple user names need to be separated by spaces.
361
362 # Root and postmaster mail recipient:
363 exim4-config exim4/dc_postmaster string ian
364
365
366
367 # Exim is able to store locally delivered email in different formats. The most commonly
368 # used ones are mbox and Maildir. mbox uses a single file for the complete mail folder
369 # stored in /var/mail/. With Maildir format every single message is stored in a
370 # separate file in ~/Maildir/.
371
372 # Please note that most mail tools in Debian expect the local delivery method to be
373 # mbox in their default.
374
375 # 1. mbox format in /var/mail/ 2. Maildir format in home directory
376
377 # Delivery method for local mail: 2
378 exim4-config exim4/dc_localdelivery select Maildir format in home directory
379 EOF
380 # MAIN_HARDCODE_PRIMARY_HOSTNAME might mess up the
381 # smarthost config type, not sure. all other settings
382 # would be unused in that config type.
383 s dd of=$exim_main_dir/000_localmacros 2>/dev/null <<'EOF'
384 MAIN_TLS_ENABLE = true
385
386 DKIM_CANON = relaxed
387 DKIM_SELECTOR = li
388
389 # from comments in
390 # https://debian-administration.org/article/718/DKIM-signing_outgoing_mail_with_exim4
391
392 # The file is based on the outgoing domain-name in the from-header.
393 DKIM_DOMAIN = ${lc:${domain:$h_from:}}
394 # sign if key exists
395 DKIM_PRIVATE_KEY= ${if exists{/etc/exim4/${dkim_domain}-private.pem} {/etc/exim4/${dkim_domain}-private.pem}}
396
397
398 # failing message on mail-tester.com:
399 # We check if there is a server (A Record) behind your hostname treetowl.
400 # You may want to publish a DNS record (A type) for the hostname treetowl or use a different hostname in your mail software
401 # https://serverfault.com/questions/46545/how-do-i-change-exim4s-primary-hostname-on-a-debian-box
402 # and this one seemed appropriate from grepping config
403 MAIN_HARDCODE_PRIMARY_HOSTNAME = li.iankelling.org
404
405 # normally empty, I set this so I can set the envelope address
406 # when doing mail redelivery to invoke filters
407 MAIN_TRUSTED_GROUPS = ian
408
409 # disabled, didn't finished configuring
410 #LOCAL_DELIVERY = dovecot_lmtp
411
412 CHECK_RCPT_LOCAL_ACL_FILE = /etc/exim4/rcpt_local_acl
413 EOF
414
415
416 s dd of=/etc/systemd/system/offlineimapsync.timer <<'EOF'
417 [Unit]
418 Description=Run offlineimap-sync once every 5 mins
419
420 [Timer]
421 OnCalendar=*:0/5
422
423 [Install]
424 WantedBy=timers.target
425 EOF
426
427 s dd of=/etc/systemd/system/offlineimapsync.service <<'EOF'
428 [Unit]
429 Description=Offlineimap sync
430 After=multi-user.target
431
432 [Service]
433 Type=oneshot
434 ExecStart=/a/bin/log-quiet/sysd-mail-once offlineimap-sync /a/bin/distro-setup/offlineimap-sync
435 EOF
436 s systemctl daemon-reload
437 s systemctl enable offlineimapsync.timer
438 s systemctl start offlineimapsync.timer
439
440 else # $HOSTNAME != $MAIL_HOST
441 s systemctl disable offlineimapsync.timer &>/dev/null ||:
442 s systemctl stop offlineimapsync.timer &>/dev/null ||:
443 #
444 #
445 # would only exist because I wrote it i the previous condition,
446 # it's not part of exim
447 s rm -f $exim_main_dir/000_localmacros
448 s debconf-set-selections <<EOF
449 exim4-config exim4/dc_eximconfig_configtype select mail sent by smarthost; no local mail
450 exim4-config exim4/dc_smarthost string $smarthost
451 EOF
452 fi
453
454 # if we already have it installed, need to reconfigure, without being prompted
455 if ! dpkg -s exim4-config &>/dev/null; then
456 s dpkg-reconfigure -u -pcritical exim4-config
457 fi
458 # light version does not have sasl auth support.
459 pi exim4-daemon-heavy spamassassin
460
461 ##### begin spamassassin config
462 ser enable spamassassin
463 # per readme.debian
464 s sed -i '/^\s*CRON\s*=/d' /etc/default/spamassassin
465 s tee -a /etc/default/spamassassin <<<CRON=1
466 # just noticed this in the config file, seems like a good idea.
467 s sed -i '/^\s*NICE\s*=/d' /etc/default/spamassassin
468 s tee -a /etc/default/spamassassin <<<'NICE="--nicelevel 15"'
469
470 s dd of=/etc/systemd/system/spamddnsfix.service <<'EOF'
471 [Unit]
472 Description=spamd dns bug fix cronjob
473
474 [Service]
475 Type=oneshot
476 ExecStart=/a/bin/distro-setup/spamd-dns-fix
477 EOF
478 s dd of=/etc/systemd/system/spamddnsfix.timer <<'EOF'
479 [Unit]
480 Description=run spamd bug fix script every 10 minutes
481
482 [Timer]
483 # the script looks back 9 minutes into the journal,
484 # it takes a second to run,
485 # so lets run every 9 minutes and 10 seconds.
486 OnActiveSec=550
487
488 [Install]
489 WantedBy=timers.target
490 EOF
491 ser daemon-reload
492 sgo spamddnsfix.timer
493 #
494 ##### end spamassassin config
495
496 gitslink # needed to install the execstart files below
497 s dd of=/etc/systemd/system/mailcert.service <<'EOF'
498 [Unit]
499 Description=Mail cert rsync
500 After=multi-user.target
501
502 [Service]
503 Type=oneshot
504 ExecStart=/usr/local/bin/sysd-mail-once mailcert /usr/local/bin/mail-cert-cron
505 EOF
506
507 s dd of=/etc/systemd/system/mailcert.timer <<'EOF'
508 [Unit]
509 Description=Run mail-cert once a day
510
511 [Timer]
512 OnCalendar=daily
513
514 [Install]
515 WantedBy=timers.target
516 EOF
517 ser daemon-reload
518 ser start mailcert
519 sgo mailcert.timer
520
521
522 # based on a little google and package search, just the dovecot
523 # packages we need instead of dovecot-common.
524 #
525 # dovecot-lmtpd is for exim to deliver to dovecot instead of maildir
526 # directly. The reason to do this is to use dovecot's sieve, which
527 # has extensions that allow it to be almost equivalent to exim's
528 # filter capabilities, some ways probably better, some worse, and
529 # sieve has the benefit of being supported in postfix and
530 # proprietary/weird environments, so there is more examples on the
531 # internet. I was torn about whether to do this or not, meh.
532 pi dovecot-core dovecot-imapd dovecot-sieve dovecot-lmtpd
533
534 # if we changed 90-sieve.conf and removed the active part of the
535 # sieve option, we wouldn't need this, but I'd rather not modify a
536 # default config if not needed. This won't work as a symlink in /a/c
537 # unfortunately.
538 lnf -T sieve/main.sieve ~/.dovecot.sieve
539
540 # we have a few config files which installing exim/dovecot overwrites,
541 # and might as well have this before reading /etc/mailpass,
542 # which this sets up too.
543 conflink
544
545 # begin setup passwd.client
546 f=/etc/exim4/passwd.client
547 s rm -f $f
548 s touch $f
549 s chmod 640 $f
550 s chown root:Debian-exim $f
551 # note: this will go away
552 s cat /etc/mailpass| while read -r domain port pass; do
553 # reference: exim4_passwd_client(5)
554 printf "%s:%s\n" "$domain" "$pass" | s tee -a $f >/dev/null
555 done
556 # end setup passwd.client
557
558 # https://blog.dhampir.no/content/make-exim4-on-debian-respect-forward-and-etcaliases-when-using-a-smarthost
559 # i only need .forwards, so just doing that one.
560 cd /etc/exim4/conf.d/router
561 a=userforward
562 b=${a}_higher_priority
563 tmp=$(mktemp)
564 of=175_$b
565 # sed to make the router name unique
566 sed -r s/^\\S+:/$b:/ 600_exim4-config_$a | s dd of=$tmp 2>/dev/null
567 if ! diff -q $tmp $of &>/dev/null; then
568 s dd if=$tmp of=$of >/dev/null
569 fi
570
571
572 ser restart exim4
573
574 fi
575
576
577
578 # linode image has a root alias. completely useless, remove it.
579 sudo sed -i '/^root:/d' /etc/aliases
580
581 s newaliases
582
583
584 # based on http://www.postfix.org/qmgr.8.html and my notes in gnus
585 dir=/nocow/$type
586 sdir=/var/spool/$type
587 if [[ $(readlink -f $sdir) != $dir ]]; then
588 ser stop $type
589 if [[ ! -e $dir && -d $sdir ]]; then
590 s mv $sdir $dir
591 fi
592 s lnf -T $dir $sdir
593 fi
594
595 sgo $type
596
597
598 # if I wanted the from address to be renamed and sent to a different address,
599 # echo "sdx@localhost development@localhost" | sudo dd of=/etc/postfix/recipient_canonical
600 # sudo postmap hash:/etc/postfix/recipient_canonical
601 # sudo service postfix reload