Example usage for org.apache.http.ssl SSLContexts custom

List of usage examples for org.apache.http.ssl SSLContexts custom

Introduction

In this page you can find the example usage for org.apache.http.ssl SSLContexts custom.

Prototype

public static SSLContextBuilder custom() 

Source Link

Document

Creates custom SSL context.

Usage

From source file:org.apache.metron.elasticsearch.client.ElasticsearchClientFactory.java

/**
 * <p>Setup connection encryption details (SSL) if applicable.
 * If ssl.enabled=true, sets up SSL connection. If enabled, keystore.path is required. User can
 * also optionally set keystore.password and keystore.type.
 * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_encrypted_communication.html
 * <p>//ww  w .  jav  a  2s.  com
 * <p>Other guidance on the HTTP Component library and configuring SSL connections.
 * http://www.robinhowlett.com/blog/2016/01/05/everything-you-ever-wanted-to-know-about-ssl-but-were-afraid-to-ask.
 * <p>
 * <p>JSSE docs - https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html
 * <p>
 * <p>Additional guidance for configuring Elasticsearch for SSL can be found here - https://www.elastic.co/guide/en/x-pack/5.6/ssl-tls.html
 */
private static SSLContext getSSLContext(ElasticsearchClientConfig esClientConfig) {
    if (esClientConfig.isSSLEnabled()) {
        LOG.info("Configuring client for SSL connection.");
        if (!esClientConfig.getKeyStorePath().isPresent()) {
            throw new IllegalStateException("KeyStore path must be provided for SSL connection.");
        }
        Optional<String> optKeyStorePass = esClientConfig.getKeyStorePassword();
        char[] keyStorePass = optKeyStorePass.map(String::toCharArray).orElse(null);
        KeyStore trustStore = getStore(esClientConfig.getKeyStoreType(), esClientConfig.getKeyStorePath().get(),
                keyStorePass);
        try {
            SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);
            return sslBuilder.build();
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            throw new IllegalStateException("Unable to load truststore.", e);
        }
    }
    return null;
}

From source file:de.hska.ld.core.client.ClientRequest.java

private CloseableHttpClient createHttpsClient() throws IOException {
    SSLContext sslContext = null;
    try {/*from   w w w. j  a v  a  2s  .  c  om*/
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
                return true;
            }
        }).useProtocol("TLSv1.2").build();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return HttpClients.custom().setSSLContext(sslContext).build();
}

From source file:org.drugis.addis.config.MainConfig.java

@Bean
public HttpClient httpClient(RequestConfig requestConfig) throws KeyStoreException, IOException,
        CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(KEYSTORE_PATH), KEYSTORE_PASSWORD.toCharArray());
    String ADDIS_LOCAL = System.getenv("ADDIS_LOCAL");

    SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadKeyMaterial(keyStore,
            KEYSTORE_PASSWORD.toCharArray());
    if (ADDIS_LOCAL != null) {
        String TRUSTSTORE_PATH = WebConstants.loadSystemEnv("TRUSTSTORE_PATH");
        sslContextBuilder.loadTrustMaterial(new File(TRUSTSTORE_PATH));
    }/*w  w w  . j a  v  a2 s . c o  m*/
    sslContextBuilder.build();
    SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build());

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", connectionSocketFactory).register("http", new PlainConnectionSocketFactory())
            .build();
    HttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(registry);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    return httpClientBuilder.setConnectionManager(clientConnectionManager).setMaxConnTotal(20)
            .setMaxConnPerRoute(2).setDefaultRequestConfig(requestConfig).build();
}

From source file:org.jodconverter.office.OnlineOfficeManagerPoolEntry.java

private SSLConnectionSocketFactory configureSsl() throws OfficeException {

    if (sslConfig == null || !sslConfig.isEnabled()) {
        return null;
    }//  w  w w  .j  av a 2  s.c o  m

    try {
        final SSLContextBuilder sslBuilder = SSLContexts.custom();
        sslBuilder.setProtocol(sslConfig.getProtocol());
        configureKeyMaterial(sslBuilder);
        configureTrustMaterial(sslBuilder);

        final SSLContext sslcontext = sslBuilder.build();

        return new SSLConnectionSocketFactory(sslcontext, sslConfig.getEnabledProtocols(),
                sslConfig.getCiphers(),
                sslConfig.isVerifyHostname() ? SSLConnectionSocketFactory.getDefaultHostnameVerifier()
                        : NoopHostnameVerifier.INSTANCE);

    } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException
            | CertificateException | UnrecoverableKeyException | NoSuchProviderException ex) {
        throw new OfficeException("Unable to create SSL context.", ex);
    }
}

From source file:eu.fthevenet.binjr.data.adapters.HttpDataAdapterBase.java

protected static SSLContext createSslCustomContext()
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        KeyManagementException, UnrecoverableKeyException, NoSuchProviderException {
    // Load platform specific Trusted CA keystore
    logger.trace(() -> "Available Java Security providers: " + Arrays.toString(Security.getProviders()));
    KeyStore tks;/*from   www.  j  ava 2  s .  com*/
    switch (AppEnvironment.getInstance().getOsFamily()) {
    case WINDOWS:
        tks = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
        tks.load(null, null);
        break;
    case OSX:
        tks = KeyStore.getInstance("KeychainStore", "Apple");
        tks.load(null, null);
        break;
    case LINUX:
    case UNSUPPORTED:
    default:
        tks = null;
        break;
    }
    return SSLContexts.custom().loadTrustMaterial(tks, null).build();
}

From source file:io.apiman.gateway.platforms.servlet.connectors.ssl.SSLSessionStrategyFactory.java

/**
 * Build an {@link SSLSessionStrategy}.// w ww . j a v a2s. c o m
 *
 * @param trustStore the trust store
 * @param trustStorePassword the truststore password (if any)
 * @param keyStore the keystore
 * @param keyStorePassword the keystore password (if any)
 * @param keyAliases the key aliases that are candidates for use (if any)
 * @param keyPassword the key password (if any)
 * @param allowedProtocols the allowed transport protocols.
 *            <strong><em>Avoid specifying insecure protocols</em></strong>
 * @param allowedCiphers allowed crypto ciphersuites, <tt>null</tt> to use system defaults
 * @param trustSelfSigned true if self signed certificates can be trusted.
 *             <strong><em>Use with caution</em></strong>
 * @param allowAnyHostname true if any hostname can be connected to (i.e. does not need to match
 *            certificate hostname). <strong><em>Do not use in production</em></strong>
 * @return the connection socket factory
 * @throws NoSuchAlgorithmException if the selected algorithm is not available on the system
 * @throws KeyStoreException if there was a problem with the keystore
 * @throws CertificateException if there was a problem with the certificate
 * @throws IOException if the truststore could not be found or was invalid
 * @throws KeyManagementException if there is a problem with keys
 * @throws UnrecoverableKeyException if the key cannot be recovered
 */
public static SSLSessionStrategy build(String trustStore, String trustStorePassword, String keyStore,
        String keyStorePassword, String[] keyAliases, String keyPassword, String[] allowedProtocols,
        String[] allowedCiphers, boolean allowAnyHostname, boolean trustSelfSigned)

        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException {

    Args.notNull(allowedProtocols, "Allowed protocols"); //$NON-NLS-1$
    Args.notNull(allowedCiphers, "Allowed ciphers"); //$NON-NLS-1$

    TrustStrategy trustStrategy = trustSelfSigned ? SELF_SIGNED : null;
    HostnameVerifier hostnameVerifier = allowAnyHostname ? ALLOW_ANY
            : SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    PrivateKeyStrategy privateKeyStrategy = keyAliases == null ? null : new SelectByAlias(keyAliases);
    boolean clientAuth = keyStore == null ? false : true;

    SSLContextBuilder builder = SSLContexts.custom();

    if (trustStore != null) {
        loadTrustMaterial(builder, new File(trustStore), trustStorePassword.toCharArray(), trustStrategy);
    }

    if (keyStore != null) {
        char[] ksp = keyStorePassword == null ? null : keyStorePassword.toCharArray();
        char[] kp = keyPassword == null ? null : keyPassword.toCharArray();
        loadKeyMaterial(builder, new File(keyStore), ksp, kp, privateKeyStrategy);
    }

    SSLContext sslContext = builder.build();
    return new SSLSessionStrategy(hostnameVerifier, new CipherSelectingSSLSocketFactory(
            sslContext.getSocketFactory(), allowedCiphers, allowedProtocols, clientAuth));
}

From source file:com.streamsets.pipeline.lib.elasticsearch.ElasticsearchStageDelegate.java

private void buildSSLContext(List<Stage.ConfigIssue> issues, RestClientBuilder restClientBuilder)
        throws IOException {
    try {/*from   ww  w .j av  a 2  s . c o  m*/
        final SSLContext sslcontext;
        final String keyStorePath = conf.securityConfig.sslTrustStorePath;
        if (StringUtils.isEmpty(keyStorePath)) {
            sslcontext = SSLContext.getDefault();
        } else {
            String keyStorePass = null;
            try {
                keyStorePass = conf.securityConfig.sslTrustStorePassword.get();
            } catch (StageException e) {
                issues.add(context.createConfigIssue(Groups.ELASTIC_SEARCH.name(),
                        SecurityConfig.CONF_PREFIX + "sslTrustStorePassword", Errors.ELASTICSEARCH_31,
                        e.toString()));
            }

            if (StringUtils.isEmpty(keyStorePass)) {
                issues.add(context.createConfigIssue(Groups.ELASTIC_SEARCH.name(),
                        SecurityConfig.CONF_PREFIX + "sslTrustStorePassword", Errors.ELASTICSEARCH_10));
            }
            Path path = Paths.get(keyStorePath);
            if (!Files.exists(path)) {
                issues.add(context.createConfigIssue(Groups.ELASTIC_SEARCH.name(),
                        SecurityConfig.CONF_PREFIX + "sslTrustStorePath", Errors.ELASTICSEARCH_11,
                        keyStorePath));
            }
            KeyStore keyStore = KeyStore.getInstance("jks");
            try (InputStream is = Files.newInputStream(path)) {
                keyStore.load(is, keyStorePass.toCharArray());
            }
            sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
        }
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder.setSSLContext(sslcontext);
            }
        });
    } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException | CertificateException e) {
        issues.add(context.createConfigIssue(Groups.ELASTIC_SEARCH.name(),
                SecurityConfig.CONF_PREFIX + "sslTrustStorePath", Errors.ELASTICSEARCH_12, e.toString(), e));
    }
}

From source file:com.vmware.photon.controller.core.Main.java

private static PhotonControllerXenonHost startXenonHost(PhotonControllerConfig photonControllerConfig,
        ThriftModule thriftModule, DeployerConfig deployerConfig, SSLContext sslContext) throws Throwable {
    // Values for CloudStore
    final HostClientFactory hostClientFactory = thriftModule.getHostClientFactory();
    final AgentControlClientFactory agentControlClientFactory = thriftModule.getAgentControlClientFactory();
    final NsxClientFactory nsxClientFactory = new NsxClientFactory();

    // Values for Scheduler
    final ServerSet cloudStoreServerSet = new StaticServerSet(
            new InetSocketAddress(photonControllerConfig.getXenonConfig().getRegistrationAddress(),
                    Constants.PHOTON_CONTROLLER_PORT));
    final CloudStoreHelper cloudStoreHelper = new CloudStoreHelper(cloudStoreServerSet);

    final CloseableHttpAsyncClient httpClient;
    try {/*from  w  w  w  . j av a2 s .com*/
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial((chain, authtype) -> true).build();
        httpClient = HttpAsyncClientBuilder.create()
                .setHostnameVerifier(SSLIOSessionStrategy.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslcontext)
                .build();
        httpClient.start();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

    ServerSet apiFeServerSet = new StaticServerSet(new InetSocketAddress(
            photonControllerConfig.getXenonConfig().getRegistrationAddress(), Constants.MANAGEMENT_API_PORT));

    logger.info("Creating PhotonController Xenon Host");
    final PhotonControllerXenonHost photonControllerXenonHost = new PhotonControllerXenonHost(
            photonControllerConfig.getXenonConfig(), hostClientFactory, agentControlClientFactory,
            nsxClientFactory, cloudStoreHelper, sslContext);
    logger.info("Created PhotonController Xenon Host");

    // Set referer Uri from the xenon host, because we do not want to rely on
    // CloudStoreHelper's default mechanise to create referer based on local address,
    // because CloudStoreHelper uses InetAddress.getLocalHost() which depends on
    // /etc/hosts having a hostname entry, which is not always available.
    // This change will allow people to run this service without need to
    // update their /etc/hosts file.
    cloudStoreHelper.setRefererUri(photonControllerXenonHost.getUri());

    final ConstraintChecker checker = new CloudStoreConstraintChecker(cloudStoreHelper,
            photonControllerXenonHost);

    logger.info("Creating Cloud Store Xenon Service Group");
    CloudStoreServiceGroup cloudStoreServiceGroup = createCloudStoreServiceGroup(deployerConfig.isInstaller());
    logger.info("Created Cloud Store Xenon Service Group");

    logger.info("Registering Cloud Store Xenon Service Group");
    photonControllerXenonHost.registerCloudStore(cloudStoreServiceGroup);
    logger.info("Registered Cloud Store Xenon Service Group");

    logger.info("Creating Scheduler Xenon Service Group");
    SchedulerServiceGroup schedulerServiceGroup = createSchedulerServiceGroup(photonControllerConfig.getRoot(),
            checker);
    logger.info("Created Scheduler Xenon Service Group");

    logger.info("Registering Scheduler Xenon Service Group");
    photonControllerXenonHost.registerScheduler(schedulerServiceGroup);
    logger.info("Registered Scheduler Xenon Service Group");

    logger.info("Creating Housekeeper Xenon Service Group");
    HousekeeperServiceGroup housekeeperServiceGroup = createHousekeeperServiceGroup();
    logger.info("Created Housekeeper Xenon Service Group");

    logger.info("Registering Housekeeper Xenon Service Group");
    photonControllerXenonHost.registerHousekeeper(housekeeperServiceGroup);
    logger.info("Registered Housekeeper Xenon Service Group");

    logger.info("Creating Deployer Xenon Service Group");
    DeployerServiceGroup deployerServiceGroup = createDeployerServiceGroup(photonControllerConfig,
            deployerConfig, apiFeServerSet, cloudStoreServerSet, httpClient);
    logger.info("Created Deployer Xenon Service Group");

    logger.info("Registering Deployer Xenon Service Group");
    photonControllerXenonHost.registerDeployer(deployerServiceGroup);
    logger.info("Registered Deployer Xenon Service Group");

    DeployerContext deployerContext = deployerConfig.getDeployerContext();
    if (deployerContext.isAuthEnabled()) {
        ServiceClient serviceClient = NettyHttpServiceClient.create(Main.class.getSimpleName(),
                Executors.newFixedThreadPool(Utils.DEFAULT_THREAD_COUNT),
                Executors.newScheduledThreadPool(Utils.DEFAULT_IO_THREAD_COUNT), photonControllerXenonHost);

        /*
        To make sure that Xenon uses only TLSv1.2 and disallows SSLv3, TLSv1,
        TLSv1.1 the Docker file for the photon-controller-core container is edited.
        The java.security file located inside the container at the location
        /var/opt/OpenJDK-* /jre/lib/security has the information under the
        jdk.tls.disabledAlgorithms
        */

        SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        KeyStore keyStore = KeyStore.getInstance("JKS");
        try (FileInputStream fis = new FileInputStream(deployerContext.getKeyStorePath())) {
            keyStore.load(fis, deployerContext.getKeyStorePassword().toCharArray());
        }
        keyManagerFactory.init(keyStore, deployerContext.getKeyStorePassword().toCharArray());
        clientContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        serviceClient.setSSLContext(clientContext);
        photonControllerXenonHost.setClient(serviceClient);
    }

    logger.info("Starting PhotonController Xenon Host");
    photonControllerXenonHost.start();
    logger.info("Started PhotonController Xenon Host");

    logger.info("Creating SystemConfig instance");
    SystemConfig.createInstance(photonControllerXenonHost);
    logger.info("Created SystemConfig instance");
    return photonControllerXenonHost;
}

From source file:io.confluent.rest.SslTest.java

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;//from  w  w  w  .  ja  v  a2 s .c  om
    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" },
                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;
}

From source file:org.springframework.integration.splunk.support.SplunkHECWriter.java

private SSLContext getSSLContext() {
    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }// ww  w  .j a  v a 2 s .c  o m
    };
    SSLContext sslContext = null;
    try {
        sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    } catch (Exception e) {
        // Handle error
    }
    return sslContext;

}