Java Code Examples for javax.net.ssl.SSLHandshakeException

The following examples show how to use javax.net.ssl.SSLHandshakeException. These examples are extracted from open source projects. 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 Project: jdk8u-jdk   Source File: JConsole.java    License: GNU General Public License v2.0 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 2
Source Project: timely   Source File: TimelyExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    // ignore SSLHandshakeException when using a self-signed server certificate
    if (ignoreSslHandshakeErrors && cause.getCause() instanceof SSLHandshakeException) {
        return;
    }
    LOG.error("Unhandled exception in pipeline", cause);
    if (cause instanceof TimelyException) {
        this.sendHttpError(ctx, (TimelyException) cause);
    } else if (null != cause.getCause() && cause.getCause() instanceof TimelyException) {
        this.sendHttpError(ctx, (TimelyException) cause.getCause());
    } else {
        TimelyException e = new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), cause.getMessage(),
                "");
        this.sendHttpError(ctx, e);
    }
}
 
Example 3
private int getApiErrorCode(final Exception e) {
    if (!service.hasInternetConnection()) {
        return API_ERROR_AIRPLANE_MODE;
    } else if (e instanceof UnknownHostException) {
        return API_ERROR_UNKNOWN_HOST;
    } else if (e instanceof ConnectException) {
        return API_ERROR_CONNECT;
    } else if (e instanceof SSLHandshakeException) {
        return API_ERROR_SSL_HANDSHAKE;
    } else if (e instanceof SSLPeerUnverifiedException || e instanceof CertificateException) {
        return API_ERROR_SSL_CERTIFICATE;
    } else if (e instanceof SSLException || e instanceof GeneralSecurityException) {
        return API_ERROR_SSL_GENERAL;
    } else if (e instanceof SocketTimeoutException) {
        return API_ERROR_TIMEOUT;
    } else {
        Log.d(Config.LOGTAG, e.getClass().getName());
        return API_ERROR_OTHER;
    }
}
 
Example 4
Source Project: openjdk-jdk9   Source File: DHCrypt.java    License: GNU General Public License v2.0 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 5
Source Project: jdk8u_jdk   Source File: ECDHCrypt.java    License: GNU General Public License v2.0 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 6
Source Project: jdk8u60   Source File: JMXStartStopTest.java    License: GNU General Public License v2.0 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 7
@Override
public SecretKey deriveKey(String algorithm,
        AlgorithmParameterSpec params) throws IOException {
    KeySchedule ks = KeySchedule.valueOf(algorithm);
    try {
        HKDF hkdf = new HKDF(cs.hashAlg.name);
        byte[] hkdfInfo =
                createHkdfInfo(ks.label, ks.getKeyLength(cs));
        return hkdf.expand(secret, hkdfInfo,
                ks.getKeyLength(cs),
                ks.getAlgorithm(cs, algorithm));
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException)(new SSLHandshakeException(
            "Could not generate secret").initCause(gse));
    }
}
 
Example 8
Source Project: openjsse   Source File: ECDHKeyExchange.java    License: GNU General Public License v2.0 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        byte[] encodedPoint) throws SSLHandshakeException {
    try {

        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);

        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKey pubKey = (ECPublicKey)kf.generatePublic(spec);

        // check constraints of ECPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), pubKey)) {
            throw new SSLHandshakeException(
                "ECPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate ECPublicKey").initCause(e);
    }
}
 
Example 9
Source Project: hottub   Source File: JMXStartStopTest.java    License: GNU General Public License v2.0 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 10
Source Project: dragonwell8_jdk   Source File: DHCrypt.java    License: GNU General Public License v2.0 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 11
Source Project: dragonwell8_jdk   Source File: ECDHCrypt.java    License: GNU General Public License v2.0 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 12
Source Project: jdk8u60   Source File: JConsole.java    License: GNU General Public License v2.0 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 13
Source Project: dropbox-sdk-java   Source File: NetworkIOException.java    License: MIT License 6 votes vote down vote up
private static String computeMessage(IOException ex) {
    String message = ex.getMessage();

    // For CertPathValidationErrors, the CertPath is in the exception object but not
    // in the exception message.  Pull it out into the message, because it would be
    // useful for debugging.
    if (ex instanceof SSLHandshakeException) {
        Throwable innerCause = ex.getCause();
        if (innerCause instanceof CertPathValidatorException) {
            CertPathValidatorException cpve = (CertPathValidatorException) innerCause;
            message += "[CERT PATH: " + cpve.getCertPath() + "]";
        }
    }

    return message;
}
 
Example 14
Source Project: firebase-android-sdk   Source File: Datastore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Determine whether the given status maps to the error that GRPC-Java throws when an Android
 * device is missing required SSL Ciphers.
 *
 * <p>This error is non-recoverable and must be addressed by the app developer.
 */
public static boolean isMissingSslCiphers(Status status) {
  Status.Code code = status.getCode();
  Throwable t = status.getCause();

  // Check for the presence of a cipher error in the event of an SSLHandshakeException. This is
  // the special case of SSLHandshakeException that contains the cipher error.
  boolean hasCipherError = false;
  if (t instanceof SSLHandshakeException && t.getMessage().contains("no ciphers available")) {
    hasCipherError = true;
  }

  return Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP
      && code.equals(Status.Code.UNAVAILABLE)
      && hasCipherError;
}
 
Example 15
@Override
public KeyMaterial requested(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals) {
    final ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
    try {
        final Set<String> keyTypesSet = supportedClientKeyTypes(keyTypeBytes);
        final String[] keyTypes = keyTypesSet.toArray(new String[keyTypesSet.size()]);
        final X500Principal[] issuers;
        if (asn1DerEncodedPrincipals == null) {
            issuers = null;
        } else {
            issuers = new X500Principal[asn1DerEncodedPrincipals.length];
            for (int i = 0; i < asn1DerEncodedPrincipals.length; i++) {
                issuers[i] = new X500Principal(asn1DerEncodedPrincipals[i]);
            }
        }
        return keyManagerHolder.keyMaterial(engine, keyTypes, issuers);
    } catch (Throwable cause) {
        logger.debug("request of key failed", cause);
        SSLHandshakeException e = new SSLHandshakeException("General OpenSslEngine problem");
        e.initCause(cause);
        engine.handshakeException = e;
        return null;
    }
}
 
Example 16
Source Project: jdk8u60   Source File: DHCrypt.java    License: GNU General Public License v2.0 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 17
Source Project: Bytecoder   Source File: CertificateStatus.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void send(HandshakeOutStream s) throws IOException {
    s.putInt8(statusType.id);
    if (statusType == CertStatusRequestType.OCSP) {
        s.putBytes24(encodedResponses.get(0));
    } else if (statusType == CertStatusRequestType.OCSP_MULTI) {
        s.putInt24(encodedResponsesLen);
        for (byte[] respBytes : encodedResponses) {
            if (respBytes != null) {
                s.putBytes24(respBytes);
            } else {
                s.putBytes24(null);
            }
        }
    } else {
        // It is highly unlikely that we will fall into this section
        // of the code.
        throw new SSLHandshakeException("Unsupported status_type: " +
                statusType.id);
    }
}
 
Example 18
@Override
public Answer<String> getAnswerForRequestStringFromServer() {
    return new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            String url = (String) invocation.getArguments()[0];
            String requestMethod = (String) invocation.getArguments()[1];
            String jsonPayload = (String) invocation.getArguments()[2];

            if (url.contains("/provider.json")) {
                //download provider json
                return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json"));
            } else if (url.contains("/ca.crt")) {
                //download provider ca cert
                return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem"));
            } else if (url.contains("config/eip-service.json")) {
                // download provider service json containing gateways, locations and openvpn settings
                throw new SSLHandshakeException("Invalid provider CA certificate");
            } else if (url.contains("/users.json")) {
                //create new user
                //TODO: implement me
            } else if (url.contains("/sessions.json")) {
                //srp auth: sendAToSRPServer
                //TODO: implement me
            } else if (url.contains("/sessions/parmegvtest10.json")){
                //srp auth: sendM1ToSRPServer
                //TODO: implement me
            }

            return null;
        }
    };
}
 
Example 19
Source Project: bluemix-parking-meter   Source File: HttpURLConnectionImpl.java    License: MIT License 5 votes vote down vote up
private boolean isRecoverable(IOException e) {
  // If the problem was a CertificateException from the X509TrustManager,
  // do not retry, we didn't have an abrupt server initiated exception.
  boolean sslFailure =
      e instanceof SSLHandshakeException && e.getCause() instanceof CertificateException;
  boolean protocolFailure = e instanceof ProtocolException;
  return !sslFailure && !protocolFailure;
}
 
Example 20
@Test
public void testPemClientAuthFailure() throws Exception {

    try (TestServer testServer = new TestServer("sslConfigurator/pem/truststore.jks",
            "sslConfigurator/pem/node1-keystore.jks", "secret", true)) {
        Path rootCaPemPath = FileHelper.getAbsoluteFilePathFromClassPath("sslConfigurator/pem/root-ca.pem");

        Settings settings = Settings.builder()
                .put("prefix.pemtrustedcas_filepath", rootCaPemPath.getFileName().toString())
                .put("prefix.enable_ssl", "true").put("path.home", rootCaPemPath.getParent().toString())
                .put("prefix.enable_ssl_client_auth", "true").put("prefix.pemcert_filepath", "wrong-kirk.pem")
                .put("prefix.pemkey_filepath", "wrong-kirk.key").put("prefix.pemkey_password", "G0CVtComen4a")
                .build();
        Path configPath = rootCaPemPath.getParent();

        SettingsBasedSSLConfigurator sbsc = new SettingsBasedSSLConfigurator(settings, configPath, "prefix");

        SSLConfig sslConfig = sbsc.buildSSLConfig();

        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslConfig.toSSLConnectionSocketFactory()).build()) {

            // Due to some race condition in Java's internal network stack, this can be one
            // of the following exceptions

            thrown.expect(either(instanceOf(SocketException.class)).or(instanceOf(SSLHandshakeException.class))
                    .or(instanceOf(SSLException.class)) // Java 11: javax.net.ssl.SSLException: readHandshakeRecord
            );

            try (CloseableHttpResponse response = httpClient.execute(new HttpGet(testServer.getUri()))) {
                Assert.fail("Connection should have failed due to wrong client cert");
            }
        }
    }
}
 
Example 21
Source Project: Bytecoder   Source File: ECDHKeyExchange.java    License: Apache License 2.0 5 votes vote down vote up
SecretKey getAgreedSecret(
        PublicKey peerPublicKey) throws SSLHandshakeException {

    try {
        KeyAgreement ka = KeyAgreement.getInstance("ECDH");
        ka.init(privateKey);
        ka.doPhase(peerPublicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example 22
Source Project: quarkus   Source File: KubernetesClientErrorHanlder.java    License: Apache License 2.0 5 votes vote down vote up
public static void handle(Exception e) {
    if (e.getCause() instanceof SSLHandshakeException) {
        LOG.error(
                "The application could not be deployed to the cluster because the Kubernetes API Server certificates are not trusted. The certificates can be configured using the relevant configuration propertiers under the 'quarkus.kubernetes-client' config root, or \"quarkus.kubernetes-client.trust-certs=true\" can be set to explicitly trust the certificates (not recommended)");
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e);
        }
    }
}
 
Example 23
Source Project: TencentKona-8   Source File: ECDHCrypt.java    License: GNU General Public License v2.0 5 votes vote down vote up
SecretKey getAgreedSecret(
        PublicKey peerPublicKey) throws SSLHandshakeException {

    try {
        KeyAgreement ka = JsseJce.getKeyAgreement("ECDH");
        ka.init(privateKey);
        ka.doPhase(peerPublicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example 24
Source Project: vertx-mail-client   Source File: MailSslTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void mailTestSSLNoTrust(TestContext testContext) {
  this.testContext = testContext;
  startServer(SERVER2_JKS);
  final MailConfig config = new MailConfig("localhost", 1465, StartTLSOptions.DISABLED, LoginOption.DISABLED)
      .setSsl(true);
  MailClient mailClient = MailClient.create(vertx, config);
  testException(mailClient, SSLHandshakeException.class);
}
 
Example 25
Source Project: ignite   Source File: RestExecutorSelfTest.java    License: Apache License 2.0 5 votes vote down vote up
/** */
 @Test
 public void differentCiphers1() throws Exception {
     ruleForExpectedException.expect(SSLHandshakeException.class);
     checkRest(
         nodeConfiguration(JETTY_WITH_CIPHERS_1),
         HTTPS_URI,
         resolvePath("client.jks"), "123456",
         resolvePath("ca.jks"), "123456",
         CIPHER_2
     );
}
 
Example 26
Source Project: reader   Source File: HttpURLConnectionImpl.java    License: MIT License 5 votes vote down vote up
private boolean isRecoverable(IOException e) {
  // If the problem was a CertificateException from the X509TrustManager,
  // do not retry, we didn't have an abrupt server initiated exception.
  boolean sslFailure =
      e instanceof SSLHandshakeException && e.getCause() instanceof CertificateException;
  boolean protocolFailure = e instanceof ProtocolException;
  return !sslFailure && !protocolFailure;
}
 
Example 27
Source Project: qpid-broker-j   Source File: TCPandSSLTransportTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTLSv1_3SupportOnSSLOnlyPort() throws Exception
{
    assumeThat("Java 11 or above is required", isJava11OrAbove(), is(true));
    try
    {
        checkHandshakeWithTlsProtocol("TLSv1.3", Transport.SSL);
    }
    catch(SSLHandshakeException e)
    {
        LOGGER.error("Should be able to connect using TLSv1.3", e);
        fail("Should be able to connect using TLSv1.3");
    }
}
 
Example 28
Source Project: reader   Source File: RouteDatabase.java    License: MIT License 5 votes vote down vote up
/** Records a failure connecting to {@code failedRoute}. */
public synchronized void failed(Route failedRoute, IOException failure) {
  failedRoutes.add(failedRoute);

  if (!(failure instanceof SSLHandshakeException)) {
    // If the problem was not related to SSL then it will also fail with
    // a different TLS mode therefore we can be proactive about it.
    failedRoutes.add(failedRoute.flipTlsMode());
  }
}
 
Example 29
Source Project: styx   Source File: HttpPipelineHandler.java    License: Apache License 2.0 5 votes vote down vote up
private static Throwable sslException(Throwable cause) {
    if (cause.getCause() != null && cause.getCause() instanceof SSLHandshakeException) {
        return cause.getCause();
    } else {
        return null;
    }
}
 
Example 30
Source Project: jdk8u_jdk   Source File: ECDHCrypt.java    License: GNU General Public License v2.0 5 votes vote down vote up
SecretKey getAgreedSecret(
        PublicKey peerPublicKey) throws SSLHandshakeException {

    try {
        KeyAgreement ka = JsseJce.getKeyAgreement("ECDH");
        ka.init(privateKey);
        ka.doPhase(peerPublicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}