JavaMail and TLS: Turn on the security switch!

Naturally one would expect that Java’s SSL implementation is secure. However, this is not the case: Special care needs to be taken regarding Man-In-The-Middle attacks: While a certificate may turn out to be valid, you cannot be sure that it has the right origin!

The problem is known for a while and library maintainers are taking steps to avoid it. However, for compatibility reasons those features may need to be turned on.

Check RFC 2595 specifies addition checks that must be performed on the server’s certificate to ensure that the server you connected to is the server you intended to connect to. This reduces the risk of “man in the middle” attacks. For compatibility with earlier releases of JavaMail, these additional checks are disabled by default. We strongly recommend that you enable these checks when using SSL. To enable these checks, set the “mail..ssl.checkserveridentity” property to “true”.

Here is the thing that most examples forget: You need to switch that feature on!

JavaMail Example with enabled origin check

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

finalAuthenticator auth=...// somewhere in your application

finalPropertiesp=newProperties();

// add your JavaMail configuration here

// this is implied by the protocol "imaps"

p.put("mail.imap.starttls.enable","true");

// not only check the certificate, but also make sure that we are

// connected to the right server.

p.put("mail.imap.ssl.checkserveridentity","true");

try{

Session session=Session.getDefaultInstance(p,auth);

Store store=session.getStore();

store.connect();

// do something with the store

}catch(MessagingExceptione){

// do something meaningful(!) with the exception

}

// close the store when you are done

To use SSL at all, you need to turn it on, either by specifying “imaps” in the property mail.store.protocol or by setting mail.imap.starttls.enable to “true”. Replace imap respectively for other protocol suites (e.g. smtp).