Search in sources :

Example 21 with ConnectionSpec

use of okhttp3.ConnectionSpec in project sonarlint-core by SonarSource.

the class OkHttpClientBuilder method build.

public OkHttpClient build() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.proxy(proxy);
    if (connectTimeoutMs >= 0) {
        builder.connectTimeout(connectTimeoutMs, TimeUnit.MILLISECONDS);
    }
    if (readTimeoutMs >= 0) {
        builder.readTimeout(readTimeoutMs, TimeUnit.MILLISECONDS);
    }
    builder.addNetworkInterceptor(this::addHeaders);
    if (proxyLogin != null) {
        builder.proxyAuthenticator((route, response) -> {
            if (response.request().header(PROXY_AUTHORIZATION) != null) {
                // Give up, we've already attempted to authenticate.
                return null;
            }
            String proxyCrendentials = Credentials.basic(proxyLogin, nullToEmpty(proxyPassword));
            return response.request().newBuilder().header(PROXY_AUTHORIZATION, proxyCrendentials).build();
        });
    }
    ConnectionSpec tls = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledTlsVersions().allEnabledCipherSuites().supportsTlsExtensions(true).build();
    builder.connectionSpecs(asList(tls, ConnectionSpec.CLEARTEXT));
    X509TrustManager trustManager = sslTrustManager != null ? sslTrustManager : systemDefaultTrustManager();
    SSLSocketFactory sslFactory = sslSocketFactory != null ? sslSocketFactory : systemDefaultSslSocketFactory(trustManager);
    builder.sslSocketFactory(sslFactory, trustManager);
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) ConnectionSpec(okhttp3.ConnectionSpec) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 22 with ConnectionSpec

use of okhttp3.ConnectionSpec in project fitpay-android-sdk by fitpay.

the class BaseClient method enableTls12OnPreLollipop.

private static OkHttpClient.Builder enableTls12OnPreLollipop(OkHttpClient.Builder client) {
    if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 22) {
        try {
            FPLog.i("pre lollipop ssl configuration being used");
            // pulled from {@link OkHttpClient} javadoc in finding the trustmanager, which isn't really exposed!
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
            SSLContext sc = SSLContext.getDefault();
            client.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()), trustManager);
            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) {
            FPLog.e("Error while setting up TLS 1.2 support on a pre-lollipop device, SDK " + Build.VERSION.SDK_INT, exc);
            throw new RuntimeException(exc);
        }
    }
    return client;
}
Also used : ConnectionSpec(okhttp3.ConnectionSpec) ArrayList(java.util.ArrayList) SSLContext(javax.net.ssl.SSLContext) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Example 23 with ConnectionSpec

use of okhttp3.ConnectionSpec in project gh4a by slapperwan.

the class ServiceFactory method enableTls12IfNeeded.

private static OkHttpClient.Builder enableTls12IfNeeded(OkHttpClient.Builder builder) {
    if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 22) {
        try {
            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            sc.init(null, null, null);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init((KeyStore) null);
            TrustManager[] trustManagers = tmf.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            X509TrustManager tm = (X509TrustManager) trustManagers[0];
            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);
            builder.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()), tm);
            builder.connectionSpecs(specs);
        } catch (Exception exc) {
            Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", exc);
        }
    }
    return builder;
}
Also used : ConnectionSpec(okhttp3.ConnectionSpec) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) ArrayList(java.util.ArrayList) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 24 with ConnectionSpec

use of okhttp3.ConnectionSpec in project Tusky by tuskyapp.

the class OkHttpUtils method getCompatibleClientBuilder.

/**
 * Makes a Builder with the maximum range of TLS versions and cipher suites enabled.
 * <p>
 * It first tries the "approved" list of cipher suites given in OkHttp (the default in
 * ConnectionSpec.MODERN_TLS) and if that doesn't work falls back to the set of ALL enabled,
 * then falls back to plain http.
 * <p>
 * API level 24 has a regression in elliptic curves where it only supports secp256r1, so this
 * first tries a fallback without elliptic curves at all, and then tries them after.
 * <p>
 * TLS 1.1 and 1.2 have to be manually enabled on API levels 16-20.
 */
@NonNull
public static OkHttpClient.Builder getCompatibleClientBuilder(SharedPreferences preferences) {
    boolean httpProxyEnabled = preferences.getBoolean("httpProxyEnabled", false);
    String httpServer = preferences.getString("httpProxyServer", "");
    int httpPort = Integer.parseInt(preferences.getString("httpProxyPort", "-1"));
    ConnectionSpec fallback = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledCipherSuites().supportsTlsExtensions(true).build();
    List<ConnectionSpec> specList = new ArrayList<>();
    specList.add(ConnectionSpec.MODERN_TLS);
    addNougatFixConnectionSpec(specList);
    specList.add(fallback);
    specList.add(ConnectionSpec.CLEARTEXT);
    OkHttpClient.Builder builder = new OkHttpClient.Builder().addInterceptor(getUserAgentInterceptor()).readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).connectionSpecs(specList);
    if (httpProxyEnabled && !httpServer.isEmpty() && (httpPort > 0) && (httpPort < 65535)) {
        InetSocketAddress address = InetSocketAddress.createUnresolved(httpServer, httpPort);
        builder.proxy(new Proxy(Proxy.Type.HTTP, address));
    }
    if (BuildConfig.DEBUG) {
        builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC));
    }
    return enableHigherTlsOnPreLollipop(builder);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) ConnectionSpec(okhttp3.ConnectionSpec) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) Proxy(java.net.Proxy) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) NonNull(android.support.annotation.NonNull)

Example 25 with ConnectionSpec

use of okhttp3.ConnectionSpec in project Tusky by tuskyapp.

the class OkHttpUtils method addNougatFixConnectionSpec.

/**
 * Android version Nougat has a regression where elliptic curve cipher suites are supported, but
 * only the curve secp256r1 is allowed. So, first it's best to just disable all elliptic
 * ciphers, try the connection, and fall back to the all cipher suites enabled list after.
 */
private static void addNougatFixConnectionSpec(List<ConnectionSpec> specList) {
    if (Build.VERSION.SDK_INT != Build.VERSION_CODES.N) {
        return;
    }
    SSLSocketFactory socketFactory;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }
        X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManager }, null);
        socketFactory = sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        Log.e(TAG, "Failed obtaining the SSL socket factory.");
        return;
    }
    String[] cipherSuites = socketFactory.getDefaultCipherSuites();
    ArrayList<String> allowedList = new ArrayList<>();
    for (String suite : cipherSuites) {
        if (!suite.contains("ECDH")) {
            allowedList.add(suite);
        }
    }
    ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).cipherSuites(allowedList.toArray(new String[0])).supportsTlsExtensions(true).build();
    specList.add(spec);
}
Also used : ConnectionSpec(okhttp3.ConnectionSpec) ArrayList(java.util.ArrayList) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Aggregations

ConnectionSpec (okhttp3.ConnectionSpec)18 Internal.applyConnectionSpec (okhttp3.internal.Internal.applyConnectionSpec)18 Test (org.junit.jupiter.api.Test)18 ArrayList (java.util.ArrayList)11 SSLSocket (javax.net.ssl.SSLSocket)9 X509TrustManager (javax.net.ssl.X509TrustManager)9 OkHttpClient (okhttp3.OkHttpClient)7 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)6 SSLContext (javax.net.ssl.SSLContext)5 TrustManager (javax.net.ssl.TrustManager)5 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)5 IOException (java.io.IOException)4 KeyManagementException (java.security.KeyManagementException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 NonNull (android.support.annotation.NonNull)2 UnknownServiceException (java.net.UnknownServiceException)2 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)2 GsonBuilder (com.google.gson.GsonBuilder)1 FileNotFoundException (java.io.FileNotFoundException)1