Example usage for org.apache.http.conn.ssl DefaultHostnameVerifier DefaultHostnameVerifier

List of usage examples for org.apache.http.conn.ssl DefaultHostnameVerifier DefaultHostnameVerifier

Introduction

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

Prototype

public DefaultHostnameVerifier() 

Source Link

Usage

From source file:io.apiman.gateway.engine.es.DefaultESClientFactory.java

/**
 * @param httpConfig//w  w  w .  j  ava  2 s . c om
 * @param config 
 */
@SuppressWarnings("nls")
private void updateSslConfig(Builder httpConfig, Map<String, String> config) {
    try {
        String clientKeystorePath = config.get("client-keystore");
        String clientKeystorePassword = config.get("client-keystore.password");
        String trustStorePath = config.get("trust-store");
        String trustStorePassword = config.get("trust-store.password");

        SSLContext sslContext = SSLContext.getInstance("TLS");
        Info kPathInfo = new Info(clientKeystorePath, clientKeystorePassword);
        Info tPathInfo = new Info(trustStorePath, trustStorePassword);
        sslContext.init(KeyStoreUtil.getKeyManagers(kPathInfo), KeyStoreUtil.getTrustManagers(tPathInfo), null);
        HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

        httpConfig.defaultSchemeForDiscoveredNodes("https");
        httpConfig.sslSocketFactory(sslSocketFactory); // for sync calls
        httpConfig.httpsIOSessionStrategy(httpsIOSessionStrategy); // for async calls

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.mandrel.requests.http.ApacheHttpRequester.java

public void init() {

    available = new Semaphore(maxParallel(), true);

    SSLContext sslContext = SSLContexts.createSystemDefault();
    HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();

    Registry<ConnectionSocketFactory> sessionStrategyRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override// w  w w  .  ja va 2  s.c o  m
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("localhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return new InetAddress[] { nameResolver().resolve(host) };
            }
        }
    };

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            sessionStrategyRegistry, dnsResolver);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(maxHeaderCount)
            .setMaxLineLength(maxLineLength).build();

    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(maxPersistentConnections());
    connManager.setDefaultMaxPerRoute(maxPersistentConnections());

    // TODO
    // Use custom credentials provider if necessary.
    // CredentialsProvider credentialsProvider = new
    // BasicCredentialsProvider();

    // Create global request configuration
    defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setMaxRedirects(maxRedirects())
            .setSocketTimeout(socketTimeout()).setConnectTimeout(connectTimeout())
            .setConnectionRequestTimeout(requestTimeOut()).setRedirectsEnabled(followRedirects()).build();

    // Create an HttpClient with the given custom dependencies and
    // configuration.
    client = HttpClients.custom().setConnectionManager(connManager)
            // .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(defaultRequestConfig).build();
}

From source file:com.vmware.photon.controller.common.auth.AuthOIDCClient.java

private IdmClient createIdmClient(String domainControllerFQDN, int domainControllerPort, String user,
        String password) throws AuthException {
    try {/*from w ww .j a v a 2 s .  c  om*/
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(certificateStore.getKeyStore());
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort,
                new DefaultHostnameVerifier(), sslContext);

        com.vmware.identity.openidconnect.client.AccessToken accessToken = getTokenHandler()
                .getAdminServerAccessToken(user, password).getAccessToken();

        com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
                accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
        idmClient.setToken(restAccessToken);
        return idmClient;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new AuthException("Failed to createIdmClient", e);
    }
}

From source file:com.thinkbiganalytics.rest.JerseyRestClient.java

public JerseyRestClient(JerseyClientConfig config) {
    useConnectionPooling = config.isUseConnectionPooling();
    SSLContext sslContext = null;
    if (config.isHttps()) {
        SslConfigurator sslConfig = null;
        byte[] keyStoreFile = null;
        byte[] truststoreFile = null;

        try {//www  .j av a  2 s  .  c o  m
            if (StringUtils.isNotBlank(config.getKeystorePath())) {
                InputStream keystore = JerseyRestClient.class.getResourceAsStream(config.getKeystorePath());
                if (keystore != null) {
                    keyStoreFile = ByteStreams.toByteArray(keystore);
                }
            }
        } catch (IOException e) {
        }

        try {
            if (StringUtils.isNotBlank(config.getTruststorePath())) {
                InputStream truststore = JerseyRestClient.class.getResourceAsStream(config.getTruststorePath());
                if (truststore != null) {
                    truststoreFile = ByteStreams.toByteArray(truststore);
                }
            }
        } catch (IOException e) {
        }

        if (keyStoreFile != null) {
            sslConfig = SslConfigurator.newInstance()
                    .trustStoreBytes(truststoreFile != null ? truststoreFile : keyStoreFile)
                    .trustStorePassword(config.getTruststorePassword() != null ? config.getTruststorePassword()
                            : config.getKeystorePassword())
                    .trustStoreType(config.getTrustStoreType())
                    .keyStoreBytes(keyStoreFile != null ? keyStoreFile : truststoreFile)
                    .keyStorePassword(config.getKeystorePassword());
        } else {
            sslConfig = SslConfigurator.newInstance()
                    .keyStoreFile(config.getKeystorePath() == null ? config.getTruststorePath()
                            : config.getKeystorePath())
                    .keyStorePassword(config.getKeystorePassword() == null ? config.getTruststorePassword()
                            : config.getKeystorePassword())
                    .trustStoreFile(config.getTruststorePath() == null ? config.getKeystorePath()
                            : config.getTruststorePath())
                    .trustStorePassword(config.getTruststorePassword() == null ? config.getKeystorePassword()
                            : config.getTruststorePassword())
                    .trustStoreType(config.getTrustStoreType());
        }

        try {
            sslContext = sslConfig.createSSLContext();
        } catch (Exception e) {
            log.error("ERROR creating CLient SSL Context.  " + e.getMessage()
                    + " Falling back to Jersey Client without SSL.  Rest Integration with '" + config.getUrl()
                    + "'  will probably not work until this is fixed!");
        }
    }

    ClientConfig clientConfig = new ClientConfig();

    // Add in Timeouts if configured.  Values are in milliseconds
    if (config.getReadTimeout() != null) {
        clientConfig.property(ClientProperties.READ_TIMEOUT, config.getReadTimeout());
    }
    if (config.getConnectTimeout() != null) {
        clientConfig.property(ClientProperties.CONNECT_TIMEOUT, config.getConnectTimeout());
    }

    if (useConnectionPooling) {

        PoolingHttpClientConnectionManager connectionManager = null;
        if (sslContext != null) {

            HostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier();

            LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    defaultHostnameVerifier);

            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSocketFactory).build();

            connectionManager = new PoolingHttpClientConnectionManager(registry);
        } else {
            connectionManager = new PoolingHttpClientConnectionManager();
        }
        connectionManager.setDefaultMaxPerRoute(100); // # of connections allowed per host/address
        connectionManager.setMaxTotal(200); // number of connections allowed in total

        clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
        HttpUrlConnectorProvider connectorProvider = new HttpUrlConnectorProvider();
        clientConfig.connectorProvider(connectorProvider);

    }

    clientConfig.register(MultiPartFeature.class);

    // allow derived classes to modify the client config
    extendClientConfig(clientConfig);

    if (sslContext != null) {
        log.info("Created new Jersey Client with SSL connecting to {} ", config.getUrl());
        client = new JerseyClientBuilder().withConfig(clientConfig).sslContext(sslContext).build();
    } else {
        log.info("Created new Jersey Client without SSL connecting to {} ", config.getUrl());
        client = JerseyClientBuilder.createClient(clientConfig);
    }

    // Register Jackson for the internal mapper
    objectMapper = new JacksonObjectMapperProvider().getContext(null);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    //register custom features
    registerClientFeatures(client);

    // Configure authentication
    if (StringUtils.isNotBlank(config.getUsername())) {
        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(config.getUsername(),
                config.getPassword());
        client.register(feature);
    }
    this.uri = config.getUrl();
    this.username = config.getUsername();

    if (StringUtils.isNotBlank(config.getHost()) && !HOST_NOT_SET_VALUE.equals(config.getHost())) {
        this.isHostConfigured = true;
    } else {
        log.info("Jersey Rest Client not initialized.  Host name is Not set!!");
    }
}

From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java

private static URL waitForDependency(URL url, String serviceName, String key, String value, String username,
        String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;//ww  w. ja v a2s.  co  m
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + url.getPath());
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(TRUSTSTORE_PATH,
                                TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(CLIENT_KEYSTORE_PATH,
                                CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    log.info(username + ":******");
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up (host=" + endpoint.getHost() + ")"
                                + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. (host=" + endpoint.getHost() + ")"
                            + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:com.vmware.identity.openidconnect.client.TestUtils.java

static IdmClient createIdmClient(AccessToken accessToken, String domainControllerFQDN, int domainControllerPort,
        KeyStore keyStore) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);//from w w w .  ja  va2 s .  c o  m
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
            accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
    idmClient.setToken(restAccessToken);
    return idmClient;
}

From source file:com.vmware.admiral.compute.RegistryHostConfigService.java

/**
 * Validates that certificate CN equals the hostname specified by user. Docker daemon will be
 * later instructed to find and trust this certificate only if these two matches. See:
 * https://docs.docker.com/docker-trusted-registry/userguide/
 *///  w  w  w  .  j  a  va  2s .  c  om
private void validateHostAddress(RegistryState state, SslTrustCertificateState sslTrust) {

    String hostname = UriUtilsExtended.extractHost(state.address);

    X509Certificate certificate = null;

    try {
        certificate = KeyUtil.decodeCertificate(sslTrust.certificate);
    } catch (CertificateException e1) {
        throw new LocalizableValidationException(
                String.format("Invalid certificate provided from host: %s", hostname),
                "compute.registry.host.address.invalid.certificate", hostname);
    }

    try {
        new DefaultHostnameVerifier().verify(hostname, certificate);
    } catch (SSLException e) {
        String errorMessage = String.format("Registry hostname (%s) does not match certificates CN (%s).",
                hostname, sslTrust.commonName);
        throw new LocalizableValidationException(errorMessage, "compute.registry.host.name.mismatch", hostname,
                sslTrust.commonName);
    }

}

From source file:org.apache.juneau.rest.client.RestClientBuilder.java

/**
 * Creates the {@link HttpClientConnectionManager} returned by {@link #createConnectionManager()}.
 * <p>/* ww  w  .  ja  va  2  s  .co m*/
 * Subclasses can override this method to provide their own connection manager.
 * <p>
 * The default implementation returns an instance of a {@link PoolingHttpClientConnectionManager}.
 *
 * @return The HTTP client builder to use to create the HTTP client.
 */
protected HttpClientConnectionManager createConnectionManager() {
    if (sslOpts != null) {
        HostnameVerifier hv = null;
        switch (sslOpts.getHostVerify()) {
        case LAX:
            hv = new NoopHostnameVerifier();
            break;
        case DEFAULT:
            hv = new DefaultHostnameVerifier();
            break;
        default:
            throw new RuntimeException("Programmer error");
        }

        for (String p : StringUtils.split(sslOpts.getProtocols(), ',')) {
            try {
                TrustManager tm = new SimpleX509TrustManager(
                        sslOpts.getCertValidate() == SSLOpts.CertValidate.LAX);

                SSLContext ctx = SSLContext.getInstance(p);
                ctx.init(null, new TrustManager[] { tm }, null);

                // Create a socket to ensure this algorithm is acceptable.
                // This will correctly disallow certain configurations (such as SSL_TLS under FIPS)
                ctx.getSocketFactory().createSocket().close();
                SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(ctx, hv);
                setSSLSocketFactory(sf);

                Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("https", sf).build();

                return (pooled ? new PoolingHttpClientConnectionManager(r)
                        : new BasicHttpClientConnectionManager(r));
            } catch (Throwable t) {
            }
        }
    }

    // Using pooling connection so that this client is threadsafe.
    return (pooled ? new PoolingHttpClientConnectionManager() : new BasicHttpClientConnectionManager());
}

From source file:com.vmware.identity.openidconnect.client.TestUtils.java

static VmdirClient createVMdirClient(AccessToken accessToken, String domainControllerFQDN,
        int domainControllerPort, KeyStore keyStore) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);/*from w ww . java2s .co m*/
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    VmdirClient vmdirClient = new VmdirClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
            accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
    vmdirClient.setToken(restAccessToken);
    return vmdirClient;
}