Search in sources :

Example 36 with SelfSignedCertificate

use of io.netty.handler.ssl.util.SelfSignedCertificate in project netty by netty.

the class SSLEngineTest method clientInitiatedRenegotiationWithFatalAlertDoesNotInfiniteLoopServer.

@Test(timeout = 30000)
public void clientInitiatedRenegotiationWithFatalAlertDoesNotInfiniteLoopServer() throws CertificateException, SSLException, InterruptedException, ExecutionException {
    final SelfSignedCertificate ssc = new SelfSignedCertificate();
    serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(sslServerProvider()).build();
    sb = new ServerBootstrap().group(new NioEventLoopGroup(1)).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(serverSslCtx.newHandler(ch.alloc()));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                    if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).isSuccess()) {
                        // This data will be sent to the client before any of the re-negotiation data can be
                        // sent. The client will read this, detect that it is not the response to
                        // renegotiation which was expected, and respond with a fatal alert.
                        ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(100));
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @Override
                public void channelRead(final ChannelHandlerContext ctx, Object msg) {
                    ReferenceCountUtil.release(msg);
                    // The server then attempts to trigger a flush operation once the application data is
                    // received from the client. The flush will encrypt all data and should not result in
                    // deadlock.
                    ctx.channel().eventLoop().schedule(new Runnable() {

                        @Override
                        public void run() {
                            ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(101));
                        }
                    }, 500, TimeUnit.MILLISECONDS);
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) {
                    serverLatch.countDown();
                }
            });
            serverConnectedChannel = ch;
        }
    });
    serverChannel = sb.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
    clientSslCtx = SslContextBuilder.forClient().sslProvider(// OpenSslEngine doesn't support renegotiation on client side
    SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    cb = new Bootstrap();
    cb.group(new NioEventLoopGroup(1)).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            SslHandler sslHandler = clientSslCtx.newHandler(ch.alloc());
            // The renegotiate is not expected to succeed, so we should stop trying in a timely manner so
            // the unit test can terminate relativley quicly.
            sslHandler.setHandshakeTimeout(1, TimeUnit.SECONDS);
            p.addLast(sslHandler);
            p.addLast(new ChannelInboundHandlerAdapter() {

                private int handshakeCount;

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                    // completed the first renegotiation handshake (which is the second handshake).
                    if (evt instanceof SslHandshakeCompletionEvent && ++handshakeCount == 2) {
                        ctx.close();
                        return;
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    ReferenceCountUtil.release(msg);
                    // Simulate a request that the server's application logic will think is invalid.
                    ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(102));
                    ctx.pipeline().get(SslHandler.class).renegotiate();
                }
            });
        }
    });
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.syncUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    serverLatch.await();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 37 with SelfSignedCertificate

use of io.netty.handler.ssl.util.SelfSignedCertificate in project netty by netty.

the class SSLEngineTest method setupHandlers.

protected void setupHandlers(ApplicationProtocolConfig serverApn, ApplicationProtocolConfig clientApn) throws InterruptedException, SSLException, CertificateException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    setupHandlers(SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey(), null).sslProvider(sslServerProvider()).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).applicationProtocolConfig(serverApn).sessionCacheSize(0).sessionTimeout(0).build(), SslContextBuilder.forClient().sslProvider(sslClientProvider()).applicationProtocolConfig(clientApn).trustManager(InsecureTrustManagerFactory.INSTANCE).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build());
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate)

Example 38 with SelfSignedCertificate

use of io.netty.handler.ssl.util.SelfSignedCertificate in project netty by netty.

the class SniClientTest method testSniClient.

private static void testSniClient(SslProvider sslClientProvider, SslProvider sslServerProvider) throws Exception {
    final String sniHost = "sni.netty.io";
    LocalAddress address = new LocalAddress("test");
    EventLoopGroup group = new DefaultEventLoopGroup(1);
    Channel sc = null;
    Channel cc = null;
    try {
        SelfSignedCertificate cert = new SelfSignedCertificate();
        final SslContext sslServerContext = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(sslServerProvider).build();
        final Promise<String> promise = group.next().newPromise();
        ServerBootstrap sb = new ServerBootstrap();
        sc = sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addFirst(new SniHandler(new Mapping<String, SslContext>() {

                    @Override
                    public SslContext map(String input) {
                        promise.setSuccess(input);
                        return sslServerContext;
                    }
                }));
            }
        }).bind(address).syncUninterruptibly().channel();
        SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(sslClientProvider).build();
        Bootstrap cb = new Bootstrap();
        cc = cb.group(group).channel(LocalChannel.class).handler(new SslHandler(sslContext.newEngine(ByteBufAllocator.DEFAULT, sniHost, -1))).connect(address).syncUninterruptibly().channel();
        Assert.assertEquals(sniHost, promise.syncUninterruptibly().getNow());
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 39 with SelfSignedCertificate

use of io.netty.handler.ssl.util.SelfSignedCertificate in project netty by netty.

the class SniHandlerTest method testReplaceHandler.

@Test(timeout = 30000)
public void testReplaceHandler() throws Exception {
    switch(provider) {
        case OPENSSL:
        case OPENSSL_REFCNT:
            final String sniHost = "sni.netty.io";
            LocalAddress address = new LocalAddress("testReplaceHandler-" + Math.random());
            EventLoopGroup group = new DefaultEventLoopGroup(1);
            Channel sc = null;
            Channel cc = null;
            SslContext sslContext = null;
            SelfSignedCertificate cert = new SelfSignedCertificate();
            try {
                final SslContext sslServerContext = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(provider).build();
                final Mapping<String, SslContext> mapping = new Mapping<String, SslContext>() {

                    @Override
                    public SslContext map(String input) {
                        return sslServerContext;
                    }
                };
                final Promise<Void> releasePromise = group.next().newPromise();
                final SniHandler handler = new SniHandler(mapping) {

                    @Override
                    protected void replaceHandler(ChannelHandlerContext ctx, String hostname, final SslContext sslContext) throws Exception {
                        boolean success = false;
                        try {
                            // The SniHandler's replaceHandler() method allows us to implement custom behavior.
                            // As an example, we want to release() the SslContext upon channelInactive() or rather
                            // when the SslHandler closes it's SslEngine. If you take a close look at SslHandler
                            // you'll see that it's doing it in the #handlerRemoved0() method.
                            SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
                            try {
                                SslHandler customSslHandler = new CustomSslHandler(sslContext, sslEngine) {

                                    @Override
                                    public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
                                        try {
                                            super.handlerRemoved0(ctx);
                                        } finally {
                                            releasePromise.trySuccess(null);
                                        }
                                    }
                                };
                                ctx.pipeline().replace(this, CustomSslHandler.class.getName(), customSslHandler);
                                success = true;
                            } finally {
                                if (!success) {
                                    ReferenceCountUtil.safeRelease(sslEngine);
                                }
                            }
                        } finally {
                            if (!success) {
                                ReferenceCountUtil.safeRelease(sslContext);
                                releasePromise.cancel(true);
                            }
                        }
                    }
                };
                ServerBootstrap sb = new ServerBootstrap();
                sc = sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addFirst(handler);
                    }
                }).bind(address).syncUninterruptibly().channel();
                sslContext = SslContextBuilder.forClient().sslProvider(provider).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
                Bootstrap cb = new Bootstrap();
                cc = cb.group(group).channel(LocalChannel.class).handler(new SslHandler(sslContext.newEngine(ByteBufAllocator.DEFAULT, sniHost, -1))).connect(address).syncUninterruptibly().channel();
                cc.writeAndFlush(Unpooled.wrappedBuffer("Hello, World!".getBytes())).syncUninterruptibly();
                // Notice how the server's SslContext refCnt is 1
                assertEquals(1, ((ReferenceCounted) sslServerContext).refCnt());
                // The client disconnects
                cc.close().syncUninterruptibly();
                if (!releasePromise.awaitUninterruptibly(10L, TimeUnit.SECONDS)) {
                    throw new IllegalStateException("It doesn't seem #replaceHandler() got called.");
                }
                // We should have successfully release() the SslContext
                assertEquals(0, ((ReferenceCounted) sslServerContext).refCnt());
            } finally {
                if (cc != null) {
                    cc.close().syncUninterruptibly();
                }
                if (sc != null) {
                    sc.close().syncUninterruptibly();
                }
                if (sslContext != null) {
                    ReferenceCountUtil.release(sslContext);
                }
                group.shutdownGracefully();
                cert.delete();
            }
        case JDK:
            return;
        default:
            throw new Error();
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SSLEngine(javax.net.ssl.SSLEngine) LocalChannel(io.netty.channel.local.LocalChannel) DomainNameMapping(io.netty.util.DomainNameMapping) Mapping(io.netty.util.Mapping) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) LocalAddress(io.netty.channel.local.LocalAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DecoderException(io.netty.handler.codec.DecoderException) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 40 with SelfSignedCertificate

use of io.netty.handler.ssl.util.SelfSignedCertificate in project netty by netty.

the class SslContextBuilderTest method testServerContextFromFile.

private static void testServerContextFromFile(SslProvider provider) throws Exception {
    SelfSignedCertificate cert = new SelfSignedCertificate();
    SslContextBuilder builder = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()).sslProvider(provider).trustManager(cert.certificate()).clientAuth(ClientAuth.OPTIONAL);
    SslContext context = builder.build();
    SSLEngine engine = context.newEngine(UnpooledByteBufAllocator.DEFAULT);
    assertTrue(engine.getWantClientAuth());
    assertFalse(engine.getNeedClientAuth());
    engine.closeInbound();
    engine.closeOutbound();
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SSLEngine(javax.net.ssl.SSLEngine)

Aggregations

SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)63 Test (org.junit.Test)32 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)28 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)26 EventLoopGroup (io.netty.channel.EventLoopGroup)25 SSLEngine (javax.net.ssl.SSLEngine)25 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)21 LoggingHandler (io.netty.handler.logging.LoggingHandler)19 SslContext (io.netty.handler.ssl.SslContext)19 Channel (io.netty.channel.Channel)17 ByteBuffer (java.nio.ByteBuffer)11 SSLEngineResult (javax.net.ssl.SSLEngineResult)10 Bootstrap (io.netty.bootstrap.Bootstrap)9 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)7 ChannelFuture (io.netty.channel.ChannelFuture)6 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)6 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)6 SocketChannel (io.netty.channel.socket.SocketChannel)6 File (java.io.File)6