Search in sources :

Example 71 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project netty by netty.

the class SSLEngineTest method clientInitiatedRenegotiationWithFatalAlertDoesNotInfiniteLoopServer.

@MethodSource("newTestParams")
@ParameterizedTest
@Timeout(30)
public void clientInitiatedRenegotiationWithFatalAlertDoesNotInfiniteLoopServer(final SSLEngineTestParam param) throws Exception {
    assumeTrue(PlatformDependent.javaVersion() >= 11);
    final SelfSignedCertificate ssc = new SelfSignedCertificate();
    serverSslCtx = wrapContext(param, SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(sslServerProvider()).sslContextProvider(serverSslContextProvider()).protocols(param.protocols()).ciphers(param.ciphers()).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(), param.type));
            ChannelPipeline p = ch.pipeline();
            SslHandler handler = !param.delegate ? serverSslCtx.newHandler(ch.alloc()) : serverSslCtx.newHandler(ch.alloc(), delegatingExecutor);
            p.addLast(handler);
            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 = wrapContext(param, SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE).protocols(param.protocols()).ciphers(param.ciphers()).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(), param.type()));
            ChannelPipeline p = ch.pipeline();
            SslHandler sslHandler = !param.delegate ? clientSslCtx.newHandler(ch.alloc()) : clientSslCtx.newHandler(ch.alloc(), delegatingExecutor);
            // 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();
    ssc.delete();
}
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) Timeout(org.junit.jupiter.api.Timeout) MethodSource(org.junit.jupiter.params.provider.MethodSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 72 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project netty by netty.

the class OpenSslPrivateKeyMethodTest method testPrivateKeyMethod.

@ParameterizedTest(name = "{index}: delegate = {0}, async = {1}, newThread={2}")
@MethodSource("parameters")
public void testPrivateKeyMethod(final boolean delegate, boolean async, boolean newThread) throws Exception {
    final AtomicBoolean signCalled = new AtomicBoolean();
    OpenSslPrivateKeyMethod keyMethod = new OpenSslPrivateKeyMethod() {

        @Override
        public byte[] sign(SSLEngine engine, int signatureAlgorithm, byte[] input) throws Exception {
            signCalled.set(true);
            assertThread(delegate);
            assertEquals(CERT.cert().getPublicKey(), engine.getSession().getLocalCertificates()[0].getPublicKey());
            // Delegate signing to Java implementation.
            final Signature signature;
            // Depending on the Java version it will pick one or the other.
            if (signatureAlgorithm == OpenSslPrivateKeyMethod.SSL_SIGN_RSA_PKCS1_SHA256) {
                signature = Signature.getInstance("SHA256withRSA");
            } else if (signatureAlgorithm == OpenSslPrivateKeyMethod.SSL_SIGN_RSA_PSS_RSAE_SHA256) {
                signature = Signature.getInstance("RSASSA-PSS");
                signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1));
            } else {
                throw new AssertionError("Unexpected signature algorithm " + signatureAlgorithm);
            }
            signature.initSign(CERT.key());
            signature.update(input);
            return signature.sign();
        }

        @Override
        public byte[] decrypt(SSLEngine engine, byte[] input) {
            throw new UnsupportedOperationException();
        }
    };
    final SslContext sslServerContext = async ? buildServerContext(new OpenSslPrivateKeyMethodAdapter(keyMethod, newThread)) : buildServerContext(keyMethod);
    final SslContext sslClientContext = buildClientContext();
    try {
        try {
            final Promise<Object> serverPromise = GROUP.next().newPromise();
            final Promise<Object> clientPromise = GROUP.next().newPromise();
            ChannelHandler serverHandler = new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(newSslHandler(sslServerContext, ch.alloc(), delegateExecutor(delegate)));
                    pipeline.addLast(new SimpleChannelInboundHandler<Object>() {

                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) {
                            serverPromise.cancel(true);
                            ctx.fireChannelInactive();
                        }

                        @Override
                        public void channelRead0(ChannelHandlerContext ctx, Object msg) {
                            if (serverPromise.trySuccess(null)) {
                                ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'P', 'O', 'N', 'G' }));
                            }
                            ctx.close();
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                            if (!serverPromise.tryFailure(cause)) {
                                ctx.fireExceptionCaught(cause);
                            }
                        }
                    });
                }
            };
            LocalAddress address = new LocalAddress("test-" + SslProvider.OPENSSL + '-' + SslProvider.JDK + '-' + RFC_CIPHER_NAME + '-' + delegate);
            Channel server = server(address, serverHandler);
            try {
                ChannelHandler clientHandler = new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(newSslHandler(sslClientContext, ch.alloc(), delegateExecutor(delegate)));
                        pipeline.addLast(new SimpleChannelInboundHandler<Object>() {

                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) {
                                clientPromise.cancel(true);
                                ctx.fireChannelInactive();
                            }

                            @Override
                            public void channelRead0(ChannelHandlerContext ctx, Object msg) {
                                clientPromise.trySuccess(null);
                                ctx.close();
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                if (!clientPromise.tryFailure(cause)) {
                                    ctx.fireExceptionCaught(cause);
                                }
                            }
                        });
                    }
                };
                Channel client = client(server, clientHandler);
                try {
                    client.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'P', 'I', 'N', 'G' })).syncUninterruptibly();
                    assertTrue(clientPromise.await(5L, TimeUnit.SECONDS), "client timeout");
                    assertTrue(serverPromise.await(5L, TimeUnit.SECONDS), "server timeout");
                    clientPromise.sync();
                    serverPromise.sync();
                    assertTrue(signCalled.get());
                } finally {
                    client.close().sync();
                }
            } finally {
                server.close().sync();
            }
        } finally {
            ReferenceCountUtil.release(sslClientContext);
        }
    } finally {
        ReferenceCountUtil.release(sslServerContext);
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) SSLEngine(javax.net.ssl.SSLEngine) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PSSParameterSpec(java.security.spec.PSSParameterSpec) Signature(java.security.Signature) ChannelInitializer(io.netty.channel.ChannelInitializer) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 73 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project netty by netty.

the class SslHandlerTest method testHandshakeTimeout0.

private static void testHandshakeTimeout0(final boolean startTls) throws Exception {
    final SslContext sslClientCtx = SslContextBuilder.forClient().startTls(true).trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(SslProvider.JDK).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    final SslHandler sslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    sslHandler.setHandshakeTimeout(500, TimeUnit.MILLISECONDS);
    try {
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInboundHandlerAdapter()).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        ChannelFuture future = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(sslHandler);
                if (startTls) {
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            ctx.writeAndFlush(wrappedBuffer(new byte[] { 1, 2, 3, 4 }));
                        }
                    });
                }
            }
        }).connect(sc.localAddress());
        if (!startTls) {
            future.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    // Write something to trigger the handshake before fireChannelActive is called.
                    future.channel().writeAndFlush(wrappedBuffer(new byte[] { 1, 2, 3, 4 }));
                }
            });
        }
        cc = future.syncUninterruptibly().channel();
        Throwable cause = sslHandler.handshakeFuture().await().cause();
        assertThat(cause, CoreMatchers.<Throwable>instanceOf(SSLException.class));
        assertThat(cause.getMessage(), containsString("timed out"));
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SSLException(javax.net.ssl.SSLException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) CodecException(io.netty.handler.codec.CodecException) DecoderException(io.netty.handler.codec.DecoderException) SSLProtocolException(javax.net.ssl.SSLProtocolException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) 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)

Example 74 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project netty by netty.

the class SslHandlerTest method testHandshakeEvents.

private void testHandshakeEvents(SslProvider provider, String protocol) throws Exception {
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).protocols(protocol).sslProvider(provider).build();
    final SelfSignedCertificate cert = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()).protocols(protocol).sslProvider(provider).build();
    EventLoopGroup group = new NioEventLoopGroup();
    final LinkedBlockingQueue<SslHandshakeCompletionEvent> serverCompletionEvents = new LinkedBlockingQueue<SslHandshakeCompletionEvent>();
    final LinkedBlockingQueue<SslHandshakeCompletionEvent> clientCompletionEvents = new LinkedBlockingQueue<SslHandshakeCompletionEvent>();
    try {
        Channel sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT));
                ch.pipeline().addLast(new SslHandshakeCompletionEventHandler(serverCompletionEvents));
            }
        }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        Bootstrap bs = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, "netty.io", 9999));
                ch.pipeline().addLast(new SslHandshakeCompletionEventHandler(clientCompletionEvents));
            }
        }).remoteAddress(sc.localAddress());
        Channel cc1 = bs.connect().sync().channel();
        Channel cc2 = bs.connect().sync().channel();
        // on the server-side and one on the client-side.
        for (int i = 0; i < 2; i++) {
            SslHandshakeCompletionEvent event = clientCompletionEvents.take();
            assertTrue(event.isSuccess());
        }
        for (int i = 0; i < 2; i++) {
            SslHandshakeCompletionEvent event = serverCompletionEvents.take();
            assertTrue(event.isSuccess());
        }
        cc1.close().sync();
        cc2.close().sync();
        sc.close().sync();
        assertEquals(0, clientCompletionEvents.size());
        assertEquals(0, serverCompletionEvents.size());
    } finally {
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslClientCtx);
        ReferenceCountUtil.release(sslServerCtx);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) InetSocketAddress(java.net.InetSocketAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 75 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project netty by netty.

the class OcspTest method newClientHandler.

private static ChannelHandler newClientHandler(final SslContext context, final OcspClientCallback callback, final ChannelHandler handler) {
    return new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SslHandler sslHandler = context.newHandler(ch.alloc());
            ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
            pipeline.addLast(sslHandler);
            pipeline.addLast(new OcspClientCallbackHandler(engine, callback));
            if (handler != null) {
                pipeline.addLast(handler);
            }
        }
    };
}
Also used : ReferenceCountedOpenSslEngine(io.netty.handler.ssl.ReferenceCountedOpenSslEngine) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler)

Aggregations

ChannelInitializer (io.netty.channel.ChannelInitializer)86 Channel (io.netty.channel.Channel)59 Bootstrap (io.netty.bootstrap.Bootstrap)42 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)39 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)36 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)32 InetSocketAddress (java.net.InetSocketAddress)32 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)31 ChannelFuture (io.netty.channel.ChannelFuture)30 ChannelPipeline (io.netty.channel.ChannelPipeline)26 EventLoopGroup (io.netty.channel.EventLoopGroup)26 LocalServerChannel (io.netty.channel.local.LocalServerChannel)21 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)21 LocalChannel (io.netty.channel.local.LocalChannel)20 SocketChannel (io.netty.channel.socket.SocketChannel)18 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)17 SslHandler (io.netty.handler.ssl.SslHandler)17 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)14 Map (java.util.Map)12 CountDownLatch (java.util.concurrent.CountDownLatch)12