Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:com.floragunn.searchguard.ssl.AbstractUnitTest.java

protected final CloseableHttpClient getHTTPClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHTTPClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("truststore.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("node-0-keystore.jks")),
                "changeit".toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }/*from   ww  w.j a v a  2  s  .  c om*/

        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}

From source file:se.skltp.adapterservices.druglogistics.dosdispensing.RetryComponent.java

private Registry<ConnectionSocketFactory> setupSSLSocketFactory() {
    try {//from   www  .  ja v  a2 s. c  om
        KeyStore keystore = loadKeystore(keystorePath, keystorePassword.toCharArray(), keystoreType);
        char[] keyPassword = keystorePassword.toCharArray();
        KeyStore truststore = loadKeystore(truststorePath, truststorePassword.toCharArray(), truststoreType);

        SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keystore, keyPassword)
                .loadTrustMaterial(truststore).build();

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", new SSLConnectionSocketFactory(sslContext,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
                .build();

        return socketFactoryRegistry;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java

/**
 * Returns the HttpClient through which the REST call is made. Uses an
 * unsafe TrustStrategy in case the user specified a HTTPS URL and
 * set the ignoreUnverifiedSSLPeer flag.
 *
 * @param logger    the logger to log messages to
 * @param build//  w  w  w.  jav  a 2s . co m
 * @return         the HttpClient
 */
private HttpClient getHttpClient(PrintStream logger, AbstractBuild<?, ?> build) throws Exception {
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    String bitbucketServer = bitbucketServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();

    // Determine if we are using the local or global settings
    String credentialsId = getCredentialsId();
    if (StringUtils.isBlank(credentialsId)) {
        credentialsId = descriptor.getCredentialsId();
    }

    Credentials credentials = CredentialsMatchers.firstOrNull(CredentialsProvider
            .lookupCredentials(CertificateCredentials.class, Jenkins.getInstance(), ACL.SYSTEM),
            CredentialsMatchers.withId(credentialsId));

    if ("".equals(bitbucketServer) || bitbucketServer == null) {
        bitbucketServer = descriptor.getBitbucketRootUrl();
    }
    if (!ignoreUnverifiedSSL) {
        ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }

    URL url = new URL(bitbucketServer);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (url.getProtocol().equals("https")
            && (ignoreUnverifiedSSL || credentials instanceof CertificateCredentials)) {
        // add unsafe trust manager to avoid thrown
        // SSLPeerUnverifiedException
        try {
            SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(
                    buildSslContext(ignoreUnverifiedSSL, credentials),
                    ignoreUnverifiedSSL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : null);
            builder.setSSLSocketFactory(sslConnSocketFactory);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnSocketFactory).build();

            HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

            builder.setConnectionManager(ccm);
        } catch (NoSuchAlgorithmException nsae) {
            logger.println("Couldn't establish SSL context:");
            nsae.printStackTrace(logger);
        } catch (KeyManagementException kme) {
            logger.println("Couldn't initialize SSL context:");
            kme.printStackTrace(logger);
        } catch (KeyStoreException kse) {
            logger.println("Couldn't initialize SSL context:");
            kse.printStackTrace(logger);
        }
    }

    // Configure the proxy, if needed
    // Using the Jenkins methods handles the noProxyHost settings
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
        Proxy proxy = proxyConfig.createProxy(url.getHost());
        if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
            SocketAddress addr = proxy.address();
            if (addr != null && addr instanceof InetSocketAddress) {
                InetSocketAddress proxyAddr = (InetSocketAddress) addr;
                HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
                builder = builder.setProxy(proxyHost);

                String proxyUser = proxyConfig.getUserName();
                if (proxyUser != null) {
                    String proxyPass = proxyConfig.getPassword();
                    BasicCredentialsProvider cred = new BasicCredentialsProvider();
                    cred.setCredentials(new AuthScope(proxyHost),
                            new UsernamePasswordCredentials(proxyUser, proxyPass));
                    builder = builder.setDefaultCredentialsProvider(cred)
                            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        }
    }

    return builder.build();
}

From source file:fi.csc.shibboleth.mobileauth.impl.authn.AuthenticateMobile.java

/**
 * This method will create CloseableHttpClient with client certificate authentication
 * //from   w  ww. java  2s  .co  m
 * @return CloseableHttpClient
 * @throws KeyStoreException
 * @throws RuntimeException
 */
private CloseableHttpClient createHttpClient() throws KeyStoreException, RuntimeException {

    KeyStore trustStore = KeyStore.getInstance(trustStoreType);
    KeyStore clientStore = KeyStore.getInstance(keystoreType);

    try {
        trustStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());
        clientStore.load(new FileInputStream(keystorePath), keystorePasswd.toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new RuntimeException("Cannot load key/trust stores", e);
    }

    final SSLConnectionSocketFactory socketFactory;

    try {
        final SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadKeyMaterial(clientStore, keystorePasswd.toCharArray()).loadTrustMaterial(trustStore)
                .build();
        socketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        throw new RuntimeException("SSL initialization error", e);
    }
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", socketFactory).build();
    final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);
    log.debug("Created httpClient");
    return HttpClients.custom().setConnectionManager(connectionManager).build();
}

From source file:com.floragunn.searchguard.AbstractUnitTest.java

protected final CloseableHttpClient getHTTPClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHTTPClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("truststore.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath(keystore)),
                "changeit".toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }/*w  w  w  . j a  v  a 2 s .  co m*/

        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * It builds a {@link SSLConnectionSocketFactory} if SSL is needed.
 * //  w w  w .j  ava 2  s .com
 * @return the {@link SSLConnectionSocketFactory} for SSL purposes.
 * @throws KeyManagementException
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @see SSLConnectionSocketFactory
 */
private static SSLConnectionSocketFactory buildSSLConnectionSocketFactory()
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    TrustStrategy ts = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // always true to avoid certificate unknown exception
            return true;
        }
    };
    SSLContextBuilder builder = SSLContexts.custom();
    builder.loadTrustMaterial(null, ts);
    SSLContext sslContext = builder.build();
    return new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:org.gtri.fhir.api.vistaex.resource.impl.VistaExResourceImpl.java

/**
 * Creates and configures a {@link SSLConnectionSocketFactory} to use in the application
 * @return/*  w  w  w  .  jav  a  2  s  . co m*/
 */
private SSLConnectionSocketFactory createSSLConnectionSocketFactory() {
    File trustStore = getFileInClassPath("gtVistaExTrustStore");
    SSLContext sslcontext = null;
    SSLConnectionSocketFactory sslsf = null;
    try {
        //TODO: At some point configure to use trust store
        sslcontext = SSLContexts.custom()
                //.loadTrustMaterial(trustStore, "gtvistaex".toCharArray(),new TrustSelfSignedStrategy())
                .loadTrustMaterial(new TrustAllStrategy()).build();
        //TODO: Fix to use non-deprecated code
        // Allow TLSv1 protocol only
        sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sslsf;
}

From source file:org.gtri.fhir.api.vistaex.resource.impl.VistaExResourceImpl.java

/**
 * Creates a {@link CloseableHttpClient} to use in the application
 * @return/*from  w w  w  .j a va 2 s  .  com*/
 */
private CloseableHttpClient createHttpClient() {
    //TODO: Fix to use non-deprecated code
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setSSLSocketFactory(getSslsf())
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
    return httpClient;
}

From source file:org.apache.geode.rest.internal.web.controllers.RestAPIsWithSSLDUnitTest.java

private CloseableHttpClient getSSLBasedHTTPClient(Properties properties) throws Exception {

    KeyStore clientKeys = KeyStore.getInstance("JKS");
    File keystoreJKSForPath = findKeyStoreJKS(properties);
    clientKeys.load(new FileInputStream(keystoreJKSForPath), "password".toCharArray());

    KeyStore clientTrust = KeyStore.getInstance("JKS");
    File trustStoreJKSForPath = findTrustStoreJKSForPath(properties);
    clientTrust.load(new FileInputStream(trustStoreJKSForPath), "password".toCharArray());

    // this is needed
    SSLContextBuilder custom = SSLContexts.custom();
    SSLContextBuilder sslContextBuilder = custom.loadTrustMaterial(clientTrust, new TrustSelfSignedStrategy());
    SSLContext sslcontext = sslContextBuilder
            .loadKeyMaterial(clientKeys, "password".toCharArray(), (aliases, socket) -> {
                if (aliases.size() == 1) {
                    return aliases.keySet().stream().findFirst().get();
                }//from  w ww. java2s.c o m
                if (!StringUtils.isEmpty(properties.getProperty(INVALID_CLIENT_ALIAS))) {
                    return properties.getProperty(INVALID_CLIENT_ALIAS);
                } else {
                    return properties.getProperty(SSL_WEB_ALIAS);
                }
            }).build();

    // Host checking is disabled here , as tests might run on multiple hosts and
    // host entries can not be assumed
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        PoolingHttpClientConnectionManager cm;
        if (Context.getInstance().getTrustAllCerts()) {
            try {
                SSLContextBuilder scb = SSLContexts.custom();
                scb.loadTrustMaterial(null, new TrustStrategy() {
                    @Override/*  w ww .  j  a v a  2s .  c  o m*/
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        return true;
                    }
                });
                SSLContext sslContext = scb.build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                        .<ConnectionSocketFactory>create().register("https", sslsf)
                        .register("http", new PlainConnectionSocketFactory()).build();
                cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            } catch (Exception e) {
                logger.warn("Could not set HttpClient to trust all SSL certificates", e);
                cm = new PoolingHttpClientConnectionManager();
            }
        } else {
            cm = new PoolingHttpClientConnectionManager();
        }
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);
        HttpHost localhost = new HttpHost("localhost", 80);
        cm.setMaxPerRoute(new HttpRoute(localhost), 50);
        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(cm);
        builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
        builder.setDefaultCookieStore(new BasicCookieStore());
        httpClient = builder.build();
    }
    return httpClient;
}