Example usage for javax.net.ssl SSLSocket startHandshake

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

Introduction

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

Prototype

public abstract void startHandshake() throws IOException;

Source Link

Document

Starts an SSL handshake on this connection.

Usage

From source file:de.vanita5.twittnuker.util.net.ssl.AbstractCheckSignatureVerifier.java

@Override
public final void verify(final String host, final SSLSocket ssl) throws IOException {
    if (host == null)
        throw new NullPointerException("host to verify is null");

    SSLSession session = ssl.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 = ssl.getInputStream();
        in.available();//from   ww w  . j  a  v a 2s  .  c o  m
        /*
         * If you're looking at the 2 lines of code above because you're
         * running into a problem, you probably have two options:
         *
         * #1. Clean up the certificate chain that your server is presenting
         * (e.g. edit "/etc/apache2/server.crt" or wherever it is your
         * server's certificate chain is defined).
         *
         * OR
         *
         * #2. Upgrade to an IBM 1.5.x or greater JVM, or switch to a
         * non-IBM JVM.
         */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if (session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE. Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    final Certificate[] certs = session.getPeerCertificates();
    final X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}

From source file:com.epam.reportportal.apache.http.conn.ssl.AbstractVerifier.java

public final void verify(final String host, final SSLSocket ssl) throws IOException {
    if (host == null) {
        throw new NullPointerException("host to verify is null");
    }/*  w ww .  ja va2s. c  om*/

    SSLSession session = ssl.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 = ssl.getInputStream();
        in.available();
        /*
          If you're looking at the 2 lines of code above because
          you're running into a problem, you probably have two
          options:
                
        #1.  Clean up the certificate chain that your server
             is presenting (e.g. edit "/etc/apache2/server.crt"
             or wherever it is your server's certificate chain
             is defined).
                
                                   OR
                
        #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
              to a non-IBM JVM.
        */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if (session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE.  Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    final Certificate[] certs = session.getPeerCertificates();
    final X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}

From source file:org.bombusim.networking.NetworkSocketDataStream.java

public void setTLS() throws IOException {
    LimeLog.i("Socket", "Switching to secure socket layer", null);

    //TODO: check on different devices:
    // !!! ENSURE TLS enabled in account settings before test
    // 1. emulator/2.2 - SSLPeerUnverifiedException (jabber.ru, google.com) - bug in emulator v2.2
    // 2. cyanogen/2.3 - works (all hosts)
    // 3. emulator/ics - works
    // 4. Gratia/2.2 - works
    SSLSocketFactory sf =/*from ww  w . j a  v a2  s.c  om*/
            //SSLCertificateSocketFactory.getDefault(20000, null);
            SSLCertificateSocketFactory.getInsecure(20000, null);

    //TODO: check on different devices:
    // 1. emulator/2.2 - works
    // 2. cyanogen/2.3 - works
    //KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
    //trustStore.load(null, null); 
    //SSLSocketFactory sf = new AndroidSSLSocketFactory(trustStore); 
    //sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

    final SSLSocket ssls = (SSLSocket) sf.createSocket(socket, host, port, true);

    ssls.addHandshakeCompletedListener(new HandshakeCompletedListener() {
        @Override
        public void handshakeCompleted(HandshakeCompletedEvent event) {
            X509Certificate[] certs;
            try {
                certs = ssls.getSession().getPeerCertificateChain();
            } catch (SSLPeerUnverifiedException e) {
                return;
            }

            StringBuilder so = new StringBuilder();

            for (X509Certificate cert : certs) {
                so.append("X509 Certificate:\n").append(" Subject:");
                appendPrincipal(so, cert.getSubjectDN());
                so.append("\n Issued by:");
                appendPrincipal(so, cert.getIssuerDN());
                so.append("\n Valid from:    ").append(DateFormat.getInstance().format(cert.getNotBefore()));
                so.append("\n Expired after: ").append(DateFormat.getInstance().format(cert.getNotAfter()));
                so.append("\n\n");
            }

            certificateInfo = so.toString();
            LimeLog.i("Socket", "Certificate chain verified", certificateInfo);
        }

        private void appendPrincipal(StringBuilder so, Principal p) {
            String name = p.getName();
            if (name == null) {
                so.append("<null>\n");
                return;
            }

            String elements[] = name.split(",");
            for (String e : elements) {
                so.append("\n   ").append(e);
            }

            so.append("\n");
        }
    });

    ssls.startHandshake();
    socket = ssls;

    istream = socket.getInputStream();
    ostream = socket.getOutputStream();

}

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./*from   w  w  w.  j a va2s . c  o 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;
        }

    }
}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

private SSLSocket openConnectionToAPNS(String host, int port, String key, String passphrase) {
    SSLSocket socket;
    try {//from  w w  w.j  a  va 2s.co m
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        //          keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(getClass().getResourceAsStream("/newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());

        // This works when built with Eclipse, but not when built from command line. 
        // Has to do with where the build system puts /resources/*.p12 file
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream(key), "strange word to use".toCharArray());

        // Currently only works when read from the server's FS. Won't currently read from within eclipse project. 
        // Putting it in /opt/kme/push prevents naming conflicts. 
        keyStore.load(new FileInputStream("/opt/kme/push/newcert.p12"), "strange word to use".toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
        keyManagerFactory.init(keyStore, "strange word to use".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
        trustManagerFactory.init(keyStore);
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
        SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
        socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
        socket.startHandshake();

        //Diagnostic output
        Enumeration e = keyStore.aliases();
        LOG.info(e.toString());
        while (e.hasMoreElements()) {
            LOG.info("Alias: " + e.nextElement().toString());
        }

        String not = (socket.isConnected()) ? "" : "NOT ";
        LOG.info("SSLSocket is " + not + "Connected");

        LOG.info("Connected to: " + socket.getInetAddress().getCanonicalHostName());
        LOG.info("Connected to: " + socket.getInetAddress().getHostAddress());

        String cs[] = socket.getEnabledCipherSuites();
        LOG.info("CipherSuites: " + Arrays.toString(cs));

        String ep[] = socket.getEnabledProtocols();
        LOG.info("Enabled Protocols: " + Arrays.toString(ep));

        LOG.info("Timeout: " + socket.getSoTimeout());
        LOG.info("Send Buffer Size: " + socket.getSendBufferSize());

        return socket;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.hyperic.hq.bizapp.agent.client.SecureAgentConnection.java

@Override
protected Socket getSocket() throws IOException {
    SSLSocket socket;

    log.debug("Creating secure socket");

    try {/*from  ww w. ja va2  s.  c  o m*/
        // Check for configured agent read timeout from System properties
        int readTimeout;

        try {
            readTimeout = Integer.parseInt(System.getProperty(PROP_READ_TIMEOUT));
        } catch (NumberFormatException e) {
            readTimeout = READ_TIMEOUT;
        }

        // Check for configured agent post handshake timeout
        // from System properties
        int postHandshakeTimeout;
        try {
            postHandshakeTimeout = Integer.parseInt(System.getProperty(PROP_POST_HANDSHAKE_TIMEOUT));
        } catch (NumberFormatException e) {
            postHandshakeTimeout = POST_HANDSHAKE_TIMEOUT;
        }

        SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, acceptUnverifiedCertificate);

        SSLSocketFactory factory = sslProvider.getSSLSocketFactory();

        // See the following links...
        // http://www.apache.org/dist/httpcomponents/httpcore/RELEASE_NOTES-4.1.x.txt
        // http://www-128.ibm.com/developerworks/forums/dw_thread.jsp?message=13695343&cat=10&thread=73546&treeDisplayType=threadmode1&forum=178#13695343
        // In any case, it would seem as though the bug has since been fixed in IBM's JRE, no need to work around it anymore...
        socket = (SSLSocket) factory.createSocket();

        // Make sure the InetAddress used to initialize the socket has a non-null hostname (empty string).
        // This prevents slow and unnecessary reverse DNS querying when the connection is opened.
        InetAddress withoutHost = InetAddress.getByName(this.agentAddress);
        InetAddress withHost = InetAddress.getByAddress("", withoutHost.getAddress());
        InetSocketAddress address = new InetSocketAddress(withHost, this.agentPort);

        socket.connect(address, readTimeout);

        // Set the socket timeout during the initial handshake to detect
        // connection issues with the agent.  
        socket.setSoTimeout(readTimeout);

        log.debug("Secure socket is connected to " + address + " - starting handshake.");

        socket.startHandshake();

        log.debug("SSL handshake complete");

        // [HHQ-3694] The timeout is set to a post handshake value.
        socket.setSoTimeout(postHandshakeTimeout);

    } catch (IOException exc) {
        IOException toThrow = new IOException(
                "Unable to connect to " + this.agentAddress + ":" + this.agentPort + ": " + exc.getMessage());
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    // Write our security settings
    try {
        DataOutputStream dOs;

        dOs = new DataOutputStream(socket.getOutputStream());
        dOs.writeUTF(this.authToken);
    } catch (IOException exc) {
        IOException toThrow = new IOException("Unable to write auth params to server");
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    return socket;
}

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

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {
    final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(socket, target, port, true);
    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {//w ww  .  j a  v a 2  s  . c  om
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    /*
        if (this.log.isDebugEnabled()) {
          this.log.debug("Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols()));
          this.log.debug("Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites()));
        }
    */

    prepareSocket(sslsock);

    // Android specific code to enable SNI
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Enabling SNI for " + target);
        }
        try {
            Method method = sslsock.getClass().getMethod("setHostname", String.class);
            method.invoke(sslsock, target);
        } catch (Exception ex) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "SNI configuration failed", ex);
            }
        }
    }
    // End of Android specific code

    //    this.log.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

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

/**
 * Initializes the HTTPs connection// ww w. ja v a2s .  c  o  m
 * 
 * @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);

            }

        });
    }

}