Example usage for javax.net.ssl SSLSession getPeerHost

List of usage examples for javax.net.ssl SSLSession getPeerHost

Introduction

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

Prototype

public String getPeerHost();

Source Link

Document

Returns the host name of the peer in this session.

Usage

From source file:org.andstatus.app.net.http.TlsSniSocketFactory.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void connectWithSNI(SSLSocket ssl, String host) throws SSLPeerUnverifiedException {
    // set reasonable SSL/TLS settings before the handshake:
    // - enable all supported protocols (enables TLSv1.1 and TLSv1.2 on Android <4.4.3, if available)
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());

    // - set SNI host name
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        MyLog.d(this, "Using documented SNI with host name " + host);
        sslSocketFactory.setHostname(ssl, host);
    } else {/*  w ww  .j  a v  a2  s. c  o  m*/
        MyLog.d(this, "No documented SNI support on Android <4.2, trying with reflection");
        try {
            java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class);
            setHostnameMethod.invoke(ssl, host);
        } catch (Exception e) {
            MyLog.i(this, "SNI not useable", e);
        }
    }

    // verify hostname and certificate
    SSLSession session = ssl.getSession();
    if (!session.isValid()) {
        MyLog.i(this, "Invalid session to host:'" + host + "'");
    }

    HostnameVerifier hostnameVerifier = secure ? new BrowserCompatHostnameVerifier()
            : new AllowAllHostnameVerifier();
    if (!hostnameVerifier.verify(host, session)) {
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
    }

    MyLog.i(this, "Established " + session.getProtocol() + " connection with " + session.getPeerHost()
            + " using " + session.getCipherSuite());
}

From source file:de.bps.webservices.clients.onyxreporter.OnyxReporterConnector.java

private boolean isServiceAvailable(String target) {

    HostnameVerifier hv = new HostnameVerifier() {
        @Override/*ww w . j av  a 2 s.co m*/
        public boolean verify(String urlHostName, SSLSession session) {
            if (urlHostName.equals(session.getPeerHost())) {
                return true;
            } else {
                return false;
            }
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    try {
        URL url = new URL(target + "?wsdl");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sslconn = (HttpsURLConnection) con;
            SSLContext context = SSLContext.getInstance("SSL");
            context.init(SSLConfigurationModule.getKeyManagers(), SSLConfigurationModule.getTrustManagers(),
                    new java.security.SecureRandom());
            sslconn.setSSLSocketFactory(context.getSocketFactory());
            sslconn.connect();
            if (sslconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                sslconn.disconnect();
                return true;
            }
        } else {
            con.connect();
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return true;
            }
        }
    } catch (Exception e) {
        Tracing.createLoggerFor(getClass()).error("Error while trying to connect to webservice: " + target, e);
    }
    return false;
}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public static void setupSSL(String enpointUrl, boolean sslDebug) {

    if (enpointUrl == null || !enpointUrl.startsWith("https")) {
        _log.info("setupSSL: no HTTPS found -> no setup needed");
        return;/*from   w  w w  .  j a  v  a  2 s.c o m*/
    }

    // enable SSL-Debuging
    if (sslDebug) {
        System.setProperty("javax.net.debug", "ssl");
    }

    ConfigurationManagerService cms = ConfigurationManagerService.getInstance();

    // Setting Cert-Props
    System.setProperty("javax.net.ssl.trustStore", cms.getProperty("javax.net.ssl.trustStore"));
    System.setProperty("javax.net.ssl.trustStorePassword", cms.getProperty("javax.net.ssl.trustStorePassword"));
    System.setProperty("javax.net.ssl.keyStore", cms.getProperty("javax.net.ssl.keyStore"));
    System.setProperty("javax.net.ssl.keyStorePassword", cms.getProperty("javax.net.ssl.keyStorePassword"));

    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            System.out.println("URL Host: expected: " + urlHostName + " found: " + session.getPeerHost());
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactoryBase.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket a <code>SSLSocket</code> value
 * @exception SSLPeerUnverifiedException  If there are problems obtaining
 * the server certificates from the SSL session, or the server host name 
 * does not match with the "Common Name" in the server certificates 
 * SubjectDN.//from   ww  w.  j  a v a2s  .c o m
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
protected void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (!verifyHostname)
        return;

    SSLSession session = socket.getSession();
    if (session == null) {
        throw new UnknownHostException("could not obtain session from socket");
    }
    String hostname = session.getPeerHost();
    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        String msg = "Could not resolve SSL sessions server hostname: " + hostname;
        // Under WebSphere, hostname can be equal to proxy-hostname
        log.warn(msg, uhe);
        //         throw new UnknownHostException(msg);
    }

    javax.security.cert.X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    //get the servers DN in its string representation
    String dn = certs[0].getSubjectDN().getName();

    //might be useful to print out all certificates we receive from the
    //server, in case one has to debug a problem with the installed certs.
    if (log.isInfoEnabled()) {
        log.info("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            log.info("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (log.isInfoEnabled()) {
            log.info("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

From source file:org.apache.ranger.admin.client.RangerAdminJersey2RESTClient.java

Client buildClient() {

    if (_isSSL) {
        if (_sslContext == null) {
            RangerSslHelper sslHelper = new RangerSslHelper(_sslConfigFileName);
            _sslContext = sslHelper.createContext();
        }/*from   w  w w .  ja v a 2 s .c  o m*/
        if (_hv == null) {
            _hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return session.getPeerHost().equals(urlHostName);
                }
            };
        }
        _client = ClientBuilder.newBuilder().sslContext(_sslContext).hostnameVerifier(_hv).build();
    }

    if (_client == null) {
        _client = ClientBuilder.newClient();
    }

    return _client;
}

From source file:org.apache.ranger.plugin.util.RangerRESTClient.java

private Client buildClient() {
    Client client = null;// w ww .  j ava 2  s. co m

    if (mIsSSL) {
        KeyManager[] kmList = getKeyManagers();
        TrustManager[] tmList = getTrustManagers();
        SSLContext sslContext = getSSLContext(kmList, tmList);
        ClientConfig config = new DefaultClientConfig();

        config.getClasses().add(JacksonJsonProvider.class); // to handle List<> unmarshalling

        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return session.getPeerHost().equals(urlHostName);
            }
        };

        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(hv, sslContext));

        client = Client.create(config);
    }

    if (client == null) {
        ClientConfig config = new DefaultClientConfig();

        config.getClasses().add(JacksonJsonProvider.class); // to handle List<> unmarshalling

        client = Client.create(config);
    }

    if (!StringUtils.isEmpty(mUsername) && !StringUtils.isEmpty(mPassword)) {
        client.addFilter(new HTTPBasicAuthFilter(mUsername, mPassword));
    }

    // Set Connection Timeout and ReadTime for the PolicyRefresh
    client.setConnectTimeout(mRestClientConnTimeOutMs);
    client.setReadTimeout(mRestClientReadTimeOutMs);

    return client;
}

From source file:org.apache.synapse.config.SynapseConfigUtils.java

/**
 * Helper method to create a HttpSURLConnection with provided KeyStores
 *
 * @param url Https URL/*w  ww.  j  av a  2  s .c  o m*/
 * @param synapseProperties properties for extracting info
 * @param proxy if there is a proxy
 * @return gives out the connection created
 */
private static HttpsURLConnection getHttpsURLConnection(URL url, Properties synapseProperties, Proxy proxy) {

    if (log.isDebugEnabled()) {
        log.debug("Creating a HttpsURL Connection from given URL : " + url);
    }

    KeyManager[] keyManagers = null;
    TrustManager[] trustManagers = null;

    IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory
            .createIdentityKeyStoreInformation(synapseProperties);

    if (identityInformation != null) {
        KeyManagerFactory keyManagerFactory = identityInformation.getIdentityKeyManagerFactoryInstance();
        if (keyManagerFactory != null) {
            keyManagers = keyManagerFactory.getKeyManagers();
        }

    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no private key entry store configuration." + " Will use JDK's default one");
        }
    }

    TrustKeyStoreInformation trustInformation = KeyStoreInformationFactory
            .createTrustKeyStoreInformation(synapseProperties);

    if (trustInformation != null) {
        TrustManagerFactory trustManagerFactory = trustInformation.getTrustManagerFactoryInstance();
        if (trustManagerFactory != null) {
            trustManagers = trustManagerFactory.getTrustManagers();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no trusted certificate store configuration." + " Will use JDK's default one");
        }
    }

    try {
        HttpsURLConnection connection;
        if (proxy != null) {
            connection = (HttpsURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpsURLConnection) url.openConnection();
        }
        //Create a SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);
        connection.setSSLSocketFactory(sslContext.getSocketFactory());

        if (trustInformation != null) {
            // Determine is it need to overwrite default Host Name verifier
            boolean enableHostnameVerifier = true;
            String value = trustInformation.getParameter(KeyStoreInformation.ENABLE_HOST_NAME_VERIFIER);
            if (value != null) {
                enableHostnameVerifier = Boolean.parseBoolean(value);
            }

            if (!enableHostnameVerifier) {

                if (log.isDebugEnabled()) {
                    log.debug("Overriding default HostName Verifier." + "HostName verification disabled");
                }

                connection.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
                    public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
                        if (log.isTraceEnabled()) {
                            log.trace("HostName verification disabled");
                            log.trace("Host:   " + hostname);
                            log.trace("Peer Host:  " + session.getPeerHost());
                        }
                        return true;
                    }
                });
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using default HostName verifier...");
                }
            }
        }
        return connection;

    } catch (NoSuchAlgorithmException e) {
        handleException("Error loading SSLContext ", e);
    } catch (KeyManagementException e) {
        handleException("Error initiation SSLContext with KeyManagers", e);
    } catch (IOException e) {
        handleException("Error opening a https connection from URL : " + url, e);
    }
    return null;
}

From source file:org.dcm4chee.xds2.src.tool.pnrsnd.PnRSnd.java

private void configTLS() {
    final HostnameVerifier origHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    final String allowedUrlHost = props.getProperty("allowedUrlHost");
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            if (!origHostnameVerifier.verify(urlHostName, session)) {
                if (isAllowedUrlHost(urlHostName)) {
                    log.warn("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                } else {
                    return false;
                }//w ww  . j  av a  2 s. co m
            }
            return true;
        }

        private boolean isAllowedUrlHost(String urlHostName) {
            if (allowedUrlHost == null || "CERT".equals(allowedUrlHost))
                return false;
            if (allowedUrlHost.equals("*"))
                return true;
            return allowedUrlHost.equals(urlHostName);
        }

    };

    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:org.jevis.commons.driver.DataSourceHelper.java

static public void doTrustToCertificates() throws Exception {
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from ww w  .ja  v a 2 s  . c o m*/

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

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

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
                System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '"
                        + session.getPeerHost() + "'.");
            }
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:org.jsslutils.extra.apachehttpclient.SslContextedSecureProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 * //from w ww.  j a  va 2 s  .co  m
 * @param socket
 *            a <code>SSLSocket</code> value
 * @exception SSLPeerUnverifiedException
 *                If there are problems obtaining the server certificates
 *                from the SSL session, or the server host name does not
 *                match with the "Common Name" in the server certificates
 *                SubjectDN.
 * @exception UnknownHostException
 *                If we are not able to resolve the SSL sessions returned
 *                server host name.
 * @throws CertificateParsingException
 */
private void verifyHostname(SSLSocket socket) throws IOException, UnknownHostException {
    synchronized (this) {
        if (!verifyHostname)
            return;
    }

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    X509Certificate[] certs = (X509Certificate[]) session.getPeerCertificates();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    try {
        List<String> cns = new ArrayList<String>();
        boolean foundDnsSan = false;
        Collection<List<?>> subjectAltNames = certs[0].getSubjectAlternativeNames();
        if (subjectAltNames != null) {
            for (List<?> san : subjectAltNames) {
                if (((Integer) san.get(0)).intValue() == 2) {
                    foundDnsSan = true;
                    String sanDns = (String) san.get(1);
                    cns.add(sanDns);
                    if (hostname.equalsIgnoreCase(sanDns)) {
                        return;
                    }
                }
            }
        }
        if (!foundDnsSan) {
            // get the common names from the first cert
            X500Principal subjectDN = certs[0].getSubjectX500Principal();
            cns = getCNs(subjectDN);
            for (String cn : cns) {
                if (hostname.equalsIgnoreCase(cn)) {
                    return;
                }
            }
        }
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cns + "'");
    } catch (CertificateParsingException e) {
        throw new IOException(e);
    }
}