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.opensaml.security.httpclient.impl.SecurityEnhancedTLSSocketFactory.java

/**
 * Perform trust evaluation by extracting the server TLS {@link X509Credential} from the 
 * {@link SSLSession} and evaluating it via a {@link TrustEngine<Credential>} 
 * and {@link CriteriaSet} supplied by the caller via the {@link HttpContext}.
 * /* w  ww .  j a  va2  s.  c  om*/
 * @param socket the socket instance being processed
 * @param context the HttpClient context being processed
 * 
 * @throws IOException if the server TLS credential is untrusted, or if there is a fatal error
 *           attempting trust evaluation.
 */
protected void performTrustEval(@Nonnull final Socket socket, @Nonnull final HttpContext context)
        throws IOException {
    if (!(socket instanceof SSLSocket)) {
        log.debug("Socket was not an instance of SSLSocket, skipping trust eval");
        return;
    }
    SSLSocket sslSocket = (SSLSocket) socket;

    log.debug("Attempting to evaluate server TLS credential against supplied TrustEngine and CriteriaSet");

    @SuppressWarnings("unchecked")
    TrustEngine<? super X509Credential> trustEngine = (TrustEngine<? super X509Credential>) context
            .getAttribute(HttpClientSecurityConstants.CONTEXT_KEY_TRUST_ENGINE);
    if (trustEngine == null) {
        log.debug("No trust engine supplied by caller, skipping trust eval");
        return;
    } else {
        log.trace("Saw trust engine of type: {}", trustEngine.getClass().getName());
    }

    CriteriaSet criteriaSet = (CriteriaSet) context
            .getAttribute(HttpClientSecurityConstants.CONTEXT_KEY_CRITERIA_SET);
    if (criteriaSet == null) {
        log.debug("No criteria set supplied by caller, building new criteria set with signing criteria");
        criteriaSet = new CriteriaSet(new UsageCriterion(UsageType.SIGNING));
    } else {
        log.trace("Saw CriteriaSet: {}", criteriaSet);
    }

    X509Credential credential = extractCredential(sslSocket);

    try {
        if (trustEngine.validate(credential, criteriaSet)) {
            log.debug("Credential evaluated as trusted");
            context.setAttribute(HttpClientSecurityConstants.CONTEXT_KEY_SERVER_TLS_CREDENTIAL_TRUSTED,
                    Boolean.TRUE);
        } else {
            log.debug("Credential evaluated as untrusted");
            context.setAttribute(HttpClientSecurityConstants.CONTEXT_KEY_SERVER_TLS_CREDENTIAL_TRUSTED,
                    Boolean.FALSE);
            throw new SSLPeerUnverifiedException(
                    "Trust engine could not establish trust of server TLS credential");
        }
    } catch (SecurityException e) {
        log.error("Trust engine error evaluating credential", e);
        throw new IOException("Trust engine error evaluating credential", e);
    }

}

From source file:org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket a <code>SSLSocket</code> value
 * @exception SSLPeerUnverifiedException  If there are problems obtaining
 * the server certificates from the SSL session, or the server host name 
 * does not match with the "Common Name" in the server certificates 
 * SubjectDN./* ww w. j a v a 2 s . c o  m*/
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (!verifyHostname)
        return;

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress addr = InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    //get the servers DN in its string representation
    String dn = certs[0].getSubjectDN().getName();

    //might be useful to print out all certificates we receive from the
    //server, in case one has to debug a problem with the installed certs.
    if (LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

From source file:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket a <code>SSLSocket</code> value
 * @exception SSLPeerUnverifiedException  If there are problems obtaining
 * the server certificates from the SSL session, or the server host name 
 * does not match with the "Common Name" in the server certificates 
 * SubjectDN./*from   w  w w. ja  v  a2s. com*/
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (sslManager == null) {
        return;
    }
    ISSLErrorManager errorMng = sslManager.getSSLErrorManager();
    if (errorMng == null) {
        return;
    }

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    //get the servers DN in its string representation
    String dn = certs[0].getSubjectDN().getName();

    //might be useful to print out all certificates we receive from the
    //server, in case one has to debug a problem with the installed certs.
    if (LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            java.security.cert.X509Certificate servCert = (java.security.cert.X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(certs[0].getEncoded()));
            if (!errorMng.continueErrorPeer(hostname, servCert)) {
                throw new SSLPeerUnverifiedException(
                        "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
            }
        } catch (CertificateException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        } catch (CertificateEncodingException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        }
    }
}

From source file:org.opensaml.security.httpclient.impl.SecurityEnhancedTLSSocketFactory.java

/**
 * Extract the server TLS {@link X509Credential} from the supplied {@link SSLSocket}.
 * /*from  w  w w .  j a v a  2s  .c  o m*/
 * @param sslSocket the SSL socket instance to process
 * @return an X509Credential representing the server TLS entity certificate as well as the 
 *          supplied supporting intermediate certificate chain (if any)
 * @throws IOException if credential data can not be extracted from the socket
 */
@Nonnull
protected X509Credential extractCredential(@Nonnull final SSLSocket sslSocket) throws IOException {
    SSLSession session = sslSocket.getSession();
    final Certificate[] peerCertificates = session.getPeerCertificates();
    if (peerCertificates == null || peerCertificates.length < 1) {
        throw new SSLPeerUnverifiedException("SSLSession peer certificates array was null or empty");
    }

    ArrayList<X509Certificate> certChain = new ArrayList<>();
    for (Certificate cert : peerCertificates) {
        certChain.add((X509Certificate) cert);
    }

    final X509Certificate entityCert = certChain.get(0);

    BasicX509Credential credential = new BasicX509Credential(entityCert);
    credential.setEntityCertificateChain(certChain);

    return credential;
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.StrictSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 * //from   ww  w  .  j  a  v  a 2 s  .  co m
 * @param socket
 *            a <code>SSLSocket</code> value
 * @exception SSLPeerUnverifiedException
 *                If there are problems obtaining the server certificates from the SSL session, or the server host
 *                name does not match with the "Common Name" in the server certificates SubjectDN.
 * @exception UnknownHostException
 *                If we are not able to resolve the SSL sessions returned server host name.
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (!verifyHostname)
        return;

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        // InetAddress addr = InetAddress.getByName(hostname);
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    // get the servers DN in its string representation
    String dn = certs[0].getSubjectDN().getName();

    // might be useful to print out all certificates we receive from the
    // server, in case one has to debug a problem with the installed certs.
    if (LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    // get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

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  .j a  va2 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;
    }
}

From source file:com.cerema.cloud2.lib.common.network.AdvancedSslSocketFactory.java

/**
 * Verifies the identity of the server. 
 * /*  w ww  .  java 2s . co 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.app.mvc.http.ext.StrictSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket a <code>SSLSocket</code> value
 * @throws SSLPeerUnverifiedException If there are problems obtaining
 *                                    the server certificates from the SSL session, or the server host name
 *                                    does not match with the "Common Name" in the server certificates
 *                                    SubjectDN.
 * @throws UnknownHostException       If we are not able to resolve
 *                                    the SSL sessions returned server host name.
 *//* www.  ja  va  2  s  .  c o m*/
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (!verifyHostname)
        return;

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress addr = InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    //get the servers DN in its string representation
    String dn = certs[0].getSubjectDN().getName();

    //might be useful to print out all certificates we receive from the
    //server, in case one has to debug a problem with the installed certs.
    if (logger.isDebugEnabled()) {
        logger.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            logger.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/*from   w w w .  ja v  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 (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:gov.miamidade.open311.utilities.SslContextedSecureProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket/*from   w w w  . j  a v a  2 s . co m*/
 *            a <code>SSLSocket</code> value
 * @exception SSLPeerUnverifiedException
 *                If there are problems obtaining the server certificates
 *                from the SSL session, or the server host name does not
 *                match with the "Common Name" in the server certificates
 *                SubjectDN.
 * @exception UnknownHostException
 *                If we are not able to resolve the SSL sessions returned
 *                server host name.
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    synchronized (this) {
        if (!verifyHostname)
            return;
    }

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    X509Certificate[] certs = (X509Certificate[]) session.getPeerCertificates();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    X500Principal subjectDN = certs[0].getSubjectX500Principal();

    // get the common names from the first cert
    List<String> cns = getCNs(subjectDN);
    boolean foundHostName = false;
    for (String cn : cns) {
        if (hostname.equalsIgnoreCase(cn)) {
            foundHostName = true;
            break;
        }
    }
    if (!foundHostName) {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cns + "'");
    }
}