Recipe 8.14 Securing POP/IMAP with stunnel and SSL

8.14.1 Problem

You want to read mail on a POP or IMAP mail server securely. Your mail client supports SSL, but the mail server does not.

8.14.2 Solution

Use stunnel, installed on the mail server machine. Suppose your client host is myclient, the mail server host is mailhost, and the mail server listens on standard port numbers (110 for POP, 143 for IMAP).

  1. Generate a self-signed X.509 certificate foo.crt, with private key in foo.key. [Recipe 4.8]

  2. Place the certificate and key into a single file:

    $ cat foo.crt foo.key > foo.pem
    $ chmod 600 foo.pem
  3. Choose an arbitrary, unused TCP port number on mailhost, such as 12345.

  4. Run this stunnel process on mailhost for a POP server, supplying the certificate's private-key passphrase when prompted:

    mailhost$ /usr/sbin/stunnel -p foo.pem -d 12345 -r localhost:110 -P none -f
    2003.03.27 15:07:08 LOG5[621:8192]: Using 'localhost.110' as tcpwrapper service name
    Enter PEM pass phrase: ********
    2003.03.27 15:07:10 LOG5[621:8192]: stunnel 3.22 on i386-redhat-linux-gnu 
    PTHREAD+LIBWRAP with OpenSSL 0.9.6b [engine] 9 Jul 2001
    2003.03.27 15:07:10 LOG5[621:8192]: FD_SETSIZE=1024, file ulimit=1024->500 
    clients allowed

    For an IMAP server, use port 143 instead of 110.

  5. Add foo.crt to the client's list of trusted certificates, in whatever way is appropriate for the client software and OS. You may need to convert the certificate format from PEM to DER: [Recipe 4.10]

    $ openssl x509 -in foo.crt -out foo.der -outform der
  6. Configure your mail client on myclient to connect to port 12345 of mailhost using SSL.

8.14.3 Discussion

This recipe assumes you are not a system administrator on mailhost, and need to get this working just for yourself. If you have root privileges, just configure your mail server to support SSL directly.

We create two secure connections to mailhost's port 12345. The stunnel command connects this arbitrary port to the mail server, all locally on mailhost. Then the mail client crosses the network via SSL to connect to port 12345. These two segments together form a complete, secure connection between mail client and mail server.

If you remove the -f option, stunnel will fork into the background and log messages to syslog, instead of remaining on the terminal and printing status messages to stderr.

8.14.4 See Also

The directory /usr/share/doc/stunnel-* contains stunnel documentation. The stunnel home page is http://www.stunnel.org.



    Chapter 9. Testing and Monitoring