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

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

Introduction

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

Prototype

public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
            final String[] supportedProtocols, final String[] supportedCipherSuites,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.apache.hadoop.gateway.GatewaySslFuncTest.java

@Test(timeout = TestUtils.MEDIUM_TIMEOUT)
public void testKnox674SslCipherSuiteConfig() throws Exception {
    LOG_ENTER();/* w w w  .ja v a 2  s  . com*/

    String topoStr = TestUtils.merge(DAT, "test-admin-topology.xml", params);
    File topoFile = new File(config.getGatewayTopologyDir(), "test-topology.xml");
    FileUtils.writeStringToFile(topoFile, topoStr);

    topos.reloadTopologies();

    String username = "guest";
    String password = "guest-password";
    String serviceUrl = gatewayUrl + "/test-topology/api/v1/version";

    HttpHost targetHost = new HttpHost("localhost", gatewayPort, gatewayScheme);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);

    CloseableHttpClient client = HttpClients.custom()
            .setSSLSocketFactory(
                    new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" },
                            new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts()))
            .build();
    HttpGet request = new HttpGet(serviceUrl);
    CloseableHttpResponse response = client.execute(request, context);
    assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version"));
    response.close();
    client.close();

    gateway.stop();
    config.setExcludedSSLCiphers(Arrays.asList(new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }));
    config.setIncludedSSLCiphers(Arrays.asList(new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }));

    startGatewayServer();
    serviceUrl = gatewayUrl + "/test-topology/api/v1/version";

    try {
        client = HttpClients.custom()
                .setSSLSocketFactory(
                        new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" },
                                new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts()))
                .build();
        request = new HttpGet(serviceUrl);
        client.execute(request, context);
        fail("Expected SSLHandshakeException");
    } catch (SSLHandshakeException e) {
        // Expected.
        client.close();
    }

    client = HttpClients.custom()
            .setSSLSocketFactory(
                    new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" },
                            new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }, new TrustAllHosts()))
            .build();
    request = new HttpGet(serviceUrl);
    response = client.execute(request, context);
    assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version"));
    response.close();
    client.close();

    LOG_EXIT();
}

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

protected CloseableHttpClient httpClientFactory() throws CannotInitializeDataAdapterException {
    try {// w w w.j  a  v a 2s.  c  o m
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(createSslCustomContext(), null, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        RegistryBuilder<AuthSchemeProvider> schemeProviderBuilder = RegistryBuilder.create();
        schemeProviderBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
            @Override
            public Principal getUserPrincipal() {
                return null;
            }

            @Override
            public String getPassword() {
                return null;
            }
        });

        return HttpClients.custom().setDefaultAuthSchemeRegistry(schemeProviderBuilder.build())
                .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(csf).build();
    } catch (Exception e) {
        throw new CannotInitializeDataAdapterException(
                "Could not initialize adapter to source '" + this.getSourceName() + "': " + e.getMessage(), e);
    }
}

From source file:com.zacwolf.commons.wbxcon.WBXCONorg.java

/**
 * Class <code>Contructor</code> initializes WBXCONorg instance for the given managed org (domain) instance.
 * As part of initialization the Constructor makes a call to establish orgID and namespaceID for the domain.
 * /* w  ww.  j  a  v  a2 s .  c o  m*/
 * The REST API calls are made via https GET and POST.  As such, the <code>HTTPSCLIENT</code> needs to be
 * initialized via a certificate stored in a default keystore.  Since the keystore contains a "static"
 * certificate provided by WebEx Connect, the keystore is generated "in source".  If WebEx Connect modifies
 * their default https certificate, you will need to download the latest version of this package from:<br />
 * <br />
 * <a href="https://github.com/ZacWolf/com.zacwolf.commons">https://github.com/ZacWolf/com.zacwolf.commons</a>
 * 
 * 
 * Whatever user is specified for wapiUSER, the following special privileges need to be granted to the account:
 * 
 * WBX:ManageDomain
 * WBX:ManageUsers
 * WBX:ManageRoles
 * 
 * @param domain_name   Name of the WebEx Connect Managed Org
 * @param wapiAUTHURL   (optional) URL used to override the default URL used to generate the initial login token
 * @param wapiUSER      WebEx UserName to use in making the REST calls
 * @param wapiPASS      WebEx user password to use in making the REST calls
 * @throws WBXCONexception
 */
WBXCONorg(final String domain_name, final String wapiAUTHURL, final String wapiUSER, final String wapiPASS)
        throws WBXCONexception {
    if (HTTPSCLIENT == null)
        try {
            //Quiet the various apache http client loggers
            Logger.getLogger("org.apache.http").setLevel(Level.SEVERE);
            Logger.getLogger("org.apache.http.wire").setLevel(Level.SEVERE);
            Logger.getLogger("org.apache.http.headers").setLevel(Level.SEVERE);
            System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
            System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
            System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "ERROR");
            System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "ERROR");
            System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "ERROR");

            final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(MAX_HTTP_REQUESTS);
            final KeyStore trustStore = KeyStore.getInstance("JCEKS");
            // Use the default keystore that is in the same package directory
            final InputStream instream = WBXCONorg.class.getClassLoader().getResourceAsStream(
                    WBXCONorg.class.getPackage().getName().replaceAll("\\.", "/") + "/" + TRUSTSTOREFILENAME);
            try {
                trustStore.load(instream, TRUSTSTOREPASS.toCharArray());
            } finally {
                instream.close();
            }
            final SSLContext sslcontext = SSLContexts.custom()// Trust own CA and all self-signed certs
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                    new String[] { "TLSv1" }, // Allow TLSv1 protocol only
                    null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            final RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_TIMEOUT * 60000)
                    .setConnectionRequestTimeout(HTTP_TIMEOUT * 60000).setSocketTimeout(HTTP_TIMEOUT * 60000)
                    .build();
            HTTPSCLIENT = HttpClients.custom().setConnectionManager(cm).setSSLSocketFactory(sslsf)
                    .setDefaultRequestConfig(config).build();
        } catch (final Exception e) {
            System.err.println(WBXCONorg.class.getCanonicalName()
                    + " UNABLE TO ESTABLISH HTTPSCLIENT FOR WAPI CALLS. All WAPI CALLS WILL FAIL!!!");
            e.printStackTrace();
            //System.exit(2);
        }
    Runtime.getRuntime().addShutdownHook(new Thread("WBXCONorg shutdownhook") {
        @Override
        public void run() {
            try {
                finalize();
            } catch (final Throwable e) {
                e.printStackTrace();
            }
        }
    });
    this.orgName = domain_name;
    this.wapiAUTHURL = wapiAUTHURL != null ? wapiAUTHURL : this.wapiAUTHURL;
    this.wapiUSER = wapiUSER + (!wapiUSER.endsWith("@" + domain_name) ? "@" + domain_name : "");
    this.wapiPASS = wapiPASS;

    final Document dom;
    try {
        System.out.println("===============  1");
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        System.out.println("===============  2");
        factory.setValidating(false);
        System.out.println("===============  3");
        factory.setCoalescing(true);
        System.out.println("===============  4");
        final DocumentBuilder db = factory.newDocumentBuilder();
        System.out.println("===============  5");
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        System.out.println("===============  6");
        params.add(new BasicNameValuePair("cmd", "get"));
        System.out.println("===============  7");
        params.add(new BasicNameValuePair("type", "org"));
        System.out.println("===============  8");
        params.add(new BasicNameValuePair("select", "org/orgID:/org/namespaceID:ext/WBX/PWSRule"));
        System.out.println("===============  9");
        params.add(new BasicNameValuePair("id", "current"));
        System.out.println("===============  10");
        System.out.println("===============  getDomainCredToken() :" + getDomainCredToken());
        params.add(new BasicNameValuePair("cred", getDomainCredToken()));
        System.out.println("===============  11");
        System.out.println("===============  params" + params.toString());
        System.out.println("===============Before wapiURL :" + this.wapiURL);
        final HttpPost httpPost = new HttpPost(this.wapiURL);
        System.out.println("=============== after wapiURL :" + this.wapiURL);

        httpPost.setEntity(new UrlEncodedFormEntity(params, org.apache.http.Consts.UTF_8));
        System.out.println("===============  12");
        final CloseableHttpResponse httpRes = HTTPSCLIENT.execute(httpPost, new BasicHttpContext());
        System.out.println("===============  13");

        if (httpRes == null) {
            System.out.println("===============  httpRes is NULL");
        }

        try {
            dom = db.parse(httpRes.getEntity().getContent());
            System.out.println("===============  14");
        } finally {
            httpRes.close();
        }
    } catch (final Exception e) {
        throw new WBXCONexception(e);
    }
    final NodeList result = dom.getElementsByTagName("result");
    if (result == null || result.item(0) == null
            || !result.item(0).getTextContent().equalsIgnoreCase("success"))
        throw new WBXCONexception(
                "ERROR::WBXCONorg:constructor(\"" + domain_name + "\")::" + documentGetErrorString(dom));

    this.orgID = dom.getElementsByTagName("orgID").item(0).getTextContent();
    this.namespaceID = dom.getElementsByTagName("namespaceID").item(0).getTextContent();
    this.passwordrule = new PWSRule(Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumLength_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumAlpha_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumNumeric_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumSpecial_9")),
            documentGetTextContentByTagName(dom, "PWRequireMixedCase_B").equalsIgnoreCase("true"));
    this.wapiUser = restapiAccountGet(this.wapiUSER);
}

From source file:com.floragunn.searchguard.httpclient.HttpClient.java

private final CloseableHttpClient createHTTPClient()
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException,
        IOException, UnrecoverableKeyException, KeyManagementException {

    // basic auth
    // pki auth//from w  w w  .jav a  2 s.  c  o m
    // kerberos auth

    final org.apache.http.impl.client.HttpClientBuilder hcb = HttpClients.custom();

    if (ssl) {

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

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

        if (trustStore != null) {
            final KeyStore myTrustStore = KeyStore
                    .getInstance(trustStore.getName().endsWith("jks") ? "JKS" : "PKCS12");
            myTrustStore.load(new FileInputStream(trustStore),
                    truststorePassword == null || truststorePassword.isEmpty() ? null
                            : truststorePassword.toCharArray());
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }

        if (keystore != null) {
            final KeyStore keyStore = KeyStore
                    .getInstance(keystore.getName().endsWith("jks") ? "JKS" : "PKCS12");
            keyStore.load(new FileInputStream(keystore),
                    keystorePassword == null || keystorePassword.isEmpty() ? null
                            : keystorePassword.toCharArray());
            sslContextbBuilder.loadKeyMaterial(keyStore,
                    keystorePassword == null || keystorePassword.isEmpty() ? null
                            : keystorePassword.toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new String[] { "TLSv1.1", "TLSv1.2" }, null,
                verifyHostnames ? SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER
                        : SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    /*if (keytab != null) {
            
    //System.setProperty("java.security.auth.login.config", "login.conf");
    //System.setProperty("java.security.krb5.conf", "krb5.conf");
            
            
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    //SPNEGO/Kerberos setup
    log.debug("SPNEGO activated");
    final AuthSchemeProvider nsf = new LoginSPNegoSchemeFactory(true);
    final Credentials jaasCreds = new JaasCredentials();
    credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
    credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest",
            "Guest"));
    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
            .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();
            
    hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    hcb.setDefaultCredentialsProvider(credsProvider);
    }*/

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

    return hcb.build();
}

From source file:com.github.tomakehurst.wiremock.HttpsAcceptanceTest.java

static String secureContentFor(String url, String clientTrustStore, String trustStorePassword)
        throws Exception {
    KeyStore trustStore = readKeyStore(clientTrustStore, trustStorePassword);

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy())
            .loadKeyMaterial(trustStore, trustStorePassword.toCharArray()).useTLS().build();

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, // supported protocols
            null, // supported cipher suites
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    String content = EntityUtils.toString(response.getEntity());
    return content;
}

From source file:com.mirth.connect.client.core.ConnectServiceUtil.java

private static CloseableHttpClient getClient(String[] protocols, String[] cipherSuites) {
    RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create();
    String[] enabledProtocols = MirthSSLUtil.getEnabledHttpsProtocols(protocols);
    String[] enabledCipherSuites = MirthSSLUtil.getEnabledHttpsCipherSuites(cipherSuites);
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            SSLContexts.createSystemDefault(), enabledProtocols, enabledCipherSuites,
            SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
    socketFactoryRegistry.register("https", sslConnectionSocketFactory);

    BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
            socketFactoryRegistry.build());
    httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(TIMEOUT).build());
    return HttpClients.custom().setConnectionManager(httpClientConnectionManager).build();
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java

private static PoolingHttpClientConnectionManager createConnManager() {

    String sslProtocolsStr = System.getProperty("https.protocols");
    String cipherSuitesStr = System.getProperty("https.cipherSuites");
    String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null;
    String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null;

    SSLConnectionSocketFactory sslConnectionSocketFactory;
    if (SSL_INSECURE) {
        try {/*from  ww  w .j  a  v a2  s. c  om*/
            SSLContext sslContext = new SSLContextBuilder().useSSL()
                    .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build();
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites,
                    SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
                            : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        } catch (Exception ex) {
            throw new SSLInitializationException(ex.getMessage(), ex);
        }
    } else {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }

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

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
    if (PERSISTENT_POOL) {
        connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE);
        connManager.setMaxTotal(MAX_CONN_TOTAL);
    } else {
        connManager.setMaxTotal(1);
    }
    return connManager;
}

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 .j  a  va  2s .  com
    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;
}