Trifork Blog

Axon Framework, DDD, Microservices

Securing connections with TLS

November 10th, 2009 by
|

In this article I’ll explore some ways to secure socket communication with TLS from a java application. To make it more concrete I’ll show you SubEtha SMTP (an excellent Java based bare bones SMTP server) and the recent TLS extensions I added to it.

What you’ll get from this article:

  • How to mix secure with insecure communication
  • How to start TLS, server side
  • How to make the connection really safe
  • How to add client authentication
  • How to apply this with SubEtha SMTP

I’ll assume you know Java, understand the concept of a socket and the purpose of TLS/SSL.

How to mix TLS with insecure communication

Often protocols need to operate both securely and insecurely. Be it for simplicity or for backward compatibility. The latter reason is important for SMTP as it is traditionally insecure.

There are two options to secure SMTP with TLS. Let discuss them shortly:

  • Option 1: use a separate server port for TLS. The client will connect to a separate port for secure mode and the TLS handshake will begin immediately after the socket is open. This mode is suitable for new protocols that need to be completely secure. This option is not suitable for protocols that also need to operate insecurely like SMTP. (See RFC2595 chapter 7 for more information.)
  • Option 2: use a single server port for both insecure as secure communication. The trick is to start the TLS handshake simultaneously on the client and the server. For telnet based protocols like SMTP, POP3 and IMAP, this is done with the STARTTLS command (RFC2595 and RFC3207).

This article will focus on the server side of option 2, but most of the code is identical to the client side and for option 1.

How to open a TLS connection – Server

TLS is implemented by JSSE which is part of the JDK since J2SDK 1.4. The JSSE Reference Guide is a good source of information, both general as very specific.

To listen on a port (without TLS), the server first needs to create a ServerSocket and then wait for new connections. This can be as simple as:

  int bindPort = 25;
  InetSocketAddress bindAddress = new InetSocketAddress(bindPort);
  ServerSocket serverSocket = new ServerSocket();
  serverSocket.setReuseAddress(true);
  serverSocket.bind(bindAddress);
  while (true) {
    Socket socket = serverSocket.accept();
    // ...start a new thread that will communicate on the socket...
  }

Later, when both parties agree that TLS should be started, a SSLSocket is needed. The SSLSocket will wrap the normal socket that was created by the ServerSocket.

Here is the code. It is very similar to what SubEtha SMTP does (find it in SMTPServer#createSSLSocket).

  // Get the default SSLSocketFactory
  SSLSocketFactory sf = ((SSLSocketFactory) SSLSocketFactory.getDefault());

  // Wrap 'socket' from above in a SSL socket
  InetSocketAddress remoteAddress =
          (InetSocketAddress) socket.getRemoteSocketAddress();
  SSLSocket s = (SSLSocket) (sf.createSocket(
          socket, remoteAddress.getHostName(), socket.getPort(), true));

  // we are a server
  s.setUseClientMode(false);

  // allow all supported protocols and cipher suites
  s.setEnabledProtocols(s.getSupportedProtocols());
  s.setEnabledCipherSuites(s.getSupportedCipherSuites());

  // and go!
  s.startHandshake();

  // continue communication on 'socket'
  socket = s;

When this code has executed, the application can continue communicating on socket as before, only now all data is encrypted prior to being sent over the big bad internet.

You are not done!

The code above mostly works but has some problems:

  • The default SSLSocketFactory is used. Configuring which private key is used is done through the JVM (info). If there is none, an anonymous cipher suite will be selected leading to vulnerability of man-in-the-middle-attacks. You have been warned!
    In addition, you now depend on the list of trusted certificate authorities known to the JVM.
  • Allowing all supported protocols and cipher suites is insecure. SSLv1 and SSLv2 have problems, but worse, some older cipher suites are so badly broken that they hardly offer any protection.
  • It has no exception handling. You will need to catch IOException, but your are better of catching SSLHandshakeException separately as it is common to get the “no cipher suites in common” error (there is no need to log a whole stacktrace for that).

Lets fix the first 2 problems.

Adding key management

To get back some control over the used certificates, you’ll need to create your own SSLSocketFactory in the form of a SSLContext. Here are the steps needed to create a SSLContext:

First you’ll create the key store. The key store contains your own private key and all the certificates that signed that key. The key store is backed by a file and protected by a passphrase.

  // Key store for your own private key and signing certificates
  InputStream keyStoreResource = new FileInputStream("/path/to/keystore.jks");
  char[] keyStorePassphrase = "secret".toCharArray();
  KeyStore ksKeys = KeyStore.getInstance("JKS");
  ksKeys.load(keyStoreResource, keyStorePassphrase);

The file /path/to/keystore.jks is in the default format as created by keytool which is part of the JDK.

A more interesting option is to use a key store in the standardized PKCS#12 format (which is also supported by openssl):

  // Key store for your own private key and signing certificates
  InputStream keyStoreResource = new FileInputStream("/path/to/keystore.p12");
  char[] keyStorePassphrase = "secret".toCharArray();
  KeyStore ksKeys = KeyStore.getInstance("PKCS12");
  ksKeys.load(keyStoreResource, keyStorePassphrase);

As a key store potentially contains many keys, you need a KeyManager to determine which key to use. Under the assumption that there is only 1 key in the key store, the default KeyManager is fine. Of course, there is an extra indirection through a KeyManagerFactory:

  // KeyManager decides which key material to use.
  KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
  kmf.init(ksKeys, keyStorePassphrase);

The second component you need is the trust store. A trust store contains certificates of trusted certificate authorities. These are needed to validate client certificates. You can use the JDK trust store (located at either $JAVA_HOME/lib/security/jssecacerts or $JAVA_HOME/lib/security/cacerts), or you can create one from scratch with keytool.

  // Trust store contains certificates of trusted certificate authorities.
  // Needed for client certificate validation.
  InputStream trustStoreIS = new FileInputStream("/path/to/truststore.certs");
  char[] trustStorePassphrase = "secret".toCharArray();
  KeyStore ksTrust = KeyStore.getInstance("JKS");
  ksTrust.load(trustStoreIS, trustStorePassphrase);

And again a TrustManager (the default one accepts all certificate authorities in the trust store):

  // TrustManager decides which certificate authorities to use.
  TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
  tmf.init(ksTrust);

Finally you can create the SSLContext:

  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

Luckily the code above only needs to run once. Thereafter you can get the SSLSocketFactory as follows.

  // Get your own custum SSLSocketFactory
  SSLSocketFactory sf = sslContext.getSocketFactory();

  // continu as above

Removing dangerous protocols and cipher suites

The second problem the code has is that it allows for broken protocols and cipher suites. To fix this you’ll need to indicate exactly which protocols and cipher suites you want to enable.

Look at the code above and replace the arguments to setEnabledProtocols and setEnabledCipherSuites:

  // select supported protocols and cipher suites
  s.setEnabledProtocols(SslConstants.intersection(
        s.getSupportedProtocols(), StrongSsl.ENABLED_PROTOCOLS));
  s.setEnabledCipherSuites(SslConstants.intersection(
        s.getSupportedCipherSuites(), StrongSsl.ENABLED_CIPHER_SUITES));

StrongTls.java is a class that lists strong protocols and ciphersuites. You can use it under the Apache 2 license. The list was compiled by a security expert at the Dutch government.

Adding client authentication

Most internet applications do not require strict identification of the client. Therefore by default TLS only lets the client check the identify of the server (hence the need for a signed private key on the server). However, for some applications client authentication is just as important.

To indicate this, add the following code just before the start of the handshake:

  // Client must authenticate
  s.setNeedClientAuth(true);

When the client certificate is not signed by a trusted certificate authority, the handshake will fail. After a successful handshake the client certificates can be accessed with:

  // Get client certificates
  Certificate[] peerCertificates = s.getSession().getPeerCertificates();

Securing SubEtha SMTP

Now lets apply all this to SubEtha SMTP. First of all you’ll need to make sure that you have SubEtha SMTP version 3.1.2 or higher. This is the version I extended to optionally require TLS and to allow custom SSLSocket creation.

First create the SSLContext as described above:

  // Key store for your own private key and signing certificates.
  InputStream keyStoreIS = new FileInputStream("/path/to/keystore.p12");
  char[] keyStorePassphrase = "secret".toCharArray();
  KeyStore ksKeys = KeyStore.getInstance("PKCS12");
  ksKeys.load(keyStoreIS, keyStorePassphrase);

  // KeyManager decides which key material to use.
  KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
  kmf.init(ksKeys, keyStorePassphrase);

  // Trust store contains certificates of trusted certificate authorities.
  // We'll need this to do client authentication.
  InputStream trustStoreIS = new FileInputStream("/path/to/truststore.certs");
  char[] trustStorePassphrase = "secret".toCharArray();
  KeyStore ksTrust = KeyStore.getInstance("JKS");
  ksTrust.load(trustStoreIS, trustStorePassphrase);

  // TrustManager decides which certificate authorities to use.
  TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
  tmf.init(ksTrust);

  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

Then create a subclass of SMTPServer and start it:

  // Your message handler factory.
  MessageHandlerFactory mhf = new YourMessageHandlerFactory();

  SMTPServer smtpServer = new SMTPServer(mhf) {
    @Override
    public SSLSocket createSSLSocket(Socket socket) throws IOException {
      InetSocketAddress remoteAddress =
              (InetSocketAddress) socket.getRemoteSocketAddress();

      SSLSocketFactory sf = sslContext.getSocketFactory();
      SSLSocket s = (SSLSocket) (sf.createSocket(
              socket, remoteAddress.getHostName(), socket.getPort(), true));

      // we are a server
      s.setUseClientMode(false);

      // select strong protocols and cipher suites
      s.setEnabledProtocols(StrongSsl.intersection(
            s.getSupportedProtocols(), StrongSsl.ENABLED_PROTOCOLS));
      s.setEnabledCipherSuites(StrongSsl.intersection(
            s.getSupportedCipherSuites(), StrongSsl.ENABLED_CIPHER_SUITES));

      //// Client must authenticate
      // s.setNeedClientAuth(true);

      return s;
    }
  };

  smtpServer.setHostName(host);
  smtpServer.setPort(port);
  smtpServer.setBindAddress(bindAddress);
  smtpServer.setRequireTLS(true);
  smtpServer.start();

That’s it, SubEtha SMTP is now accessible only with TLS. If you also required client authentication, you can get the client certificates from the context parameter in the message handler.

Some further considerations

To prevent “no cipher suites in common” errors, it is wise to install the unlimited security library. Download “Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6” from the Sun Java download site (last item in the list) and install it as described in the readme. This allows for longer keys which can improve security and increases TLS compatibility.

Conclusions

With some minor adjustments to the excellent SubEtha SMTP library, it is possible to have very secure e-mail transmission.

Further reading

5 Responses

  1. March 2, 2010 at 09:30 by Erik van Oosten

    SubEtha SMTP is now also in maven central. Just add the following dependency to your pom:

    <dependency>
    <groupId>org.subethamail</groupId>
    <artifactId>subethasmtp</artifactId>
    <version>3.1.3</version>
    </dependency>

  2. May 24, 2011 at 07:36 by Gabriel

    Hey! nice article.
    Would you please give me some tip about how to create the key and a self signed certificate? I’m trying to do it using keytool but I think I’m not getting it right. I’m pretty new at this.
    Thanks a lot!

  3. September 13, 2011 at 10:32 by Philip Avery

    Hi, this may be a bit tricky, I don’t know java, or understand the concept of a socket or the purpose of TLS/SSL.

    I am running a java daemon on windows XP. It is failing with the error:
    Error creating bean with name ‘subethaServer’

    The daemon I am running was written by a.n.other and runs on Linux. I am trying to get it to work on XP and I think it is a case of something missing from my environment. Probably something to do with subEtha.

    Are there any simple instructions for assembling the necessary components on an XP machine?

  4. January 22, 2013 at 16:22 by SMTP certificate

    […] test subEthaSMTP SMTP server. Everything is OK, but I want use SSL/TLS. I read the article about this and have a […]

  5. October 23, 2013 at 05:01 by Elwood Blues

    The order of the values passed to setEnabledProtocols and setEnabledCipherSuites are important in determining the priority of the protocols and ciphers to use. The logic in your intersection method uses a HashSet to filter the lists, which can cause a change of order of the values in the list, so you lose control of the order.