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

Yes, dovecot is running. Ports enabled in router, and I set dovecot like you wrote. I didn't installed email client yet.
Error is the same.

Sasha Valeria

Wed, 08/28/2019 - 05:20

First off, thank you for making this, and thank you for keeping it up all these years! nearly 40 pages of comments makes it hard to sift through for problems similar to my own, though.

So, i'm pretty sure i set everything up correctly. Fixed the few errors that were popping up because i accidentally added a space to one of the "-o smt [blagh]" things in master.cf.
Thunderbird connects, and i can even click "send" on an email and thunderbird *says* it's been sent.
But nothing's going out. And anything i try to send from gmail doesn't get in either.

all the ports are forwarded correctly, all that stuff works as far as i can tell, but this part doesn't.

Have you tried any other email clients? Thunderbird has become a bit temperamental since Mozilla stopped actively developing it. If you've done that, try watching the logs as you send an email and see what happens (do you see a connection from the client?). If not, it could be a firewall thing (e.g. port forwarding), a DNS issue or a misconfiguration (is postfix running?). Sam

Thanks for this Sam, bet you're glad you wrote it so long ago and here is hoping you are still answering queries.

I have followed the guide from the start and am at the section for;
Now try openssl:

openssl s_client -connect localhost:465 -quiet

I get
Can't use SSL_get_servername
depth=0 CN = email-pi
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = email-pi
verify return:1
220 itsnotsecure.com ESMTP Postfix (Raspbian)

email-pi is my hostname, not my email name. I have checked the postfix/main.cf and postfix/master.cf and cannot see the error. Any clues / thoughts?

Many thanks,
Chris

Sam Hobbs

Wed, 09/04/2019 - 14:05

Chris, The common name is on the certificate, which at the moment should be the default cert automatically generated during the installation of postfix (which uses your hostname as the common name). You can replace the certificate with a new one with your domain name on it. Nowadays I'd recommend LetsEncrypt - it's free and there are great tutorials for certbot, the software that generates the certificate and gets it signed (see here). Sam

Tony Baynes

Sun, 09/15/2019 - 14:06

Hi Sam. Many thanks for the massive effort you are putting into your tutorials. I'm a Noob, trying very hard to follow your tutorials to the letter. I'm trying to set up SSL in your "Raspberry Pi Email Server Part 2: Dovecot" tutorial. Everything was working perfectly up to now, but I've suddenly hit a brick wall with the "Can't use SSL_get_servername" error.

pi@raspberrypi:/etc/postfix $ sudo nano /etc/postfix/master.cf
pi@raspberrypi:/etc/postfix $ sudo service postfix restart
pi@raspberrypi:/etc/postfix $ telnet localhost 465
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
exit
Connection closed by foreign host.
pi@raspberrypi:/etc/postfix $ openssl s_client -connect localhost:465 -quiet
Can't use SSL_get_servername
depth=0 CN = raspberrypi
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = raspberrypi
verify return:1
220 senyab.com ESMTP Postfix (Raspbian)
quit
221 2.0.0 Bye

I've been back through the changes to the various configuration files, but have not picked up any errors. There is one difference that I noticed, between your tutorial and the /etc/postfix/master.cf file, in a line which had to be un-commented, which might not have anything to do with this error, but I thought it worth pointing out....
The tutorial:
smtps inet n - - - - smtpd

From the master.cf file:
smtps inet n - y - - smtpd

The "y" is under the column "chroot (no)".

I'm going to start with a clean slate (again) and try and get past this, but thought is worth bouncing off you first, just in case it's something that can be fixed easily?

Morning, Thanks for the well structured question! I think the "Can't use SSL_get_servername" message is not an error (just information), the error reported by openssl s_client is that your certificate is self-signed (which is true, and what we're expecting as you are using the default certificate that was automatically generated when you installed postfix). Later on you can replace the default certificate with a free signed cert from LetsEncrypt. The certbot site has customised instructions for installation (for example, apache on debian buster for your setup if you're using raspbian buster). Sam

When I run this command: openssl s_client -connect localhost:465 -quiet,

I run into an error message: 3069558800:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../ssl/record/ssl3_record.c:332:

Online posts appear to indicate I need to install ssl, though I'm not sure this is the right step to take. Any thoughts on what I can do? I have followed your directions verbatim, so it shouldn't be an issue of missing something in the steps. Otherwise, should I re-install under the /etc/postfix/sasl directory? Or, should I generate a csr file then place it in that directory as recommended by another forum?

Thanks for your assistance with this issue.

As so many others before me: Thanks for a great tutorial!
Can I ask for advice on the second part where we are testing auth with telnet?
When I do the "ehlo facebook.com" I get the same "250"-list, but I am missing the "250-AUTH PLAIN LOGIN" between "STARTTLS" and "ENHANCEDSTATUSCODES".
I have tripple checked the instructions, but am obviously missing something. Do you think you can point me in the right direction?

Regards,
Kristian

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

Sam, this is brilliant! Followed it closely to the letter so far and I've been able to set up everything. Well, almost.

I'm having a problem while logging in from outside. Up until setting up Thunderbird -- no issues. When I'm trying to setup server I cannot connect via 993. If I connect via 143 everything runs perfectly fine, but I'd prefer to have the email secure. Any chance you could help? I've no idea which info to paste save for the fact that I'm using snakeoil (about which Thunderbird warned me about, but I knew that so I was expecting it), and the port is forwarded to Pi. Even tried DMZ on it, still nothing.

Hi Sam, please disregard the comment about not being able to log in through 993. My config was wrong, I simply ran through the tutorial too fast. As of publishing the comment all works smoothly with current packages on latest Raspbian.

Now my website runs smoothly and has email capability, both outgoing and incoming. Thank you for the tutorial that actually explains how do you go about setting it up. It is informative and newbie friendly, unlike others that just dump configs at you and you get frustrated. Now I need PTR since my emails get bounced back or flat out don't get delivered or go to spam.

One think though, do you know of a tutorial on encrypting mail and DMARC? Google mail policy says I need those so I won't get flagged as spam-sender and I see a red crossed out lock next to emails sent to gmail saying it's not encrypted. I really want that self-hosted independent email :)

Good afternoon Sam,

First thank you for the great work you have done with this tutorial.

I have followed everything to the letter and after a week with more than one headache, I have managed to mount it to send and receive mail perfectly, but I have a problem, I can only configure the mail clients by putting the local ip address raspberry, if I put my domain name they are not able to configure correctly, it is as if they could not resolve the mail server name, which I do not understand because I receive and send external mails with those same clients when I am in my local network and I configure as a server the ip that raspberry has on my lan network.

What could be the problem?

I'm sorry for my English but I'm not very used to express myself in writing.

Thanks and best regards.

Hi David, If you try with a mobile device on an external network (3G or something like that) are you able to connect? Some routers have a problem doing something called hairpin NAT, which might be the problem if it works from external networks but not from within your own network. Testing with a mobile device should help identify the problem. Sam

Hi again Sam,

I am sorry that it took so long to respond, but I have been quite upset lately, I know what you mean, if I have tried to configure it from 3G networks but I cannot connect through the domain url. I have redirected my domain with cloudflare to the dynamic ip of my raspberry pi, it works perfectly as a web server and a cloud that I have mounted, but I cannot get mail to be configured when I am out of my network pointing to the domain name.

I think the problem is in cloudflare that assigns a name that it generates to the mx registry, the truth is that I don't know how to solve the problem anymore, to see if you can give me any indication to solve it.

Sorry for my english, it's real bad.

Greetings and thank you

I'll be honest, I've forgotten what it is I'm trying to achieve with all this, but now that I'm (hopefully) halfway through it seems like a bad move to stop now. I've reached the part about testing the SASL, but when I telnet it connects, and then is promptly "closed by foreign host".

I'm 100% stumbling through all this after only starting on Tuesday so I have absolutely no clue what the issue is, nor where to start looking. I've gone back through as many of the steps as I can track, but everything *appears* to be as it should by this point. If I can provide any additional info to aid this please let me know how/what to get you and I'm more than happy to.

2020-Feb-08.
In part 1, all worked well, telnet works and the email is received.
Then in part2: https://samhobbs.co.uk/2013/12/raspberry-pi-email-server-part-2-dovecot

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:
After I add:

smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes

and restart the services, telnet no longer works! Using NOOBS 3.3

What is going wrong?
This is what I get:

telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
ehlo xxx.com
Connection closed by foreign host.

So I can connect perfectly with the openssl command, and I can send out emails with that without an issue, I'm seeing my cert etc. working, but I cannot connect with a client. It shows me my cert, I click to trust it, but it then says "cannot connect using ssl"

What have I done wrong? Am I blocking some kind of traffic?

Using the mail app on iPhone btw.

James King

Thu, 04/30/2020 - 20:38

Hi,

Is this guide still valid? I have followed it and managed to send an email on page 1 with no problems. I am now on the section entitled:

Instruct Postfix to use Dovecot SASL

I have followed all instructions, everything seems to have gone fine, but I am stuck, as when I go into telnet to try and see if SASL authentication is working OK, I get no response from the ehlo command.

In fact, the first time I telnet, it closes very quickly, then I do it again and it stays open, but typing ehlo facebook.com gives no response, and it eventually times out.

If I comment out "smtpd_sasl_auth_enable = yes" then everything works again, but obviously I am aware that sasl auth is not enabled in that case.

I was wondering if you knew if the instructions might have changed at all?

Thank you.
James

Same issue and also works if i comment out: smtpd_sasl_auth_enable = yes
Logfile shows:
Mar 13 09:51:41 mando postfix/smtpd[1466]: connect from localhost[127.0.0.1]
Mar 13 09:51:41 mando postfix/smtpd[1466]: warning: SASL: Connect to private/auth failed: No such file or directory
Mar 13 09:51:41 mando postfix/smtpd[1466]: fatal: no SASL authentication mechanisms
Mar 13 09:51:42 mando postfix/master[1459]: warning: process /usr/lib/postfix/sbin/smtpd pid 1466 exit status 1
Mar 13 09:51:42 mando postfix/master[1459]: warning: /usr/lib/postfix/sbin/smtpd: bad command startup -- throttling

There is a little "GOTCHA" when editing /etc/postfix/main.cf that makes telnet stop working.
In the tutorial part 1, Helo access restrictions we add the following;

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

In the next section it says to add one more line to the end of the restrictions list;

check_helo_access hash:/etc/postfix/helo_access

what it doesn't tell you to do is to also add the comma to the line prior although it is illustrated.

smtpd_helo_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_invalid_helo_hostname,
reject_non_fqdn_helo_hostname,
reject_unknown_helo_hostname <------------------------ must add extra comma!!!!
check_helo_access hash:/etc/postfix/helo_access

Sebastian

Wed, 05/20/2020 - 10:02

after setting up AUTH PLAIN, the place where you do ehlo facebook.com, I can't telnet into localhost 25 anymore. I looked in systemctl and for some reason dovecot says ACTIVE/SUB failed. i've tried to revert and change the config files but i don't seem to be able to get it working again. there does appear to be a difference between the dovecot config file in current repository and the one you used for the guide; update, i presume. would that be the cause? is your guide too outdated for RPi4?

Okay, I've been trying to follow this guide for over a week now. Googling all my issues, when things don't work and so on. and, ever since i came to the openssl bit nothing really works anymore. It just keeps telling me it's not the correct hostname and i asked about it and was told it is because i'm using localhost. but, if it's supposed to be a non-issue i should be able to use thunderbird at this point; which I can't. I have already setup one of my domains for google through the same host so I know the MX records and DNS is done correctly, but the openssl errors etc is where i suspect the issue lies. there was a lot of things that were simply no longer correct in the guide for the current versions of software (especially dovecot).

sebastian

Sat, 06/06/2020 - 01:18

Hi Sam
i hope You can help me
when i run tihis command
"openssl s_client -connect localhost:465 -quiet -CApath /etc/ssl/certs"
i get this "verify error:num=18:self signed certificate"
and i lost
br
Sebastian

Followed the guide to the letter up to this point:

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

All I get is "Can't use SSL_get_servername"

The next line confirms its using the self signed certificate & lists the node name and not the hostname defined in main.cf

depth=0 CN = NODENAME
verify error:num=18:self signed certificate

What could I be doing wrong? Is there another config file that holds this info?

HI

I am going though this to setup my Pi as a mail server

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

Everytime i set this in /etc/postfix/master.cf It applys but when i go to something like

Telnet localhost 25 it does not want to connect

pi@raspberrypi:~ $ telnet localhost 25
Trying ::1...
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused

Same with Telnet localhost 465

Now i have restarted the service but same issue

what am i doing wrong

Thanks

Rainbow Asteroids

Fri, 07/17/2020 - 01:04

There seems to be an issue with my certificate. Whenever I attempt to send an email w/ thunderbird, it gets angry at me telling me that my cert is self-signed. I pointed Dovecot to my cert signed by Let's Encrypt and doing openssl s_client -connect domain.com:993 -quiet proves this, however when I swap the port to 465, openssl tells me that my cert is self-signed.

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.