Search in sources :

Example 1 with TrustStrategy

use of org.apache.http.conn.ssl.TrustStrategy 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 TrustStrategy

use of org.apache.http.conn.ssl.TrustStrategy in project cloudstack by apache.

the class HypervDirectConnectResource method postHttpRequest.

public static String postHttpRequest(final String jsonCmd, final URI agentUri) {
    // Using Apache's HttpClient for HTTP POST
    // Java-only approach discussed at on StackOverflow concludes with
    // comment to use Apache HttpClient
    // http://stackoverflow.com/a/2793153/939250, but final comment is to
    // use Apache.
    String logMessage = StringEscapeUtils.unescapeJava(jsonCmd);
    logMessage = cleanPassword(logMessage);
    s_logger.debug("POST request to " + agentUri.toString() + " with contents " + logMessage);
    // Create request
    HttpClient httpClient = null;
    final TrustStrategy easyStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
            return true;
        }
    };
    try {
        final SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf));
        final ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (final KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }
    String result = null;
    // TODO: are there timeout settings and worker thread settings to tweak?
    try {
        final HttpPost request = new HttpPost(agentUri);
        // JSON encode command
        // Assumes command sits comfortably in a string, i.e. not used for
        // large data transfers
        final StringEntity cmdJson = new StringEntity(jsonCmd);
        request.addHeader("content-type", "application/json");
        request.setEntity(cmdJson);
        s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage);
        final HttpResponse response = httpClient.execute(request);
        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            final String errMsg = "Failed to send : HTTP error code : " + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            final String unsupportMsg = "Unsupported command " + agentUri.getPath() + ".  Are you sure you got the right type of" + " server?";
            final Answer ans = new UnsupportedAnswer(null, unsupportMsg);
            s_logger.error(ans);
            result = s_gson.toJson(new Answer[] { ans });
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            final String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            return null;
        } else {
            result = EntityUtils.toString(response.getEntity());
            final String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }
    } catch (final ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (final IOException connEx) {
        // Problem with underlying communications
        s_logger.error(connEx);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) HttpResponse(org.apache.http.HttpResponse) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyManagementException(java.security.KeyManagementException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) UnsupportedAnswer(com.cloud.agent.api.UnsupportedAnswer) CheckSshAnswer(com.cloud.agent.api.check.CheckSshAnswer) GetDomRVersionAnswer(com.cloud.agent.api.GetDomRVersionAnswer) CheckS2SVpnConnectionsAnswer(com.cloud.agent.api.CheckS2SVpnConnectionsAnswer) SetPortForwardingRulesAnswer(com.cloud.agent.api.routing.SetPortForwardingRulesAnswer) SetSourceNatAnswer(com.cloud.agent.api.routing.SetSourceNatAnswer) PlugNicAnswer(com.cloud.agent.api.PlugNicAnswer) GetVmConfigAnswer(com.cloud.agent.api.GetVmConfigAnswer) NetworkUsageAnswer(com.cloud.agent.api.NetworkUsageAnswer) Answer(com.cloud.agent.api.Answer) UnPlugNicAnswer(com.cloud.agent.api.UnPlugNicAnswer) SetStaticNatRulesAnswer(com.cloud.agent.api.routing.SetStaticNatRulesAnswer) IpAssocAnswer(com.cloud.agent.api.routing.IpAssocAnswer) SetFirewallRulesAnswer(com.cloud.agent.api.routing.SetFirewallRulesAnswer) CheckRouterAnswer(com.cloud.agent.api.CheckRouterAnswer) SetStaticRouteAnswer(com.cloud.agent.api.routing.SetStaticRouteAnswer) UnsupportedAnswer(com.cloud.agent.api.UnsupportedAnswer) UnrecoverableKeyException(java.security.UnrecoverableKeyException) HttpClient(org.apache.http.client.HttpClient) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 3 with TrustStrategy

use of org.apache.http.conn.ssl.TrustStrategy in project oxAuth by GluuFederation.

the class HttpService method getHttpsClientTrustAll.

public HttpClient getHttpsClientTrustAll() {
    try {
        SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, new AllowAllHostnameVerifier());
        PlainSocketFactory psf = PlainSocketFactory.getSocketFactory();
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", 80, psf));
        registry.register(new Scheme("https", 443, sf));
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
        return new DefaultHttpClient(ccm);
    } catch (Exception ex) {
        log.error("Failed to create TrustAll https client", ex);
        return new DefaultHttpClient();
    }
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) PoolingClientConnectionManager(org.apache.http.impl.conn.PoolingClientConnectionManager) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) CertificateException(java.security.cert.CertificateException) PlainSocketFactory(org.apache.http.conn.scheme.PlainSocketFactory) PoolingClientConnectionManager(org.apache.http.impl.conn.PoolingClientConnectionManager) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) X509Certificate(java.security.cert.X509Certificate) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) SslDefaultHttpClient(org.xdi.net.SslDefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 4 with TrustStrategy

use of org.apache.http.conn.ssl.TrustStrategy in project gocd by gocd.

the class GoAgentServerHttpClientBuilder method build.

public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).build()).setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();
    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create().useProtocol(systemEnvironment.get(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT));
    if (trustStore != null || trustStrategy != null) {
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    }
    sslContextBuilder.loadKeyMaterial(agentKeystore(), keystorePassword().toCharArray());
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Example 5 with TrustStrategy

use of org.apache.http.conn.ssl.TrustStrategy in project openhab1-addons by openhab.

the class Util method getConnection.

public static Sardine getConnection(CalDavConfig config) {
    if (config.isDisableCertificateVerification()) {
        if (config.getUrl().startsWith(HTTP_URL_PREFIX)) {
            log.error("do not use '{}' if no ssl is used", CalDavLoaderImpl.PROP_DISABLE_CERTIFICATE_VERIFICATION);
        }
        log.trace("connecting to caldav '{}' with disabled certificate verification (url={}, username={}, password={})", config.getKey(), config.getUrl(), config.getUsername(), config.getPassword());
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setHostnameVerifier(new AllowAllHostnameVerifier());
        try {
            httpClientBuilder.setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                @Override
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build());
        } catch (KeyManagementException e) {
            log.error("error verifying certificate", e);
        } catch (NoSuchAlgorithmException e) {
            log.error("error verifying certificate", e);
        } catch (KeyStoreException e) {
            log.error("error verifying certificate", e);
        }
        if (StringUtils.isEmpty(config.getUsername()) && StringUtils.isEmpty(config.getPassword())) {
            log.trace("connecting without credentials for '{}'", config.getKey());
            return new SardineImpl(httpClientBuilder);
        } else {
            return new SardineImpl(httpClientBuilder, config.getUsername(), config.getPassword());
        }
    } else {
        log.trace("connecting to caldav '{}' (url={}, username={}, password={})", config.getKey(), config.getUrl(), config.getUsername(), config.getPassword());
        if (StringUtils.isEmpty(config.getUsername()) && StringUtils.isEmpty(config.getPassword())) {
            log.trace("connecting without credentials for '{}'", config.getKey());
            return new SardineImpl();
        } else {
            return new SardineImpl(config.getUsername(), config.getPassword());
        }
    }
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) CertificateException(java.security.cert.CertificateException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) SardineImpl(com.github.sardine.impl.SardineImpl)

Aggregations

TrustStrategy (org.apache.http.conn.ssl.TrustStrategy)12 X509Certificate (java.security.cert.X509Certificate)8 CertificateException (java.security.cert.CertificateException)7 IOException (java.io.IOException)6 SSLContext (javax.net.ssl.SSLContext)6 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)6 X509HostnameVerifier (org.apache.http.conn.ssl.X509HostnameVerifier)5 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)4 Scheme (org.apache.http.conn.scheme.Scheme)4 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)4 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)4 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)4 AllowAllHostnameVerifier (org.apache.http.conn.ssl.AllowAllHostnameVerifier)4 SSLContextBuilder (org.apache.http.conn.ssl.SSLContextBuilder)4 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)4 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)4 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)4 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)4 URI (java.net.URI)3 KeyManagementException (java.security.KeyManagementException)3