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();
}
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);
}
}
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);
}
}
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);
}
}
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);
}
}
};
}
Aggregations