Search in sources :

Example 61 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project cas by apereo.

the class ValidateEndpointCommand method tlsConnectionReport.

private static void tlsConnectionReport(final HttpsURLConnection httpsConnection) {
    val systemTrustManagers = getSystemTrustManagers();
    final Certificate[] certificates;
    try {
        certificates = httpsConnection.getServerCertificates();
    } catch (final SSLPeerUnverifiedException e) {
        LoggingUtils.error(LOGGER, e);
        throw new RuntimeException(e);
    }
    val serverCertificates = Arrays.copyOf(certificates, certificates.length, X509Certificate[].class);
    LOGGER.info("Server provided certs: ");
    for (val certificate : serverCertificates) {
        val validity = FunctionUtils.doAndHandle(o -> {
            certificate.checkValidity();
            return "valid";
        }, e -> "invalid: " + e.getMessage()).apply(certificate);
        LOGGER.info("\tsubject: [{}]", certificate.getSubjectDN().getName());
        LOGGER.info("\tissuer: [{}]", certificate.getIssuerDN().getName());
        LOGGER.info("\texpiration: [{}] - [{}] [{}]", certificate.getNotBefore(), certificate.getNotAfter(), validity);
        LOGGER.info("\ttrust anchor [{}]", checkTrustedCertStatus(certificate, systemTrustManagers));
        LOGGER.info("---");
    }
}
Also used : lombok.val(lombok.val) ShellCommandGroup(org.springframework.shell.standard.ShellCommandGroup) HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) SSLContext(javax.net.ssl.SSLContext) Arrays(java.util.Arrays) SneakyThrows(lombok.SneakyThrows) URL(java.net.URL) TrustManager(javax.net.ssl.TrustManager) ShellMethod(org.springframework.shell.standard.ShellMethod) StringUtils(org.apache.commons.lang3.StringUtils) ShellOption(org.springframework.shell.standard.ShellOption) ArrayList(java.util.ArrayList) LoggingUtils(org.apereo.cas.util.LoggingUtils) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) Proxy(java.net.Proxy) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Unchecked(org.jooq.lambda.Unchecked) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) lombok.val(lombok.val) KeyStore(java.security.KeyStore) ShellComponent(org.springframework.shell.standard.ShellComponent) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) Slf4j(lombok.extern.slf4j.Slf4j) Certificate(java.security.cert.Certificate) X509TrustManager(javax.net.ssl.X509TrustManager) BufferedReader(java.io.BufferedReader) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 62 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project JGroups by belaban.

the class CertficateCNMatcher method verify.

public void verify(SSLSession session) throws SecurityException {
    Principal principal = null;
    try {
        principal = session.getPeerPrincipal();
        String name = principal.getName();
        Matcher m = pattern.matcher(name);
        boolean find = m.find();
        if (!find)
            throw new SecurityException(String.format("pattern '%s' not found in peer certificate '%s'", cn_name, name));
        else
            System.out.printf("** pattern '%s' found in peer certificate '%s'\n", cn_name, name);
    } catch (SSLPeerUnverifiedException e) {
        throw new SecurityException(e);
    }
}
Also used : Matcher(java.util.regex.Matcher) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) Principal(java.security.Principal)

Example 63 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project vertx-tcp-eventbus-bridge by vert-x3.

the class TcpEventBusBridgeEventTest method before.

@Before
public void before(TestContext context) {
    vertx = Vertx.vertx();
    final Async async = context.async();
    vertx.eventBus().consumer("hello", (Message<JsonObject> msg) -> msg.reply(new JsonObject().put("value", "Hello " + msg.body().getString("value"))));
    vertx.eventBus().consumer("echo", (Message<JsonObject> msg) -> msg.reply(msg.body()));
    vertx.setPeriodic(1000, __ -> vertx.eventBus().send("ping", new JsonObject().put("value", "hi")));
    sslKeyPairCerts = new SSLKeyPairCerts().createTwoWaySSL();
    TcpEventBusBridge bridge = TcpEventBusBridge.create(vertx, new BridgeOptions().addInboundPermitted(new PermittedOptions().setAddress("hello")).addInboundPermitted(new PermittedOptions().setAddress("echo")).addInboundPermitted(new PermittedOptions().setAddress("test")).addOutboundPermitted(new PermittedOptions().setAddress("echo")).addOutboundPermitted(new PermittedOptions().setAddress("ping")), new NetServerOptions().setClientAuth(ClientAuth.REQUEST).setSsl(true).setTrustStoreOptions(sslKeyPairCerts.getServerTrustStore()).setKeyStoreOptions(sslKeyPairCerts.getServerKeyStore()), be -> {
        logger.info("Handled a bridge event " + be.getRawMessage());
        if (be.socket().isSsl()) {
            try {
                for (Certificate c : be.socket().peerCertificates()) {
                    logger.info(((X509Certificate) c).getSubjectDN().toString());
                }
            } catch (SSLPeerUnverifiedException e) {
                throw new RuntimeException("Failed to get peer certificates chain", e);
            }
        }
        be.complete(true);
    });
    bridge.listen(7000, res -> {
        context.assertTrue(res.succeeded());
        async.complete();
    });
}
Also used : Message(io.vertx.core.eventbus.Message) Async(io.vertx.ext.unit.Async) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) JsonObject(io.vertx.core.json.JsonObject) BridgeOptions(io.vertx.ext.bridge.BridgeOptions) PermittedOptions(io.vertx.ext.bridge.PermittedOptions) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) Before(org.junit.Before)

Example 64 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project hono by eclipse.

the class X509AuthHandlerTest method testParseCredentialsIncludesMqttClientId.

/**
 * Verifies that the handler includes the MQTT client identifier in the authentication
 * information retrieved from a device's CONNECT packet.
 *
 * @param ctx The vert.x test context.
 * @throws SSLPeerUnverifiedException if the client certificate cannot be determined.
 */
@SuppressWarnings("unchecked")
@Test
public void testParseCredentialsIncludesMqttClientId(final VertxTestContext ctx) throws SSLPeerUnverifiedException {
    // GIVEN an auth handler configured with an auth provider
    final JsonObject authInfo = new JsonObject().put(RequestResponseApiConstants.FIELD_PAYLOAD_SUBJECT_DN, "CN=device").put(RequestResponseApiConstants.FIELD_PAYLOAD_TENANT_ID, "tenant");
    when(clientAuth.validateClientCertificate(any(Certificate[].class), any(List.class), (SpanContext) any())).thenReturn(Future.succeededFuture(authInfo));
    // WHEN trying to authenticate a request that contains a client certificate
    final X509Certificate clientCert = getClientCertificate("CN=device", "CN=tenant");
    final SSLSession sslSession = mock(SSLSession.class);
    when(sslSession.getPeerCertificates()).thenReturn(new X509Certificate[] { clientCert });
    final MqttEndpoint endpoint = mock(MqttEndpoint.class);
    when(endpoint.isSsl()).thenReturn(true);
    when(endpoint.sslSession()).thenReturn(sslSession);
    when(endpoint.clientIdentifier()).thenReturn("mqtt-device");
    final MqttConnectContext context = MqttConnectContext.fromConnectPacket(endpoint, span);
    authHandler.parseCredentials(context).onComplete(ctx.succeeding(info -> {
        ctx.verify(() -> {
            assertThat(info.getString(RequestResponseApiConstants.FIELD_PAYLOAD_SUBJECT_DN)).isEqualTo("CN=device");
            assertThat(info.getString(RequestResponseApiConstants.FIELD_PAYLOAD_TENANT_ID)).isEqualTo("tenant");
            assertThat(info.getString(X509AuthHandler.PROPERTY_CLIENT_IDENTIFIER)).isEqualTo("mqtt-device");
        });
        ctx.completeNow();
    }));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) X500Principal(javax.security.auth.x500.X500Principal) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) SSLSession(javax.net.ssl.SSLSession) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) JsonObject(io.vertx.core.json.JsonObject) X509Authentication(org.eclipse.hono.adapter.auth.device.X509Authentication) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) RequestResponseApiConstants(org.eclipse.hono.util.RequestResponseApiConstants) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Test(org.junit.jupiter.api.Test) List(java.util.List) Certificate(java.security.cert.Certificate) DeviceCredentialsAuthProvider(org.eclipse.hono.adapter.auth.device.DeviceCredentialsAuthProvider) Span(io.opentracing.Span) SubjectDnCredentials(org.eclipse.hono.adapter.auth.device.SubjectDnCredentials) Mockito.mock(org.mockito.Mockito.mock) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) SSLSession(javax.net.ssl.SSLSession) JsonObject(io.vertx.core.json.JsonObject) List(java.util.List) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.jupiter.api.Test)

Example 65 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project fabric8 by jboss-fuse.

the class KubernetesHelper method isServiceSsl.

public static boolean isServiceSsl(String host, int port, boolean trustAllCerts) {
    try {
        LOG.info("Checking if a service is SSL on " + host + ":" + port);
        SSLSocketFactory sslsocketfactory;
        if (trustAllCerts) {
            sslsocketfactory = TrustEverythingSSLTrustManager.getTrustingSSLSocketFactory();
        } else {
            sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        }
        Socket socket = sslsocketfactory.createSocket();
        // Connect, with an explicit timeout value
        socket.connect(new InetSocketAddress(host, port), 1 * 1000);
        try {
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            // Write a test byte to get a reaction :)
            out.write(1);
            while (in.available() > 0) {
                System.out.print(in.read());
            }
            return true;
        } finally {
            LOG.info("Checked if a service is SSL on " + host + ":" + port);
            socket.close();
        }
    } catch (SSLHandshakeException e) {
        LOG.error("SSL handshake failed - this probably means that you need to trust the kubernetes root SSL certificate or set the environment variable " + Utils.convertSystemPropertyNameToEnvVar(io.fabric8.kubernetes.client.Config.KUBERNETES_TRUST_CERT_SYSTEM_PROPERTY), e);
    } catch (SSLProtocolException e) {
        LOG.error("SSL protocol error", e);
    } catch (SSLKeyException e) {
        LOG.error("Bad SSL key", e);
    } catch (SSLPeerUnverifiedException e) {
        LOG.error("Could not verify server", e);
    } catch (SSLException e) {
        LOG.debug("Address does not appear to be SSL-enabled - falling back to http", e);
    } catch (IOException e) {
        LOG.debug("Failed to validate service", e);
    }
    return false;
}
Also used : SSLProtocolException(javax.net.ssl.SSLProtocolException) InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SSLKeyException(javax.net.ssl.SSLKeyException) SSLException(javax.net.ssl.SSLException) Socket(java.net.Socket) SSLHandshakeException(javax.net.ssl.SSLHandshakeException)

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