So, the other day I found myself having to connect to a server with self-signed SSL certificates while writing Nashorn Javascript. The precise details of how I found myself in this situation are pretty unimportant (I was re-writing an ant build script which had to obtain a build parameter by querying a running instance of a server in dev…), but the problem was suitably esoteric that I couldn’t find a code snippet with a quick search, while probably not being so esoteric that I am the only one who will ever need this, and hence, this post.
So, without further ado:
//***** BEGIN DISABLING SSL SECURITY *****
// Create a trust manager that does not validate certificate chains
var X509TrustManager = Java.type("javax.net.ssl.X509TrustManager");
var permissiveTrustManager = Java.extend(X509TrustManager,
{
getAcceptedIssuers: function(){return null;},
checkClientTrusted: function(certs, authType){return;},
checkServerTrusted: function(certs, authType){return;}
}
);
var trustAllCerts = [new permissiveTrustManager()];
// Install the all-trusting trust manager
var sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
var HostnameVerifier = Java.type("javax.net.ssl.HostnameVerifier");
var allHostsValid = Java.extend(HostnameVerifier,
{
verify: function(hostname,session){return true;}
}
);
// Install the all-trusting host verifier
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new allHostsValid());
//***** SSL SECURITY DISABLED *****
//Make your completely insecure SSL calls
//url = new java.net.URL(endpoint);
//urlConn = url.openConnection();
//etc.