Search in sources :

Example 96 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project netty by netty.

the class SslErrorTest method testCorrectAlert.

@ParameterizedTest(name = "{index}: serverProvider = {0}, clientProvider = {1}, exception = {2}, serverProduceError = {3}")
@MethodSource("data")
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testCorrectAlert(SslProvider serverProvider, final SslProvider clientProvider, final CertificateException exception, final boolean serverProduceError) throws Exception {
    // As this only works correctly at the moment when OpenSslEngine is used on the server-side there is
    // no need to run it if there is no openssl is available at all.
    OpenSsl.ensureAvailability();
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContextBuilder sslServerCtxBuilder = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(serverProvider).clientAuth(ClientAuth.REQUIRE);
    SslContextBuilder sslClientCtxBuilder = SslContextBuilder.forClient().keyManager(new File(getClass().getResource("test.crt").getFile()), new File(getClass().getResource("test_unencrypted.pem").getFile())).sslProvider(clientProvider);
    if (serverProduceError) {
        sslServerCtxBuilder.trustManager(new ExceptionTrustManagerFactory(exception));
        sslClientCtxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslServerCtxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        sslClientCtxBuilder.trustManager(new ExceptionTrustManagerFactory(exception));
    }
    final SslContext sslServerCtx = sslServerCtxBuilder.build();
    final SslContext sslClientCtx = sslClientCtxBuilder.build();
    Channel serverChannel = null;
    Channel clientChannel = null;
    EventLoopGroup group = new NioEventLoopGroup();
    final Promise<Void> promise = group.next().newPromise();
    try {
        serverChannel = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc()));
                if (!serverProduceError) {
                    ch.pipeline().addLast(new AlertValidationHandler(clientProvider, serverProduceError, exception, promise));
                }
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        ctx.close();
                    }
                });
            }
        }).bind(0).sync().channel();
        clientChannel = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(sslClientCtx.newHandler(ch.alloc()));
                if (serverProduceError) {
                    ch.pipeline().addLast(new AlertValidationHandler(clientProvider, serverProduceError, exception, promise));
                }
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        ctx.close();
                    }
                });
            }
        }).connect(serverChannel.localAddress()).syncUninterruptibly().channel();
        // Block until we received the correct exception
        promise.syncUninterruptibly();
    } finally {
        if (clientChannel != null) {
            clientChannel.close().syncUninterruptibly();
        }
        if (serverChannel != null) {
            serverChannel.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslServerCtx);
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : LoggingHandler(io.netty.handler.logging.LoggingHandler) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) File(java.io.File) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Timeout(org.junit.jupiter.api.Timeout) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 97 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project netty by netty.

the class SslHandlerTest method testHandshakeFailedByWriteBeforeChannelActive.

@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailedByWriteBeforeChannelActive() throws Exception {
    final SslContext sslClientCtx = SslContextBuilder.forClient().protocols(SslProtocols.SSL_v3).trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(SslProvider.JDK).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    final CountDownLatch activeLatch = new CountDownLatch(1);
    final AtomicReference<AssertionError> errorRef = new AtomicReference<AssertionError>();
    final SslHandler sslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    try {
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInboundHandlerAdapter()).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        cc = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

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

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        if (cause instanceof AssertionError) {
                            errorRef.set((AssertionError) cause);
                        }
                    }

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        activeLatch.countDown();
                    }
                });
            }
        }).connect(sc.localAddress()).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 }));
            }
        }).syncUninterruptibly().channel();
        // Ensure there is no AssertionError thrown by having the handshake failed by the writeAndFlush(...) before
        // channelActive(...) was called. Let's first wait for the activeLatch countdown to happen and after this
        // check if we saw and AssertionError (even if we timed out waiting).
        activeLatch.await(5, TimeUnit.SECONDS);
        AssertionError error = errorRef.get();
        if (error != null) {
            throw error;
        }
        assertThat(sslHandler.handshakeFuture().await().cause(), CoreMatchers.<Throwable>instanceOf(SSLException.class));
    } 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) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) 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) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 98 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project netty by netty.

the class SniClientJava8TestUtil method testSniClient.

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

            @Override
            protected void initChannel(Channel ch) throws Exception {
                SslHandler handler = finalContext.newHandler(ch.alloc());
                SSLParameters parameters = handler.engine().getSSLParameters();
                SNIMatcher matcher = new SNIMatcher(0) {

                    @Override
                    public boolean matches(SNIServerName sniServerName) {
                        return match;
                    }
                };
                parameters.setSNIMatchers(Collections.singleton(matcher));
                handler.engine().setSSLParameters(parameters);
                ch.pipeline().addFirst(handler);
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        if (evt instanceof SslHandshakeCompletionEvent) {
                            SslHandshakeCompletionEvent event = (SslHandshakeCompletionEvent) evt;
                            if (match) {
                                if (event.isSuccess()) {
                                    promise.setSuccess(null);
                                } else {
                                    promise.setFailure(event.cause());
                                }
                            } else {
                                if (event.isSuccess()) {
                                    promise.setFailure(new AssertionError("expected SSLException"));
                                } else {
                                    Throwable cause = event.cause();
                                    if (cause instanceof SSLException) {
                                        promise.setSuccess(null);
                                    } else {
                                        promise.setFailure(new AssertionError("cause not of type SSLException: " + ThrowableUtil.stackTraceToString(cause)));
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }).bind(address).syncUninterruptibly().channel();
        sslClientContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(sslClientProvider).build();
        SslHandler sslHandler = new SslHandler(sslClientContext.newEngine(ByteBufAllocator.DEFAULT, sniHost, -1));
        Bootstrap cb = new Bootstrap();
        cc = cb.group(group).channel(LocalChannel.class).handler(sslHandler).connect(address).syncUninterruptibly().channel();
        promise.syncUninterruptibly();
        sslHandler.handshakeFuture().syncUninterruptibly();
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        ReferenceCountUtil.release(sslServerContext);
        ReferenceCountUtil.release(sslClientContext);
        cert.delete();
        group.shutdownGracefully();
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) LocalChannel(io.netty.channel.local.LocalChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) SSLException(javax.net.ssl.SSLException) SNIServerName(javax.net.ssl.SNIServerName) SSLParameters(javax.net.ssl.SSLParameters) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) KeyStoreException(java.security.KeyStoreException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SNIMatcher(javax.net.ssl.SNIMatcher) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 99 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project netty by netty.

the class DetectPeerCloseWithoutReadTest method clientCloseWithoutServerReadIsDetected0.

private void clientCloseWithoutServerReadIsDetected0(final boolean extraReadRequested) throws InterruptedException {
    EventLoopGroup serverGroup = null;
    EventLoopGroup clientGroup = null;
    Channel serverChannel = null;
    try {
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicInteger bytesRead = new AtomicInteger();
        final int expectedBytes = 100;
        serverGroup = newGroup();
        clientGroup = newGroup();
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup);
        sb.channel(serverChannel());
        // Ensure we read only one message per read() call and that we need multiple read()
        // calls to consume everything.
        sb.childOption(ChannelOption.AUTO_READ, false);
        sb.childOption(ChannelOption.MAX_MESSAGES_PER_READ, 1);
        sb.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(expectedBytes / 10));
        sb.childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(new TestHandler(bytesRead, extraReadRequested, latch));
            }
        });
        serverChannel = sb.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        Bootstrap cb = new Bootstrap();
        cb.group(serverGroup);
        cb.channel(clientChannel());
        cb.handler(new ChannelInboundHandlerAdapter());
        Channel clientChannel = cb.connect(serverChannel.localAddress()).syncUninterruptibly().channel();
        ByteBuf buf = clientChannel.alloc().buffer(expectedBytes);
        buf.writerIndex(buf.writerIndex() + expectedBytes);
        clientChannel.writeAndFlush(buf).addListener(ChannelFutureListener.CLOSE);
        latch.await();
        assertEquals(expectedBytes, bytesRead.get());
    } finally {
        if (serverChannel != null) {
            serverChannel.close().syncUninterruptibly();
        }
        if (serverGroup != null) {
            serverGroup.shutdownGracefully();
        }
        if (clientGroup != null) {
            clientGroup.shutdownGracefully();
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ServerChannel(io.netty.channel.ServerChannel) Channel(io.netty.channel.Channel) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventLoopGroup(io.netty.channel.EventLoopGroup) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 100 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project netty by netty.

the class NettyBlockHoundIntegrationTest method testHandshake.

private static void testHandshake(SslContext sslClientCtx, SslHandler clientSslHandler, SslHandler serverSslHandler) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    try {
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(serverSslHandler).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) {
                ch.pipeline().addLast(clientSslHandler).addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                        if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).cause() != null) {
                            ((SslHandshakeCompletionEvent) evt).cause().printStackTrace();
                        }
                        ctx.fireUserEventTriggered(evt);
                    }
                });
            }
        }).connect(sc.localAddress());
        cc = future.syncUninterruptibly().channel();
        clientSslHandler.handshakeFuture().await().sync();
        serverSslHandler.handshakeFuture().await().sync();
    } 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) SslHandshakeCompletionEvent(io.netty.handler.ssl.SslHandshakeCompletionEvent) InetSocketAddress(java.net.InetSocketAddress) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) 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)

Aggregations

EventLoopGroup (io.netty.channel.EventLoopGroup)367 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)271 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)162 Bootstrap (io.netty.bootstrap.Bootstrap)137 Channel (io.netty.channel.Channel)131 ChannelFuture (io.netty.channel.ChannelFuture)129 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)109 SocketChannel (io.netty.channel.socket.SocketChannel)94 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)92 InetSocketAddress (java.net.InetSocketAddress)69 Test (org.junit.jupiter.api.Test)67 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)60 LoggingHandler (io.netty.handler.logging.LoggingHandler)55 ChannelPipeline (io.netty.channel.ChannelPipeline)51 SslContext (io.netty.handler.ssl.SslContext)51 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)50 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)49 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)46 LocalServerChannel (io.netty.channel.local.LocalServerChannel)42 LocalChannel (io.netty.channel.local.LocalChannel)40