Setting up a mail server (WIP)

1. Introduction

I use Postfix as a SMTP and Dovecot (with Pigeonhole (Sieve)) as an IMAP server. ClamAV for an antivirus. For antispam I use SpamAssassin. For DKIM and DMARC — OpenDKIM and OpenDMARC respectively.

It is vital to make the DKIM, DMARC and SPF DNS records. Also, if you want your mail server to be trusted by every other mail servers then you should get a static IP-address if you don't yet. And you have to ask your ISP to edit PTR DNS record for your static IP-address to point to your domain.

Unfortunately for me I don't have neither, and I'm afraid that even if I get the static IP-address, my ISP won't edit PTR record, because that's available only for bussiness customers. And about domains, there is such things as untrustworthy abused TLDs, and top TLD is in that list. That's definitely because it's a cheap TLD.

Server is configured in a simple way using PAM (real system users) with user's passwords and with mail stored in ~/Maildir.

2. Installing

You need to install following packages: postfix, dovecot, pidgeonhole (or could be dovecot-sieve), clamav, opendkim, opendmarc, and spamassassin.

3. Postfix SMTP server

Its configuration files are in directory /etc/postfix. There are two configuration files we'll work with. The first one is a main.cf file. Then we configure services in master.cf. Also I'll show you how to make aliases for users.

3.1. main.cf

Let's take a look at all base options that should be modified:

myhostname = mail.example.org
mydomain = example.org
myorigin = $mydomain
 
inet_interfaces = all
 
mydestination = $myhostname, localhost, $mydomain, mail.$mydomain
 
local_recipient_maps = unix:passwd.byname $alias_maps
 
mynetworks = localhost, 192.168.0.0/24
 
alias_maps = hash:/etc/postfix/aliases
alias_database = $alias_maps
 
recipient_delimiter = +
 
home_mailbox = Maildir/
 
mailbox_transport = lmtp:unix:private/dovecot-lmtp
 
inet_protocols = ipv4

Now let's clarify what are they doing.

Set myhostname to a hostname of a server (e.g. mail.example.org). Set mydomain to your domain name (e.g. example.org). Set myorigin to $mydomain to set origin of mail being sent from your server.

mydestination is a list of domains that are delivered through a local transport. If server should go outside then this option must include $mydomain alongside names for the local machine. E.g. $myhostname, localhost, $mydomain, mail.$mydomain.

local_recipient_maps are lookup tables with all names and/or addresses of local recipients. In my case it set to unix:passwd.byname $alias_maps.

I have inet_interfaces = all to listen on all the interfaces.

In mynetworks, as stated in a Postfix's manual, we specify a list of “trusted” clients that have more privileges than “strangers”. In particular, such clients are allowed to relay mail through Postfix. I have it set to localhost and my LAN.

In alias_maps we specify a list of lookup tables that contain aliases for existing users. And in alias_database just add $alias_maps. alias_database is, as stated in a manual, separate because not all the tables specified with $alias_maps have to be local files.

recipient_delimeter = +. Here we set a delimeter to a plus sign (that's just a usual practice that I obeyed).

I use a Maildir-style mailboxes, so home_mailbox is set to Maildir/ (slash is necessary).

We use Dovecot, so mailbox_transport should be set to lmtp:unix:private/dovecot-lmtp. Here we point to where Dovecot LMTP server listens, in our case it is a UNIX-socket.

Optionaly, you can set inet_protocols to IP versions used by you, I set it just to ipv4 for a quite legitimate reason of not having IPv6 address. :) It is a space-separated list, so to support both write ipv4 ipv6.

Next I'll cover how to make encryption working, set up milters (mail filters (i.e. OpenDKIM and OpenDMARC)), and restrictions.

Next let's configure our milters:

milter_default_action = accept
milter_protocol = 6
smtpd_milters =
	unix:/var/spool/opendmarc/opendmarc.sock
	unix:/var/spool/opendkim/opendkim.sock
	inet 192.168.0.54:7357
non_smtpd_milters = $smtpd_milters

milter_default_action specifies default action of a milter. Here we accept an e-mail message.

milter_protocol specifies protocol version used by milters, current is 6.

smtpd_milters is a list of milters the messages will go through. You can connect to milter with internet protocol with inet:, with a unix socket unix:. The last one with port 7357 is a ClamAV by the way.

Now lets do some tweaks:

biff = no
strict_rfc821_envelopes = yes
disable_vrfy_command = yes
smtpd_helo_required = yes
smtpd_delay_reject = yes

mailbox_size_limit = 0
message_size_limit = 52428800

biff set to no, so the local service for new mail notifications disabled. We run on a server machine, we don't need them.

strict_rfc821_envelopes set to yes require addresses to be enclosed with <>.

Disabling VRFY command with disable_vrfy_command set to yes prevents some email addresses harvesting techniques.

smtpd_helo_required requires remote client to send HELO or EHLO command. This may stop some poorly written spam bots.

smtpd_delay_reject makes Postfix wait until RCPT TO command before evaluating some restrictions.

mailbox_size_limit and message_size_limit sets maximum size of a whole mailbox and of each email. Here I set no limit for a mailbox, and max of 50MiB for an email message.

And now it's time for SASL configuration:

smtpd_sasl_type = dovecot
smtps_sasl_path = private/auth
smtps_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $mydomain
broken_sasl_auth_clients = no

It's pretty clear. We chose dovecot as our SASL, set path to it withing /var/spool, and enable it. Then we set option to not allow anonymous connections. Set our domain for SASL, and wether let the clients with obsolete version of AUTH command in or not, we chose not to.

It's time for encryption, lets specify a list of high ciphers to use:

tls_high_cipherlist = ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384

High means just that those ciphers are strong. I took them from a file options-ssl-nginx.conf generated by certbot, and ditched 128 byte key size.

Lets do client part of encryption.

smtp_use_tls = yes
smtp_tls_security_level = may
smtp_tls_note_starttls_offer = yes
smtp_tls_connection_reuse = yes
smtp_tls_key_file = /etc/letsencrypt/live/example.org/privkey.pem
smtp_tls_cert_file = /etc/letsencrypt/live/example.org/fullchain.pem
smtp_tls_mandatory_protocols = !SSLv2,!SSLv3,!TLSv1,!TLSv1.1
smtp_tls_protocols = $smtp_tls_mandatory_protocols
smtp_tls_mandatory_ciphers = high
smtp_tls_exclude_ciphers = aNULL, MD5, CAMELLIA

First we enable it with a smtp_use_tls option. Set security level (smtp_tls_security_level) to may, since not every SMTP server out there have encryption. Noting servers of our ability to use encryption with option smtp_tls_note_starttls_offer. Set to reuse connection instead of opening the new one each time.

smtp_tls_key_file and smtp_tls_cert_file are paths to our encryption key and certificate.

smtp_tls_mandatory_protocols and smtp_tls_protocols here we disallow old vulnerable protocols to use. Here only TLS version 1.2 and 1.3 are allowed.

In smtp_tls_mandatory_ciphers we declare to use only good secure cyphers. And in smtp_tls_exclude_ciphers we exclude the most weak one.

With server part everything is the same, just a few more options added:

smtpd_use_tls = yes
smtpd_tls_security_level = may
smtpd_tls_auth_only = yes
smtpd_tls_key_file = /etc/letsencrypt/live/example.org/privkey.pem
smtpd_tls_cert_file = /etc/letsencrypt/live/example.org/fullchain.pem
smtpd_tls_mandatory_protocols = $smtp_tls_mandatory_protocols
smtpd_tls_protocols = $smtpd_tls_mandatory_protocols
smtpd_tls_mandatory_ciphers = $smtp_tls_mandatory_ciphers
smtpd_tls_exclude_ciphers = $smtp_tls_exclude_ciphers
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom

Security level is may, but for auth TLS is required. smtpd_tls_loglevel is for logging a summary of a TLS handshake.

smtpd_tls_received_header makes Postfix include information about the protocol and cypher used to a Received: header.

smtpd_tls_session_cache_timeout is for how long to store session. tls_random_source is for setting an entropy source.

The final part is my "favorite". :) The restrictions! There is a set of them for each stage the message falls through. Here's the ones I configured:smtpd_helo_restrictions, smtpd_relay_restrictions, smtpd_data_restrictions, smtpd_sender_restrictions, and smtpd_recipient_restrictions.

So lets roll. This my working restrictions setup:

smtpd_helo_restrictions =
   reject_unknown_helo_hostname,
   reject_invalid_helo_hostname,
   reject_non_fqdn_helo_hostname
smtpd_data_restrictions =
   reject_multi_recipient_bounce,
   reject_unauth_pipelining
smtpd_sender_restrictions =
   permit_sasl_authenticated,
   reject_non_fqdn_sender,
   reject_unknown_sender_domain
smtpd_recipient_restrictions =
   reject_unknown_recipient_domain,
   reject_non_fqdn_recipient

In order to explain what every restriction does I'd have to copy-paste from man 5 postconf. :)

The first set of restrictions are for HELO or EHLO command, that we force the client to send with priorly set option smtpd_helo_required to yes. Here reject_unknown_helo_hostname rejects hostnames that doesn't have DNS A or MX records. reject_invalid_helo_hostname rejects malformed hostnames, and reject_non_fqdn_helo_hostname ensures that the hostname is a fully-qualified domain name.

The second one are for DATA command. And here man page is better than me at explaining it. Here is the link for reject_multi_recipient_bounce and reject_unauth_pipelining. All I can say is that it is better to have them than not to. :)

The rest is simpler, permit_sasl_authenticated in smtpd_sender_restrictions accepts the senders that were authenticated by SALS (e.g. Dovecot or Cyrus). And all the reject_unknown_* and reject_non_fqdn_* has the same meaning as for theirs *_helo_* counterparts, just used in theirs specific places.

3.2. master.cf

The following services are needed: smtp, submission, smtps, and we add spamassassin service. The rest in this file left untouchable.

smtp       inet  n       -       n       -       -       smtpd
 -o content_filter=spamassassin
submission inet n       -       n       -       -       smtpd
 -o syslog_name=postfix/submission
 -o smtpd_tls_security_level=encrypt
 -o smtpd_sasl_auth_enable=yes
 -o smtpd_tls_auth_only=yes
 -o milter_macro_daemon_name=ORIGINATING
 -o content_filter=spamassassin
smtps      inet  n       -       n       -       -       smtpd
 -o content_filter=spamassassin
 -o syslog_name=postfix/smtps
 -o smtpd_tls_wrappermode=yes
 -o smtpd_sasl_auth_enable=yes
 
spamassassin unix -     n       n       -       -       pipe
user=spamd argv=/bin/vendor_perl/spamc
 -e /sbin/sendmail -oi -f ${sender} ${recipient}

smtp is listening on port 25, and smtps on port 465. submission is listening on port 587 and is used by mail client to send mail.

3.3. User aliases

User aliases are in aliases file. They has a form "<alias>: <username>", e.g. me: arav. Where username may be other alias. After modifications you need to run newaliases program to update aliases.db database file.

3.4. Starting Postfix

To start a Postfix service on systemd-based Linux distro run systemctl start postfix. To make Postfix run on every boot run systemctl enable postfix.

4. Dovecot POP3/IMAP server with Sieve mail filter

5. SpamAssassin spam filter

Here we are working with a local.cf file to configure SpamAssassin.

I didn't any fancy tweaking, didn't make any custom rules. I just changed options presented in file.

I left rewrite_header option commented since I don't want to append anything to a Subject header of spam messages.

Option report_safe I set to 2 to save spam messages as a text/plain attachment instead of modifying original message.

trusted_networks sets networks and hosts that are considered trusted, i.e. not spammers.

lock_method left to be flock, since I don't use NFS.

required_score left to be its default value of 5.0.

I use Bayesian classifier, so options use_bayes and bayes_auto_learn are set to 1.

I chose to normalise charset to UTF-8 with option normalize_charset 1.

5.1. Updating built-in rule set

I sometimes run sa-update util to update built-in rules and pre-compile them with sa-compile util. After that restart SpamAssassin.

And so SpamAssassin make use of compiled rules ensure that a plugin Rule2XSBody in a v320.pre is uncommented.

5.2. Bayesian classifier training

After you set up SpamAssassin for the first time you have to train Bayesian classifier. It will start to work after 200 messages will be examined.

For training use sa-learn utility and use --ham and --spam to mark messages as normal mail and spam. I additionaly have to specify a path to database with --dbpath /var/lib/spamassassin/.spamassassin option, otherwise it will complain, so try first without it.

6. OpenDKIM signing and verifying filter

On ArchLinux OpenDKIM is unable to write in /run, so I created /var/spool/opendkim directory for it.

6.1. opendkim.conf

Well, that's main config file

KeyTable           refile:/etc/opendkim/keytable
SigningTable       refile:/etc/opendkim/signingtable
InternalHosts      refile:/etc/opendkim/internal-hosts
 
Socket local:/var/spool/opendkim/opendkim.sock
PidFile /var/spool/opendkim/opendkim.pid
UMask  000
UserID opendkim:opendkim
 
Mode sv
SubDomains yes
 
Canonicalization relaxed/simple
 
Syslog yes
SyslogSuccess yes
LogWhy yes
 
SoftwareHeader yes

I myself set up a multi-domain variant just in case. So, here we have two main tables: KeyTable and SigningTable. Those files tells OpenDKIM where to find keys and what domains to sign. You may use one key for all domains or generate keys for each domain.

InternalHosts tells OpenDKIM what hosts should be signed rather than verified.

Socket tells where to listen to connections, in this case we use UNIX sockets.

Mode selects operating mode(s). In our case we have two modes: (s)igner and (v)erifier.

SubDomains set to yes tells that we allow subdomains of our domains to be signed and verified.

Canonicalization selects the canonicalization method(s) to be used with signing. We set relaxed for header and simple for body. I don't fully understand it and just use what suggested.

Below are logging options that tells to write in syslog.

With SoftwareHeader set to yes OpenDKIM will be always adding "DKIM-Filter" header field.

6.2. Generating keys

opendkim-genkey -r -s myselector -b 2048 -d example.com

This command will generate a key pair stored in files "myselector.private" and "myselector.txt" for a given domain.

-r restricts the key to emails use only. -s is a name of selector.-b is the size of the key in bits. -d is our domain.

Name of a selector is usually a mail, but that's just what I use, you can choose whatever you want.

6.3. Populating KeyTable and SigningTable

KeyTable has following structure (a line per domain):

myselector._domainkey.example.com example.com:myselector:/etc/opendkim/myselector.private

And SigningTable this one:

*@example.com myselector._domainkey.example.com

6.4. internal-hosts file

As stated above in this file we put hosts whose mail should be signed rather than verified. And its structure is the following:

127.0.0.1
192.168.0.0/24

127.0.0.1 is necessary to be there according to a manual.

6.5. Starting OpenDKIM

systemctl start opendkim and systemctl enable opendkim to start and enable OpenDKIM service to run on OS start up if you got Poetteringed just like me. :)

7. OpenDMARC email policy filter

Its configuration lies in /etc/opendmarc/opendmarc.conf and is fully documented. Here are the options I changed:

AuthservID OpenDMARC
FailureReports true
FailureReportsBcc admin@example.org
FailureReportsSentBy admin@example.org
IgnoreAuthenticatedClient yes
RejectFailures true
RequiredHeaders yes
Socket unix:/var/spool/opendmarc/opendmarc.sock
SoftwareHeader true
SPFSelfValidate true
Syslog true
TrustedAuthservIDs mail.example.org,example.org
UMask 002

What's in a Socket option should be added to Postfix's smtpd_milters and non_smtpd_milters.

Creating DMARC DNS record covered in 8.4.

8. DNS records

8.1. MX and A/AAAA

It's good to have a dedicated A (IPv4 address) or AAAA (IPv6 address) record for a mail server's hostname instead of a CNAME record so other servers won't need to do two DNS requests. Hostname is usually mail.example.org if there's just one server, you can call it whatever you want. Remind you that we set it in Postfix in myhostname option.

And A record looks like this:

mail  IN  86400  A  203.0.113.4

Where mail is a hostname, 86400 is a TTL of a record in seconds.

Next we need to add a MX (mail exchanger) record that looks like this:

  MX 10 mail.example.org.

Here 10 is a priority of a record. The lower a number the higher a priority.

A period at the end of the hostnames is necessary in DNS records.

8.2. PTR

PTR is a reverse DNS record that stands for pointer and is used to “bind” a hostname to IP-address. Mail servers looks for this record and check so this name equals to a hostname provided in EHLO. Most servers will reject your mail if your PTR looks something like 1.2.3.4.pppoe.someisp.net or not set at all.

There are three ways to set this record: ask your hosting or internet-provider, or get your own Autonomous System (:^)).

Example of this record:

1  IN  PTR  mail.example.org.

8.3. SPF

SPF stands for Sender Policy Framework and in my case it looks exactly like this:

v=spf1 +a +mx -all

So, v is a version of a protocol. +a +mx means that only servers specified in the A and MX DNS records could send email, and -all that no one else could do that.

8.4. DMARC

DMARC stands for Domain-based Message Authentication Reporting and Conformance. And its DNS record could be like this one that I use:

_dmarc    IN    TXT    "v=DMARC1; p=reject; rua=mailto:admin@example.org; ruf=mailto:admin@example.org"

v is a version of a protocol.

p is a default policy that could be set to none, quarantine and reject. I chose to reject mail that comes from «me” if there's something wrong with a origin of a message. If you could get email from subdomains then you need to set sp as well.

rua is an address for the reports and ruf is for the forensic reports.

8.5. DKIM

In 5.2 we generated a key pair for our domain and now we'll take what's inside a myselector.txt file and add it to our DNS.

DKIM DNS record looks like this:

myselector._domainkey    IN    TXT    ( "v=DKIMv1; k=rsa; s=email; p=<public key goes here>" )

By the way, brackets are used in case a content of a record doesn't fit on one line.

9. Setting up a ClamAV antivirus

All you need to make it work together with Postfix is to add /run/clamav/milter.sock to smtpd_milters and non_smtpd_milters options in Postfix, also make some changes in configs of ClamAV.

In clamav-milter.conf you need the following:

MilterSocket unix:/run/clamav/milter.sock
ClamdSocket unix:/run/clamav/clamd.ctl

Also, in case you need ClamAV to add headers also in case a message is free of viruses add AddHeader Add or AddHeader Replace option. The difference between them is detaily described in config file itself.

Before starting ClamAV you need to update its virus definitions with freshclam util. Also, enable and start clamav-freshclam systemd service to keep definitions recent.

I don't know how it is in other distros, but, for whatever reason, an Arch Linux's package doesn't have a systemd service file for the ClamAV milter. So I just copy it here from ArchWiki:

[Unit]
Description='ClamAV Milter'
After=clamav-daemon.service
 
[Service]
Type=forking
ExecStart=/usr/bin/clamav-milter --config-file /etc/clamav/clamav-milter.conf
 
[Install]
WantedBy=multi-user.target

Save it as /usr/lib/systemd/system/clamav-milter.service and run systemctl daemon-reload.

Next you need to enable and start clamav-daemon and clamav-milter.