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:com.android.emailcommon.utility.SSLSocketFactory.java

@Override
public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose)
        throws IOException, UnknownHostException {
    SSLSocket sslSocket = (SSLSocket) socketfactory.createSocket(socket, host, port, autoClose);

    // Set Server Name Indication if it's available for this socket
    setSocketHostname(sslSocket, host);/*  ww w  .java2 s  .  c o m*/

    // Start handshake prior to hostname verification to ensure
    // handshake exceptions do not get silenced by hostname verification.
    sslSocket.startHandshake();

    hostnameVerifier.verify(host, sslSocket);
    // verifyHostName() didn't blowup - good!
    return sslSocket;
}

From source file:org.parosproxy.paros.network.SSLConnector.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
 *//*from  www.j  a v  a2  s.c  o m*/
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {
    InetAddress inetAddress = getCachedMisconfiguredHost(host, port);
    if (inetAddress != null) {
        return clientSSLSockFactory.createSocket(socket, inetAddress.getHostAddress(), port, autoClose);
    }

    try {
        SSLSocket socketSSL = (SSLSocket) clientSSLSockFactory.createSocket(socket, host, port, autoClose);
        socketSSL.startHandshake();

        return socketSSL;
    } catch (SSLException e) {
        if (e.getMessage().contains(CONTENTS_UNRECOGNIZED_NAME_EXCEPTION)) {
            cacheMisconfiguredHost(host, port, InetAddress.getByName(host));
        }
        // Throw the exception anyway because the socket might no longer be usable (e.g. closed). The connection will be 
        // retried (see HttpMethodDirector#executeWithRetry(HttpMethod) for more information on the retry policy).
        throw e;
    }
}

From source file:org.parosproxy.paros.network.SSLConnector.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.//  w w  w  .j  a  va2  s .  com
 * 
 * @param host
 *            the host name/IP
 * @param port
 *            the port on the host
 * @param localAddress
 *            the local host name/IP to bind the socket to
 * @param localPort
 *            the port on the local machine
 * @param params
 *            {@link HttpConnectionParams Http connection parameters}
 * 
 * @return Socket a new socket
 * 
 * @throws IOException
 *             if an I/O error occurs while creating the socket
 * @throws UnknownHostException
 *             if the IP address of the host cannot be determined
 * @throws    ConnectTimeoutException        
 */
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        InetAddress hostAddress = getCachedMisconfiguredHost(host, port);
        if (hostAddress != null) {
            return clientSSLSockFactory.createSocket(hostAddress, port, localAddress, localPort);
        }
        try {
            SSLSocket sslSocket = (SSLSocket) clientSSLSockFactory.createSocket(host, port, localAddress,
                    localPort);
            sslSocket.startHandshake();

            return sslSocket;
        } catch (SSLException e) {
            if (!e.getMessage().contains(CONTENTS_UNRECOGNIZED_NAME_EXCEPTION)) {
                throw e;
            }

            hostAddress = InetAddress.getByName(host);
            cacheMisconfiguredHost(host, port, hostAddress);
            return clientSSLSockFactory.createSocket(hostAddress, port, localAddress, localPort);
        }
    }
    Socket socket = clientSSLSockFactory.createSocket();
    SocketAddress localAddr = new InetSocketAddress(localAddress, localPort);
    socket.bind(localAddr);
    SocketAddress remoteAddr = new InetSocketAddress(host, port);
    socket.connect(remoteAddr, timeout);

    return socket;
}

From source file:org.parosproxy.paros.network.SSLConnector.java

/**
 * Create a SSLsocket using an existing connected socket. It can be used
 * such as a tunneled SSL proxy socket (eg when a CONNECT request is
 * received). This SSLSocket will start server side handshake immediately.
 * //from www  . j  a v a2  s  .  c  o m
 * @param targethost the host where you want to connect to 
 * @param socket
 * @return
 * @throws IOException
 */
public Socket createTunnelServerSocket(String targethost, Socket socket) throws IOException {
    // ZAP: added host name parameter
    SSLSocket s = (SSLSocket) getTunnelSSLSocketFactory(targethost).createSocket(socket,
            socket.getInetAddress().getHostAddress(), socket.getPort(), true);

    s.setUseClientMode(false);
    s.startHandshake();
    return s;
}

From source file:org.kuali.mobility.push.factory.iOSConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    SSLSocket socket = null;
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(certPath.getInputStream(), certPassword.toCharArray());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
    keyManagerFactory.init(keyStore, certPassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
    trustManagerFactory.init(keyStore);//from  ww w  .jav  a 2s .  com
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
    socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
    socket.startHandshake();
    return socket;
}

From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public static List<CertificateInfo> getCertificate(String host, int port) throws PhrescoException {
    List<CertificateInfo> certificates = new ArrayList<CertificateInfo>();
    CertificateInfo info;//  w w w  .j a  v a2  s .co m
    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            socket.startHandshake();
            socket.close();
        } catch (SSLException e) {

        }
        X509Certificate[] chain = tm.chain;
        for (int i = 0; i < chain.length; i++) {
            X509Certificate x509Certificate = chain[i];
            String subjectDN = x509Certificate.getSubjectDN().getName();
            String[] split = subjectDN.split(",");
            info = new CertificateInfo();
            info.setSubjectDN(subjectDN);
            info.setDisplayName(split[0]);
            info.setCertificate(x509Certificate);
            certificates.add(info);
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return certificates;
}

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

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {
    final SSLSocket sslsock = (SSLSocket) socketfactory.createSocket(socket, target, port, true);
    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    }/*from w  w  w .j  ava  2s .com*/
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }
    prepareSocket(sslsock);

    // Android specific code to enable SNI
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {

        if (socketfactory instanceof SSLCertificateSocketFactory) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "Enabling SNI for " + target);
            }
            ((SSLCertificateSocketFactory) socketfactory).setHostname(sslsock, target);
        }
    }
    // End of Android specific code

    sslsock.startHandshake();
    verifyHostname(sslsock, target, context);
    return sslsock;
}

From source file:android.core.SSLSocketTest.java

public void testSSLHandshakeHangTimeout() {

    Thread thread = new Thread() {
        @Override/*from w w w  .ja  v a 2s .c  o  m*/
        public void run() {
            try {
                SSLSocket socket = (SSLSocket) clientFactory.createSocket("www.heise.de", 80);
                socket.setSoTimeout(5000);
                socket.startHandshake();
                socket.close();
            } catch (Exception ex) {
                handshakeException = ex;
            }
        }
    };

    thread.start();

    try {
        thread.join(10000);
    } catch (InterruptedException ex) {
        // Ignore.
    }

    if (handshakeException == null) {
        fail("SSL handshake should have failed.");
    }
}

From source file:com.techcavern.pircbotz.InputParser.java

/**
 * Process any lines relevant to connect. Only called before bot is logged into the server
 * @param rawLine Raw, unprocessed line from the server
 * @param code /*from  w w  w .  j  av a  2 s  .  c om*/
 * @param target
 * @param parsedLine Processed line
 * @throws IrcException If the server rejects the bot (nick already in use or a 4** or 5** code
 * @throws IOException If an error occurs during upgrading to SSL
 */
public void processConnect(String rawLine, String code, String target, List<String> parsedLine)
        throws IrcException, IOException {
    if (CONNECT_CODES.contains(code)) {
        // We're connected to the server.
        bot.loggedIn(configuration.getName() + (nickSuffix == 0 ? "" : nickSuffix));
        log.debug("Logged onto server.");

        configuration.getListenerManager().dispatchEvent(new ConnectEvent<PircBotZ>(bot));

        //Handle automatic on connect stuff
        if (configuration.getNickservPassword() != null)
            bot.sendIRC().identify(configuration.getNickservPassword());
        ImmutableMap<String, String> autoConnectChannels = bot.reconnectChannels();
        if (autoConnectChannels == null)
            autoConnectChannels = configuration.getAutoJoinChannels();
        for (Map.Entry<String, String> channelEntry : autoConnectChannels.entrySet())
            bot.sendIRC().joinChannel(channelEntry.getKey(), channelEntry.getValue());
    } else if (code.equals("433")) {
        //EXAMPLE: * AnAlreadyUsedName :Nickname already in use
        //Nickname in use, rename
        String usedNick = parsedLine.get(1);
        boolean autoNickChange = configuration.isAutoNickChange();
        String autoNewNick = null;
        if (autoNickChange) {
            nickSuffix++;
            bot.sendIRC().changeNick(autoNewNick = configuration.getName() + nickSuffix);
        }
        configuration.getListenerManager()
                .dispatchEvent(new NickAlreadyInUseEvent<PircBotZ>(bot, usedNick, autoNewNick, autoNickChange));
    } else if (code.equals("439")) {
        //EXAMPLE: PircBotX: Target change too fast. Please wait 104 seconds
        // No action required.
        //TODO: Should we delay joining channels here or something?
        log.warn("Ignoring too fast error");
    } else if (configuration.isCapEnabled() && code.equals("421") && parsedLine.get(1).equals("CAP")) {
        //EXAMPLE: 421 you CAP :Unknown command
        log.warn("Ignoring unknown command error, server does not support CAP negotiation");
    } else if (configuration.isCapEnabled() && code.equals("451") && target.equals("CAP")) {
        //EXAMPLE: 451 CAP :You have not registered
        //Ignore, this is from servers that don't support CAP
        log.warn("Ignoring not registered error, server does not support CAP negotiation");
    } else if (code.startsWith("5") || code.startsWith("4"))
        throw new IrcException(IrcException.Reason.CannotLogin, "Received error: " + rawLine);
    else if (code.equals("670")) {
        //Server is saying that we can upgrade to TLS
        SSLSocketFactory sslSocketFactory = ((SSLSocketFactory) SSLSocketFactory.getDefault());
        for (CapHandler curCapHandler : configuration.getCapHandlers())
            if (curCapHandler instanceof TLSCapHandler)
                sslSocketFactory = ((TLSCapHandler) curCapHandler).getSslSocketFactory();
        SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(bot.getSocket(),
                bot.getLocalAddress().getHostAddress(), bot.getSocket().getPort(), true);
        sslSocket.startHandshake();
        bot.changeSocket(sslSocket);
        //Notify CAP Handlers
        for (CapHandler curCapHandler : configuration.getCapHandlers())
            curCapHandler.handleUnknown(bot, rawLine);
    } else if (code.equals("CAP")) {
        //Handle CAP Code; remove extra from params
        String capCommand = parsedLine.get(1);
        ImmutableList<String> capParams = ImmutableList.copyOf(StringUtils.split(parsedLine.get(2)));
        if (capCommand.equals("LS"))
            for (CapHandler curCapHandler : configuration.getCapHandlers()) {
                log.debug("Executing cap handler " + curCapHandler);
                if (curCapHandler.handleLS(bot, capParams)) {
                    log.debug("Cap handler " + curCapHandler + " finished");
                    capHandlersFinished.add(curCapHandler);
                }
            }
        else if (capCommand.equals("ACK")) {
            //Server is enabling a capability, store that
            bot.getEnabledCapabilities().addAll(capParams);

            for (CapHandler curCapHandler : configuration.getCapHandlers())
                if (curCapHandler.handleACK(bot, capParams)) {
                    log.trace("Removing cap handler " + curCapHandler);
                    capHandlersFinished.add(curCapHandler);
                }
        } else if (capCommand.equals("NAK")) {
            for (CapHandler curCapHandler : configuration.getCapHandlers())
                if (curCapHandler.handleNAK(bot, capParams))
                    capHandlersFinished.add(curCapHandler);
        } else
            //Maybe the CapHandlers know how to use it
            for (CapHandler curCapHandler : configuration.getCapHandlers())
                if (curCapHandler.handleUnknown(bot, rawLine))
                    capHandlersFinished.add(curCapHandler);
    } else
        //Pass to CapHandlers, could be important
        for (CapHandler curCapHandler : configuration.getCapHandlers())
            if (curCapHandler.handleUnknown(bot, rawLine))
                capHandlersFinished.add(curCapHandler);

    //Send CAP END if all CapHandlers are finished
    if (configuration.isCapEnabled() && !capEndSent
            && capHandlersFinished.containsAll(configuration.getCapHandlers())) {
        capEndSent = true;
        bot.sendCAP().end();
        bot.enabledCapabilities = Collections.unmodifiableList(bot.enabledCapabilities);
    }
}

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.  ja  v  a 2 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;
    }
}