HTTP HTTP message using HTTPS Confusion - javax.net.ssl.SSLException: hostname in certificate did not match

I am sending https POST to some url using Apache HttpClient.

HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse response = httpClient.execute(httpPost); 

And I get:

 javax.net.ssl.SSLException: hostname in certificate didn't match: <*.*.*.*> != <*.url 

Now, after searching, I found a solution in stackoverflow:

 HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); registry.register(new Scheme("https", socketFactory, 443)); SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry); HttpClient httpClient = new DefaultHttpClient(mgr, client.getParams()); HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); 

And the POST is successful.

But I do not understand what is happening here! Is my connection still secure? This is the right decision? If not, what is the best solution?

+4
source share
2 answers

If you do not verify the host name, you simply do not verify that you are talking to the entity you wanted to talk to: instead, it could be MITM. For example, the same problem as disabling VERIFYHOST using Curl . You may also be interested in this question on Security.SE .

As for your original problem, the hostname (or IP address) in the certificate should match the hostname that you contacted, that is, the URL. If you are using an IP address, this IP address must be in the alternate name of the certificate subject. (See this question .) In general, it is easier to use names rather than IP addresses, even on a local network.

EDIT: Given that you are using Apache Http Client 4.0.2, release notes for 4.0.3 say:

This is a crash release that captures critical regression in the SSL connection control code. The release of HttpClient 4.0.2 included improved support for multi-pass hosts, which unfortunately had an error that would cause the default SSL host name verification logic to fail. An attempt to establish an SSL connection with HttpClient 4.0.2 may result in javax.net.ssl.SSLException: "the hostname in the certificate does not match ...".

+3
source

Important - if you allow all hosts (that is, disable hostname verification), then this is certainly NOT safe. You should not do this in production.

I think you are probably using self-signed certificates, which may be the main reason for this exception. If so, create a certificate with the host as localhost (or your IP), and then try. In production, just enable hostname verification and your code will work fine.

+1
source

All Articles