Search in sources :

Example 1 with SSLInitializationException

use of org.apache.http.ssl.SSLInitializationException in project snowflake-jdbc by snowflakedb.

the class SFTrustManager method getTrustManager.

/**
 * Get TrustManager for the algorithm. This is mainly used to get the JVM default trust manager
 * and cache all of the root CA.
 *
 * @param algorithm algorithm.
 * @return TrustManager object.
 */
private X509TrustManager getTrustManager(String algorithm) {
    try {
        TrustManagerFactory factory = TrustManagerFactory.getInstance(algorithm);
        factory.init((KeyStore) null);
        X509TrustManager ret = null;
        for (TrustManager tm : factory.getTrustManagers()) {
            // Manager here.
            if (tm instanceof X509TrustManager) {
                ret = (X509TrustManager) tm;
                break;
            }
        }
        if (ret == null) {
            return null;
        }
        synchronized (ROOT_CA_LOCK) {
            // cache root CA certificates for later use.
            if (ROOT_CA.isEmpty()) {
                for (X509Certificate cert : ret.getAcceptedIssuers()) {
                    Certificate bcCert = Certificate.getInstance(cert.getEncoded());
                    ROOT_CA.put(bcCert.getSubject().hashCode(), bcCert);
                }
            }
        }
        return ret;
    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateEncodingException ex) {
        throw new SSLInitializationException(ex.getMessage(), ex);
    }
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) SSLInitializationException(org.apache.http.ssl.SSLInitializationException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 2 with SSLInitializationException

use of org.apache.http.ssl.SSLInitializationException in project oci-java-sdk by oracle.

the class ApacheConnectorPropertiesClientConfigDecorator method getRegistry.

private Registry<ConnectionSocketFactory> getRegistry() {
    final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory());
    Registry<ConnectionSocketFactory> registry;
    SSLConnectionSocketFactory sslConnectionSocketFactory = null;
    if (config.getSslContext() != null) {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(config.getSslContext(), config.getHostnameVerifier());
    }
    try {
        if (sslConnectionSocketFactory != null) {
            registry = registryBuilder.register("https", sslConnectionSocketFactory).build();
        } else {
            registry = registryBuilder.register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
        }
    } catch (SSLInitializationException e) {
        registry = registryBuilder.register("https", PlainConnectionSocketFactory.getSocketFactory()).build();
    }
    return registry;
}
Also used : ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLInitializationException(org.apache.http.ssl.SSLInitializationException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory)

Example 3 with SSLInitializationException

use of org.apache.http.ssl.SSLInitializationException in project snowflake-jdbc by snowflakedb.

the class HttpUtil method buildHttpClient.

/**
 * Build an Http client using our set of default.
 *
 * @param key Key to HttpClient hashmap containing OCSP mode and proxy information, could be null
 * @param ocspCacheFile OCSP response cache file. If null, the default OCSP response file will be
 *     used.
 * @param downloadCompressed Whether the HTTP client should be built requesting no decompression
 * @return HttpClient object
 */
public static CloseableHttpClient buildHttpClient(@Nullable HttpClientSettingsKey key, File ocspCacheFile, boolean downloadCompressed) {
    // set timeout so that we don't wait forever.
    // Setup the default configuration for all requests on this client
    int timeToLive = convertSystemPropertyToIntValue(JDBC_TTL, DEFAULT_TTL);
    logger.debug("time to live in connection pooling manager: {}", timeToLive);
    // Set proxy settings for DefaultRequestConfig. If current proxy settings are the same as for
    // the last request, keep the current DefaultRequestConfig. If not, build a new
    // DefaultRequestConfig and set the new proxy settings for it
    HttpHost proxy = (key != null && key.usesProxy()) ? new HttpHost(key.getProxyHost(), key.getProxyPort(), key.getProxyProtocol().toString()) : null;
    // If defaultrequestconfig is not initialized or its proxy settings do not match current proxy
    // settings, re-build it (current or old proxy settings could be null, so null check is
    // included)
    boolean noDefaultRequestConfig = DefaultRequestConfig == null || DefaultRequestConfig.getProxy() == null;
    if (noDefaultRequestConfig || !DefaultRequestConfig.getProxy().equals(proxy)) {
        RequestConfig.Builder builder = RequestConfig.custom().setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT).setSocketTimeout(DEFAULT_HTTP_CLIENT_SOCKET_TIMEOUT);
        // the route planner will determine whether to use a proxy based on nonProxyHosts value.
        if (proxy != null && Strings.isNullOrEmpty(key.getNonProxyHosts())) {
            builder.setProxy(proxy);
        }
        DefaultRequestConfig = builder.build();
    }
    TrustManager[] trustManagers = null;
    if (key != null && key.getOcspMode() != OCSPMode.INSECURE) {
        // OCSP FailOpen is ON by default
        try {
            TrustManager[] tm = { new SFTrustManager(key, ocspCacheFile) };
            trustManagers = tm;
        } catch (Exception | Error err) {
            // dump error stack
            StringWriter errors = new StringWriter();
            err.printStackTrace(new PrintWriter(errors));
            logger.error(errors.toString());
            // rethrow the exception
            throw new RuntimeException(err);
        }
    }
    try {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", new SFSSLConnectionSocketFactory(trustManagers, socksProxyDisabled)).register("http", new SFConnectionSocketFactory()).build();
        // Build a connection manager with enough connections
        connectionManager = new PoolingHttpClientConnectionManager(registry, null, null, null, timeToLive, TimeUnit.SECONDS);
        int maxConnections = convertSystemPropertyToIntValue(JDBC_MAX_CONNECTIONS_PROPERTY, DEFAULT_MAX_CONNECTIONS);
        int maxConnectionsPerRoute = convertSystemPropertyToIntValue(JDBC_MAX_CONNECTIONS_PER_ROUTE_PROPERTY, DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
        logger.debug("Max connections total in connection pooling manager: {}; max connections per route: {}", maxConnections, maxConnectionsPerRoute);
        connectionManager.setMaxTotal(maxConnections);
        connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setConnectionManager(connectionManager).useSystemProperties().setRedirectStrategy(new DefaultRedirectStrategy()).setUserAgent(// needed for Okta
        buildUserAgent()).disableCookieManagement();
        if (key != null && key.usesProxy()) {
            // use the custom proxy properties
            SnowflakeMutableProxyRoutePlanner sdkProxyRoutePlanner = httpClientRoutePlanner.computeIfAbsent(key, k -> new SnowflakeMutableProxyRoutePlanner(key.getProxyHost(), key.getProxyPort(), key.getProxyProtocol(), key.getNonProxyHosts()));
            httpClientBuilder = httpClientBuilder.setProxy(proxy).setRoutePlanner(sdkProxyRoutePlanner);
            if (!Strings.isNullOrEmpty(key.getProxyUser()) && !Strings.isNullOrEmpty(key.getProxyPassword())) {
                Credentials credentials = new UsernamePasswordCredentials(key.getProxyUser(), key.getProxyPassword());
                AuthScope authScope = new AuthScope(key.getProxyHost(), key.getProxyPort());
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(authScope, credentials);
                httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        }
        httpClientBuilder.setDefaultRequestConfig(DefaultRequestConfig);
        if (downloadCompressed) {
            httpClientBuilder = httpClientBuilder.disableContentCompression();
        }
        return httpClientBuilder.build();
    } catch (NoSuchAlgorithmException | KeyManagementException ex) {
        throw new SSLInitializationException(ex.getMessage(), ex);
    }
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) HttpHost(org.apache.http.HttpHost) DefaultRedirectStrategy(org.apache.http.impl.client.DefaultRedirectStrategy) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SnowflakeSQLException(net.snowflake.client.jdbc.SnowflakeSQLException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLInitializationException(org.apache.http.ssl.SSLInitializationException) TrustManager(javax.net.ssl.TrustManager) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) AuthScope(org.apache.http.auth.AuthScope) SSLInitializationException(org.apache.http.ssl.SSLInitializationException) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

SSLInitializationException (org.apache.http.ssl.SSLInitializationException)3 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)2 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)2 KeyManagementException (java.security.KeyManagementException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 CertificateEncodingException (java.security.cert.CertificateEncodingException)1 X509Certificate (java.security.cert.X509Certificate)1 TrustManager (javax.net.ssl.TrustManager)1 SnowflakeSQLException (net.snowflake.client.jdbc.SnowflakeSQLException)1 HttpHost (org.apache.http.HttpHost)1 AuthScope (org.apache.http.auth.AuthScope)1 Credentials (org.apache.http.auth.Credentials)1 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)1 CredentialsProvider (org.apache.http.client.CredentialsProvider)1 RequestConfig (org.apache.http.client.config.RequestConfig)1 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)1 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)1 DefaultRedirectStrategy (org.apache.http.impl.client.DefaultRedirectStrategy)1 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)1 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)1