Example usage for javax.net.ssl SSLPeerUnverifiedException SSLPeerUnverifiedException

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

Introduction

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

Prototype

public SSLPeerUnverifiedException(String reason) 

Source Link

Document

Constructs an exception reporting that the SSL peer's identity has not been verified.

Usage

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

private void verify(SSLSocket socket) throws SSLException {
    SSLSession session = socket.getSession();
    Certificate cert = session.getPeerCertificates()[0];
    byte[] encoded;
    try {//  w  w w . j  a v  a  2 s .  com
        encoded = cert.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new SSLProtocolException("Invalid certificate encoding");
    }
    boolean match = Stream.<Function<byte[], String>>of(DigestUtils::md5Hex, DigestUtils::sha1Hex,
            DigestUtils::sha256Hex, DigestUtils::sha512Hex).map(f -> f.apply(encoded))
            .anyMatch(fingerprints::contains);

    if (!match) {
        System.err.println("Rejecting; fingerprint not matched");
        throw new SSLPeerUnverifiedException("Failed to verify: certificate fingerprint mismatch");
    }
}

From source file:at.bitfire.davdroid.mirakel.webdav.TlsSniSocketFactory.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void connectWithSNI(SSLSocket ssl, String host) throws SSLPeerUnverifiedException {
    // - set SNI host name
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Log.d(TAG, "Using documented SNI with host name " + host);
        sslSocketFactory.setHostname(ssl, host);
    } else {//from w w  w .j av  a  2  s.  co  m
        Log.d(TAG, "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) {
            Log.w(TAG, "SNI not useable", e);
        }
    }

    // verify hostname and certificate
    SSLSession session = ssl.getSession();
    if (!hostnameVerifier.verify(host, session))
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);

    Log.d(TAG, "Established " + session.getProtocol() + " connection with " + session.getPeerHost() + " using "
            + session.getCipherSuite());
}

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();/*ww  w. j a v a 2  s  .  c  om*/
    }

    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.dcache.ftp.client.extended.GridFTPControlChannel.java

/**
 * Performs authentication with specified user credentials and
 * a specific username (assuming the user dn maps to the passed username).
 *
 * @throws IOException     on i/o error//from   w  ww.java 2  s .c  om
 * @throws ServerException on server refusal or faulty server behavior
 */
private DssContext authenticate(DssContextFactory factory, String expectedHostName)
        throws IOException, ServerException {
    DssContext context;
    try {
        try {
            Reply reply = inner.exchange(new Command("AUTH", "GSSAPI"));
            if (!Reply.isPositiveIntermediate(reply)) {
                throw ServerException.embedUnexpectedReplyCodeException(new UnexpectedReplyCodeException(reply),
                        "Server refused GSSAPI authentication.");
            }
        } catch (FTPReplyParseException rpe) {
            throw ServerException.embedFTPReplyParseException(rpe, "Received faulty reply to AUTH GSSAPI.");
        }

        context = factory.create(inner.getRemoteAddress(), inner.getLocalAddress());

        Reply reply;
        byte[] inToken = new byte[0];
        do {
            byte[] outToken = context.init(inToken);
            reply = inner.exchange(new Command("ADAT",
                    BaseEncoding.base64().encode(outToken != null ? outToken : new byte[0])));
            if (reply.getMessage().startsWith("ADAT=")) {
                inToken = BaseEncoding.base64().decode(reply.getMessage().substring(5));
            } else {
                inToken = new byte[0];
            }
        } while (Reply.isPositiveIntermediate(reply) && !context.isEstablished());

        if (!Reply.isPositiveCompletion(reply)) {
            throw ServerException.embedUnexpectedReplyCodeException(new UnexpectedReplyCodeException(reply),
                    "Server failed GSI handshake.");
        }

        if (inToken.length > 0 || !context.isEstablished()) {
            byte[] outToken = context.init(inToken);
            if (outToken != null || !context.isEstablished()) {
                throw new ServerException(ServerException.WRONG_PROTOCOL,
                        "Unexpected GSI handshake completion.");
            }
        }

        SSLSession session = ((SslEngineDssContext) context).getSSLSession();
        if (!this.hostnameVerifier.verify(expectedHostName, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + expectedHostName + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
    } catch (FTPReplyParseException e) {
        throw ServerException.embedFTPReplyParseException(e, "Received faulty reply to ADAT.");
    }
    return context;
}

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   ww w .  j a  v 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:org.hyperic.util.security.DefaultSSLProviderImpl.java

private X509HostnameVerifier getHostnameVerifier() {
    return new X509HostnameVerifier() {
        private AllowAllHostnameVerifier internalVerifier = new AllowAllHostnameVerifier();

        public boolean verify(String host, SSLSession session) {
            return internalVerifier.verify(host, session);
        }/*w w  w .ja  v  a  2 s.  c  om*/

        public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
            internalVerifier.verify(host, cns, subjectAlts);
        }

        public void verify(String host, X509Certificate cert) throws SSLException {
            internalVerifier.verify(host, cert);
        }

        public void verify(String host, SSLSocket ssl) throws IOException {
            try {
                internalVerifier.verify(host, ssl);
            } catch (SSLPeerUnverifiedException e) {
                SSLPeerUnverifiedException sslPeerUnverifiedException = new SSLPeerUnverifiedException(
                        "The authenticity of host '" + host + "' can't be established: " + e);
                sslPeerUnverifiedException.initCause(e);
                throw sslPeerUnverifiedException;
            }
        }
    };
}

From source file:org.hyperic.util.security.DatabaseSSLProviderImpl.java

private X509HostnameVerifier getHostnameVerifier() {
    return new X509HostnameVerifier() {
        private AllowAllHostnameVerifier internalVerifier = new AllowAllHostnameVerifier();

        public boolean verify(String host, SSLSession session) {
            return internalVerifier.verify(host, session);
        }/*from   w  w  w .j  a  v a 2  s .c  om*/

        public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
            internalVerifier.verify(host, cns, subjectAlts);
        }

        public void verify(String host, X509Certificate cert) throws SSLException {
            internalVerifier.verify(host, cert);
        }

        public void verify(String host, SSLSocket ssl) throws IOException {
            try {
                internalVerifier.verify(host, ssl);
            } catch (SSLPeerUnverifiedException e) {
                throw new SSLPeerUnverifiedException(
                        "The authenticity of host '" + host + "' can't be established.");
            }
        }
    };
}

From source file:android.net.SSLCertificateSocketFactory.java

/**
 * 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"./*from   ww w .j  av  a 2s  .c  o  m*/
 *
 * @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);
        }
    }
}

From source file:org.apache.http.HC4.nio.conn.ssl.SSLIOSessionStrategy.java

protected void verifySession(final HttpHost host, final IOSession iosession, final SSLSession sslsession)
        throws SSLException {
    if (!this.hostnameVerifier.verify(host.getHostName(), sslsession)) {
        final Certificate[] certs = sslsession.getPeerCertificates();
        final X509Certificate x509 = (X509Certificate) certs[0];
        final X500Principal x500Principal = x509.getSubjectX500Principal();
        throw new SSLPeerUnverifiedException("Host name '" + host.getHostName() + "' does not match "
                + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
    }//from ww  w  .  ja v a2s  . co m
}

From source file:com.owncloud.android.network.AdvancedSslSocketFactory.java

/**
 * Verifies the identity of the server. 
 * /*from   ww  w  .  j av a  2s.  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;
    }
}