Operating System BSD

Build Your Own Mail Server on FreeBSD 15 with OpenSMTPD, Dovecot and spamd

Set up OpenSMTPD, Dovecot and spamd greylisting behind PF on FreeBSD 15, with TLS and Maildir mailboxes for system users.

This guide builds a small, complete mail server on FreeBSD 15.1 (the steps are the same on FreeBSD 14.5): OpenSMTPD receives and sends mail, Dovecot gives your mail client IMAP access, and OpenBSD's spamd greylists unknown senders in front of the SMTP port, steered by the PF firewall. Mailboxes belong to ordinary system users and are stored in Maildir format. FreeBSD 11 reached end of life in 2021; its packages are gone and OpenSMTPD's configuration grammar has changed completely since then, so accept ... deliver to rules from older tutorials no longer load.

Running your own mail server is practical for a few mailboxes if you accept the upkeep: you are responsible for DNS, TLS certificates, updates and your IP address's reputation.

How the pieces fit together

Unknown sender   -> PF redirect -> spamd (greylist, port 8025)
Whitelisted host -> PF pass     -> OpenSMTPD (port 25) -> ~/Maildir
Your mail client -> OpenSMTPD (port 587, TLS + login) -> Internet
Your mail client -> Dovecot (IMAPS, port 993)         -> ~/Maildir

spamd answers first-time senders with a temporary error. Real mail servers retry; when the same delivery is retried after the waiting period (25 minutes by default), spamd adds the sender's address to the PF table spamd-white, and from then on PF lets that host through to OpenSMTPD.

Requirements

  • A FreeBSD 15.1 or 14.5 server with root access. Commands are run as root.
  • A static IPv4 address (203.0.113.10 in the examples) and a host name, here mail.example.com.
  • Outbound and inbound TCP port 25. Many hosting providers block it by default; ask your provider to open it before you start.
  • DNS records: an A record for mail.example.com, an MX record for example.com pointing to it, a PTR (reverse DNS) record for the IP address that resolves back to mail.example.com, and an SPF TXT record such as v=spf1 mx -all.
  • The name of your network interface (vtnet0 on most virtual servers). Check with ifconfig.
  • Access to your provider's web console. The FreeBSD Handbook advises doing the first firewall configuration from the console, because a wrong rule can cut off SSH.

Install the packages

pkg update
pkg install opensmtpd dovecot spamd py312-certbot

If the certbot package is not found, run pkg search certbot; its prefix follows the default Python version. The dovecot package is the 2.3 series. FreeBSD also packages Dovecot 2.4 as dovecot24, but 2.4 uses a different configuration format and the settings below are for 2.3.

Since FreeBSD 14 the base system's default mail agent is dma, selected in /etc/mail/mailer.conf. Make sure no Sendmail daemon is started, then point the standard mail commands at OpenSMTPD so that local programs and cron jobs deliver through it. Replace the active lines in /etc/mail/mailer.conf with:

sendmail        /usr/local/sbin/smtpctl
send-mail       /usr/local/sbin/smtpctl
mailq           /usr/local/sbin/smtpctl
makemap         /usr/local/libexec/opensmtpd/makemap
newaliases      /usr/local/libexec/opensmtpd/makemap
sysrc sendmail_enable=NONE

Get a TLS certificate

Request a Let's Encrypt certificate while the firewall is not yet active. The standalone method needs port 80 to be free:

certbot certonly --standalone -d mail.example.com

The certificate and key are written to /usr/local/etc/letsencrypt/live/mail.example.com/.

Create a mail user

Every mailbox is a system account. Create one with adduser; choose nologin as the shell if the person only needs mail:

adduser

The examples assume a user called alice, whose address will be alice@example.com. To receive system mail, edit /etc/mail/aliases and set root: alice.

Both daemons check passwords through PAM: Dovecot under the service name dovecot, OpenSMTPD under smtpd. Neither package installs a PAM file, so without one both would use the system's fallback policy in /etc/pam.d/other. Create a service file for each. The two lines are the same checks FreeBSD ships for its own imap PAM service: the password and the account's validity, against the system password database.

printf 'auth\t\trequired\tpam_unix.so\naccount\t\trequired\tpam_unix.so\n' > /etc/pam.d/dovecot
cp /etc/pam.d/dovecot /etc/pam.d/smtpd

Configure PF and spamd

For greylisting, spamd needs its service names in /etc/services and the fdescfs file system mounted on /dev/fd. The package ships a helper for the first step:

/usr/local/sbin/add-spamd-to-etc-service
echo 'fdescfs /dev/fd fdescfs rw 0 0' >> /etc/fstab
mount /dev/fd

The package also installs /usr/local/etc/spamd/spamd.conf.sample. That file only configures optional downloaded blacklists for spamd-setup, and the service script runs spamd-setup only when spamd.conf exists, so leave the sample uncopied for plain greylisting. If you do want blacklists, copy it to spamd.conf and first review the lists named in its all entry; the Handbook warns that using every list in the sample blocks large parts of the Internet.

Create /etc/pf.conf. Change ext_if to your interface name. If your SSH daemon listens on a port other than 22, replace ssh in the first pass in rule with that port number:

ext_if = "vtnet0"

table <spamd-white> persist

set skip on lo0
scrub in all

# Known-good senders go straight to OpenSMTPD, everyone else to spamd
no rdr on $ext_if inet proto tcp from <spamd-white> to any port smtp
rdr pass on $ext_if inet proto tcp from any to any port smtp \
    -> 127.0.0.1 port spamd

block in all
pass out all keep state

# No interface name here: a wrong ext_if must not be able to block SSH
pass in proto tcp to port { ssh, http, submission, imaps }
pass in log on $ext_if inet proto tcp to port smtp
pass in on $ext_if inet6 proto tcp to port smtp
pass out log on $ext_if inet proto tcp to port smtp
pass in inet proto icmp icmp-type echoreq
pass in inet6 proto icmp6

The two log rules matter: spamlogd watches the PF log for SMTP connections that reach the real mail server and keeps those hosts whitelisted, including hosts you send mail to. The redirect is IPv4 only, so mail arriving over IPv6 reaches OpenSMTPD directly. Port 80 stays open for certificate renewal.

Load the PF kernel module and check the rule set for syntax errors. Nothing is filtered yet:

kldload -n pf
pfctl -nf /etc/pf.conf

Now make a trial run that switches the firewall off again by itself after two minutes:

service pf onestart; sleep 120; pfctl -d

Enabling PF can freeze the SSH session you typed this in, because the firewall keeps no state for a connection that was opened before it started. The command line keeps running on the server anyway. Open a new SSH connection straight away. If it logs in, the rules let SSH through. If it does not, wait: after two minutes PF is disabled, your first session responds again, and you can correct pf.conf and repeat the trial. Do not go on until a new connection has succeeded while PF was active.

After a successful trial, make the firewall permanent and start the services:

sysrc pf_enable=YES pflog_enable=YES
sysrc obspamd_enable=YES obspamlogd_enable=YES
service pf start
service pflog start
service obspamd start
service obspamlogd start

If the session freezes again at service pf start, reconnect and run the remaining three commands.

Configure OpenSMTPD

Create /usr/local/etc/mail/smtpd.conf. Replace vtnet0 with your interface name and example.com with your domain:

pki mail.example.com cert "/usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem"
pki mail.example.com key "/usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem"

table aliases file:/etc/mail/aliases

listen on lo0
listen on vtnet0 port 25 tls pki mail.example.com hostname mail.example.com
listen on vtnet0 port 587 tls-require pki mail.example.com hostname mail.example.com auth

action "local_mail" maildir alias <aliases>
action "outbound" relay helo mail.example.com

match from any for domain "example.com" action "local_mail"
match for local action "local_mail"
match from local for any action "outbound"
match auth from any for any action "outbound"

What the rules do:

  • Port 25 accepts mail from other servers and offers STARTTLS. Port 587 is for your own mail clients: it requires TLS and a login (auth with no table means system user names and passwords).
  • maildir delivers to ~/Maildir in the recipient's home directory, after expanding aliases.
  • Mail from anywhere is accepted only for example.com. Relaying to other domains is allowed only from the server itself or from authenticated users, and only the port 587 listener offers authentication, so the server is not an open relay. Do not add a rule that combines from any with for any without auth.

Check the file and start the daemon:

sysrc smtpd_enable=YES
service smtpd configtest
service smtpd start

Configure Dovecot

The package installs no active configuration. Copy the examples into place:

cp -R /usr/local/etc/dovecot/example-config/* /usr/local/etc/dovecot/

Then change four settings. In /usr/local/etc/dovecot/dovecot.conf, serve IMAP only:

protocols = imap

In /usr/local/etc/dovecot/conf.d/10-mail.conf, use the Maildir that OpenSMTPD delivers to:

mail_location = maildir:~/Maildir

In /usr/local/etc/dovecot/conf.d/10-ssl.conf, require TLS and point to the certificate (the < before each path is part of the syntax):

ssl = required
ssl_cert = </usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem
ssl_key = </usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem

The example 10-auth.conf already authenticates system users through PAM and refuses plaintext logins on unencrypted connections, so it needs no change. Start Dovecot:

sysrc dovecot_enable=YES
service dovecot start

Test the server

Send a local message and confirm it lands in the Maildir:

echo "Test body" | mail -s "Local test" alice
ls /home/alice/Maildir/new/

Check that submission and IMAP present the certificate:

openssl s_client -connect mail.example.com:587 -starttls smtp -brief
openssl s_client -connect mail.example.com:993 -brief

Set up a mail client with IMAP on port 993 (TLS) and SMTP on port 587 (STARTTLS), both with user name alice and her system password. Send a message to an outside address, then send one back. The first message from an unknown server is delayed by greylisting; watch it happen:

spamdb
pfctl -t spamd-white -T show
tail -f /var/log/maillog

spamdb lists GREY entries for pending senders and WHITE entries once they have passed.

Maintenance

  • Certificate renewal: run certbot renew from cron (for example weekly), then service smtpd restart and service dovecot restart so both daemons load the new certificate.
  • Whitelisting a host by hand: spamdb -a 198.51.100.25 adds an address to the whitelist without waiting for a retry.
  • Aliases: after editing /etc/mail/aliases, run smtpctl update table aliases.
  • Queue: smtpctl show queue lists messages waiting to be delivered.
  • Updates: apply base system and package updates regularly; a mail server is exposed to the whole Internet.

Reference documentation: smtpd.conf(5) and spamd(8).

Frequently asked questions

Mail from large providers arrives very late or not at all. Why?

Greylisting expects a retry from the same IP address. Large providers send from pools of addresses, so each retry can look like a new sender. Whitelist their published sending ranges in an extra PF table with its own no rdr rule, or add individual addresses with spamdb -a. If that upkeep is not worth it, remove the two redirect lines and let OpenSMTPD take all mail directly.

Other servers reject or junk my outgoing mail. What is missing?

Usually DNS. Check that the PTR record of your IP address matches mail.example.com and that the SPF record covers the server. Most large receivers also expect DKIM signatures and a DMARC record; FreeBSD packages opensmtpd-filter-dkimsign for signing, and the smtpd.conf manual page contains an example of wiring it in.

Can I host several domains or virtual users?

Yes. For more domains, replace the single domain in the first match rule with a list table. For mailboxes that are not system accounts, OpenSMTPD and Dovecot can both read users from a password file or database, which is described in table(5) and the Dovecot documentation. System accounts are the simplest option for a handful of mailboxes.

Does spamd filter message content?

No. It only looks at the connection: who is sending and whether they retry. It is unrelated to SpamAssassin's daemon of the same name, which is why FreeBSD's service is called obspamd. For content filtering, OpenSMTPD can pass messages to Rspamd through the opensmtpd-filter-rspamd package.

Share story:

Continue reading other guides on How VPS.