4

In trying to disable TLS 1.0, there are KitKat devices needing access to my API. I have tried overriding the default socket factory without success. I have tried converting to okhttp. Still not working. How do I get Android KitKat to connect to my API?

jnrcorp
  • 1,905
  • 1
  • 18
  • 25

3 Answers3

8

I had the same issue on pre-lollipop devices. As I'm using Retrofit, here is the solution for OkHttp.

Tls12SocketFactory.java:

public class Tls12SocketFactory extends SSLSocketFactory {
    private static final String[] TLS_V12_ONLY = {"TLSv1.2"};

    final SSLSocketFactory delegate;

    public Tls12SocketFactory(SSLSocketFactory base) {
        this.delegate = base;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        return patch(delegate.createSocket(s, host, port, autoClose));
    }

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

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

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

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

    private Socket patch(Socket s) {
        if (s instanceof SSLSocket) {
            ((SSLSocket) s).setEnabledProtocols(TLS_V12_ONLY);
        }
        return s;
    }
}

OkHttpUtils.java:

public class OkHttpUtills {

    public static OkHttpClient createHttpClient() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder client = new OkHttpClient.Builder()
                .followRedirects(true)
                .followSslRedirects(true)
                .addInterceptor(logging)
                .cache(null)
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS);
        return enableTls12OnPreLollipop(client).build();
    }


    /**
     * Enables TLSv1.2 protocol (which is disabled by default)
     * on pre-Lollipop devices, as well as on Lollipop, because some issues can take place on Samsung devices.
     *
     * @param client OKHtp client builder
     * @return
     */
    private static OkHttpClient.Builder enableTls12OnPreLollipop(OkHttpClient.Builder client) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
            try {
                SSLContext sc = SSLContext.getInstance("TLSv1.2");
                sc.init(null, null, null);
                client.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));

                ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                        .tlsVersions(TlsVersion.TLS_1_2)
                        .build();

                List<ConnectionSpec> specs = new ArrayList<>();
                specs.add(cs);
                specs.add(ConnectionSpec.COMPATIBLE_TLS);
                specs.add(ConnectionSpec.CLEARTEXT);

                client.connectionSpecs(specs);
            } catch (Exception exc) {
                Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", exc);
            }
        }
        return client;
    }
}

Hope this could help you.

dniHze
  • 2,162
  • 16
  • 22
  • As a side note, the reason this strategy was not working for me is because my AWS ALB Configuration was using the security policy: ELBSecurityPolicy-TLS-1-2-2017-01 http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-security-policy-table.html I solved the issue of the failed communication by switching to ELBSecurityPolicy-TLS-1-1-2017-01, which offers more ciphers. – jnrcorp Jul 20 '17 at 15:41
  • Check https://developer.android.com/training/articles/security-gms-provider It worked for me – Abins Shaji May 18 '18 at 06:20
  • This is the only place I found an explanation of why some people enable it for Lollipop, as some issues can take place on Samsung devices. Great answer! :) – rewgoes Jan 31 '20 at 05:28
1

OkHttp 3.12.x will do this automatically, see https://github.com/square/okhttp/blob/okhttp_3.12.x/okhttp/src/main/java/okhttp3/internal/platform/AndroidPlatform.java#L452

Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69
0

Additionally I needed an implementation (Java Security Provider) of TLS 1.2 for the 4.4.3 android phone.

If you have access to Google Play Services you could obtain it by

ProviderInstaller.installIfNeeded(getContext());

You need to include gms in your build.gradle

 compile 'com.google.android.gms:play-services:6.+'

This was already mentioned in the comments and is described here


Otherwise if you are not able to use Google Play Services you can use conscrypt

        Provider conscrypt = Conscrypt.newProvider();

        // Add as provider
        Security.insertProviderAt(conscrypt, 1);

        X509TrustManager tm = new
                X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain,
                                                   String authType) throws
                            CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] chain,
                                                   String authType) throws
                            CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                };
        SSLContext sslContext = SSLContext.getInstance("TLS", conscrypt);

        sslContext.init(null, new TrustManager[]{tm}, null);

        SSLContext.setDefault(sslContext);
        HttpsURLConnection.setDefaultSSLSocketFactory(
                sslContext.getSocketFactory());

Additionally you need a TlsSocketFactory implementation which supports TLS 1.2 as already mentioned. I found this approach from a gist in github. Kudos to Karewan

pero_hero
  • 2,881
  • 3
  • 10
  • 24