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:org.transdroid.daemon.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 .ja v  a2s  .  c o  m*/
    }

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

    // For self-signed certificates use a custom trust manager
    if (acceptAllCertificates) {
        sslSocketFactory.setTrustManagers(new TrustManager[] { new IgnoreSSLTrustManager() });
    } else if (selfSignedCertificateKey != null) {
        sslSocketFactory
                .setTrustManagers(new TrustManager[] { new SelfSignedTrustManager(selfSignedCertificateKey) });
    }

    // 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 (!(acceptAllCertificates || selfSignedCertificateKey != null)
            && !hostnameVerifier.verify(host, session)) {
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
    }

    /*DLog.d(TlsSniSocketFactory.class.getSimpleName(),
    "Established " + session.getProtocol() + " connection with " + session.getPeerHost() +
          " using " + session.getCipherSuite());*/

    return ssl;
}

From source file:org.apache.jmeter.protocol.amf.proxy.AmfProxy.java

/**
 * Negotiate a SSL connection.//from www  .  j a va2  s  . c om
 *
 * @param sock socket in
 * @param host
 * @return a new client socket over ssl
 * @throws Exception if negotiation failed
 */
private Socket startSSL(Socket sock, String host) throws IOException {
    SSLSocketFactory sslFactory = getSSLSocketFactory(host);
    SSLSocket secureSocket;
    if (sslFactory != null) {
        try {
            secureSocket = (SSLSocket) sslFactory.createSocket(sock, sock.getInetAddress().getHostName(),
                    sock.getPort(), true);
            secureSocket.setUseClientMode(false);
            if (log.isDebugEnabled()) {
                log.debug("SSL transaction ok with cipher: " + secureSocket.getSession().getCipherSuite());
            }
            return secureSocket;
        } catch (IOException e) {
            log.error("Error in SSL socket negotiation: ", e);
            throw e;
        }
    } else {
        log.warn("Unable to negotiate SSL transaction, no keystore?");
        throw new IOException("Unable to negotiate SSL transaction, no keystore?");
    }
}

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 {//from  w ww. jav a  2s  .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:com.irccloud.android.HTTPFetcher.java

private void http_thread() {
    try {// www  .  ja v  a  2s  . c o  m
        mThread.setName("http-stream-thread");
        int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getProtocol().equals("https") ? 443 : 80);

        String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
        if (!TextUtils.isEmpty(mURI.getQuery())) {
            path += "?" + mURI.getQuery();
        }

        PrintWriter out = new PrintWriter(mSocket.getOutputStream());

        if (mProxyHost != null && mProxyHost.length() > 0 && mProxyPort > 0) {
            out.print("CONNECT " + mURI.getHost() + ":" + port + " HTTP/1.0\r\n");
            out.print("\r\n");
            out.flush();
            HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(
                    mSocket.getInputStream());

            // Read HTTP response status line.
            StatusLine statusLine = parseStatusLine(readLine(stream));
            if (statusLine == null) {
                throw new HttpException("Received no reply from server.");
            } else if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }

            // Read HTTP response headers.
            while (!TextUtils.isEmpty(readLine(stream)))
                ;
            if (mURI.getProtocol().equals("https")) {
                mSocket = getSSLSocketFactory().createSocket(mSocket, mURI.getHost(), port, false);
                SSLSocket s = (SSLSocket) mSocket;
                try {
                    s.setEnabledProtocols(ENABLED_PROTOCOLS);
                } catch (IllegalArgumentException e) {
                    //Not supported on older Android versions
                }
                try {
                    s.setEnabledCipherSuites(ENABLED_CIPHERS);
                } catch (IllegalArgumentException e) {
                    //Not supported on older Android versions
                }
                out = new PrintWriter(mSocket.getOutputStream());
            }
        }

        if (mURI.getProtocol().equals("https")) {
            SSLSocket s = (SSLSocket) mSocket;
            StrictHostnameVerifier verifier = new StrictHostnameVerifier();
            if (!verifier.verify(mURI.getHost(), s.getSession()))
                throw new SSLException("Hostname mismatch");
        }

        Crashlytics.log(Log.DEBUG, TAG, "Sending HTTP request");

        out.print("GET " + path + " HTTP/1.0\r\n");
        out.print("Host: " + mURI.getHost() + "\r\n");
        if (mURI.getHost().equals(NetworkConnection.IRCCLOUD_HOST)
                && NetworkConnection.getInstance().session != null
                && NetworkConnection.getInstance().session.length() > 0)
            out.print("Cookie: session=" + NetworkConnection.getInstance().session + "\r\n");
        out.print("Connection: close\r\n");
        out.print("Accept-Encoding: gzip\r\n");
        out.print("User-Agent: " + NetworkConnection.getInstance().useragent + "\r\n");
        out.print("\r\n");
        out.flush();

        HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream());

        // Read HTTP response status line.
        StatusLine statusLine = parseStatusLine(readLine(stream));
        if (statusLine != null)
            Crashlytics.log(Log.DEBUG, TAG, "Got HTTP response: " + statusLine);

        if (statusLine == null) {
            throw new HttpException("Received no reply from server.");
        } else if (statusLine.getStatusCode() != HttpStatus.SC_OK
                && statusLine.getStatusCode() != HttpStatus.SC_MOVED_PERMANENTLY) {
            Crashlytics.log(Log.ERROR, TAG, "Failure: " + mURI + ": " + statusLine.getStatusCode() + " "
                    + statusLine.getReasonPhrase());
            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        // Read HTTP response headers.
        String line;

        boolean gzipped = false;
        while (!TextUtils.isEmpty(line = readLine(stream))) {
            Header header = parseHeader(line);
            if (header.getName().equalsIgnoreCase("content-encoding")
                    && header.getValue().equalsIgnoreCase("gzip"))
                gzipped = true;
            if (statusLine.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                    && header.getName().equalsIgnoreCase("location")) {
                Crashlytics.log(Log.INFO, TAG, "Redirecting to: " + header.getValue());
                mURI = new URL(header.getValue());
                mSocket.close();
                mSocket = null;
                mThread = null;
                connect();
                return;
            }
        }

        if (gzipped)
            onStreamConnected(new GZIPInputStream(mSocket.getInputStream()));
        else
            onStreamConnected(mSocket.getInputStream());

        onFetchComplete();
    } catch (Exception ex) {
        NetworkConnection.printStackTraceToCrashlytics(ex);
        onFetchFailed();
    }
}

From source file:net.i2p.util.I2PSSLSocketFactory.java

/**
 *  Validate the hostname/*from   w  ww  .j  av  a2 s. c  o  m*/
 *
 *  ref: https://developer.android.com/training/articles/security-ssl.html
 *  ref: http://op-co.de/blog/posts/java_sslsocket_mitm/
 *  ref: http://kevinlocke.name/bits/2012/10/03/ssl-certificate-verification-in-dispatch-and-asynchttpclient/
 *
 *  @throws SSLException on hostname verification failure
 *  @since 0.9.20
 */
public static void verifyHostname(I2PAppContext ctx, SSLSocket socket, String host) throws SSLException {
    Log log = ctx.logManager().getLog(I2PSSLSocketFactory.class);
    if (ctx.getBooleanProperty(PROP_DISABLE) || host.equals("localhost") || host.equals("127.0.0.1")
            || host.equals("::1") || host.equals("0:0:0:0:0:0:0:1")) {
        if (log.shouldWarn())
            log.warn("Skipping hostname validation for " + host);
        return;
    }
    HostnameVerifier hv;
    if (SystemVersion.isAndroid()) {
        // https://developer.android.com/training/articles/security-ssl.html
        hv = HttpsURLConnection.getDefaultHostnameVerifier();
    } else {
        // haha the above may work for Android but it doesn't in Oracle
        //
        // quote http://kevinlocke.name/bits/2012/10/03/ssl-certificate-verification-in-dispatch-and-asynchttpclient/ :
        // Unlike SSLContext, using the Java default (HttpsURLConnection.getDefaultHostnameVerifier)
        // is not a viable option because the default HostnameVerifier expects to only be called
        // in the case that there is a mismatch (and therefore always returns false) while some
        // of the AsyncHttpClient providers (e.g. Netty, the default) call it on all connections.
        // To make matters worse, the check is not trivial (consider SAN and wildcard matching)
        // and is implemented in sun.security.util.HostnameChecker (a Sun internal proprietary API).
        // This leaves the developer in the position of either depending on an internal API or
        // finding/copying/creating another implementation of this functionality.
        //
        hv = new DefaultHostnameVerifier(getDefaultMatcher(ctx));
    }
    SSLSession sess = socket.getSession();
    // Verify that the certicate hostname is for mail.google.com
    // This is due to lack of SNI support in the current SSLSocket.
    if (!hv.verify(host, sess)) {
        throw new SSLHandshakeException("SSL hostname verify failed, Expected " + host +
        // throws SSLPeerUnverifiedException
        //", found " + sess.getPeerPrincipal() +
        // returns null
        //", found " + sess.getPeerHost() +
        // enable logging for DefaultHostnameVerifier to find out the CN and SANs
                " - set " + PROP_DISABLE + "=true to disable verification (dangerous!)");
    }
    // At this point SSLSocket performed certificate verificaiton and
    // we have performed hostname verification, so it is safe to proceed.
}

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * Will be a server socket... this one simply registers the listeners.
 *//*from   ww  w.  j  a v a  2s  .co  m*/
public void configureServerSSLSocket(Socket socket) throws IOException {
    if (socket instanceof SSLSocket) {
        SSLSocket sslSocket = (SSLSocket) socket;
        try {
            sslSocket.startHandshake();
            SSLSession session = sslSocket.getSession();
            Certificate[] peer = session.getPeerCertificates();
            if (logger.isDebugEnabled()) {
                logger.debug(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0,
                        ((X509Certificate) peer[0]).getSubjectDN()));
            }
        } catch (SSLPeerUnverifiedException ex) {
            if (this.sslConfig.isRequireAuth()) {
                logger.fatal(
                        LocalizedMessage.create(
                                LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER_0_1,
                                new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }),
                        ex);
                throw ex;
            }
        } catch (SSLException ex) {
            logger.fatal(
                    LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1,
                            new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }),
                    ex);
            throw ex;
        }
    }
}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * Initializes the HTTPs connection//from   w  w  w .ja  v  a 2 s  . c  om
 * 
 * @param sslPort
 *            the number of the port the server should be listening for
 *            SSL/TLS connections
 */
public void InitializeSecure(int sslPort) {
    if (sslPort != -1) {
        SSLSocketFactory sslf = null;
        SSLSocket s = null;
        port = sslPort;
        try {
            // notifyOfProggress(false);
            KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
            trusted.load(null, null);

            sslf = new MySSLSocketFactory(trusted);
            Log.w("Android mobile voting", "1");
            sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Log.w("Android mobile voting", "2");
            BasicHttpParams params = new BasicHttpParams();
            Log.w("Android mobile voting", "3");
            HttpConnectionParams.setConnectionTimeout(params, 500);
            Log.w("Android mobile voting", "4");
            s = (SSLSocket) sslf.connectSocket(sslf.createSocket(), server.getAddress(), sslPort, null, 0,
                    params);
            if (exc) {
                SSLSession ssls = null;
                ssls = s.getSession();
                final javax.security.cert.X509Certificate[] x = ssls.getPeerCertificateChain();

                for (int i = 0; i < x.length; i++) {

                    parent.mHandler.post(new Runnable() {

                        @Override
                        public void run() {

                            try {
                                parent.askForTrust(getThumbPrint(x[0]), instance);
                            } catch (NoSuchAlgorithmException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (CertificateEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (final Exception ex) {
                                parent.mHandler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        parent.showToast(ex.toString());

                                    }

                                });
                                Log.w("Android Mobile Voting", "400 Error");
                                parent.finish();
                            }

                        }
                    });

                }

            }

            s.startHandshake();

            Scheme https = new Scheme("https", sslf, sslPort);

            schemeRegistry.register(https);
            usingScheme = "https";
            port = sslPort;
            if (!exc)
                retrieveQuestions();
        } catch (final Exception ex) {
            parent.mHandler.post(new Runnable() {

                @Override
                public void run() {
                    parent.showToast(ex.toString());

                }

            });
            // Log.w("Android Mobile Voting", "400 Error");
            parent.finish();

        }
    } else {
        parent.mHandler.post(new Runnable() {

            @Override
            public void run() {
                parent.showNoSSLDialog(instance);

            }

        });
    }

}

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

/**
 * Performs the handshake and server certificates validation
 * @param sslSocket The secure connection socket
 * @param domain The website domain/*from www  .  j a v a  2s.c om*/
 * @return An SSL error object if there is an error and null otherwise
 */
public SslError doHandshakeAndValidateServerCertificates(HttpsConnection connection, SSLSocket sslSocket,
        String domain) throws SSLHandshakeException, IOException {

    ++sTotal;

    SSLContext sslContext = HttpsConnection.getContext();
    if (sslContext == null) {
        closeSocketThrowException(sslSocket, "SSL context is null");
    }

    X509Certificate[] serverCertificates = null;

    long sessionBeforeHandshakeLastAccessedTime = 0;
    byte[] sessionBeforeHandshakeId = null;

    SSLSession sessionAfterHandshake = null;

    synchronized (sslContext) {
        // get SSL session before the handshake
        SSLSession sessionBeforeHandshake = getSSLSession(sslContext, connection.getHost());
        if (sessionBeforeHandshake != null) {
            sessionBeforeHandshakeLastAccessedTime = sessionBeforeHandshake.getLastAccessedTime();

            sessionBeforeHandshakeId = sessionBeforeHandshake.getId();
        }

        // start handshake, close the socket if we fail
        try {
            sslSocket.setUseClientMode(true);
            sslSocket.startHandshake();
        } catch (IOException e) {
            closeSocketThrowException(sslSocket, e.getMessage(), "failed to perform SSL handshake");
        }

        // retrieve the chain of the server peer certificates
        Certificate[] peerCertificates = sslSocket.getSession().getPeerCertificates();

        if (peerCertificates == null || peerCertificates.length <= 0) {
            closeSocketThrowException(sslSocket, "failed to retrieve peer certificates");
        } else {
            serverCertificates = new X509Certificate[peerCertificates.length];
            for (int i = 0; i < peerCertificates.length; ++i) {
                serverCertificates[i] = (X509Certificate) (peerCertificates[i]);
            }

            // update the SSL certificate associated with the connection
            if (connection != null) {
                if (serverCertificates[0] != null) {
                    connection.setCertificate(new SslCertificate(serverCertificates[0]));
                }
            }
        }

        // get SSL session after the handshake
        sessionAfterHandshake = getSSLSession(sslContext, connection.getHost());
    }

    if (sessionBeforeHandshakeLastAccessedTime != 0 && sessionAfterHandshake != null
            && Arrays.equals(sessionBeforeHandshakeId, sessionAfterHandshake.getId())
            && sessionBeforeHandshakeLastAccessedTime < sessionAfterHandshake.getLastAccessedTime()) {

        if (HttpLog.LOGV) {
            HttpLog.v("SSL session was reused: total reused: " + sTotalReused + " out of total of: " + sTotal);

            ++sTotalReused;
        }

        // no errors!!!
        return null;
    }

    // check if the first certificate in the chain is for this site
    X509Certificate currCertificate = serverCertificates[0];
    if (currCertificate == null) {
        closeSocketThrowException(sslSocket, "certificate for this site is null");
    } else {
        if (!DomainNameChecker.match(currCertificate, domain)) {
            String errorMessage = "certificate not for this host: " + domain;

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            sslSocket.getSession().invalidate();
            return new SslError(SslError.SSL_IDMISMATCH, currCertificate);
        }
    }

    //
    // first, we validate the chain using the standard validation
    // solution; if we do not find any errors, we are done; if we
    // fail the standard validation, we re-validate again below,
    // this time trying to retrieve any individual errors we can
    // report back to the user.
    //
    try {
        synchronized (mDefaultTrustManager) {
            mDefaultTrustManager.checkServerTrusted(serverCertificates, "RSA");

            // no errors!!!
            return null;
        }
    } catch (CertificateException e) {
        if (HttpLog.LOGV) {
            HttpLog.v("failed to pre-validate the certificate chain, error: " + e.getMessage());
        }
    }

    sslSocket.getSession().invalidate();

    SslError error = null;

    // we check the root certificate separately from the rest of the
    // chain; this is because we need to know what certificate in
    // the chain resulted in an error if any
    currCertificate = serverCertificates[serverCertificates.length - 1];
    if (currCertificate == null) {
        closeSocketThrowException(sslSocket, "root certificate is null");
    }

    // check if the last certificate in the chain (root) is trusted
    X509Certificate[] rootCertificateChain = { currCertificate };
    try {
        synchronized (mDefaultTrustManager) {
            mDefaultTrustManager.checkServerTrusted(rootCertificateChain, "RSA");
        }
    } catch (CertificateExpiredException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate has expired";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        error = new SslError(SslError.SSL_EXPIRED, currCertificate);
    } catch (CertificateNotYetValidException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate not valid yet";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        error = new SslError(SslError.SSL_NOTYETVALID, currCertificate);
    } catch (CertificateException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate not trusted";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
    }

    // Then go through the certificate chain checking that each
    // certificate trusts the next and that each certificate is
    // within its valid date range. Walk the chain in the order
    // from the CA to the end-user
    X509Certificate prevCertificate = serverCertificates[serverCertificates.length - 1];

    for (int i = serverCertificates.length - 2; i >= 0; --i) {
        currCertificate = serverCertificates[i];

        // if a certificate is null, we cannot verify the chain
        if (currCertificate == null) {
            closeSocketThrowException(sslSocket, "null certificate in the chain");
        }

        // verify if trusted by chain
        if (!prevCertificate.getSubjectDN().equals(currCertificate.getIssuerDN())) {
            String errorMessage = "not trusted by chain";

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
        }

        try {
            currCertificate.verify(prevCertificate.getPublicKey());
        } catch (GeneralSecurityException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "not trusted by chain";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
        }

        // verify if the dates are valid
        try {
            currCertificate.checkValidity();
        } catch (CertificateExpiredException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "certificate expired";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            if (error == null || error.getPrimaryError() < SslError.SSL_EXPIRED) {
                error = new SslError(SslError.SSL_EXPIRED, currCertificate);
            }
        } catch (CertificateNotYetValidException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "certificate not valid yet";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            if (error == null || error.getPrimaryError() < SslError.SSL_NOTYETVALID) {
                error = new SslError(SslError.SSL_NOTYETVALID, currCertificate);
            }
        }

        prevCertificate = currCertificate;
    }

    // if we do not have an error to report back to the user, throw
    // an exception (a generic error will be reported instead)
    if (error == null) {
        closeSocketThrowException(sslSocket,
                "failed to pre-validate the certificate chain due to a non-standard error");
    }

    return error;
}

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * When a socket is accepted from a server socket, it should be passed to this method for SSL
 * configuration./*ww w  . j  a v a2 s . co  m*/
 */
private void configureClientSSLSocket(Socket socket, int timeout) throws IOException {
    if (socket instanceof SSLSocket) {
        SSLSocket sslSocket = (SSLSocket) socket;

        sslSocket.setUseClientMode(true);
        sslSocket.setEnableSessionCreation(true);

        String[] protocols = this.sslConfig.getProtocolsAsStringArray();

        // restrict cyphers
        if (protocols != null && !"any".equalsIgnoreCase(protocols[0])) {
            sslSocket.setEnabledProtocols(protocols);
        }
        String[] ciphers = this.sslConfig.getCiphersAsStringArray();
        if (ciphers != null && !"any".equalsIgnoreCase(ciphers[0])) {
            sslSocket.setEnabledCipherSuites(ciphers);
        }

        try {
            if (timeout > 0) {
                sslSocket.setSoTimeout(timeout);
            }
            sslSocket.startHandshake();
            SSLSession session = sslSocket.getSession();
            Certificate[] peer = session.getPeerCertificates();
            if (logger.isDebugEnabled()) {
                logger.debug(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0,
                        ((X509Certificate) peer[0]).getSubjectDN()));
            }
        } catch (SSLHandshakeException ex) {
            logger.fatal(
                    LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1,
                            new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }),
                    ex);
            throw ex;
        } catch (SSLPeerUnverifiedException ex) {
            if (this.sslConfig.isRequireAuth()) {
                logger.fatal(LocalizedMessage
                        .create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER), ex);
                throw ex;
            }
        } catch (SSLException ex) {
            logger.fatal(
                    LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1,
                            new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }),
                    ex);
            throw ex;
        }

    }
}