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

Sam, I have followed your tutorial on Apache2 and setting up an email server. Both have gone well. You can see my Pi hosted page above. The CAcert down load worked including confirmation received at my Pi server so I can receive email OK. However after an initial send, I seem to be encountering errors due to my IP being block listed. I changed my IP [unpowering the router] and the problem persists with new IPs. I wonder what it could be? Can you help?
Thanks,
Des

Hi! Nice site :) Ideally you want a static IP address for an email server, because a lot of dynamic IP ranges get marked as sources of spam on blocklists. So, try and get a static IP address. My ISP, PlusNet, lets you have one for a one-off charge of £5 which is brilliant. You may have less luck with other ISPs (the American ones in particular seem to charge a monthly fee). In the meantime, have you set a SPF record? If not, do that - it should reduce the spaminess score of your outgoing mail. Sam

host mx4.cc.ic.ac.uk[155.198.5.154] said: 550 Sender verify failed (in reply to MAIL FROM command)
Hi Sam, Thanks again for your help. I got a fixed IP which appears on no block lists and then went over to Namecheap to set up the DNS record including MX and SPF. I am still not able to send. However the block list issue has gone but I do receive the message above from one recipient and another reports invalid DNS PTR resouece record. I think I am closer, but not quite there. Can you see where I am going wrong?
Des

According to this, it looks like the recipient server is pretty strict and requires a matching PTR record for your email server before it will accept email. I haven't come across this before, although I knew in practice that it's possible to configure a server like that...most accept a matching PTR or a SPF record. If you want your email to be accepted by that server, you'll have to get your ISP to change your PTR record to match the hostname your server EHLO's with. Sam

Hi Sam thanks a lot for the last comment. It worked perfectly. Plus-net obliged in switching the PTR but it will take 24 hours. Meanwhile after sorting MX and TXT using Name-cheap's dns service I can now send and receive to the servers who rejected earlier. Before doing the next stage I would like to make backup image of the set up so far. I did try this earlier using Win 32 Disk Image but although it reported a successful read when I came to use it it failed to write it. In your prep tutorial I recall you made a back up using Linux and I could do that - for learning purposes I have Ubuntu installed on a second HD. But its still early days for me. So my question is have you covered recovery the image into a new SD card anywhere? If not could you outline the steps -
Thanks in advance
Des

Gotta love PlusNet :) The only place I've covered full disk backups is in my tutorial on how to boot from a flash drive - the dd command is the one you want. It makes a bitcopy, which is not the same thing as just dragging and dropping the files to a new HDD - it preserves all of the information on when files were changed, their permissions etc. Let me know if you need a hand! Sam

I have applied part 1, 2 and 3 to my Rapsberry, it works perfect! Squirrelmail recieves and can send mails. Note that my Raspberry is on a router DMZ port.

I also run another script on my webserver that sends out mails for registration issues. (Webtrees.net)
After PART 1 of this document I tested "webtrees" and it worked perfect (with default Mail configuration).

Note that webtrees comes with the following Mail Configuration options
Message : Use PHP mail to send messages / Use SMTP to send messages
Sender name: webmaster
SMTP mail server
Sever name: localhost
Port number: 25/465
Use password: yes/no
Username:
Password:
Secure connection: none/ssl/tls
Sending server name:

The default setting where "Use PHP mail to send messages", I don't know if the SMTP mail server settings apply to that, but port number was 25 and of course no password and secure settngs are applied.

After continue PART 2 and 3 successfully, tested Squirrelmail successfully I noticed that my webtrees registration doesn't send out any mails anymore. I changed the Mail configuration settings time after time to test...but I can't figure out what are the right one, as nothing that I have filled in seems to work till so far. And I know it can work, as Squirrelmail send out all mail without any problem to my Gmail.

Thanks a lot in advance, and thanks for putting those great descriptions online, they are both useful and educative.

Sam,
Could I ask your advice on this? I am now looking at ways to use the sites
more effectively.

I use Dreamweaver to maintain my own and a couple of sites on a volunteer
basis [friends and local charities] and simply ftp up to the sites on the
host servers. It makes the managing of links within the site simple.

I think it would be unsafe to try to do this to http sites? would you agree
But I think it should be safe to ftp to sites on the Pi using the local
network - just as with filezilla [no port forwarding on 21]. Would you
agree?

At present filezilla can only FTP to my user directory on the Pi [I do not
have permission anywhere else] and sudo cp to /var/www/ from there. This
would mean I cannot use Dreamweaver to directly manage the site's
directory root. You mentioned earlier that you use ftp to manage your
sites and I wondered how you do it. Do you do it similar to the above or
is it possible to manage the site at the directory root directly.

Thanks in advance,
Des

The two sites that I run on this server both use content management systems - this site uses Drupal and the other is Wordpress. I don't use FTP directly, the CMS makes changes to the files on the system via FTP, and I never actually use an FTP client.
I think it would be unsafe to try to do this to http sites? would you agree
I take it you're talking about sending passwords in plain text? I think you're mixing up the method used to serve the content in a browser (http or https) and the method you're using to modify files (ftp or ftps). They are totally different, and whether or not the site is https doesn't affect your FTP connection (e.g. you could change the files for an http only site using an FTP client that connects using ftps, which would not send any passwords in plain text). Why don't you change the website files to be owned by your user? Apache just needs to be able to read the files it's serving, it doesn't necessarily need to own them. More about that in the tutorial I linked above! Sam

Thanks Sam that worked a treat. I usually use the FTP function in Dreamweaver to upload to sites but cannot get it to work on the Pi - still not sure why.
However changing ownership of /var/www/domain to user as you suggested made it simple using a separate FTP once the site was built. I looked at Drupal and was very impressed. I may switch when I have bit more time. Wordpress too looks excellent. I am familiar with Bridge & Dreamweaver for photo galleries but it would be good to use open source for these in the long term.
Thanks again,
Des

Justin Wingate

Wed, 05/06/2015 - 18:55

Hi Sam,

I've really enjoyed your tutorials, and have used them to setup my Pi as an Owncloud server, which is working flawlessly with one exception, which lead me to this tutorial...I wanted to be able to send out email notifications through Owncloud, and apparently I needed to configure an email server on my Pi to do this. Now I'm here! But I have a problem after completing the steps up through the Dovecot configuration...

The issue is I am able to email my pi@wingpi.noip.me email address from my gmail account, and have even had success receiving that email and viewing it using Thunderbird in both Windows and my Chromebook using Ubuntu and K9 on Android. However, when I try and send out emails FROM my pi@wingpi.noip.me address they don't end up in my gmail inbox, or spam, or anywhere. When testing using telnet as per your tutorial I got no error at all, and I'm not sure where to go from here. I've checked the canyouseeme site you referenced, and it does not appear that my ports are being blocked (as evidenced by my being able to receive emails on my server), so I need some help. It might boil down to that MX or SPF deal, and I've just upgraded my noip account to allow me to make changes to those things, but I'm pretty lost. You're the man, Sam, now please...BE MY HERO!!!

Kind Regards,
Justin

May 7 09:53:24 wingpi postfix/smtp[7988]: D8E82821CE: to=, relay=127.0.0.1[127.0.0.1]:11125, delay=0.76, delays=0.22/0.02/0.45/0.08, dsn=5.7.1, status=bounced (host 127.0.0.1[127.0.0.1] said: 530 5.7.1 Authentication required (in reply to MAIL FROM command))

Looks like your pi is rejecting email from itself... do you have permit_mynetworks at the top of your restriction lists, and does your mynetworks statement include the loopback address? Sam

permit_mynetworks was not at the top of the restrictions list, so I just moved that so that it now at the top. Here's what things look like now:

smtpd_recipient_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_unauth_destination
smtpd_helo_required = yes
smtpd_helo_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_invalid_helo_hostname,
reject_non_fqdn_helo_hostname,
reject_unknown_helo_hostname
check_helo_access hash:/etc/postfix/helo_access
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
smtpd_tls_auth_only = yes

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

myhostname = wingpi.noip.me
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = wingpi.noip.me, wingpi, localhost.localdomain, localhost

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = ipv4
home_mailbox = Maildir/
mailbox_command =

Interestingly enough as soon as I moved mynetworks to the top of the restrictions list, I got all the "undelivered Mail Returned to Sender" for all the emails I've tried sending over the last 2 days. Does that ring any bells? I'm totally at a loss for what might be getting in the way.

Again, check your mail log when sending. You might be getting an actual rejection from gmail now (I see you're using no IP, I wouldn't be surprised if you got rejected because your IP is in a dynamic pool or something like that). Sam

It still says the same thing...

May 7 16:37:29 wingpi postfix/smtp[11339]: 31CC381FB7: to=, relay=127.0.0.1[127.0.0.1]:11125, delay=0.66, delays=0.16/0.02/0.41/0.07, dsn=5.7.1, status=bounced (host 127.0.0.1[127.0.0.1] said: 530 5.7.1 Authentication required (in reply to MAIL FROM command))

Okay, good news. After not having success originally, I had tried a workaroundusing using stunnel that I read about the night before last, which required me to add a couple of lines to the TLS parameters. I just commented out those lines, and now my emails are getting through, although they are going into Spam. I'm okay with that. At least they are not bouncing back or just "vanishing" like they were before.

hello,
I finished installed everything up to squirrelmail.
Dovecot and Postfix up and running with no warnings. Squirrelmail also is logging in into testmail account with no problem.

I arrived at part 2 just before testing IMAP with no problems. The thing is if I connect with telnet to 25 it is all fine but when I try 465 the server answer a 'connection closed by foreign host'. What should I check?

I've to add i using my ISP smtp as relay and it is configured correctly as port 465.
Squirrelmail for example still needs localhost:465 (postfix) as SMTP server in configuration part3? I imagine that postfix is then relaying mail to my ISP server.

Thanks!
marco

Use openssl s_client for port 465, because it's TLS only (you can't use telnet). Yep, if you've configured everything correctly then postfix should forward outgoing mail through your ISP's SMTP relay. Sam

Hi sam.
I just tested it again. I can say IMAP is working and i received emails from gmail correctly.
I've to change settings again in squirrelmail for SMTP to localhost:25 no auth and no tls to get it working with no errors (at least in squirrelmail). Anyway it seems I can't send out nothing. My gmail test account hasn't received anything from my mail server

When I try this:
openssl s_client -connect localhost:465 -quiet

i get back:
write:errno=104

The configtest on squirrel gives me no error:
Checking outgoing mail service....
SMTP server OK (220 xxxx.ddns.net ESMTP Postfix (Debian/GNU))

My ISP SMTP is configured in main.cf and sasl_passwd.

BTW This tutorial rules with no other competitors on internet. thank you.

You're welcome :) The difference between the squirrelmail configtest and your openssl test on port 465 is because squirrelmail is testing port 25, and of course openssl is testing port 465. You should be able to configure squirrelmail to use port 465, we just need to find out what is messing up port 465. Can you check your /var/log/mail.err for useful errors? Sam

Sam,
nothing related to smtp on mail.err but on log I have these 2 warnings:

No server certs available. TLS won't be enabled.

Wrapper mode request dropped from localhost for service smtps. TLS context initialization failed.

Sam Hobbs

Sun, 05/10/2015 - 20:25

In reply to by marco

Looks like your TLS certs/key files are messed up or missing. In /etc/postfix/main.cf, do you have:
smtpd_tls_key_file=/etc/ssl/private/yourkey.key
smtpd_tls_cert_file=/etc/ssl/certs/yourcert.crt
? Sam

I've added the crt and key file generated on cacert site (following your instructions(
now when i connect with
openssl s_client -connect localhost:465 -quiet

i get

verify error:num=20:unable to get local issuer certificate
verify error:num=27:certificate not trusted
verify error:num=21:unable to verify the first certificate
verify return:1

when i try to send mail with squirrelmail (smtp set to localhost:465) i get an error...server replied with etc.

marco

hi,
yes I found the same option using google. It's all ok but still I can't send emails for some reason. I gotta look into the mail.log file.

Sorry for the cryptic message, actually squirrelmail responded with an empty string like this "ERROR: server replied with" and nothing else.
My ISP SMTP works with authentication on 587 with my email login (the one the ISP gave me). What configuration you suggest under the SMTP server configuration in squirrelmail. Right now I have localhost:465, I have put the mailbox login/password (example testmail user) and TLS enabled. Is this ok?

thank you
m

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.