Search in sources :

Example 61 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project jersey by jersey.

the class ApacheConnector method createConnectionManager.

private HttpClientConnectionManager createConnectionManager(final Client client, final Configuration config, final SSLContext sslContext, final boolean useSystemProperties) {
    final String[] supportedProtocols = useSystemProperties ? split(System.getProperty("https.protocols")) : null;
    final String[] supportedCipherSuites = useSystemProperties ? split(System.getProperty("https.cipherSuites")) : null;
    HostnameVerifier hostnameVerifier = client.getHostnameVerifier();
    final LayeredConnectionSocketFactory sslSocketFactory;
    if (sslContext != null) {
        sslSocketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites, hostnameVerifier);
    } else {
        if (useSystemProperties) {
            sslSocketFactory = new SSLConnectionSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault(), supportedProtocols, supportedCipherSuites, hostnameVerifier);
        } else {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(), hostnameVerifier);
        }
    }
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
    final Integer chunkSize = ClientProperties.getValue(config.getProperties(), ClientProperties.CHUNKED_ENCODING_SIZE, ClientProperties.DEFAULT_CHUNK_SIZE, Integer.class);
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry, new ConnectionFactory(chunkSize));
    if (useSystemProperties) {
        String s = System.getProperty("http.keepAlive", "true");
        if ("true".equalsIgnoreCase(s)) {
            s = System.getProperty("http.maxConnections", "5");
            final int max = Integer.parseInt(s);
            connectionManager.setDefaultMaxPerRoute(max);
            connectionManager.setMaxTotal(2 * max);
        }
    }
    return connectionManager;
}
Also used : SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) LayeredConnectionSocketFactory(org.apache.http.conn.socket.LayeredConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) ManagedHttpClientConnectionFactory(org.apache.http.impl.conn.ManagedHttpClientConnectionFactory) LayeredConnectionSocketFactory(org.apache.http.conn.socket.LayeredConnectionSocketFactory) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HostnameVerifier(javax.net.ssl.HostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 62 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project hive by apache.

the class HiveConnection method getTwoWaySSLSocketFactory.

SSLConnectionSocketFactory getTwoWaySSLSocketFactory() throws SQLException {
    SSLConnectionSocketFactory socketFactory = null;
    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(JdbcConnectionParams.SUNX509_ALGORITHM_STRING, JdbcConnectionParams.SUNJSSE_ALGORITHM_STRING);
        String keyStorePath = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE);
        String keyStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE_PASSWORD);
        KeyStore sslKeyStore = KeyStore.getInstance(JdbcConnectionParams.SSL_KEY_STORE_TYPE);
        if (keyStorePath == null || keyStorePath.isEmpty()) {
            throw new IllegalArgumentException(JdbcConnectionParams.SSL_KEY_STORE + " Not configured for 2 way SSL connection, keyStorePath param is empty");
        }
        try (FileInputStream fis = new FileInputStream(keyStorePath)) {
            sslKeyStore.load(fis, keyStorePassword.toCharArray());
        }
        keyManagerFactory.init(sslKeyStore, keyStorePassword.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(JdbcConnectionParams.SUNX509_ALGORITHM_STRING);
        String trustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE);
        String trustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE);
        if (trustStorePath == null || trustStorePath.isEmpty()) {
            throw new IllegalArgumentException(JdbcConnectionParams.SSL_TRUST_STORE + " Not configured for 2 way SSL connection");
        }
        try (FileInputStream fis = new FileInputStream(trustStorePath)) {
            sslTrustStore.load(fis, trustStorePassword.toCharArray());
        }
        trustManagerFactory.init(sslTrustStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
        socketFactory = new SSLConnectionSocketFactory(context);
    } catch (Exception e) {
        throw new SQLException("Error while initializing 2 way ssl socket factory ", e);
    }
    return socketFactory;
}
Also used : SQLException(java.sql.SQLException) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) TTransportException(org.apache.thrift.transport.TTransportException) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SaslException(javax.security.sasl.SaslException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) TException(org.apache.thrift.TException) IOException(java.io.IOException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 63 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project weixin-java-tools by chanjarster.

the class WxMpServiceImpl method setWxMpConfigStorage.

public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) {
    this.wxMpConfigStorage = wxConfigProvider;
    String http_proxy_host = wxMpConfigStorage.getHttp_proxy_host();
    int http_proxy_port = wxMpConfigStorage.getHttp_proxy_port();
    String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username();
    String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password();
    final HttpClientBuilder builder = HttpClients.custom();
    if (StringUtils.isNotBlank(http_proxy_host)) {
        // 使用代理服务器
        if (StringUtils.isNotBlank(http_proxy_username)) {
            // 需要用户认证的代理服务器
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(http_proxy_host, http_proxy_port), new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
            builder.setDefaultCredentialsProvider(credsProvider);
        } else {
        // 无需用户认证的代理服务器
        }
        httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
    }
    if (wxConfigProvider.getSSLContext() != null) {
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(wxConfigProvider.getSSLContext(), new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        builder.setSSLSocketFactory(sslsf);
    }
    httpClient = builder.build();
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 64 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project openhab1-addons by openhab.

the class Tr064Comm method createTr064HttpClient.

/***
     * Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
     * and sets Auth. Scheme to Digest Auth
     *
     * @param fboxUrl the URL from config file of fbox to connect to
     * @return the ready-to-use httpclient for tr064 requests
     */
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);
    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
    // auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    // known from fbox specification
    digestAuth.overrideParamter("realm", "HTTPS Access");
    // never known at first request
    digestAuth.overrideParamter("nonce", "");
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);
    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        // accept self signed certs
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        // dont
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
    // verify
    // hostname
    // against
    // cert
    // CN
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
    // BUILDER
    // setup builder with parameters defined before
    hc = // set the SSL options which trust every self signed
    HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// set auth options using digest
    credp).setDefaultRequestConfig(// set the request config specifying timeout
    rc).build();
    return hc;
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) URISyntaxException(java.net.URISyntaxException) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URISyntaxException(java.net.URISyntaxException) SOAPException(javax.xml.soap.SOAPException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 65 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project openhab1-addons by openhab.

the class IhcConnectionPool method init.

private void init() {
    // Create a local instance of cookie store
    cookieStore = new BasicCookieStore();
    // Create local HTTP context
    localContext = HttpClientContext.create();
    // Bind custom cookie store to the local context
    localContext.setCookieStore(cookieStore);
    httpClientBuilder = HttpClientBuilder.create();
    // Setup a Trust Strategy that allows all certificates.
    logger.debug("Initialize SSL context");
    // Create a trust manager that does not validate certificate chains,
    // but accept all.
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            logger.trace("Trusting server cert: " + certs[0].getIssuerDN());
        }
    } };
    try {
        // Controller supports only SSLv3 and TLSv1
        sslContext = SSLContext.getInstance("TLSv1");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        logger.warn("Exception", e);
    } catch (KeyManagementException e) {
        logger.warn("Exception", e);
    }
    httpClientBuilder.setSslcontext(sslContext);
    // Controller accepts only HTTPS connections and because normally IP
    // address are used on home network rather than DNS names, create custom
    // host name verifier.
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {

        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            logger.trace("HostnameVerifier: arg0 = " + arg0);
            logger.trace("HostnameVerifier: arg1 = " + arg1);
            return true;
        }
    };
    // Create an SSL Socket Factory, to use our weakened "trust strategy"
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build();
    // Create connection-manager using our Registry. Allows multi-threaded
    // use
    PoolingHttpClientConnectionManager connMngr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    // Increase max connection counts
    connMngr.setMaxTotal(20);
    connMngr.setDefaultMaxPerRoute(6);
    httpClientBuilder.setConnectionManager(connMngr);
}
Also used : SSLSession(javax.net.ssl.SSLSession) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509TrustManager(javax.net.ssl.X509TrustManager)

Aggregations

SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)157 SSLContext (javax.net.ssl.SSLContext)99 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)63 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)54 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)52 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)49 IOException (java.io.IOException)42 TrustSelfSignedStrategy (org.apache.http.conn.ssl.TrustSelfSignedStrategy)42 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)42 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)36 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)31 KeyManagementException (java.security.KeyManagementException)30 RequestConfig (org.apache.http.client.config.RequestConfig)25 NoopHostnameVerifier (org.apache.http.conn.ssl.NoopHostnameVerifier)25 KeyStoreException (java.security.KeyStoreException)24 HttpClient (org.apache.http.client.HttpClient)24 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)24 KeyStore (java.security.KeyStore)22 CertificateException (java.security.cert.CertificateException)21 Test (org.junit.Test)21