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:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 * Returns the certificate chain provided by the HTTPS server.
 *
 * The first certificate identifies the server.
 * The remainder should verify the cert upto a trusted root.
 *
 *
 * @param url//from www  .java 2  s  .  c  o m
 * @return
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
public List<X509Certificate> getCertHttps(URL url)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {
    ArrayList<X509Certificate> toReturn = new ArrayList<>();

    // Setup a temp ssl context that accepts all certificates for this connection
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        private X509Certificate[] certToReturn;

        @Override
        public void checkClientTrusted(X509Certificate[] c, String s) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] c, String s) {
            certToReturn = c;
        }

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

    //Setup a temp hostname verifier that verifies all hostnames for this connection
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession ss) {
            return true;
        }
    };
    HttpsURLConnection httpsConn = null;
    try {
        httpsConn = (HttpsURLConnection) url.openConnection();

        httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
        httpsConn.setHostnameVerifier(hv);
        httpsConn.connect();

        Certificate[] certs = httpsConn.getServerCertificates();

        for (Certificate cert : certs) {
            if (cert instanceof X509Certificate) {
                toReturn.add((X509Certificate) cert);
            }
        }
    } finally {
        if (httpsConn != null) {
            httpsConn.disconnect();
        }
    }
    return toReturn;
}

From source file:luki.x.net.XNetEngine.java

private void setDefaultHostnameVerifier() {
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }//from w  ww .  j  ava  2s .c  o  m
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:com.streamsets.datacollector.http.TestWebServerTaskHttpHttps.java

private void configureHttpsUrlConnection(HttpsURLConnection conn) throws Exception {
    SSLContext sc = SSLContext.getInstance("SSL");
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }/*from   ww  w . jav a  2 s  . co m*/

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

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    conn.setSSLSocketFactory(sc.getSocketFactory());
    conn.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
}

From source file:net.subclient.subsonic.SubsonicConnection.java

/**
 * Prepares HTTPS connections to accept any domains and self-signed certificates
 * @throws NoSuchAlgorithmException /*from  www .java2  s  .  co m*/
 * @throws KeyManagementException 
 */
private void setSSLProperties() throws NoSuchAlgorithmException, KeyManagementException {
    //Disable certificate chacks to force trust self-signed certificates
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };
    SSLContext sc = null;
    sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    //Set a hostname verifier that trust any hostname
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

From source file:net.sf.taverna.cagrid.activity.CaGridActivity.java

/**
 * This static block is needed in case some of the caGrid services require
 * https which is more than likely and needs to be executed before we start
 * loading caGrid services or otherwise some of these services will fail.
 * Some caGrid services requiring https have a weird CN in their server
 * certificates - instead of CN=<HOSTNAME> they have CN="host/"+<HOSTNAME>,
 * i.e. string "host/" prepended so we have to tell Java's SSL to accept
 * these hostnames as well. This is not very good at is sets this hostname
 * verifier across all https connections created in the JVM from now on, but
 * solves the problem with such caGrid services.
 * //from www .  j  a  v a  2  s  .  co  m
 */
protected static void setHostNameVerifier() {
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String hostName, SSLSession session) {
            String hostNameFromCertificate = null;
            try {
                hostNameFromCertificate = session.getPeerPrincipal().getName().substring(3,
                        session.getPeerPrincipal().getName().indexOf(','));
            } catch (SSLPeerUnverifiedException e) {
                e.printStackTrace();
                return false;
            }
            logger.info("Hostname verifier: host from url: " + hostName + " vs. host from certificate: "
                    + hostNameFromCertificate);
            //return (hostName.equals(hostNameFromCertificate) || ("host/"+hostName).equals(hostNameFromCertificate));
            //force no-verification, dangerous!!!
            System.out.println(hostName + "\nis using a certificate issued to:\n " + hostNameFromCertificate);
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java

private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException {
    LdapContext ctx = null;//from   w w  w  . j a  v  a2s.c  om
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);

    try {
        // Create initial context
        ctx = new InitialLdapContext(env, null);
        // Establish TLS session
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());

        if (disableHostNameVerification) {
            tls.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }

        tls.negotiate();

        // Initialize security credentials & perform read operation for
        // verification.
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.lookup(userDN);
        logger.debug("Authentication successful for {}", userDN);

    } catch (NamingException | IOException ex) {
        throw new AuthenticationException("Error validating LDAP user", ex);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) { /* Ignore. */
            }
        }
    }
}

From source file:com.tsavo.trade.TradeBot.java

public static void initSSL() throws KeyManagementException, NoSuchAlgorithmException {

    // SSL Certificates trustStore ----------------------------------------
    // Set the SSL certificate for mtgox - Read up on Java Trust store.
    // System.setProperty("javax.net.ssl.trustStore", "trader.jks");
    // System.setProperty("javax.net.ssl.trustStorePassword", "zabbas"); //
    // I// www  .  j  a va2 s.c om

    class MyManager implements X509TrustManager {

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

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

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

        }

    }

    TrustManager[] managers = new TrustManager[] { new MyManager() };
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, managers, new SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    // System.setProperty("javax.net.debug","ssl"); //Uncomment for
    // debugging SSL errors

}

From source file:no.digipost.api.client.DigipostClient.java

/**
 * Dersom vi tester mot et av Digiposts testmiljer, vil vi ikke bruke
 * SSL-validering./*from w  w  w.ja v a 2  s.  c  o  m*/
 */
public static JerseyClient createJerseyClientWithoutSSLValidation() {
    TrustManager[] noopTrustManager = new TrustManager[] { new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    HostnameVerifier noopHostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(final String hostname, final SSLSession session) {
            return true;
        }
    };

    SSLContext sc;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, noopTrustManager, new SecureRandom());
        ClientConfig c = new ClientConfig();
        c.register(LoggingFilter.class);
        c.register(MultiPartFeature.class);

        return new JerseyClientBuilder().sslContext(sc).withConfig(c).hostnameVerifier(noopHostnameVerifier)
                .build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.maven.report.projectinfo.ProjectInfoReportUtils.java

/**
 * @param url not null/*from  w  w w .  j a v  a  2s.  c  o  m*/
 * @param project not null
 * @param settings not null
 * @return the url connection with auth if required. Don't check the certificate if SSL scheme.
 * @throws IOException if any
 */
private static URLConnection getURLConnection(URL url, MavenProject project, Settings settings)
        throws IOException {
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(TIMEOUT);
    conn.setReadTimeout(TIMEOUT);

    // conn authorization
    if (settings.getServers() != null && !settings.getServers().isEmpty() && project != null
            && project.getDistributionManagement() != null
            && (project.getDistributionManagement().getRepository() != null
                    || project.getDistributionManagement().getSnapshotRepository() != null)
            && (StringUtils.isNotEmpty(project.getDistributionManagement().getRepository().getUrl())
                    || StringUtils.isNotEmpty(
                            project.getDistributionManagement().getSnapshotRepository().getUrl()))) {
        Server server = null;
        if (url.toString().contains(project.getDistributionManagement().getRepository().getUrl())) {
            server = settings.getServer(project.getDistributionManagement().getRepository().getId());
        }
        if (server == null && url.toString()
                .contains(project.getDistributionManagement().getSnapshotRepository().getUrl())) {
            server = settings.getServer(project.getDistributionManagement().getSnapshotRepository().getId());
        }

        if (server != null && StringUtils.isNotEmpty(server.getUsername())
                && StringUtils.isNotEmpty(server.getPassword())) {
            String up = server.getUsername().trim() + ":" + server.getPassword().trim();
            String upEncoded = new String(Base64.encodeBase64Chunked(up.getBytes())).trim();

            conn.setRequestProperty("Authorization", "Basic " + upEncoded);
        }
    }

    if (conn instanceof HttpsURLConnection) {
        HostnameVerifier hostnameverifier = new HostnameVerifier() {
            /** {@inheritDoc} */
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        ((HttpsURLConnection) conn).setHostnameVerifier(hostnameverifier);

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            /** {@inheritDoc} */
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            /** {@inheritDoc} */
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            /** {@inheritDoc} */
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());

            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        } catch (NoSuchAlgorithmException e1) {
            // ignore
        } catch (KeyManagementException e) {
            // ignore
        }
    }

    return conn;
}