Java Code Examples for javax.net.ssl.SSLHandshakeException#getCause()

The following examples show how to use javax.net.ssl.SSLHandshakeException#getCause() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 6 votes vote down vote up
@Test
public void testPinnedDomainExpiredChain() throws IOException {
    // Initialize TrustKit
    String serverHostname = "expired.badssl.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceiveHandshakeError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && !(e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceiveHandshakeError = true;
        }
    }
    assertTrue(didReceiveHandshakeError);

    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence there is no reporting
        return;
    }

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED)
    );
}
 
Example 2
Source File: OkHttp3MemorizationTests.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
@Test
public void testOr() throws Exception {
  MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
    .saveTo(memoDir, "sekrit".toCharArray())
    .noTOFU()
    .build();

  final TrustManagerBuilder tmb=new TrustManagerBuilder()
    .withConfig(InstrumentationRegistry.getContext(),
      R.xml.okhttp3_selfsigned_debug, false)
    .or()
    .add(memo);

  OkHttp3Integrator.applyTo(tmb, builder);
  OkHttpClient client=builder.build();
  CertificateNotMemorizedException memoEx;

  try {
    client.newCall(buildRequest()).execute();

    throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
  }
  catch (SSLHandshakeException e) {
    if (e.getCause() instanceof CertificateNotMemorizedException) {
      memoEx=(CertificateNotMemorizedException)e.getCause();
    }
    else {
      throw new AssertionFailedError("Expected CertificateNotMemorizedException, did not get!");
    }
  }

  memo.memorize(memoEx);

  Response response=client.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());
}
 
Example 3
Source File: OkHttp3MemorizationTests.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnd() throws Exception {
  MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
    .saveTo(memoDir, "sekrit".toCharArray())
    .noTOFU()
    .build();

  final TrustManagerBuilder tmb=new TrustManagerBuilder()
    .withConfig(InstrumentationRegistry.getContext(),
      R.xml.okhttp3_selfsigned_debug, true)
    .and()
    .add(memo);

  OkHttp3Integrator.applyTo(tmb, builder);
  OkHttpClient client=builder.build();
  CertificateNotMemorizedException memoEx;

  try {
    client.newCall(buildRequest()).execute();

    throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
  }
  catch (SSLHandshakeException e) {
    if (e.getCause() instanceof CertificateNotMemorizedException) {
      memoEx=(CertificateNotMemorizedException)e.getCause();
    }
    else {
      throw new AssertionFailedError("Expected CertificateNotMemorizedException, did not get!");
    }
  }

  memo.memorize(memoEx);

  Response response=client.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());
}
 
Example 4
Source File: OkHttp3MemorizationTests.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleItemPrivate() throws Exception {
  MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
    .saveTo(memoDir, "sekrit".toCharArray())
    .noTOFU()
    .onlySingleItemChains()
    .build();

  final TrustManagerBuilder tmb=new TrustManagerBuilder()
    .withConfig(InstrumentationRegistry.getContext(),
      R.xml.okhttp3_selfsigned_debug, true)
    .and()
    .add(memo);

  OkHttp3Integrator.applyTo(tmb, builder);
  OkHttpClient client=builder.build();
  CertificateNotMemorizedException memoEx;

  try {
    client.newCall(buildRequest()).execute();

    throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
  }
  catch (SSLHandshakeException e) {
    if (e.getCause() instanceof CertificateNotMemorizedException) {
      memoEx=(CertificateNotMemorizedException)e.getCause();
    }
    else {
      throw new AssertionFailedError("Expected CertificateNotMemorizedException, did not get!");
    }
  }

  memo.memorize(memoEx);

  Response response=client.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());
}
 
Example 5
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 5 votes vote down vote up
@Test
public void testPinnedDomainWrongHostnameChain() throws IOException {
    // Initialize TrustKit
    String serverHostname = "wrong.host.badssl.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceiveHandshakeError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && !(e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceiveHandshakeError = true;
        }
    }
    assertTrue(didReceiveHandshakeError);

    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence there is no reporting
        return;
    }

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED)
    );
}
 
Example 6
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 5 votes vote down vote up
@Test
public void testPinnedDomainInvalidPin() throws IOException {
    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence the connection will succeed
        return;
    }

    String serverHostname = "www.yahoo.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceivePinningError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && (e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceivePinningError = true;
        }
    }
    assertTrue(didReceivePinningError);

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}
 
Example 7
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 5 votes vote down vote up
@Test
public void testPinnedDomainUntrustedChainAndPinningNotEnforced() throws IOException {
    String serverHostname = "untrusted-root.badssl.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceiveHandshakeError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && !(e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceiveHandshakeError = true;
        }
    }

    // Ensure the SSL handshake failed (but not because of a pinning error)
    assertTrue(didReceiveHandshakeError);

    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence there is no reporting
        return;
    }

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED)
    );
}
 
Example 8
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 5 votes vote down vote up
@Test
public void testNonPinnedDomainUntrustedRootChain() throws IOException {
    String serverHostname = "www.cacert.org";
    final DomainPinningPolicy domainPolicy = new DomainPinningPolicy.Builder()
            .setHostname("other.domain.com")
            .setShouldEnforcePinning(true)
            .setPublicKeyHashes(new HashSet<String>() {{
                // Wrong pins
                add("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
                add("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=");
            }}).build();

    TestableTrustKit.init(new HashSet<DomainPinningPolicy>() {{ add(domainPolicy); }},
            InstrumentationRegistry.getInstrumentation().getContext(),
            mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    // This means that TrustKit does not interfere with default certificate validation
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceiveHandshakeError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && !(e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceiveHandshakeError = true;
        }
    }
    assertTrue(didReceiveHandshakeError);

    // Ensure the background reporter was NOT called as we only want reports for pinned domains
    verify(mockReporter, never()).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}
 
Example 9
Source File: OkHttp3MemorizationTests.java    From cwac-netsecurity with Apache License 2.0 4 votes vote down vote up
@Test
public void testTOFU() throws Exception {
  MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
    .saveTo(memoDir, "sekrit".toCharArray())
    .build();

  final TrustManagerBuilder tmb=new TrustManagerBuilder().add(memo);

  OkHttp3Integrator.applyTo(tmb, builder);
  OkHttpClient client=builder.build();
  Response response=client.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());

  response=client.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());

  MemorizingTrustManager memoNoTofu=new MemorizingTrustManager.Builder()
    .saveTo(memoDir, "sekrit".toCharArray())
    .noTOFU()
    .build();
  TrustManagerBuilder tmbNoTofu=new TrustManagerBuilder().add(memoNoTofu);
  OkHttpClient.Builder builderNoTofu=new OkHttpClient.Builder();

  OkHttp3Integrator.applyTo(tmbNoTofu, builderNoTofu);

  OkHttpClient clientNoTofu=builderNoTofu.build();

  response=clientNoTofu.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());

  memoNoTofu.clearAll(true);
  builderNoTofu=new OkHttpClient.Builder();
  OkHttp3Integrator.applyTo(tmbNoTofu, builderNoTofu);
  clientNoTofu=builderNoTofu.build();

  try {
    clientNoTofu.newCall(buildRequest()).execute();

    throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
  }
  catch (SSLHandshakeException e) {
    if (!(e.getCause() instanceof CertificateNotMemorizedException)) {
      throw e;
    }
  }
}
 
Example 10
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 4 votes vote down vote up
@Test
public void testDebugOverridesInvalidPin() throws IOException, CertificateException {
    if (Build.VERSION.SDK_INT >= 24) {
        // This test will not work when using the Android N XML network policy because we can't
        // dynamically switch overridePins to false (as it is true in the XML policy)
        return;
    }
    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence the connection will succeed
        return;
    }

    String serverHostname = "www.cacert.org";
    final DomainPinningPolicy domainPolicy = new DomainPinningPolicy.Builder()
            .setHostname(serverHostname)
            .setShouldEnforcePinning(true)
            .setPublicKeyHashes(new HashSet<String>() {{
                // Wrong pins
                add("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
                add("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=");
            }}).build();

    // Create a configuration with debug overrides enabled to add the cacert.org CA and to set
    // overridePins to false, making the connection fail
    TestableTrustKit.init(new HashSet<DomainPinningPolicy>() {{ add(domainPolicy); }},
            false,
            new HashSet<Certificate>(){{ add(caCertDotOrgRoot); }},
            InstrumentationRegistry.getInstrumentation().getContext(),
            mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    // This means that debug-overrides properly enables the supplied debug CA cert but does not
    // disable pinning when overridePins is false
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceivePinningError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && (e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceivePinningError = true;
        }
    }
    assertTrue(didReceivePinningError);

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}