Search in sources :

Example 6 with SSLContextBuilder

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

the class HttpTransportTest method testHttpServiceWithJsonWithHTTPSAndHTTP.

@Test
public void testHttpServiceWithJsonWithHTTPSAndHTTP() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");
    properties.put("https.enabled", "true");
    properties.put("https.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("https.hostname", "localhost");
    properties.put("https.selfSigned", "true");
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);
    try {
        context.refresh();
        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
        SSLContextBuilder builder = SSLContexts.custom();
        builder.loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext = builder.build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

            @Override
            public void verify(String host, SSLSocket ssl) throws IOException {
            }

            @Override
            public void verify(String host, X509Certificate cert) throws SSLException {
            }

            @Override
            public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
            }

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build());
        RestTemplate httpClient = new RestTemplate(requestFactory);
        httpClient.setErrorHandler(new ResponseErrorHandler() {

            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {
            }
        });
        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));
        TestObject response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        response = httpClient.postForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        ResponseEntity<ServiceError> error = httpClient.postForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);
        error = httpClient.getForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);
        error = httpClient.getForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
        response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        response = httpClient.postForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("stuff"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        error = httpClient.postForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);
        error = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);
        error = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) HashMap(java.util.HashMap) ResponseErrorHandler(org.springframework.web.client.ResponseErrorHandler) SSLSocket(javax.net.ssl.SSLSocket) CertificateException(java.security.cert.CertificateException) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLException(javax.net.ssl.SSLException) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) StandardEnvironment(org.springframework.core.env.StandardEnvironment) ServiceError(com.kixeye.chassis.transport.dto.ServiceError) SSLSession(javax.net.ssl.SSLSession) YamlJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe) XmlMessageSerDe(com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe) JsonJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe) ProtobufMessageSerDe(com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) MapPropertySource(org.springframework.core.env.MapPropertySource) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) RestTemplate(org.springframework.web.client.RestTemplate) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) Test(org.junit.Test)

Example 7 with SSLContextBuilder

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

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

the class SSLTestConfig method buildClientSSLContext.

/**
   * Builds a new SSLContext for HTTP <b>clients</b> to use when communicating with servers which have 
   * been configured based on the settings of this object.  
   *
   * NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking 
   * due to lack of entropy, also explicitly allows the use of self-signed 
   * certificates (since that's what is almost always used during testing).
   */
public SSLContext buildClientSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    assert isSSLMode();
    SSLContextBuilder builder = SSLContexts.custom();
    builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE);
    // NOTE: KeyStore & TrustStore are swapped because they are from configured from server perspective...
    // we are a client - our keystore contains the keys the server trusts, and vice versa
    builder.loadTrustMaterial(buildKeyStore(keyStore, getKeyStorePassword()), new TrustSelfSignedStrategy()).build();
    if (isClientAuthMode()) {
        builder.loadKeyMaterial(buildKeyStore(trustStore, getTrustStorePassword()), getTrustStorePassword().toCharArray());
    }
    return builder.build();
}
Also used : SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 9 with SSLContextBuilder

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

the class SSLTestConfig method buildServerSSLContext.

/**
   * Builds a new SSLContext for jetty servers which have been configured based on the settings of 
   * this object.
   *
   * NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking 
   * due to lack of entropy, also explicitly allows the use of self-signed 
   * certificates (since that's what is almost always used during testing).
   * almost always used during testing). 
   */
public SSLContext buildServerSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    assert isSSLMode();
    SSLContextBuilder builder = SSLContexts.custom();
    builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE);
    builder.loadKeyMaterial(buildKeyStore(keyStore, getKeyStorePassword()), getKeyStorePassword().toCharArray());
    if (isClientAuthMode()) {
        builder.loadTrustMaterial(buildKeyStore(trustStore, getTrustStorePassword()), new TrustSelfSignedStrategy()).build();
    }
    return builder.build();
}
Also used : SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 10 with SSLContextBuilder

use of org.apache.http.conn.ssl.SSLContextBuilder in project iTest by e-government-ua.

the class DeleteTask method createHttpClient_AcceptsUntrustedCerts.

public HttpClient createHttpClient_AcceptsUntrustedCerts() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSslcontext(sslContext);
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);
    HttpClient client = b.build();
    return client;
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpClient(org.apache.http.client.HttpClient) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContext(javax.net.ssl.SSLContext) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Aggregations

SSLContextBuilder (org.apache.http.conn.ssl.SSLContextBuilder)10 SSLContext (javax.net.ssl.SSLContext)7 X509Certificate (java.security.cert.X509Certificate)5 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)5 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)5 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)5 TrustStrategy (org.apache.http.conn.ssl.TrustStrategy)5 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)5 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)4 URI (java.net.URI)3 CertificateException (java.security.cert.CertificateException)3 TrustSelfSignedStrategy (org.apache.http.conn.ssl.TrustSelfSignedStrategy)3 X509HostnameVerifier (org.apache.http.conn.ssl.X509HostnameVerifier)3 ServiceError (com.kixeye.chassis.transport.dto.ServiceError)2 SerDeHttpMessageConverter (com.kixeye.chassis.transport.http.SerDeHttpMessageConverter)2 MessageSerDe (com.kixeye.chassis.transport.serde.MessageSerDe)2 JsonJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe)2 ProtobufMessageSerDe (com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe)2 XmlMessageSerDe (com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe)2 YamlJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe)2