List of usage examples for org.apache.http.ssl SSLContexts custom
public static SSLContextBuilder custom()
From source file:org.openbaton.sdk.api.util.RestRequest.java
private CloseableHttpClient getHttpClientForSsl() { SSLContext sslContext = null; try {//ww w . ja v a 2s. c om sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); } catch (NoSuchAlgorithmException e) { log.error("Could not initialize the HttpClient for SSL connections"); log.error(e.getMessage(), e); } catch (KeyManagementException e) { log.error("Could not initialize the HttpClient for SSL connections"); log.error(e.getMessage(), e); } catch (KeyStoreException e) { log.error("Could not initialize the HttpClient for SSL connections"); log.error(e.getMessage(), e); } // necessary to trust self signed certificates SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, new NoopHostnameVerifier()); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionSocketFactory).build(); return HttpClientBuilder.create().setDefaultRequestConfig(config) .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry)) .setSSLSocketFactory(sslConnectionSocketFactory).build(); }
From source file:org.openbaton.marketplace.core.VNFPackageManagement.java
private CloseableHttpClient getHttpClientForSsl(RequestConfig config) { SSLContext sslContext = null; try {/*from w ww . j av a 2 s . c o m*/ sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); } catch (NoSuchAlgorithmException e) { log.error("Could not initialize the HttpClient for SSL connections"); log.error(e.getMessage(), e); } catch (KeyManagementException e) { log.error("Could not initialize the HttpClient for SSL connections"); log.error(e.getMessage(), e); } catch (KeyStoreException e) { log.error("Could not initialize the HttpClient for SSL connections"); log.error(e.getMessage(), e); } // necessary to trust self signed certificates SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, new NoopHostnameVerifier()); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionSocketFactory).build(); return HttpClientBuilder.create().setDefaultRequestConfig(config) .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry)) .setSSLSocketFactory(sslConnectionSocketFactory).build(); }
From source file:org.apache.ofbiz.base.util.UtilHttp.java
public static CloseableHttpClient getAllowAllHttpClient(String jksStoreFileName, String jksStorePassword) { try {// ww w. j a va 2s.c om // Trust own CA and all self-signed certs SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(FileUtil.getFile(jksStoreFileName), jksStorePassword.toCharArray(), new TrustSelfSignedStrategy()).build(); // No host name verifier SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpClient; } catch (Exception e) { return HttpClients.createDefault(); } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
private void setUpSSL() throws InvalidArgumentException { if (cryptoPrimitives == null) { try {/*from w w w . j a v a2 s. com*/ cryptoPrimitives = new CryptoPrimitives(); cryptoPrimitives.init(); } catch (Exception e) { throw new InvalidArgumentException(e); } } if (isSSL && null == registry) { if (!properties.containsKey("pemBytes") && !properties.containsKey("pemFile")) { logger.warn("SSL with no CA certficates in either pemBytes or pemFile"); } try { if (properties.containsKey("pemBytes")) { byte[] permbytes = (byte[]) properties.get("pemBytes"); try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(permbytes))) { cryptoPrimitives.addCACertificatesToTrustStore(bis); } } if (properties.containsKey("pemFile")) { String pemFile = properties.getProperty("pemFile"); if (pemFile != null) { String[] pems = pemFile.split("[ \t]*,[ \t]*"); for (String pem : pems) { if (null != pem && !pem.isEmpty()) { try { try (BufferedInputStream bis = new BufferedInputStream( new ByteArrayInputStream(Files.readAllBytes(Paths.get(pem))))) { cryptoPrimitives.addCACertificatesToTrustStore(bis); } } catch (IOException e) { throw new InvalidArgumentException( format("Unable to add CA certificate, can't open certificate file %s", new File(pem).getAbsolutePath())); } } } } } SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(cryptoPrimitives.getTrustStore(), null).build(); ConnectionSocketFactory sf; if (null != properties && "true".equals(properties.getProperty("allowAllHostNames"))) { AllHostsSSLSocketFactory msf = new AllHostsSSLSocketFactory(cryptoPrimitives.getTrustStore()); msf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); sf = msf; } else { sf = new SSLConnectionSocketFactory(sslContext); } registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sf) .register("http", new PlainConnectionSocketFactory()).build(); } catch (Exception e) { logger.error(e); throw new InvalidArgumentException(e); } } }
From source file:ddf.test.itests.platform.TestSecurity.java
private HttpClient createHttpClient(String protocol, String[] cipherSuites, CredentialsProvider credentialsProvider) throws KeyManagementException, NoSuchAlgorithmException { SSLContext context = SSLContexts.custom().useProtocol(protocol).build(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context, null, cipherSuites, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider) .setSSLSocketFactory(socketFactory).build(); }
From source file:org.apache.gobblin.elasticsearch.writer.ElasticsearchRestWriter.java
private static RestClient buildRestClient(List<InetSocketTransportAddress> hosts, int threadCount, boolean sslEnabled, String keyStoreType, String keyStoreFilePassword, String identityFilepath, String trustStoreType, String trustStoreFilePassword, String cacertsFilepath) throws Exception { HttpHost[] httpHosts = new HttpHost[hosts.size()]; String scheme = sslEnabled ? "https" : "http"; for (int h = 0; h < httpHosts.length; h++) { InetSocketTransportAddress host = hosts.get(h); httpHosts[h] = new HttpHost(host.getAddress(), host.getPort(), scheme); }/*from w w w .j a v a 2 s. co m*/ RestClientBuilder builder = RestClient.builder(httpHosts); if (sslEnabled) { log.info("ssl configuration: trustStoreType = {}, cacertsFilePath = {}", trustStoreType, cacertsFilepath); KeyStore truststore = KeyStore.getInstance(trustStoreType); FileInputStream trustInputStream = new FileInputStream(cacertsFilepath); try { truststore.load(trustInputStream, trustStoreFilePassword.toCharArray()); } finally { trustInputStream.close(); } SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(truststore, null); log.info("ssl key configuration: keyStoreType = {}, keyFilePath = {}", keyStoreType, identityFilepath); KeyStore keystore = KeyStore.getInstance(keyStoreType); FileInputStream keyInputStream = new FileInputStream(identityFilepath); try { keystore.load(keyInputStream, keyStoreFilePassword.toCharArray()); } finally { keyInputStream.close(); } sslBuilder.loadKeyMaterial(keystore, keyStoreFilePassword.toCharArray()); final SSLContext sslContext = sslBuilder.build(); builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder // Set ssl context .setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()) // Configure number of threads for clients .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build())); } else { builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder // Configure number of threads for clients .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build())); } // Configure timeouts builder.setRequestConfigCallback( requestConfigBuilder -> requestConfigBuilder.setConnectionRequestTimeout(0)); // Important, otherwise the client has spurious timeouts return builder.build(); }
From source file:org.apache.hive.jdbc.HiveConnection.java
private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException { boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null || (!JdbcConnectionParams.COOKIE_AUTH_FALSE .equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH))); String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2 : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME); CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null; HttpClientBuilder httpClientBuilder; // Request interceptor for any request pre-processing logic HttpRequestInterceptor requestInterceptor; Map<String, String> additionalHttpHeaders = new HashMap<String, String>(); // Retrieve the additional HttpHeaders for (Map.Entry<String, String> entry : sessConfMap.entrySet()) { String key = entry.getKey(); if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) { additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()), entry.getValue());//from w w w . j a v a 2 s .com } } // Configure http client for kerberos/password based authentication if (isKerberosAuthMode()) { /** * Add an interceptor which sets the appropriate header in the request. * It does the kerberos authentication and get the final service ticket, * for sending to the server before every request. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpKerberosRequestInterceptor( sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { // Check for delegation token, if present add it in the header String tokenStr = getClientDelegationToken(sessConfMap); if (tokenStr != null) { requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { /** * Add an interceptor to pass username/password in the header. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders); } } // Configure http client for cookie based authentication if (isCookieEnabled) { // Create a http client with a retry mechanism when the server returns a status code of 401. httpClientBuilder = HttpClients.custom() .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() { @Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { int statusCode = response.getStatusLine().getStatusCode(); boolean ret = statusCode == 401 && executionCount <= 1; // Set the context attribute to true which will be interpreted by the request // interceptor if (ret) { context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE); } return ret; } @Override public long getRetryInterval() { // Immediate retry return 0; } }); } else { httpClientBuilder = HttpClientBuilder.create(); } // In case the server's idletimeout is set to a lower value, it might close it's side of // connection. However we retry one more time on NoHttpResponseException httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount > 1) { LOG.info("Retry attempts to connect to server exceeded."); return false; } if (exception instanceof org.apache.http.NoHttpResponseException) { LOG.info("Could not connect to the server. Retrying one more time."); return true; } return false; } }); // Add the request interceptor to the client builder httpClientBuilder.addInterceptorFirst(requestInterceptor); // Add an interceptor to add in an XSRF header httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor()); // Configure http client for SSL if (useSsl) { String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL); String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE); String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD); KeyStore sslTrustStore; SSLConnectionSocketFactory socketFactory; SSLContext sslContext; /** * The code within the try block throws: SSLInitializationException, KeyStoreException, * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException & * UnrecoverableKeyException. We don't want the client to retry on any of these, * hence we catch all and throw a SQLException. */ try { if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) { socketFactory = getTwoWaySSLSocketFactory(); } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) { // Create a default socket factory based on standard JSSE trust material socketFactory = SSLConnectionSocketFactory.getSocketFactory(); } else { // Pick trust store config from the given path sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE); try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) { sslTrustStore.load(fis, sslTrustStorePassword.toCharArray()); } sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build(); socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null)); } final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", socketFactory).build(); httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } catch (Exception e) { String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage(); throw new SQLException(msg, " 08S01", e); } } return httpClientBuilder.build(); }
From source file:org.finra.herd.dao.helper.HttpClientHelper.java
/** * Creates a new HTTP client./* w w w .j av a 2 s .c o m*/ * * @param trustSelfSignedCertificate specifies whether to trust a self-signed certificate * @param disableHostnameVerification specifies whether to turn off hostname verification * * @return the HTTP client * @throws KeyStoreException if a key store exception occurs * @throws NoSuchAlgorithmException if a no such algorithm exception occurs * @throws KeyManagementException if key management exception */ public CloseableHttpClient createHttpClient(Boolean trustSelfSignedCertificate, Boolean disableHostnameVerification) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { // Create an HTTP client builder. HttpClientBuilder httpClientBuilder = HttpClients.custom(); // Create an SSL context builder. SSLContextBuilder sslContextBuilder = SSLContexts.custom(); // If specified, setup a trust strategy that allows all certificates. if (BooleanUtils.isTrue(trustSelfSignedCertificate)) { sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); } // If specified, turn hostname verification off. HostnameVerifier hostnameVerifier = BooleanUtils.isTrue(disableHostnameVerification) ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; // Create and assign an SSL connection socket factory. SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build(), hostnameVerifier); httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory); // Build and return an HTTP client. return httpClientBuilder.build(); }
From source file:org.geoserver.wps.remote.plugin.XMPPClient.java
@Override public void init() throws Exception { // Initializes the XMPP Client and starts the communication. It also // register GeoServer as "manager" to the service channels on the MUC // (Multi/* ww w . ja va 2 s .c om*/ // User Channel) Rooms LOGGER.info(String.format("Initializing connection to server %1$s port %2$d", server, port)); int packetReplyTimeout = DEFAULT_PACKET_REPLY_TIMEOUT; if (getConfiguration().get("xmpp_packet_reply_timeout") != null) { packetReplyTimeout = Integer.parseInt(getConfiguration().get("xmpp_packet_reply_timeout")); } SmackConfiguration.setDefaultPacketReplyTimeout(packetReplyTimeout); config = new ConnectionConfiguration(server, port); checkSecured(getConfiguration()); // Trust own CA and all self-signed certs SSLContext sslcontext = null; if (this.certificateFile != null && this.certificatePassword != null) { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(this.certificateFile); try { trustStore.load(instream, this.certificatePassword.toCharArray()); } finally { instream.close(); } sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); } if (sslcontext != null) { // config.setSASLAuthenticationEnabled(false); config.setSecurityMode(SecurityMode.enabled); config.setCustomSSLContext(sslcontext); } else { config.setSecurityMode(SecurityMode.disabled); } // Actually performs the connection to the XMPP Server for (int testConn = 0; testConn < 5; testConn++) { try { // Try first the TCP Endpoint connection = new XMPPTCPConnection(config); connection.connect(); break; } catch (NoResponseException e) { connection = null; if (testConn >= 5) { LOGGER.warning( "No XMPP TCP Endpoint available or could not get any response from the Server. Falling back to BOSH Endpoint."); } else { LOGGER.log(Level.WARNING, "Tentative #" + (testConn + 1) + " - Error while trying to connect to XMPP TCP Endpoint.", e); Thread.sleep(500); } } } if (connection == null || !connection.isConnected()) { for (int testConn = 0; testConn < 5; testConn++) { try { // Falling back to BOSH Endpoint BOSHConfiguration boshConfig = new BOSHConfiguration((sslcontext != null), server, port, null, getConfiguration().get("xmpp_domain")); if (sslcontext != null) { // boshConfig.setSASLAuthenticationEnabled(false); boshConfig.setSecurityMode(SecurityMode.enabled); boshConfig.setCustomSSLContext(sslcontext); } else { boshConfig.setSecurityMode(SecurityMode.disabled); } connection = new XMPPBOSHConnection(boshConfig); connection.connect(); break; } catch (NoResponseException e) { connection = null; if (testConn >= 5) { LOGGER.warning( "No XMPP BOSH Endpoint available or could not get any response from the Server. The XMPP Client won't be available."); } else { LOGGER.log(Level.WARNING, "Tentative #" + (testConn + 1) + " - Error while trying to connect to XMPP BOSH Endpoint.", e); Thread.sleep(500); } } } } LOGGER.info("Connected: " + connection.isConnected()); // Check if the connection to the XMPP server is successful; the login // and registration is not yet performed at this time if (connection.isConnected()) { chatManager = ChatManager.getInstanceFor(connection); discoStu = ServiceDiscoveryManager.getInstanceFor(connection); // Add features to our XMPP client discoProperties(); // Performs login with "admin" user credentials performLogin(getConfiguration().get("xmpp_manager_username"), getConfiguration().get("xmpp_manager_password")); // Start "ping" task in order to maintain alive the connection startPingTask(); // Send invitation to the registered endpoints sendInvitations(); // getEndpointsLoadAverages(); // checkPendingRequests(); } else { setEnabled(false); LOGGER.warning("Not connected! The XMPP client has been disabled."); } }