Example usage for javax.net.ssl SSLSocket getSession

List of usage examples for javax.net.ssl SSLSocket getSession

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocket getSession.

Prototype

public abstract SSLSession getSession();

Source Link

Document

Returns the SSL Session in use by this connection.

Usage

From source file:eu.eidas.node.auth.metadata.NodeMetadataFetcher.java

protected SecureProtocolSocketFactory hubLocalSslSocketFactory() {
    HostnameVerifier hostnameVerifier;

    if (!Boolean.getBoolean(DefaultBootstrap.SYSPROP_HTTPCLIENT_HTTPS_DISABLE_HOSTNAME_VERIFICATION)) {
        hostnameVerifier = new StrictHostnameVerifier();
    } else {/*w  w w.  j a  va2s .co  m*/
        hostnameVerifier = org.apache.commons.ssl.HostnameVerifier.ALLOW_ALL;
    }

    X509TrustManager trustedCertManager = new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            try {
                return new X509Certificate[] { CertificateUtil.toCertificate(hubSslCertificateString) };
            } catch (EIDASSAMLEngineException e) {
                throw new RuntimeException("Unable to load trusted certificate: ", e);
            }
        }

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

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    };

    TLSProtocolSocketFactory tlsProtocolSocketFactory = new TLSProtocolSocketFactory(null, trustedCertManager,
            hostnameVerifier) {
        @Override
        protected void verifyHostname(Socket socket) throws SSLException {
            if (socket instanceof SSLSocket) {
                SSLSocket sslSocket = (SSLSocket) socket;
                try {
                    sslSocket.startHandshake();
                } catch (IOException e) {
                    throw new SSLException(e);
                }
                SSLSession sslSession = sslSocket.getSession();
                if (!sslSession.isValid()) {
                    throw new SSLException("SSLSession was invalid: Likely implicit handshake failure: "
                            + "Set system property javax.net.debug=all for details");
                }
                super.verifyHostname(sslSocket);
            }
        }
    };

    Protocol.registerProtocol("https", new Protocol("https", tlsProtocolSocketFactory, 443));

    return tlsProtocolSocketFactory;
}

From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.AbstractApacheClientHttpInvoker.java

/**
 * Verifies a hostname with the given verifier.
 *///from   w  ww . j a  v a 2 s  . c om
protected void verify(HostnameVerifier verifier, String host, SSLSocket sslSocket) throws IOException {
    try {
        if (verifier instanceof X509HostnameVerifier) {
            ((X509HostnameVerifier) verifier).verify(host, sslSocket);
        } else {
            if (!verifier.verify(host, sslSocket.getSession())) {
                throw new SSLException("Hostname in certificate didn't match: <" + host + ">");
            }
        }
    } catch (IOException ioe) {
        closeSocket(sslSocket);
        throw ioe;
    }
}

From source file:android.net.http.CertificateChainValidator.java

private void closeSocketThrowException(SSLSocket socket, String errorMessage)
        throws SSLHandshakeException, IOException {
    if (HttpLog.LOGV) {
        HttpLog.v("validation error: " + errorMessage);
    }/*w  w  w . jav  a  2s  .c o m*/

    if (socket != null) {
        SSLSession session = socket.getSession();
        if (session != null) {
            session.invalidate();
        }

        socket.close();
    }

    throw new SSLHandshakeException(errorMessage);
}

From source file:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from   w w w.j  a  va2 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 (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:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.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 a2 s .c o m
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (sslManager == null) {
        return;
    }
    ISSLErrorManager errorMng = sslManager.getSSLErrorManager();
    if (errorMng == null) {
        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 = 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.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            java.security.cert.X509Certificate servCert = (java.security.cert.X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(certs[0].getEncoded()));
            if (!errorMng.continueErrorPeer(hostname, servCert)) {
                throw new SSLPeerUnverifiedException(
                        "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
            }
        } catch (CertificateException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        } catch (CertificateEncodingException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        }
    }
}

From source file:com.mendhak.gpslogger.common.network.CertificateValidationWorkflow.java

private void connectToSSLSocket(Socket plainSocket) throws IOException {
    SSLSocketFactory factory = Networks.getSocketFactory(context);
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
    if (plainSocket != null) {
        socket = (SSLSocket) factory.createSocket(plainSocket, host, port, true);
    }/*from w  w  w . j  av a  2s .c  o  m*/

    if (serverType == ServerType.SMTP) {
        socket.setUseClientMode(true);
        socket.setNeedClientAuth(true);
    }

    socket.setSoTimeout(5000);
    LOG.debug("Starting handshake...");
    socket.startHandshake();
    SSLSession session = socket.getSession();
    Certificate[] servercerts = session.getPeerCertificates();

}

From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java

@Test
public void testMutualSSL() throws Exception {

    Security.addProvider(new BeIDProvider());

    final KeyPair serverKeyPair = generateKeyPair();
    final PrivateKey serverPrivateKey = serverKeyPair.getPrivate();
    final DateTime notBefore = new DateTime();
    final DateTime notAfter = notBefore.plusDays(1);
    final X509Certificate serverCertificate = generateCACertificate(serverKeyPair, "CN=Test", notBefore,
            notAfter);//from   w w w  .  jav a 2  s  .  c  om

    final KeyManager keyManager = new ServerTestX509KeyManager(serverPrivateKey, serverCertificate);
    final TrustManager trustManager = new ServerTestX509TrustManager();
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] { keyManager }, new TrustManager[] { trustManager }, new SecureRandom());

    final SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();

    final int serverPort = 8443;
    final SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory
            .createServerSocket(serverPort);

    sslServerSocket.setNeedClientAuth(true);

    final TestRunnable testRunnable = new TestRunnable(serverPort);
    final Thread thread = new Thread(testRunnable);
    thread.start();

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    LOG.debug("server accepted");
    InputStream inputStream = sslSocket.getInputStream();
    int result = inputStream.read();
    LOG.debug("result: " + result);
    assertEquals(12, result);
    SSLSession sslSession = sslSocket.getSession();
    sslSession.invalidate();
    sslSocket = (SSLSocket) sslServerSocket.accept();
    inputStream = sslSocket.getInputStream();
    result = inputStream.read();
    LOG.debug("result: " + result);
    assertEquals(34, result);
}

From source file:org.transdroid.util.TlsSniSocketFactory.java

@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException {
    if (autoClose) {
        // we don't need the plainSocket
        plainSocket.close();/*from w  w w  .  j  a v  a 2  s  .c  o m*/
    }

    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory
            .getDefault(0);

    // create and connect SSL socket, but don't do hostname/certificate verification yet
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);

    // enable TLSv1.1/1.2 if available
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());

    // set up SNI before the handshake
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        sslSocketFactory.setHostname(ssl, host);
    } else {
        try {
            java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class);
            setHostnameMethod.invoke(ssl, host);
        } catch (Exception e) {
            Log.d(TlsSniSocketFactory.class.getSimpleName(), "SNI not usable: " + e);
        }
    }

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

    return ssl;
}

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 {//from   w  ww. j a va  2 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());
}