Search in sources :

Example 1 with ConnectionSpec

use of okhttp3.ConnectionSpec in project muzei by romannurik.

the class OkHttpClientFactory method enableTls12.

/**
     * Enable TLS on the OKHttp builder by setting a custom SocketFactory
     */
private static OkHttpClient.Builder enableTls12(OkHttpClient.Builder client) {
    Log.i(TAG, "Enabling HTTPS compatibility mode");
    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];
        client.sslSocketFactory(new TLSSocketFactory(), trustManager);
        ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1).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(TAG, "Error while setting TLS", exc);
    }
    return client;
}
Also used : ConnectionSpec(okhttp3.ConnectionSpec) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) ArrayList(java.util.ArrayList) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 2 with ConnectionSpec

use of okhttp3.ConnectionSpec in project okhttp by square.

the class RealConnection method connect.

public void connect(int connectTimeout, int readTimeout, int writeTimeout, boolean connectionRetryEnabled) {
    if (protocol != null)
        throw new IllegalStateException("already connected");
    RouteException routeException = null;
    List<ConnectionSpec> connectionSpecs = route.address().connectionSpecs();
    ConnectionSpecSelector connectionSpecSelector = new ConnectionSpecSelector(connectionSpecs);
    if (route.address().sslSocketFactory() == null) {
        if (!connectionSpecs.contains(ConnectionSpec.CLEARTEXT)) {
            throw new RouteException(new UnknownServiceException("CLEARTEXT communication not enabled for client"));
        }
        String host = route.address().url().host();
        if (!Platform.get().isCleartextTrafficPermitted(host)) {
            throw new RouteException(new UnknownServiceException("CLEARTEXT communication to " + host + " not permitted by network security policy"));
        }
    }
    while (true) {
        try {
            if (route.requiresTunnel()) {
                connectTunnel(connectTimeout, readTimeout, writeTimeout);
            } else {
                connectSocket(connectTimeout, readTimeout);
            }
            establishProtocol(connectionSpecSelector);
            break;
        } catch (IOException e) {
            closeQuietly(socket);
            closeQuietly(rawSocket);
            socket = null;
            rawSocket = null;
            source = null;
            sink = null;
            handshake = null;
            protocol = null;
            http2Connection = null;
            if (routeException == null) {
                routeException = new RouteException(e);
            } else {
                routeException.addConnectException(e);
            }
            if (!connectionRetryEnabled || !connectionSpecSelector.connectionFailed(e)) {
                throw routeException;
            }
        }
    }
    if (http2Connection != null) {
        synchronized (connectionPool) {
            allocationLimit = http2Connection.maxConcurrentStreams();
        }
    }
}
Also used : ConnectionSpec(okhttp3.ConnectionSpec) UnknownServiceException(java.net.UnknownServiceException) IOException(java.io.IOException)

Example 3 with ConnectionSpec

use of okhttp3.ConnectionSpec in project okhttp by square.

the class RealConnection method connectTls.

private void connectTls(ConnectionSpecSelector connectionSpecSelector) throws IOException {
    Address address = route.address();
    SSLSocketFactory sslSocketFactory = address.sslSocketFactory();
    boolean success = false;
    SSLSocket sslSocket = null;
    try {
        // Create the wrapper over the connected socket.
        sslSocket = (SSLSocket) sslSocketFactory.createSocket(rawSocket, address.url().host(), address.url().port(), true);
        // Configure the socket's ciphers, TLS versions, and extensions.
        ConnectionSpec connectionSpec = connectionSpecSelector.configureSecureSocket(sslSocket);
        if (connectionSpec.supportsTlsExtensions()) {
            Platform.get().configureTlsExtensions(sslSocket, address.url().host(), address.protocols());
        }
        // Force handshake. This can throw!
        sslSocket.startHandshake();
        Handshake unverifiedHandshake = Handshake.get(sslSocket.getSession());
        // Verify that the socket's certificates are acceptable for the target host.
        if (!address.hostnameVerifier().verify(address.url().host(), sslSocket.getSession())) {
            X509Certificate cert = (X509Certificate) unverifiedHandshake.peerCertificates().get(0);
            throw new SSLPeerUnverifiedException("Hostname " + address.url().host() + " not verified:" + "\n    certificate: " + CertificatePinner.pin(cert) + "\n    DN: " + cert.getSubjectDN().getName() + "\n    subjectAltNames: " + OkHostnameVerifier.allSubjectAltNames(cert));
        }
        // Check that the certificate pinner is satisfied by the certificates presented.
        address.certificatePinner().check(address.url().host(), unverifiedHandshake.peerCertificates());
        // Success! Save the handshake and the ALPN protocol.
        String maybeProtocol = connectionSpec.supportsTlsExtensions() ? Platform.get().getSelectedProtocol(sslSocket) : null;
        socket = sslSocket;
        source = Okio.buffer(Okio.source(socket));
        sink = Okio.buffer(Okio.sink(socket));
        handshake = unverifiedHandshake;
        protocol = maybeProtocol != null ? Protocol.get(maybeProtocol) : Protocol.HTTP_1_1;
        success = true;
    } catch (AssertionError e) {
        if (Util.isAndroidGetsocknameError(e))
            throw new IOException(e);
        throw e;
    } finally {
        if (sslSocket != null) {
            Platform.get().afterHandshake(sslSocket);
        }
        if (!success) {
            closeQuietly(sslSocket);
        }
    }
}
Also used : Address(okhttp3.Address) ConnectionSpec(okhttp3.ConnectionSpec) SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) X509Certificate(java.security.cert.X509Certificate) Handshake(okhttp3.Handshake)

Example 4 with ConnectionSpec

use of okhttp3.ConnectionSpec in project okhttp by square.

the class ConnectionSpecSelectorTest method someFallbacksSupported.

@Test
public void someFallbacksSupported() throws Exception {
    ConnectionSpec sslV3 = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).tlsVersions(TlsVersion.SSL_3_0).build();
    ConnectionSpecSelector connectionSpecSelector = createConnectionSpecSelector(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS, sslV3);
    TlsVersion[] enabledSocketTlsVersions = { TlsVersion.TLS_1_1, TlsVersion.TLS_1_0 };
    SSLSocket socket = createSocketWithEnabledProtocols(enabledSocketTlsVersions);
    // MODERN_TLS is used here.
    connectionSpecSelector.configureSecureSocket(socket);
    assertEnabledProtocols(socket, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0);
    boolean retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION);
    assertTrue(retry);
    socket.close();
    // COMPATIBLE_TLS is used here.
    socket = createSocketWithEnabledProtocols(enabledSocketTlsVersions);
    connectionSpecSelector.configureSecureSocket(socket);
    assertEnabledProtocols(socket, TlsVersion.TLS_1_0);
    retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION);
    assertFalse(retry);
    socket.close();
// sslV3 is not used because SSLv3 is not enabled on the socket.
}
Also used : TlsVersion(okhttp3.TlsVersion) ConnectionSpec(okhttp3.ConnectionSpec) SSLSocket(javax.net.ssl.SSLSocket) Test(org.junit.Test)

Example 5 with ConnectionSpec

use of okhttp3.ConnectionSpec in project java-sdk by watson-developer-cloud.

the class HttpClientSingleton method configureHttpClient.

/**
 * Configures the HTTP client.
 *
 * @return the HTTP client
 */
private OkHttpClient configureHttpClient() {
    final OkHttpClient.Builder builder = new OkHttpClient.Builder();
    addCookieJar(builder);
    builder.connectTimeout(60, TimeUnit.SECONDS);
    builder.writeTimeout(60, TimeUnit.SECONDS);
    builder.readTimeout(90, TimeUnit.SECONDS);
    builder.addNetworkInterceptor(HttpLogging.getLoggingInterceptor());
    ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledCipherSuites().build();
    builder.connectionSpecs(Arrays.asList(spec, ConnectionSpec.CLEARTEXT));
    setupTLSProtocol(builder);
    return builder.build();
}
Also used : Builder(okhttp3.OkHttpClient.Builder) OkHttpClient(okhttp3.OkHttpClient) ConnectionSpec(okhttp3.ConnectionSpec) Builder(okhttp3.OkHttpClient.Builder)

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