Search in sources :

Example 21 with SSLException

use of javax.net.ssl.SSLException 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 22 with SSLException

use of javax.net.ssl.SSLException in project netty by netty.

the class SSLEngineTest method testSSLEngineUnwrapNoSslRecord.

@Test
public void testSSLEngineUnwrapNoSslRecord() throws Exception {
    clientSslCtx = SslContextBuilder.forClient().sslProvider(sslClientProvider()).build();
    SSLEngine client = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
    try {
        ByteBuffer src = allocateBuffer(client.getSession().getApplicationBufferSize());
        ByteBuffer dst = allocateBuffer(client.getSession().getPacketBufferSize());
        ByteBuffer empty = allocateBuffer(0);
        SSLEngineResult clientResult = client.wrap(empty, dst);
        assertEquals(SSLEngineResult.Status.OK, clientResult.getStatus());
        assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP, clientResult.getHandshakeStatus());
        try {
            client.unwrap(src, dst);
            fail();
        } catch (SSLException expected) {
        // expected
        }
    } finally {
        cleanupClientSslEngine(client);
    }
}
Also used : SSLEngineResult(javax.net.ssl.SSLEngineResult) SSLEngine(javax.net.ssl.SSLEngine) ByteBuffer(java.nio.ByteBuffer) SSLException(javax.net.ssl.SSLException) Test(org.junit.Test)

Example 23 with SSLException

use of javax.net.ssl.SSLException in project netty by netty.

the class SSLEngineTest method mySetupClientHostnameValidation.

private void mySetupClientHostnameValidation(File serverCrtFile, File serverKeyFile, File clientTrustCrtFile, final boolean failureExpected) throws SSLException, InterruptedException {
    final String expectedHost = "localhost";
    serverSslCtx = SslContextBuilder.forServer(serverCrtFile, serverKeyFile, null).sslProvider(sslServerProvider()).trustManager(InsecureTrustManagerFactory.INSTANCE).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build();
    clientSslCtx = SslContextBuilder.forClient().sslProvider(sslClientProvider()).trustManager(clientTrustCrtFile).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) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(serverSslCtx.newHandler(ch.alloc()));
            p.addLast(new MessageDelegatorChannelHandler(serverReceiver, serverLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == SslHandshakeCompletionEvent.SUCCESS) {
                        if (failureExpected) {
                            serverException = new IllegalStateException("handshake complete. expected failure");
                        }
                        serverLatch.countDown();
                    } else if (evt instanceof SslHandshakeCompletionEvent) {
                        serverException = ((SslHandshakeCompletionEvent) evt).cause();
                        serverLatch.countDown();
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @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);
                    }
                }
            });
            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();
            InetSocketAddress remoteAddress = (InetSocketAddress) serverChannel.localAddress();
            SslHandler sslHandler = clientSslCtx.newHandler(ch.alloc(), expectedHost, 0);
            SSLParameters parameters = sslHandler.engine().getSSLParameters();
            parameters.setEndpointIdentificationAlgorithm("HTTPS");
            sslHandler.engine().setSSLParameters(parameters);
            p.addLast(sslHandler);
            p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == SslHandshakeCompletionEvent.SUCCESS) {
                        if (failureExpected) {
                            clientException = new IllegalStateException("handshake complete. expected failure");
                        }
                        clientLatch.countDown();
                    } else if (evt instanceof SslHandshakeCompletionEvent) {
                        clientException = ((SslHandshakeCompletionEvent) evt).cause();
                        clientLatch.countDown();
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @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(expectedHost, 0)).sync().channel();
    final int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
    ChannelFuture ccf = cb.connect(new InetSocketAddress(expectedHost, port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLParameters(javax.net.ssl.SSLParameters) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 24 with SSLException

use of javax.net.ssl.SSLException in project netty by netty.

the class SSLEngineTest method mySetupMutualAuth.

private void mySetupMutualAuth(File servertTrustCrtFile, File serverKeyFile, final File serverCrtFile, String serverKeyPassword, File clientTrustCrtFile, File clientKeyFile, File clientCrtFile, String clientKeyPassword) throws InterruptedException, SSLException {
    serverSslCtx = SslContextBuilder.forServer(serverCrtFile, serverKeyFile, serverKeyPassword).sslProvider(sslServerProvider()).trustManager(servertTrustCrtFile).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build();
    clientSslCtx = SslContextBuilder.forClient().sslProvider(sslClientProvider()).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) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            SSLEngine engine = 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 {
                            InputStream in = new FileInputStream(serverCrtFile);
                            try {
                                final byte[] cert = SslContext.X509_CERT_FACTORY.generateCertificate(in).getEncoded();
                                // Verify session
                                SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession();
                                assertEquals(1, session.getPeerCertificates().length);
                                assertArrayEquals(cert, session.getPeerCertificates()[0].getEncoded());
                                assertEquals(1, session.getPeerCertificateChain().length);
                                assertArrayEquals(cert, session.getPeerCertificateChain()[0].getEncoded());
                                assertEquals(1, session.getLocalCertificates().length);
                                assertArrayEquals(cert, session.getLocalCertificates()[0].getEncoded());
                                assertEquals(PRINCIPAL_NAME, session.getLocalPrincipal().getName());
                                assertEquals(PRINCIPAL_NAME, session.getPeerPrincipal().getName());
                            } finally {
                                in.close();
                            }
                        } 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(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientSslCtx.newHandler(ch.alloc()));
            p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    cause.printStackTrace();
                    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();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SSLEngine(javax.net.ssl.SSLEngine) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) InetSocketAddress(java.net.InetSocketAddress) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SSLSession(javax.net.ssl.SSLSession) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) FileInputStream(java.io.FileInputStream) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 25 with SSLException

use of javax.net.ssl.SSLException in project netty by netty.

the class SSLEngineTest method setupHandlers.

protected void setupHandlers(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();
            p.addLast(serverSslCtx.newHandler(ch.alloc()));
            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();
            p.addLast(clientSslCtx.newHandler(ch.alloc()));
            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);
                    }
                }
            });
        }
    });
    serverChannel = sb.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.syncUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Aggregations

SSLException (javax.net.ssl.SSLException)326 IOException (java.io.IOException)106 CertificateException (java.security.cert.CertificateException)54 X509Certificate (java.security.cert.X509Certificate)43 SslContext (io.netty.handler.ssl.SslContext)37 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)37 InetSocketAddress (java.net.InetSocketAddress)35 SSLEngineResult (javax.net.ssl.SSLEngineResult)34 SocketException (java.net.SocketException)33 Test (org.junit.Test)33 ByteBuffer (java.nio.ByteBuffer)32 SSLEngine (javax.net.ssl.SSLEngine)30 KeyStore (java.security.KeyStore)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)29 SSLSocket (javax.net.ssl.SSLSocket)29 InputStream (java.io.InputStream)26 SSLContext (javax.net.ssl.SSLContext)25 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)24 Bootstrap (io.netty.bootstrap.Bootstrap)23 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)22