users@glassfish.java.net

Verifying CN field of SSL server cert, best practice

From: Andreas Junius <AJunius_at_internode.com.au>
Date: Fri, 7 Sep 2012 02:17:36 +0000

Hi all,

I've a special use case, where the SSL server certificate contains a user id rather than the host name. I implemented therefore a custom hostnameVerifier, which checks against this name (and which works):

connection.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                String cnContent = null;
                try {
                    String rawName = session.getPeerPrincipal().getName();
                    String[] rawFields = rawName.split(",");
                    if (rawFields != null) {
                        for (String s : rawFields) {
                            if (s.startsWith("CN") || s.startsWith("cn")) {
                                // might fail
                                cnContent = s.split("=")[1];
                                break;
                            }
                        }
                    }
                } catch (SSLPeerUnverifiedException e) {
                    LOGGER.severe(e.getMessage() + ", " + Arrays.toString(e.getStackTrace()));
                }
                return userId.equals(cnContent);
            }
        });

So, my question is: is that a valid approach? Is there a better way to get the contents of the CN field? Or should I rather implement a custom trustmanager?

Cheers,
Andy