Почтовый сервер на базе OpenBSD 6.0

Материал из OpenBSD-Wiki
Перейти к навигации Перейти к поиску

Вступление

Перевод статьи 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 Mail Server - Part 1, Initial Setup

  1. 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.
  2. 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
  3. Reload pf with:
    # pfctl -f /etc/pf.conf
  4. Update the system by fetching the sources via ftp and patching.
  5. Set up $PKG_PATH to install packages.
  6. Configure MX records etc. at domain registrar, perhaps with an unused domain for testing purposes.

OpenSMTPD и spamd

  1. Read the man page for smtpd and smtpd.conf and review the configuration files.
  2. 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

  3. 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

  4. Create ~/Maildir for user ("joe" in this example).
  5. 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
  6. 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
    ...
  7. Reload pf and start /etc/rc.d/smtpd.
  8. 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
  9. 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

  10. 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.
  11. 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

Примечания

  1. С релиза 6.1, OpenBSD не будет распространяться на CD, но вы по прежнему можете приобрести различные предметы с символикой OpenBSD. прим. переводчика