Search in sources :

Example 16 with SelfSignedCertificate

use of io.netty.handler.ssl.util.SelfSignedCertificate in project netty by netty.

the class SslHandlerTest method testCloseNotify.

private static void testCloseNotify(SslProvider provider, final long closeNotifyReadTimeout, final boolean timeout) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider).build();
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(provider).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    try {
        final Promise<Channel> clientPromise = group.next().newPromise();
        final Promise<Channel> serverPromise = group.next().newPromise();
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                SslHandler handler = sslServerCtx.newHandler(ch.alloc());
                handler.setCloseNotifyReadTimeoutMillis(closeNotifyReadTimeout);
                handler.sslCloseFuture().addListener(new PromiseNotifier<Channel, Future<Channel>>(serverPromise));
                handler.handshakeFuture().addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) {
                        if (!future.isSuccess()) {
                            // Something bad happened during handshake fail the promise!
                            serverPromise.tryFailure(future.cause());
                        }
                    }
                });
                ch.pipeline().addLast(handler);
            }
        }).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 {
                final AtomicBoolean closeSent = new AtomicBoolean();
                if (timeout) {
                    ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() {

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (closeSent.get()) {
                                // Drop data on the floor so we will get a timeout while waiting for the
                                // close_notify.
                                ReferenceCountUtil.release(msg);
                            } else {
                                super.channelRead(ctx, msg);
                            }
                        }
                    });
                }
                SslHandler handler = sslClientCtx.newHandler(ch.alloc());
                handler.setCloseNotifyReadTimeoutMillis(closeNotifyReadTimeout);
                handler.sslCloseFuture().addListener(new PromiseNotifier<Channel, Future<Channel>>(clientPromise));
                handler.handshakeFuture().addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) {
                        if (future.isSuccess()) {
                            closeSent.compareAndSet(false, true);
                            future.getNow().close();
                        } else {
                            // Something bad happened during handshake fail the promise!
                            clientPromise.tryFailure(future.cause());
                        }
                    }
                });
                ch.pipeline().addLast(handler);
            }
        }).connect(sc.localAddress()).syncUninterruptibly().channel();
        serverPromise.awaitUninterruptibly();
        clientPromise.awaitUninterruptibly();
        // Server always received the close_notify as the client triggers the close sequence.
        assertTrue(serverPromise.isSuccess());
        // Depending on if we wait for the response or not the promise will be failed or not.
        if (closeNotifyReadTimeout > 0 && !timeout) {
            assertTrue(clientPromise.isSuccess());
        } else {
            assertFalse(clientPromise.isSuccess());
        }
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslServerCtx);
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) 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) PromiseNotifier(io.netty.util.concurrent.PromiseNotifier) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) CodecException(io.netty.handler.codec.CodecException) SSLProtocolException(javax.net.ssl.SSLProtocolException) DecoderException(io.netty.handler.codec.DecoderException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 17 with SelfSignedCertificate

use of io.netty.handler.ssl.util.SelfSignedCertificate in project netty by netty.

the class SSLEngineTest method testBeginHandshakeCloseOutbound.

@Test
public void testBeginHandshakeCloseOutbound() throws Exception {
    SelfSignedCertificate cert = new SelfSignedCertificate();
    clientSslCtx = SslContextBuilder.forClient().sslProvider(sslClientProvider()).build();
    SSLEngine client = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
    serverSslCtx = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()).sslProvider(sslServerProvider()).build();
    SSLEngine server = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
    try {
        testBeginHandshakeCloseOutbound(client);
        testBeginHandshakeCloseOutbound(server);
    } finally {
        cleanupClientSslEngine(client);
        cleanupServerSslEngine(server);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SSLEngine(javax.net.ssl.SSLEngine) Test(org.junit.Test)

Example 18 with SelfSignedCertificate

use of io.netty.handler.ssl.util.SelfSignedCertificate in project netty by netty.

the class SSLEngineTest method testUnwrapBehavior.

@Test
public void testUnwrapBehavior() throws Exception {
    SelfSignedCertificate cert = new SelfSignedCertificate();
    clientSslCtx = SslContextBuilder.forClient().trustManager(cert.cert()).sslProvider(sslClientProvider()).build();
    SSLEngine client = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
    serverSslCtx = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()).sslProvider(sslServerProvider()).build();
    SSLEngine server = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
    byte[] bytes = "Hello World".getBytes(CharsetUtil.US_ASCII);
    try {
        ByteBuffer plainClientOut = allocateBuffer(client.getSession().getApplicationBufferSize());
        ByteBuffer encryptedClientToServer = allocateBuffer(server.getSession().getPacketBufferSize() * 2);
        ByteBuffer plainServerIn = allocateBuffer(server.getSession().getApplicationBufferSize());
        handshake(client, server);
        // create two TLS frames
        // first frame
        plainClientOut.put(bytes, 0, 5);
        plainClientOut.flip();
        SSLEngineResult result = client.wrap(plainClientOut, encryptedClientToServer);
        assertEquals(SSLEngineResult.Status.OK, result.getStatus());
        assertEquals(5, result.bytesConsumed());
        assertTrue(result.bytesProduced() > 0);
        assertFalse(plainClientOut.hasRemaining());
        // second frame
        plainClientOut.clear();
        plainClientOut.put(bytes, 5, 6);
        plainClientOut.flip();
        result = client.wrap(plainClientOut, encryptedClientToServer);
        assertEquals(SSLEngineResult.Status.OK, result.getStatus());
        assertEquals(6, result.bytesConsumed());
        assertTrue(result.bytesProduced() > 0);
        // send over to server
        encryptedClientToServer.flip();
        // try with too small output buffer first (to check BUFFER_OVERFLOW case)
        int remaining = encryptedClientToServer.remaining();
        ByteBuffer small = allocateBuffer(3);
        result = server.unwrap(encryptedClientToServer, small);
        assertEquals(SSLEngineResult.Status.BUFFER_OVERFLOW, result.getStatus());
        assertEquals(remaining, encryptedClientToServer.remaining());
        // now with big enough buffer
        result = server.unwrap(encryptedClientToServer, plainServerIn);
        assertEquals(SSLEngineResult.Status.OK, result.getStatus());
        assertEquals(5, result.bytesProduced());
        assertTrue(encryptedClientToServer.hasRemaining());
        result = server.unwrap(encryptedClientToServer, plainServerIn);
        assertEquals(SSLEngineResult.Status.OK, result.getStatus());
        assertEquals(6, result.bytesProduced());
        assertFalse(encryptedClientToServer.hasRemaining());
        plainServerIn.flip();
        assertEquals(ByteBuffer.wrap(bytes), plainServerIn);
    } finally {
        cleanupClientSslEngine(client);
        cleanupServerSslEngine(server);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SSLEngineResult(javax.net.ssl.SSLEngineResult) SSLEngine(javax.net.ssl.SSLEngine) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 19 with SelfSignedCertificate

use of io.netty.handler.ssl.util.SelfSignedCertificate in project netty by netty.

the class SSLEngineTest method testCloseNotifySequence.

@Test
public void testCloseNotifySequence() throws Exception {
    SelfSignedCertificate cert = new SelfSignedCertificate();
    clientSslCtx = SslContextBuilder.forClient().trustManager(cert.cert()).sslProvider(sslClientProvider()).build();
    SSLEngine client = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
    serverSslCtx = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()).sslProvider(sslServerProvider()).build();
    SSLEngine server = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
    try {
        ByteBuffer plainClientOut = allocateBuffer(client.getSession().getApplicationBufferSize());
        ByteBuffer plainServerOut = allocateBuffer(server.getSession().getApplicationBufferSize());
        ByteBuffer encryptedClientToServer = allocateBuffer(client.getSession().getPacketBufferSize());
        ByteBuffer encryptedServerToClient = allocateBuffer(server.getSession().getPacketBufferSize());
        ByteBuffer empty = allocateBuffer(0);
        handshake(client, server);
        // This will produce a close_notify
        client.closeOutbound();
        // Something still pending in the outbound buffer.
        assertFalse(client.isOutboundDone());
        assertFalse(client.isInboundDone());
        // Now wrap and so drain the outbound buffer.
        SSLEngineResult result = client.wrap(empty, encryptedClientToServer);
        encryptedClientToServer.flip();
        assertEquals(SSLEngineResult.Status.CLOSED, result.getStatus());
        // Need an UNWRAP to read the response of the close_notify
        assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP, result.getHandshakeStatus());
        int produced = result.bytesProduced();
        int consumed = result.bytesConsumed();
        int closeNotifyLen = produced;
        assertTrue(produced > 0);
        assertEquals(0, consumed);
        assertEquals(produced, encryptedClientToServer.remaining());
        // Outbound buffer should be drained now.
        assertTrue(client.isOutboundDone());
        assertFalse(client.isInboundDone());
        assertFalse(server.isOutboundDone());
        assertFalse(server.isInboundDone());
        result = server.unwrap(encryptedClientToServer, plainServerOut);
        plainServerOut.flip();
        assertEquals(SSLEngineResult.Status.CLOSED, result.getStatus());
        // Need a WRAP to respond to the close_notify
        assertEquals(SSLEngineResult.HandshakeStatus.NEED_WRAP, result.getHandshakeStatus());
        produced = result.bytesProduced();
        consumed = result.bytesConsumed();
        assertEquals(closeNotifyLen, consumed);
        assertEquals(0, produced);
        // Should have consumed the complete close_notify
        assertEquals(0, encryptedClientToServer.remaining());
        assertEquals(0, plainServerOut.remaining());
        assertFalse(server.isOutboundDone());
        assertTrue(server.isInboundDone());
        result = server.wrap(empty, encryptedServerToClient);
        encryptedServerToClient.flip();
        assertEquals(SSLEngineResult.Status.CLOSED, result.getStatus());
        // UNWRAP/WRAP are not expected after this point
        assertEquals(SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, result.getHandshakeStatus());
        produced = result.bytesProduced();
        consumed = result.bytesConsumed();
        assertEquals(closeNotifyLen, produced);
        assertEquals(0, consumed);
        assertEquals(produced, encryptedServerToClient.remaining());
        assertTrue(server.isOutboundDone());
        assertTrue(server.isInboundDone());
        result = client.unwrap(encryptedServerToClient, plainClientOut);
        plainClientOut.flip();
        assertEquals(SSLEngineResult.Status.CLOSED, result.getStatus());
        // UNWRAP/WRAP are not expected after this point
        assertEquals(SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, result.getHandshakeStatus());
        produced = result.bytesProduced();
        consumed = result.bytesConsumed();
        assertEquals(closeNotifyLen, consumed);
        assertEquals(0, produced);
        assertEquals(0, encryptedServerToClient.remaining());
        assertTrue(client.isOutboundDone());
        assertTrue(client.isInboundDone());
        // Ensure that calling wrap or unwrap again will not produce a SSLException
        encryptedServerToClient.clear();
        plainServerOut.clear();
        result = server.wrap(plainServerOut, encryptedServerToClient);
        assertEngineRemainsClosed(result);
        encryptedClientToServer.clear();
        plainServerOut.clear();
        result = server.unwrap(encryptedClientToServer, plainServerOut);
        assertEngineRemainsClosed(result);
        encryptedClientToServer.clear();
        plainClientOut.clear();
        result = client.wrap(plainClientOut, encryptedClientToServer);
        assertEngineRemainsClosed(result);
        encryptedServerToClient.clear();
        plainClientOut.clear();
        result = client.unwrap(encryptedServerToClient, plainClientOut);
        assertEngineRemainsClosed(result);
    } finally {
        cert.delete();
        cleanupClientSslEngine(client);
        cleanupServerSslEngine(server);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SSLEngineResult(javax.net.ssl.SSLEngineResult) SSLEngine(javax.net.ssl.SSLEngine) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 20 with SelfSignedCertificate

use of io.netty.handler.ssl.util.SelfSignedCertificate in project netty by netty.

the class SSLEngineTest method testProtocol.

private void testProtocol(String[] clientProtocols, String[] serverProtocols) throws Exception {
    SelfSignedCertificate cert = new SelfSignedCertificate();
    clientSslCtx = SslContextBuilder.forClient().trustManager(cert.cert()).sslProvider(sslClientProvider()).protocols(clientProtocols).build();
    SSLEngine client = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
    serverSslCtx = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()).sslProvider(sslServerProvider()).protocols(serverProtocols).build();
    SSLEngine server = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
    try {
        handshake(client, server);
    } finally {
        cleanupClientSslEngine(client);
        cleanupServerSslEngine(server);
        cert.delete();
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SSLEngine(javax.net.ssl.SSLEngine)

Aggregations

SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)63 Test (org.junit.Test)32 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)28 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)26 EventLoopGroup (io.netty.channel.EventLoopGroup)25 SSLEngine (javax.net.ssl.SSLEngine)25 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)21 LoggingHandler (io.netty.handler.logging.LoggingHandler)19 SslContext (io.netty.handler.ssl.SslContext)19 Channel (io.netty.channel.Channel)17 ByteBuffer (java.nio.ByteBuffer)11 SSLEngineResult (javax.net.ssl.SSLEngineResult)10 Bootstrap (io.netty.bootstrap.Bootstrap)9 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)7 ChannelFuture (io.netty.channel.ChannelFuture)6 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)6 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)6 SocketChannel (io.netty.channel.socket.SocketChannel)6 File (java.io.File)6