List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory
public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory, final X509HostnameVerifier hostnameVerifier)
From source file:org.openscore.content.httpclient.build.conn.SSLConnectionSocketFactoryBuilder.java
public SSLConnectionSocketFactory build() { if (!"true".equalsIgnoreCase(trustAllRootsStr) && !"false".equalsIgnoreCase(trustAllRootsStr)) { throw new IllegalArgumentException("'trustAllRoots' can only be 'true' or 'false'"); }//from w ww. jav a 2 s . c o m boolean trustAllRoots = Boolean.parseBoolean(trustAllRootsStr); SSLContextBuilder sslContextBuilder = SSLContexts.custom(); if (!trustAllRoots) { boolean useClientCert = !StringUtils.isEmpty(keystore); //validate SSL certificates sent by the server boolean useTrustCert = !StringUtils.isEmpty(trustKeystore); String javaKeystore = System.getProperty("java.home") + "/lib/security/cacerts"; boolean storeExists = new File(javaKeystore).exists(); if (!useClientCert && storeExists) { keystore = "file:" + javaKeystore; keystorePassword = (StringUtils.isEmpty(keystorePassword)) ? "changeit" : keystorePassword; useClientCert = true; } else if (useClientCert && !keystore.startsWith("http")) { keystore = "file:" + keystore; } if (!useTrustCert && storeExists) { trustKeystore = "file:" + javaKeystore; trustPassword = (StringUtils.isEmpty(trustPassword)) ? "changeit" : trustPassword; useTrustCert = true; } else if (useTrustCert && !trustKeystore.startsWith("http")) { trustKeystore = "file:" + trustKeystore; } createTrustKeystore(sslContextBuilder, useTrustCert); //todo client key authentication should not depend on 'trustAllRoots' createKeystore(sslContextBuilder, useClientCert); } else { try { //need to override isTrusted() method to accept CA certs because the Apache HTTP Client ver.4.3 will only accepts self-signed certificates sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage() + ". " + TRUST_ALL_ROOTS_ERROR + trustAllRoots, e); } } sslContextBuilder.useSSL(); sslContextBuilder.useTLS(); SSLConnectionSocketFactory sslsf; try { String x509HostnameVerifierStr = x509HostnameVerifier.toLowerCase(); X509HostnameVerifier x509HostnameVerifier = null; switch (x509HostnameVerifierStr) { case "strict": x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; break; case "browser_compatible": x509HostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; break; case "allow_all": x509HostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; break; default: x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; } sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), x509HostnameVerifier); } catch (Exception e) { throw new RuntimeException(e.getMessage() + ". " + SSL_CONNECTION_ERROR, e); } return sslsf; }
From source file:com.codedx.burp.security.SSLConnectionSocketFactoryFactory.java
/** * Creates a new SSLConnectionSocketFactory with the behavior described in * {@link #getFactory(String)}. Instead of returning, this method registers * the factory instance to the <code>factoriesByHost<code> map, as well as * registering its <code>ExtraCertManager</code> to the * <code>certManagersByHost</code> map. The cert manager registration is * important in order to detect and purge trusted certificates on a per-host * basis.//from w w w. j a va2 s . c o m * * @param host * @param burpExtender * @throws IOException * @throws GeneralSecurityException */ private static void initializeFactory(String host, BurpExtender burpExtender) throws IOException, GeneralSecurityException { // set up the certificate management File managedKeyStoreFile = getTrustStoreForHost(host); ExtraCertManager certManager = new SingleExtraCertManager(managedKeyStoreFile, "u9lwIfUpaN"); // get the default hostname verifier that gets used by the modified one // and the invalid cert dialog HostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier(); InvalidCertificateStrategy invalidCertStrat = new InvalidCertificateDialogStrategy(defaultHostnameVerifier, host, burpExtender); /* * Set up a composite trust manager that uses the default trust manager * before delegating to the "reloadable" trust manager that allows users * to accept invalid certificates. */ List<X509TrustManager> trustManagersForComposite = new LinkedList<>(); X509TrustManager systemTrustManager = getDefaultTrustManager(); ReloadableX509TrustManager customTrustManager = new ReloadableX509TrustManager(certManager, invalidCertStrat); trustManagersForComposite.add(systemTrustManager); trustManagersForComposite.add(customTrustManager); X509TrustManager trustManager = new CompositeX509TrustManager(trustManagersForComposite); // setup the SSLContext using the custom trust manager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { trustManager }, null); // the actual hostname verifier that will be used with the socket // factory Set<String> allowedHosts = new HashSet<>(); allowedHosts.add(host); HostnameVerifier modifiedHostnameVerifier = new HostnameVerifierWithExceptions(defaultHostnameVerifier, allowedHosts); SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext, modifiedHostnameVerifier); // Register the `factory` and the `customTrustManager` under the given // `host` factoriesByHost.put(host, factory); customTrustByHost.put(host, customTrustManager); }
From source file:org.syslog_ng.elasticsearch_v2.client.http.ESHttpsClient.java
@Override protected void setupHttpClientBuilder(HttpClientConfig.Builder httpClientConfigBuilder, ElasticSearchOptions options) {/*from w w w . j av a 2 s. co m*/ SSLContextBuilder sslContextBuilder = setupSSLContextBuilder(options); SSLContext sslContext = buildSSLContext(sslContextBuilder); HostnameVerifier hostnameVerifier = setupHostnameVerifier(options); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier); httpClientConfigBuilder.sslSocketFactory(sslSocketFactory).httpsIOSessionStrategy(httpsIOSessionStrategy); }
From source file:net.shibboleth.idp.cas.proxy.impl.HttpClientProxyAuthenticator.java
private CloseableHttpClient createHttpClient(final TrustEngine<? super X509Credential> x509TrustEngine) { final SSLConnectionSocketFactory socketFactory; try {// w w w . java 2s .com final SSLContext sslContext = SSLContexts.custom().useTLS() .loadTrustMaterial(null, new TrustEngineTrustStrategy(x509TrustEngine)).build(); socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER); } catch (Exception e) { throw new RuntimeException("SSL initialization error", e); } final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(HTTPS_SCHEME, socketFactory).build(); final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry); return HttpClients.custom().setConnectionManager(connectionManager).build(); }
From source file:com.bosch.cr.examples.inventorybrowser.server.CustomProxyServlet.java
private synchronized CloseableHttpClient getHttpClient() { if (httpClient == null) { try {/* w w w . j av a2 s . c om*/ HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...) SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true) .build(); httpClientBuilder.setSSLContext(sslContext); // #### ONLY FOR TEST: Do NOT verify hostname SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory).build(); PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry); httpClientBuilder.setConnectionManager(httpClientConnectionManager); if (getConfig().getProperty("http.proxyHost") != null) { httpClientBuilder.setProxy(new HttpHost(getConfig().getProperty("http.proxyHost"), Integer.parseInt(getConfig().getProperty("http.proxyPort")))); } httpClient = httpClientBuilder.build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) { throw new RuntimeException(ex); } } return httpClient; }
From source file:org.elasticsearch.xpack.security.transport.ssl.SslIntegrationTests.java
public void testThatConnectionToHTTPWorks() throws Exception { Settings.Builder builder = Settings.builder(); addSSLSettingsForStore(builder,/*from ww w.ja va2 s .co m*/ "/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.jks", "testclient"); SSLService service = new SSLService(builder.build(), null); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(nodeClientUsername(), new String(nodeClientPassword().getChars()))); try (CloseableHttpClient client = HttpClients.custom() .setSSLSocketFactory(new SSLConnectionSocketFactory(service.sslSocketFactory(Settings.EMPTY), SSLConnectionSocketFactory.getDefaultHostnameVerifier())) .setDefaultCredentialsProvider(provider).build(); CloseableHttpResponse response = SocketAccess .doPrivileged(() -> client.execute(new HttpGet(getNodeUrl())))) { assertThat(response.getStatusLine().getStatusCode(), is(200)); String data = Streams .copyToString(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)); assertThat(data, containsString("You Know, for Search")); } }
From source file:org.apache.hadoop.gateway.shell.Hadoop.java
private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException { // SSL/* w w w. j a v a 2s . c om*/ HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; TrustStrategy trustStrategy = null; if (clientContext.connection().secure()) { hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); } else { trustStrategy = TrustSelfSignedStrategy.INSTANCE; System.out.println("**************** WARNING ******************\n" + "This is an insecure client instance and may\n" + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n" + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n" + "*******************************************"); } KeyStore trustStore = getTrustStore(); SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build(); // Pool PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(clientContext.pool().maxTotal()); connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute()); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setBufferSize(clientContext.connection().bufferSize()).build(); connectionManager.setDefaultConnectionConfig(connectionConfig); SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive()) .setSoLinger(clientContext.socket().linger()) .setSoReuseAddress(clientContext.socket().reuseAddress()) .setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay()) .build(); connectionManager.setDefaultSocketConfig(socketConfig); // Auth URI uri = URI.create(clientContext.url()); host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); CredentialsProvider credentialsProvider = null; if (clientContext.username() != null && clientContext.password() != null) { credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(clientContext.username(), clientContext.password())); AuthCache authCache = new BasicAuthCache(); BasicScheme authScheme = new BasicScheme(); authCache.put(host, authScheme); context = new BasicHttpContext(); context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache); } return HttpClients.custom().setConnectionManager(connectionManager) .setDefaultCredentialsProvider(credentialsProvider).build(); }
From source file:com.github.lpezet.antiope.dao.DefaultHttpClientFactory.java
@Override public HttpClient createHttpClient(APIConfiguration pConfiguration) { // Use a custom connection factory to customize the process of // initialization of outgoing HTTP connections. Beside standard connection // configuration parameters HTTP connection factory can define message // parser / writer routines to be employed by individual connections. HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory( new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory()); SSLContext oSslContext = null; X509HostnameVerifier oHostnameVerifier = null; if (pConfiguration.isCheckSSLCertificates()) { oSslContext = SSLContexts.createSystemDefault(); oHostnameVerifier = new BrowserCompatHostnameVerifier(); } else {//from w ww . j a va2s . c o m final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager try { final SSLContext sslContext = SSLContext.getInstance(SSL); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); oSslContext = sslContext; } catch (NoSuchAlgorithmException e) { throw new APIClientException(e); } catch (KeyManagementException e) { throw new APIClientException(e); } oHostnameVerifier = new AllowAllHostnameVerifier(); } // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register(HTTP, PlainConnectionSocketFactory.INSTANCE) .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build(); // Use custom DNS resolver to override the system DNS resolution. DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } };*/ // Create a connection manager with custom configuration. PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager( oSocketFactoryRegistry, oConnFactory, oDnsResolver); // Create socket configuration SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true) .setSoTimeout(pConfiguration.getSocketTimeout()).build(); // Configure the connection manager to use socket configuration either // by default or for a specific host. oConnManager.setDefaultSocketConfig(oSocketConfig); // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig); // Create message constraints MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); // Create connection configuration ConnectionConfig oConnectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(oMessageConstraints).build(); // Configure the connection manager to use connection configuration either // by default or for a specific host. oConnManager.setDefaultConnectionConfig(oConnectionConfig); // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); // Configure total max or per route limits for persistent connections // that can be kept in the pool or leased by the connection manager. oConnManager.setMaxTotal(100); oConnManager.setDefaultMaxPerRoute(10); //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); // Use custom cookie store if necessary. CookieStore oCookieStore = new BasicCookieStore(); // Use custom credentials provider if necessary. // // Create global request configuration RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) //.setExpectContinueEnabled(true) // WARNING: setting it to true slows things down by 4s!!!! .setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)) .setConnectTimeout(pConfiguration.getConnectionTimeout()).build(); CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider(); HttpHost oProxy = null; if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) { String proxyHost = pConfiguration.getProxyHost(); int proxyPort = pConfiguration.getProxyPort(); String proxyUsername = pConfiguration.getProxyUsername(); String proxyPassword = pConfiguration.getProxyPassword(); String proxyDomain = pConfiguration.getProxyDomain(); String proxyWorkstation = pConfiguration.getProxyWorkstation(); oProxy = new HttpHost(proxyHost, proxyPort); if (proxyUsername != null && proxyPassword != null) { oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } // Create an HttpClient with the given custom dependencies and configuration. CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager) .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider) .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build(); return oHttpClient; /* RequestConfig oRequestConfig = RequestConfig.custom() .setConnectTimeout(pConfiguration.getConnectionTimeout()) .setSocketTimeout(pConfiguration.getSocketTimeout()) .setStaleConnectionCheckEnabled(true) .build(); */ }