Search in sources :

Example 1 with SimpleTrustManagerFactory

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

the class SslHandlerTest method testAlertProducedAndSend.

private void testAlertProducedAndSend(SslProvider provider) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider).trustManager(new SimpleTrustManagerFactory() {

        @Override
        protected void engineInit(KeyStore keyStore) {
        }

        @Override
        protected void engineInit(ManagerFactoryParameters managerFactoryParameters) {
        }

        @Override
        protected TrustManager[] engineGetTrustManagers() {
            return new TrustManager[] { new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    // Fail verification which should produce an alert that is send back to the client.
                    throw new CertificateException();
                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
                // NOOP
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return EmptyArrays.EMPTY_X509_CERTIFICATES;
                }
            } };
        }
    }).clientAuth(ClientAuth.REQUIRE).build();
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).keyManager(new File(getClass().getResource("test.crt").getFile()), new File(getClass().getResource("test_unencrypted.pem").getFile())).sslProvider(provider).build();
    NioEventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    try {
        final Promise<Void> promise = group.next().newPromise();
        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(ch.alloc()));
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        // Just trigger a close
                        ctx.close();
                    }
                });
            }
        }).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(sslClientCtx.newHandler(ch.alloc()));
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        if (cause.getCause() instanceof SSLException) {
                            // We received the alert and so produce an SSLException.
                            promise.setSuccess(null);
                        }
                    }
                });
            }
        }).connect(sc.localAddress()).syncUninterruptibly().channel();
        promise.syncUninterruptibly();
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslServerCtx);
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) InetSocketAddress(java.net.InetSocketAddress) CertificateException(java.security.cert.CertificateException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SSLException(javax.net.ssl.SSLException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) 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) SimpleTrustManagerFactory(io.netty.handler.ssl.util.SimpleTrustManagerFactory) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) 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) X509TrustManager(javax.net.ssl.X509TrustManager) File(java.io.File) ManagerFactoryParameters(javax.net.ssl.ManagerFactoryParameters) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 2 with SimpleTrustManagerFactory

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

the class SslErrorTest method testCorrectAlert.

@Test(timeout = 30000)
public void testCorrectAlert() 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.
    Assume.assumeTrue(OpenSsl.isAvailable());
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(serverProvider).trustManager(new SimpleTrustManagerFactory() {

        @Override
        protected void engineInit(KeyStore keyStore) {
        }

        @Override
        protected void engineInit(ManagerFactoryParameters managerFactoryParameters) {
        }

        @Override
        protected TrustManager[] engineGetTrustManagers() {
            return new TrustManager[] { new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    throw exception;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                // NOOP
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return EmptyArrays.EMPTY_X509_CERTIFICATES;
                }
            } };
        }
    }).clientAuth(ClientAuth.REQUIRE).build();
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).keyManager(new File(getClass().getResource("test.crt").getFile()), new File(getClass().getResource("test_unencrypted.pem").getFile())).sslProvider(clientProvider).build();
    Channel serverChannel = null;
    Channel clientChannel = null;
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        serverChannel = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<Channel>() {

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

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

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

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        // Unwrap as its wrapped by a DecoderException
                        Throwable unwrappedCause = cause.getCause();
                        if (unwrappedCause instanceof SSLException) {
                            if (exception instanceof TestCertificateException) {
                                CertPathValidatorException.Reason reason = ((CertPathValidatorException) exception.getCause()).getReason();
                                if (reason == CertPathValidatorException.BasicReason.EXPIRED) {
                                    verifyException(unwrappedCause, "expired", promise);
                                } else if (reason == CertPathValidatorException.BasicReason.NOT_YET_VALID) {
                                    verifyException(unwrappedCause, "bad", promise);
                                } else if (reason == CertPathValidatorException.BasicReason.REVOKED) {
                                    verifyException(unwrappedCause, "revoked", promise);
                                }
                            } else if (exception instanceof CertificateExpiredException) {
                                verifyException(unwrappedCause, "expired", promise);
                            } else if (exception instanceof CertificateNotYetValidException) {
                                verifyException(unwrappedCause, "bad", promise);
                            } else if (exception instanceof CertificateRevokedException) {
                                verifyException(unwrappedCause, "revoked", promise);
                            }
                        }
                    }
                });
            }
        }).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) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) CertificateException(java.security.cert.CertificateException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SSLException(javax.net.ssl.SSLException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CertificateRevokedException(java.security.cert.CertificateRevokedException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) SimpleTrustManagerFactory(io.netty.handler.ssl.util.SimpleTrustManagerFactory) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertificateRevokedException(java.security.cert.CertificateRevokedException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) CertPathValidatorException(java.security.cert.CertPathValidatorException) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) X509TrustManager(javax.net.ssl.X509TrustManager) File(java.io.File) ManagerFactoryParameters(javax.net.ssl.ManagerFactoryParameters) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)2 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)2 Channel (io.netty.channel.Channel)2 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)2 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)2 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)2 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)2 SimpleTrustManagerFactory (io.netty.handler.ssl.util.SimpleTrustManagerFactory)2 File (java.io.File)2 KeyStore (java.security.KeyStore)2 CertificateException (java.security.cert.CertificateException)2 X509Certificate (java.security.cert.X509Certificate)2 ManagerFactoryParameters (javax.net.ssl.ManagerFactoryParameters)2 SSLException (javax.net.ssl.SSLException)2 X509TrustManager (javax.net.ssl.X509TrustManager)2 EventLoopGroup (io.netty.channel.EventLoopGroup)1 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)1 CodecException (io.netty.handler.codec.CodecException)1