My Little Corner of the Net

Setting Up a Mail Server with Chasquid and Dovecot – Part 1 The Servers

Conventional wisdom says you shouldn’t try to run your own mail server.  It’s difficult: as the percentage of email that is unwanted continues to grow, it becomes harder and harder to ensure that your legitimate messages are delivered.  It’s difficult to build a reputation as a legitimate sender, and the tools needed to do that are always changing.  You have to keep an eye on blacklists, and you need to be constantly vigilant about your server’s security to ensure that no else can hijack it to send spam…and that’s just for getting messages you send delivered.  On the receiving end there’s spam filtering, ensuring that incoming messages end up in the right mailbox, TLS certificate management…and the list goes on.

I guess I’m not conventional (or, perhaps I’m just not wise).  I’ve been running my own mail servers for the better part of 20 years now and it’s been working for me.  Of course, until now, I had never taken the time to really understand my mail servers because I was just using the ones installed with the various web hosting control panels that I’ve used over the years.  All of the control panels I’ve used, however, are built around the LAMP stack and, as my hosting needs have changed, with more things running in Docker or being built in other languages, like Go, I’ve kind of outgrown the panels.  I needed to find a new email solution and, after checking out several possible solutions, I settled on running my own servers using Chasquid and Dovecot.  I’ve been running this setup for a few months now and, so far, it is working well for me.

This article will be a tutorial on how I set up my servers for my specific needs.  I hope you find it useful, but honestly, like a lot of my tutorials, I’m writing it more for me to reference the next time I have to set it up again.  There are definitely things in here that I would do differently if the circumstances were different and there are probably things that won’t make sense in other situations.  The tutorial is built on these assumptions:

  • I’m using Debian Linux on a VPS with a large hosting provider.  At the time of this writing, I’m on Debian Bookworm (12.12).  The process will probably be similar for other Linux distros, but some paths and commands may be different.  You probably won’t have much luck if you try to run this from a server on your home network as ISPs tend to block SMTP ports on residential networks and receiving hosts tend to reject mail coming from residential networks, both in the name of fighting spam.  Server specs shouldn’t matter too much if your email traffic is light to moderate.
  • Both the SMTP server (Chasquid) and POP/IMAP server (Dovecot) will be running on the same machine.
  • Each domain will have a single hostname (mail.example.com) that will be used for both sending and receiving mail.
  • Users are required to use TLS when connecting to the servers to send or receive mail.  Both Chasquid and Dovecot will be configured with TLS certificates for each domain that they host.
  • I’m using a third-party service (MXGuarddog) for spam filtering, so I am not installing SpamAssassin, ClamAV, Greylistd or any other spam/virus filtering or prevention tools on my server.  Chasquid does, however, support those three aforementioned tools.
  • Since I am using MXGuarddog, I’m using an arbitrary port number for incoming SMTP connections.  MXGuarddog knows the port I’m using and routes the mail it processes there instead of to port 25, but if spammers try to sneak around the protections I have in place, they won’t be able to find the server.

The setup process isn’t difficult, but it is lengthy, so I’ve decided to break up the tutorial into three parts: this article will focus on getting the services installed and running; part two will look at configuring domains and adding email accounts, including setting up DKIM signing and individual TLS certificates, and part three will cover the extra things that might be important, including aliases, certificate renewals, send-only accounts, and how Chasquid can interface with other services, such as spam filters.

Step 1: Installing Dovecot

If you’re familiar with Linux mail servers, you’ve probably heard of Dovecot.  Taking it’s name from a house for pigeons or doves (appropriate as pigeons have traditionally been used as messengers), it is currently one of the most popular POP3 and IMAP4 mail servers for Linux.

Dovecot is a complex piece of software that can do a lot of different things.  For me, I only need a POP/IMAP server for delivering mail to my email clients.  I’m also running Dovecot’s LMTP (local mail transfer protocol) server, which is what Chasquid will use to deliver incoming messages to their respective mailboxes.

To get started we’ll first make sure our apt package listing is up to date:

sudo apt update

Then we’ll install the necessary Dovecot packages.  This command will install a bunch of additional dependencies as well:

sudo apt install dovecot-imapd dovecot-pop3d dovecot-lmtpd

Now we need to configure Dovecot.  Dovecot comes with an elaborate, multi-file configuration that tries to address every possible configuration option.  I found that it was much easier to replace that setup with a custom configuration than to try overriding the original files.

First, we’ll rename the old dovecot.conf file, just in case we ever need to go back and check something in it:

sudo mv /etc/dovecot/dovecot.conf /etc/dovecot/doevcot.conf.bak

Then we’ll create a new dovecot.conf file with our custom configuration with this command:

cat <<EOF | sudo tee /etc/dovecot/dovecot.conf
#
# Logging
#
log_path = /var/log/dovecot/dovecot.log

#
# Email storage
#

# Store emails in /var/vmail/domain/user
mail_home = /var/vmail/%d/%n

# Store mailboxes in maildir format (file per message).
mail_location = maildir:~/Maildir

# User and group used to store and access mailboxes.
mail_uid = dovecot
mail_gid = dovecot

# As we're using virtual mailboxes, the system user will be "dovecot", which
# has uid in the 100-500 range. By default using uids <500 is blocked, so we
# need to explicitly lower the value to allow storage of mail as "dovecot".
first_valid_uid = 100
first_valid_gid = 100

#
# Authentication
#

# For convenience, place all mail account config together in the
# chasquid domain directory. Since chasquid uses "users" for it's
# user directory, an extra file named "passwd" shouldn't cause conflicts.

auth_mechanisms = plain
passdb {
    driver = passwd-file
    args = scheme=CRYPT username_format=%u /etc/chasquid/domains/%d/passwd
}
userdb {
    driver = passwd-file
    args = username_format=%u /etc/chasquid/domains/%d/passwd
}

#
# TLS
#

# TLS is mandatory.
# Add a conf file for each domain with paths to TLS certs
# in /etc/dovecot/domains
ssl = required
!include_try /etc/dovecot/domains/*.conf

# Only allow TLS 1.2 and up.
ssl_min_protocol = TLSv1.2

#
# Protocols
#
protocols = lmtp imap pop3

#
# IMAP
#
service imap-login {
    inet_listener imap {
        # Disable plain text IMAP, just in case.
        port = 0
    }
    inet_listener imaps {
        port = 993
        ssl = yes
    }
}

service imap {
}

#
# POP3
#
service pop3-login {
    inet_listener pop3 {
        # Disable plain text POP3, just in case.
        port = 0
    }
    inet_listener pop3s {
        port = 995
        ssl = yes
    }
}

service pop3 {
}

#
# Internal services
#
service auth {
    unix_listener auth-userdb {
    }

    # Grant chasquid access to request user authentication.
    unix_listener auth-chasquid-userdb {
        mode = 0660
        user = chasquid
    }
    unix_listener auth-chasquid-client {
        mode = 0660
        user = chasquid
    }
}
service auth-worker {
}
dict {
}
service lmtp {
    # This is used by mda-lmtp.
    unix_listener lmtp {
    }
}

#
# Default Folders
#
namespace inbox {
    type = private
    separator = .
    inbox = yes
    mailbox Drafts {
        special_use = \Drafts
        auto = subscribe
    }

    mailbox Junk {
        special_use = \Junk
        auto = create
    }

    mailbox "Junk E-mail" {
        special_use = \Junk
        auto = no
    }

    mailbox spam {
        special_use = \Junk
        auto = no
    }

    mailbox Spam {
        special_use = \Junk
        auto = no
    }

    mailbox Trash {
        special_use = \Trash
        auto = subscribe
    }

    mailbox TRASH {
        special_use = \Trash
        auto = no
    }

    mailbox "Deleted Items" {
        special_use = \Trash
        auto = no
    }

    mailbox Sent {
        special_use = \Sent
        auto = subscribe
    }

    mailbox "Sent Mail" {
        special_use = \Sent
        auto = no
    }

    mailbox "Sent Messages" {
        special_use = \Sent
        auto = no
    }

    mailbox "Sent Items" {
        special_use = \Sent
        auto = no
    }

    mailbox sent-mail {
        special_use = \Sent
        auto = no
    }

    Archive {
        special_use = \Archive
        auto = create
    }

    mailbox Archives {
        special_use = \Archive
        auto = no
    }
}
EOF

This configuration does a bunch of things:

  • It sets up logging, to help with debugging.
  • It specifies that we’re using virtual accounts (accounts that are not tied to Linux user accounts) and sets the user that will own those accounts.
  • It sets where mailboxes will be stored (by domain and within /var/vmail) and how they’ll be set up (using Maildir format, for one file per message).  It also specifies how user accounts are defined and where passwords are stored (I’m storing them in per-domain passwd files alongside the Chasquid domain configurations, to keep all user-related configs together.)
  • It defines our TLS requirements and specifies where to find domain-specific TLS certs (which we’ll cover more in part 2).
  • It specifies which protocols Dovecot will handle and configures the specifics of those.  Most notably, we’re disabling the older non-encrypted versions of the POP3 and IMAP protocols and requiring the use of TLS to fetch mail for better security.
  • It establishes an interface that Chasquid can use to authenticate users so that they can use a single password to both send and receive mail.
  • And it defines a what a default mailbox should look like when a user first accesses it.  As part of this, it aliases commonly used folder names together so that, for example, all sent mail will stay together across different email clients, even if one uses “Sent,” another uses “Sent Items,” and a third uses “Sent Mail.”

We also need to set up a couple of other directories.  First, we’ll create /etc/dovecot/domains where we’ll add a config file for each domain we host.  This will contain paths to the domain’s TLS certificates so that users can access their mailboxes using mail.example.com rather than myserver.example.com and not get certificate warnings.  Then we’ll add directories for dovecot to write it’s log files and for it to store the mail it receives.  Finally, we’ll set ownership on the mailbox directory to the dovenull user.

sudo mkdir -p /etc/dovecot/domains
sudo mkdir -p /var/log/dovecot
sudo mkdir -p /var/vmail
sudo chown dovenull.dovenull /var/vmail

Finally, we’ll need to restart dovecot so that it will start to use the new configuration:

sudo systemctl restart dovecot

If all goes well, Dovecot is configured and running.  Now it’s time to install Chasquid.

Installing Chasquid

I’ll admit I had not heard of Chasquid until I started researching this project, but it looked interesting, so I decided to give it a try and I’ve been happy.  Chasquid is a security-first MTA (mail transfer agent) that mostly works out of the box.

Chasquid takes its name from the Chasquis, a relay team of highly trained messengers that delivered oral messages throughout the Inca empire.  It has several features that I liked, such as:

  • It does not support features like open relaying, that are often lead to improper, insecure mailserver configurations.
  • It requires TLS for users submitting outgoing messages.
  • It can handle all of the standard sender validation techniques, including SPF checking and DKIM signing and verification.
  • It keeps track of the domains it receives incoming messages from and will reject connections if the domain’s sending server had previously connected with TLS but later tries to use plain text.  This helps prevent spammers from spoofing legitimate servers or using mailware to send messages.

Chasquid also supports all of the features you expect from an SMTP server:

  • The ability to scan for spam or viruses using third party tools like SpamAssassin or ClamAV, as well as greylisting.
  • Email aliases, including aliases that “pipe” to commands for special processing.
  • Suffix dropping (i.e. the ability to use user+somethingextra@example.com and have it be delivered to user@example.com automatically).

Chasquid is available as a Debian package, so we can install it like any other package:

sudo apt install chasquid

Then we can configure it with this command:

cat <<EOF | sudo tee -a /etc/chasquid/chasquid.conf

# Deliver email via lmtp to dovecot.
mail_delivery_agent_bin: "/usr/bin/mda-lmtp"
mail_delivery_agent_args: "--addr"
mail_delivery_agent_args: "/run/dovecot/lmtp"
mail_delivery_agent_args: "-f"
mail_delivery_agent_args: "%from%"
mail_delivery_agent_args: "-d"
mail_delivery_agent_args: "%to%"

# Use dovecot authentication.
dovecot_auth: true

# Log to file
mail_log_path: "/var/log/chasquid/chasquid.log"
EOF

Chasquid uses “sane defaults,” so there isn’t much configuration required.  The main thing we do here is tell Chasquid how to access Dovecot’s LMTP service to deliver mail.  We also set up logging and tell Chasquid to use Dovecot authentication to validate users trying to send mail against their Dovecot accounts.  All that’s required to do this is `dovecot_auth: true`, as Chasquid will look in the standard locations where most Linux distributions place this socket when it tries to connect.  If you’re using an uncommon Linux distro or a non-starndard Dovecot installation, you might have to make adjustments.

As I noted in the intro, I’m using the third-party provider, MXGuarddog, as my spam filter.  MXGuarddog serves as the mail exchanger (MX) for my domains.  Sending MTAs forward all mail to their servers, they filter it, and forward non-spam on to Chasquid.  Since there’s nothing stopping a spammer from ignoring my MX records and just trying to connect directly to any of my domains’ known host names, like mail.example.com, I use an arbitrary port number for server-to-server SMTP:

cat <<EOF | sudo tee -a /etc/chasquid/chasquid.conf

# since we're using MXGuardDog as our MX, listen on a non-standard
# port so that non-compliant spammers won't find us
smtp_address: ":20005"
EOF

Of course, it’s even better to change the port number to something completely arbitrary, like 59731 or 20956.  Once you’ve done that, you can set your server’s port number in MXGuarddog’s settings, and they’ll forward mail to that port instead of port 25.  As an alternative, you could set your server’s firewall to only allow traffic in from MXGuarddog’s published IP addresses.

I’ve been using MXGuarddog for years and I’ve found that their service works much better than any SpamAssassin config I’ve ever tried, and at 25 cents per email account per month, it’s totally worth it.  My only complaint with MXGuarddog is that they tend to be a little too aggressive:  even with my settings at their most permissive levels, they still block a lot of mail I want, especially from mailing lists, so it’s important to keep an eye on your spam reports and whitelist anything important that gets flagged.

If you choose not to use an outside spam filter and choose instead to use SpamAssassin, ClamAV, and/or Greylistd to control spam, there’s no further configuration needed for Chasquid.  Chasquid runs a hook script for every message it processes and, if it finds any of those programs installed on the server, it will call them during processing.

That’s all that’s needed to configure Chasquid, so we can give it a restart to be ready to start sending and receiving mail:

systemctl restart chasquid

Setting up a firewall

It’s always good to run a firewall on your server as an extra layer of defense against attacks.  If you already have a firewall configured, you’ll want to make sure that you open the following ports in it:

  • Dovecot: 993 (secure IMAP), 995 (secure POP3)
  • Chasquid: 587 (secure SMTP with STARTTLS), 465 (secure SMTP), and either 25 or whatever alternate port you chose for incoming SMTP above

You should not open  ports 143 (non-encrypted IMAP) or 110 (non-encrypted POP3), as these protocols pass credentials and message contents in the clear, and we specifically turned them off in the Dovecot configuration.

If you don’t have a firewall on your server already, I personally like to use ufw (Uncomplicated Firewall) for its ease of use.  To install ufw run:

sudo apt install ufw

The set up your configuration using the ufw command.

First, make sure you open up SSH (port 22), since that’s most likely what you’re using to access the server right now, and you don’t want to block yourself:

sudo ufw allow 22/tcp

Then allow the ports for Dovecot and Chasquid (remember to change 25 to your random SMTP port if you changed it):

sudo ufw allow 993,995/tcp
sudo ufw allow 25,465,587/tcp

And finally, enable the firewall.  This should work without dropping your current SSH session.

sudo ufw enable

Wrapping up

So far we’ve installed Dovecot and Chasquid using a configuration that’s secure and that should make sense for most users.  In part two, we’ll look at how to add email domains to the server, how to set up user email accounts, and we’ll explore what needs to be done to ensure the messages we send get delivered properly.

Note: I may receive service credits from MXGuarddog for mentioning them here. Regardless, they’ve been a great provider who I’ve been paying a modest sum to manage my spam for years, and my recommendation is genuine.

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

<