Raspberry Pi Email Server Part 2: Dovecot

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

Type: 

Comments

It seems like I'm on 3 blacklists: Protected Sky, SORBS DUHL and Spamhaus ZEN which I find quite odd since I have never sent email to anybody except for two Gmail accounts. I've also never hosted any copyrighted content, phising, scams or viruses nor have I ddossed or otherwise attacheed anyone

It might be from when someone else had that static IP - see if you can get a different one from your ISP.

Also worth checking your mail logs to verify nothing fishy is going on.

Sam

Greetings, and thank you for this most excellent tutorial. You'll forget more of this that I will ever know.

My configuration is a Pi with ports (22 25 115 143 220 465 585 993 8080) forwarded to it from my router. I use ATT (Yahoo) as my upstream agent. Using Thunderbird on another machine in my private network, I am able to send email to between my Pi and ATT email. I can (on the Pi) connect using 'telnet localhost 143' however I an unable to connect to 465 using ssl...

openssl s_client -connect localhost:465 -quiet
connect: Connection refused
connect:errno=111

'systemctl status ...' shows postfix and dovecot started (as does ps).


nmap -sS localhost

Starting Nmap 6.47 ( http://nmap.org ) at 2016-09-21 08:18 CDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00040s latency).
rDNS record for 127.0.0.1: rpi0
Not shown: 993 closed ports
PORT STATE SERVICE
22/tcp open ssh
25/tcp open smtp
80/tcp open http
111/tcp open rpcbind
143/tcp open imap
2049/tcp open nfs
3306/tcp open mysql

The head of my master.cf is...

[comment snip]
# ==========================================================================
smtp inet n - - - - smtpd
-o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
#smtp inet n - - - 1 postscreen
[snip]

I thank you again for this tutorial and really commend you on your support for those following it. Have you any ideas for me?

-- John Navratil

Hi John,

The first line of the snippet you posted from master.cf should start with smtps, not smtp:

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

Change that, reload postfix and let me know if you can't connect on port 465 afterwards!

Sam

Sorry for the late reply and thanks for the correction. That was it!

Off topic, and apropos of nothing, this is why programmers are cautioned against the use of too similar variable names, particularly at the end of the name (smpt/smpts, dhcpd/dhcpcd, e.g.)

Wouldn't smtp/smtpS or dhcpd/dhcpCd, as bad as those petty distinctions are, be more clear - especially to the non-expert? Oh, well!

I'm at the testing phase for Dovecot. When I try to telnet localhost 25 I get the following:
telnet localhost 25
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
pi@raspberrypi:/etc/dovecot/conf.d $
nay ideas why this might be happening?

Do you mean testing SASL? When you connect on port 25 you are connecting to postfix, although postfix uses Dovecot SASL for authentication!

Is postfix running?

sudo service postfix status

You might find you get some useful errors in the mail log when you connect; if you open two separate SSH connections and run this command in one window:

tail -f /var/log/mail.log

it will show you the last few lines of the log and follow it as new entries are written (CTRL+C to exit when you're done). In the other window, connect with telnet and see what appears in the log.

Sam

Hi Sam

Excellent tutorial well detailed but I've become rather stuck at the end connecting to the mail server using K9, it just states unable to connect after entering all the details. I've tried using putty from windows 7 and I can confirm I can connect on port 22 but I am unable to connect on port 993 (I normally use RDP). The port forwarding on the router is definitely configured correctly and pointing at the pi. I was unable to complete the certificate section as I think I was missing something. the mkcert.sh file was not in the directory that was in the tutorial so I wrote one manually from what you'd put on the page this came up with <./mkcert.sh command not found> after some tweaking I got it to attempt to run but came up with </etc/dovecot/dovecot.pem already exists cannot overwrite.

Not sure if that is related but will probably be something I have to re-look at later. Hope you can help and great job on a complex tutorial exceptionally well written.

Hi,

Hopefully that won't be the reason why you're having problems - the mkcert part wasn't in the tutorial originally, I had to add it because of a packaging error in Dovecot some people reported to me. Basically dovecot wasn't creating a default certificate during installation. I think that has been fixed now though - if a cert exists at the location pointed to in the default config file, dovecot should start up ok and you should be able to connect, but you might get a certificate error in the client that you can dismiss temporarily.

Anyway, two things to check: is dovecot running, and do you get any errors in the mail log when you try to connect with openssl s_client? I'm thinking it's probably going to be a DNS problem if you did all the tests without error the first time round and you're sure your port forwards are correct, but it's worth checking this first.

Sam

I think it's bad DNS setup. This is my first venture with webservers / Mail Servers and although I'm proficient with windows / Linux there is a lot of details to keep track of which is why your tutorial was so handy.

I'll correct the things I know are wrong with the DNS setup (being provided by freenom.com) and I'll double check for errors on the openssl s_client when I get home from work.

Thanks Sam

Matt.

My DNS setup was completely wrong lol. Although now I've connected and can send mail from the mail server I get the following when I try to send mail to it.

postmaster@mail.hotmail.com
Reply|
Today, 06:20
matt@atticempire.tk
This is an automatically generated Delivery Status Notification.

THIS IS A WARNING MESSAGE ONLY.

YOU DO NOT NEED TO RESEND YOUR MESSAGE.

Delivery to the following recipients has been delayed.

matt@atticempire.tk

Also all mail is going into junk currently so attempting to decipher SPF and PTR records at the moment to try to stop this but the not sending is a bigger problem currently LOL.

Thanks for your help.

Matt.

If you watch your mail logs and attempt to send an email to the server from a freemail provider, what happens? Hotmail is saying that the delivery is delayed, but not why. I'm wondering if their server made a successful connection and there's a config problem on your server, or if they couldn't find an MX record and therefore delayed delivery or something.

Sam

Hi Sam

Not sure how to view the log in hotmail. But a few days later I got this email back.

Undeliverable: testing
P
postmaster@mail.hotmail.com
Reply|
Fri 30/09, 18:21
matt@atticempire.tk
To send this message again, click here.
This is an automatically generated Delivery Status Notification.

Unable to deliver message to the following recipients, due to being unable to connect successfully to the destination mail server.

matt@atticempire.tk

I was also getting an immediate failure from my work email address when attempting to send to my pi domain email address. However I am still able to send emails from my pi domain email address to external email addresses.

I've been having a quick look through you DNS Basics tutorial to try to determine what I might be missing and I have to admit I am not getting an Answer section on either DNS A dig command or MX dig command. However I'm not sure if this nugget of information is pointing to the problem or is a symptom of the problem. My ISP only provides static IP's so I haven't had to use dynamic DNS to keep track of the external IP addresses.

Hi,

I received your email showing the DNS setup. I think the problem is your MX record.

I can successfully connect to your server using telnet and your IP address, and fetch the DNS A records for the www and mail subdomains, but I don't get an answer if I request your MX record. Not sure how you should change the inputs in your screenshot to get the result we're after, but the A records are fine so don't change those.

Hope that helps,

Sam

Yes I ran a host command to check my mx record and it bounced back saying no mx record for atticempire.tk not sure if it's worth trying to solve it or move domain service to namecheap? I'll think on it this week.

Hi Sam

Sorry it's been a while! I've been all over the place recently.

I believe I've managed to fix the MX Record issue by switching to a different domain service and moving to atticempire.co.uk instead. when I now run the command;

host atticempire.co.uk

It now returns that it has found an MX record equally when I use the dig command it comes back with an answer section. Unfortunately though I'm still experiencing the same issue where I'm able to send mail but not receive. Also I notice in your previous comment you said you were able to connect to my network on port 25 however for me it wasn't working when I tried to telnet on port 25 from outside the network. Equally the ping command timed out yet everything seems to be working fine. I've checked with my ISP Kingston Communication and they don't block inbound to 25 so I'm stuck yet again.

P.S. I also tried to use tracert to get an understanding of when the packets stopped but it didn't shed much light it stopped around the 6th hop.

telnet localhost 143
Trying ::1...
Connected to localhost.localdomain.
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"
* BYE Internal error occurred. Refer to server log for more information.
Connection closed by foreign host.

Marius,

Refer to the server log for more information ;)

It's at /var/log/mail.log. If I had to guess, I'd say you haven't told Dovecot where your mailbox is and it's trying to read from /var/mail instead of /home/user/Maildir...

Sam

Thank your very much for an excellent description of what to do and why to do it.
I now have Postfix and Dovecot running on my newly acquire Raspberry Pi 3.
The only comment I have is that the command:

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

did not run cleanly until later when I had installed a proper CAcert.

Before I had the certificate I got:
error:num=18:self signed certificate ....

Hi,

The default automatically generated certificate is self signed - the error you are describing is explained in part 2.

Glad you got it working.

Sam

Thanks again for making these guides. I managed previously to have everything working fine - except for my IP being blacklisted unfortunately. That was not an issue as mainly used e-mail address for receiving and sent from another - or let the person know in person to expect first e-mail from me to land in their spam folder.

My sd-card on my pi corrupted so I have had to set everything up again. I managed to have everything working fine using the presspi distro. However, was suffering crashes on it so switched to Raspbian Lite. Annoyingly, fourth time going through the guides I have managed to do something wrong. I can send e-mails and access squirrelmail, but I do not receive any e-mails. Tried sending them from two different accounts, neither of which have received mail undelivered notices as yet. Ran through everything again, and again, to see if could spot what was wrong but it all looks like it matches up with the instructions.

Any idea what sections of my config I should be double-checking to figure out where I have gone wrong?

Cheers,

Abe

Abe,

If you can send emails to yourself using the local telnet test on port 25, start by double checking your DNS and port forwards on your router (make sure you Pi's LAN IP address is static, too).

Sam

Hi Sam,

Think I might have found a clue as to what is wrong but no idea still of how to fix it. Looking in the mail logs I noticed there are error messages when google (when sending from gmail) and my internet provider tried to connect to the mail server.

warning: hash:/etc/postfix/helo_access is unavailable open database /etc/postfix/helo_access.db: No file or directory
warning: hash:/etc/postfix/helo_access: table lookup problem

Checked helo_access and it looks fine, reading helo_access.db just gives a bunch of random characters.

Regards,

Abe

If you run:

sudo postmap /etc/postfix/helo_access

and then restart postfix, does the problem persist? Every time you change the plain text file /etc/postfix/helo_access you need to postmap it to generate/update the database.

Sam

Didn't work but it gave me an idea - deleted the file completely, remade it, postmap, restarted postfix - and everything is working as it should! No idea what it was but there must have been something wrong with the file where it couldn't be accessed - though permissions etc all looked fine. Thanks again for all your help.

Thanks for the incredibly quick reply. I can send myself emails from Squirrelmail and from my phone email app. When trying with telnet I get "invalid name" rejection after "rcpt to:". The DNS records, port forwarding, nor IP assigned to the pi have changed - though double checked them all just in case and they all look fine.

Can you post the full telnet session output, sending from a valid external email address to your account on the pi, no auth step?

Sam

Hi Sam!
Thanks for these giuide! I made it. It seems works correctly, but not. I can send mail in the internal network, but I can't sed to external side. The message is loose. There is a quiet interest thing. I make an account with thunderbird on my workplace and I send a mail to my other e-mail (gmail). It is an external network. My mail is arrived to my pi's sent directory, but didn't arrive to my other e-mail. What is the problem? Can You help me?

Your ISP might be blocking port 25 - if you telnet samhobbs.co.uk 25 from the pi, does the connection time out? If so, that would indicate they are blocking the port.

Sam

Pages

Add new comment