Search in sources :

Example 66 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project fdroidclient by f-droid.

the class DownloaderService method handleIntent.

/**
 * This method is invoked on the worker thread with a request to process.
 * Only one Intent is processed at a time, but the processing happens on a
 * worker thread that runs independently from other application logic.
 * So, if this code takes a long time, it will hold up other requests to
 * the same DownloaderService, but it will not hold up anything else.
 * When all requests have been handled, the DownloaderService stops itself,
 * so you should not ever call {@link #stopSelf}.
 * <p/>
 * Downloads are put into subdirectories based on hostname/port of each repo
 * to prevent files with the same names from conflicting.  Each repo enforces
 * unique APK file names on the server side.
 *
 * @param intent The {@link Intent} passed via {@link
 *               android.content.Context#startService(Intent)}.
 * @see org.fdroid.fdroid.IndexV1Updater#update()
 */
private void handleIntent(Intent intent) {
    final Uri uri = intent.getData();
    final long repoId = intent.getLongExtra(Downloader.EXTRA_REPO_ID, 0);
    final Uri canonicalUrl = Uri.parse(intent.getStringExtra(Downloader.EXTRA_CANONICAL_URL));
    final SanitizedFile localFile = ApkCache.getApkDownloadPath(this, canonicalUrl);
    sendBroadcast(uri, Downloader.ACTION_STARTED, localFile, repoId, canonicalUrl);
    try {
        activeCanonicalUrl = canonicalUrl.toString();
        downloader = DownloaderFactory.create(this, uri, localFile);
        downloader.setListener(new ProgressListener() {

            @Override
            public void onProgress(long bytesRead, long totalBytes) {
                Intent intent = new Intent(Downloader.ACTION_PROGRESS);
                intent.setData(canonicalUrl);
                intent.putExtra(Downloader.EXTRA_BYTES_READ, bytesRead);
                intent.putExtra(Downloader.EXTRA_TOTAL_BYTES, totalBytes);
                localBroadcastManager.sendBroadcast(intent);
            }
        });
        downloader.setTimeout(timeout);
        downloader.download();
        if (downloader.isNotFound()) {
            sendBroadcast(uri, Downloader.ACTION_INTERRUPTED, localFile, getString(R.string.download_404), repoId, canonicalUrl);
        } else {
            sendBroadcast(uri, Downloader.ACTION_COMPLETE, localFile, repoId, canonicalUrl);
        }
    } catch (InterruptedException e) {
        sendBroadcast(uri, Downloader.ACTION_INTERRUPTED, localFile, repoId, canonicalUrl);
    } catch (ConnectException | HttpRetryException | NoRouteToHostException | SocketTimeoutException | SSLHandshakeException | SSLKeyException | SSLPeerUnverifiedException | SSLProtocolException | ProtocolException | UnknownHostException e) {
        // if the above list of exceptions changes, also change it in IndexV1Updater.update()
        Log.e(TAG, "CONNECTION_FAILED: " + e.getLocalizedMessage());
        sendBroadcast(uri, Downloader.ACTION_CONNECTION_FAILED, localFile, repoId, canonicalUrl);
    } catch (IOException e) {
        e.printStackTrace();
        sendBroadcast(uri, Downloader.ACTION_INTERRUPTED, localFile, e.getLocalizedMessage(), repoId, canonicalUrl);
    } finally {
        if (downloader != null) {
            downloader.close();
        }
    }
    downloader = null;
    activeCanonicalUrl = null;
}
Also used : SSLProtocolException(javax.net.ssl.SSLProtocolException) ProtocolException(java.net.ProtocolException) UnknownHostException(java.net.UnknownHostException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) Intent(android.content.Intent) IOException(java.io.IOException) SSLKeyException(javax.net.ssl.SSLKeyException) Uri(android.net.Uri) HttpRetryException(java.net.HttpRetryException) NoRouteToHostException(java.net.NoRouteToHostException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLProtocolException(javax.net.ssl.SSLProtocolException) SocketTimeoutException(java.net.SocketTimeoutException) ProgressListener(org.fdroid.fdroid.ProgressListener) SanitizedFile(org.fdroid.fdroid.data.SanitizedFile) ConnectException(java.net.ConnectException)

Example 67 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project okhttp by square.

the class JavaApiConverter method createOkResponseForCachePut.

/**
   * 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();
}
Also used : HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) JavaNetHeaders(okhttp3.internal.JavaNetHeaders) CipherSuite(okhttp3.CipherSuite) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) CacheRequest(okhttp3.internal.cache.CacheRequest) Request(okhttp3.Request) ResponseBody(okhttp3.ResponseBody) CacheResponse(java.net.CacheResponse) Response(okhttp3.Response) SecureCacheResponse(java.net.SecureCacheResponse) StatusLine(okhttp3.internal.http.StatusLine) HttpURLConnection(java.net.HttpURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) RequestBody(okhttp3.RequestBody) Certificate(java.security.cert.Certificate) Handshake(okhttp3.Handshake)

Example 68 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project okhttp by square.

the class CallTest method unmatchingPinnedCertificate.

@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!"));
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 69 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project robovm by robovm.

the class myHostnameVerifier method test_getPeerPrincipal.

/**
     * javax.net.ssl.HttpsURLConnection#getPeerPrincipal()
     */
public final void test_getPeerPrincipal() throws Exception {
    URL url = new URL("https://localhost:55555");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    try {
        connection.getPeerPrincipal();
        fail("IllegalStateException wasn't thrown");
    } catch (IllegalStateException expected) {
    }
    HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
    try {
        Principal p = con.getPeerPrincipal();
        fail("SSLPeerUnverifiedException wasn't thrown");
    } catch (SSLPeerUnverifiedException expected) {
    }
    con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
    Principal p = con.getPeerPrincipal();
    assertNotNull(p);
}
Also used : SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Principal(java.security.Principal)

Example 70 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project platform_frameworks_base by android.

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