/** * Return the cert chain presented by the peer in the * java.security.cert format. * Note: This method can be used only when using certificate-based * cipher suites; using it with non-certificate-based cipher suites, * such as Kerberos, will throw an SSLPeerUnverifiedException. * * @return array of peer X.509 certs, with the peer's own cert * first in the chain, and with the "root" CA last. */ @Override public java.security.cert.Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException { // // clone to preserve integrity of session ... caller can't // change record of peer identity even by accident, much // less do it intentionally. // if ((cipherSuite.keyExchange == K_KRB5) || (cipherSuite.keyExchange == K_KRB5_EXPORT)) { throw new SSLPeerUnverifiedException("no certificates expected" + " for Kerberos cipher suites"); } if (peerCerts == null) { throw new SSLPeerUnverifiedException("peer not authenticated"); } // Certs are immutable objects, therefore we don't clone them. // But do need to clone the array, so that nothing is inserted // into peerCerts. return (java.security.cert.Certificate[])peerCerts.clone(); }
public static Handshake get(SSLSession session) { String cipherSuiteString = session.getCipherSuite(); if (cipherSuiteString == null) throw new IllegalStateException("cipherSuite == null"); CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString); String tlsVersionString = session.getProtocol(); if (tlsVersionString == null) throw new IllegalStateException("tlsVersion == null"); TlsVersion tlsVersion = TlsVersion.forJavaName(tlsVersionString); Certificate[] peerCertificates; try { peerCertificates = session.getPeerCertificates(); } catch (SSLPeerUnverifiedException ignored) { peerCertificates = null; } List<Certificate> peerCertificatesList = peerCertificates != null ? Util.immutableList(peerCertificates) : Collections.<Certificate>emptyList(); Certificate[] localCertificates = session.getLocalCertificates(); List<Certificate> localCertificatesList = localCertificates != null ? Util.immutableList(localCertificates) : Collections.<Certificate>emptyList(); return new Handshake(tlsVersion, cipherSuite, peerCertificatesList, localCertificatesList); }
@Test public void unmatchingPinnedCertificate() throws Exception { enableTls(); server.enqueue(new MockResponse()); // Pin publicobject.com's cert. client = client.newBuilder() .certificatePinner(new CertificatePinner.Builder() .add(server.getHostName(), "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=") .build()) .build(); // When we pin the wrong certificate, connectivity fails. Request request = new Request.Builder().url(server.url("/")).build(); try { client.newCall(request).execute(); fail(); } catch (SSLPeerUnverifiedException expected) { assertTrue(expected.getMessage().startsWith("Certificate pinning failure!")); } }
/** * Returns the server's certificate chain, or throws * SSLPeerUnverified Exception if * the server did not authenticate. */ public java.security.cert.Certificate[] getServerCertificates() throws SSLPeerUnverifiedException { if (cachedResponse != null) { List<java.security.cert.Certificate> l = ((SecureCacheResponse)cachedResponse).getServerCertificateChain(); if (l == null) { return null; } else { return l.toArray(new java.security.cert.Certificate[0]); } } if (http == null) { throw new IllegalStateException("connection not yet open"); } else { return (((HttpsClient)http).getServerCertificates ()); } }
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection) throws IOException { this.uri = uri.toString(); this.varyHeaders = varyHeaders; this.requestMethod = httpConnection.getRequestMethod(); this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true); SSLSocket sslSocket = getSslSocket(httpConnection); if (sslSocket != null) { cipherSuite = sslSocket.getSession().getCipherSuite(); Certificate[] peerCertificatesNonFinal = null; try { peerCertificatesNonFinal = sslSocket.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException ignored) { } peerCertificates = peerCertificatesNonFinal; localCertificates = sslSocket.getSession().getLocalCertificates(); } else { cipherSuite = null; peerCertificates = null; localCertificates = null; } }
public void checkError(Throwable e){ try { throwable = e; fireBaseReportError(e); Crashlytics.logException(e); e.printStackTrace(); if (e instanceof HttpException) { int code = getHttpErrorCode(e); httpMessage(code); } else if (e instanceof ConnectException) { showToast(mContext.getString(R.string.slow_internet)); } else if (e instanceof UnknownHostException || e instanceof SocketTimeoutException) { showToast(mContext.getString(R.string.internet_not_connected)); } else if (e instanceof SSLHandshakeException || e instanceof SSLPeerUnverifiedException) { showToast(mContext.getString(R.string.server_problem)); } else { showToast(mContext.getString(R.string.unknown_error_msg)); } } catch (Exception err){ err.printStackTrace(); } }
/** * Return the cert chain presented by the peer. * Note: This method can be used only when using certificate-based * cipher suites; using it with non-certificate-based cipher suites, * such as Kerberos, will throw an SSLPeerUnverifiedException. * * @return array of peer X.509 certs, with the peer's own cert * first in the chain, and with the "root" CA last. */ public X509Certificate[] getCertificateChain() throws SSLPeerUnverifiedException { /* * clone to preserve integrity of session ... caller can't * change record of peer identity even by accident, much * less do it intentionally. */ if ((cipherSuite.keyExchange == K_KRB5) || (cipherSuite.keyExchange == K_KRB5_EXPORT)) { throw new SSLPeerUnverifiedException("no certificates expected" + " for Kerberos cipher suites"); } if (peerCerts != null) { return peerCerts.clone(); } else { throw new SSLPeerUnverifiedException("peer not authenticated"); } }
/** * Return the cert chain presented by the peer. * Note: This method can be used only when using certificate-based * cipher suites; using it with non-certificate-based cipher suites, * such as Kerberos, will throw an SSLPeerUnverifiedException. * * @return array of peer X.509 certs, with the peer's own cert * first in the chain, and with the "root" CA last. */ public X509Certificate[] getCertificateChain() throws SSLPeerUnverifiedException { /* * clone to preserve integrity of session ... caller can't * change record of peer identity even by accident, much * less do it intentionally. */ if (ClientKeyExchangeService.find(cipherSuite.keyExchange.name) != null) { throw new SSLPeerUnverifiedException("no certificates expected" + " for " + cipherSuite.keyExchange + " cipher suites"); } if (peerCerts != null) { return peerCerts.clone(); } else { throw new SSLPeerUnverifiedException("peer not authenticated"); } }
private void processResponseCertificates(HttpURLConnection con, Response response) throws SSLPeerUnverifiedException { if (con instanceof HttpsURLConnection) { try { HttpsURLConnection secureConn = (HttpsURLConnection) con; response.cipherSuite = secureConn.getCipherSuite(); response.serverCertificates = secureConn.getServerCertificates(); response.clientCertificates = secureConn.getLocalCertificates(); } catch (IllegalStateException e) { // If the response is not a 200, getting response certificates will fail with the (misleading) message // "connection not yet open". Ignore this. } } }
/** * Returns the server's certificate chain, or throws * SSLPeerUnverified Exception if * the server did not authenticate. */ public java.security.cert.Certificate[] getServerCertificates() throws SSLPeerUnverifiedException { if (cachedResponse != null) { List<java.security.cert.Certificate> l = ((SecureCacheResponse)cachedResponse) .getServerCertificateChain(); if (l == null) { return null; } else { return l.toArray(new java.security.cert.Certificate[0]); } } if (http == null) { throw new IllegalStateException("connection not yet open"); } else { return (((HttpsClient)http).getServerCertificates ()); } }
@Override public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException, RenegotiationRequiredException { try { return channel.getSslSession().getPeerCertificateChain(); } catch (SSLPeerUnverifiedException e) { try { SslClientAuthMode sslClientAuthMode = channel.getOption(Options.SSL_CLIENT_AUTH_MODE); if (sslClientAuthMode == SslClientAuthMode.NOT_REQUESTED) { throw new RenegotiationRequiredException(); } } catch (IOException e1) { //ignore, will not actually happen } throw e; } }
@Override public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException, RenegotiationRequiredException { try { return channel.getSslSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { try { SslClientAuthMode sslClientAuthMode = channel.getOption(Options.SSL_CLIENT_AUTH_MODE); if (sslClientAuthMode == SslClientAuthMode.NOT_REQUESTED) { throw new RenegotiationRequiredException(); } } catch (IOException e1) { //ignore, will not actually happen } throw e; } }
/** * Returns the DN extracted from the server certificate. * * @param socket the SSL Socket * @return the extracted DN * @throws CertificateException if there is a problem parsing the certificate */ private static String extractPeerDNFromServerSSLSocket(Socket socket) throws CertificateException { String dn = null; if (socket instanceof SSLSocket) { final SSLSocket sslSocket = (SSLSocket) socket; try { final Certificate[] certChains = sslSocket.getSession().getPeerCertificates(); if (certChains != null && certChains.length > 0) { X509Certificate x509Certificate = convertAbstractX509Certificate(certChains[0]); dn = x509Certificate.getSubjectDN().getName().trim(); logger.debug("Extracted DN={} from server certificate", dn); } } catch (SSLPeerUnverifiedException e) { if (e.getMessage().equals(PEER_NOT_AUTHENTICATED_MSG)) { logger.error("The server did not present a certificate and thus the DN cannot" + " be extracted. Check that the other endpoint is providing a complete certificate chain"); } throw new CertificateException(e); } } return dn; }
/** * Returns the identity of the peer which was established as part of * defining the session. * * @return the peer's principal. Returns an X500Principal of the * end-entity certificate for X509-based cipher suites, and * Principal for Kerberos cipher suites. * * @throws SSLPeerUnverifiedException if the peer's identity has not * been verified */ @Override public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { if ((cipherSuite.keyExchange == K_KRB5) || (cipherSuite.keyExchange == K_KRB5_EXPORT)) { if (peerPrincipal == null) { throw new SSLPeerUnverifiedException("peer not authenticated"); } else { // Eliminate dependency on KerberosPrincipal return peerPrincipal; } } if (peerCerts == null) { throw new SSLPeerUnverifiedException("peer not authenticated"); } return peerCerts[0].getSubjectX500Principal(); }
public static Handshake get(SSLSession session) { String cipherSuite = session.getCipherSuite(); if (cipherSuite == null) { throw new IllegalStateException("cipherSuite == null"); } Certificate[] peerCertificates; List<Certificate> peerCertificatesList; List<Certificate> localCertificatesList; try { peerCertificates = session.getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { peerCertificates = null; } if (peerCertificates != null) { peerCertificatesList = Util.immutableList(peerCertificates); } else { peerCertificatesList = Collections.emptyList(); } Certificate[] localCertificates = session.getLocalCertificates(); if (localCertificates != null) { localCertificatesList = Util.immutableList(localCertificates); } else { localCertificatesList = Collections.emptyList(); } return new Handshake(cipherSuite, peerCertificatesList, localCertificatesList); }
/** * Creates an OkHttp {@link Response} using the supplied {@link URI} and {@link URLConnection} to * supply the data. The URLConnection is assumed to already be connected. If this method returns * {@code null} the response is uncacheable. */ public static Response createOkResponseForCachePut(URI uri, URLConnection urlConnection) throws IOException { HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection; Response.Builder okResponseBuilder = new Response.Builder(); // Request: Create one from the URL connection. Headers responseHeaders = createHeaders(urlConnection.getHeaderFields()); // Some request headers are needed for Vary caching. Headers varyHeaders = varyHeaders(urlConnection, responseHeaders); if (varyHeaders == null) { return null; } // OkHttp's Call API requires a placeholder body; the real body will be streamed separately. String requestMethod = httpUrlConnection.getRequestMethod(); RequestBody placeholderBody = HttpMethod.requiresRequestBody(requestMethod) ? Util.EMPTY_REQUEST : null; Request okRequest = new Request.Builder() .url(uri.toString()) .method(requestMethod, placeholderBody) .headers(varyHeaders) .build(); okResponseBuilder.request(okRequest); // Status line StatusLine statusLine = StatusLine.parse(extractStatusLine(httpUrlConnection)); okResponseBuilder.protocol(statusLine.protocol); okResponseBuilder.code(statusLine.code); okResponseBuilder.message(statusLine.message); // A network response is required for the Cache to find any Vary headers it needs. Response networkResponse = okResponseBuilder.build(); okResponseBuilder.networkResponse(networkResponse); // Response headers Headers okHeaders = extractOkResponseHeaders(httpUrlConnection, okResponseBuilder); okResponseBuilder.headers(okHeaders); // Response body ResponseBody okBody = createOkBody(urlConnection); okResponseBuilder.body(okBody); // Handle SSL handshake information as needed. if (httpUrlConnection instanceof HttpsURLConnection) { HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) httpUrlConnection; Certificate[] peerCertificates; try { peerCertificates = httpsUrlConnection.getServerCertificates(); } catch (SSLPeerUnverifiedException e) { peerCertificates = null; } Certificate[] localCertificates = httpsUrlConnection.getLocalCertificates(); String cipherSuiteString = httpsUrlConnection.getCipherSuite(); CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString); Handshake handshake = Handshake.get(null, cipherSuite, nullSafeImmutableList(peerCertificates), nullSafeImmutableList(localCertificates)); okResponseBuilder.handshake(handshake); } return okResponseBuilder.build(); }
@Override public List<Certificate> getServerCertificateChain() throws SSLPeerUnverifiedException { if (entry.peerCertificates == null || entry.peerCertificates.length == 0) { throw new SSLPeerUnverifiedException(null); } return Arrays.asList(entry.peerCertificates.clone()); }
/** * Reports a failure to complete a connection. Determines the next {@link ConnectionSpec} to try, * if any. * * @return {@code true} if the connection should be retried using {@link * #configureSecureSocket(SSLSocket)} or {@code false} if not */ public boolean connectionFailed(IOException e) { // Any future attempt to connect using this strategy will be a fallback attempt. isFallback = true; if (!isFallbackPossible) { return false; } // If there was a protocol problem, don't recover. if (e instanceof ProtocolException) { return false; } // If there was an interruption or timeout (SocketTimeoutException), don't recover. // For the socket connect timeout case we do not try the same host with a different // ConnectionSpec: we assume it is unreachable. if (e instanceof InterruptedIOException) { return false; } // Look for known client-side or negotiation errors that are unlikely to be fixed by trying // again with a different connection spec. if (e instanceof SSLHandshakeException) { // If the problem was a CertificateException from the X509TrustManager, // do not retry. if (e.getCause() instanceof CertificateException) { return false; } } if (e instanceof SSLPeerUnverifiedException) { // e.g. a certificate pinning error. return false; } // On Android, SSLProtocolExceptions can be caused by TLS_FALLBACK_SCSV failures, which means we // retry those when we probably should not. return (e instanceof SSLHandshakeException || e instanceof SSLProtocolException); }
@Test public void normalizeUnknownSelfSignedCertificate() throws Exception { HeldCertificate root = new HeldCertificate.Builder() .serialNumber("1") .build(); CertificateChainCleaner cleaner = CertificateChainCleaner.get(); try { cleaner.clean(list(root), "hostname"); fail(); } catch (SSLPeerUnverifiedException expected) { } }
private static Principal getPeerPrincipal(SSLSession session) throws SSLPeerUnverifiedException { Principal principal; try { principal = session.getPeerPrincipal(); } catch (AbstractMethodError e) { // if the JSSE provider does not support it, return null, since // we need it only for Kerberos. principal = null; } return principal; }
@Test public void unsuccessfulCheck() throws Exception { CertificatePinner certificatePinner = new CertificatePinner.Builder() .add("example.com", certA1Sha256Pin) .build(); try { certificatePinner.check("example.com", certB1.certificate); fail(); } catch (SSLPeerUnverifiedException expected) { } }
public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException { if (certificates.length == 0) { throw new SSLPeerUnverifiedException("peer not authenticated"); } else { return certificates; } }
/** * Returns the server's principal, or throws SSLPeerUnverifiedException * if the server did not authenticate. */ Principal getPeerPrincipal() throws SSLPeerUnverifiedException { if (cachedResponse != null) { return ((SecureCacheResponse)cachedResponse).getPeerPrincipal(); } if (http == null) { throw new IllegalStateException("connection not yet open"); } else { return (((HttpsClient)http).getPeerPrincipal()); } }
/** * Creates an OkHttp {@link Response} using the supplied {@link URI} and {@link URLConnection} to * supply the data. The URLConnection is assumed to already be connected. If this method returns * {@code null} the response is uncacheable. */ public static Response createOkResponseForCachePut(URI uri, URLConnection urlConnection) throws IOException { HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection; Response.Builder okResponseBuilder = new Response.Builder(); // Request: Create one from the URL connection. Headers responseHeaders = createHeaders(urlConnection.getHeaderFields()); // Some request headers are needed for Vary caching. Headers varyHeaders = varyHeaders(urlConnection, responseHeaders); if (varyHeaders == null) { return null; } // OkHttp's Call API requires a placeholder body; the real body will be streamed separately. String requestMethod = httpUrlConnection.getRequestMethod(); RequestBody placeholderBody = HttpMethod.requiresRequestBody(requestMethod) ? Util.EMPTY_REQUEST : null; Request okRequest = new Request.Builder() .url(uri.toString()) .method(requestMethod, placeholderBody) .headers(varyHeaders) .build(); okResponseBuilder.request(okRequest); // Status line StatusLine statusLine = StatusLine.parse(extractStatusLine(httpUrlConnection)); okResponseBuilder.protocol(statusLine.protocol); okResponseBuilder.code(statusLine.code); okResponseBuilder.message(statusLine.message); // A network response is required for the Cache to find any Vary headers it needs. Response networkResponse = okResponseBuilder.build(); okResponseBuilder.networkResponse(networkResponse); // Response headers Headers okHeaders = extractOkResponseHeaders(httpUrlConnection, okResponseBuilder); okResponseBuilder.headers(okHeaders); // Response body ResponseBody okBody = createOkBody(urlConnection); okResponseBuilder.body(okBody); // Handle SSL handshake information as needed. if (httpUrlConnection instanceof HttpsURLConnection) { HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) httpUrlConnection; Certificate[] peerCertificates; try { peerCertificates = httpsUrlConnection.getServerCertificates(); } catch (SSLPeerUnverifiedException e) { peerCertificates = null; } Certificate[] localCertificates = httpsUrlConnection.getLocalCertificates(); String cipherSuiteString = httpsUrlConnection.getCipherSuite(); CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString); Handshake handshake = Handshake.get(TlsVersion.SSL_3_0, cipherSuite, nullSafeImmutableList(peerCertificates), nullSafeImmutableList(localCertificates)); okResponseBuilder.handshake(handshake); } return okResponseBuilder.build(); }
/** * SSLSession's peerPrincipal for the remote host. * @return Principal */ public Principal peerPrincipal() throws IOException { try { return sslEngine.getSession().getPeerPrincipal(); } catch (SSLPeerUnverifiedException se) { log.debug("SSL peer is not authenticated, returning ANONYMOUS instead"); return KafkaPrincipal.ANONYMOUS; } }
@Test public void chainTooLong() throws Exception { List<HeldCertificate> heldCertificates = chainOfLength(11); List<Certificate> certificates = new ArrayList<>(); for (HeldCertificate heldCertificate : heldCertificates) { certificates.add(heldCertificate.certificate); } X509Certificate root = heldCertificates.get(heldCertificates.size() - 1).certificate; CertificateChainCleaner cleaner = CertificateChainCleaner.get(root); try { cleaner.clean(certificates, "hostname"); fail(); } catch (SSLPeerUnverifiedException expected) { } }
@Test public void unsuccessfulCheckForOneHostnameWithWildcardAndDirectCertificate() throws Exception { CertificatePinner certificatePinner = new CertificatePinner.Builder() .add("*.example.com", certA1Sha256Pin) .add("a.example.com", certB1Sha256Pin) .build(); try { certificatePinner.check("a.example.com", certC1.certificate); fail(); } catch (SSLPeerUnverifiedException expected) { } }
private void testConnection(AbstractProfileBase profile) throws JobException { boolean result = false; if (profile != null) { try { StorageAdapter sourceAdapter = StorageAdapterMgr.getStorageAdapter(profile, null); result = sourceAdapter.testConnection(); } catch (ConnectionTestException e) { String msg = null; if (e.getMessage() != null) { msg = e.getMessage(); } if (e.getCause() != null && e.getCause() instanceof SSLPeerUnverifiedException) { msg += " If SSL is enabled make sure you are using the --insecure flag."; } if (msg != null) { LOG.log(Level.WARNING, "Exception while connecting to profile: " + profile.getName() + ": " + msg, e); throw new JobException(msg); } } if (result == false) { throw new JobException("Cannot connect to profile: " + profile.getName() + "."); } } }
private X509Certificate getX509Certificate() { try { X509Certificate[] certChain = sslHandler.engine().getSession().getPeerCertificateChain(); if (certChain.length > 0) { return certChain[0]; } } catch (SSLPeerUnverifiedException e) { log.warn(e.getMessage()); return null; } return null; }