Installing a Mail Server for a Small Business

A sceptical guide

= Forewarning =

This page is still under construction.

I am neither an actual sysadmin nor a mail server expert, so take my advice with a big grain of salt. By the way, I am not a lawyer either, so you will find no valid legal advice here.

Your feedback is welcome, just drop me a line.

Once again, for the hard of understanding: if admittedly unprofessional advice, spiced with cynicism and maybe even some unjustified criticism, deeply disturbs or angers you, stop reading now!

= Big Decision Time =

So I hear that you need an e-mail service for your small business, volunteer-driven association or charity. Choose your lesser evil:


 * Outsource the whole thing:
 * Find a reasonable IT service provider. This is easier said as done.
 * Lose quite a lot of control. You cannot afford to annoy your IT service provider anymore.
 * Probably pay too much in consultancy fees.


 * Use a basic offering from your Internet Service Provider or some other mail service provider:
 * Lose control of your data. Your e-mails may end up in the wrong hands if your provider gets hacked. Start worrying about data protection regulation.
 * Risk being taken hostage. For example, your provider can go bankrupt or turn evil. At the very least, you need to do backups yourself, just in case.
 * Any free or bundled service from your ISP will probably be too basic. For example, many ISPs have no shared calendar. And mailbox size limits are often too small.
 * If you choose a separate mail server provider with more e-mail and collaboration features, probably pay too much per mailbox. Some people consider $5/user/month to be cheap for a good mail and groupware service. Buy say you are in a volunteer-driven association or charity, with 20 users that only work a few hours a week (like in a small library). That's $1200 per year. Most volunteers would probably prefer to invest the money somewhere else.
 * If the Internet connection goes down, your e-mail stops working internally too.


 * Use a fully-fledged cloud service like business-grade Gmail or Microsoft Office 365:
 * Lose all control of your data to a company specialised in customer data snooping. You cannot stop paying your subscription, or your lose access to your e-mails. Start worrying about data protection regulations.
 * Definitely pay too much. Do you really need all the features you are paying for?
 * If the Internet connection is down, your e-mail stops working internally too.


 * Use a hosting provider and setup your own e-mail server:
 * You need many skills.
 * The server needs to be constantly kept up to date, for security reasons. Even if updates are automatic, you cannot really leave them unattended for long, you need to monitor at least whether they are still updating themselves.
 * Lose control of your data. Your provider has full access to your virtual machine. I heard that there are special encryption solutions, but if you can go that far, this guide is definitely not for you.
 * If the Internet connection goes down, your e-mail stops working internally too.


 * Install a complete open-source software distribution on premises specifically designed for small business management in general, or at least for e-mail or groupware in particular:
 * Examples are: Univention Corporate Server Kolab Kopano ClearOS Zentyal Zimbra Zarafa EGroupware Open-Xchange Sovereign Mail-in-a-Box iRedMail Koozali SME Server ... and many more, including some local offers in your country ...
 * This kind of complete solutions tend to be complicated and bloated. Some features are nice to have indeed, but the IT costs often outweigh the benefits in the long run.
 * You risk getting locked into a proprietary system. These small businesses distributions come and go, or change drastically. If they change too much, upgrading an extensively-configured system may be a huge pain. If it is very special, migrating to a different system system is no fun.
 * Once the system is configured, there is no reason why you should pay monthly fees. But vendors do not usually supply automatic or easy-to-install security upgrades for free. And these systems are designed to be exposed on the Internet, so having unpatched systems is risky. It's kind of contradictory if you think about it: the software is free, but you cannot really use it for free. But there are exceptions:
 * Univention does support a multidrop mode of operation and documents how to set fetchmail up, so the system needs not be exposed on the Internet, lowering the risk of running outdated software.
 * Koozali SME Server supports multidrop too.
 * iRedMail, Mail-in-a-Box and Sovereign configure existing operating system distributions, so bug fixes and updates are available for free. But these systems are designed to be exposed to the Internet, so you cannot really leave them unattended for long, you need to monitor at least whether they are still updating themselves.


 * Install and maintain your own mail server on premises. This is an impossible task for most people. You need not just general sysadmin skills, but specific mail server know-how. Just the research part is overkill. That is the reason why I wrote this guide.

The rest of this article is for do-it-yourself kind of people who want to install the mail server components on premises.

= Design your E-mail and Systems Operations Policy =

Use a Virtual Machine
You should install your mail server in a virtual machine. You could use a Docker container, but a virtual machine is probably easier to manage.

You are going to invest a significant amount of time setting the mail server up. If you make a mistake along the way, you can revert to an earlier snapshot, instead of starting from scratch.

Sooner or later you will have to upgrade the mail server software, or the operating system it is running upon. You can copy the VM to another PC and test the upgrade procedure before modifying your main server. If upgrading the main server does go wrong in the end, you can just restore to the latest snapshot to avoid long service downtimes.

Backing up your mail server becomes then just a matter of copying your VM as a big file. I have written a simple script to automate libvirt-based VM backups, but there are more optimised solutions available. After all, backing up a VM is a standard operation.

Avoid enterprise-level servers. They are expensive, special, and often do not live up to their promises. Take 2 standard PCs (or entry-level servers), and if the primary fails, start the VM on the secondary.

Offline Backup
You need a strategy for an offline and off-site backup. The classic 3-2-1 backup rule is probably your best bet.

An automatic cloud backup is more convenient, but has many drawbacks:
 * Monthly fees are due just to keep the data at rest on the cloud.
 * You need a very fast Internet connection to do a restore test of a complete backup in a reasonable amount of time.
 * If the cloud provider goes bankrupt, you no longer have a backup. So you need a secondary, offline backup anyway. The secondary backup needs to be offline to protect against encrypting ransomware. If you are going to be implementing it anyway, you may as well drop the cloud.

You need to encrypt your offline and off-site backups. You can use an encrypted container like VeraCrypt or LUKS, but even password-protecting with a simple compressor like 7z will probably be enough.

You can add data redundancy with a tool like par2 for extra robustness. I have written some scripts for 7z + par2 and for simple mirroring backups, but there is really no shortage of file backup solutions.

Archiving Policy
An e-mail archiving policy is often a must. The problem is that most users will never bother deleting big attachments from incoming or outgoing e-mails. Their mailboxes will forever grow, and your mail server will become unmanageable: backups will take forever, performance will drop, and disks will become full. Besides, when connecting a new e-mail client like Thunderbird or a smartphone, the new client may choose to download or sync a huge inbox or sent folder, unduly overloading the network connection.

No amount of convincing will do. You need to set a hard limit on the mailbox sizes. When the mailbox limit is reached, the user will need to clean old e-mails. Which is also not realistic.

Therefore, when a mailbox becomes full, your only practical options are to delete old e-mails or to archive them (move them to offline storage). An automatic, unforgiving system is often not appropriate in a small business, where you do not want to annoy your colleagues too much. But those 2 options do not have to be automatic: when the mailbox hits the limit, because the user has "forgotten" to take preventive action, you can then discuss with the user whether you will be deleting or archiving, and which e-mails will be affected.

But you need to be prepared. If a mailbox is full and cannot send or receive any more e-mails, that is not the time to start discussing or designing an archiving method.

Encryption at Rest
Decide whether you want encryption at rest on your server. Very few people implement this, because it is difficult. But if someone physically steals your server, he/she will then have access to all data on disk.

You can of course assume that your premises are physically secure, or that any robbers will only be interested in the hardware. There may be a legal requirement arising from the data protection regulation, so you should probably seek legal advice.

Options for encryption at rest are:
 * Use an e-mail server that encrypts each mailbox. This is non-standard and will probably make you life harder.
 * Use a special server solution that detects whether the server is not inside your premises anymore. I have heard of such a thing, but it sounds complicated. Your feedback is welcome.
 * Use a manual boot procedure for your server, so that somebody has to type the disk encryption password manually if the server restarts. If it is a virtual machine, you could do that remotely over a VPN or SSH. But it is still a manual procedure, so that your servers will not reboot automatically after an upgrade, or will not start automatically after a power loss.

Data Retention
You should find out whether you are legally required to enforce an e-mail retention policy at company level. If the answer is not clear, you probably need to talk to a lawyer.

This should not be hard to implement: just copy all incoming and outgoing e-mails to a separate mailbox. There are several methods to achieve this, but I haven't investigated them yet. Your feedback is welcome.

As a bonus, such a solution could serve as a last-resort backup. If a user manages to completely delete an e-mail, even from the trash folder, perhaps on purpose, you can always restore it from the data retention pool.

= Internal vs External (Exposed) Mail Server =

You certainly cannot afford to expose your mail server on the Internet. That is just crazy. The Internet is full of spammers and automated hackers just waiting for people like you, who do not have the resources to keep their mail servers patched and secure. Professional hosters have fallen in the past.

Even if software updates are automatic, you cannot really leave such systems unattended for long, you need to monitor at least whether they are still updating themselves. I would never install a mail server that is craving for attention in any way. In a small business, most people cannot keep up with the latest software releases. The most you can hope for is not to lag too much behind. You probably have heard of Windows XP and Windows 7 staying in operation years after their end of life. Big public and private organisations have been known to miss such deadlines too.

Besides, you cannot match the service level of a dedicated mail hoster in terms of high availability.

You also do not want to worry about:
 * getting a static IP address, or investigating some DynDNS workaround
 * setting up DNS records
 * configuring and testing SPF or DKIM
 * obtaining SSL certificates
 * dealing with spam and virus, maybe filtering by geographical location
 * fighting e-mail reputation issues
 * defending against denial of service attacks that use excessive bandwidth or server resources with measures like fail2ban
 * working around port 25 (SMTP) restrictions from your Internet or hosting provider

Unfortunately, most of the mail server guides you will find on the Internet assume that you are crazy enough to expose your server on the Internet, and do not feature any prominent warning about such security and operational aspects. My guess is that the people who write these guides are all evil sadists. 8-)

Therefore, the only sane configuration for your mail server is to be a secondary/satellite server to your ISP mail server.

There is one drawback though: your ISP can read all incoming and outgoing mail. This is the price we will have to pay in this configuration.

Most Internet Service Providers provide very cheap but very basic mail services with reasonable virus and spam filtering. E-mail is a commodity item nowadays. If you are dissatisfied, changing ISP is relatively easy. Your ISP mail server will be the one accepting external SMTP connections and doing virus and spam filtering. Standard e-mail security features like SPF will also be handled by your ISP.

Your mail server will live inside your LAN and not be accessible from the outside. It will download all e-mails from your ISP mail server at regular intervals (or maybe even immediately upon e-mail reception), and delete them from the ISP, either straight away or maybe after a few days. Such collective e-mail downloads are usually performed by a specialised tool like fetchmail or getmail. It is no longer so important that your mail server is not hardened and completely up to date, because your server sits behind your firewall and behind the ISP mail server.

This recommendation applies even if you run a hosted mail server on the Internet. Keeping your server protected (not exposed at all) is the only sensible approach if you are not a mail and hosting professional.

As a bonus, if your internal mail server goes down, e-mails will not immediately bounce back to their senders. Internal mail server outages will largely go unnoticed outside your LAN.

This constellation [external ISP mail server + internal mail server] is actually pretty common. Microsoft used to sell a rather popular product called Small Business Server, which included a mail server called Microsoft Exchange Server. Exchange had a plug-in called POP3 Connector which was designed to collect e-mails from the ISP mail server. Many comparable e-mail download products for internal mail servers still exist today. So do not listen to any scaremongers spreading fear, uncertainty and doubt about this kind of mail server setup.

With a mail server on premises, should the Internet connection go down, internal e-mails will continue to work.

If a sysadmin needs access to your internal mail server from the outside, you can set up an SSH server. If general users need access to e-mail, and maybe remote desktop and file server access too, you can set up a VPN, which is not very difficult. Incidentally, I have written a guide for installing OpenVPN, but there are many more on the Internet.

Nothing else, other than SSH and VPN, should be accessible from the outside.

Well, if you really want to push your luck, you could expose the IMAP port on the Internet, so that users have convenient and instant e-mail while on the road. But then you should also implement some traffic limiting or shaping, because synchronising a big mailbox over the Internet can eat most of your upload bandwidth and impact office users for a while. And you will need to start monitoring your mail server more closely.

There are 2 strategies for the mailboxes on your ISP mail server:


 * Each user has a separate mailbox on the ISP mail server. Assuming that your internal server does not delete the e-mails from the ISP immediately after downloading them, your users have access to their newest e-mails when outside the office even without a VPN. Sending e-mails from outside the office always works, either with a mail client, or with the web interface the ISP normally provides. The drawback is that you need to create a mailbox per user on the ISP too, which means more administration.


 * The ISP provides a single "catch-all" e-mail mailbox for your domain. This is usually called a "multidrop" or "domain mailbox". There is no reason why the standard ISP virus and spam protection should not apply to this single mailbox too. A single internal process can download all e-mails for all users at once, from one catch-all mailbox, making server management easier.

= Enable SPF at your ISP =

Do not forget to enable SPF on your ISP mail service. SPF is your first line of defence against hackers and spammers forging e-mails that pretend to have been written by you. Nowadays, SPF is considered to be a basic e-mail protection measure.

If there is no easy "enable SPF" option at your ISP, enabling it actually boils down to adding a DNS TXT record like this:

your.domain.com TXT  v=spf1 mx a include:outgoing-mail-server.your-isp.com -all

There are many guides on the Internet about enabling SPF, and you can use one of several online services to check whether the DNS SPF entry is correctly configured.

= Find Out How Your ISP Mail Server Works =

Go to your ISP and create a "catch all" mailbox like multidrop@example.com. Then connect to that mailbox with either your ISP webmail interface, or with an e-mail client like Thunderbird.

Send a few e-mails to addresses like test1@example.com and test2@example.com. They should all land in the same multidrop@example.com mailbox. Now look at the full e-mail headers in each e-mail, and find out which header has the original recipient, like test1@example.com.

That header records the envelope recipient, and is what we will be using later to deliver the e-mails to the separate, internal user mailboxes. If the ISP uses Postfix, then the header name will probably be X-Original-To.

You should do a further test, just to make sure you will not be having trouble later on. Send an e-mail to test1@example.com, and blind-copy (BCC) test2@example.com. You should get the same e-mail twice, each with a different envelope recipient header. If not, your ISP mail serer is not configured properly, which is no good sign in this day and age.

= Install Dovecot =

On Ubuntu/Debian:

sudo apt-get install dovecot-imapd  dovecot-managesieved  dovecot-lmtpd  dovecot-submissiond  getmail

Just by installing the packages, the dovecot service starts automatically. That does not make any sense, because we have not configured the server yet, so stop and disable it now:

sudo systemctl disable --now dovecot.service

= The Old Local Mail =

Many many years ago, there was a central, very expensive Unix computer with many user terminals. Each user had their own mailbox and was often greeted with "you have new mail" when logging on via a text console. There was no Internet at the time.

Times have changed since then, and e-mail means now something completely different. Nobody reads such local mails anymore, and the old greeter message is even turn off by default as far as I can tell.

However, old traditions die hard. A standard Ubuntu installation still has a mail user account with /var/mail as home directory. There you will find a big text file for each user in mbox format, which is a text-based format. If you install a Mail Transfer Agent like Postfix for whatever reason (maybe automatically as a result of a package dependency), things will automatically start sending e-mails to local users, and those mailbox files will start to grow.

For example, I once added a cron job and forgot to append the usual ">/dev/null 2>&1" to the command. The cron service sent then a local mail to the root user with the command's output every time it ran. After a few months, I had "70102 messages 70102 unread", and the mailbox file had grown to 60 MiB.

Somebody should tell the Ubuntu/Debian developers that we now live in year 2020. Linux should actually run forever without automatically filling the disk with rubbish. The usual excuse for this kind of misbehaviour is that many system tools or processes have no other way to send notifications. But no amount of convincing will get users to start reading local mail nowadays.

Because I expect that this local mail rubbish will sooner or later go away, I will avoid storing any modern mailboxes under /var/mail, so that a mail server like Dovecot has no chance of interacting or colliding with the old local mail system.

The default Dovecot installation on Ubuntu 20.04 does however integrate with the local mail though through the following configuration settings:

mail_location = mbox:~/mail:INBOX=/var/mail/%u mail_privileged_group = mail
 * 1) Typically this is set to "mail" to give access to /var/mail.

Dovecot will then litter your existing user home directories with subdirectories named ~/mail. At this point, I distrust the default Dovecot configuration, so we will create a complete new configuration from scratch.

= About Virtual Users =

You normally do not want to associate e-mail accounts with local user accounts, so we will be using the "virtual users" mode, which means that e-mail accounts will be independent from any other local system user accounts.

You could use some fancy centralised server, like LDAP or Samba's Active Directory, to link e-mail accounts to computer user accounts. But then there would be a dependency between servers, and upgrading the LDAP server would impact the mail server. In a small business, I recommend keeping the servers separate, even if it means creating more than one account per user (one file server account, and one e-mail account).

= Dovecot Configuration =

If you think that this article is somewhat funny, I will mention that Dovecot's manual starts with the claim that it is "simple to set up". After a few day's worth of investigation and tests, I can confirm that Dovecot's documentation is funny too.

We will start by deleting the default Dovecot configuration, because as I stated above, I do not trust it. Just rename file /etc/dovecot/dovecot.conf away and start a new one.

After making any changes to the configuration, you need to restart Dovecot like this (but remember that we have disabled it altogether until the first configuration is complete):

sudo systemctl restart dovecot.service

= Choosing the Mail Storage Location =

Dovecot is very flexible, you can place your mailboxes wherever you want. For security reasons, we will create a separate local user with permission to access the mailbox files for all virtual users, so I will place the mailboxes in that user's standard home directory. But you may choose some other mailbox storage location of your liking, or even change the new user's home directory to somewhere outside /home.

Most people name this new user vmail, probably because we will be using "virtual users". But it's still a bad username, so I will use dovecot-mailboxes instead. Create it like this:

sudo useradd --create-home  --user-group  --system  --shell /usr/sbin/nologin  dovecot-mailboxes

Option --system is only a convention so that the new user does not come up in the logon screen.

Later on, we will specify in the Dovecot configuration file where exactly under /home/dovecot-mailboxes the mailboxes will be placed. You do not need to create any files or subdirectories there, as Dovecot will create the mailboxes on first touch. Dovecot sets the top-level subdirectory permissions to drwx-- upon creation, so it seems safe.

= Create the First E-Mail Accounts =

Now you are ready to define your mailboxes. First of all, install a fully-fledged SQL database server, and then learn enough SQL to be able to send user account queries, and then...

I am kidding you. You just need to store a few usernames and passwords, so a simple text file will do. Many mail server guides want you to install PostgreSQL, or some other monster database server, or maybe even integrate with an LDAP directory server. But you cannot realistically ban people from ever writing mail server guides for the unwary, can you?

So create file /home/dovecot-mailboxes/dovecot-passwd with the following contents:

account1@example.com:{PLAIN}pass:::::: account2@example.com:{PLAIN}pass::::::

You do not even need to change the example addresses above to your real e-mail addresses, you can actually use account1@example.com for your first IMAP connection test.

The Dovecot service, which runs with user 'dovecot' and group 'dovecot', needs permission to read the password file. Therefore, containing directory /home/dovecot-mailboxes must have 'x' permission for 'other' users, which is the default under Ubuntu/Debian. The password file itself could have the following permissions, owner and group:

-rw-r- dovecot-mailboxes  dovecot [...] dovecot-passwd

Such password files should actually use hashed or encrypted passwords, instead of the plain text password in the test content above, so it would not matter much that the file is readable by everyone. But you should always tighten file access permissions, just in case.

You can of course place the password file somewhere else on the filesystem if you like.

= Create and Test the First Configuration =

Place the following contents into file /etc/dovecot/dovecot.conf :

TODO

Now that Dovecot has a first complete configuration, you can enable and start it like this:

sudo systemctl enable --now dovecot.service

Check if Dovecot knows the first test e-mail account:

sudo doveadm user "account1@example.com"

You can now start a standard e-mail client like Thunderbird and connect over IMAP. The connection parameters are:

Server name: localhost Protocol: IMAP port 143 Connection security: none Authentication: password, transmitted insecurely (normal password) User name: account1@example.com Password: pass

Note that sending (SMTP) will not work yet, so it does not really matter what you configure.

Your e-mail client should see the inbox, and you should be able to create an e-mail draft (but not send it).

= E-Mail Passwords in Plain Text over the Network =

The mail server we are installing will have no SSL/TLS enabled, so all passwords will be sent in clear text over the network. That is clearly not secure.

But you will not be connecting to the mail server over the Internet, only over Ethernet switches in your private LAN, so the lack of transport security is not really a critical issue in this scenario. Skipping the security aspects saves us quite some work.

You can of course generate and distribute your own security certificates. Drop me a line if you come up with an easy guide that I could embed here.