29

I am connecting an SSL client to my SSL server. When the client fails to verify a certificate due to the root not existing in the client's key store, I need the option to add that certificate to the local key store in code and continue. There are examples for always accepting all certificates, but I want the user to verify the cert and add it to local key store without leaving the application.

SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("localhost", 23467);
try{
    sslsocket.startHandshake();
} catch (IOException e) {
    //here I want to get the peer's certificate, conditionally add to local key store, then reauthenticate successfully
}

There is a whole lot of stuff about custom SocketFactory, TrustManager, SSLContext, etc and I don't really understand how they all fit together or which would be the shortest path to my goal.

Cœur
  • 37,241
  • 25
  • 195
  • 267
iratepr
  • 313
  • 1
  • 4
  • 8
  • this might be a little late, but http://jcalcote.wordpress.com/2010/06/22/managing-a-dynamic-java-trust-store/ this link helps. – goh Apr 17 '13 at 02:26

2 Answers2

22

You could implement this using a X509TrustManager.

Obtain an SSLContext with

SSLContext ctx = SSLContext.getInstance("TLS");

Then initialize it with your custom X509TrustManager by using SSLContext#init. The SecureRandom and the KeyManager[] may be null. The latter is only useful if you perform client authentication, if in your scenario only the server needs to authenticate you don't need to set it.

From this SSLContext, get your SSLSocketFactory using SSLContext#getSocketFactory and proceed as planned.

As concerns your X509TrustManager implementation, it could look like this:

TrustManager tm = new X509TrustManager() {
    public void checkClientTrusted(X509Certificate[] chain,
                    String authType)
                    throws CertificateException {
        //do nothing, you're the client
    }

    public X509Certificate[] getAcceptedIssuers() {
        //also only relevant for servers
    }

    public void checkServerTrusted(X509Certificate[] chain,
                    String authType)
                    throws CertificateException {
        /* chain[chain.length -1] is the candidate for the
         * root certificate. 
         * Look it up to see whether it's in your list.
         * If not, ask the user for permission to add it.
         * If not granted, reject.
         * Validate the chain using CertPathValidator and 
         * your list of trusted roots.
         */
    }
};

Edit:

Ryan was right, I forgot to explain how to add the new root to the existing ones. Let's assume your current KeyStore of trusted roots was derived from cacerts (the 'Java default trust store' that comes with your JDK, located under jre/lib/security). I assume you loaded that key store (it's in JKS format) with KeyStore#load(InputStream, char[]).

KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream in = new FileInputStream("<path to cacerts"");
ks.load(in, "changeit".toCharArray);

The default password to cacerts is "changeit" if you haven't, well, changed it.

Then you may add addtional trusted roots using KeyStore#setEntry. You can omit the ProtectionParameter (i.e. null), the KeyStore.Entry would be a TrustedCertificateEntry that takes the new root as parameter to its constructor.

KeyStore.Entry newEntry = new KeyStore.TrustedCertificateEntry(newRoot);
ks.setEntry("someAlias", newEntry, null);

If you'd like to persist the altered trust store at some point, you may achieve this with KeyStore#store(OutputStream, char[].

emboss
  • 38,880
  • 7
  • 101
  • 108
  • 2
    Note that this is 100% insecure. You may as well not use SSL at all. This is vunerable to man-in-the-middle attacks. – user207421 Jul 19 '11 at 23:47
  • 1
    @EJP: Please explain. MITM with SSL is normally only possible if you neglect hostname verification. This is still performed internally by the DefaultHostnameVerifier. – emboss Jul 20 '11 at 00:00
  • Regardless of the correctness of security here, it doesn't answer the question. The question is how to programmatically add a cert to the keystore. – Ryan Stewart Jul 20 '11 at 02:56
  • 2
    @emboss but who is to say that the certificate you just blindly trusted actually came from the host it said it came from? – user207421 Jul 20 '11 at 08:48
  • @EJP: The same issue occurs with an already trusted CA. That's where the HostnameVerifier jumps in: It checks whether the domain name of the server you are connected to is equal to the subject dn of the certificate (or if it' a wildcard certificate, if the subject dn is equal to *.domain.name). If this is not given, then the same checks will be applied for the Subject Alternative Name entry in the certificate. If all of these are different from the actual host name, the connection will be dropped. That process is completely independent of you trusting the root of the chain or not. – emboss Jul 20 '11 at 09:09
  • 1
    @emboss A trusted CA will verify that the person asking it to sign the CA is authorized to adminstrate the domain in the subjectDN. The issue here is that as the certificate isn't trusted, why should anybody believe what it says its DN is? – user207421 Jul 20 '11 at 10:20
  • @EJP: Ok, a CA will refrain from issuing a certificate to you that says "www.google.com" on it, that's true. But the whole point in the second scenario is what the OP is trying to achieve: You are presented with a certificate for a host named shady.server.org. Hostname verification guarantees that this is the host you are communicating with. So it's up to you to trust this server or not. You face the same problem if a 'real' CA is not listed in cacerts. Just because it's not listed in cacerts doesn't make it 'bad' by default. – emboss Jul 20 '11 at 10:38
  • 2
    @emboss There is no hostname verification step to neglect in SSL. It is part of HTTPS, not SSL. In Java it is implemented by HttpsURLConnection, not by SSLSocket. There is no evidence here that he is even using HTTPS. All he has mentioned is SSL. See also the tags. – user207421 Jul 20 '11 at 12:26
  • @EJP: You're turning in circles here. If we talk about plain socket connections then there is also conceptually no difference between trusting a root certificate "blindly" after examining it or having a list of already trusted certificates like "cacerts". If you think about it, it's even worse having somebody trusting for you instead of doing the selection yourself. It's just common sense since the individual generally doesn't know whom to trust as a CA. – emboss Jul 20 '11 at 13:41
  • First thanks for the solution, this is what I was looking for. Although I find it weird that to insert a hook to handle an unknown certificate I have to rewrite the default certificate checking. I don't understand why standard SSL doesn't do hostname verification, unless the certificate doesn't have a subject dn. As I am connecting to my own server, I can require this field. – iratepr Jul 20 '11 at 16:49
  • 1
    @iratepr: Hostname verification is performed by Java only if you connect via a HttpsUrlConnection. If you do SSL on the Socket level you would have to do this on your own. By using the approach I described you will not replace the entire certificate validation mechanism (the chain is e.g. still built using the PKIX algorithm) - you are just presented with the final result in the hook method and can then decide whether to accept or not. – emboss Jul 20 '11 at 17:34
  • 2
    @emboss your point escapes me. It appears that you're the one who is going in circles here. (1) He doesn't appear to be using HTTPS, so hostname verification doesn't arise, unless you are suggesting he adds manual code for it. (2) HTTPS doesn't use hostname verification *instead of* certificate authentication, it does *both.* – user207421 Jul 21 '11 at 04:57
6

In the JSSE API (the part that takes care of SSL/TLS), checking whether a certificate is trusted doesn't necessarily involve a KeyStore. This will be the case in the vast majority of cases, but assuming there will always be one is incorrect. This is done via a TrustManager. This TrustManager is likely to use the default trust store KeyStore or the one specified via the javax.net.ssl.trustStore system property, but that's not necessarily the case, and this file isn't necessarily $JAVA_HOME/jre/lib/security/cacerts (all this depends on the JRE security settings).

In the general case, you can't get hold of the KeyStore that's used by the trust manager you're using from the application, more so if the default trust store is used without any system property settings. Even if you were able to find out what that KeyStore is, you would still be facing two possible problems (at least):

  • You might not be able to write to that file (which is not necessarily a problem if you're not saving the changes permanently).
  • This KeyStore might not even be file-based (e.g. it could be the Keychain on OSX) and you might not have write access to it either.

What I would suggest is to write a wrapper around the default TrustManager (more specifically, X509TrustManager) which performs the checks against the default trust manager and, if this initial check fails, performs a callback to the user-interface to check whether to add it to a "local" trust store.

This can be done as shown in this example (with a brief unit test), if you want to use something like jSSLutils.

Preparing your SSLContext would be done like this:

KeyStore keyStore = // ... Create and/or load a keystore from a file
                    // if you want it to persist, null otherwise.

// In ServerCallbackWrappingTrustManager.CheckServerTrustedCallback
CheckServerTrustedCallback callback = new CheckServerTrustedCallback {
    public boolean checkServerTrusted(X509Certificate[] chain,
            String authType) {
        return true; // only if the user wants to accept it.
    }
}

// Without arguments, uses the default key managers and trust managers.
PKIXSSLContextFactory sslContextFactory = new PKIXSSLContextFactory();
sslContextFactory
   .setTrustManagerWrapper(new ServerCallbackWrappingTrustManager.Wrapper(
                    callback, keyStore));
SSLContext sslContext = sslContextFactory.buildSSLContext();
SSLSocketFactory sslSocketFactory = sslContext.getSslSocketFactory();
// ...

// Use keyStore.store(...) if you want to save the resulting keystore for later use.

(Of course, you don't need to use this library and its SSLContextFactory, but implement your own X509TrustManager, "wrapping" or not the default one, as you prefer.)

Another factor you have to take into account is the user interaction with this callback. By the time the user has made the decision to click on accept or reject (for example), the handshake may have timed out, so you may have to make a second attempt to connect when the user has accepted the certificate.

Another point to take into account in the design of the callback is that the trust manager doesn't know which socket is being used (unlike its X509KeyManager counterpart), so there should be as little ambiguity as to what user action caused that pop-up (or however you want to implement the callback). If multiple connections are made, you wouldn't want to validate the wrong one. It seems possible to solve this by using a distinct callback, SSLContext and SSLSocketFactory per SSLSocket that's supposed to make a new connection, some way of tying up the SSLSocket and the callback to the action taken by the user to trigger that connection attempt in the first place.

Bruno
  • 119,590
  • 31
  • 270
  • 376
  • All interesting points! Its amazing to see how different languages implement things like this, and how many ways there are to approach the same problem. In my case, I happen to be using a single socket per client, and a custom keystore specified by system property. The answer suggested by emboss seems to most simply satisfy my requirements for this task, but I am glad to know some of the bigger picture and how it might affect this and future projects. – iratepr Jul 20 '11 at 20:19