Search in sources :

Example 6 with TrustSelfSignedStrategy

use of org.apache.http.conn.ssl.TrustSelfSignedStrategy in project spring-boot by spring-projects.

the class AbstractServletWebServerFactoryTests method serverHeaderCanBeCustomizedWhenUsingSsl.

@Test
public void serverHeaderCanBeCustomizedWhenUsingSsl() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    factory.setServerHeader("MyServer");
    factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks"));
    this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello"));
    this.webServer.start();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), HttpMethod.GET, new HttpComponentsClientHttpRequestFactory(httpClient));
    assertThat(response.getHeaders().get("Server")).containsExactly("MyServer");
}
Also used : ServletRegistrationBean(org.springframework.boot.web.servlet.ServletRegistrationBean) HttpClient(org.apache.http.client.HttpClient) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) Test(org.junit.Test)

Example 7 with TrustSelfSignedStrategy

use of org.apache.http.conn.ssl.TrustSelfSignedStrategy in project metron by apache.

the class TaxiiHandler method buildClient.

private static HttpClient buildClient(URL proxy, String username, String password) throws Exception {
    // Start with a default TAXII HTTP client.
    HttpClient client = new HttpClient();
    // Create an Apache HttpClientBuilder to be customized by the command line arguments.
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
    // Proxy
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
        builder.setProxy(proxyHost);
    }
    // Basic authentication. User & Password
    if (username != null ^ password != null) {
        throw new Exception("'username' and 'password' arguments are required to appear together.");
    }
    // from:  http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3
    SSLContextBuilder ssbldr = new SSLContextBuilder();
    ssbldr.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ssbldr.build(), SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    // max connection
    cm.setMaxTotal(20);
    // ""
    System.setProperty("jsse.enableSNIExtension", "false");
    CloseableHttpClient httpClient = builder.setSSLSocketFactory(sslsf).setConnectionManager(cm).build();
    client.setHttpclient(httpClient);
    return client;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) HttpHost(org.apache.http.HttpHost) HttpClient(org.mitre.taxii.client.HttpClient) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) DatatypeConfigurationException(javax.xml.datatype.DatatypeConfigurationException) JAXBException(javax.xml.bind.JAXBException) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 8 with TrustSelfSignedStrategy

use of org.apache.http.conn.ssl.TrustSelfSignedStrategy in project janusgraph by JanusGraph.

the class SSLConfigurationCallbackTest method testAllowSelfSignedCerts.

@Test
public void testAllowSelfSignedCerts() throws Exception {
    final SSLConfigurationCallback cb = SSLConfigurationCallback.Builder.createCustom(sslContextBuilderMock).allowSelfSignedCertificates().build();
    cb.customizeHttpClient(httpAsyncClientBuilderMock);
    final ArgumentCaptor<TrustStrategy> trustStrategyCaptor = ArgumentCaptor.forClass(TrustStrategy.class);
    verify(sslContextBuilderMock).loadTrustMaterial(trustStrategyCaptor.capture());
    verify(sslContextBuilderMock).build();
    verify(httpAsyncClientBuilderMock).setSSLContext(sslContextMock);
    verifyNoMoreInteractions(sslContextMock, sslContextBuilderMock, httpAsyncClientBuilderMock);
    assertEquals(1, trustStrategyCaptor.getAllValues().size());
    final TrustStrategy trustStrategy = trustStrategyCaptor.getValue();
    // this assertion is implementation-specific but should be good enough
    // given the simplicity of the class under test
    assertTrue(trustStrategy instanceof TrustSelfSignedStrategy);
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 9 with TrustSelfSignedStrategy

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

the class Tr064Comm method createTr064HttpClient.

/***
     * Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
     * and sets Auth. Scheme to Digest Auth
     *
     * @param fboxUrl the URL from config file of fbox to connect to
     * @return the ready-to-use httpclient for tr064 requests
     */
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);
    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
    // auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    // known from fbox specification
    digestAuth.overrideParamter("realm", "HTTPS Access");
    // never known at first request
    digestAuth.overrideParamter("nonce", "");
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);
    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        // accept self signed certs
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        // dont
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
    // verify
    // hostname
    // against
    // cert
    // CN
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
    // BUILDER
    // setup builder with parameters defined before
    hc = // set the SSL options which trust every self signed
    HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// set auth options using digest
    credp).setDefaultRequestConfig(// set the request config specifying timeout
    rc).build();
    return hc;
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) URISyntaxException(java.net.URISyntaxException) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URISyntaxException(java.net.URISyntaxException) SOAPException(javax.xml.soap.SOAPException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 10 with TrustSelfSignedStrategy

use of org.apache.http.conn.ssl.TrustSelfSignedStrategy in project spring-boot by spring-projects.

the class AbstractServletWebServerFactoryTests method sslWantsClientAuthenticationSucceedsWithClientCertificate.

@Test
public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    addTestTxtFile(factory);
    factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks"));
    this.webServer = factory.getWebServer();
    this.webServer.start();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray());
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).loadKeyMaterial(keyStore, "password".toCharArray()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test");
}
Also used : HttpClient(org.apache.http.client.HttpClient) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) KeyStore(java.security.KeyStore) File(java.io.File) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) FileInputStream(java.io.FileInputStream) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) Test(org.junit.Test)

Aggregations

TrustSelfSignedStrategy (org.apache.http.conn.ssl.TrustSelfSignedStrategy)25 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)19 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)15 HttpClient (org.apache.http.client.HttpClient)13 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)13 Test (org.junit.Test)12 File (java.io.File)6 KeyStore (java.security.KeyStore)6 SSLContextBuilder (org.apache.http.conn.ssl.SSLContextBuilder)6 FileInputStream (java.io.FileInputStream)5 ServletRegistrationBean (org.springframework.boot.web.servlet.ServletRegistrationBean)5 IOException (java.io.IOException)4 SSLContext (javax.net.ssl.SSLContext)4 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)4 RequestConfig (org.apache.http.client.config.RequestConfig)2 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)2 HttpGet (org.apache.http.client.methods.HttpGet)2 NoopHostnameVerifier (org.apache.http.conn.ssl.NoopHostnameVerifier)2 ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)2 BufferedReader (java.io.BufferedReader)1