Java Code Examples for org.apache.http.ssl.SSLContextBuilder#build()

The following examples show how to use org.apache.http.ssl.SSLContextBuilder#build() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpClientFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 7 votes vote down vote up
protected SSLContext generateSSLContext() {
    SSLContextBuilder contextBuilder = SSLContexts.custom();
    try {
        if (getTrustStoreFile() != null) {
            contextBuilder.loadTrustMaterial(getTrustStoreFile(), getTrustStorePassword(), getTrustStrategy());
        }

        if (getKeyStoreFile() != null) {
            contextBuilder.loadKeyMaterial(getKeyStoreFile(), getKeyStorePassword(), getKeyPassword(), getPrivateKeyStrategy());
        }

        return contextBuilder.build();
    } catch (GeneralSecurityException | IOException e) {
        throw new RuntimeException("Unable to configure SSL", e);
    }
}
 
Example 2
Source File: TruststoreSSLContextUtils.java    From knox with Apache License 2.0 6 votes vote down vote up
public static SSLContext getTruststoreSSLContext(KeystoreService keystoreService) {
  SSLContext sslContext = null;
  try {
    if(keystoreService != null) {
      KeyStore truststore = keystoreService.getTruststoreForHttpClient();
      if (truststore != null) {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        sslContextBuilder.loadTrustMaterial(truststore, null);
        sslContext = sslContextBuilder.build();
      }
    }
  } catch (KeystoreServiceException | NoSuchAlgorithmException | KeyStoreException
               | KeyManagementException e) {
    LOGGER.failedToLoadTruststore(e.getMessage(), e);
  }
  return sslContext;
}
 
Example 3
Source File: ValidatorController.java    From validator-badge with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient getCarelessHttpClient(boolean disableRedirect) {
    CloseableHttpClient httpClient = null;

    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
        HttpClientBuilder httpClientBuilder = HttpClients
                .custom()
                .setSSLSocketFactory(sslsf);
        if (disableRedirect) {
            httpClientBuilder.disableRedirectHandling();
        }
        httpClientBuilder.setUserAgent("swagger-validator");
        httpClient = httpClientBuilder.build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        LOGGER.error("can't disable SSL verification", e);
    }

    return httpClient;
}
 
Example 4
Source File: IftttIndegoAdapter.java    From iot-device-bosch-indego-controller with Apache License 2.0 6 votes vote down vote up
/**
 * This creates a HTTP client instance for connecting the IFTTT server.
 * 
 * @return the HTTP client instance
 */
private CloseableHttpClient buildHttpClient ()
{
    if ( configuration.isIftttIgnoreServerCertificate() ) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted (X509Certificate[] chain_, String authType_) throws CertificateException
                {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        }
        catch (Exception ex) {
            LOG.error(ex);
            // This should never happen, but we have to handle it
            throw new RuntimeException(ex);
        }
    }
    else {
        return HttpClients.createDefault();
    }
}
 
Example 5
Source File: HttpsFactory.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private synchronized SSLContext createSecureSslContext() {
    if (secureSslContext == null) {
        log.debug("Protocol: {}", config.getProtocol());
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        try {
            loadTrustMaterial(sslContextBuilder);
            loadKeyMaterial(sslContextBuilder);
            secureSslContext = sslContextBuilder.build();
            validateSslConfig();
            return secureSslContext;
        } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
                | UnrecoverableKeyException | KeyManagementException e) {
            apimlLog.log("org.zowe.apiml.common.sslContextInitializationError", e.getMessage());
            throw new HttpsConfigError("Error initializing SSL Context: " + e.getMessage(), e,
                    ErrorCode.HTTP_CLIENT_INITIALIZATION_FAILED, config);
        }
    } else {
        return secureSslContext;
    }
}
 
Example 6
Source File: HttpUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void setSkipCertificateValidation() {
    if (!tlsWarningEmitted.getAndSet(true)) {
        // Since this is a static util, it may happen that TLS is setup many times in one command
        // invocation (e.g. when a command requires logging in). However, we would like to
        // prevent this warning from appearing multiple times. That's why we need to guard it with a boolean.
        System.err.println("The server is configured to use TLS but there is no truststore specified.");
        System.err.println("The tool will skip certificate validation. This is highly discouraged for production use cases");
    }

    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build());
    } catch (Exception e) {
        throw new RuntimeException("Failed setting up TLS", e);
    }
}
 
Example 7
Source File: SecurityUtils.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
public static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    final char[] pwd = password.toCharArray();
    SSLContextBuilder sslcontextBuilder = SSLContexts.custom()
            .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)
    ;
    if (keystoreFile != null) {
        sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
    }

    sslcontextBuilder.setProtocol("TLSv1.2");

    return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
        @Override
        public boolean verify(final String s, final SSLSession sslSession) {
            return true;
        }
    });
}
 
Example 8
Source File: SecurityUtils.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    final char[] pwd = password.toCharArray();
    SSLContextBuilder sslcontextBuilder = SSLContexts.custom()//
            .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)//
    ;
    if (keystoreFile != null) {
        sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
    }

    return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
        @Override
        public boolean verify(final String s, final SSLSession sslSession) {
            return true;
        }
    });
}
 
Example 9
Source File: TemplateManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
CloseableHttpClient getHttpsClient()
{
    try
    {
        RequestConfig config = RequestConfig.custom().setSocketTimeout( 5000 ).setConnectTimeout( 5000 ).build();

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial( null, ( TrustStrategy ) ( x509Certificates, s ) -> true );
        SSLConnectionSocketFactory sslSocketFactory =
                new SSLConnectionSocketFactory( sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE );

        return HttpClients.custom().setDefaultRequestConfig( config ).setSSLSocketFactory( sslSocketFactory )
                          .build();
    }
    catch ( Exception e )
    {
        LOG.error( e.getMessage() );
    }

    return HttpClients.createDefault();
}
 
Example 10
Source File: HttpUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void setSkipCertificateValidation() {
    if (!tlsWarningEmitted.getAndSet(true)) {
        // Since this is a static util, it may happen that TLS is setup many times in one command
        // invocation (e.g. when a command requires logging in). However, we would like to
        // prevent this warning from appearing multiple times. That's why we need to guard it with a boolean.
        System.err.println("The server is configured to use TLS but there is no truststore specified.");
        System.err.println("The tool will skip certificate validation. This is highly discouraged for production use cases");
    }

    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build());
    } catch (Exception e) {
        throw new RuntimeException("Failed setting up TLS", e);
    }
}
 
Example 11
Source File: ServerHttpsRequestIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	this.server.setHandler(new CheckRequestHandler());
	this.server.afterPropertiesSet();
	this.server.start();

	// Set dynamically chosen port
	this.port = this.server.getPort();

	SSLContextBuilder builder = new SSLContextBuilder();
	builder.loadTrustMaterial(new TrustSelfSignedStrategy());
	SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
			builder.build(), NoopHostnameVerifier.INSTANCE);
	CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
			socketFactory).build();
	HttpComponentsClientHttpRequestFactory requestFactory =
			new HttpComponentsClientHttpRequestFactory(httpclient);
	this.restTemplate = new RestTemplate(requestFactory);
}
 
Example 12
Source File: ClientProvider.java    From james-project with Apache License 2.0 6 votes vote down vote up
private SSLContext sslContext() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException,
    CertificateException, IOException {

    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    SSLValidationStrategy strategy = configuration.getSslConfiguration()
        .getStrategy();

    switch (strategy) {
        case DEFAULT:
            return sslContextBuilder.build();
        case IGNORE:
            return sslContextBuilder.loadTrustMaterial(TRUST_ALL)
                .build();
        case OVERRIDE:
            return applyTrustStore(sslContextBuilder)
                .build();
        default:
            throw new NotImplementedException(
                String.format("unrecognized strategy '%s'", strategy.name()));
    }
}
 
Example 13
Source File: AzkabanAjaxAPIClient.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private static CloseableHttpClient getHttpClient()
    throws IOException {
  try {
    // Self sign SSL
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

    // Create client
    return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCookieStore(new BasicCookieStore()).build();
  } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
    throw new IOException("Issue with creating http client", e);
  }
}
 
Example 14
Source File: BasicHttpsSecurityApplicationTests.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
private SSLConnectionSocketFactory socketFactory() throws Exception {
	char[] password = "password".toCharArray();
	KeyStore truststore = KeyStore.getInstance("PKCS12");
	truststore.load(new ClassPathResource("rod.p12").getInputStream(), password);
	SSLContextBuilder builder = new SSLContextBuilder();
	builder.loadKeyMaterial(truststore, password);
	builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
	return new SSLConnectionSocketFactory(builder.build(),
			new NoopHostnameVerifier());
}
 
Example 15
Source File: PostHTTP.java    From nifi with Apache License 2.0 5 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
        final String alias = keystore.aliases().nextElement();
        final Certificate cert = keystore.getCertificate(alias);
        if (cert instanceof X509Certificate) {
            principal = ((X509Certificate) cert).getSubjectDN();
        }
    }

    builder = builder.setProtocol(service.getSslAlgorithm());

    final SSLContext sslContext = builder.build();
    return sslContext;
}
 
Example 16
Source File: SSLTruststoreUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static HttpClient getHttpClientWithSSL(File keyStoreFile, String keyStorePassword, String keyStoreProvider,
        File trustStoreFile, String trustStorePassword, String trustStoreProvider) {

    try {
        KeyStore trustStore = KeyStore.getInstance(trustStoreProvider);
        try (FileInputStream fis = new FileInputStream(trustStoreFile)) {
            trustStore.load(fis, trustStorePassword.toCharArray());
        }
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .setProtocol("TLS")
                .loadTrustMaterial(trustStore, null);
        if (keyStoreFile != null) {
            KeyStore keyStore = KeyStore.getInstance(keyStoreProvider);
            try (FileInputStream fis = new FileInputStream(keyStoreFile)) {
                keyStore.load(fis, keyStorePassword.toCharArray());
            }
            sslContextBuilder.loadKeyMaterial(keyStore, keyStorePassword.toCharArray(), null);
        }
        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", socketFactory)
                .build();

        return HttpClientBuilder.create()
                .setSSLSocketFactory(socketFactory)
                        //.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setConnectionManager(new PoolingHttpClientConnectionManager(registry))
                .setSchemePortResolver(new DefaultSchemePortResolver())
                .build();

    } catch (Exception e) {
        LOGGER.error("Creating HttpClient with customized SSL failed. We are returning the default one instead.", e);
        return HttpClients.createDefault();
    }
}
 
Example 17
Source File: HttpClientBuilders.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Return an {@link HttpClientBuilder} that can be used to build an {@link HttpClient} which trusts all certificates
 * (particularly including self-signed certificates).
 *
 * @return a {@link HttpClientBuilder} for <i>SSL trust all</i>
 */
public static HttpClientBuilder getSSLTrustAllHttpClientBuilder() {
	try {
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(null, (X509Certificate[] chain, String authType) -> true);

		HostnameVerifier hostNameVerifier = (String hostname, SSLSession session) -> true;
		SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(), hostNameVerifier);

		return HttpClients.custom().setSSLSocketFactory(sslSF).useSystemProperties();
	} catch (Exception e) {
		// key management exception, etc.
		throw new RuntimeException(e);
	}
}
 
Example 18
Source File: SslTest.java    From rest-utils with Apache License 2.0 4 votes vote down vote up
private int makeGetRequest(String url, String clientKeystoreLocation, String clientKeystorePassword,
                           String clientKeyPassword)
    throws Exception {
  log.debug("Making GET " + url);
  HttpGet httpget = new HttpGet(url);
  CloseableHttpClient httpclient;
  if (url.startsWith("http://")) {
    httpclient = HttpClients.createDefault();
  } else {
    // trust all self-signed certs.
    SSLContextBuilder sslContextBuilder = SSLContexts.custom()
            .loadTrustMaterial(new TrustSelfSignedStrategy());

    // add the client keystore if it's configured.
    if (clientKeystoreLocation != null) {
      sslContextBuilder.loadKeyMaterial(new File(clientKeystoreLocation),
              clientKeystorePassword.toCharArray(),
              clientKeyPassword.toCharArray());
    }
    SSLContext sslContext = sslContextBuilder.build();

    SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"},
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    httpclient = HttpClients.custom()
            .setSSLSocketFactory(sslSf)
            .build();
  }

  int statusCode = -1;
  CloseableHttpResponse response = null;
  try {
    response = httpclient.execute(httpget);
    statusCode = response.getStatusLine().getStatusCode();
  } finally {
    if (response != null) {
      response.close();
    }
    httpclient.close();
  }
  return statusCode;
}
 
Example 19
Source File: SettingsBasedSSLConfiguratorTest.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private SSLContext createSSLContext(String trustStorePath, String keyStorePath, String password) {

            try {
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                KeyStore trustStore = KeyStore.getInstance("JKS");
                InputStream trustStream = new FileInputStream(
                        FileHelper.getAbsoluteFilePathFromClassPath(trustStorePath).toFile());
                trustStore.load(trustStream, password.toCharArray());
                tmf.init(trustStore);

                KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                KeyStore keyStore = KeyStore.getInstance("JKS");

                Path path = FileHelper.getAbsoluteFilePathFromClassPath(keyStorePath);

                if (path == null) {
                    throw new RuntimeException("Could not find " + keyStorePath);
                }

                InputStream keyStream = new FileInputStream(path.toFile());

                keyStore.load(keyStream, password.toCharArray());
                kmf.init(keyStore, password.toCharArray());

                SSLContextBuilder sslContextBuilder = SSLContexts.custom();

                sslContextBuilder.loadTrustMaterial(trustStore, null);

                sslContextBuilder.loadKeyMaterial(keyStore, password.toCharArray(), new PrivateKeyStrategy() {

                    @Override
                    public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                        return "node1";
                    }
                });

                return sslContextBuilder.build();
            } catch (GeneralSecurityException | IOException e) {
                throw new RuntimeException(e);
            }
        }
 
Example 20
Source File: HttpClient.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private final HttpAsyncClientBuilder asyncClientBuilder(HttpAsyncClientBuilder httpClientBuilder)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {

    // basic auth
    // pki auth

    if (ssl) {

        final SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        if (log.isTraceEnabled()) {
            log.trace("Configure HTTP client with SSL");
        }

        if (trustStore != null) {
            sslContextBuilder.loadTrustMaterial(trustStore, null);
        }

        if (keystore != null) {
            sslContextBuilder.loadKeyMaterial(keystore, keyPassword, new PrivateKeyStrategy() {

                @Override
                public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                    if(aliases == null || aliases.isEmpty()) {
                        return keystoreAlias;
                    }

                    if(keystoreAlias == null || keystoreAlias.isEmpty()) {
                        return aliases.keySet().iterator().next();
                    }

                    return keystoreAlias;                    }
            });
        }

        final HostnameVerifier hnv = verifyHostnames?new DefaultHostnameVerifier():NoopHostnameVerifier.INSTANCE;

        final SSLContext sslContext = sslContextBuilder.build();
        httpClientBuilder.setSSLStrategy(new SSLIOSessionStrategy(
                sslContext,
                supportedProtocols,
                supportedCipherSuites,
                hnv
                ));
    }

    if (basicCredentials != null) {
        httpClientBuilder.setDefaultHeaders(Lists.newArrayList(new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicCredentials)));
    }

    // TODO: set a timeout until we have a proper way to deal with back pressure
    int timeout = 5;

    RequestConfig config = RequestConfig.custom()
      .setConnectTimeout(timeout * 1000)
      .setConnectionRequestTimeout(timeout * 1000)
      .setSocketTimeout(timeout * 1000).build();

    httpClientBuilder.setDefaultRequestConfig(config);

    return httpClientBuilder;

}