Raspberry Pi Email Server Part 2: Dovecot

Powered by Drupal
Submitted by Sam Hobbs on

Dovecot Logo This is the second part of a five part tutorial that will show you how to install a full featured email server on your Raspberry Pi. This tutorial covers Dovecot, which provides SASL authentication and IMAP capabilities.

The parts are:

The Introduction & Contents Page (read first)

Raspberry Pi Email Server Part 1: Postfix

Raspberry Pi Email Server Part 2: Dovecot

Raspberry Pi Email Server Part 3: Squirrelmail

Raspberry Pi Email Server Part 4: Spam Detection with Spamassassin

Raspberry Pi Email Server Part 5: Spam Sorting with LMTP & Sieve

Fixing the errors that appeared during dovecot installation

In part 1, when you installed Dovecot I mentioned that you might see some errors like this:

Creating config file /etc/dovecot/conf.d/20-imap.conf with new version
[....] Restarting IMAP/POP3 mail server: dovecotError: socket() failed: Address family not supported by protocol
Error: service(imap-login): listen(::, 143) failed: Address family not supported by protocol
Error: socket() failed: Address family not supported by protocol
Error: service(imap-login): listen(::, 993) failed: Address family not supported by protocol
Fatal: Failed to start listeners
 failed!
invoke-rc.d: initscript dovecot, action "restart" failed.
dpkg: error processing dovecot-imapd (--configure):
 subprocess installed post-installation script returned error exit status 1
Setting up dovecot-ldap (1:2.1.7-7) ...

These errors are caused by the lack of IPv6 support, which I mentioned in the previous tutorial. To remove the errors, open the main dovecot configuration file (/etc/dovecot/dovecot.conf) and find this line:

listen = *, ::

And change it to:

listen = *

The * means “all IPv4 addresses”, the :: means “all IPv6 addresses”. Now restart Dovecot, and you shouldn’t get any errors:

sudo service dovecot restart

Note: since I wrote this tutorial, there have been a few small changes to the default configuration file - you may find that the line is commented (with a # at the start of the line). If so, remember to uncomment it when you make your changes!

Tell Dovecot where your Mailbox is

Open /etc/dovecot/conf.d/10-mail.conf and find this line:

mail_location = mbox:~/mail:INBOX=/var/mail/%u

Change it to this:

mail_location = maildir:~/Maildir

Instruct Postfix to use Dovecot SASL

Now we need to tell Postfix that we would like to use Dovecot for SASL authentication. Open /etc/postfix/main.cf and add these lines:

smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes

Now tell Dovecot to listen for SASL authentication requests from Postfix. Open /etc/dovecot/conf.d/10-master.conf and comment out the current block that begins with service auth (place a # at the start of each line). Replace it with this:

service auth {
        unix_listener /var/spool/postfix/private/auth {
                mode = 0660
                user = postfix
                group = postfix
        }
}

Now you want to enable plain text logins. Do it by adding these two lines to /etc/dovecot/conf.d/10-auth.conf. Make sure they are not already present in the file, or your settings may be overwritten with the default ones if the default is declared later in the file than the lines you add. If the parameters are already present, you can either modify the existing lines or comment them out and add these new ones:

disable_plaintext_auth = no
auth_mechanisms = plain login

Note that although the logins are in plain text, we will be setting Postfix up later so that it only allows you to use plaintext logins from within SSL/TLS. This means that your login and password will sent in an encrypted session - you wouldn't see them in plain text if you used a packet sniffer, for example. For now, we’re allowing unencrypted plain text logins so that we can test logging in with Telnet. Since the connection is local (from the Pi to the Pi), your password isn’t being sent over any insecure networks so this is fine.

Testing SASL

Creating a new user for testing purposes is a good idea. Let’s call this temporary user testmail and give it the password test1234 Use this command to add the user, and follow the prompts including setting a password.

sudo adduser testmail

Now restart Postfix and Dovecot:

sudo service postfix restart
sudo service dovecot restart

We’re now going to try and send an email after authenticating with SASL. The server is expecting to see a base64 encoded version of your username and password, so we have to convert it first. There are three ways of doing this, so I've given examples below using the testmail username and test1234 password:

#Method No.1
echo -ne '\000testmail\000test1234' | openssl base64

#Method No.2
perl -MMIME::Base64 -e 'print encode_base64("\0testmail\0test1234");'

#Method No.3
printf '\0%s\0%s' 'testmail' 'test1234' | openssl base64

I have discovered that if your password starts with a number, methods 1 and 2 don’t work. Assuming the username and password are testmail and test1234, the commands produce this:

AHRlc3RtYWlsAHRlc3QxMjM0

WARNING: If you’re having problems with authentication and you paste examples to forums or mailing lists, be aware that it is really easy to convert this back into your username and password (hence the creation of a test user). If you're using your real username and password to test, redact it before posting! Now, still logged into the Pi via SSH, you can telnet port 25 to test whether or not SASL is working. There’s only one extra step, which is the AUTH PLAIN command that comes after ehlo but before mail from. For testing, the permit_mynetworks parameter should be commented out under your postfix smtpd_recipient_restrictions block in /etc/postfix/main.cf. If you’re following on from Raspberry Pi Email Server Part 1: Postfix then this should already be the case. If you have to change it, remember to reload postfix (sudo service postfix reload) after you change the value. Here’s an example:

telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 samhobbs ESMTP Postfix (Debian/GNU)
ehlo facebook.com
250-samhobbs
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
AUTH PLAIN AHRlc3RtYWlsAHRlc3QxMjM0
235 2.7.0 Authentication successful
mail from:testmail
250 2.1.0 Ok
rcpt to:me@externalemail.com
250 2.1.5 Ok
data
354 End data with .
Subject: This is my first email that has been authenticated with Dovecot SASL
Woop woop
.
250 2.0.0 Ok: queued as B87133F768
quit
221 2.0.0 Bye
Connection closed by foreign host.

Now try again but enter the username/password incorrectly (base64 encode something random) – you should get an error message and the email won’t send. If everything went to plan, then SASL is working properly! You can now uncomment permit_mynetworks again.

Separating Incoming email (unauthenticated) from Outgoing Email (SASL authenticated)

It’s probably a good idea to have a dedicated port for sending outgoing email…here’s why: Port 25 doesn’t require (but does offer) SSL/TLS encryption. If you mess up configuring your mail client you could end up letting it authenticate with SASL over insecure connections. Using a different port that only accepts SSL/TLS connections removes the risk that a poorly configured email client could be sending your password unencrypted over dodgy networks. There are two ports you can use for this:

  1. 465: SMTP over SSL
  2. 587: Email submission

587 is the “official” port for email clients (like K9 mail, Thunderbird and Outlook) to use when submitting messages to the Mail Submission Agent (your email server) – the submission may be encrypted or unencrypted depending on the server configuration. 465 was a port that was assigned for SMTP with SSL/TLS before the STARTTLS protocol was introduced, back in the days when you chose your port and that decided on the type of connection you were going to get (encrypted or unencrypted). STARTTLS changed things because it allows you to connect with an unencrypted connection (like the one you get with Telnet), and then upgrade to an encrypted connection without changing port… so when STARTTLS was introduced, SMTPS on port 465 was removed from the standard because you could do the same thing with a single port (25). However, I think there is some value in specifying a port for submission that only accepts SSL/TLS encrypted connections, and won’t work if the connection isn’t encrypted. This means that if you misconfigure your email client it just won’t work, instead of working and sending your password in an unencrypted format. So, anyway… Here’s how to set up Postfix to listen on port 465 for encrypted connections. The first step is telling Postfix to listen on port 465, so open /etc/postfix/master.cf and uncomment the line:

smtps     inet  n       -       -       -       -       smtpd

Now restart Postfix:

sudo service postfix restart

Test whether Postfix is listening on port 465:

telnet localhost 465
Trying 127.0.0.1...                                                                           
Connected to localhost.                                                                       
Escape character is '^]'.
220 samhobbs.co.uk ESMTP Postfix (Debian/GNU)
ehlo samhobbs.co.uk
250-samhobbs
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
quit
221 2.0.0 Bye
Connection closed by foreign host.

OK, so now it’s listening on the right port, but it’s allowing unencrypted connections. Here’s how you force TLS on port 465: open /etc/postfix/master.cf and find the line you uncommented earlier. Below it are some options, you want to edit them so that they look like this (i.e. uncomment lines 2 and 3):

smtps     inet  n       -       -       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes

Line 3 is forcing TLS on port 465, and line 2 means that connections to port 465 have a different label in the logs, which can be useful for debugging.

sudo service postfix restart

Now try connecting with Telnet again… you should be able to establish a connection, but not receive any prompts from the server:

telnet localhost 465                                            
Trying 127.0.0.1...                                                                           
Connected to localhost.
Escape character is '^]'.
exit
exit
Connection closed by foreign host.

Now try openssl:

openssl s_client -connect localhost:465 -quiet
depth=0 CN = samhobbs
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = samhobbs
verify return:1
220 samhobbs.co.uk ESMTP Postfix (Debian/GNU)
quit
221 2.0.0 Bye

Good: we are able to start a TLS encrypted connection. We got some errors because the certificate is self-signed (it's not signed by a certificate that is in the trusted root store on the server) but this is OK because we're just using the certificate for testing for now. When you come back later to set up a proper certificate, you can use this command to verify it. The -CApath option tells openssl where the trusted certificates are stored on your system:

openssl s_client -connect localhost:465 -quiet -CApath /etc/ssl/certs

Successful validation looks something like this:

sam@samhobbs:~$ openssl s_client -connect localhost:465 -quiet -CApath /etc/ssl/certs
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify return:1                                                                              
depth=2 C = GB, ST = Greater Manchester, L = Salford, O = COMODO CA Limited, CN = COMODO RSA Certification Authority
verify return:1                                                                              
depth=1 C = GB, ST = Greater Manchester, L = Salford, O = COMODO CA Limited, CN = COMODO RSA Domain Validation Secure Server CA
verify return:1                                                                              
depth=0 OU = Domain Control Validated, OU = PositiveSSL, CN = samhobbs.co.uk                 
verify return:1                                                                              
220 samhobbs.co.uk ESMTP Postfix (Ubuntu)                                                    
quit                                                                                         
221 2.0.0 Bye

There are a couple more changes we want to make here: first, tell Postfix to only advertise SASL authentication over encrypted connections (so that you don’t accidentally send your password in the clear). Open /etc/postfix/main.cf and add this line:

smtpd_tls_auth_only = yes
sudo service postfix reload

Now connect to port 25 and you shouldn’t see AUTH advertised:

telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 samhobbs.co.uk ESMTP Postfix (Debian/GNU)
ehlo samhobbs.co.uk
250-samhobbs.co.uk
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN

Lastly, we want to override the smtp_recipient_restrictions for port 465 so that it doesn't accept incoming messages from unauthenticated users. At first, I didn't make this change and I noticed that some spam emails were coming in on port 465 and bypassing my spam filter, which I configured to scan all incoming email on port 25, but not 465 because I only expected it to be used for outgoing email. We can do this by overriding the smtp_recipient_restrictions list for port 465 in /etc/postfix/master.cf. Open master.cf and find the smtps line. Add a new recipient restrictions list option like this:

smtps     inet  n       -       -       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject

Now reload postfix:

sudo service postfix reload

Perfect! Postfix configuration is now complete.

Testing IMAP

There are two main protocols for fetching mail: POP and IMAP. The main difference between them is what they do with emails when they collect them: a POP client will fetch email from your server and remove it from the server when it’s done. This is inconvenient if you want to connect with two or more devices (like a phone and a computer) and have complete copies of all your emails on both. IMAP, on the other hand, makes a copy of the emails on the server and leaves the originals there. For this reason, I think IMAP is much more useful than POP and I didn’t even bother to set up POP on my server. We can now test the IMAP server with Telnet in a similar way to SMTP & SASL testing earlier. This time, we’ll be using port 143, the standard port for IMAP. The stages are:

  1. establish a connection with telnet localhost 143
  2. log in with a login "USERNAME" "PASSWORD"" (not base64 encoded this time)
  3. select inbox to see messages inside b select inbox
  4. logout with c logout

In case you're wondering, the "a b c" thing is done because a client can send multiple commands to the server at once, and they might not come back in the same order depending on what they are. So, the responses have the same letter as the commands they are responding to so that the client doesn't get muddled. Here’s an example, using the testmail user we created earlier:

telnet localhost 143
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE STARTTLS AUTH=PLAIN AUTH=LOGIN] Dovecot ready.
a login "testmail" "test1234"
a OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS MULTIAPPEND UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS SPECIAL-USE] Logged in
b select inbox
* FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
* OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen \Draft \*)] Flags permitted.
* 1 EXISTS
* 0 RECENT
* OK [UNSEEN 1] First unseen.
* OK [UIDVALIDITY 1385217480] UIDs valid
* OK [UIDNEXT 2] Predicted next UID
* OK [NOMODSEQ] No permanent modsequences
b OK [READ-WRITE] Select completed.
c logout
* BYE Logging out
c OK Logout completed.
Connection closed by foreign host.

Adding TLS support

Now that we know IMAP is working, we need to enable IMAPS (imap with SSL/TLS). The standard port for this is 993. Many other tutorials that were written for older versions of dovecot will tell you to do this in different ways that won’t work, I tried 3 different methods before I ended up with a working one. First, edit /etc/dovecot/conf.d/10-master.conf, find the “service imap-login” block and uncomment the port and SSL lines so that it looks like this:

service imap-login {
  inet_listener imap {
    port = 143
  } 
  inet_listener imaps {
    port = 993
    ssl = yes
  }
}

Edit 14/10/2015: the default dovecot configuration files changed recently after Jessie became the new stable distribution of Debian, which caused some users problems; TLS on port 993 used to be enabled by default but now it isn't. We need to re-enable it. In /etc/dovecot/conf.d/10-ssl.conf, find ssl = no and change it to:

ssl = yes

There have been some security vulnerabilities discovered in older versions of the SSL protocol in recent times. SSLv2 is disabled by default, but it doesn't harm to explicitly disable it again. SSLv3 is vulnerable to an attack called POODLE, so we will disable it too. In the same file, find the ssl_protocols parameter line, uncomment it and add !SSLv3 to the end, like this:

ssl_protocols = !SSLv2 !SSLv3

Edit 02/09/2017: if you're using Debian Stretch or later, or one of its derivatives, then you will need to edit that line to match the following. The SSLv2 option is no longer recognised as an option for ssl_protocols because it has been removed entirely:

ssl_protocols = !SSLv3

For some bizarre reason, the Dovecot package for Raspberry Pi (and possibly newer versions of Ubuntu) does not create a self-signed certificate during installation like it used to. So, we have to create one manually. If you look in /usr/share/dovecot/ you will find the script that used to be used to generate the certificate; we can use it ourselves to simplify the process. The script is located at /usr/share/dovecot/mkcert.sh and looks like this:

#!/bin/sh

# Generates a self-signed certificate.
# Edit dovecot-openssl.cnf before running this.

OPENSSL=${OPENSSL-openssl}
SSLDIR=${SSLDIR-/etc/ssl}
OPENSSLCONFIG=${OPENSSLCONFIG-dovecot-openssl.cnf}

CERTDIR=/etc/dovecot
KEYDIR=/etc/dovecot/private

CERTFILE=$CERTDIR/dovecot.pem
KEYFILE=$KEYDIR/dovecot.pem

if [ ! -d $CERTDIR ]; then
  echo "$SSLDIR/certs directory doesn't exist"
  exit 1
fi

if [ ! -d $KEYDIR ]; then
  echo "$SSLDIR/private directory doesn't exist"
  exit 1
fi

if [ -f $CERTFILE ]; then
  echo "$CERTFILE already exists, won't overwrite"
  exit 1
fi

if [ -f $KEYFILE ]; then
  echo "$KEYFILE already exists, won't overwrite"
  exit 1
fi

$OPENSSL req -new -x509 -nodes -config $OPENSSLCONFIG -out $CERTFILE -keyout $KEYFILE -days 365 || exit 2
chmod 0600 $KEYFILE
echo 
$OPENSSL x509 -subject -fingerprint -noout -in $CERTFILE || exit 2

If you were going to use this certificate for any significant length of time, it would be worth editing the parameters in the config file it uses (/usr/share/dovecot/dovecot-openssl.cnf) to set the proper common name and contact details on the certificate. However, I suggest you leave the defaults as they are, use this certificate just for testing, and then come back later and generate a new cert when everything is working (more on that later). You must be in the same folder as the configuration file when you run the script, or it will not find the config and the certificate generation will fail. The following two commands will change to the right folder and then execute the script:

cd /usr/share/dovecot
sudo ./mkcert.sh

You should see a message "writing new private key to '/etc/dovecot/private/dovecot.pem'" and then some details about the certificate. Next, find the following two lines in /etc/dovecot/conf.d/10-ssl.conf and uncomment them:

#ssl_cert = </etc/dovecot/dovecot.pem
#ssl_key = </etc/dovecot/private/dovecot.pem

Now reload dovecot to apply the changes:

sudo service dovecot reload

Since IMAPS is a connection over SSL/TLS, we can’t use Telnet to test it. Instead, we use openssl to create a secure connection. There are two versions of the command, one will show you LOADS of information about the certificate used to encrypt the connection, and the other will suppress this info. I recommend trying the long version out of interest, but both will work the same for the test: For full information:

openssl s_client -connect localhost:993

For minimal information:

openssl s_client -connect localhost:993 -quiet

I won’t print the output of the first command, because it’s ridiculously long. Here’s an example of the second, including a login test:

admin@samhobbs /etc/dovecot/conf.d $ openssl s_client -connect localhost:993 -quiet
depth=0 O = Dovecot mail server, OU = samhobbs, CN = samhobbs, emailAddress = root@samhobbs.co.uk
verify error:num=18:self signed certificate
verify return:1
depth=0 O = Dovecot mail server, OU = samhobbs, CN = samhobbs, emailAddress = root@samhobbs.co.uk
verify return:1
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE AUTH=PLAIN AUTH=LOGIN] Dovecot ready.
a login "testmail" "test1234"
a OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS MULTIAPPEND UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS SPECIAL-USE] Logged in
b logout
* BYE Logging out
b OK Logout completed.
Connection closed by foreign host.

Good stuff: SSL/TLS is working on port 993, and you can log in successfully. Note that by default Dovecot uses a “snakeoil” self-signed certificate. SSL/TLS certificates are used for two purposes: encryption and verification. The “snakeoil” certificate will encrypt your content but it won’t verify that you’re talking to your server – you could be talking to someone imitating your server (anyone can create a self-signed certificate claiming to be any website). If you’d like to get your certificate signed without forking out loads of money to a cert signing authority, I’d recommend CAcert. I've written a tutorial explaining how to generate your own cert and get it signed here. If you opt for a commercial certificate, you can use the CAcert tutorial to generate the certificate and then this tutorial will explain the differences in the installation/configuration of commercial certificates once you have it signed. If you're testing a proper certificate, use this command to tell openssl where the trusted root certificates are stored:

openssl s_client -connect localhost:993 -quiet -CApath /etc/ssl/certs

Tidying up and enabling WAN access

Before opening the ports on your router to the world, it’s a good idea to delete that test user because the password is so easy to guess.

sudo userdel testmail

Also, if you still use the "pi" login, for goodness' sake change the password from "raspberry"! You can do this using the passwd command when logged in as pi:

passwd

Or you can achieve the same thing when logged in as another user by using sudo to gain root privileges:

sudo passwd pi

Now you can open a few ports on your router’s firewall. Make sure your Pi has a static LAN IP address and then forward these ports from WAN to its LAN IP address:

  • Port 25 for SMTP (used for receiving emails)
  • Port 465 for secure SMTP (used for sending emails after SASL authentication)
  • Port 993 for IMAPS (used to receive emails on your phone/tablet/computer)

Here’s an example on my router, running OpenWrt: openwrt-port-forwards-raspberry-pi-email-server.png

Setting up IMAP Email Clients

I’m now going to run through setting up IMAP email clients quickly, using K9 Mail on Android and Thunderbird on GNU/Linux as examples. The setup for Thunderbird on Windows and Mac OSX should be very similar. The basics are this:

  • Select an IMAP connection
  • Your login is your username only (omit @yourdomain.com), and you password is…your password!
  • For incoming emails: select use SSL/TLS always and the program should automatically select port 993
  • For outgoing emails: select SSL/TLS always. The program may suggest port 587, but you want port 465

K9 Mail

Open K9 Mail and select add new account. Type in your account information (you@yourdomain.com and password) and then select manual setup. Select IMAP and then enter your information as follows… Incoming email: K9 Incoming Email Settings Outgoing email: K9 Outgoing Email Settings

Thunderbird

Open Thunderbird, and then click Account Actions –> Add Mail Account. Fill in your password and email address, which is your username followed by your fully qualified domain name (FQDN), i.e. username@yourdomain.com: Thunderbird Step 1: Mail Account Setup Thunderbird will try to auto-detect settings and fail. Don’t worry, this is normal. Select “manual config”:  Thunderbird Step 2: TB will try to autodetect settings, and fail. Select “Manual Config" Now edit the settings as appropriate. I had to remove a period (.) from in front of my “server hostname”, and edit the SSL and Authentication settings. If you select “SSL/TLS” for both incoming and outgoing, ports 993 and 465 are automatically selected: Thunderbird Step 3: Edit the settings so that they match these (but change them to match your username and domain name!) Now try emailing yourself from your external email address, and see if your email gets through. If you are having problems, be sure to check you’ve set up an MX record as well as a DNS A record.

Stuck in spam filters?

A few people have contacted me recently to say that their email server is working fine but their emails are getting sent to Gmail's spam folder. If you are experiencing problems like this (or even if you're not), try setting up an SPF and/or PTR record as explained in my DNS basics tutorial. You might also want to check if your domain name or IP address are on any blacklists. There's a handy website called MX toolbox that lets you do this (choose blacklist check from the dropdown menu).

Almost done…

Good news! If you’ve reached this far and everything is working, then you’re almost done. The next step (Webmail with Squirrelmail) is optional but by far the easiest of the three steps. If you’ve hit a rut, please post a comment and I’ll try and help you out. If not… continue to Raspberry Pi Email Server Part 3: Squirrelmail

Comments

Hi Sam, This time I do have it working. In my case its been quite a journey but can now send and receive emails regardless that I'm using my dynamic IP Address. This is how I understood the solution... I needed to connect to port 465 on the relay host using SSL encryption but postfix doesn't support that. So in the end I had to use another program called stunnel to create an SSL connection to the server on another port which I can then use as if it was port 465. This was a handy link explaining in very nice detail http://eglug.org/book/export/html/1923

All the test emails I sent over last couple of days have suddenly flooded my inbox! Great to see those emails finally being received. Thanks for your help getting me going in the right direction. I now know a lot more about email servers than I ever did before.

Adrian

That's great news! Thanks for providing a link, it was really frustrating not being able to test it myself, I'll have a read. I got a second NUC for Xmas so I'll be setting up a backup server at my parents' house. They're with BT so I'll have to relay email through BT's SMTP server when the backup is sending mail. I feel sure it's possible to do all of that with Postfix (it must be something that people need quite often, right?), so I'll let you know how I get on with that and fall back on Stunnel if I have no luck. Sam

Yes it seems like a big ommission in postfix. The log reports not implemented when you try it but maybe there is some other way around it I missed. Anyway for now I'm just happy it works so I doubt I'll delve more into it myself, will be interested how you get on though.

cheers

Hi, been following the tutorial.

Initially it works fine, I can send the emails and then restrict sending from my network per tutorial one, but then on this tutorial I get a problem that Telnet stops returning the 220 line and eventually closed itself (says closed by foreign host as with when i type "quit", but i didn't type anything.

after undoing everything, then restarting and reloading postfix and retrying telnet after every change, i've noticed it's the "smtpd_sasl_auth_enable = yes" line causing the trouble. if i comment out that but leave the smtp_sasl_type = dovecot and smtpd_sasl_path = private/auth lines, telnet will continue responding as expected.

can you suggest any help?

Hi Dave, Do you get any errors when you restart? If you look at the end of your mail log /var/log/mail.log do you see any related messages? Without smtpd_sasl_auth_enable = yes you shouldn't get the AUTH capability advertised when you EHLO, because the default for that parameter is "no". A couple of other people have had trouble setting the path that dovecot should listen on for connections from postfix (specifically, this line under " service auth"):
unix_listener /var/spool/postfix/private/auth {
Check carefully that you have that whole block of code written exactly as it is in the tutorial. Sam

thank you, especially for the quick response

i didn't have the "unix_listener /var/spool/postfix/private/auth" bit correct - after that it's fine.

You're very welcome :) I'm getting quite good at predicting what's wrong now! Sam

hitting a problem now where thunderbird is saying it can't verify the configuration and asking if the username or password are wrong (they aren't, i've checked)

Have you:
  1. Tested IMAP with Telnet/Openssl
  2. Opened the correct ports on your router
  3. Double checked the ports in Thunderbird are correct

Hi Sam,
thanks again for the prompt response.
1) i'll retest imap as i note that mail can be sent from the server but isn't incoming.
2) confession - i'm not actually doing this on a raspberry pi but on a ubuntu virtual machine hosted on windows azure, so i don't need to open anything on the router but i do need to create endpoints on the server for imap/smtp on those ports which i have done.
3) yes, the thunderbird ports were correct.

Ha! I don't get why people don't tell me stuff like that sooner, it's not like I'm going to not help you because it isn't a raspberry pi! My server runs Ubuntu too, and I can assure you the tutorial works. The only thing you should be aware of is that Postfix in Ubuntu is a newer version so it has smtpd_relay_restrictions as well as smtpd_recipient_restrictions. The relay restrictions were introduced to prevent accidental creation of a permissive recipient restriciton list that would allow spammers to use the server as a relay. There's more info in the postfix documentation if you're interested - you don't have to read it though, you can just leave the relay access restrictions at their default values and use this tutorial as it is written. Yes the 0 exists thing is the number of messages in the inbox, so if you don't have any you won't see anything there. Try sending yourself an email with telnet if you want to check it lands in the right Maildir! Well spotted on the openssl front, the reason that happens is that I was using the self-signed "snakeoil" certificate that Dovecot generates automatically at the time. The script uses the hostname of the machine (mine is/was samhobbs), if you were on a raspberry pi this would probably be "raspberrypi". The common name on the "real", signed cert should be your fully qualified domain name (yourdomain.com), so that's fine. Just to check that it's not a firewall issue, could you try to connect from your computer directly (not localhost), e.g.:
openssl s_client -connect yourdomain.com:993 -quiet
BTW if you want to check your cert is valid, you can use the -CApath option like this (/etc/ssl/certs is the certificate directory on Ubuntu - the certs may be installed somewhere else but they are all symlinked here):
feathers-mcgraw@Hobbs-T440s:~$ openssl s_client -connect samhobbs.co.uk:993 -quiet -CApath /etc/ssl/certs
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify return:1
depth=2 C = GB, ST = Greater Manchester, L = Salford, O = COMODO CA Limited, CN = COMODO RSA Certification Authority
verify return:1
depth=1 C = GB, ST = Greater Manchester, L = Salford, O = COMODO CA Limited, CN = COMODO RSA Domain Validation Secure Server CA
verify return:1
depth=0 OU = Domain Control Validated, OU = PositiveSSL, CN = samhobbs.co.uk
verify return:1
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE AUTH=PLAIN AUTH=LOGIN] Dovecot (Ubuntu) ready.
a logout
Sam

I've been running circles to figure this out. I've been following instructions for postfix and dovecot, but I admit that I've not been testing along with telnet. At the end of the dovecot tutorial I then tried testing telnet and it doesn't work.
Here's what it spits out after trying to authenticate and then send mail:
root@domain:~# telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 domain.com ESMTP Postfix (Debian/GNU)
ehlo google.com
250-domain.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
AUTH PLAIN [hash]
503 5.5.1 Error: authentication not enabled
mail from:testmail
250 2.1.0 Ok
rcpt to:smthng@example.com
554 5.7.1 <smthng@example.com>: Relay access denied

Thanks in advance for giving me tips!

You've probably missed a step under "instruct postfix to use dovecot sasl" in part 2. Sasl isn't enabled or you'd see it advertised when you EHLO. Can you check thrugh each of those changes carefully go see if you can find the one you missed? If you've done some and not others you may find you get a useful error when you restart postfix or dovecot - if you do, it may help to pinpoint the problem:
sudo service postfix restart
sudo service dovecot restart
Sam

Everything was right with the files and restarting services printed out no errors. But I tried commenting out the line «smtpd_tls_auth_only = yes» on postfix/main.cf and it worked!
But, yet, web mail services are rejecting my email and I can't connect through 465 (port forwarding was not overlooked).

Ah sorry, I forgot you're doing it out of sequence. That line you commented out means auth is only advertised over secure connections so if you want to test it with that in place you'll have to use openssl to create a secure connection. So in other words there's nothing wrong with the telnet output you posted in your original comment, because the telnet session isn't secure so postfix shouldn't be letting you authenticate. Have you tested port 465 with openssl? What are the errors you get from other smtp servers, are the emails actually bouncing or are they just landing in spam? Sam

Actually, forget what I said about port 465. I was typing 265 in the command-line instead. Working into midnight has it's disadvantages...
About what you said for the commented out line: That indeed clarifies the issue. It's understandable given that I bashed all the code first and asked questions later (or rather "run the tests later").
About the email being sent: It is indeed blocked by gmail, hotmail (nowadays they call it "outlook"?) and another custom server I use in my job which operating system and e-mail service I don't know but I believe it to be Windows based and ancient. Here's what gmail returns back to my server:
host gmail-smtp-in.l.google.com[74.125.195.26] said:
550-5.7.1 [188.81.51.209 12] Our system has detected that this message is 550-5.7.1 likely unsolicited mail. To reduce the amount of spam sent to Gmail, 550-5.7.1 this message has been blocked. Please visit 550-5.7.1 http://support.google.com/mail/bin/answer.py?hl=en&answer=188131 for 550 5.7.1 more information. u2si7944030wix.82 - gsmtp (in reply to end of DATA command)

Is this related to using the "snakeoil" certificate? Maybe for testing using short messages?

Ha! Don't worry, I've been there many times before! Are these emails ones you sent with telnet or an email client, or both? Someone pinted out that the telnet test in this tutorial is missing a date, which may set off a spam filter. I have two ideas. Try setting up an SPF record to see if that helps (it's a DNS record that you input as a TXT type, defining which IP addresses are authorised to send email for your domain). Mine looks like this:
v=spf1 mx a ~all
...which means allow IP addresses that match an MX or DNS A record for the domain, and disallow the rest. This should be fine for yours too. The above may help if it's a problem with your IP address. I also think you should email me from your server so I can check the spam score of your email, it might tell us something. It's also possible that it's the message body as you said, but you could test that by copying the text of a "normal" email and sending that to yourself. Sam

Hi there Sam!
After trying your mailserver tutorial with a no-ip pointer I finally got my domain and set up my "real" mailserver.
Everything went ok (for the dummiest people like me this is not just copy and paste tutorial commands, so minor problems can be found) but I'm looking for a HDD quota warning because I do not wish to get my HDD full of e-mails and I'm not finding my answer.
This far I've set my message_size_limit and now I would like to set a "disk almost full" warning.
Can you tell me how to do it?
Thanks in advance!

You'd really have to try hard to fill up a hard drive with emails - my Maildir is only 4.0KB! I don't know of any postfix parameter that will do warnings for you. You can set a mailbox_size_limit if you're worried about this. Why not write a shell script that does a ls -l on your Maildir and sends you an email if it's close to the limit? There's some relevant stuff about sending automated emails in my backup script that you could adapt. Sam

Hi

Brilliant tutorial by the way, really easily to grasp what the code means with the explainations.

I have however come to a stumbling block and would appreciate any assistance in trying to solve this. After adding smtpd_tls_auth_only = yes and restarting postfix I get the following error when using telnet

telnet localhost 25
Trying 127.0.0.1...
Trying ::1...
telnet: Unable to connect to remote host: Address family not supported by protocol

(Edit by Sam: deleted main.cf)

Perfect article (read 1&2 parts)! Hope that author actually didn't leave backdoors for spammers... joke:) I would add one thing. It would be great to mention about PTR record for mail server IP that is almost always required to successful mail exchange (I mean spam filters). For example, google takes into account the fact if PTR isn't point to an actual mail server hostname and marks such emails as spam. So, I would mention about it somewhere in the beginning to not to be disappointed after performing all these actions. In other words, if you can't change your PTR (probably via ISP), then there is no sense to set up you own mail server.

Hi, Thanks for the comment :) You're right about the PTR record, it's something I've discussed quite a lot in the comments but it should be in the tutorial as you say. I'm planning on writing a basic DNS tutorial (it's on my long list of things to do), and I'll link to it from the tutorial when it's done. If you can't set up a PTR record you might find that a SPF record will get you past gmail's spam filter. Sam

Andrey

Sun, 02/01/2015 - 13:35

In reply to by Sam Hobbs

Hi Sam, thanks for the clarifications. Yes, I set up SPF too and probably it's enough for google, but it wasn't enough for my company mail server (some Microsoft Exchange) that said me that it used http://www.spamrats.com/ for spam check. And this spamrats checks PTR. OK, we will wait your DNS tutorial in future. Once again thanks for the articles. I feel myself as an IT administrator with 2 years experience after reading and setting up all of this.

sidewinder

Thu, 02/05/2015 - 14:00

Hi Sam,

great tutorial, things work like expected. One question I have is this:
in the described configuration the email users are the same as the raspberry pi system users. I like the simplicity of that, but noticed that users like "pi" and "root" and other users that you get with a default Raspian install are allowed to receive email this way. Is there an easy way to limit this? I tried experimenting with the user database settings in Dovecot shortly (http://wiki2.dovecot.org/UserDatabase), but without success so far.

In my setup, I added my own username to the "sudo" group (and the "adm" group for log files, although that's less important) and then deleted the user "pi". You certainly shouldn't leave the user "pi" enabled without changing the default pw of "raspberry" or you'll be in trouble if spammers figure it out (it would enable them to send spam from your server). Root won't normally receive email unless you've done something unusual and set a root PW. I use an alias in /etc/aliases mapping "root", "postmaster" and "webmaster" to my login because it's useful to receive email notifications for these accounts for things like fail2ban, and you need at least one of these defined to get a cacert certificate as described in that tutorial. If you really want to block a user from receiving email there is a way involving postmapping a database defined at /etc/postfix/recipient_access similar to the helo access db and then adding it to the recipient restrictions list, but if it's a username you're not using just delete it! Sam

Add new comment

The content of this field is kept private and will not be shown publicly.

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.