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

Glen Davies

Mon, 04/28/2014 - 19:56

After following on from your first tutorial, I remember seeing a rule that prevented sending mail, reject_non_fqdn_helo_hostname

Whilst testing I entered Facebook instead of Facebook.com and still received a mail.

Should that be the case?

Sam Hobbs

Mon, 04/28/2014 - 21:50

In reply to by Glen Davies

It depends what else was in the list. The way those lists work is that Postfix goes down the list until it gets a definite match, i.e. REJECT or PERMIT. The block I had was this:
smtpd_helo_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_invalid_helo_hostname,
        reject_non_fqdn_helo_hostname,
        reject_unknown_helo_hostname
So if the submission matches one of those two permit settings at the top (for mynetworks and sasl authentication) then the submission is accepted and the rest isn't processed. So, if you didn't have mynetworks commented out then that would explain why. The submission would only be tested against the reject_non_fqdn_helo_hostname parameter if it didn't come from your "mynetworks", it wasn't authenticated with SASL, it it had a valid helo hostname. The order of these lists is really important, because if you get things in the wrong order you can accidentally create a permissive list and, for example, let anyone send email from your server to any destination (not just your domain). This could happen if you put a permit statement before a test you wanted all mail to go through. Interestingly, the version of Postfix in the RasPi repos is the one from Debian Stable which is quite old, if you used Ubuntu or Debian Sid (unstable) you would get a newer version of Postfix that actually has a different list called smtpd_relay_restrictions in addition to smtpd_recipient_restrictions to help make the lists easier to understand and stop people from getting this wrong by accident! Hope that helps! Sam

I have been following all these instructions and implementing everything that has been instructed. I think that I have hit a rut. I can't say that I understand everything that has been going on but I have followed all the tests and they have all worked. Except for the last lot. When it comes to using IMAPS and a mail client, nothing seems to work. It says that it cannot connect to server. I think I may need a little bit of hand holding.

Assuming all the tests come out successful up to and including testing IMAP what could be going wrong? Would my port forwarding rules be most likely causing the problems?

I don't really know what to say but I can give more information when required.

Joshua

So, you can connect with openssl from within a SSH session to the pi (to localhost) but you can't connect with your email client? If that's right, then it could be a few different things, problems with your:
  • MX record
  • port forwarding
We'll do this step by step, to eliminate things. Which operating system do you use on your computer? If it's a Linux distro, try this from the terminal (I think this will work on MacOS too):
openssl s_client -connect <local-ip-address-of-raspi>:993 -quiet
e.g.
openssl s_client -connect 192.168.1.103:993 -quiet
If you're on Windows, you can use PuTTY instead. If that works, try using your domain name:
openssl s_client -connect yourdomain.com:993 -quiet
Sam

I am running MacOS on my laptop (which is using terminal to ssh) and that command doesn't seem to be doing anything at the moment.

I don't really know what an MX record is... (sorry).

As for port forwarding. My router (with plusnet) seems to handle it in a slightly odd way. There are some preset forwarding possibilities which have worked fine for ssh and ftp and HTTP web server with the pi. When it came to doing it as an email server it all seemed a bit limited. There was one option for port 25 and I created a few more to cover secure SMTP and IMAPS.

Ha, no worries! So is everything working now or are you still having router issues? I actually have one of the PlusNet standard routers in a box somewhere (I bought myself one so I could mess around with it and install *wrt). If you are still having problems I'll dig it out and have a look. Sam

I have the same problem but not in the fact that I have a typo I just cant seem to find the port forwarding on my router
any help is very much appreciated even tho this post is over 3 years old I'm still hopeful
I have a huawei HG533 router and can't find any help on port forwarding with that router and a Raspbian OS to which is my server

Please help
James

Well. I can run

openssl s_client -connect prophetsandbeards.co.uk:993 -quiet

and can connect like that with a login "username" "password" etc.

But when it comes to actually setting up the email client it goes a bit pear shaped. It cannot find the server and I just cannot make it work. If I try and send an email to my server I get an error like

"The error that the other server returned was:
550 5.1.1 recipient rejected"

Presumably the email address is User@domain.co.uk where the user is one of the users on the pi and the password is the password used to sign in to the pi with. So the default username and password out of the box would be pi and raspberry?

Hmm... What you just described doesn't sound like an IMAP problem, it sounds like you may have misconfigured Postfix. Postfix is used when you send & receive emails; Dovecot is used to fetch emails that are already in the mailbox on your server. So, when you say you get the error when you send an email to your server do you mean from an external email account like gmail to you@yourdomain.com, or do you mean sending an email through your server i.e. from you@yourdomain.com to an external email address such as a gmail account? Your last paragraph about the email address and password is correct... but if you still have the default user pi and and password raspberry please change the password!! Sam

Ha! Yeah, the first thing I did was change the default username and password!

So, I have successfully sent an email out through the server to an external email (gmail) but not externally to my domain. So somewhere in the Postfix setup I have gone a bit wrong?

Check /etc/postfix/main.cf and look for a line like this:
mydestination = samhobbs.co.uk, samhobbs, localhost.localdomain, localhost
Make sure your domain name is in there. Looks like your mail server doesn't think it is the destination for the email that is being sent to it. Sam

Yep, that looks good. Is your mail client apple mail by any chance? Before "the crash" when I was using WordPress on this site, I was chatting to someone who was having problems getting Apple Mail to connect, I'm not sure we ever cracked why it was behaving strangely though. He actually made me an account on his server so I could test it from here... all of my clients worked but his didn't! If you don't mind, I will try to send a couple of emails to you from here to see what kind of response I get... what's your username at prophetsandbeards? Joshua? Sam

Sam Hobbs

Thu, 05/08/2014 - 21:59

sam@samhobbs:/etc/postfix$ telnet prophetsandbeards.co.uk 25
Trying 84.92.55.180...
Connected to prophetsandbeards.co.uk.
Escape character is '^]'.
220 prophetsandbeards.co.uk ESMTP Postfix (Debian/GNU)
ehlo samhobbs.co.uk
250-prophetsandbeards.co.uk
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
mail from: sam@samhobbs.co.uk
250 2.1.0 Ok
rcpt to: joshua@prophetsandbeards.co.uk
250 2.1.5 Ok
data
354 End data with <CR><LF>.<CR><LF>
Subject: test email from Sam Hobbs
This is a test email
.
250 2.0.0 Ok: queued as 322D0216EE
Have a look in your inbox and see if it's in there?
ll ~/Maildir/new
ll ~/Maildir/cur
Sam

OK so I tried sending to you from an email client and the email bounced.
host smtp.secureserver.net[72.167.238.29]
    said: 550 5.1.1 <joshua@prophetsandbeards.co.uk> recipient rejected (in
    reply to RCPT TO command
Where I had been going wrong troubleshooting this is I forgot that when you connect with Telnet your computer does a normal DNS lookup to decide which IP address to connect to, using an A record. When you use a mail client to connect it looks for the MX record (not the A record) to decide the domain name of the mail server it needs to connect to to connect to to, and then does a DNS A lookup for that domain name to find your IP address. So, you have a DNS A record set up properly (pointing to your IP address) but your MX record isn't configured properly - it's pointing to a different domain name (kicking myself - you told me earlier you didn't know what an MX record was! ). However, it is pointing at a mail server of some kind, I suspect your DNS registrar's SMTP server? Here's how I looked it up, using the dig command. This one shows the A record, which maps your domain name to your IP address:
sam@samhobbs:~/Maildir$ dig prophetsandbeards.co.uk

; <<>> DiG 9.9.5-3-Ubuntu <<>> prophetsandbeards.co.uk
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 15518
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;prophetsandbeards.co.uk.       IN      A

;; ANSWER SECTION:
prophetsandbeards.co.uk. 600    IN      A       84.92.55.180

;; AUTHORITY SECTION:
prophetsandbeards.co.uk. 3600   IN      NS      ns24.domaincontrol.com.
prophetsandbeards.co.uk. 3600   IN      NS      ns23.domaincontrol.com.

;; Query time: 36 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: Thu May 08 22:12:00 BST 2014
;; MSG SIZE  rcvd: 123
...and this one shows the MX record (the one used by mail clients):
sam@samhobbs:~/Maildir$ dig prophetsandbeards.co.uk mx

; <<>> DiG 9.9.5-3-Ubuntu <<>> prophetsandbeards.co.uk mx
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 25470
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;prophetsandbeards.co.uk.       IN      MX

;; ANSWER SECTION:
prophetsandbeards.co.uk. 3433   IN      MX      0 smtp.secureserver.net.
prophetsandbeards.co.uk. 3433   IN      MX      10 mailstore1.secureserver.net.

;; Query time: 22 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: Thu May 08 22:05:10 BST 2014
;; MSG SIZE  rcvd: 116
I suspect your DNS registrar offers some kind of email forwarding for webmaster@yourdomain.com and similar addresses or something like that? Who is your DNS registrar (is it domaincontrol.com)? You should be able to configure an MX record when you log in to your account. I'm with namecheap, was pretty easy with them. Sam

Can I just clarify something? In my MX record I am supposed to change them to prophetsandbeards.co.uk ?

Having done this, I can now send an email to joshua@prophetsandbeards.co.uk which seems to send ok. I can't get Mail or thunderbird to connect still which is a pain. When I log in using openssl s_client -connect localhost:993 -quiet I can see that there is a message there, but I have no idea how to access it or where it is actually stored.

What is going on now?

Yep that's right... here's my example MX record:
feathers-mcgraw@Hobbs-T440s:~$ dig samhobbs.co.uk mx

; <<>> DiG 9.9.5-3-Ubuntu <<>> samhobbs.co.uk mx
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 24100
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;samhobbs.co.uk.                        IN      MX

;; ANSWER SECTION:
samhobbs.co.uk.         1800    IN      MX      10 samhobbs.co.uk.

;; Query time: 212 msec
;; SERVER: 127.0.1.1#53(127.0.1.1)
;; WHEN: Fri May 09 20:56:41 BST 2014
;; MSG SIZE  rcvd: 59
And here's yours now:
feathers-mcgraw@Hobbs-T440s:~$ dig prophetsandbeards.co.uk mx

; <<>> DiG 9.9.5-3-Ubuntu <<>> prophetsandbeards.co.uk mx
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 50835
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 2, ADDITIONAL: 2

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;prophetsandbeards.co.uk.       IN      MX

;; ANSWER SECTION:
prophetsandbeards.co.uk. 3600   IN      MX      0 prophetsandbeards.co.uk.
prophetsandbeards.co.uk. 3600   IN      MX      10 prophetsandbeards.co.uk.

;; AUTHORITY SECTION:
prophetsandbeards.co.uk. 3600   IN      NS      ns24.domaincontrol.com.
prophetsandbeards.co.uk. 3600   IN      NS      ns23.domaincontrol.com.                                                              
                                                                                                                                     
;; ADDITIONAL SECTION:                                                                                                               
prophetsandbeards.co.uk. 600    IN      A       84.92.55.180                                                                         
                                                                                                                                     
;; Query time: 52 msec                                                                                                               
;; SERVER: 127.0.1.1#53(127.0.1.1)                                                                                                   
;; WHEN: Fri May 09 20:58:14 BST 2014                                                                                                
;; MSG SIZE  rcvd: 155
Seems like your record has a duplicate in it, but that's OK. Big organisations sometimes have more than one email server receiving email and the list is there so that they can try the first and move on down the list if the first is unavailable (under high load, for example). So you can delete one of those if you like, but maybe leave it there for now so we're not changing too many things at once while we're troubleshooting your other problem. I think we should take a look in the logs as you try to log in with your email client. Try this command on the Pi:
tail -f /var/log/mail.log
...which will show the last few lines in your mail log and update it as new entries are written. You should see some entries in there like this:
May  9 21:10:35 samhobbs dovecot: imap-login: Login: user=<sam>, method=PLAIN, rip=192.168.1.1, lip=192.168.1.103, mpid=13993, TLS, session=<ksHBMP34JwDAqAEB>
...but look for errors too. To get out of tail use CTRL C which will stop it listening for new entries and then q to quit. Also, check your mail error log:
tail /var/log/mail.err
Sam

I feel like we are getting close.

So now I can send and receive emails using my raspberry pi server! I can go to Maildir/new and read any messages that are sent to me like that. Horray! I still can't get either Mail or thunderbird to connect though.

In my DNS manager with Godaddy where I changed the MX record there is a list under the heading CNAME (alias), in this list are options to change email, IMAP, SMTP, POP, mail etc. Should I be changing any of these things to match the A record?

after doing a tail on mail.log I got a whole bunch of information which I couldn't really work out. There is a lot of 'disconnected' and 'lost connection' messages but nothing as clean as what you wrote.

May 10 07:13:06 raspberrypi dovecot: imap-login: Disconnected (disconnected before greeting, waited 1 secs): user=<>, rip=84.92.55.180, lip=192.168.1.95, TLS handshaking: Disconnected, session=<4iYacgb5tABUXDe0>

Also there was nothing in mail.err but there was stuff in mail.err.1 so I looked at that and found some errors ...

May 8 11:36:19 raspberrypi dovecot: master: Error: socket() failed: Address family not supported by protocol
May 8 11:36:19 raspberrypi dovecot: master: Error: service(imap-login): listen(::, 143) failed: Address family not supported by protocol
May 8 11:36:19 raspberrypi dovecot: master: Error: socket() failed: Address family not supported by protocol
May 8 11:36:19 raspberrypi dovecot: master: Error: service(imap-login): listen(::, 993) failed: Address family not supported by protocol
May 8 11:36:19 raspberrypi dovecot: master: Fatal: Failed to start listeners

but that was two days ago so maybe this has been fixed now?

Those errors are the ones that should have been sorted at the start of tutorial 2. Restart Dovecot and Postfix and see if you get any errors appearing in /var/log/mail.err, they may be old errors like you said.
In my DNS manager with Godaddy where I changed the MX record there is a list under the heading CNAME (alias), in this list are options to change email, IMAP, SMTP, POP, mail etc. Should I be changing any of these things to match the A record?
Not sure to be honest, mine was really simple - just the one place for all of it. Probably worth a try! Sam

Have we hit the end of the road?

I don't know what CNAME (alias) is all about, the little question mark was talking about subdomains. Either way there has been no difference after editing them. So now I still don't have any errors in mail.err and some old ones in mail.err.1 (which are probably from when we started this a few days ago), I can send and receive email using telnet and in Maildir/new, but the Mail clients still don't recognise the server as existing.

Any more thoughts?

Can you post some of the output from your mail.log please? I want to see if there's anything funny looking in there. Next step: make yourself a new user and try logging in with that. If that's unsuccessful, you could email me the username/password and I'll try logging in from here. If I'm successful then it must be a quirk of either the software you are using or the fact that you are on your LAN... either way, we'll have learned something! Sam

Michael Massie

Mon, 05/12/2014 - 20:05

Hi, great tutorial, thanks for sharing. I have got stuck at the Telnet 143 stage at part b select inbox. I get an error message stating "NO [SERVERBUG] Internal error occurred. Refer to server log for more information.

Any hints would be appreciated. Where can I find the server log?

Thanks for any help.
Michael.

Hi Michael, You probably want /var/log/mail.err, so try:
tail -f /var/log/mail.err
in one session and try using telnet at the same time, see what pops up. If there's nothing interesting there, try:
tail -f /var/log/mail.log
for more info (not just errors). Sam

Wouter

Thu, 06/05/2014 - 15:17

In reply to by michael

If I might ask, what did you do exactly to fix it? I am getting the same error and when I check the error log file it says that INBOX doesn't exist.
What do I do now?

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.