use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.
the class SniHandlerTest method testNonSslRecord.
@ParameterizedTest(name = "{index}: sslProvider={0}")
@MethodSource("data")
public void testNonSslRecord(SslProvider provider) throws Exception {
SslContext nettyContext = makeSslContext(provider, false);
try {
final AtomicReference<SslHandshakeCompletionEvent> evtRef = new AtomicReference<SslHandshakeCompletionEvent>();
SniHandler handler = new SniHandler(new DomainNameMappingBuilder<SslContext>(nettyContext).build());
final EmbeddedChannel ch = new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof SslHandshakeCompletionEvent) {
assertTrue(evtRef.compareAndSet(null, (SslHandshakeCompletionEvent) evt));
}
}
});
try {
final byte[] bytes = new byte[1024];
bytes[0] = SslUtils.SSL_CONTENT_TYPE_ALERT;
DecoderException e = assertThrows(DecoderException.class, new Executable() {
@Override
public void execute() throws Throwable {
ch.writeInbound(Unpooled.wrappedBuffer(bytes));
}
});
assertThat(e.getCause(), CoreMatchers.instanceOf(NotSslRecordException.class));
assertFalse(ch.finish());
} finally {
ch.finishAndReleaseAll();
}
assertThat(evtRef.get().cause(), CoreMatchers.instanceOf(NotSslRecordException.class));
} finally {
releaseAll(nettyContext);
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter 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);
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.
the class SSLEngineTest method setupHandlers.
protected void setupHandlers(final BufferType type, final boolean delegate, SslContext serverCtx, SslContext clientCtx) throws InterruptedException, SSLException, CertificateException {
serverSslCtx = serverCtx;
clientSslCtx = clientCtx;
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();
SslHandler sslHandler = !delegate ? serverSslCtx.newHandler(ch.alloc()) : serverSslCtx.newHandler(ch.alloc(), delegatingExecutor);
p.addLast(sslHandler);
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 {
ctx.fireExceptionCaught(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();
SslHandler sslHandler = !delegate ? clientSslCtx.newHandler(ch.alloc()) : clientSslCtx.newHandler(ch.alloc(), delegatingExecutor);
p.addLast(sslHandler);
p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
p.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause.getCause() instanceof SSLHandshakeException) {
clientException = cause.getCause();
clientLatch.countDown();
} else {
ctx.fireExceptionCaught(cause);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
clientLatch.countDown();
}
});
}
});
serverChannel = sb.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
ChannelFuture ccf = cb.connect(serverChannel.localAddress());
assertTrue(ccf.syncUninterruptibly().isSuccess());
clientChannel = ccf.channel();
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.
the class SSLEngineTest method mySetupMutualAuth.
private void mySetupMutualAuth(final SSLEngineTestParam param, File servertTrustCrtFile, File serverKeyFile, final File serverCrtFile, String serverKeyPassword, File clientTrustCrtFile, File clientKeyFile, final File clientCrtFile, String clientKeyPassword) throws InterruptedException, SSLException {
serverSslCtx = wrapContext(param, SslContextBuilder.forServer(serverCrtFile, serverKeyFile, serverKeyPassword).sslProvider(sslServerProvider()).sslContextProvider(serverSslContextProvider()).protocols(param.protocols()).ciphers(param.ciphers()).trustManager(servertTrustCrtFile).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build());
clientSslCtx = wrapContext(param, SslContextBuilder.forClient().sslProvider(sslClientProvider()).sslContextProvider(clientSslContextProvider()).protocols(param.protocols()).ciphers(param.ciphers()).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) {
ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), param.type));
ChannelPipeline p = ch.pipeline();
final SSLEngine engine = wrapEngine(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 {
verifySSLSessionForMutualAuth(param, engine.getSession(), serverCrtFile, PRINCIPAL_NAME);
} 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(), param.type));
final SslHandler handler = !param.delegate ? clientSslCtx.newHandler(ch.alloc()) : clientSslCtx.newHandler(ch.alloc(), delegatingExecutor);
handler.engine().setNeedClientAuth(true);
ChannelPipeline p = ch.pipeline();
p.addLast(handler);
p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
p.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt == SslHandshakeCompletionEvent.SUCCESS) {
try {
verifySSLSessionForMutualAuth(param, handler.engine().getSession(), clientCrtFile, PRINCIPAL_NAME);
} catch (Throwable cause) {
clientException = cause;
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
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();
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter 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);
}
}
Aggregations