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