Search in sources :

Example 31 with SSLSession

use of javax.net.ssl.SSLSession 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 32 with SSLSession

use of javax.net.ssl.SSLSession in project netty by netty.

the class SSLEngineTest method mySetupMutualAuth.

private void mySetupMutualAuth(File servertTrustCrtFile, File serverKeyFile, final File serverCrtFile, String serverKeyPassword, File clientTrustCrtFile, File clientKeyFile, File clientCrtFile, String clientKeyPassword) throws InterruptedException, SSLException {
    serverSslCtx = SslContextBuilder.forServer(serverCrtFile, serverKeyFile, serverKeyPassword).sslProvider(sslServerProvider()).trustManager(servertTrustCrtFile).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build();
    clientSslCtx = SslContextBuilder.forClient().sslProvider(sslClientProvider()).trustManager(clientTrustCrtFile).keyManager(clientCrtFile, clientKeyFile, clientKeyPassword).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build();
    serverConnectedChannel = null;
    sb = new ServerBootstrap();
    cb = new Bootstrap();
    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            SSLEngine engine = serverSslCtx.newEngine(ch.alloc());
            engine.setUseClientMode(false);
            engine.setNeedClientAuth(true);
            p.addLast(new SslHandler(engine));
            p.addLast(new MessageDelegatorChannelHandler(serverReceiver, serverLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    if (cause.getCause() instanceof SSLHandshakeException) {
                        serverException = cause.getCause();
                        serverLatch.countDown();
                    } else {
                        serverException = cause;
                        ctx.fireExceptionCaught(cause);
                    }
                }

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == SslHandshakeCompletionEvent.SUCCESS) {
                        try {
                            InputStream in = new FileInputStream(serverCrtFile);
                            try {
                                final byte[] cert = SslContext.X509_CERT_FACTORY.generateCertificate(in).getEncoded();
                                // Verify session
                                SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession();
                                assertEquals(1, session.getPeerCertificates().length);
                                assertArrayEquals(cert, session.getPeerCertificates()[0].getEncoded());
                                assertEquals(1, session.getPeerCertificateChain().length);
                                assertArrayEquals(cert, session.getPeerCertificateChain()[0].getEncoded());
                                assertEquals(1, session.getLocalCertificates().length);
                                assertArrayEquals(cert, session.getLocalCertificates()[0].getEncoded());
                                assertEquals(PRINCIPAL_NAME, session.getLocalPrincipal().getName());
                                assertEquals(PRINCIPAL_NAME, session.getPeerPrincipal().getName());
                            } finally {
                                in.close();
                            }
                        } catch (Throwable cause) {
                            serverException = cause;
                        }
                    }
                }
            });
            serverConnectedChannel = ch;
        }
    });
    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientSslCtx.newHandler(ch.alloc()));
            p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    cause.printStackTrace();
                    if (cause.getCause() instanceof SSLHandshakeException) {
                        clientException = cause.getCause();
                        clientLatch.countDown();
                    } else {
                        ctx.fireExceptionCaught(cause);
                    }
                }
            });
        }
    });
    serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
    int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
    ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SSLEngine(javax.net.ssl.SSLEngine) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) InetSocketAddress(java.net.InetSocketAddress) 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) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) 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) ChannelPipeline(io.netty.channel.ChannelPipeline) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) FileInputStream(java.io.FileInputStream) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 33 with SSLSession

use of javax.net.ssl.SSLSession in project okhttp by square.

the class OkHttpAsync method prepare.

@Override
public void prepare(final Benchmark benchmark) {
    concurrencyLevel = benchmark.concurrencyLevel;
    targetBacklog = benchmark.targetBacklog;
    client = new OkHttpClient.Builder().protocols(benchmark.protocols).dispatcher(new Dispatcher(new ThreadPoolExecutor(benchmark.concurrencyLevel, benchmark.concurrencyLevel, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()))).build();
    if (benchmark.tls) {
        SslClient sslClient = SslClient.localhost();
        SSLSocketFactory socketFactory = sslClient.socketFactory;
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(String s, SSLSession session) {
                return true;
            }
        };
        client = client.newBuilder().sslSocketFactory(socketFactory, sslClient.trustManager).hostnameVerifier(hostnameVerifier).build();
    }
    callback = new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            System.out.println("Failed: " + e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            ResponseBody body = response.body();
            long total = SynchronousHttpClient.readAllAndClose(body.byteStream());
            long finish = System.nanoTime();
            if (VERBOSE) {
                long start = (Long) response.request().tag();
                System.out.printf("Transferred % 8d bytes in %4d ms%n", total, TimeUnit.NANOSECONDS.toMillis(finish - start));
            }
            requestsInFlight.decrementAndGet();
        }
    };
}
Also used : Call(okhttp3.Call) SslClient(okhttp3.internal.tls.SslClient) SSLSession(javax.net.ssl.SSLSession) IOException(java.io.IOException) Dispatcher(okhttp3.Dispatcher) HostnameVerifier(javax.net.ssl.HostnameVerifier) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) Callback(okhttp3.Callback) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 34 with SSLSession

use of javax.net.ssl.SSLSession in project camel by apache.

the class NettyEndpoint method updateMessageHeader.

protected void updateMessageHeader(Message in, ChannelHandlerContext ctx) {
    in.setHeader(NettyConstants.NETTY_CHANNEL_HANDLER_CONTEXT, ctx);
    in.setHeader(NettyConstants.NETTY_REMOTE_ADDRESS, ctx.channel().remoteAddress());
    in.setHeader(NettyConstants.NETTY_LOCAL_ADDRESS, ctx.channel().localAddress());
    if (configuration.isSsl()) {
        // setup the SslSession header
        SSLSession sslSession = getSSLSession(ctx);
        in.setHeader(NettyConstants.NETTY_SSL_SESSION, sslSession);
        // enrich headers with details from the client certificate if option is enabled
        if (configuration.isSslClientCertHeaders()) {
            enrichWithClientCertInformation(sslSession, in);
        }
    }
}
Also used : SSLSession(javax.net.ssl.SSLSession)

Example 35 with SSLSession

use of javax.net.ssl.SSLSession in project camel by apache.

the class NettySSLTest method testSSLInOutWithNettyConsumer.

@Test
public void testSSLInOutWithNettyConsumer() throws Exception {
    // ibm jdks dont have sun security algorithms
    if (isJavaVendor("ibm")) {
        return;
    }
    context.addRoutes(new RouteBuilder() {

        public void configure() {
            // needClientAuth=true so we can get the client certificate details
            from("netty4:tcp://localhost:{{port}}?sync=true&ssl=true&passphrase=changeit&keyStoreFile=#ksf&trustStoreFile=#tsf&needClientAuth=true").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class);
                    if (session != null) {
                        javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0];
                        Principal principal = cert.getSubjectDN();
                        log.info("Client Cert SubjectDN: {}", principal.getName());
                        exchange.getOut().setBody("When You Go Home, Tell Them Of Us And Say, For Your Tomorrow, We Gave Our Today.");
                    } else {
                        exchange.getOut().setBody("Cannot start conversion without SSLSession");
                    }
                }
            });
        }
    });
    context.start();
    String response = template.requestBody("netty4:tcp://localhost:{{port}}?sync=true&ssl=true&passphrase=changeit&keyStoreFile=#ksf&trustStoreFile=#tsf", "Epitaph in Kohima, India marking the WWII Battle of Kohima and Imphal, Burma Campaign - Attributed to John Maxwell Edmonds", String.class);
    assertEquals("When You Go Home, Tell Them Of Us And Say, For Your Tomorrow, We Gave Our Today.", response);
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) SSLSession(javax.net.ssl.SSLSession) Principal(java.security.Principal) Test(org.junit.Test)

Aggregations

SSLSession (javax.net.ssl.SSLSession)340 HostnameVerifier (javax.net.ssl.HostnameVerifier)121 SSLContext (javax.net.ssl.SSLContext)74 IOException (java.io.IOException)65 X509Certificate (java.security.cert.X509Certificate)64 CertificateException (java.security.cert.CertificateException)49 SSLSocket (javax.net.ssl.SSLSocket)49 TrustManager (javax.net.ssl.TrustManager)45 X509TrustManager (javax.net.ssl.X509TrustManager)43 Test (org.junit.Test)39 Certificate (java.security.cert.Certificate)33 SecureRandom (java.security.SecureRandom)31 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)29 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)28 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)28 URL (java.net.URL)24 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)24 KeyManagementException (java.security.KeyManagementException)23 SSLException (javax.net.ssl.SSLException)22 InputStream (java.io.InputStream)18