Example usage for org.apache.http.conn.ssl NoopHostnameVerifier INSTANCE

List of usage examples for org.apache.http.conn.ssl NoopHostnameVerifier INSTANCE

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl NoopHostnameVerifier INSTANCE.

Prototype

NoopHostnameVerifier INSTANCE

To view the source code for org.apache.http.conn.ssl NoopHostnameVerifier INSTANCE.

Click Source Link

Usage

From source file:com.aliyun.oss.common.comm.DefaultServiceClient.java

protected HttpClientConnectionManager createHttpClientConnectionManager() {
    SSLContext sslContext = null;
    try {//from   ww w  .  j  av  a  2s .c o  m
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        }).build();

    } catch (Exception e) {
        throw new ClientException(e.getMessage());
    }

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(Protocol.HTTP.toString(), PlainConnectionSocketFactory.getSocketFactory())
            .register(Protocol.HTTPS.toString(), sslSocketFactory).build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnections());
    connectionManager.setMaxTotal(config.getMaxConnections());
    connectionManager.setValidateAfterInactivity(config.getValidateAfterInactivity());
    connectionManager.setDefaultSocketConfig(
            SocketConfig.custom().setSoTimeout(config.getSocketTimeout()).setTcpNoDelay(true).build());
    if (config.isUseReaper()) {
        IdleConnectionReaper.setIdleConnectionTime(config.getIdleConnectionTime());
        IdleConnectionReaper.registerConnectionManager(connectionManager);
    }
    return connectionManager;
}

From source file:org.jboss.pnc.auth.keycloakutil.util.HttpUtil.java

public static HttpClient getHttpClient() {
    if (httpClient == null) {
        HttpClientBuilder clientBuilder = HttpClientBuilder.create().useSystemProperties();
        if (sslRequired) {
            if (sslsf != null) {
                clientBuilder.setSSLSocketFactory(sslsf);
            }/*from   w  ww .j  a  v a 2  s . c o  m*/
        } else {
            SSLContext sslContext;
            try {
                sslContext = SSLContext.getInstance("SSL");

                // set up a TrustManager that trusts everything
                sslContext.init(null, new TrustManager[] { new X509TrustManager() {

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                    }
                } }, new SecureRandom());
            } catch (NoSuchAlgorithmException ex) {
                throw new AuthenticationException("Cannot get SSLContext instance for \"SSL\" protocol.", ex);
            } catch (KeyManagementException ex) {
                throw new AuthenticationException("SSLContext initialization failed.", ex);
            }

            clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext);
        }
        httpClient = clientBuilder.build();
    }
    return httpClient;
}

From source file:org.wso2.appcloud.integration.test.utils.clients.BaseClient.java

public HttpResponse doGetRequest(String endpoint, Header[] headers) throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;/*from w  w  w .  j a v  a  2 s  . c  o m*/
    int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();
        HttpGet httpGet = new HttpGet(endpoint);
        httpGet.setConfig(requestConfig);
        httpGet.setHeaders(headers);

        httpGet.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        org.apache.http.HttpResponse httpResponse = (httpclient.execute(httpGet));
        return new HttpResponse(EntityUtils.toString(httpResponse.getEntity()),
                httpResponse.getStatusLine().getStatusCode());
    } catch (IOException e) {
        log.error("Failed to invoke API endpoint:" + endpoint, e);
        throw new AppCloudIntegrationTestException("Failed to invoke API endpoint:" + endpoint, e);
    } finally {
        HttpClientUtils.closeQuietly(httpclient);
    }
}

From source file:org.jboss.as.test.integration.management.http.HttpGenericOperationUnitTestCase.java

private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    try {//from   w  w w  .j a  v  a  2 s . c  om
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                new UsernamePasswordCredentials(username, password));
        PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry);
        HttpClientBuilder.create().setConnectionManager(connectionPool).build();
        return HttpClientBuilder.create().setConnectionManager(connectionPool)
                .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.bosch.iot.things.example.historian.Controller.java

private synchronized CloseableHttpClient getHttpClient() {
    if (theHttpClient == null) {

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
        try {/*  w  w  w . j a v a 2s . com*/
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            java.util.logging.Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }

        Properties config = getConfig();
        if (config.getProperty("http.proxyHost") != null) {
            httpClientBuilder.setProxy(new HttpHost(config.getProperty("http.proxyHost"),
                    Integer.parseInt(config.getProperty("http.proxyPort"))));
        }
        if (config.getProperty("http.proxyUser") != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                    new AuthScope(HttpHost.create(getConfig().getProperty("thingsServiceEndpointUrl"))),
                    new UsernamePasswordCredentials(config.getProperty("http.proxyUser"),
                            config.getProperty("http.proxyPwd")));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }

        theHttpClient = httpClientBuilder.build();
    }
    return theHttpClient;
}

From source file:com.ibm.og.client.ApacheClient.java

private ConnectionSocketFactory createSslConnectionSocketFactory() {
    final SSLSocketFactory sslSocketFactory = createSSLSocketFactory();
    String[] configuredProtocols = null;
    String[] configuredCipherSuites = null;
    if (this.protocols != null) {
        configuredProtocols = Iterables.toArray(this.protocols, String.class);
    }/* ww  w.j  a v  a2 s.c  om*/
    if (this.cipherSuites != null) {
        final List<String> supportedCipherSuites = ImmutableList
                .copyOf(sslSocketFactory.getSupportedCipherSuites());
        for (final String cipherSuite : this.cipherSuites) {
            checkArgument(supportedCipherSuites.contains(cipherSuite), "Unsupported cipher suite [%s]",
                    cipherSuite);
        }

        configuredCipherSuites = Iterables.toArray(this.cipherSuites, String.class);
    }
    final PublicSuffixMatcher suffixMatcher = PublicSuffixMatcherLoader.getDefault();
    final HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

    return new SSLConnectionSocketFactory(sslSocketFactory, configuredProtocols, configuredCipherSuites,
            hostnameVerifier);

}

From source file:com.wudaosoft.net.httpclient.Request.java

protected void init() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        CertificateException, IOException {

    Args.notNull(hostConfig, "Host config");

    SSLConnectionSocketFactory sslConnectionSocketFactory = null;

    if (sslcontext == null) {

        if (hostConfig.getCA() != null) {
            // Trust root CA and all self-signed certs
            SSLContext sslcontext1 = SSLContexts.custom().loadTrustMaterial(hostConfig.getCA(),
                    hostConfig.getCAPassword(), TrustSelfSignedStrategy.INSTANCE).build();

            // Allow TLSv1 protocol only
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1, new String[] { "TLSv1" },
                    null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        } else {/*from w  ww .  jav a  2s. co  m*/

            if (isTrustAll) {

                SSLContext sslcontext1 = SSLContext.getInstance("TLS");

                TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                            throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                            throws CertificateException {
                    }

                } };

                sslcontext1.init(null, trustAllCerts, null);

                sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1,
                        NoopHostnameVerifier.INSTANCE);
            } else {
                sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            }
        }
    } else {

        sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    }

    if (keepAliveStrategy == null) {
        keepAliveStrategy = new ConnectionKeepAliveStrategy() {

            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                // Honor 'keep-alive' header
                HeaderElementIterator it = new BasicHeaderElementIterator(
                        response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        try {
                            return Long.parseLong(value) * 1000;
                        } catch (NumberFormatException ignore) {
                        }
                    }
                }
                // HttpHost target = (HttpHost)
                // context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
                // if
                // ("xxxxx".equalsIgnoreCase(target.getHostName()))
                // {
                // // Keep alive for 5 seconds only
                // return 3 * 1000;
                // } else {
                // // otherwise keep alive for 30 seconds
                // return 30 * 1000;
                // }

                return 30 * 1000;
            }

        };
    }

    if (retryHandler == null) {
        retryHandler = new HttpRequestRetryHandler() {

            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= 3) {
                    // Do not retry if over max retry count
                    return false;
                }
                if (exception instanceof InterruptedIOException) {
                    // Timeout
                    return false;
                }
                if (exception instanceof UnknownHostException) {
                    // Unknown host
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {
                    // Connection refused
                    return false;
                }
                if (exception instanceof SSLException) {
                    // SSL handshake exception
                    return false;
                }
                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                if (idempotent) {
                    // Retry if the request is considered idempotent
                    return true;
                }
                return false;
            }
        };
    }

    connManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory).build());

    if (hostConfig.getHost() != null) {

        connManager.setMaxTotal(hostConfig.getPoolSize() + 60);

        connManager.setMaxPerRoute(
                new HttpRoute(hostConfig.getHost(), null,
                        !HttpHost.DEFAULT_SCHEME_NAME.equals(hostConfig.getHost().getSchemeName())),
                hostConfig.getPoolSize());

        connManager.setDefaultMaxPerRoute(20);
    } else {
        connManager.setMaxTotal(hostConfig.getPoolSize());
        int hostCount = hostConfig.getHostCount() == 0 ? 10 : hostConfig.getHostCount();
        connManager.setDefaultMaxPerRoute(hostConfig.getPoolSize() / hostCount);
    }

    // connManager.setValidateAfterInactivity(2000);

    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(isKeepAlive).build();
    connManager.setDefaultSocketConfig(socketConfig);

    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset()).build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    new IdleConnectionMonitorThread(connManager).start();

    if (requestInterceptor == null) {
        requestInterceptor = new SortHeadersInterceptor(hostConfig);
    }

    if (!hostConfig.isMulticlient()) {
        defaultHttpContext = HttpClientContext.create();
        httpClient = create();
    }
}

From source file:org.elasticsearch.xpack.core.ssl.SSLServiceTests.java

public void testSSLStrategy() {
    // this just exhaustively verifies that the right things are called and that it uses the right parameters
    VerificationMode mode = randomFrom(VerificationMode.values());
    Settings settings = Settings.builder().put("supported_protocols", "protocols").put("cipher_suites", "")
            .put("verification_mode", mode.name()).build();
    SSLService sslService = mock(SSLService.class);
    SSLConfiguration sslConfig = new SSLConfiguration(settings);
    SSLParameters sslParameters = mock(SSLParameters.class);
    SSLContext sslContext = mock(SSLContext.class);
    String[] protocols = new String[] { "protocols" };
    String[] ciphers = new String[] { "ciphers!!!" };
    String[] supportedCiphers = new String[] { "supported ciphers" };
    List<String> requestedCiphers = new ArrayList<>(0);
    ArgumentCaptor<HostnameVerifier> verifier = ArgumentCaptor.forClass(HostnameVerifier.class);
    SSLIOSessionStrategy sslStrategy = mock(SSLIOSessionStrategy.class);

    when(sslService.sslConfiguration(settings)).thenReturn(sslConfig);
    when(sslService.sslContext(sslConfig)).thenReturn(sslContext);
    when(sslService.supportedCiphers(supportedCiphers, requestedCiphers, false)).thenReturn(ciphers);
    when(sslService.sslParameters(sslContext)).thenReturn(sslParameters);
    when(sslParameters.getCipherSuites()).thenReturn(supportedCiphers);
    when(sslService.sslIOSessionStrategy(eq(sslContext), eq(protocols), eq(ciphers), verifier.capture()))
            .thenReturn(sslStrategy);//from  ww  w . jav  a  2s . c  om

    // ensure it actually goes through and calls the real method
    when(sslService.sslIOSessionStrategy(settings)).thenCallRealMethod();

    assertThat(sslService.sslIOSessionStrategy(settings), sameInstance(sslStrategy));

    if (mode.isHostnameVerificationEnabled()) {
        assertThat(verifier.getValue(), instanceOf(DefaultHostnameVerifier.class));
    } else {
        assertThat(verifier.getValue(), sameInstance(NoopHostnameVerifier.INSTANCE));
    }
}

From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java

public void changeAppIcon(String applicationHash, File appIcon) throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;//  w  w w.ja  v a  2s . c  o m
    org.apache.http.HttpResponse response = null;
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();

        HttpPost httppost = new HttpPost(this.endpoint);
        httppost.setConfig(requestConfig);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart(PARAM_NAME_CHANGE_ICON, new FileBody(appIcon));
        builder.addPart(PARAM_NAME_ACTION, new StringBody(CHANGE_APP_ICON_ACTION, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_HASH_ID,
                new StringBody(applicationHash, ContentType.TEXT_PLAIN));
        httppost.setEntity(builder.build());
        httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity());
            throw new AppCloudIntegrationTestException("Update app icon failed " + result);
        }
    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        // And this will be asserted so if it failed due to a valid case, it will be captured.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
    } catch (IOException e) {
        log.error("Failed to invoke app icon update API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlRealm.java

private static Tuple<AbstractReloadingMetadataResolver, Supplier<EntityDescriptor>> parseHttpMetadata(
        String metadataUrl, RealmConfig config, SSLService sslService)
        throws ResolverException, ComponentInitializationException, PrivilegedActionException {
    final String entityId = require(config, IDP_ENTITY_ID);

    HttpClientBuilder builder = HttpClientBuilder.create();
    // ssl setup/*from   w w w  .java 2  s  . co m*/
    Settings sslSettings = config.settings().getByPrefix(SamlRealmSettings.SSL_PREFIX);
    boolean isHostnameVerificationEnabled = sslService.getVerificationMode(sslSettings, Settings.EMPTY)
            .isHostnameVerificationEnabled();
    HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier()
            : NoopHostnameVerifier.INSTANCE;
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(
            sslService.sslSocketFactory(sslSettings), verifier);
    builder.setSSLSocketFactory(factory);

    HTTPMetadataResolver resolver = new PrivilegedHTTPMetadataResolver(builder.build(), metadataUrl);
    TimeValue refresh = IDP_METADATA_HTTP_REFRESH.get(config.settings());
    resolver.setMinRefreshDelay(refresh.millis());
    resolver.setMaxRefreshDelay(refresh.millis());
    initialiseResolver(resolver, config);

    return new Tuple<>(resolver, () -> {
        // for some reason the resolver supports its own trust engine and custom socket factories.
        // we do not use these as we'd rather rely on the JDK versions for TLS security!
        SpecialPermission.check();
        try {
            return AccessController.doPrivileged(
                    (PrivilegedExceptionAction<EntityDescriptor>) () -> resolveEntityDescriptor(resolver,
                            entityId, metadataUrl));
        } catch (PrivilegedActionException e) {
            throw ExceptionsHelper.convertToRuntime((Exception) ExceptionsHelper.unwrapCause(e));
        }
    });
}