Example usage for javax.net.ssl SSLHandshakeException SSLHandshakeException

List of usage examples for javax.net.ssl SSLHandshakeException SSLHandshakeException

Introduction

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

Prototype

public SSLHandshakeException(String reason) 

Source Link

Document

Constructs an exception reporting an error found by an SSL subsystem during handshaking.

Usage

From source file:org.lizardirc.beancounter.security.VerifyingSslSocketFactory.java

private void verifyHostname(String s) throws SSLException {
    if (!s.equals(hostname)) {
        System.err.println("Rejecting; bad host " + s + " where we expected " + hostname);
        throw new SSLHandshakeException("Attempting to connect to hostname other than that specified");
    }//from  ww  w .j  a  v  a2s  .c  o  m
}

From source file:eu.impact_project.resultsrepository.DavHandler.java

/**
 * Saves files into folders which are constructed.
 * // w  w w.  j  av a2 s  .c o  m
 * @param urlParts
 *            Special information that is coded in the URL of each result
 *            file.
 * @param urls
 *            Source URLs.
 */
public void saveFiles(UrlParts urlParts, ToolResults urls) throws HttpException, IOException {
    String serviceDir = urlParts.service;
    String port = urlParts.port;
    String extension = urlParts.extension;
    String evaluationId = urlParts.evalId;

    String baseUrl = getFolderHierarchyUrl();
    String serviceUrl = createFolder(baseUrl, serviceDir);
    serviceUrl = createFolder(serviceUrl, evaluationId);
    // serviceUrl = createFolder(serviceUrl, "testing123");
    String portUrl = createFolder(serviceUrl, port);

    int i = 1;
    for (String sourceUrl : urls.getFields()) {
        try {
            String targetFileName = format(i) + "." + extension;
            copyFile(sourceUrl, portUrl + separator + targetFileName);
            i++;
        } catch (SSLHandshakeException e) {
            throw new SSLHandshakeException("URL: " + sourceUrl);
        }
    }
}

From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/* ww  w  .jav a 2s .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.owncloud.android.network.AdvancedSslSocketFactory.java

/**
 * Verifies the identity of the server. 
 * /*  w  w w. jav a2  s. c o  m*/
 * The server certificate is verified first.
 * 
 * Then, the host name is compared with the content of the server certificate using the current host name verifier, if any.
 * @param socket
 */
private void verifyPeerIdentity(String host, int port, Socket socket) throws IOException {
    try {
        CertificateCombinedException failInHandshake = null;
        /// 1. VERIFY THE SERVER CERTIFICATE through the registered TrustManager (that should be an instance of AdvancedX509TrustManager) 
        try {
            SSLSocket sock = (SSLSocket) socket; // a new SSLSession instance is created as a "side effect" 
            sock.startHandshake();

        } catch (RuntimeException e) {

            if (e instanceof CertificateCombinedException) {
                failInHandshake = (CertificateCombinedException) e;
            } else {
                Throwable cause = e.getCause();
                Throwable previousCause = null;
                while (cause != null && cause != previousCause
                        && !(cause instanceof CertificateCombinedException)) {
                    previousCause = cause;
                    cause = cause.getCause();
                }
                if (cause != null && cause instanceof CertificateCombinedException) {
                    failInHandshake = (CertificateCombinedException) cause;
                }
            }
            if (failInHandshake == null) {
                throw e;
            }
            failInHandshake.setHostInUrl(host);

        }

        /// 2. VERIFY HOSTNAME
        SSLSession newSession = null;
        boolean verifiedHostname = true;
        if (mHostnameVerifier != null) {
            if (failInHandshake != null) {
                /// 2.1 : a new SSLSession instance was NOT created in the handshake
                X509Certificate serverCert = failInHandshake.getServerCertificate();
                try {
                    mHostnameVerifier.verify(host, serverCert);
                } catch (SSLException e) {
                    verifiedHostname = false;
                }

            } else {
                /// 2.2 : a new SSLSession instance was created in the handshake
                newSession = ((SSLSocket) socket).getSession();
                if (!mTrustManager.isKnownServer((X509Certificate) (newSession.getPeerCertificates()[0]))) {
                    verifiedHostname = mHostnameVerifier.verify(host, newSession);
                }
            }
        }

        /// 3. Combine the exceptions to throw, if any
        if (!verifiedHostname) {
            SSLPeerUnverifiedException pue = new SSLPeerUnverifiedException(
                    "Names in the server certificate do not match to " + host + " in the URL");
            if (failInHandshake == null) {
                failInHandshake = new CertificateCombinedException(
                        (X509Certificate) newSession.getPeerCertificates()[0]);
                failInHandshake.setHostInUrl(host);
            }
            failInHandshake.setSslPeerUnverifiedException(pue);
            pue.initCause(failInHandshake);
            throw pue;

        } else if (failInHandshake != null) {
            SSLHandshakeException hse = new SSLHandshakeException("Server certificate could not be verified");
            hse.initCause(failInHandshake);
            throw hse;
        }

    } catch (IOException io) {
        try {
            socket.close();
        } catch (Exception x) {
            // NOTHING - irrelevant exception for the caller 
        }
        throw io;
    }
}

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  va  2 s. com*/
        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:net.i2p.util.I2PSSLSocketFactory.java

/**
 *  Validate the hostname/*from   w  w w . j a va  2  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:com.cerema.cloud2.lib.common.network.AdvancedSslSocketFactory.java

/**
 * Verifies the identity of the server. 
 * //from  w  ww  . j a  v a  2  s. c  o m
 * The server certificate is verified first.
 * 
 * Then, the host name is compared with the content of the server certificate using the current host name verifier,
 *  if any.
 * @param socket
 */
private void verifyPeerIdentity(String host, int port, Socket socket) throws IOException {
    try {
        CertificateCombinedException failInHandshake = null;
        /// 1. VERIFY THE SERVER CERTIFICATE through the registered TrustManager 
        ///   (that should be an instance of AdvancedX509TrustManager) 
        try {
            SSLSocket sock = (SSLSocket) socket; // a new SSLSession instance is created as a "side effect" 
            sock.startHandshake();

        } catch (RuntimeException e) {

            if (e instanceof CertificateCombinedException) {
                failInHandshake = (CertificateCombinedException) e;
            } else {
                Throwable cause = e.getCause();
                Throwable previousCause = null;
                while (cause != null && cause != previousCause
                        && !(cause instanceof CertificateCombinedException)) {
                    previousCause = cause;
                    cause = cause.getCause();
                }
                if (cause != null && cause instanceof CertificateCombinedException) {
                    failInHandshake = (CertificateCombinedException) cause;
                }
            }
            if (failInHandshake == null) {
                throw e;
            }
            failInHandshake.setHostInUrl(host);

        }

        /// 2. VERIFY HOSTNAME
        SSLSession newSession = null;
        boolean verifiedHostname = true;
        if (mHostnameVerifier != null) {
            if (failInHandshake != null) {
                /// 2.1 : a new SSLSession instance was NOT created in the handshake
                X509Certificate serverCert = failInHandshake.getServerCertificate();
                try {
                    mHostnameVerifier.verify(host, serverCert);
                } catch (SSLException e) {
                    verifiedHostname = false;
                }

            } else {
                /// 2.2 : a new SSLSession instance was created in the handshake
                newSession = ((SSLSocket) socket).getSession();
                if (!mTrustManager.isKnownServer((X509Certificate) (newSession.getPeerCertificates()[0]))) {
                    verifiedHostname = mHostnameVerifier.verify(host, newSession);
                }
            }
        }

        /// 3. Combine the exceptions to throw, if any
        if (!verifiedHostname) {
            SSLPeerUnverifiedException pue = new SSLPeerUnverifiedException(
                    "Names in the server certificate do not match to " + host + " in the URL");
            if (failInHandshake == null) {
                failInHandshake = new CertificateCombinedException(
                        (X509Certificate) newSession.getPeerCertificates()[0]);
                failInHandshake.setHostInUrl(host);
            }
            failInHandshake.setSslPeerUnverifiedException(pue);
            pue.initCause(failInHandshake);
            throw pue;

        } else if (failInHandshake != null) {
            SSLHandshakeException hse = new SSLHandshakeException("Server certificate could not be verified");
            hse.initCause(failInHandshake);
            throw hse;
        }

    } catch (IOException io) {
        try {
            socket.close();
        } catch (Exception x) {
            // NOTHING - irrelevant exception for the caller 
        }
        throw io;
    }
}

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);
    }/*from  w  ww  .j av  a2s  .  c  om*/

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

        socket.close();
    }

    throw new SSLHandshakeException(errorMessage);
}

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  w  w .  j a  v  a2  s  .  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:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from   w ww . j  ava2 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;
    }
}