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.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);// Make an empty store

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH);
    BufferedInputStream bis = new BufferedInputStream(fis);
    while (bis.available() > 0) {
        Certificate cert = cf.generateCertificate(bis);
        // System.out.println(cert.getPublicKey().toString());
        trustStore.setCertificateEntry("jetty" + bis.available(), cert);
    }//from  ww w.  j  av  a 2  s  . co  m

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory sslFactory = ctx.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if (0 == hostname.compareToIgnoreCase(url.getHost())) {
                return true;
            }
            return false;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslFactory);

    return urlConnection.getInputStream();
}

From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 * @param req servlet request//ww w. jav a 2  s .c o  m
 * @param resp servlet response
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {

        URL url = getURL(req, req.getParameter("uri"));
        HttpURLConnection con = (HttpURLConnection) (url.openConnection());
        con.setAllowUserInteraction(false);
        con.setUseCaches(false);

        // TODO: figure out why this is necessary for HTTPS URLs
        if (con instanceof HttpsURLConnection) {
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                        return true;
                    } else {
                        log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                        return false;
                    }
                }
            };
            ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
        }
        // pass along all appropriate HTTP headers
        Enumeration headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String hname = (String) headerNames.nextElement();
            if (!unproxiedHeaders.contains(hname.toLowerCase())) {
                con.addRequestProperty(hname, req.getHeader(hname));
            }
        }
        con.connect();

        // read result headers of GET, write to response
        Map<String, List<String>> headers = con.getHeaderFields();
        for (String key : headers.keySet()) {
            if (key != null) { // TODO: why is this check necessary!
                List<String> header = headers.get(key);
                if (header.size() > 0)
                    resp.setHeader(key, header.get(0));
            }
        }

        InputStream in = con.getInputStream();
        OutputStream out = resp.getOutputStream();
        final byte[] buf = new byte[8192];
        int len;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();

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

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

public static File downloadFile(final String url) throws IOException {
    InputStream in = null;/*from w  ww. j  a  v a 2s. c  o  m*/
    OutputStream out = null;
    try {
        LOGGER.info("downloadFile: " + url);
        final URL u = new URL(url);
        final URLConnection urlc = u.openConnection();
        if (urlc instanceof HttpsURLConnection) {
            final HttpsURLConnection http = (HttpsURLConnection) urlc;
            http.setInstanceFollowRedirects(false);
            http.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String arg0, final SSLSession arg1) {
                    return true;
                }
            });
            http.setRequestMethod(GET_STR);
            http.setAllowUserInteraction(true);
        }
        in = urlc.getInputStream();//new GZIPInputStream(dbURL.openStream());
        //      if(sourceCompressed) { in = new GZIPInputStream(in); }

        final File outputFile = File.createTempFile(tmpPrefix, tmpSuffix);
        out = new FileOutputStream(outputFile);

        IOUtils.copy(in, out);
        return outputFile;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:org.apache.brooklyn.util.http.HttpTool.java

/**
 * Connects to the given url and returns the connection.
 * Caller should {@code connection.getInputStream().close()} the result of this
 * (especially if they are making heavy use of this method).
 *//* ww  w  . j  a  va 2 s. com*/
public static URLConnection connectToUrl(String u) throws Exception {
    final URL url = new URL(u);
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();

    // sometimes openConnection hangs, so run in background
    Future<URLConnection> f = executor.submit(new Callable<URLConnection>() {
        public URLConnection call() {
            try {
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });
                URLConnection connection = url.openConnection();
                TrustingSslSocketFactory.configure(connection);
                connection.connect();

                connection.getContentLength(); // Make sure the connection is made.
                return connection;
            } catch (Exception e) {
                exception.set(e);
                LOG.debug("Error connecting to url " + url + " (propagating): " + e, e);
            }
            return null;
        }
    });
    try {
        URLConnection result = null;
        try {
            result = f.get(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("Error connecting to url " + url + ", probably timed out (rethrowing): " + e);
            throw new IllegalStateException(
                    "Connect to URL not complete within 60 seconds, for url " + url + ": " + e);
        }
        if (exception.get() != null) {
            LOG.debug("Error connecting to url " + url + ", thread caller of " + exception,
                    new Throwable("source of rethrown error " + exception));
            throw exception.get();
        } else {
            return result;
        }
    } finally {
        f.cancel(true);
    }
}

From source file:com.jwrapper.maven.java.JavaDownloadMojo.java

protected void setupNonVerifingSSL() throws Exception {

    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//from   w w w  . ja  v  a  2  s .c  om
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    // Install the all-trusting trust manager
    final SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

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

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

}

From source file:org.wso2.extension.siddhi.device.utils.ClientUtils.java

public static OkHttpClient getSSLClient() {

    boolean isIgnoreHostnameVerification = Boolean
            .parseBoolean(System.getProperty("org.wso2" + ".ignoreHostnameVerification"));
    OkHttpClient okHttpClient;/*from w ww. j  a v a 2s. c om*/
    final String proxyHost = System.getProperty("http.proxyHost");
    final String proxyPort = System.getProperty("http.proxyPort");
    final String nonProxyHostsValue = System.getProperty("http.nonProxyHosts");

    final ProxySelector proxySelector = new ProxySelector() {
        @Override
        public List<Proxy> select(URI uri) {
            List<Proxy> proxyList = new ArrayList<>();
            String host = uri.getHost();

            if (!StringUtils.isEmpty(host)) {
                if (host.startsWith(DEFAULT_HOST_IP) || host.startsWith(DEFAULT_HOST)
                        || StringUtils.isEmpty(nonProxyHostsValue)
                        || StringUtils.contains(nonProxyHostsValue, host) || StringUtils.isEmpty(proxyHost)
                        || StringUtils.isEmpty(proxyPort)) {
                    proxyList.add(Proxy.NO_PROXY);
                } else {
                    proxyList.add(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))));
                }
            } else {
                log.error("Host is null. Host could not be empty or null");
            }
            return proxyList;
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    };

    X509TrustManager trustAllCerts = new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[0];
        }

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

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    };
    if (isIgnoreHostnameVerification) {
        okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }).proxySelector(proxySelector).build();
        return okHttpClient;
    } else {
        SSLSocketFactory trustedSSLSocketFactory = getTrustedSSLSocketFactory();
        okHttpClient = new OkHttpClient.Builder().sslSocketFactory(trustedSSLSocketFactory)
                .proxySelector(proxySelector).build();
        return okHttpClient;
    }
}

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

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

    // https settings
    if (config.isDisableCertVerify()) {
        try {/*ww w  .  j  a v  a2s.co m*/
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        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));

    // Build http client
    client = httpClientBuilder.build();
    LOGGER.info("HTTP client is initialized");

    // Shutdown hook to close the http client
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if (client != null) {
                try {
                    client.close();
                    LOGGER.info("HTTP client is closed");
                } catch (Throwable e) {
                    LOGGER.error("Could not close http client", e);
                }
            }
        }
    });
}

From source file:vn.vnpttech.ssdc.nms.mediation.stbacs.main.XmppManager.java

public void init(final String username, final String password) throws Exception {

    logger.info(String.format("Initializing connection to server %1$s port %2$d", server, port));

    SmackConfiguration.setDefaultPacketReplyTimeout(packetReplyTimeout);
    //        SmackConfiguration.setPacketReplyTimeout(packetReplyTimeout);
    ////from  ww  w .ja  va2s  . c om
    //        config = new ConnectionConfiguration(server, port);
    //        config.setSASLAuthenticationEnabled(true);
    //        config.setSecurityMode(SecurityMode.disabled);

    boolean smackDebug = "true".equals(System.getProperty("smack.debug", "false"));

    this.username = username;
    this.password = password;

    XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
            .setUsernameAndPassword(username, password).setServiceName(server).setHost(server).setPort(port)
            .setCompressionEnabled(false).setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
            //.allowEmptyOrNullUsernames()
            .setDebuggerEnabled(smackDebug).setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String string, SSLSession ssls) {
                    return true;
                }
            }).build();

    connection = new XMPPTCPConnection(config);
    connection.setPacketReplyTimeout(packetReplyTimeout);
    connection.connect();

    logger.info("Connected: " + connection.isConnected());
    logger.info("Add filter to listen online/offline state");
    connection.addAsyncStanzaListener(new StanzaListener() {
        public void processPacket(Stanza packet) throws SmackException.NotConnectedException {

            try {
                StringBuilder sb = new StringBuilder();
                final Presence presence = (Presence) packet;
                sb.setLength(0);
                sb.append("presenceChanged: Presence changed status. From=").append(presence.getFrom())
                        .append(", Status=").append(presence.getStatus()).append(", Mode=")
                        .append(presence.getMode()).append(", Type=").append(presence.getType())
                        .append(", Priority=").append(presence.getPriority());
                logger.info(sb);
                //connection.sendStanza(result);
                final String serialNumber = StringUtils.substringBefore(presence.getFrom(), "@");
                if (!username.equals(serialNumber)) {
                    notifyExecutor.execute(new Runnable() {
                        public void run() {
                            onNotify(serialNumber, presence);
                        }
                    });
                }
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
    }, new StanzaTypeFilter(Presence.class));

    // Add packet Listener
    logger.info("Add filter to listen IQConnectionRequest");
    connection.addAsyncStanzaListener(new StanzaListener() {
        public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
            StringBuilder sb = new StringBuilder();
            sb.append("Received IQ.Type.GET, RAW=").append(packet.toXML());
            logger.debug(sb);

            final IQConnectionRequest iq = (IQConnectionRequest) packet;
            final IQ result = iq.getReply();

            logger.debug("Reply: " + result.toXML());
            connection.sendStanza(result);
        }
    }, new StanzaTypeFilter(IQConnectionRequest.class));

    // Listen for error
    logger.info("Add filter to listen Stanza Error");
    connection.addAsyncStanzaListener(new StanzaListener() {
        public void processPacket(Stanza packet) {
            StringBuilder sb = new StringBuilder();
            sb.append("Received IQ.Type.ERROR, RAW=").append(packet.toXML());
            logger.debug(sb);
            logger.debug("Error: Can't request to CPE --> Find packet id in command factory: "
                    + packet.getStanzaId());
            Command cm = CommandRequestFactory.getCommandByPacketId(packet.getStanzaId());
            if (cm != null) {
                String err = packet.getError().getConditionText() + ":" + packet.getError().getCondition() + ":"
                        + packet.getError().getType() + ":" + packet.getError().getDescriptiveText();
                logger.debug("Found command in factory, serialNumber: " + cm.getSerialNumberCPE()
                        + ", commandID=" + cm.getId() + ", ERROR=" + err);
                cm.receiveError(
                        new ConnectionException("No connection to the device: " + cm.getSerialNumberCPE()));
            }
        }
    }, new StanzaFilter() {

        public boolean accept(Stanza stanza) {
            return stanza instanceof IQ && ((IQ) stanza).getType() == IQ.Type.error;
        }
    });
    //        connection.addAsyncStanzaListener(new StanzaListener() {
    //            public void processPacket(Stanza packet) {
    //                StringBuilder sb = new StringBuilder();
    //                sb.append("Received IQ.Type.RESULT, RAW=")
    //                        .append(packet);
    //                logger.debug(sb);
    //            }
    //        }, new StanzaFilter() {
    //
    //            public boolean accept(Stanza stanza) {
    //                return (stanza instanceof IQ)
    //                        && !(stanza instanceof UnparsedIQ)
    //                        && ((IQ) stanza).getType() == IQ.Type.result;
    //            }
    //        });

    //        logger.info("Add listener to listen online/offline state");
    //        Roster roster = Roster.getInstanceFor(connection);
    //        roster.addRosterListener(new RosterListener() {
    //            public void presenceChanged(Presence presence) {
    //                try {
    //                    sb.setLength(0);
    //                    sb.append("presenceChanged: Presence changed status. From=")
    //                            .append(presence.getFrom())
    //                            .append(", Status=")
    //                            .append(presence.getStatus())
    //                            .append(", Mode=")
    //                            .append(presence.getMode())
    //                            .append(", Type=")
    //                            .append(presence.getType())
    //                            .append(", Priority=")
    //                            .append(presence.getPriority());
    //                    logger.info(sb);
    //                    String serialNumber = StringUtils.substringBefore(presence.getFrom(), "@");
    //                    onNotify(serialNumber, presence);
    //                } catch (Exception ex) {
    //                    logger.error(ex.getMessage(), ex);
    //                }
    //            }
    //
    //            public void entriesAdded(Collection<String> addresses) {
    //                logger.info("entriesAdded: WOOOOWH");
    //                logger.info(addresses);
    //            }
    //
    //            public void entriesUpdated(Collection<String> addresses) {
    //                logger.info("entriesUpdated: WOOOOWH");
    //                logger.info(addresses);
    //            }
    //
    //            public void entriesDeleted(Collection<String> addresses) {
    //                logger.info("entriesDeleted: WOOOOWH");
    //                logger.info(addresses);
    //            }
    //
    //        });
}

From source file:test.integ.be.fedict.trust.XKMSTrustTest.java

@Test
public void testValidateUnilateralTLSTrust() throws Exception {
    LOG.debug("validate using unilateral TLS Trust.");

    // Retrieve server public key
    SSLTrustManager.initialize();/*  ww  w  . j  a v a2s.c  o  m*/
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket(TestUtils.XKMS_WS_HOST, port);
    socket.startHandshake();
    Certificate[] serverCerts = socket.getSession().getPeerCertificates();
    PublicKey publicKey = serverCerts[0].getPublicKey();
    LOG.debug("server public key: " + publicKey);
    socket.close();

    /*
     * Override default verification that CN of server SSL certificate has
     * to be equal to the hostname.
     */
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return hostname.equals(TestUtils.XKMS_WS_HOST);
        }
    });

    // setup
    List<X509Certificate> signCertificateChain = TestUtils.getSignCertificateChain();
    XKMS2Client client = new XKMS2Client(
            "https://" + TestUtils.XKMS_WS_HOST + ":" + port + TestUtils.XKMS_WS_CONTEXT_PATH);
    client.setServicePublicKey(publicKey);

    /*
     * Operate: validate non repudiation
     */
    client.validate(TrustServiceDomains.BELGIAN_EID_NON_REPUDIATION_TRUST_DOMAIN, signCertificateChain);
}