Search in sources :

Example 81 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project voltdb by VoltDB.

the class TestJSONInterface method httpUrlOverJSONExecute.

private static String httpUrlOverJSONExecute(String method, String url, String user, String password, String scheme, int expectedCode, String expectedCt, String varString) throws Exception {
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> true).build();
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
    // allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClientBuilder hb = HttpClientBuilder.create();
    hb.setSslcontext(sslContext);
    hb.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = hb.build()) {
        HttpRequestBase request;
        switch(method) {
            case "POST":
                HttpPost post = new HttpPost(url);
                post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
                request = post;
                break;
            case "PUT":
                HttpPut put = new HttpPut(url);
                put.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
                request = put;
                break;
            case "DELETE":
                HttpDelete delete = new HttpDelete(url);
                request = delete;
                break;
            case "GET":
                request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
                break;
            default:
                request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
                break;
        }
        // play nice by using HTTP 1.1 continue requests where the client sends the request headers first
        // to the server to see if the server is willing to accept it. This allows us to test large requests
        // without incurring server socket connection terminations
        RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
        request.setProtocolVersion(HttpVersion.HTTP_1_1);
        request.setConfig(rc);
        if (user != null && password != null) {
            if (scheme.equalsIgnoreCase("hashed")) {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
                String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
                request.setHeader("Authorization", "Hashed " + h);
            } else if (scheme.equalsIgnoreCase("hashed256")) {
                MessageDigest md = MessageDigest.getInstance("SHA-256");
                byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
                String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
                request.setHeader("Authorization", "Hashed " + h);
            } else if (scheme.equalsIgnoreCase("basic")) {
                request.setHeader("Authorization", "Basic " + new String(Base64.encodeToString(new String(user + ":" + password).getBytes(), false)));
            }
        }
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                String ct = response.getHeaders("Content-Type")[0].getValue();
                if (expectedCt != null) {
                    assertTrue(ct.contains(expectedCt));
                }
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || HANDLED_CLIENT_ERRORS.contains(status)) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(request, rh);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) MessageDigest(java.security.MessageDigest) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 82 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project geode by apache.

the class RestAPIsWithSSLDUnitTest method getSSLBasedHTTPClient.

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();
        }
        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();
}
Also used : Arrays(java.util.Arrays) SSLContext(javax.net.ssl.SSLContext) StringUtils(org.apache.commons.lang.StringUtils) Date(java.util.Date) AvailablePort(org.apache.geode.internal.AvailablePort) AttributesFactory(org.apache.geode.cache.AttributesFactory) RegionAttributes(org.apache.geode.cache.RegionAttributes) Cache(org.apache.geode.cache.Cache) JSONObject(org.json.JSONObject) Map(java.util.Map) SSLContexts(org.apache.http.ssl.SSLContexts) CacheServer(org.apache.geode.cache.server.CacheServer) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) Parameterized(org.junit.runners.Parameterized) Collection(java.util.Collection) HttpEntity(org.apache.http.HttpEntity) KeyStore(java.security.KeyStore) ClientRegionShortcut(org.apache.geode.cache.client.ClientRegionShortcut) SecurableCommunicationChannel(org.apache.geode.internal.security.SecurableCommunicationChannel) ManagementException(org.apache.geode.management.ManagementException) Category(org.junit.experimental.categories.Category) GemFireCacheImpl(org.apache.geode.internal.cache.GemFireCacheImpl) HttpGet(org.apache.http.client.methods.HttpGet) ClientCache(org.apache.geode.cache.client.ClientCache) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) HttpClients(org.apache.http.impl.client.HttpClients) InternalDistributedSystem(org.apache.geode.distributed.internal.InternalDistributedSystem) IgnoredException(org.apache.geode.test.dunit.IgnoredException) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) InternalCache(org.apache.geode.internal.cache.InternalCache) CacheFactory(org.apache.geode.cache.CacheFactory) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) LocatorTestBase(org.apache.geode.cache.client.internal.LocatorTestBase) BindException(java.net.BindException) Host(org.apache.geode.test.dunit.Host) VM(org.apache.geode.test.dunit.VM) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Region(org.apache.geode.cache.Region) RegionFactory(org.apache.geode.cache.RegionFactory) CategoryWithParameterizedRunnerFactory(org.apache.geode.test.junit.runners.CategoryWithParameterizedRunnerFactory) DistributedSystem(org.apache.geode.distributed.DistributedSystem) NetworkUtils(org.apache.geode.test.dunit.NetworkUtils) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Properties(java.util.Properties) AvailablePortHelper(org.apache.geode.internal.AvailablePortHelper) RegionShortcut(org.apache.geode.cache.RegionShortcut) IOException(java.io.IOException) Test(org.junit.Test) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TestUtil(org.apache.geode.util.test.TestUtil) File(java.io.File) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory) DataPolicy(org.apache.geode.cache.DataPolicy) BufferedReader(java.io.BufferedReader) Assert(org.junit.Assert) InputStream(java.io.InputStream) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) File(java.io.File) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) FileInputStream(java.io.FileInputStream) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 83 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project lucene-solr by apache.

the class SSLTestConfig method buildClientSSLConnectionSocketFactory.

/** 
   * Constructs a new SSLConnectionSocketFactory for HTTP <b>clients</b> to use when communicating 
   * with servers which have been configured based on the settings of this object. Will return null
   * unless {@link #isSSLMode} is true.
   */
public SSLConnectionSocketFactory buildClientSSLConnectionSocketFactory() {
    if (!isSSLMode()) {
        return null;
    }
    SSLConnectionSocketFactory sslConnectionFactory;
    try {
        boolean sslCheckPeerName = toBooleanDefaultIfNull(toBooleanObject(System.getProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME)), true);
        SSLContext sslContext = buildClientSSLContext();
        if (sslCheckPeerName == false) {
            sslConnectionFactory = new SSLConnectionSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } else {
            sslConnectionFactory = new SSLConnectionSocketFactory(sslContext);
        }
    } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IllegalStateException("Unable to setup https scheme for HTTPClient to test SSL.", e);
    }
    return sslConnectionFactory;
}
Also used : UnrecoverableKeyException(java.security.UnrecoverableKeyException) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) KeyManagementException(java.security.KeyManagementException)

Example 84 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project ddf by codice.

the class TestSecurity method createHttpClient.

private HttpClient createHttpClient(String protocol, String[] cipherSuites, CredentialsProvider credentialsProvider) throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContexts.custom().useProtocol(protocol).build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context, null, cipherSuites, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(socketFactory).build();
}
Also used : SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory)

Example 85 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project ddf by codice.

the class KeystoreEditor method createNonVerifyingSslSocket.

SSLSocket createNonVerifyingSslSocket(String decodedUrl) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException, IOException {
    URL httpsUrl = new URL(decodedUrl);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManager tm = new NonVerifyingTrustManager();
    sslContext.init(null, new TrustManager[] { tm }, null);
    SSLConnectionSocketFactory sslSocketFactory = new NonVerifyingSslSocketFactory(sslContext);
    return (SSLSocket) sslSocketFactory.connectSocket(30000, null, new HttpHost(httpsUrl.getHost()), new InetSocketAddress(httpsUrl.getHost(), httpsUrl.getPort()), null, null);
}
Also used : HttpHost(org.apache.http.HttpHost) InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URL(java.net.URL) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Aggregations

SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)157 SSLContext (javax.net.ssl.SSLContext)99 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)63 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)54 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)52 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)49 IOException (java.io.IOException)42 TrustSelfSignedStrategy (org.apache.http.conn.ssl.TrustSelfSignedStrategy)42 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)42 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)36 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)31 KeyManagementException (java.security.KeyManagementException)30 RequestConfig (org.apache.http.client.config.RequestConfig)25 NoopHostnameVerifier (org.apache.http.conn.ssl.NoopHostnameVerifier)25 KeyStoreException (java.security.KeyStoreException)24 HttpClient (org.apache.http.client.HttpClient)24 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)24 KeyStore (java.security.KeyStore)22 CertificateException (java.security.cert.CertificateException)21 Test (org.junit.Test)21