org.apache.http.nio.conn.ssl.SSLIOSessionStrategy Java Examples

The following examples show how to use org.apache.http.nio.conn.ssl.SSLIOSessionStrategy. 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 log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
public HttpClientFactory build() {

            if (this.sslSocketFactory == null) {
                this.sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            }
            if (this.plainSocketFactory == null) {
                this.plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
            }
            if (this.httpIOSessionStrategy == null) {
                this.httpIOSessionStrategy = NoopIOSessionStrategy.INSTANCE;
            }
            if (this.httpsIOSessionStrategy == null) {
                this.httpsIOSessionStrategy = SSLIOSessionStrategy.getSystemDefaultStrategy();
            }

            return new HttpClientFactory(this);
        }
 
Example #2
Source File: JKSCertInfo.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void applyTo(HttpClientConfig.Builder clientConfigBuilder) {

    try (
            FileInputStream keystoreFile = new FileInputStream(new File(keystorePath));
            FileInputStream truststoreFile = new FileInputStream(new File(truststorePath))
    ) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(keystoreFile, keystorePassword.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keystorePassword.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("jks");
        trustStore.load(truststoreFile, truststorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        clientConfigBuilder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        clientConfigBuilder.httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }
}
 
Example #3
Source File: PEMCertInfo.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void applyTo(HttpClientConfig.Builder builder) {

    if (java.security.Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    try (
            FileInputStream clientCert = new FileInputStream(new File(clientCertPath));
            FileInputStream key = new FileInputStream(new File(keyPath));
            FileInputStream certificateAuthoritiies = new FileInputStream(new File(caPath))
    ) {
        KeyStore keyStore = PemReader.loadKeyStore(clientCert, key, Optional.ofNullable(keyPassphrase));
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyPassphrase.toCharArray());

        KeyStore trustStore = PemReader.loadTrustStore(certificateAuthoritiies);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        builder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        builder.httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }

}
 
Example #4
Source File: JKSCertInfo.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void applyTo(HttpClientFactory.Builder httpClientFactoryBuilder) {

    try (
            FileInputStream keystoreFile = new FileInputStream(new File(keystorePath));
            FileInputStream truststoreFile = new FileInputStream(new File(truststorePath))
    ) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(keystoreFile, keystorePassword.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keystorePassword.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("jks");
        trustStore.load(truststoreFile, truststorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        httpClientFactoryBuilder.withSslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        httpClientFactoryBuilder.withHttpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }
}
 
Example #5
Source File: PEMCertInfo.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void applyTo(HttpClientFactory.Builder builder) {

    if (java.security.Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        java.security.Security.addProvider(new BouncyCastleProvider());
    }

    try (
            FileInputStream clientCert = new FileInputStream(new File(clientCertPath));
            FileInputStream key = new FileInputStream(new File(keyPath));
            FileInputStream certificateAuthoritiies = new FileInputStream(new File(caPath))
    ) {
        KeyStore keyStore = PemReader.loadKeyStore(clientCert, key, Optional.ofNullable(keyPassphrase));
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyPassphrase.toCharArray());

        KeyStore trustStore = PemReader.loadTrustStore(certificateAuthoritiies);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        builder.withSslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        builder.withHttpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }

}
 
Example #6
Source File: AsyncClientCustomSSL.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public final static void main(String[] args) throws Exception {
    // KeyStore trustStore =
    // KeyStore.getInstance(KeyStore.getDefaultType());
    // FileInputStream instream = new FileInputStream(new
    // File("my.keystore"));
    // try {
    // trustStore.load(instream, "nopassword".toCharArray());
    // } finally {
    // instream.close();
    // }
    // // Trust own CA and all self-signed certs
    // SSLContext sslcontext =
    // SSLContexts.custom().loadTrustMaterial(trustStore, new
    // TrustSelfSignedStrategy())
    // .build();
    SSLContext sslcontext = SSLContexts.createDefault();
    // Allow TLSv1 protocol only
    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new String[] { "TLSv1" }, null,
            SSLIOSessionStrategy.getDefaultHostnameVerifier());
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).build();
    try {
        httpclient.start();
        HttpGet request = new HttpGet("https://github.com/dzh");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example #7
Source File: RestClient.java    From light with Apache License 2.0 5 votes vote down vote up
private Registry<SchemeIOSessionStrategy> asyncRegistry() throws Exception {
    // Allow TLSv1 protocol only
    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(
            sslContext(),
            new String[] { "TLSv1" },
            null,
            hostnameVerifier());

    // Create a registry of custom connection session strategies for supported
    // protocol schemes.
    return RegistryBuilder.<SchemeIOSessionStrategy>create()
            .register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", sslSessionStrategy)
            .build();
}
 
Example #8
Source File: DefaultEsClientFactory.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the SSL connection to use certificates by setting the keystores
 * @param httpConfig the http client configuration
 * @param config the configuration
 */
@SuppressWarnings("nls")
private void updateSslConfig(Builder httpConfig, Map<String, String> config) {
    try {
        String clientKeystorePath = config.get("client.keystore");
        String clientKeystorePassword = config.get("client.keystore.password");
        String trustStorePath = config.get("client.truststore");
        String trustStorePassword = config.get("client.truststore.password");

        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();

        String trustCertificate = config.get("client.trust.certificate");
        if (!StringUtils.isBlank(trustCertificate) && trustCertificate.equals("true")) {
            sslContextBuilder = sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy());
        }

        SSLContext sslContext = sslContextBuilder.build();
        Info kPathInfo = new Info(clientKeystorePath, clientKeystorePassword);
        Info tPathInfo = new Info(trustStorePath, trustStorePassword);
        sslContext.init(KeyStoreUtil.getKeyManagers(kPathInfo), KeyStoreUtil.getTrustManagers(tPathInfo), new SecureRandom());

        String trustHost = config.get("client.trust.host");
        HostnameVerifier hostnameVerifier = !StringUtils.isBlank(trustHost) && trustHost.equals("true") ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

        httpConfig.defaultSchemeForDiscoveredNodes("https");
        httpConfig.sslSocketFactory(sslSocketFactory); // for sync calls
        httpConfig.httpsIOSessionStrategy(httpsIOSessionStrategy); // for async calls

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: SettingsBasedSSLConfigurator.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
public SSLIOSessionStrategy toSSLIOSessionStrategy() {
    return new SSLIOSessionStrategy(sslContext, supportedProtocols, supportedCipherSuites, hostnameVerifier);
}
 
Example #10
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;

}
 
Example #11
Source File: AbstractHttpClientGenerator.java    From cetty with Apache License 2.0 4 votes vote down vote up
protected SSLIOSessionStrategy buildSSLIOSessionStrategy() {
    SSLContext sslcontext = SSLContexts.createDefault();
    return new SSLIOSessionStrategy(sslcontext);
}
 
Example #12
Source File: AutoCleanedPoolingNHttpClientConnectionManager.java    From caravan with Apache License 2.0 4 votes vote down vote up
protected static Registry<SchemeIOSessionStrategy> getDefaultRegistry() {
    return RegistryBuilder.<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", SSLIOSessionStrategy.getDefaultStrategy()).build();
}
 
Example #13
Source File: ElasticsearchIO.java    From beam with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
RestClient createClient() throws IOException {
  HttpHost[] hosts = new HttpHost[getAddresses().size()];
  int i = 0;
  for (String address : getAddresses()) {
    URL url = new URL(address);
    hosts[i] = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    i++;
  }
  RestClientBuilder restClientBuilder = RestClient.builder(hosts);
  if (getUsername() != null) {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
        AuthScope.ANY, new UsernamePasswordCredentials(getUsername(), getPassword()));
    restClientBuilder.setHttpClientConfigCallback(
        httpAsyncClientBuilder ->
            httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
  }
  if (getKeystorePath() != null && !getKeystorePath().isEmpty()) {
    try {
      KeyStore keyStore = KeyStore.getInstance("jks");
      try (InputStream is = new FileInputStream(new File(getKeystorePath()))) {
        String keystorePassword = getKeystorePassword();
        keyStore.load(is, (keystorePassword == null) ? null : keystorePassword.toCharArray());
      }
      final TrustStrategy trustStrategy =
          isTrustSelfSignedCerts() ? new TrustSelfSignedStrategy() : null;
      final SSLContext sslContext =
          SSLContexts.custom().loadTrustMaterial(keyStore, trustStrategy).build();
      final SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslContext);
      restClientBuilder.setHttpClientConfigCallback(
          httpClientBuilder ->
              httpClientBuilder.setSSLContext(sslContext).setSSLStrategy(sessionStrategy));
    } catch (Exception e) {
      throw new IOException("Can't load the client certificate from the keystore", e);
    }
  }
  restClientBuilder.setRequestConfigCallback(
      new RestClientBuilder.RequestConfigCallback() {
        @Override
        public RequestConfig.Builder customizeRequestConfig(
            RequestConfig.Builder requestConfigBuilder) {
          if (getConnectTimeout() != null) {
            requestConfigBuilder.setConnectTimeout(getConnectTimeout());
          }
          if (getSocketTimeout() != null) {
            requestConfigBuilder.setSocketTimeout(getSocketTimeout());
          }
          return requestConfigBuilder;
        }
      });
  return restClientBuilder.build();
}