Search in sources :

Example 76 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project geode by apache.

the class SocketCreator method configureClientSSLSocket.

/**
   * When a socket is accepted from a server socket, it should be passed to this method for SSL
   * configuration.
   */
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;
        }
    }
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLSession(javax.net.ssl.SSLSession) SSLException(javax.net.ssl.SSLException) X509Certificate(java.security.cert.X509Certificate) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 77 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project jdk8u_jdk by JetBrains.

the class StartTlsResponseImpl method verify.

/*
     * Verifies that the hostname in the server's certificate matches the
     * hostname of the server.
     * The server's first certificate is examined. If it has a subjectAltName
     * that contains a dNSName then that is used as the server's hostname.
     * The server's hostname may contain a wildcard for its left-most name part.
     * Otherwise, if the certificate has no subjectAltName then the value of
     * the common name attribute of the subject name is used.
     *
     * @param hostname The hostname of the server.
     * @param session the SSLSession used on the connection to host.
     * @return true if the hostname is verified, false otherwise.
     */
private boolean verify(String hostname, SSLSession session) throws SSLPeerUnverifiedException {
    java.security.cert.Certificate[] certs = null;
    // if IPv6 strip off the "[]"
    if (hostname != null && hostname.startsWith("[") && hostname.endsWith("]")) {
        hostname = hostname.substring(1, hostname.length() - 1);
    }
    try {
        HostnameChecker checker = HostnameChecker.getInstance(HostnameChecker.TYPE_LDAP);
        // Use ciphersuite to determine whether Kerberos is active.
        if (session.getCipherSuite().startsWith("TLS_KRB5")) {
            Principal principal = getPeerPrincipal(session);
            if (!HostnameChecker.match(hostname, principal)) {
                throw new SSLPeerUnverifiedException("hostname of the kerberos principal:" + principal + " does not match the hostname:" + hostname);
            }
        } else {
            // X.509
            // get the subject's certificate
            certs = session.getPeerCertificates();
            X509Certificate peerCert;
            if (certs[0] instanceof java.security.cert.X509Certificate) {
                peerCert = (java.security.cert.X509Certificate) certs[0];
            } else {
                throw new SSLPeerUnverifiedException("Received a non X509Certificate from the server");
            }
            checker.match(hostname, peerCert);
        }
        // no exception means verification passed
        return true;
    } catch (SSLPeerUnverifiedException e) {
        /*
             * The application may enable an anonymous SSL cipher suite, and
             * hostname verification is not done for anonymous ciphers
             */
        String cipher = session.getCipherSuite();
        if (cipher != null && (cipher.indexOf("_anon_") != -1)) {
            return true;
        }
        throw e;
    } catch (CertificateException e) {
        /*
             * Pass up the cause of the failure
             */
        throw (SSLPeerUnverifiedException) new SSLPeerUnverifiedException("hostname of the server '" + hostname + "' does not match the hostname in the " + "server's certificate.").initCause(e);
    }
}
Also used : HostnameChecker(sun.security.util.HostnameChecker) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) CertificateException(java.security.cert.CertificateException) Principal(java.security.Principal) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate)

Example 78 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project jdk8u_jdk by JetBrains.

the class StartTlsResponseImpl method negotiate.

/**
     * Negotiates a TLS session using an SSL socket factory.
     * <p>
     * Creates an SSL socket using the supplied SSL socket factory and
     * attaches it to the existing connection. Performs the TLS handshake
     * and returns the negotiated session information.
     * <p>
     * If cipher suites have been set via <tt>setEnabledCipherSuites</tt>
     * then they are enabled before the TLS handshake begins.
     * <p>
     * Hostname verification is performed after the TLS handshake completes.
     * The default check performs a case insensitive match of the server's
     * hostname against that in the server's certificate. The server's
     * hostname is extracted from the subjectAltName in the server's
     * certificate (if present). Otherwise the value of the common name
     * attribute of the subject name is used. If a callback has
     * been set via <tt>setHostnameVerifier</tt> then that verifier is used if
     * the default check fails.
     * <p>
     * If an error occurs then the SSL socket is closed and an IOException
     * is thrown. The underlying connection remains intact.
     *
     * @param factory The possibly null SSL socket factory to use.
     * If null, the default SSL socket factory is used.
     * @return The negotiated SSL session
     * @throw IOException If an IO error was encountered while establishing
     * the TLS session.
     * @see #setEnabledCipherSuites
     * @see #setHostnameVerifier
     */
public SSLSession negotiate(SSLSocketFactory factory) throws IOException {
    if (isClosed && sslSocket != null) {
        throw new IOException("TLS connection is closed.");
    }
    if (factory == null) {
        factory = getDefaultFactory();
    }
    if (debug) {
        System.out.println("StartTLS: About to start handshake");
    }
    SSLSession sslSession = startHandshake(factory).getSession();
    if (debug) {
        System.out.println("StartTLS: Completed handshake");
    }
    SSLPeerUnverifiedException verifExcep = null;
    try {
        if (verify(hostname, sslSession)) {
            isClosed = false;
            return sslSession;
        }
    } catch (SSLPeerUnverifiedException e) {
        // Save to return the cause
        verifExcep = e;
    }
    if ((verifier != null) && verifier.verify(hostname, sslSession)) {
        isClosed = false;
        return sslSession;
    }
    // Verification failed
    close();
    sslSession.invalidate();
    if (verifExcep == null) {
        verifExcep = new SSLPeerUnverifiedException("hostname of the server '" + hostname + "' does not match the hostname in the " + "server's certificate.");
    }
    throw verifExcep;
}
Also used : SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLSession(javax.net.ssl.SSLSession) IOException(java.io.IOException)

Example 79 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project android_frameworks_base by ResurrectionRemix.

the class SSLCertificateSocketFactory method verifyHostname.

/**
     * Verify the hostname of the certificate used by the other end of a
     * connected socket.  You MUST call this if you did not supply a hostname
     * to {@link #createSocket()}.  It is harmless to call this method
     * redundantly if the hostname has already been verified.
     *
     * <p>Wildcard certificates are allowed to verify any matching hostname,
     * so "foo.bar.example.com" is verified if the peer has a certificate
     * for "*.example.com".
     *
     * @param socket An SSL socket which has been connected to a server
     * @param hostname The expected hostname of the remote server
     * @throws IOException if something goes wrong handshaking with the server
     * @throws SSLPeerUnverifiedException if the server cannot prove its identity
     *
     * @hide
     */
public static void verifyHostname(Socket socket, String hostname) throws IOException {
    if (!(socket instanceof SSLSocket)) {
        throw new IllegalArgumentException("Attempt to verify non-SSL socket");
    }
    if (!isSslCheckRelaxed()) {
        // The code at the start of OpenSSLSocketImpl.startHandshake()
        // ensures that the call is idempotent, so we can safely call it.
        SSLSocket ssl = (SSLSocket) socket;
        ssl.startHandshake();
        SSLSession session = ssl.getSession();
        if (session == null) {
            throw new SSLException("Cannot verify SSL socket without session");
        }
        if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)) {
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + hostname);
        }
    }
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLSession(javax.net.ssl.SSLSession) SSLException(javax.net.ssl.SSLException)

Example 80 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project android_frameworks_base by crdroidandroid.

the class SSLCertificateSocketFactory method verifyHostname.

/**
     * Verify the hostname of the certificate used by the other end of a
     * connected socket.  You MUST call this if you did not supply a hostname
     * to {@link #createSocket()}.  It is harmless to call this method
     * redundantly if the hostname has already been verified.
     *
     * <p>Wildcard certificates are allowed to verify any matching hostname,
     * so "foo.bar.example.com" is verified if the peer has a certificate
     * for "*.example.com".
     *
     * @param socket An SSL socket which has been connected to a server
     * @param hostname The expected hostname of the remote server
     * @throws IOException if something goes wrong handshaking with the server
     * @throws SSLPeerUnverifiedException if the server cannot prove its identity
     *
     * @hide
     */
public static void verifyHostname(Socket socket, String hostname) throws IOException {
    if (!(socket instanceof SSLSocket)) {
        throw new IllegalArgumentException("Attempt to verify non-SSL socket");
    }
    if (!isSslCheckRelaxed()) {
        // The code at the start of OpenSSLSocketImpl.startHandshake()
        // ensures that the call is idempotent, so we can safely call it.
        SSLSocket ssl = (SSLSocket) socket;
        ssl.startHandshake();
        SSLSession session = ssl.getSession();
        if (session == null) {
            throw new SSLException("Cannot verify SSL socket without session");
        }
        if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)) {
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + hostname);
        }
    }
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLSession(javax.net.ssl.SSLSession) SSLException(javax.net.ssl.SSLException)

Aggregations

SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)112 X509Certificate (java.security.cert.X509Certificate)40 Certificate (java.security.cert.Certificate)39 SSLSession (javax.net.ssl.SSLSession)27 SSLSocket (javax.net.ssl.SSLSocket)23 IOException (java.io.IOException)21 SSLException (javax.net.ssl.SSLException)15 CertificateException (java.security.cert.CertificateException)14 X509Certificate (javax.security.cert.X509Certificate)12 Principal (java.security.Principal)11 Test (org.junit.jupiter.api.Test)11 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)10 InetSocketAddress (java.net.InetSocketAddress)8 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)8 Test (org.junit.Test)8 UnknownHostException (java.net.UnknownHostException)7 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)6 SSLProtocolException (javax.net.ssl.SSLProtocolException)6 MockResponse (mockwebserver3.MockResponse)6