IP direct connection approach for HTTPS (with SNI) on Android

Updated at:

This topic describes how to connect an Android app to an IP address over HTTPS using the HTTPDNS Android SDK, including how to handle certificate verification and Server Name Indication (SNI) in both standard and SNI scenarios.

Important
  1. OkHttp provides a custom DNS service interface that enables direct IP connections. If you use the OkHttp network framework for Android development, this solution is simpler and more versatile than the general solution. For more information, see Best practices for integrating the HTTPDNS Android SDK with the OkHttp framework.

  2. If you use CDN services on the server side or plan to use CDN services in the future, use the solution for HTTPS SNI scenarios.

Background

When the HTTPDNS Android SDK resolves a domain name to an IP address, your app replaces the domain name in the request URL with that IP address. This creates two problems for HTTPS connections:

  • Certificate verification failure: The TLS certificate is issued for the original domain name, not the IP address. When Android validates the certificate against the URL host, the IP address causes a mismatch.

  • SNI breakage: In SNI scenarios (one IP serving multiple HTTPS certificates), the server needs the original domain name during the TLS handshake to select the correct certificate. Replacing the domain name with an IP address prevents the server from matching a certificate.

The solution depends on your scenario:

  • Standard scenarios

Override HostnameVerifier to substitute the IP address back to the original domain name during certificate verification. This approach is simpler and works for single-domain servers.

  • SNI scenarios

Implement a custom SSLSocketFactory for the HttpsURLConnection interface. When creating a socket, use the API provided by the HTTPDNS Android SDK to replace the domain name with its resolved IP address, then configure SNI and HostnameVerifier. Use this approach when the server hosts multiple HTTPS certificates on the same IP address, or when you use CDN services.

Note

If you use an IPv6 address to replace the host in the request URL, enclose the IPv6 address in square brackets [].

For example: https://[2400:3200:xxx:1]/path

Best practices

  • Solution for standard HTTPS scenarios

Override HostnameVerifier to replace the IP address with the original domain name before certificate verification. The example below uses HttpURLConnection.

try {
      // If you use an IPv6 address to replace the host in the request URL, enclose the IPv6 address in square brackets ([]).
      // For example: https://[2400:3200:xxx:1]/path
      String url = "https://124.239.XX.XX/?sprefer=sypc00";
      HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();

      connection.setRequestProperty("Host", "m.taobao.com");
      connection.setHostnameVerifier(new HostnameVerifier() {

      /*
       * HostnameVerifier is called when the URL hostname does not match the
       * peer's identification hostname during a TLS handshake.
       *
       * After HTTPDNS replaces the hostname with an IP address, the URL no longer
       * matches the certificate domain. Use this callback to verify against the
       * original domain name instead.
       */

        @Override
        public boolean verify(String hostname, SSLSession session) {
             return HttpsURLConnection.getDefaultHostnameVerifier().verify("m.taobao.com", session);
        }
    }); 
    connection.connect();
     } catch (Exception e) {
           e.printStackTrace();
     } finally { 
   }
Important

If you receive an SSL verification error when using this solution, such as System.err: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found., check whether your scenario is SNI (single IP with multiple HTTPS domain names).

  • Solution for SNI HTTPS scenarios

  1. The following sample code covers the key integration points for SNI scenarios using HttpsURLConnection. For the complete code, see the Demo project source code.

  2. Implement a custom SSLSocketFactory. In createSocket, replace the domain name with the IP address from domain name resolution and configure SNI and HostnameVerifier.

class TlsSniSocketFactory extends SSLSocketFactory {
    private final String TAG = TlsSniSocketFactory.class.getSimpleName();
    HostnameVerifier hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    private HttpsURLConnection conn;

    public TlsSniSocketFactory(HttpsURLConnection conn) {
        this.conn = conn;
    }

    @Override
    public Socket createSocket() throws IOException {
        return null;
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return null;
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
        return null;
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return null;
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        return null;
    }

    // TLS layer
    @Override
    public String[] getDefaultCipherSuites() {
        return new String[0];
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return new String[0];
    }

    @Override
    public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException {
        String peerHost = this.conn.getRequestProperty("Host");
        if (peerHost == null){           
            peerHost = host;
        }

        Log.i(TAG, "customized createSocket. host: " + peerHost);
        InetAddress address = plainSocket.getInetAddress();

        if (autoClose) {
            // we don't need the plainSocket
            plainSocket.close();
        }
        // create and connect SSL socket, but don't do hostname/certificate verification yet
        SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
        SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(address, port);

        // enable TLSv1.1/1.2 if available
        ssl.setEnabledProtocols(ssl.getSupportedProtocols());

       // set up SNI before the handshake
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Log.i(TAG, "Setting SNI hostname");
            sslSocketFactory.setHostname(ssl, peerHost);
       } else {
            Log.d(TAG, "No documented SNI support on Android <4.2, trying with reflection");
            try {
                 java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class);
                 setHostnameMethod.invoke(ssl, peerHost);
            } catch (Exception e) {
                 Log.w(TAG, "SNI not useable", e);
            }
        }

        // verify hostname and certificate
        SSLSession session = ssl.getSession();

        if (!hostnameVerifier.verify(peerHost, session)){
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + peerHost);
        }

       Log.i(TAG, "Established " + session.getProtocol() + " connection with " + session.getPeerHost() +
                " using " + session.getCipherSuite());

        return ssl;
    }
}

The following sample code shows how to use the custom SSLSocketFactory to make HTTPS requests with SNI and handle redirects.

public void recursiveRequest(String path, String reffer) {
    URL url = null;
    try {
          url = new URL(path);
          conn = (HttpsURLConnection) url.openConnection();
          String ip = dnsResolver.getIPV4ByHost(url.getHost());
          // If you use an IPv6 address to replace the host in the request URL, enclose the IPv6 address in square brackets ([]).
          // For example: https://[2400:3200:xxx:1]/path
          if (ip != null) {
               // Replace the URL with the HTTPDNS-resolved IP address and set the Host header.
               Log.d(TAG, "get IP: " + ip + " for host: " + url.getHost() + "from pdns resolver success!");
               String newUrl = path.replaceFirst(url.getHost(), ip);
               conn = (HttpsURLConnection) new URL(newUrl).openConnection();
               // Set the Host field in the HTTP request header.
               conn.setRequestProperty("Host", url.getHost());
            }
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(false);
            TlsSniSocketFactory sslSocketFactory = new TlsSniSocketFactory(conn);
            conn.setSSLSocketFactory(sslSocketFactory);
            conn.setHostnameVerifier(new HostnameVerifier() {
            /*
             * HostnameVerifier is called when the URL hostname does not match the
             * peer's identification hostname during a TLS handshake.
             *
             * After HTTPDNS replaces the hostname with an IP address, the URL no longer
             * matches the certificate domain. Use this callback to verify against the
             * original domain name instead.
             */
            @Override
            public boolean verify(String hostname, SSLSession session) {
                String host = conn.getRequestProperty("Host");
                if (null == host) {
                    host = conn.getURL().getHost();
                }
                return HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session);
             }
         });
         int code = conn.getResponseCode();// Network block
         if (needRedirect(code)) {
             // The case of the `Location` header is significant for temporary and permanent redirects.
             String location = conn.getHeaderField("Location");
             if (location == null) {
                 location = conn.getHeaderField("location");
             }
             if (!(location.startsWith("http://") || location.startsWith("https://"))) {
                 // Sometimes the host is omitted and only the path is returned. Complete the URL in this case.
                 URL originalUrl = new URL(path);
                 location = originalUrl.getProtocol() + "://"+originalUrl.getHost() + location;
             }
             recursiveRequest(location, path);
         } else {
            // redirect finish.
            DataInputStream dis = new DataInputStream(conn.getInputStream());
            int len;
            byte[] buff = new byte[4096];
            StringBuilder response = new StringBuilder();
            while ((len = dis.read(buff)) != -1) {
                response.append(new String(buff, 0, len));
            }
            Log.d(TAG, "Response: " + response.toString());
         }
    } catch (MalformedURLException e) {
        Log.w(TAG, "recursiveRequest MalformedURLException");
    } catch (IOException e) {
        Log.w(TAG, "recursiveRequest IOException");
    } catch (Exception e) {
        Log.w(TAG, "unknow exception");
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
Important
  1. This topic covers integrating the HTTPDNS Android SDK for standard and SNI HTTPS scenarios.

  2. To learn how to use the domain name resolution service of the HTTPDNS Android SDK or resolve issues with integrating the SDK, see the Android SDK Developer Guide.

  3. For the complete code to integrate the HTTPDNS Android SDK in HTTPS SNI scenarios, see the demo project source code.