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:wptools.lib.Misc.java

/**
 * Bypass the normal SSL certificate authentication. If the passed
 * fingerprint is null, bypasses all authentication (dangerous).
 * Else trust anything whose chain contains a cert with the specified
 * fingerprint./*from  w w  w  .j  a va2  s. c o  m*/
 * @param fing      Fingerprint
 */
public static void bypassSslAuth(final byte[] fing) {
    // Determine fingerprint type from its length
    final String type;
    if (fing == null) {
        type = null;
    } else {
        switch (fing.length) {
        case MD5_LEN:
            type = "MD5";
            break;
        case SHA1_LEN:
            type = "SHA-1";
            break;
        case SHA256_LEN:
            type = "SHA-256";
            break;
        default:
            throw new IllegalArgumentException("Invalid hash.");
        }
    }

    // Create a trust manager
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            matchFing(certs);
        }

        private void matchFing(X509Certificate[] certs) throws CertificateException {
            if (fing == null)
                return;
            MessageDigest md = null;
            try {
                md = MessageDigest.getInstance(type);
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException(e);
            }
            for (X509Certificate cert : certs) {
                md.reset();
                if (Arrays.equals(md.digest(cert.getEncoded()), fing))
                    return;
            }
            throw new CertificateException("No matching fingerprint found.");
        }
    } };

    // Install the trust manager
    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    };

    try {
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:com.qingstor.sdk.request.QSOkHttpRequestClient.java

private static OkHttpClient getUnsafeOkHttpClient() {
    try {/*from  w  w  w .  j  av  a  2s.  c o m*/
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

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

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(QSConstant.HTTPCLIENT_CONNECTION_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(QSConstant.HTTPCLIENT_READ_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(QSConstant.HTTPCLIENT_WRITE_TIME_OUT, TimeUnit.SECONDS);
        builder.sslSocketFactory(sslSocketFactory);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage());
        throw new RuntimeException(e);
    }
}

From source file:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java

public Envelope wsCall(String location, String username, String password, boolean ignoreCertPath, String xml,
        String soapAction) throws IOException, SOAPException {
    URI serviceLocation;//from  w w w.  j a va2s  .  c  o  m
    try {
        serviceLocation = new URI(location);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid uri for artifact resolve: " + location);
    }
    if (log.isDebugEnabled())
        log.debug("serviceLocation..:" + serviceLocation);
    if (log.isDebugEnabled())
        log.debug("SOAP Request: " + xml);

    HttpURLConnection c = (HttpURLConnection) serviceLocation.toURL().openConnection();
    if (c instanceof HttpsURLConnection) {
        HttpsURLConnection sc = (HttpsURLConnection) c;

        if (ignoreCertPath) {
            sc.setSSLSocketFactory(new DummySSLSocketFactory());
            sc.setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
    }
    c.setAllowUserInteraction(false);
    c.setDoInput(true);
    c.setDoOutput(true);
    c.setFixedLengthStreamingMode(xml.getBytes("UTF-8").length);
    c.setRequestMethod("POST");
    c.setReadTimeout(20000);
    c.setConnectTimeout(30000);

    addContentTypeHeader(xml, c);
    c.addRequestProperty("SOAPAction", "\"" + (soapAction == null ? "" : soapAction) + "\"");

    if (username != null && password != null) {
        c.addRequestProperty("Authorization",
                "Basic " + Base64.encodeBytes((username + ":" + password).getBytes(), Base64.DONT_BREAK_LINES));
    }
    OutputStream outputStream = c.getOutputStream();
    IOUtils.write(xml, outputStream, "UTF-8");
    outputStream.flush();
    outputStream.close();

    if (c.getResponseCode() == 200) {
        InputStream inputStream = c.getInputStream();
        String result = IOUtils.toString(inputStream, "UTF-8");
        inputStream.close();

        if (log.isDebugEnabled())
            log.debug("Server SOAP response: " + result);
        XMLObject res = SAMLUtil.unmarshallElementFromString(result);

        Envelope envelope = (Envelope) res;
        if (SAMLUtil.getFirstElement(envelope.getBody(), Fault.class) != null) {
            log.warn(
                    "Result has soap11:Fault, but server returned 200 OK. Treating as error, please fix the server");
            throw new SOAPException(c.getResponseCode(), result);
        }
        return envelope;
    } else {
        log.debug("Response code: " + c.getResponseCode());

        InputStream inputStream = c.getErrorStream();
        String result = IOUtils.toString(inputStream, "UTF-8");
        inputStream.close();
        if (log.isDebugEnabled())
            log.debug("Server SOAP fault: " + result);

        throw new SOAPException(c.getResponseCode(), result);
    }
}

From source file:org.ojbc.web.portal.services.SamlServiceImpl.java

Element retrieveAssertionFromShibboleth(HttpServletRequest request) throws Exception {
    // Note: pulled this straight from Andrew's demo JSP that displays the assertion and http request...

    /*// w  w w .  j  a va2  s . c  o  m
     *  fix for Exception in thread "main" javax.net.ssl.SSLHandshakeException:
     *       sun.security.validator.ValidatorException:
     *           PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
     *               unable to find valid certification path to requested target
     */
    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) {
        }
    } };
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true; // andrew had this as false...dont know how that would work...
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    /*
     * end of the fix
     */
    //Hard coded to pick up a single assertion...could loop through assertion headers if there will  be more than one
    String assertionHttpHeaderName = request.getHeader("Shib-Assertion-01");
    LOG.info("Loading assertion from: " + assertionHttpHeaderName);

    if (assertionHttpHeaderName == null) {
        LOG.warn("Shib-Assertion-01 header was null, Returning null asssertion document element");
        return null;
    }

    URL url = new URL(assertionHttpHeaderName);
    URLConnection con = url.openConnection();

    InputStream is = con.getInputStream();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document assertionDoc = db.parse(is);

    return assertionDoc.getDocumentElement();

}

From source file:com.produban.cloudfoundry.bosh.bosh_javaclient.BoshClientImpl.java

/**
 * This method sets up {@link HttpsURLConnection} so that no certificate or
 * hostname check is performed./*from   w  ww .j av  a 2s . c o  m*/
 */
private void disableSSLChecks() {
    try {
        TrustManager trustAllCertificates = new X509TrustManager() {

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

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                // I do nothing because the way to say "OK" is not to throw
                // a CertificateException

            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                // I do nothing because the way to say "OK" is not to throw
                // a CertificateException

            }
        };

        TrustManager[] trustAllCertificatesArray = { trustAllCertificates };
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCertificatesArray, new java.security.SecureRandom());

        HostnameVerifier allHostsValid = new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true; // I always say 'OK'
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new IllegalStateException("Something strange happened here", e);
    }
}

From source file:org.apache.fineract.restwebservice.PlatformRestClient.java

/**
 * Skip SSL certificate verification/*from   w ww.  ja  v a 2s  . c  o  m*/
 */
private void skipSslCertificateVerification() {
    final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    try {
        // get the SSL context object
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // initialize the SSL context
        sslContext.init(null, trustManager, new SecureRandom());

        // Set the default SSLSocketFactory
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    } catch (Exception e) {
    }
}

From source file:hudson.plugins.sitemonitor.SiteMonitorRecorder.java

private HttpURLConnection getConnection(String urlString)
        throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {

    if (urlString.startsWith("https://")) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);

        HttpsURLConnection connection = (HttpsURLConnection) ProxyConfiguration.open(new URL(urlString));
        connection.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }/*from w w  w  .  j a va  2  s  . c om*/
        });
        return connection;

    } else if (urlString.contains("@")) {

        URL passedURL = new URL(urlString);
        String creds = urlString.substring(urlString.indexOf("//") + 2, urlString.indexOf("@"));
        String userName = creds.substring(0, creds.indexOf(":"));
        String passWord = creds.substring(creds.indexOf(":") + 1, creds.length());
        String userPassword = userName + ":" + passWord;
        // TODO cambiar implementacin de Base64
        String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
        // TODO soporta proxy?
        HttpURLConnection connection = (HttpURLConnection) passedURL.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        return connection;

    } else {
        return (HttpURLConnection) ProxyConfiguration.open(new URL(urlString));
    }
}

From source file:gov.nih.nci.cabig.ccts.security.SecureURL.java

/**
 * Retrieve the contents from the given URL as a String, assuming the URL's
 * server matches what we expect it to match.
 *//*from  ww  w. j av a  2 s.  c om*/
public static String retrieve(String url) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("entering retrieve(" + url + ")");
    }
    BufferedReader r = null;
    try {
        URL u = new URL(url);
        if (!u.getProtocol().equals("https")) {
            // IOException may not be the best exception we could throw here
            // since the problem is with the URL argument we were passed,
            // not
            // IO. -awp9
            log.error("retrieve(" + url + ") on an illegal URL since protocol was not https.");
            throw new IOException("only 'https' URLs are valid for this method");
        }

        // JAP: changing to allow validation of Globus-style host names.
        // URLConnection uc = u.openConnection();
        HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
        uc.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                boolean valid = false;
                try {
                    String expectedHostname = hostname.toLowerCase();
                    log.debug("expectedHostname = " + expectedHostname);

                    String subjectDN = session.getPeerCertificateChain()[0].getSubjectDN().getName()
                            .toLowerCase();
                    log.debug("subjectDN = " + subjectDN);
                    String assertedHostname = null;
                    for (String part : subjectDN.split(",")) {
                        String[] nameValue = part.split("=");
                        String name = nameValue[0].toLowerCase().trim();
                        String value = nameValue[1].trim();
                        if (name.equals("cn")) {
                            assertedHostname = value;
                            break;
                        }
                    }
                    if (assertedHostname == null) {
                        log.warn("No common name found in subject distinguished name.");
                        return false;
                    }
                    log.debug("assertedHostname = " + assertedHostname);
                    if (assertedHostname.startsWith("host/")) {
                        expectedHostname = "host/" + expectedHostname;
                        log.debug("detected Globus-style common name, expectedHostname = " + expectedHostname);
                    }
                    valid = assertedHostname.equals(expectedHostname);
                    log.debug("valid = " + valid);
                } catch (Exception ex) {
                    log.warn(ex);
                }
                return valid;
            }

        });

        uc.setRequestProperty("Connection", "close");
        r = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line;
        StringBuffer buf = new StringBuffer();
        while ((line = r.readLine()) != null)
            buf.append(line + "\n");
        return buf.toString();
    } finally {
        try {
            if (r != null)
                r.close();
        } catch (IOException ex) {
            // ignore
        }
    }
}

From source file:guru.mmp.common.http.SecureHttpClientBuilder.java

private synchronized SSLConnectionSocketFactory getSSLConnectionSocketFactory() {
    if (sslSocketFactory == null) {
        try {//from   www.ja  v a2  s  .  c o m
            SSLContext sslContext = SSLContext.getInstance("TLS");

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Skip client verification step
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    if (serverValidationEnabled) {
                        // TODO: Implement server certificate validation
                    }
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } };

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

            sslSocketFactory = new SSLConnectionSocketFactory(sslContext.getSocketFactory(),
                    new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession sslSession) {
                            if (serverValidationEnabled) {
                                // TODO: Implement proper verification of the server identity -- MARCUS
                            }

                            return true;

                            // if (hostname.equalsIgnoreCase(sslSession.getPeerHost()))
                            // {
                            // return true;
                            // }
                            // else
                            // {
                            // logger.error("Failed to verify the SSL connection to the host ("
                            // + hostname + ") which returned a certificate for the host (" + sslSession.getPeerHost() + ")");
                            //
                            // return false;
                            // }
                        }
                    });
        } catch (Throwable e) {
            throw new RuntimeException("Failed to create the no-trust SSL socket factory", e);
        }
    }

    return sslSocketFactory;
}

From source file:io.hops.security.HopsUtil.java

/**
 * Set the default HTTPS trust policy to trust anything.
 *
 * NOTE: Use it only during development or use it wisely!
 */// w w w . ja  va2  s.  com
public static void trustAllHTTPS() {
    try {
        final SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, trustAll, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (GeneralSecurityException ex) {
        throw new IllegalStateException("Could not initialize SSLContext for CRL fetcher", ex);
    }
}