Example usage for javax.net.ssl SSLException SSLException

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

Introduction

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

Prototype

public SSLException(Throwable cause) 

Source Link

Document

Creates a SSLException with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.DefaultHostnameVerifier.java

static void matchDNSName(final String host, final List<String> subjectAlts,
        final PublicSuffixMatcher publicSuffixMatcher) throws SSLException {
    final String normalizedHost = host.toLowerCase(Locale.ROOT);
    for (int i = 0; i < subjectAlts.size(); i++) {
        final String subjectAlt = subjectAlts.get(i);
        final String normalizedSubjectAlt = subjectAlt.toLowerCase(Locale.ROOT);
        if (matchIdentityStrict(normalizedHost, normalizedSubjectAlt, publicSuffixMatcher)) {
            return;
        }//from   www .ja va2s.c o m
    }
    throw new SSLException("Certificate for <" + host + "> doesn't match any "
            + "of the subject alternative names: " + subjectAlts);
}

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.DefaultHostnameVerifier.java

static void matchCN(final String host, final String cn, final PublicSuffixMatcher publicSuffixMatcher)
        throws SSLException {
    if (!matchIdentityStrict(host, cn, publicSuffixMatcher)) {
        throw new SSLException("Certificate for <" + host + "> doesn't match "
                + "common name of the certificate subject: " + cn);
    }/*from  ww  w.  j a  va2 s . c  om*/
}

From source file:org.eclipse.mylyn.commons.repositories.http.tests.CommonHttpClientTest.java

@Test(expected = SSLException.class)
public void testCertificateAuthenticationNoCertificate() throws Exception {
    if (!CommonTestUtil.isHttpsProxyBroken()) {
        System.err.println(//from w  w w  . j  av a2s.  c o  m
                "Skipped CommonHttpClientTest.testCertificateAuthenticationNoCertificate() due to broken https proxy");
        throw new SSLException(""); // skip test 
    }

    RepositoryLocation location = new RepositoryLocation();
    location.setUrl("https://mylyn.org/secure/index.txt");

    HttpGet request = new HttpGet(location.getUrl());
    CommonHttpClient client = new CommonHttpClient(location);
    // work-around for bug 369805
    Scheme oldScheme = setUpDefaultFactory(client);
    try {
        HttpResponse response = client.execute(request, null);
        HttpUtil.release(request, response, null);
    } finally {
        tearDownDefaultFactory(client, oldScheme);
    }
}

From source file:com.epam.reportportal.apache.http.conn.ssl.AbstractVerifier.java

public final void verify(final String host, final String[] cns, final String[] subjectAlts,
        final boolean strictWithSubDomains) throws SSLException {

    // Build the list of names we're going to check.  Our DEFAULT and
    // STRICT implementations of the HostnameVerifier only use the
    // first CN provided.  All other CNs are ignored.
    // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
    final LinkedList<String> names = new LinkedList<String>();
    if (cns != null && cns.length > 0 && cns[0] != null) {
        names.add(cns[0]);/*from  w  w  w .  jav a2 s.c o m*/
    }
    if (subjectAlts != null) {
        for (final String subjectAlt : subjectAlts) {
            if (subjectAlt != null) {
                names.add(subjectAlt);
            }
        }
    }

    if (names.isEmpty()) {
        final String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt";
        throw new SSLException(msg);
    }

    // StringBuilder for building the error message.
    final StringBuilder buf = new StringBuilder();

    // We're can be case-insensitive when comparing the host we used to
    // establish the socket to the hostname in the certificate.
    final String hostName = normaliseIPv6Address(host.trim().toLowerCase(Locale.US));
    boolean match = false;
    for (final Iterator<String> it = names.iterator(); it.hasNext();) {
        // Don't trim the CN, though!
        String cn = it.next();
        cn = cn.toLowerCase(Locale.US);
        // Store CN in StringBuilder in case we need to report an error.
        buf.append(" <");
        buf.append(cn);
        buf.append('>');
        if (it.hasNext()) {
            buf.append(" OR");
        }

        // The CN better have at least two dots if it wants wildcard
        // action.  It also can't be [*.co.uk] or [*.co.jp] or
        // [*.org.uk], etc...
        final String parts[] = cn.split("\\.");
        final boolean doWildcard = parts.length >= 3 && parts[0].endsWith("*") && validCountryWildcard(cn)
                && !isIPAddress(host);

        if (doWildcard) {
            final String firstpart = parts[0];
            if (firstpart.length() > 1) { // e.g. server*
                final String prefix = firstpart.substring(0, firstpart.length() - 1); // e.g. server
                final String suffix = cn.substring(firstpart.length()); // skip wildcard part from cn
                final String hostSuffix = hostName.substring(prefix.length()); // skip wildcard part from host
                match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix);
            } else {
                match = hostName.endsWith(cn.substring(1));
            }
            if (match && strictWithSubDomains) {
                // If we're in strict mode, then [*.foo.com] is not
                // allowed to match [a.b.foo.com]
                match = countDots(hostName) == countDots(cn);
            }
        } else {
            match = hostName.equals(normaliseIPv6Address(cn));
        }
        if (match) {
            break;
        }
    }
    if (!match) {
        throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf);
    }
}

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  a  va 2s.  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);
        }
    }
}

From source file:org.apache.axis2.transport.nhttp.HttpCoreNIOSSLSender.java

protected SSLIOSessionHandler getSSLIOSessionHandler(TransportOutDescription transportOut) throws AxisFault {

    final Parameter hostnameVerifier = transportOut.getParameter("HostnameVerifier");

    return new SSLIOSessionHandler() {

        public void initalize(SSLEngine sslengine, HttpParams params) {
        }/*w w  w . jav  a 2s.  c o m*/

        public void verify(SocketAddress remoteAddress, SSLSession session) throws SSLException {

            String address = null;
            if (remoteAddress instanceof InetSocketAddress) {
                address = ((InetSocketAddress) remoteAddress).getHostName();
            } else {
                address = remoteAddress.toString();
            }

            boolean valid = false;
            if (hostnameVerifier != null) {
                if ("Strict".equals(hostnameVerifier.getValue())) {
                    valid = HostnameVerifier.STRICT.verify(address, session);
                } else if ("AllowAll".equals(hostnameVerifier.getValue())) {
                    valid = HostnameVerifier.ALLOW_ALL.verify(address, session);
                } else if ("DefaultAndLocalhost".equals(hostnameVerifier.getValue())) {
                    valid = HostnameVerifier.DEFAULT_AND_LOCALHOST.verify(address, session);
                }
            } else {
                valid = HostnameVerifier.DEFAULT.verify(address, session);
            }

            if (!valid) {
                throw new SSLException("Host name verification failed for host : " + address);
            }
        }
    };
}

From source file:eu.eidas.auth.engine.metadata.impl.BaseMetadataFetcher.java

/**
 * Override this method to plug your own SSLSocketFactory.
 * <p>/*from w ww .  java 2 s.c o m*/
 * This default implementation relies on the default one from the JVM, i.e. using the default trustStore
 * ($JRE/lib/security/cacerts).
 *
 * @return the SecureProtocolSocketFactory instance to be used to connect to https metadata URLs.
 */
@Nonnull
protected SecureProtocolSocketFactory newSslSocketFactory() {

    HostnameVerifier hostnameVerifier;

    if (!Boolean.getBoolean(DefaultBootstrap.SYSPROP_HTTPCLIENT_HTTPS_DISABLE_HOSTNAME_VERIFICATION)) {
        hostnameVerifier = new StrictHostnameVerifier();
    } else {
        hostnameVerifier = org.apache.commons.ssl.HostnameVerifier.ALLOW_ALL;
    }

    TLSProtocolSocketFactory tlsProtocolSocketFactory = new TLSProtocolSocketFactory(null, null,
            hostnameVerifier) {
        @Override
        protected void verifyHostname(Socket socket) throws SSLException {
            if (socket instanceof SSLSocket) {
                SSLSocket sslSocket = (SSLSocket) socket;
                try {
                    sslSocket.startHandshake();
                } catch (IOException e) {
                    throw new SSLException(e);
                }
                SSLSession sslSession = sslSocket.getSession();
                if (!sslSession.isValid()) {
                    throw new SSLException("SSLSession was invalid: Likely implicit handshake failure: "
                            + "Set system property javax.net.debug=all for details");
                }
                super.verifyHostname(sslSocket);
            }
        }
    };

    Protocol.registerProtocol("https", new Protocol("https", tlsProtocolSocketFactory, 443));

    return tlsProtocolSocketFactory;
}

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.DefaultHostnameVerifier.java

static String extractCN(final String subjectPrincipal) throws SSLException {
    if (subjectPrincipal == null) {
        return null;
    }//from   w  w  w .j a  v a  2s .  c  o  m
    try {
        final LdapName subjectDN = new LdapName(subjectPrincipal);
        final List<Rdn> rdns = subjectDN.getRdns();
        for (int i = rdns.size() - 1; i >= 0; i--) {
            final Rdn rds = rdns.get(i);
            final Attributes attributes = rds.toAttributes();
            final Attribute cn = attributes.get("cn");
            if (cn != null) {
                try {
                    final Object value = cn.get();
                    if (value != null) {
                        return value.toString();
                    }
                } catch (NoSuchElementException ignore) {
                } catch (NamingException ignore) {
                }
            }
        }
        return null;
    } catch (InvalidNameException e) {
        throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name");
    }
}

From source file:com.irccloud.android.HTTPFetcher.java

private void http_thread() {
    try {// ww w . j  ava 2 s  . c o m
        mThread.setName("http-stream-thread");
        int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getProtocol().equals("https") ? 443 : 80);

        String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
        if (!TextUtils.isEmpty(mURI.getQuery())) {
            path += "?" + mURI.getQuery();
        }

        PrintWriter out = new PrintWriter(mSocket.getOutputStream());

        if (mProxyHost != null && mProxyHost.length() > 0 && mProxyPort > 0) {
            out.print("CONNECT " + mURI.getHost() + ":" + port + " HTTP/1.0\r\n");
            out.print("\r\n");
            out.flush();
            HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(
                    mSocket.getInputStream());

            // Read HTTP response status line.
            StatusLine statusLine = parseStatusLine(readLine(stream));
            if (statusLine == null) {
                throw new HttpException("Received no reply from server.");
            } else if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }

            // Read HTTP response headers.
            while (!TextUtils.isEmpty(readLine(stream)))
                ;
            if (mURI.getProtocol().equals("https")) {
                mSocket = getSSLSocketFactory().createSocket(mSocket, mURI.getHost(), port, false);
                SSLSocket s = (SSLSocket) mSocket;
                try {
                    s.setEnabledProtocols(ENABLED_PROTOCOLS);
                } catch (IllegalArgumentException e) {
                    //Not supported on older Android versions
                }
                try {
                    s.setEnabledCipherSuites(ENABLED_CIPHERS);
                } catch (IllegalArgumentException e) {
                    //Not supported on older Android versions
                }
                out = new PrintWriter(mSocket.getOutputStream());
            }
        }

        if (mURI.getProtocol().equals("https")) {
            SSLSocket s = (SSLSocket) mSocket;
            StrictHostnameVerifier verifier = new StrictHostnameVerifier();
            if (!verifier.verify(mURI.getHost(), s.getSession()))
                throw new SSLException("Hostname mismatch");
        }

        Crashlytics.log(Log.DEBUG, TAG, "Sending HTTP request");

        out.print("GET " + path + " HTTP/1.0\r\n");
        out.print("Host: " + mURI.getHost() + "\r\n");
        if (mURI.getHost().equals(NetworkConnection.IRCCLOUD_HOST)
                && NetworkConnection.getInstance().session != null
                && NetworkConnection.getInstance().session.length() > 0)
            out.print("Cookie: session=" + NetworkConnection.getInstance().session + "\r\n");
        out.print("Connection: close\r\n");
        out.print("Accept-Encoding: gzip\r\n");
        out.print("User-Agent: " + NetworkConnection.getInstance().useragent + "\r\n");
        out.print("\r\n");
        out.flush();

        HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream());

        // Read HTTP response status line.
        StatusLine statusLine = parseStatusLine(readLine(stream));
        if (statusLine != null)
            Crashlytics.log(Log.DEBUG, TAG, "Got HTTP response: " + statusLine);

        if (statusLine == null) {
            throw new HttpException("Received no reply from server.");
        } else if (statusLine.getStatusCode() != HttpStatus.SC_OK
                && statusLine.getStatusCode() != HttpStatus.SC_MOVED_PERMANENTLY) {
            Crashlytics.log(Log.ERROR, TAG, "Failure: " + mURI + ": " + statusLine.getStatusCode() + " "
                    + statusLine.getReasonPhrase());
            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        // Read HTTP response headers.
        String line;

        boolean gzipped = false;
        while (!TextUtils.isEmpty(line = readLine(stream))) {
            Header header = parseHeader(line);
            if (header.getName().equalsIgnoreCase("content-encoding")
                    && header.getValue().equalsIgnoreCase("gzip"))
                gzipped = true;
            if (statusLine.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                    && header.getName().equalsIgnoreCase("location")) {
                Crashlytics.log(Log.INFO, TAG, "Redirecting to: " + header.getValue());
                mURI = new URL(header.getValue());
                mSocket.close();
                mSocket = null;
                mThread = null;
                connect();
                return;
            }
        }

        if (gzipped)
            onStreamConnected(new GZIPInputStream(mSocket.getInputStream()));
        else
            onStreamConnected(mSocket.getInputStream());

        onFetchComplete();
    } catch (Exception ex) {
        NetworkConnection.printStackTraceToCrashlytics(ex);
        onFetchFailed();
    }
}

From source file:eu.eidas.node.auth.metadata.NodeMetadataFetcher.java

protected SecureProtocolSocketFactory hubLocalSslSocketFactory() {
    HostnameVerifier hostnameVerifier;

    if (!Boolean.getBoolean(DefaultBootstrap.SYSPROP_HTTPCLIENT_HTTPS_DISABLE_HOSTNAME_VERIFICATION)) {
        hostnameVerifier = new StrictHostnameVerifier();
    } else {/*from w ww .  j a v  a  2  s.  com*/
        hostnameVerifier = org.apache.commons.ssl.HostnameVerifier.ALLOW_ALL;
    }

    X509TrustManager trustedCertManager = new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            try {
                return new X509Certificate[] { CertificateUtil.toCertificate(hubSslCertificateString) };
            } catch (EIDASSAMLEngineException e) {
                throw new RuntimeException("Unable to load trusted certificate: ", e);
            }
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    };

    TLSProtocolSocketFactory tlsProtocolSocketFactory = new TLSProtocolSocketFactory(null, trustedCertManager,
            hostnameVerifier) {
        @Override
        protected void verifyHostname(Socket socket) throws SSLException {
            if (socket instanceof SSLSocket) {
                SSLSocket sslSocket = (SSLSocket) socket;
                try {
                    sslSocket.startHandshake();
                } catch (IOException e) {
                    throw new SSLException(e);
                }
                SSLSession sslSession = sslSocket.getSession();
                if (!sslSession.isValid()) {
                    throw new SSLException("SSLSession was invalid: Likely implicit handshake failure: "
                            + "Set system property javax.net.debug=all for details");
                }
                super.verifyHostname(sslSocket);
            }
        }
    };

    Protocol.registerProtocol("https", new Protocol("https", tlsProtocolSocketFactory, 443));

    return tlsProtocolSocketFactory;
}