views:

493

answers:

1

I would like to monitor a simple url. But when its a https server I get a handshake exception. Its possible to verify state of a https url the way browser use to connect? (without having a local certificate). I don't know how browsers do to get content from a https url but I would like to make it the same way. Without need to store a specific certificate for each server. The https being monitored should be anyone.

try {
    URL u = new URL(row.getUrl());
    String protocol = u.getProtocol();
    if(protocol.equals("https")) {
        HttpsURLConnection hc = (HttpsURLConnection)u.openConnection();
        System.out.println("Response Code: " + hc.getResponseCode());
        hc.disconnect();
    }
    if(protocol.equals("http")) {
    u.openConnection();
    u.getContent();
    }
    System.out.println("url is up.");
} catch (Exception e) {
    (...)
}
+1  A: 

If you really don't care about the validity of the server's certificate, then you want to set an SSLContext that has a TrustManager that doesn't check anything. Then you need to use that to set the default SSLSocketFactory into the HttpsURLConnection, so that the trust manager is used when you use the URL. Here's an example:

TrustManager[] trustEverything = new TrustManager[] {
    new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() { return null; }
        public void checkClientTrusted(X509Certificate[] certs, String authType) { }
        public void checkServerTrusted(X509Certificate[] certs, String authType) { }
    }
};

SSLContext sslctx = SSLContext.getInstance("SSL");
sslctx.init(null, trustEverything, null);

HttpsURLConnection.setDefaultSSLSocketFactory(sslctx.getSocketFactory());

A full example using this technique can be found here.

As @erickson points out, this means that you can't tell if you're really talking to the server you're concerned about. An even better solution is to update your Trust store to include the self-signed certificate of the server you're talking to, instead of ignoring all checks.

Jared Oberhaus
I came up to some struggling but found this from your sample: http://www.java-samples.com/showtutorial.php?tutorialid=211Now it working. Thanks.
Ruben Trancoso
Good solution, but just remember: you're only checking that "some" server is up; you've lost server authentication so you don't know for sure whether it's yours or a spoof.
erickson
Thanks @Ruben Trancoso, glad I could point you in the right direction. I'll add that link to my answer.
Jared Oberhaus
Excellent point, @erickson. We're throwing away an important feature of SSL/TLS by doing this... I'll add something to my answer to address that.
Jared Oberhaus