Example usage for javax.net.ssl HostnameVerifier HostnameVerifier

List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier

Introduction

In this page you can find the example usage for javax.net.ssl HostnameVerifier HostnameVerifier.

Prototype

HostnameVerifier

Source Link

Usage

From source file:org.flowable.http.bpmn.impl.HttpActivityBehaviorImpl.java

public HttpActivityBehaviorImpl() {
    HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {//from  w  ww  .j av a  2 s  .  c om
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new ProcessErrorPropagator());
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static String fetchSecureContent(final String url, final int timeout) throws IOException {
    LOGGER.info("fetchSecureContent: " + url);
    final URL u = new URL(url);
    final URLConnection conn = u.openConnection();
    if (timeout != 0) {
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);//from  ww  w  .  j  a v  a 2  s. com
    }
    if (conn instanceof HttpsURLConnection) {
        final HttpsURLConnection http = (HttpsURLConnection) conn;
        http.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
        http.setRequestMethod(GET_STR);
        http.setAllowUserInteraction(true);
    }
    return IOUtils.toString(conn.getInputStream());
}

From source file:com.ibm.caas.CaaSResource.java

/**
 * Pass throughout CERTs [workaround]/*from  w  ww  . ja v  a 2s .c  o m*/
 */
public void relaxHostChecking() {

    // Override SSL Trust manager without certificate chains validation
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }

    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Hostname verification. 
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            /**
             * Verify that the host name is an acceptable match with the server's authentication scheme.
             * @hostname - the host name
             * @session - SSLSession used on the connection to host
             * @return true if the host name is acceptable
             */
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        // Sets the default HostnameVerifier by all-trusting host verifier.
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java

private boolean disableSSL() {
    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }// w  w w.  j a  va 2 s  . c  om
    };

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    // install all-trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        return true;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        return false;
    } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>//ww w . j ava 2  s  .  c  o  m
 *  ? ??   HTTPS   HandShake Exception ? ??  Exception? ? ?
 * RHEV Manager(host) ? SSL ??  ?   ? ?? ?.
 * </pre>
 * @throws Exception
 */
public void init() throws Exception {
    // http://javaresolutions.blogspot.kr/2014/07/javaxnetsslsslprotocolexception.html
    // -Djsse.enableSNIExtension=false
    // System.setProperty("jsse.enableSNIExtension", "false");

    System.setProperty("jsse.enableSNIExtension", "false");

    // Create a hostname verifier that does not validate hostname
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            /*
            if (hostname.equals(host)) {
            return true;
            }
                    
            return false;
            */
            return true;
        }
    });

    // Create a trust manager that does not validate certificate chains
    // Refer to https://code.google.com/p/misc-utils/wiki/JavaHttpsUrl
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // nothing to do.
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // nothing to do.
        }

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

    try {
        // Install the all-trusting trust manager
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (KeyManagementException e) {
        logger.error("KeyManagementException has occurred.", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException has occurred.", e);
    }
}

From source file:org.wso2.iot.firealarm.access.api.AccessTokenClient.java

public AccessTokenInfo getAccessToken(String username, String password, String appInstanceId)
        throws AccessTokenException {
    SSLContext ctx;/*  w ww  .  ja  v  a 2 s  . co m*/
    String response = "";
    try {
        ctx = SSLContext.getInstance("TLS");

        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);

        URL url = new URL(tokenURL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        //System.out.println(conn.getResponseCode());
        conn.disconnect();

        HttpClient httpClient = new HttpClient();

        PostMethod postMethod = new PostMethod(tokenURL);
        postMethod.addParameter(new NameValuePair("grant_type", grantType));
        postMethod.addParameter(new NameValuePair("username", username));
        postMethod.addParameter(new NameValuePair("password", password));
        postMethod.addParameter(new NameValuePair("scope", scope + appInstanceId));

        postMethod.addRequestHeader("Authorization", "Basic " + appToken);
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        httpClient.executeMethod(postMethod);

        response = postMethod.getResponseBodyAsString();
        log.info(response);
        JSONObject jsonObject = new JSONObject(response);

        AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
        accessTokenInfo.setAccess_token(jsonObject.getString("access_token"));
        accessTokenInfo.setRefresh_token(jsonObject.getString("refresh_token"));
        accessTokenInfo.setExpires_in(jsonObject.getInt("expires_in"));
        accessTokenInfo.setToken_type(jsonObject.getString("token_type"));

        return accessTokenInfo;

    } catch (NoSuchAlgorithmException | KeyManagementException | IOException | JSONException e) {
        log.error(e.getMessage());
        throw new AccessTokenException("Configuration Error for Access Token Generation");
    } catch (NullPointerException e) {

        return null;
    }

}

From source file:test.TestFinal.java

public static JerseyClient getJerseyClient(boolean isSSL) {
    ClientBuilder clientBuilder = JerseyClientBuilder.newBuilder().register(MultiPartFeature.class);

    // Create a secure JerseyClient
    if (isSSL) {/*w ww  . j a  va 2  s  . c  o  m*/
        try {
            HostnameVerifier verifier = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };

            TrustManager[] tm = new TrustManager[] { new X509TrustManager() {

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

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

                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }
            } };

            SSLContext sslContext = sslContext = SSLContext.getInstance("SSL");

            sslContext.init(null, tm, new SecureRandom());

            clientBuilder.sslContext(sslContext).hostnameVerifier(verifier);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

    return (JerseyClient) clientBuilder.build().register(JacksonJsonProvider.class);
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.TenantMgtAdminServiceClient.java

/**
 * Create basic SSL connection factory/*  ww  w .j  av a  2 s . c  om*/
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:gov.nih.nci.cabig.caaers.service.ProxyWebServiceFacade.java

public String simpleSendAndReceive(String message) {
    String wsURI = configuration.get(Configuration.ESB_WS_URL);
    StringBuilder sb = new StringBuilder(8192);

    try {/*www  .j  a  va2  s . com*/

        URL url = new URL(wsURI);

        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        if (httpConnection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) httpConnection).setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String hostname, SSLSession session) {
                    // TODO Auto-generated method stub
                    log.warn("Going to trust hostname: '" + hostname + "'.");
                    return true;
                }
            });
        }
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoOutput(true);
        httpConnection.connect();

        StringBuffer xmlMessage = new StringBuffer();

        xmlMessage.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
                .append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">")
                .append("<soapenv:Header>");

        //Generate header;
        xmlMessage.append("<wsse:Security xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" ").append(
                "xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">")
                .append("<wsse:UsernameToken wsu:Id=\"UsernameToken-2765109\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">")
                .append("<wsse:Username>").append(configuration.get(Configuration.WS_USERNAME))
                .append("</wsse:Username>")
                .append("<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">")
                .append(configuration.get(Configuration.WS_PASSWORD)).append("</wsse:Password>")
                .append("</wsse:UsernameToken>").append("</wsse:Security> ");
        xmlMessage.append("</soapenv:Header>").append("<soapenv:Body>").append(message)
                .append("</soapenv:Body>").append("</soapenv:Envelope>");

        try (OutputStream out = httpConnection.getOutputStream();
                OutputStreamWriter write = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
            write.write(xmlMessage.toString());
        }

        try (InputStream in = httpConnection.getInputStream();
                BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
            String str = null;

            while ((str = r.readLine()) != null) {
                sb.append(str);
            }

        }

    } catch (Exception e) {
        log.error("Error while processing the proxywebservoce facade.\nFailed message: '" + message
                + "'. \nStacktrace;\n", e);
    }

    return sb.toString();
}

From source file:com.threatconnect.sdk.conn.ConnectionUtil.java

/**
 * Adds the ability to trust self signed certificates for this HttpClientBuilder
 * /*from   w  w w .  j a  va 2s.  c o  m*/
 * @param httpClientBuilder
 * the HttpClientBuilder to apply these settings to
 */
public static void trustSelfSignedCerts(final HttpClientBuilder httpClientBuilder) {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
                new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        // allow all
                        return true;
                    }
                });

        httpClientBuilder.setSSLSocketFactory(sslsf);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        logger.error("Error adding SSLSocketFactory to HttpClientBuilder", ex);
    }
}