Search in sources :

Example 1 with X509Certificate

use of javax.security.cert.X509Certificate in project vert.x by eclipse.

the class NetTest method testTLS.

void testTLS(boolean clientCert, boolean clientTrust, boolean serverCert, boolean serverTrust, boolean requireClientAuth, boolean clientTrustAll, boolean shouldPass, boolean startTLS, String[] enabledCipherSuites, String[] enabledSecureTransportProtocols) throws Exception {
    server.close();
    NetServerOptions options = new NetServerOptions();
    if (!startTLS) {
        options.setSsl(true);
    }
    if (serverTrust) {
        options.setTrustStoreOptions(new JksOptions().setPath("tls/server-truststore.jks").setPassword("wibble"));
    }
    if (serverCert) {
        options.setKeyStoreOptions(new JksOptions().setPath("tls/server-keystore.jks").setPassword("wibble"));
    }
    if (requireClientAuth) {
        options.setClientAuth(ClientAuth.REQUIRED);
    }
    for (String suite : enabledCipherSuites) {
        options.addEnabledCipherSuite(suite);
    }
    for (String protocol : enabledSecureTransportProtocols) {
        options.addEnabledSecureTransportProtocol(protocol);
    }
    Consumer<NetSocket> certificateChainChecker = socket -> {
        try {
            X509Certificate[] certs = socket.peerCertificateChain();
            if (clientCert) {
                assertNotNull(certs);
                assertEquals(1, certs.length);
            } else {
                assertNull(certs);
            }
        } catch (SSLPeerUnverifiedException e) {
            assertTrue(clientTrust || clientTrustAll);
        }
    };
    options.setPort(4043);
    server = vertx.createNetServer(options);
    Handler<NetSocket> serverHandler = socket -> {
        if (socket.isSsl()) {
            certificateChainChecker.accept(socket);
        }
        AtomicBoolean upgradedServer = new AtomicBoolean();
        AtomicInteger upgradedServerCount = new AtomicInteger();
        socket.handler(buff -> {
            socket.write(buff);
            if (startTLS) {
                if (upgradedServer.compareAndSet(false, true)) {
                    assertFalse(socket.isSsl());
                    socket.upgradeToSsl(v -> {
                        certificateChainChecker.accept(socket);
                        upgradedServerCount.incrementAndGet();
                        assertTrue(socket.isSsl());
                    });
                } else {
                    assertTrue(socket.isSsl());
                    assertEquals(1, upgradedServerCount.get());
                }
            } else {
                assertTrue(socket.isSsl());
            }
        });
    };
    server.connectHandler(serverHandler).listen(ar -> {
        client.close();
        NetClientOptions clientOptions = new NetClientOptions();
        if (!startTLS) {
            clientOptions.setSsl(true);
        }
        if (clientTrustAll) {
            clientOptions.setTrustAll(true);
        }
        if (clientTrust) {
            clientOptions.setTrustStoreOptions(new JksOptions().setPath("tls/client-truststore.jks").setPassword("wibble"));
        }
        if (clientCert) {
            clientOptions.setKeyStoreOptions(new JksOptions().setPath("tls/client-keystore.jks").setPassword("wibble"));
        }
        for (String suite : enabledCipherSuites) {
            clientOptions.addEnabledCipherSuite(suite);
        }
        for (String protocol : enabledSecureTransportProtocols) {
            clientOptions.addEnabledSecureTransportProtocol(protocol);
        }
        client = vertx.createNetClient(clientOptions);
        client.connect(4043, "localhost", ar2 -> {
            if (ar2.succeeded()) {
                if (!shouldPass) {
                    fail("Should not connect");
                    return;
                }
                final int numChunks = 100;
                final int chunkSize = 100;
                final List<Buffer> toSend = new ArrayList<>();
                final Buffer expected = Buffer.buffer();
                for (int i = 0; i < numChunks; i++) {
                    Buffer chunk = TestUtils.randomBuffer(chunkSize);
                    toSend.add(chunk);
                    expected.appendBuffer(chunk);
                }
                final Buffer received = Buffer.buffer();
                final NetSocket socket = ar2.result();
                final AtomicBoolean upgradedClient = new AtomicBoolean();
                socket.handler(buffer -> {
                    received.appendBuffer(buffer);
                    if (received.length() == expected.length()) {
                        assertEquals(expected, received);
                        testComplete();
                    }
                    if (startTLS && !upgradedClient.get()) {
                        upgradedClient.set(true);
                        assertFalse(socket.isSsl());
                        socket.upgradeToSsl(v -> {
                            assertTrue(socket.isSsl());
                            for (int i = 1; i < numChunks; i++) {
                                socket.write(toSend.get(i));
                            }
                        });
                    } else {
                        assertTrue(socket.isSsl());
                    }
                });
                int numToSend = startTLS ? 1 : numChunks;
                for (int i = 0; i < numToSend; i++) {
                    socket.write(toSend.get(i));
                }
            } else {
                if (shouldPass) {
                    fail("Should not fail to connect");
                } else {
                    testComplete();
                }
            }
        });
    });
    await();
}
Also used : java.util(java.util) io.vertx.core(io.vertx.core) io.vertx.core.impl(io.vertx.core.impl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cert(io.vertx.test.core.tls.Cert) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) AtomicReference(java.util.concurrent.atomic.AtomicReference) LoggerFactory(io.vertx.core.logging.LoggerFactory) InetAddress(java.net.InetAddress) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReadStream(io.vertx.core.streams.ReadStream) OutputStreamWriter(java.io.OutputStreamWriter) JsonObject(io.vertx.core.json.JsonObject) Assume(org.junit.Assume) Logger(io.vertx.core.logging.Logger) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) BufferedWriter(java.io.BufferedWriter) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Message(io.vertx.core.eventbus.Message) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) X509Certificate(javax.security.cert.X509Certificate) io.vertx.core.net(io.vertx.core.net) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) ClientAuth(io.vertx.core.http.ClientAuth) InternalLoggerFactory(io.netty.util.internal.logging.InternalLoggerFactory) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) TemporaryFolder(org.junit.rules.TemporaryFolder) Trust(io.vertx.test.core.tls.Trust) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) TestUtils.assertIllegalArgumentException(io.vertx.test.core.TestUtils.assertIllegalArgumentException) Buffer(io.vertx.core.buffer.Buffer) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 2 with X509Certificate

use of javax.security.cert.X509Certificate in project netty by netty.

the class SSLEngineTest method testMutualAuthSameCertChain.

@Test(timeout = 30000)
public void testMutualAuthSameCertChain() throws Exception {
    serverSslCtx = SslContextBuilder.forServer(new ByteArrayInputStream(X509_CERT_PEM.getBytes(CharsetUtil.UTF_8)), new ByteArrayInputStream(PRIVATE_KEY_PEM.getBytes(CharsetUtil.UTF_8))).trustManager(new ByteArrayInputStream(X509_CERT_PEM.getBytes(CharsetUtil.UTF_8))).clientAuth(ClientAuth.REQUIRE).sslProvider(sslServerProvider()).build();
    sb = new ServerBootstrap();
    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    final Promise<String> promise = sb.config().group().next().newPromise();
    serverChannel = sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ch.pipeline().addFirst(serverSslCtx.newHandler(ch.alloc()));
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof SslHandshakeCompletionEvent) {
                        Throwable cause = ((SslHandshakeCompletionEvent) evt).cause();
                        if (cause == null) {
                            SSLSession session = ((SslHandler) ctx.pipeline().first()).engine().getSession();
                            X509Certificate[] peerCertificateChain = session.getPeerCertificateChain();
                            Certificate[] peerCertificates = session.getPeerCertificates();
                            if (peerCertificateChain == null) {
                                promise.setFailure(new NullPointerException("peerCertificateChain"));
                            } else if (peerCertificates == null) {
                                promise.setFailure(new NullPointerException("peerCertificates"));
                            } else if (peerCertificateChain.length + peerCertificates.length != 4) {
                                String excTxtFmt = "peerCertificateChain.length:%s, peerCertificates.length:%s";
                                promise.setFailure(new IllegalStateException(String.format(excTxtFmt, peerCertificateChain.length, peerCertificates.length)));
                            } else {
                                for (int i = 0; i < peerCertificateChain.length; i++) {
                                    if (peerCertificateChain[i] == null || peerCertificates[i] == null) {
                                        promise.setFailure(new IllegalStateException("Certificate in chain is null"));
                                        return;
                                    }
                                }
                                promise.setSuccess(null);
                            }
                        } else {
                            promise.setFailure(cause);
                        }
                    }
                }
            });
            serverConnectedChannel = ch;
        }
    }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
    clientSslCtx = SslContextBuilder.forClient().keyManager(new ByteArrayInputStream(CLIENT_X509_CERT_CHAIN_PEM.getBytes(CharsetUtil.UTF_8)), new ByteArrayInputStream(CLIENT_PRIVATE_KEY_PEM.getBytes(CharsetUtil.UTF_8))).trustManager(new ByteArrayInputStream(X509_CERT_PEM.getBytes(CharsetUtil.UTF_8))).sslProvider(sslClientProvider()).build();
    cb = new Bootstrap();
    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    clientChannel = cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ch.pipeline().addLast(new SslHandler(clientSslCtx.newEngine(ch.alloc())));
        }
    }).connect(serverChannel.localAddress()).syncUninterruptibly().channel();
    promise.syncUninterruptibly();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SSLSession(javax.net.ssl.SSLSession) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) X509Certificate(javax.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Certificate(java.security.cert.Certificate) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) X509Certificate(javax.security.cert.X509Certificate) Test(org.junit.Test)

Example 3 with X509Certificate

use of javax.security.cert.X509Certificate in project robovm by robovm.

the class HandshakeCompletedEventTest method test_getPeerCertificateChain.

/**
     * @throws IOException
     * javax.net.ssl.HandshakeCompletedEvent#getPeerCertificateChain()
     */
public final void test_getPeerCertificateChain() throws Exception {
    ByteArrayInputStream bis = new ByteArrayInputStream(certificate.getBytes());
    mySSLSession session = new mySSLSession((X509Certificate[]) null);
    SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
    HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
    try {
        event.getPeerCertificateChain();
        fail("SSLPeerUnverifiedException wasn't thrown");
    } catch (SSLPeerUnverifiedException expected) {
    }
    X509Certificate xc = X509Certificate.getInstance(bis);
    X509Certificate[] xcs = { xc };
    session = new mySSLSession(xcs);
    event = new HandshakeCompletedEvent(socket, session);
    X509Certificate[] res = event.getPeerCertificateChain();
    assertEquals(1, res.length);
}
Also used : HandshakeCompletedEvent(javax.net.ssl.HandshakeCompletedEvent) ByteArrayInputStream(java.io.ByteArrayInputStream) SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) org.apache.harmony.xnet.tests.support.mySSLSession(org.apache.harmony.xnet.tests.support.mySSLSession) X509Certificate(javax.security.cert.X509Certificate)

Example 4 with X509Certificate

use of javax.security.cert.X509Certificate in project robovm by robovm.

the class HandshakeCompletedEventTest method test_getPeerCertificates.

/**
     * @throws IOException
     * javax.net.ssl.HandshakeCompletedEvent#getPeerCertificates()
     */
public final void test_getPeerCertificates() throws IOException {
    mySSLSession session = new mySSLSession("localhost", 1080, null);
    SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
    HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
    try {
        event.getPeerCertificates();
        fail("SSLPeerUnverifiedException wasn't thrown");
    } catch (SSLPeerUnverifiedException expected) {
    }
    session = new mySSLSession((X509Certificate[]) null);
    event = new HandshakeCompletedEvent(socket, session);
    Certificate[] res = event.getPeerCertificates();
    assertEquals(3, res.length);
}
Also used : HandshakeCompletedEvent(javax.net.ssl.HandshakeCompletedEvent) SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) org.apache.harmony.xnet.tests.support.mySSLSession(org.apache.harmony.xnet.tests.support.mySSLSession) X509Certificate(javax.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 5 with X509Certificate

use of javax.security.cert.X509Certificate in project camel by apache.

the class NettyEndpoint method enrichWithClientCertInformation.

/**
     * Enriches the message with client certificate details such as subject name, serial number etc.
     * <p/>
     * If the certificate is unverified then the headers is not enriched.
     *
     * @param sslSession  the SSL session
     * @param message     the message to enrich
     */
protected void enrichWithClientCertInformation(SSLSession sslSession, Message message) {
    try {
        X509Certificate[] certificates = sslSession.getPeerCertificateChain();
        if (certificates != null && certificates.length > 0) {
            X509Certificate cert = certificates[0];
            Principal subject = cert.getSubjectDN();
            if (subject != null) {
                message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_SUBJECT_NAME, subject.getName());
            }
            Principal issuer = cert.getIssuerDN();
            if (issuer != null) {
                message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_ISSUER_NAME, issuer.getName());
            }
            BigInteger serial = cert.getSerialNumber();
            if (serial != null) {
                message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_SERIAL_NO, serial.toString());
            }
            message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_NOT_BEFORE, cert.getNotBefore());
            message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_NOT_AFTER, cert.getNotAfter());
        }
    } catch (SSLPeerUnverifiedException e) {
    // ignore
    }
}
Also used : SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) BigInteger(java.math.BigInteger) X509Certificate(javax.security.cert.X509Certificate) Principal(java.security.Principal)

Aggregations

X509Certificate (javax.security.cert.X509Certificate)10 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)6 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Certificate (java.security.cert.Certificate)2 HandshakeCompletedEvent (javax.net.ssl.HandshakeCompletedEvent)2 SSLSocket (javax.net.ssl.SSLSocket)2 CertificateException (javax.security.cert.CertificateException)2 org.apache.harmony.xnet.tests.support.mySSLSession (org.apache.harmony.xnet.tests.support.mySSLSession)2 Test (org.junit.Test)2 Attribute (cz.metacentrum.perun.core.api.Attribute)1 AttributeNotExistsException (cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException)1 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)1 Bootstrap (io.netty.bootstrap.Bootstrap)1 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)1 Channel (io.netty.channel.Channel)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)1 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)1 SocketChannel (io.netty.channel.socket.SocketChannel)1 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)1