Search in sources :

Example 31 with AllowAllHostnameVerifier

use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project keycloak by keycloak.

the class HttpClientBuilder method build.

public HttpClient build() {
    X509HostnameVerifier verifier = null;
    if (this.verifier != null)
        verifier = new VerifierWrapper(this.verifier);
    else {
        switch(policy) {
            case ANY:
                verifier = new AllowAllHostnameVerifier();
                break;
            case WILDCARD:
                verifier = new BrowserCompatHostnameVerifier();
                break;
            case STRICT:
                verifier = new StrictHostnameVerifier();
                break;
        }
    }
    try {
        SSLSocketFactory sslsf = null;
        SSLContext theContext = sslContext;
        if (disableTrustManager) {
            theContext = SSLContext.getInstance("SSL");
            theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
            verifier = new AllowAllHostnameVerifier();
            sslsf = new SniSSLSocketFactory(theContext, verifier);
        } else if (theContext != null) {
            sslsf = new SniSSLSocketFactory(theContext, verifier);
        } else if (clientKeyStore != null || truststore != null) {
            sslsf = new SniSSLSocketFactory(SSLSocketFactory.TLS, clientKeyStore, clientPrivateKeyPassword, truststore, null, verifier);
        } else {
            final SSLContext tlsContext = SSLContext.getInstance(SSLSocketFactory.TLS);
            tlsContext.init(null, null, null);
            sslsf = new SniSSLSocketFactory(tlsContext, verifier);
        }
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        registry.register(httpsScheme);
        ClientConnectionManager cm = null;
        if (connectionPoolSize > 0) {
            ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry, connectionTTL, connectionTTLUnit);
            tcm.setMaxTotal(connectionPoolSize);
            if (maxPooledPerRoute == 0)
                maxPooledPerRoute = connectionPoolSize;
            tcm.setDefaultMaxPerRoute(maxPooledPerRoute);
            cm = tcm;
        } else {
            cm = new SingleClientConnManager(registry);
        }
        BasicHttpParams params = new BasicHttpParams();
        params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        if (proxyHost != null) {
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
        if (socketTimeout > -1) {
            HttpConnectionParams.setSoTimeout(params, (int) socketTimeoutUnits.toMillis(socketTimeout));
        }
        if (establishConnectionTimeout > -1) {
            HttpConnectionParams.setConnectionTimeout(params, (int) establishConnectionTimeoutUnits.toMillis(establishConnectionTimeout));
        }
        DefaultHttpClient client = new DefaultHttpClient(cm, params);
        if (disableCookieCache) {
            client.setCookieStore(new CookieStore() {

                @Override
                public void addCookie(Cookie cookie) {
                // To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public List<Cookie> getCookies() {
                    return Collections.emptyList();
                }

                @Override
                public boolean clearExpired(Date date) {
                    // To change body of implemented methods use File | Settings | File Templates.
                    return false;
                }

                @Override
                public void clear() {
                // To change body of implemented methods use File | Settings | File Templates.
                }
            });
        }
        return client;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) Date(java.util.Date) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) CookieStore(org.apache.http.client.CookieStore) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) SingleClientConnManager(org.apache.http.impl.conn.SingleClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BrowserCompatHostnameVerifier(org.apache.http.conn.ssl.BrowserCompatHostnameVerifier) List(java.util.List) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 32 with AllowAllHostnameVerifier

use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project keycloak by keycloak.

the class HttpClientBuilder method build.

public HttpClient build() {
    X509HostnameVerifier verifier = null;
    if (this.verifier != null)
        verifier = new VerifierWrapper(this.verifier);
    else {
        switch(policy) {
            case ANY:
                verifier = new AllowAllHostnameVerifier();
                break;
            case WILDCARD:
                verifier = new BrowserCompatHostnameVerifier();
                break;
            case STRICT:
                verifier = new StrictHostnameVerifier();
                break;
        }
    }
    try {
        SSLSocketFactory sslsf = null;
        SSLContext theContext = sslContext;
        if (disableTrustManager) {
            theContext = SSLContext.getInstance("SSL");
            theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
            verifier = new AllowAllHostnameVerifier();
            sslsf = new SniSSLSocketFactory(theContext, verifier);
        } else if (theContext != null) {
            sslsf = new SniSSLSocketFactory(theContext, verifier);
        } else if (clientKeyStore != null || truststore != null) {
            sslsf = new SniSSLSocketFactory(SSLSocketFactory.TLS, clientKeyStore, clientPrivateKeyPassword, truststore, null, verifier);
        } else {
            final SSLContext tlsContext = SSLContext.getInstance(SSLSocketFactory.TLS);
            tlsContext.init(null, null, null);
            sslsf = new SniSSLSocketFactory(tlsContext, verifier);
        }
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        registry.register(httpsScheme);
        ClientConnectionManager cm = null;
        if (connectionPoolSize > 0) {
            ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry, connectionTTL, connectionTTLUnit);
            tcm.setMaxTotal(connectionPoolSize);
            if (maxPooledPerRoute == 0)
                maxPooledPerRoute = connectionPoolSize;
            tcm.setDefaultMaxPerRoute(maxPooledPerRoute);
            cm = tcm;
        } else {
            cm = new SingleClientConnManager(registry);
        }
        BasicHttpParams params = new BasicHttpParams();
        params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        if (proxyHost != null) {
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
        if (socketTimeout > -1) {
            HttpConnectionParams.setSoTimeout(params, (int) socketTimeoutUnits.toMillis(socketTimeout));
        }
        if (establishConnectionTimeout > -1) {
            HttpConnectionParams.setConnectionTimeout(params, (int) establishConnectionTimeoutUnits.toMillis(establishConnectionTimeout));
        }
        DefaultHttpClient client = new DefaultHttpClient(cm, params);
        if (disableCookieCache) {
            client.setCookieStore(new CookieStore() {

                @Override
                public void addCookie(Cookie cookie) {
                // To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public List<Cookie> getCookies() {
                    return Collections.emptyList();
                }

                @Override
                public boolean clearExpired(Date date) {
                    // To change body of implemented methods use File | Settings | File Templates.
                    return false;
                }

                @Override
                public void clear() {
                // To change body of implemented methods use File | Settings | File Templates.
                }
            });
        }
        return client;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) Date(java.util.Date) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) CookieStore(org.apache.http.client.CookieStore) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) SingleClientConnManager(org.apache.http.impl.conn.SingleClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BrowserCompatHostnameVerifier(org.apache.http.conn.ssl.BrowserCompatHostnameVerifier) List(java.util.List) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 33 with AllowAllHostnameVerifier

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

the class NetScalerControlCenterResource method getHttpClient.

public static HttpClient getHttpClient() {
    HttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_PORT, sf));
        ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }
    return httpClient;
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyManagementException(java.security.KeyManagementException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 34 with AllowAllHostnameVerifier

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

the class NetScalerControlCenterResource method postHttpRequest.

public static String postHttpRequest(final String jsonCmd, final URI agentUri, String sessionID) throws ExecutionException {
    // 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 = getHttpClient();
    TrustStrategy easyStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_PORT, sf));
        ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (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 {
        HttpPost request = new HttpPost(agentUri);
        // JSON encode command
        // Assumes command sits comfortably in a string, i.e. not used for
        // large data transfers
        StringEntity cmdJson = new StringEntity(jsonCmd);
        request.addHeader("content-type", "application/json");
        request.addHeader("Cookie", "SessId=" + sessionID);
        request.setEntity(cmdJson);
        s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage + "SEssion id: " + sessionID);
        HttpResponse response = httpClient.execute(request);
        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            String errMsg = "Failed : HTTP error code : " + response.getStatusLine().getStatusCode();
            throw new ExecutionException(NccHttpCode.NOT_FOUND);
        } else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) && (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED)) {
            String errMsg = "Command Not Success " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            throw new ExecutionException(NccHttpCode.INTERNAL_ERROR + " " + errMsg);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            // make login request and store new session id
            throw new ExecutionException(NccHttpCode.UNAUTHORIZED);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            // Successfully created the resource in the NCC, Now get the Job ID and send to the response
            result = response.getFirstHeader(NccHttpCode.JOB_ID).getValue();
        } else {
            result = EntityUtils.toString(response.getEntity());
            String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }
    } catch (ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (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) UnrecoverableKeyException(java.security.UnrecoverableKeyException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 35 with AllowAllHostnameVerifier

use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project qi4j-sdk by Qi4j.

the class AbstractSecureJettyTest method beforeSecure.

@Before
public void beforeSecure() throws GeneralSecurityException, IOException {
    // Trust HTTP Client
    KeyStore truststore = KeyStore.getInstance("JCEKS");
    truststore.load(new FileInputStream(TRUSTSTORE_FILE), KS_PASSWORD.toCharArray());
    AllowAllHostnameVerifier verifier = new AllowAllHostnameVerifier();
    DefaultHttpClient trustClient = new DefaultHttpClient();
    SSLSocketFactory trustSslFactory = new SSLSocketFactory(truststore);
    trustSslFactory.setHostnameVerifier(verifier);
    SchemeRegistry trustSchemeRegistry = trustClient.getConnectionManager().getSchemeRegistry();
    trustSchemeRegistry.unregister(HTTPS);
    trustSchemeRegistry.register(new Scheme(HTTPS, HTTPS_PORT, trustSslFactory));
    trustHttpClient = trustClient;
    // Mutual HTTP Client
    KeyStore keystore = KeyStore.getInstance("JCEKS");
    keystore.load(new FileInputStream(CLIENT_KEYSTORE_FILE), KS_PASSWORD.toCharArray());
    DefaultHttpClient mutualClient = new DefaultHttpClient();
    SSLSocketFactory mutualSslFactory = new SSLSocketFactory(keystore, KS_PASSWORD, truststore);
    mutualSslFactory.setHostnameVerifier(verifier);
    SchemeRegistry mutualSchemeRegistry = mutualClient.getConnectionManager().getSchemeRegistry();
    mutualSchemeRegistry.unregister(HTTPS);
    mutualSchemeRegistry.register(new Scheme(HTTPS, HTTPS_PORT, mutualSslFactory));
    mutualHttpClient = mutualClient;
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) Before(org.junit.Before)

Aggregations

AllowAllHostnameVerifier (org.apache.http.conn.ssl.AllowAllHostnameVerifier)35 Scheme (org.apache.http.conn.scheme.Scheme)22 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)22 HttpResponse (org.apache.http.HttpResponse)15 HttpClient (org.apache.http.client.HttpClient)15 MockResponse (com.google.mockwebserver.MockResponse)12 RecordedRequest (com.google.mockwebserver.RecordedRequest)12 TestSSLContext (libcore.javax.net.ssl.TestSSLContext)12 HttpGet (org.apache.http.client.methods.HttpGet)12 IOException (java.io.IOException)10 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)10 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)10 SSLContext (javax.net.ssl.SSLContext)9 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)9 KeyManagementException (java.security.KeyManagementException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 CertificateException (java.security.cert.CertificateException)8 TrustStrategy (org.apache.http.conn.ssl.TrustStrategy)8 KeyStoreException (java.security.KeyStoreException)7 UnrecoverableKeyException (java.security.UnrecoverableKeyException)5