Search in sources :

Example 6 with X509HostnameVerifier

use of org.apache.http.conn.ssl.X509HostnameVerifier in project syncany by syncany.

the class CommandLineClient method sendToRest.

private int sendToRest(Command command, String commandName, String[] commandArgs, File portFile) {
    try {
        // Read port config (for daemon) from port file
        PortTO portConfig = readPortConfig(portFile);
        // Create authentication details
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(SERVER_HOSTNAME, portConfig.getPort()), new UsernamePasswordCredentials(portConfig.getUser().getUsername(), portConfig.getUser().getPassword()));
        // Allow all hostnames in CN; this is okay as long as hostname is localhost/127.0.0.1!
        // See: https://github.com/syncany/syncany/pull/196#issuecomment-52197017
        X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();
        // Fetch the SSL context (using the user key/trust store)
        SSLContext sslContext = UserConfig.createUserSSLContext();
        // Create client with authentication details
        CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext).setHostnameVerifier(hostnameVerifier).setDefaultCredentialsProvider(credentialsProvider).build();
        // Build and send request, print response
        Request request = buildFolderRequestFromCommand(command, commandName, commandArgs, config.getLocalDir().getAbsolutePath());
        String serverUri = SERVER_SCHEMA + SERVER_HOSTNAME + ":" + portConfig.getPort() + SERVER_REST_API;
        String xmlMessageString = XmlMessageFactory.toXml(request);
        StringEntity xmlMessageEntity = new StringEntity(xmlMessageString);
        HttpPost httpPost = new HttpPost(serverUri);
        httpPost.setEntity(xmlMessageEntity);
        logger.log(Level.INFO, "Sending HTTP Request to: " + serverUri);
        logger.log(Level.FINE, httpPost.toString());
        logger.log(Level.FINE, xmlMessageString);
        HttpResponse httpResponse = client.execute(httpPost);
        int exitCode = handleRestResponse(command, httpResponse);
        return exitCode;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Command " + command.toString() + " FAILED. ", e);
        return showErrorAndExit(e.getMessage());
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) Request(org.syncany.operations.daemon.messages.api.Request) FolderRequest(org.syncany.operations.daemon.messages.api.FolderRequest) PortTO(org.syncany.config.to.PortTO) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SSLContext(javax.net.ssl.SSLContext) ConfigException(org.syncany.config.ConfigException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StringEntity(org.apache.http.entity.StringEntity) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) AuthScope(org.apache.http.auth.AuthScope)

Example 7 with X509HostnameVerifier

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

the class HttpTransportTest method testHttpServiceWithJsonWithHTTPS.

@Test
public void testHttpServiceWithJsonWithHTTPS() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    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).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);
    } 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) 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 8 with X509HostnameVerifier

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

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

the class Utils method createHttpClientTrustAll.

public static HttpClient createHttpClientTrustAll() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    }, 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;
        }
    });
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    registry.register(new Scheme("https", 443, sf));
    ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
    return new DefaultHttpClient(ccm);
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) PoolingClientConnectionManager(org.apache.http.impl.conn.PoolingClientConnectionManager) Scheme(org.apache.http.conn.scheme.Scheme) SSLSocket(javax.net.ssl.SSLSocket) SSLSession(javax.net.ssl.SSLSession) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) PoolingClientConnectionManager(org.apache.http.impl.conn.PoolingClientConnectionManager) X509Certificate(java.security.cert.X509Certificate) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 10 with X509HostnameVerifier

use of org.apache.http.conn.ssl.X509HostnameVerifier in project dal by ctripcorp.

the class WebUtil method initWeakSSLClient.

private static HttpClient initWeakSSLClient() {
    HttpClientBuilder b = HttpClientBuilder.create();
    // setup a Trust Strategy that allows all certificates.
    //
    SSLContext sslContext = null;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] arg0, String arg1) {
                return true;
            }
        }).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
    // do nothing, has been handled outside
    }
    b.setSslcontext(sslContext);
    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    X509HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);
    /**
         * Set timeout option
         */
    RequestConfig.Builder configBuilder = RequestConfig.custom();
    configBuilder.setConnectTimeout(TIMEOUT);
    configBuilder.setSocketTimeout(TIMEOUT);
    b.setDefaultRequestConfig(configBuilder.build());
    // finally, build the HttpClient;
    //      -- done!
    HttpClient sslClient = b.build();
    return sslClient;
}
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) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509Certificate(java.security.cert.X509Certificate) 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) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) HttpClient(org.apache.http.client.HttpClient) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder)

Aggregations

X509HostnameVerifier (org.apache.http.conn.ssl.X509HostnameVerifier)11 SSLContext (javax.net.ssl.SSLContext)7 IOException (java.io.IOException)5 X509Certificate (java.security.cert.X509Certificate)5 HttpClient (org.apache.http.client.HttpClient)5 Scheme (org.apache.http.conn.scheme.Scheme)5 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)5 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)5 TrustStrategy (org.apache.http.conn.ssl.TrustStrategy)5 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)5 CertificateException (java.security.cert.CertificateException)4 SSLException (javax.net.ssl.SSLException)4 SSLSession (javax.net.ssl.SSLSession)4 SSLSocket (javax.net.ssl.SSLSocket)4 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)4 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)4 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)4 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)4 SSLContextBuilder (org.apache.http.conn.ssl.SSLContextBuilder)3 ServiceError (com.kixeye.chassis.transport.dto.ServiceError)2