Search in sources :

Example 1 with SSLContextBuilder

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

the class TestJSONOverHttps method callProcOverJSON.

private String callProcOverJSON(String varString, final int expectedCode) throws Exception {
    URI uri = URI.create("https://localhost:" + m_port + "/api/1.0/");
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return 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 b = HttpClientBuilder.create();
    b.setSslcontext(sslContext);
    b.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = b.build()) {
        HttpPost post = new HttpPost(uri);
        // 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();
        post.setProtocolVersion(HttpVersion.HTTP_1_1);
        post.setConfig(rc);
        post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || status == 400) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(post, rh);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StringEntity(org.apache.http.entity.StringEntity) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder)

Example 2 with SSLContextBuilder

use of org.apache.http.conn.ssl.SSLContextBuilder in project camel by apache.

the class JettySolrFactory method installAllTrustingClientSsl.

private static void installAllTrustingClientSsl() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    // // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override
        public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    SSLContext.setDefault(sslContext);
// // Install the all-trusting trust manager
// final SSLContext sslContext = SSLContext.getInstance( "SSL" );
// sslContext.init( null, trustAllCerts, new
// java.security.SecureRandom() );
// // Create an ssl socket factory with our all-trusting manager
// final SSLSocketFactory sslSocketFactory =
// sslContext.getSocketFactory();
// HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) SSLContext(javax.net.ssl.SSLContext) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) X509Certificate(java.security.cert.X509Certificate) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 3 with SSLContextBuilder

use of org.apache.http.conn.ssl.SSLContextBuilder in project nifi by apache.

the class PostHTTP method createSSLContext.

private SSLContext createSSLContext(final SSLContextService service) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }
    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }
    builder = builder.useProtocol(service.getSslAlgorithm());
    final SSLContext sslContext = builder.build();
    return sslContext;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SSLContext(javax.net.ssl.SSLContext) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) KeyStore(java.security.KeyStore) File(java.io.File) FlowFile(org.apache.nifi.flowfile.FlowFile) FileInputStream(java.io.FileInputStream) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 4 with SSLContextBuilder

use of org.apache.http.conn.ssl.SSLContextBuilder in project acs-aem-commons by Adobe-Consulting-Services.

the class HttpClientFactoryImpl method activate.

@Activate
protected void activate(Map<String, Object> config) throws Exception {
    boolean useSSL = PropertiesUtil.toBoolean(config.get(PROP_USE_SSL), DEFAULT_USE_SSL);
    String scheme = useSSL ? "https" : "http";
    String hostname = PropertiesUtil.toString(config.get(PROP_HOST_DOMAIN), null);
    int port = PropertiesUtil.toInteger(config.get(PROP_GATEWAY_PORT), 0);
    if (hostname == null || port == 0) {
        throw new IllegalArgumentException("Configuration not valid. Both host and port must be provided.");
    }
    baseUrl = String.format("%s://%s:%s", scheme, hostname, port);
    int connectTimeout = PropertiesUtil.toInteger(config.get(PROP_CONNECT_TIMEOUT), DEFAULT_CONNECT_TIMEOUT);
    int soTimeout = PropertiesUtil.toInteger(config.get(PROP_SO_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
    HttpClientBuilder builder = httpClientBuilderFactory.newBuilder();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(soTimeout).build();
    builder.setDefaultRequestConfig(requestConfig);
    boolean disableCertCheck = PropertiesUtil.toBoolean(config.get(PROP_DISABLE_CERT_CHECK), DEFAULT_DISABLE_CERT_CHECK);
    if (useSSL && disableCertCheck) {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        builder.setHostnameVerifier(new AllowAllHostnameVerifier()).setSslcontext(sslContext);
    }
    httpClient = builder.build();
    executor = Executor.newInstance(httpClient);
    String username = PropertiesUtil.toString(config.get(PROP_USERNAME), null);
    String password = PropertiesUtil.toString(config.get(PROP_PASSWORD), null);
    if (username != null && password != null) {
        HttpHost httpHost = new HttpHost(hostname, port, useSSL ? "https" : "http");
        executor.auth(httpHost, username, password).authPreemptive(httpHost);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) HttpHost(org.apache.http.HttpHost) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContext(javax.net.ssl.SSLContext) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) Activate(org.apache.felix.scr.annotations.Activate)

Example 5 with SSLContextBuilder

use of org.apache.http.conn.ssl.SSLContextBuilder in project validator by validator.

the class PrudentHttpEntityResolver method setParams.

/**
 * Sets the timeouts of the HTTP client.
 *
 * @param connectionTimeout
 *            timeout until connection established in milliseconds. Zero
 *            means no timeout.
 * @param socketTimeout
 *            timeout for waiting for data in milliseconds. Zero means no
 *            timeout.
 * @param maxRequests
 *            maximum number of connections to a particular host
 */
public static void setParams(int connectionTimeout, int socketTimeout, int maxRequests) {
    PrudentHttpEntityResolver.maxRequests = maxRequests;
    PoolingHttpClientConnectionManager phcConnMgr;
    // 
    Registry<ConnectionSocketFactory> registry = // 
    RegistryBuilder.<ConnectionSocketFactory>create().register("http", // 
    PlainConnectionSocketFactory.getSocketFactory()).register("https", // 
    SSLConnectionSocketFactory.getSocketFactory()).build();
    HttpClientBuilder builder = HttpClients.custom().useSystemProperties();
    builder.setRedirectStrategy(new LaxRedirectStrategy());
    builder.setMaxConnPerRoute(maxRequests);
    builder.setMaxConnTotal(Integer.parseInt(System.getProperty("nu.validator.servlet.max-total-connections", "200")));
    if ("true".equals(System.getProperty("nu.validator.xml.promiscuous-ssl", "true"))) {
        // 
        try {
            SSLContext promiscuousSSLContext = // 
            new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                @Override
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build();
            builder.setSslcontext(promiscuousSSLContext);
            // 
            HostnameVerifier verifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            // 
            SSLConnectionSocketFactory promiscuousSSLConnSocketFactory = new SSLConnectionSocketFactory(promiscuousSSLContext, verifier);
            registry = // 
            RegistryBuilder.<ConnectionSocketFactory>create().register("https", // 
            promiscuousSSLConnSocketFactory).register("http", // 
            PlainConnectionSocketFactory.getSocketFactory()).build();
        } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException | NumberFormatException e) {
            e.printStackTrace();
        }
    }
    phcConnMgr = new PoolingHttpClientConnectionManager(registry);
    phcConnMgr.setDefaultMaxPerRoute(maxRequests);
    phcConnMgr.setMaxTotal(200);
    builder.setConnectionManager(phcConnMgr);
    RequestConfig.Builder config = RequestConfig.custom();
    config.setCircularRedirectsAllowed(true);
    config.setMaxRedirects(Integer.parseInt(System.getProperty("nu.validator.servlet.max-redirects", "20")));
    config.setConnectTimeout(connectionTimeout);
    config.setCookieSpec(CookieSpecs.BEST_MATCH);
    config.setSocketTimeout(socketTimeout);
    config.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
    client = builder.setDefaultRequestConfig(config.build()).build();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) KeyManagementException(java.security.KeyManagementException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) LaxRedirectStrategy(org.apache.http.impl.client.LaxRedirectStrategy) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder)

Aggregations

SSLContextBuilder (org.apache.http.conn.ssl.SSLContextBuilder)21 SSLContext (javax.net.ssl.SSLContext)11 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)11 TrustSelfSignedStrategy (org.apache.http.conn.ssl.TrustSelfSignedStrategy)9 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)8 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)8 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)8 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)8 KeyManagementException (java.security.KeyManagementException)7 KeyStoreException (java.security.KeyStoreException)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 TrustStrategy (org.apache.http.conn.ssl.TrustStrategy)7 RequestConfig (org.apache.http.client.config.RequestConfig)6 IOException (java.io.IOException)5 X509Certificate (java.security.cert.X509Certificate)5 CertificateException (java.security.cert.CertificateException)4 X509HostnameVerifier (org.apache.http.conn.ssl.X509HostnameVerifier)4 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)4 URI (java.net.URI)3 AllowAllHostnameVerifier (org.apache.http.conn.ssl.AllowAllHostnameVerifier)3