Java Code Examples for javax.net.ssl.SSLHandshakeException

The following are top voted examples for showing how to use javax.net.ssl.SSLHandshakeException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: http-fetcher   File: SimpleHttpFetcher.java   View source code 8 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Decide about retry #" + executionCount + " for exception " + exception.getMessage());
    }

    if (executionCount >= _maxRetryCount) {
        // Do not retry if over max retry count
        return false;
    } else if (exception instanceof NoHttpResponseException) {
        // Retry if the server dropped connection on us
        return true;
    } else if (exception instanceof SSLHandshakeException) {
        // Do not retry on SSL handshake exception
        return false;
    }

    HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
    // Retry if the request is considered idempotent
    return idempotent;
}
 
Example 2
Project: hadoop-oss   File: TestSSLHttpServer.java   View source code 7 votes vote down vote up
/**
 * Test that verifies that excluded ciphers (SSL_RSA_WITH_RC4_128_SHA,
 * TLS_ECDH_ECDSA_WITH_RC4_128_SHA,TLS_ECDH_RSA_WITH_RC4_128_SHA,
 * TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA) are not
 * available for negotiation during SSL connection.
 */
@Test
public void testExcludedCiphers() throws Exception {
  URL url = new URL(baseUrl, "/echo?a=b&c=d");
  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
  PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
      = new PrefferedCipherSSLSocketFactory(sslSocketF,
          excludeCiphers.split(","));
  conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
  assertFalse("excludedCipher list is empty", excludeCiphers.isEmpty());
  try {
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copyBytes(in, out, 1024);
    fail("No Ciphers in common, SSLHandshake must fail.");
  } catch (SSLHandshakeException ex) {
    LOG.info("No Ciphers in common, expected succesful test result.", ex);
  }
}
 
Example 3
Project: hadoop-oss   File: TestSSLHttpServer.java   View source code 7 votes vote down vote up
/** Test that verified that additionally included cipher
 * TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is only available cipher for working
 * TLS connection from client to server disabled for all other common ciphers.
 */
@Test
public void testOneEnabledCiphers() throws Exception {
  URL url = new URL(baseUrl, "/echo?a=b&c=d");
  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
  PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
      = new PrefferedCipherSSLSocketFactory(sslSocketF,
          oneEnabledCiphers.split(","));
  conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
  assertFalse("excludedCipher list is empty", oneEnabledCiphers.isEmpty());
  try {
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copyBytes(in, out, 1024);
    assertEquals(out.toString(), "a:b\nc:d\n");
    LOG.info("Atleast one additional enabled cipher than excluded ciphers,"
        + " expected successful test result.");
  } catch (SSLHandshakeException ex) {
    fail("Atleast one additional cipher available for successful handshake."
        + " Unexpected test failure: " + ex);
  }
}
 
Example 4
Project: dtsopensource   File: HttpProtocolParent.java   View source code 7 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (executionCount >= 5) {// 如果已经重试了5次,就放弃
        return false;
    }
    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }
    if (exception instanceof InterruptedIOException) {// 超时
        return false;
    }
    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }
    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }
    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }
    if (exception instanceof SSLException) {// SSL握手异常
        return false;
    }
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();
    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
 
Example 5
Project: hadoop-oss   File: TestSSLHttpServer.java   View source code 6 votes vote down vote up
/** Test verifies that mutually exclusive server's disabled cipher suites and
 * client's enabled cipher suites can successfully establish TLS connection.
 */
@Test
public void testExclusiveEnabledCiphers() throws Exception {
  URL url = new URL(baseUrl, "/echo?a=b&c=d");
  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
  PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
      = new PrefferedCipherSSLSocketFactory(sslSocketF,
          exclusiveEnabledCiphers.split(","));
  conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
  assertFalse("excludedCipher list is empty",
      exclusiveEnabledCiphers.isEmpty());
  try {
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copyBytes(in, out, 1024);
    assertEquals(out.toString(), "a:b\nc:d\n");
    LOG.info("Atleast one additional enabled cipher than excluded ciphers,"
        + " expected successful test result.");
  } catch (SSLHandshakeException ex) {
    fail("Atleast one additional cipher available for successful handshake."
        + " Unexpected test failure: " + ex);
  }
}
 
Example 6
Project: My-Android-Base-Code   File: ErrorUtils.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 7
Project: hekate   File: InvalidSslConfigurationTest.java   View source code 6 votes vote down vote up
@Test
public void testInvalidCertificate() throws Exception {
    NetworkServer server = createServer();

    get(server.start(newServerAddress()));

    NetworkSslConfig ssl = new NetworkSslConfig()
        .withProvider(context().ssl().get().getProvider())
        .withKeyStorePath("ssl/hekate-test2.jks")
        .withKeyStorePassword("hekate-test2")
        .withTrustStorePath("ssl/hekate-test2.jks")
        .withTrustStorePassword("hekate-test2");

    NetworkClient<String> client = createClient(cfg ->
        cfg.setSsl(NettySslUtils.clientContext(ssl, context().resources()))
    );

    try {
        client.connect(server.address(), new NetworkClientCallbackMock<>()).get();

        fail("Error was expected.");
    } catch (ExecutionException e) {
        assertTrue(getStacktrace(e), ErrorUtils.isCausedBy(SSLHandshakeException.class, e));
    }
}
 
Example 8
Project: PicCrawler   File: RetryHandler.java   View source code 6 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
 
Example 9
Project: OpenJSharp   File: JConsole.java   View source code 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example 10
Project: ProxyPool   File: RetryHandler.java   View source code 6 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
 
Example 11
Project: jdk8u-jdk   File: DHCrypt.java   View source code 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
 
Example 12
Project: jdk8u-jdk   File: ECDHCrypt.java   View source code 6 votes vote down vote up
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example 13
Project: jdk8u-jdk   File: JConsole.java   View source code 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example 14
Project: jdk8u-jdk   File: JMXStartStopTest.java   View source code 6 votes vote down vote up
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof NoSuchObjectException ||
                t instanceof ConnectException ||
                t instanceof SSLHandshakeException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
 
Example 15
Project: openjdk-jdk10   File: DHCrypt.java   View source code 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
 
Example 16
Project: openjdk-jdk10   File: ECDHCrypt.java   View source code 6 votes vote down vote up
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example 17
Project: openjdk-jdk10   File: JConsole.java   View source code 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example 18
Project: openjdk-jdk10   File: JMXStartStopTest.java   View source code 6 votes vote down vote up
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof RemoteException ||
                t instanceof SSLHandshakeException ||
                t instanceof ConnectException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
 
Example 19
Project: openjdk9   File: DHCrypt.java   View source code 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
 
Example 20
Project: openjdk9   File: ECDHCrypt.java   View source code 6 votes vote down vote up
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example 21
Project: openjdk9   File: JConsole.java   View source code 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example 22
Project: openjdk9   File: JMXStartStopTest.java   View source code 6 votes vote down vote up
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof RemoteException ||
                t instanceof SSLHandshakeException ||
                t instanceof ConnectException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
 
Example 23
Project: helium   File: BaseTest.java   View source code 6 votes vote down vote up
protected byte[] downloadFile(String xpath, String fitxer) {
	
	//System.setProperty ("jsse.enableSNIExtension", "false");
	
	FileDownloader downloader = new FileDownloader(driver);
	driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
	boolean isPresent = driver.findElements(By.xpath(xpath)).size() > 0;
	driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	assertTrue("Enllaç al fitxer " + fitxer + " no existeix" , isPresent);
	
	byte[] downloadedFile = null;
	
	try {
		downloadedFile = downloader.downloadFile(driver.findElement(By.xpath(xpath)));
	} catch (SSLHandshakeException certEx) {
		certEx.printStackTrace();
		fail("No s'ha pogut descarregar el fitxer " + fitxer + ". Error de certificat.");
	} catch (Exception e) {
		e.printStackTrace();
		fail("No s'ha pogut descarregar el fitxer " + fitxer);
	}
	
	assertThat(downloader.getHTTPStatusOfLastDownloadAttempt(), is(equalTo(200)));
	
	return downloadedFile;
}
 
Example 24
Project: zapp   File: MediathekListFragment.java   View source code 6 votes vote down vote up
@Override
public void onFailure(@NonNull Call<MediathekAnswer> call, @NonNull Throwable t) {
	adapter.setLoading(false);
	swipeRefreshLayout.setRefreshing(false);

	if (!call.isCanceled()) {
		// ignore canceled calls, because it most likely was canceled by app code
		Timber.e(t);

		if (t instanceof SSLHandshakeException || t instanceof UnknownServiceException) {
			showError(R.string.error_mediathek_ssl_error);
		} else {
			showError(R.string.error_mediathek_info_not_available);
		}
	}
}
 
Example 25
Project: infoarchive-sip-sdk   File: WhenMakingHttpCallsUsingApache.java   View source code 6 votes vote down vote up
@Test
public void shouldAllowCustomProcessingOfResponse() throws IOException {
  String uri = "http://google.com";
  String expected = randomString();
  ResponseFactory<String> responseFactory = (resp, closer) -> {
    return expected;
  };

  try {
    String actual = httpClient.get(uri, Collections.emptyList(), responseFactory);

    assertEquals("Response", expected, actual);
  } catch (HttpException e) {
    Throwable cause = e.getCause();
    if (cause instanceof SSLHandshakeException || cause instanceof UnknownHostException) {
      // This can happen when on a VPN and the company blocks certain TLS traffic
      return;
    }
    throw e;
  }
}
 
Example 26
Project: client-java-httpclient-repacked   File: TestSSLSocketFactory.java   View source code 6 votes vote down vote up
@Test(expected=SSLHandshakeException.class)
public void testSSLTrustVerification() throws Exception {
    final SSLContext serverSSLContext = SSLContexts.custom()
            .useProtocol("TLS")
            .loadTrustMaterial(keystore)
            .loadKeyMaterial(keystore, "nopassword".toCharArray())
            .build();

    this.localServer = new LocalTestServer(serverSSLContext);
    this.localServer.registerDefaultHandlers();
    this.localServer.start();

    final HttpHost host = new HttpHost("localhost", 443, "https");
    final HttpContext context = new BasicHttpContext();
    // Use default SSL context
    final SSLContext defaultsslcontext = SSLContexts.createDefault();

    final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(defaultsslcontext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    final Socket socket = socketFactory.createSocket(context);
    final InetSocketAddress remoteAddress = this.localServer.getServiceAddress();
    socketFactory.connectSocket(0, socket, host, remoteAddress, null, context);
}
 
Example 27
Project: conscrypt   File: ConscryptSocketTest.java   View source code 6 votes vote down vote up
@Test
public void test_setEnabledProtocols_FiltersSSLv3_HandshakeException() throws Exception {
    TestConnection connection = new TestConnection(new X509Certificate[] {cert, ca}, certKey);

    connection.clientHooks = new ClientHooks() {
        @Override
        public AbstractConscryptSocket createSocket(ServerSocket listener) throws IOException {
            AbstractConscryptSocket socket = super.createSocket(listener);
            socket.setEnabledProtocols(new String[] {"SSLv3"});
            assertEquals(
                    "SSLv3 should be filtered out", 0, socket.getEnabledProtocols().length);
            return socket;
        }
    };

    connection.doHandshake();
    assertThat(connection.clientException, instanceOf(SSLHandshakeException.class));
    assertTrue(
            connection.clientException.getMessage().contains("SSLv3 is no longer supported"));
    assertThat(connection.serverException, instanceOf(SSLHandshakeException.class));

    assertFalse(connection.clientHooks.isHandshakeCompleted);
    assertFalse(connection.serverHooks.isHandshakeCompleted);
}
 
Example 28
Project: conscrypt   File: NativeSsl.java   View source code 6 votes vote down vote up
private void setTlsChannelId(OpenSSLKey channelIdPrivateKey) throws SSLException {
    if (!parameters.channelIdEnabled) {
        return;
    }

    if (parameters.getUseClientMode()) {
        // Client-side TLS Channel ID
        if (channelIdPrivateKey == null) {
            throw new SSLHandshakeException("Invalid TLS channel ID key specified");
        }
        NativeCrypto.SSL_set1_tls_channel_id(ssl, channelIdPrivateKey.getNativeRef());
    } else {
        // Server-side TLS Channel ID
        NativeCrypto.SSL_enable_tls_channel_id(ssl);
    }
}
 
Example 29
Project: conscrypt   File: SSLEngineTest.java   View source code 6 votes vote down vote up
@Test
public void test_SSLEngine_beginHandshake_noKeyStore() throws Exception {
    TestSSLContext c = TestSSLContext.newBuilder()
                               .useDefaults(false)
                               .clientContext(SSLContext.getDefault())
                               .serverContext(SSLContext.getDefault())
                               .build();
    SSLEngine[] p = null;
    try {
        // TODO Fix KnownFailure AlertException "NO SERVER CERTIFICATE FOUND"
        // ServerHandshakeImpl.selectSuite should not select a suite without a required cert
        p = TestSSLEnginePair.connect(c, null);
        fail();
    } catch (SSLHandshakeException expected) {
        // Ignored.
    } finally {
        if (p != null) {
            TestSSLEnginePair.close(p);
        }
    }
    c.close();
}
 
Example 30
Project: conscrypt   File: SSLEngineTest.java   View source code 6 votes vote down vote up
/**
 * http://code.google.com/p/android/issues/detail?id=31903
 * This test case verifies that if the server requires a client cert
 * (setNeedClientAuth) but the client does not provide one SSL connection
 * establishment will fail
 */
@Test
public void test_SSLEngine_clientAuthNeededNoClientCert() throws Exception {
    TestSSLContext clientAuthContext =
            TestSSLContext.create(TestKeyStore.getClient(), TestKeyStore.getServer());
    TestSSLEnginePair p = null;
    try {
        p = TestSSLEnginePair.create(clientAuthContext, new TestSSLEnginePair.Hooks() {
            @Override
            void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
                server.setNeedClientAuth(true);
            }
        });
        fail();
    } catch (SSLHandshakeException expected) {
        // Ignored.
    } finally {
        clientAuthContext.close();
        if (p != null) {
            p.close();
        }
    }
}
 
Example 31
Project: vespa   File: HTTPSearcher.java   View source code 6 votes vote down vote up
@Override
public boolean retryRequest(IOException e, int executionCount, HttpContext httpContext) {
    if (e == null) {
        throw new IllegalArgumentException("Exception parameter may not be null");
    }
    if (executionCount > retries) {
        return false;
    }
    if (e instanceof NoHttpResponseException) {
        // Retry if the server dropped connection on us
        return true;
    }
    if (e instanceof InterruptedIOException) {
        // Timeout from federation layer
        return false;
    }
    if (e instanceof UnknownHostException) {
        // Unknown host
        return false;
    }
    if (e instanceof SSLHandshakeException) {
        // SSL handshake exception
        return false;
    }
    return true;
}
 
Example 32
Project: cloud-sql-jdbc-socket-factory   File: SslSocketFactory.java   View source code 6 votes vote down vote up
public Socket create(String instanceName) throws IOException {
  try {
    return createAndConfigureSocket(instanceName, CertificateCaching.USE_CACHE);
  } catch (SSLHandshakeException e) {
    logger.warning(
        String.format(
            "SSL handshake failed for Cloud SQL instance [%s], "
                + "retrying with new certificate.\n%s",
            instanceName,
            Throwables.getStackTraceAsString(e)));

    if (!forcedRenewRateLimiter.tryAcquire()) {
      logger.warning(
          String.format(
              "Renewing too often, rate limiting certificate renewal for Cloud SQL "
                  + "instance [%s].",
              instanceName));
      forcedRenewRateLimiter.acquire();
    }
    return createAndConfigureSocket(instanceName, CertificateCaching.BYPASS_CACHE);
  }
}
 
Example 33
Project: jdk8u_jdk   File: ECDHCrypt.java   View source code 6 votes vote down vote up
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example 34
Project: jdk8u_jdk   File: JConsole.java   View source code 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example 35
Project: jdk8u_jdk   File: JMXStartStopTest.java   View source code 6 votes vote down vote up
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof NoSuchObjectException ||
                t instanceof ConnectException ||
                t instanceof SSLHandshakeException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
 
Example 36
Project: lookaside_java-1.8.0-openjdk   File: DHCrypt.java   View source code 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
 
Example 37
Project: lookaside_java-1.8.0-openjdk   File: ECDHCrypt.java   View source code 6 votes vote down vote up
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example 38
Project: lookaside_java-1.8.0-openjdk   File: JConsole.java   View source code 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example 39
Project: lookaside_java-1.8.0-openjdk   File: JMXStartStopTest.java   View source code 6 votes vote down vote up
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof NoSuchObjectException ||
                t instanceof ConnectException ||
                t instanceof SSLHandshakeException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
 
Example 40
Project: GitHub   File: RetryAndFollowUpInterceptor.java   View source code 5 votes vote down vote up
private boolean isRecoverable(IOException e, boolean requestSendStarted) {
  // If there was a protocol problem, don't recover.
  if (e instanceof ProtocolException) {
    return false;
  }

  // If there was an interruption don't recover, but if there was a timeout connecting to a route
  // we should try the next route (if there is one).
  if (e instanceof InterruptedIOException) {
    return e instanceof SocketTimeoutException && !requestSendStarted;
  }

  // Look for known client-side or negotiation errors that are unlikely to be fixed by trying
  // again with a different route.
  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;
  }

  // An example of one we might want to retry with a different route is a problem connecting to a
  // proxy and would manifest as a standard IOException. Unless it is one we know we should not
  // retry, we return true and try a new route.
  return true;
}