Почтовый сервер на базе OpenBSD 6.0
Вступление
Перевод статьи Chess Griffin с небольшим количеством комментариев от переводчика, в основном связанных с тем, что с момента релиза OpenBSD 5.6, система стала еще лучше!
Цель
Создать достаточно безопасный почтовый сервер на базе OpenBSD и нескольких пакетов. OpenSMTPD, spamd, pf и httpd входят в состав базовой системы. Дополнительно потребуются ClamAV, ClamSMTP, SpamAssassin, SpamPD, DKIMproxy, Dovecot, Dovecot-Pigeonhole и Roundcube.
Окончательный результат
Обработка входящих сообщений
pf -> spamd -> opensmtpd -> clamsmtpd -> clamd -> clamsmtpd -> opensmtpd -> spampd -> SpamAssassin -> spampd -> opensmtpd -> deliver to dovecot/lmtp
Обработка исходящих сообщений
opensmtpd -> clamsmtpd -> clamd -> clamsmtpd -> opensmtpd -> dkimproxy -> opensmtpd -> relay out
Дополнительно
Доступ посредством IMAP (SSL): Dovecot
Доступ к почте через веб-интерфейса (SSL): httpd и Roundcube
Почему OpenBSD?
Это прекрасная операционная система, созданная и поддерживаемая многими умными людьми. Кроме того, мне нравится, что большое количество великолепного программного обеспечения включено в базовую систему. Если вы найдёте это руководство полезным или откроете как восхитительна OpenBSD, пожалуйста подумайте над тем, чтобы поддержать проект - это может быть приобретение набора компакт дисков [1] или сделав пожертвование. Команда разработчиков OpenBSD отлично выполняет свою работу, которая приносит пользу всему сообществу и ваша поддержка не будет лишней!
Зачем SpamAssassin в дополнение к spamd?
Spamd отлично работает, не создавая лишней нагрузки. Он отлавливает большую часть моего спама (более 95%), так что я почти решил отказаться от возни со SpamAssassin. Но подумав, решил что будет интересно попробовать интегрировать их оба.
Почему не <вставьте имя любимой операционной системы или программы>?
Никогда не слышал об этом. ;-)
Why bother with setting up your own email server to begin with? Why not just keep using Gmail?
I used to run my own email server back when I hosted the Linux Reality podcast and decided it would be a fun exercise to try it again. The email server I set up using the steps in this guide might become my primary email server. Or, I might take the server down tomorrow and go back to using AOL and working on my Geocities page. Who knows?
Assumptions:
This guide assumes an understanding of how to install and configure OpenBSD and an understanding of networking and email, both in general and in regards to OpenBSD in particular. Additionally, this guide assumes an understanding of how to install packages with a properly configured $PKG_PATH, how to work from the command line and edit configuration files, how to change DNS records and MX records, and other general nuts and bolts. These kinds of basic topics will not be covered in this guide.
Disclaimer:
I am an ordinary OpenBSD user. I am not a sysadmin, developer, programmer, kung-fu master, or expert in any of these areas. This guide is mainly a writeup for myself so I can replicate these steps in the future. If someone finds it helpful, fine, but it is by no means the only way or even the best way to configure an email server. There are most likely mistakes in this guide, so take it for what it's worth and YMMV. If your email breaks because of this guide, then don't run your own email server. Feedback and corrections are welcome.
Updates:
Updated the last line of example smtpd.conf from "for any" to "for domain <vdomains>". Thanks to Christoph on the opensmtpd-misc mailing list. Removed bit about enabling pf since it's enabled by default. Duh. Also changed notations of port 587 to 'submission' which is the name of that port in /etc/services. Thanks to rjc.
Resources:
- OpenBSD FAQ (required)
- OpenBSD man pages (required)
- OpenSMTPD wiki
- Helpful thread on OpenSMTPD mailing list re: tagging and proxying
- http://www.kernel-panic.it/openbsd/mail/ (the bits about ClamAV and SpamAssassing are helpful)
- https://coderwall.com/p/eejzja/simple-smtp-server-with-opensmtpd
- http://blog.ehouse.io/mail-server-basic-smtp.html
- http://blog.admiral0.it/computing/mail-server-with-opensmtpd-dovecot-and-amavisdspamassassin
Initial Setup
- Install OpenBSD 5.6. If using the auto-partitioner, make sure enough space is allocated to /usr and /usr/src to allow for extracting the sources (below). Edit /etc/rc.conf.local and add “-s” to ntpd_flags so time is set at boot if desired.
- Add a rule to default /etc/pf.conf to allow incoming ssh connections, such as:
# cat /etc/pf.conf
…
pass in on egress proto tcp to any port ssh
…
- Reload pf with:
# pfctl -f /etc/pf.conf
- Update the system by fetching the sources via ftp and patching.
- Set up $PKG_PATH to install packages.
- Configure MX records etc. at domain registrar, perhaps with an unused domain for testing purposes.
OpenSMTPD и spamd
- Read the man page for smtpd and smtpd.conf and review the configuration files.
- Set up virtual users and virtual domains:
# cat /etc/mail/vusers
joe@example.com joe
@example.com joe
joe@example.net joe
@example.net joe
# cat /etc/mail/vdomains
example.com
example.net
- Create SSL certificates as described in man 5 smtpd.conf:
# openssl genrsa -out /etc/ssl/private/mail.example.com.key 4096
# openssl req -new -x509 -key /etc/ssl/private/mail.example.com.key -out /etc/ssl/mail.example.com.crt -days 365
# chmod 600 /etc/ssl/mail.example.com.crt
# chmod 600 /etc/ssl/private/mail.example.com.key
- Create ~/Maildir for user ("joe" in this example).
- Edit /etc/mail/smtpd.conf so it listens on egress with tls (for incoming mail) and egress port 587 (submission) with tls and authentication (for outgoing mail), accepts mail for virtual users and virtual domains, and delivers this mail to Maildir. Note that the smtpd.conf man page clearly says: "For each message processed by the daemon, the filter rules are evaluated in sequential order, from first to last. The first matching rule decides what action is taken." Therefore, the order of the rules in smtpd.conf is very important and will become more important as additional bits are added (e.g. for clamsmtp, spampd, and dkimproxy).
# cat /etc/mail/smtpd.conf
pki mail.example.com certificate "/etc/ssl/mail.example.com.crt"
pki mail.example.com key "/etc/ssl/private/mail.example.com.key"
listen on lo0
listen on egress tls pki mail.example.com auth-optional
listen on egress port submission tls-require pki mail.example.com auth
table aliases db:/etc/mail/aliases.db
table vusers file:/etc/mail/vusers
table vdomains file:/etc/mail/vdomains
accept for local alias <aliases> deliver to maildir
accept from any for domain <vdomains> virtual <vusers> deliver to maildir
accept from local for any relay
- Edit pf.conf to allow connections on smtp port 25 and port 587, such as:
# cat /etc/pf.conf
...
pass in on egress proto tcp to any port smtp
pass in on egress proto tcp to any port submission
...
- Reload pf and start /etc/rc.d/smtpd.
- Test sending mail to/from the user's account. Since there is no imap client yet, might want to install mutt or something similar and point to the user's ~/Maildir to check incoming mail. The user should be able to connect to OpenSMTPD on port 587 from an outside client to send mail through OpenSMTPD to another party. Sending outbound mail from the command line should also work. Perhaps telnet into the server or run a couple of SMTP checks against the server like this one to verify things are working correctly. The session transcript should look something like this:
Connecting to 123.456.789.000
220 mail.example.com ESMTP OpenSMTPD [624 ms]
EHLO MXTB-PWS3.mxtoolbox.com
250-mail.example.com Hello MXTB-PWS3.mxtoolbox.com [64.20.227.133], pleased to meet you
250-8BITMIME
250-ENHANCEDSTATUSCODES
250-SIZE 36700160
250-DSN
250-STARTTLS
250 HELP [640 ms]
MAIL FROM: <supertool@mxtoolbox.com>
250 2.0.0: Ok [640 ms]
RCPT TO: <test@example.com>
550 Invalid recipient [640 ms]
MXTB-PWS3v2 3260ms
- If that works, set up spamd. This is a very simple and standard setup and there are lots of resources out there on how to do this, but here is the shorthand: Add spamd_flags=”-v” to /etc/rc.conf.local. Edit /etc/mail/spamd.conf to add override/whitelist if desired (file /etc/mail/nospamd in sample pf rules). Add spamd pf rules from example /etc/pf.conf and comment out prior rule that passed smtp on egress (because now we want incoming mail to be redirected to spamd running on localhost port 8025):
# cat /etc/pf.conf
...
#pass in on egress proto tcp to any port smtp
pass in on egress proto tcp to any port submission
# rules for spamd(8)
table <spamd-white> persist
table <nospamd> persist file "/etc/mail/nospamd"
pass in on egress proto tcp from any to any port smtp rdr-to 127.0.0.1 port spamd
pass in on egress proto tcp from <nospamd> to any port smtp
pass in log on egress proto tcp from <spamd-white> to any port smtp
pass out log on egress proto tcp to any port smtp
...
- Reload pf and start /etc/rc.d/spamd. Check netstat to see if spamd is listening on port 8025:
# netstat -na -f inet
- Send test emails again and check logs and 'spamdb' to see if email is getting greylisted. Once spamd is working, those third-party SMTP checks won't work because spamd is intercepting incoming mail. Same with telnet, if you can stand waiting for the stuttering. ;-) Anyway, now the session transcript should look something like this:
Connecting to 123.456.789.000
220 mail.example.com ESMTP spamd IP-based SPAM blocker; Sat Jan 31 11:33:21 2015 [11716 ms]
EHLO MXTB-PWS3.mxtoolbox.com
250 Hello, spam sender. Pleased to be wasting your time. [640 ms]
MAIL FROM: <supertool@mxtoolbox.com>
250 You are about to try to deliver spam. Your time will be spent, for nothing. [640 ms]
RCPT TO: <test@example.com>
250 This is hurting you more than it is hurting me. [640 ms]
MXTB-PWS3v2 14602ms
- Haha. Love spamd.
- So here is what's happening:
- Incoming mail:
- pf -> relay to spamd -> send to opensmtpd on lo0 -> deliver to maildir
- Outoing mail:
- opensmtpd on lo0 -> relay out
ClamAV and ClamSMTP
- Install clamav and clamsmtp from packages.
- Edit /etc/freshclam.conf -- comment out the “Example” line and uncomment the "DatabaseMirror" line and add the relevant country code in place of the "XY."
# cat /etc/freshclam.conf
#Example
...
DatabaseMirror db.us.clamav.net
...
- Run ‘freshclam’ to update the database. Add a freshclam command to root’s crontab to have periodic updates:
20 * * * * /usr/local/bin/freshclam >/dev/null 2>&1
- Once freshclam has updated the database, edit /etc/clamd.conf. Comment out the “Example” line, uncomment “TCPSocket” and “TCPAddr” lines and change them so clamd listens on port 3310 at 127.0.0.1.
# cat /etc/clamd.conf
#Example
...
TCPSocket 3310
...
TCPAddr 127.0.0.1
...
- Add “clamd” to pkg_scripts in /etc/rc.conf.local and then start clamd. Check netstat -na -f inet to see if clamd is running on 127.0.0.1:3310. Check out both /etc/freshclam.conf and /etc/clamd.conf to look at logging options or actions (in VirusEvent) to take when a virus is found. Can set it up so it drops an email into root's mailbox when a virus is found.
- Now, set up clamsmtp, which is a proxy for clamd. Two config files will be used, one for incoming mail and one for outgoing mail. OpenSMTPD will accept mail, send it to clamsmtp on one port for incoming mail (10025) and a different port (10027) for outgoing mail. Clamsmtp will run the mail through clamd, and then return it to OpenSMTPD for incoming mail (10026) or outgoing mail (10028). Depending on which port the mail is returned to, OpenSMTPD will tag it CLAM_IN or CLAM_OUT.
- So copy /etc/clamsmtpd.conf and create /etc/clamsmtpd-in.conf and /etc/clamsmtpd-out.conf. Modify the files like so:
# cat /etc/clamsmtpd-in.conf
OutAddress: 10026
...
Listen: 0.0.0.0:10025
...
ClamAddress: 127.0.0.1:3310
...
# cat /etc/clamsmtpd-out.conf
OutAddress: 10028
...
Listen: 0.0.0.0:10027
...
ClamAddress: 127.0.0.1:3310
...
- Start them both:
# /usr/local/sbin/clamsmtpd -f /etc/clamsmtpd-in.conf
# /usr/local/sbin/clamsmtpd -f /etc/clamsmtpd-out.conf
- (add something similar to /etc/rc.local so they start at boot)
- Edit /etc/mail/smtpd.conf so it looks like this:
# cat /etc/mail/smtpd.conf
pki mail.example.com certificate "/etc/ssl/mail.example.com.crt"
pki mail.example.com key "/etc/ssl/private/mail.example.com.key"
listen on lo0
listen on lo0 port 10026 tag CLAM_IN # incoming mail
listen on lo0 port 10028 tag CLAM_OUT # outgoing mail
listen on egress tls pki mail.example.com auth-optional
listen on egress port submission tls-require pki mail.example.com auth
table aliases db:/etc/mail/aliases.db
table vusers file:/etc/mail/vusers
table vdomains file:/etc/mail/vdomains
accept for local alias <aliases> deliver to maildir
# tagged mail returned from clamsmtpd either deliver or relay
accept tagged CLAM_IN for domain <vdomains> virtual <vusers> deliver to maildir
accept tagged CLAM_OUT for any relay
# start here - untagged mail is sent to clamsmtpd
accept from any for domain <vdomains> relay via smtp://127.0.0.1:10025 # incoming mail
accept from local for any relay via smtp://127.0.0.1:10027 # outgoing mail
- So here is what's happening:
- Incoming mail:
- pf -> relay to spamd -> send to opensmtpd on lo0 -> relay untagged mail to clamsmtpd on port 10025 -> relay to clamd on port 3310 -> return to clamsmtpd -> return to opensmtpd on lo0 port 10026 and tag it CLAM_IN -> deliver to maildir
- Outoing mail:
- opensmtpd on lo0 -> relay untagged mail to clamsmtpd on port 10027 -> relay to clamd on port 3310 -> return to clamsmtpd -> return to opensmtpd on lo0 port 10028 and tag it CLAM_OUT -> relay out
- Send some emails both ways. This should be in the header:
X-Virus-Scanned: ClamAV using ClamSMTP
SpamAssassin and SpamPD
Примечания
- ↑ С релиза 6.1, OpenBSD не будет распространяться на CD, но вы по прежнему можете приобрести различные предметы с символикой OpenBSD. прим. переводчика