Example usage for javax.net.ssl SSLSession getProtocol

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

Introduction

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

Prototype

public String getProtocol();

Source Link

Document

Returns the standard name of the protocol used for all connections in the session.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    System.setProperty("javax.net.ssl.keyStore", "lfkeystore2");
    System.setProperty("javax.net.ssl.keyStorePassword", "wshr.ut");

    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(5432);
    while (true) {
        Socket s = ss.accept();//from ww  w .j  av a 2 s.c  om
        SSLSession session = ((SSLSocket) s).getSession();
        Certificate[] cchain2 = session.getLocalCertificates();
        for (int i = 0; i < cchain2.length; i++) {
            System.out.println(((X509Certificate) cchain2[i]).getSubjectDN());
        }
        System.out.println("Peer host is " + session.getPeerHost());
        System.out.println("Cipher is " + session.getCipherSuite());
        System.out.println("Protocol is " + session.getProtocol());
        System.out.println("ID is " + new BigInteger(session.getId()));
        System.out.println("Session created in " + session.getCreationTime());
        System.out.println("Session accessed in " + session.getLastAccessedTime());

        PrintStream out = new PrintStream(s.getOutputStream());
        out.println("Hi");
        out.close();
        s.close();
    }

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    System.setProperty("javax.net.ssl.trustStore", "clienttrust");

    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = ssf.createSocket("127.0.0.1", 5432);

    SSLSession session = ((SSLSocket) s).getSession();
    Certificate[] cchain = session.getPeerCertificates();
    System.out.println("The Certificates used by peer");
    for (int i = 0; i < cchain.length; i++) {
        System.out.println(((X509Certificate) cchain[i]).getSubjectDN());
    }// w w w  .j  a  va 2 s  . co m
    System.out.println("Peer host is " + session.getPeerHost());
    System.out.println("Cipher is " + session.getCipherSuite());
    System.out.println("Protocol is " + session.getProtocol());
    System.out.println("ID is " + new BigInteger(session.getId()));
    System.out.println("Session created in " + session.getCreationTime());
    System.out.println("Session accessed in " + session.getLastAccessedTime());

    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String x = in.readLine();
    System.out.println(x);
    in.close();

}

From source file:at.bitfire.davdroid.mirakel.webdav.TlsSniSocketFactory.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void connectWithSNI(SSLSocket ssl, String host) throws SSLPeerUnverifiedException {
    // - set SNI host name
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Log.d(TAG, "Using documented SNI with host name " + host);
        sslSocketFactory.setHostname(ssl, host);
    } else {// w  w w .  ja va2  s  .c  o  m
        Log.d(TAG, "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) {
            Log.w(TAG, "SNI not useable", e);
        }
    }

    // verify hostname and certificate
    SSLSession session = ssl.getSession();
    if (!hostnameVerifier.verify(host, session))
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);

    Log.d(TAG, "Established " + session.getProtocol() + " connection with " + session.getPeerHost() + " using "
            + session.getCipherSuite());
}

From source file:com.rastating.droidbeard.net.TlsSocketFactory.java

@Override
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {
    // Create and connect SSL socket, but don't do hostname/certificate verification yet
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory
            .getDefault(0);//from   w  w  w .  j  av  a2s . c o m

    // Setup custom trust manager if we are trusting all certificates
    if (mTrustAllCertificates) {
        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

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

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

        sslSocketFactory.setTrustManagers(new TrustManager[] { tm });
    }

    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);

    // Enable TLSv1.1/1.2 if available
    // (see https://github.com/rfc2822/davdroid/issues/229)
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());
    SSLSession session = ssl.getSession();

    // Verify hostname and certificate if we aren't trusting all certificates
    if (!mTrustAllCertificates) {
        if (!hostnameVerifier.verify(host, session))
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
    }

    Log.i("droidbeard", "Established " + session.getProtocol() + " connection with " + session.getPeerHost()
            + " using " + session.getCipherSuite());
    return ssl;
}

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  w  w .  jav  a 2  s.  co 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:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from w w  w. j  av a2 s  .  c  o m
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Secure session established");
            LOGGER.debug(" negotiated protocol: {}", session.getProtocol());
            LOGGER.debug(" negotiated cipher suite: {}", session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                LOGGER.debug(" peer principal: {}", peer);
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    LOGGER.debug(" peer alternative names: {}", altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                LOGGER.debug(" issuer principal: {}", issuer);
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    LOGGER.debug(" issuer alternative names: {}", altNames);
                }
            } catch (Exception ignore) {
            }
        }

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (RuntimeException | IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            iox.addSuppressed(x);
        }
        throw iox;
    }
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/* w ww.j a v a2s. c  o  m*/
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        HostnameVerifier hostnameVerifier = insecure ? insecureHostnameVerifier : defaultHostnameVerifier;
        if (!hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.SSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {// w  ww . j  a va2s . co m
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:org.apache.pulsar.client.impl.ClientCnx.java

/**
 * verifies host name provided in x509 Certificate in tls session
 *
 * it matches hostname with below scenarios
 *
 * <pre>// w  ww  .j a v a 2  s  . co  m
 *  1. Supports IPV4 and IPV6 host matching
 *  2. Supports wild card matching for DNS-name
 *  eg:
 *     HostName                     CN           Result
 * 1.  localhost                    localhost    PASS
 * 2.  localhost                    local*       PASS
 * 3.  pulsar1-broker.com           pulsar*.com  PASS
 * </pre>
 *
 * @param ctx
 * @return true if hostname is verified else return false
 */
private boolean verifyTlsHostName(String hostname, ChannelHandlerContext ctx) {
    ChannelHandler sslHandler = ctx.channel().pipeline().get("tls");

    SSLSession sslSession = null;
    if (sslHandler != null) {
        sslSession = ((SslHandler) sslHandler).engine().getSession();
        if (log.isDebugEnabled()) {
            log.debug("Verifying HostName for {}, Cipher {}, Protocols {}", hostname,
                    sslSession.getCipherSuite(), sslSession.getProtocol());
        }
        return hostnameVerifier.verify(hostname, sslSession);
    }
    return false;
}