Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable SNI in HTTP request using Apache HTTPComponents HttpClient?

I am trying to figure out how to send a successful HTTP GET request to a server requiring SNI.

I searched on SO and other places, and found some articles that said that SNI is now supported in JDK7, as well as Apache HTTP Components.

https://issues.apache.org/jira/browse/HTTPCLIENT-1119 https://wiki.apache.org/HttpComponents/SNISupport

Relevant SO article: Certificate chain different between HTTPSURLconnection and Apache (System) DefaultHttpClient

--

However, I cannot seem to find any docs that show how to get this to work.

Here is the code I am using...


            KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
            String trustedCertsPath = System.getenv("JAVA_HOME") + "/jre/lib/security/cacerts";
            FileInputStream certstream = new FileInputStream(new File(trustedCertsPath));
            try {
                trustStore.load(certstream, "changeit".toCharArray());
            } finally {
                certstream.close();
            }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                .build();

        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        CloseableHttpClient httpclient2 = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();

        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet(uri);
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                tempFile = File.createTempFile(httpFile.getTempFilePrefix(), httpFile.getTempFilePosfix());
                FileOutputStream os = new FileOutputStream(tempFile);

                InputStream instream = entity.getContent();
                try {
                    IOUtils.copy(instream, os);
                } finally {
                    try { instream.close(); } catch (Exception e) {}
                    try { os.close(); } catch (Exception e) {}
                }
            }
        } finally {
            response.close();
        }

When I run this, the request fails.

The server requires SNI in the request, and without it, it returns an expired cert that has the wrong CommonName, due to which it gets rejected.

If I use the httpclient2 instance, that is setup using a custom SSL context to allow all hTTP certs, then the request succeeds. However, that is not something I want to enable on a server that does a lot of downloads per day against different hosts.

I am using httpclient v 4.3.5

Any help appreciated.

Thanks.

like image 843
feroze Avatar asked Sep 15 '14 18:09

feroze


People also ask

How does Apache HttpClient handle invalid SSL certificates?

To resolve the issue, do one of the following: Configure SSLContext with a TrustManager that accepts any certificate (see below). Configure SSLContext with an appropriate trust store that includes your certificate. Add the certificate for that site to the default Java trust store.

Does HttpClient support https?

C# Only http and https schemes are allowed - HttpClient - Microsoft Q&A.

What is SNI in Java?

SNI (server name indication) is an extension to the TLS protocol that allows the client to specify the hostname before the handshaking starts so that the server knows which certificate to serve. The new SNIHostName, SNIMatcher, and SNIServerName classes that support this functionality are located in the javax. net.


1 Answers

SNI should work completely transparently when running on Java 1.7 or newer. No configuration is required. If for whatever reason SSL handshake with SNI enabled server fails you should be able to find out why (and whether or not the SNI extension was properly employed) by turning on SSL debug logging as described here [1] and here [2]

'Debugging SSL/TLS Connections' may look outdated but it can still be useful when troubleshooting SSL related issues.

[1] http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/ReadDebug.html

[2] http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html#Debug

like image 162
ok2c Avatar answered Sep 30 '22 08:09

ok2c