Search in sources :

Example 61 with SSLEngine

use of javax.net.ssl.SSLEngine 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 62 with SSLEngine

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

the class SSLEngineTest method testCloseInboundAfterBeginHandshake.

@Test
public void testCloseInboundAfterBeginHandshake() 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 {
        testCloseInboundAfterBeginHandshake(client);
        testCloseInboundAfterBeginHandshake(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 63 with SSLEngine

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

the class OpenSslEngineTest method testNeededDstCapacityIsCorrectlyCalculated.

@Test
public void testNeededDstCapacityIsCorrectlyCalculated() throws Exception {
    clientSslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(sslClientProvider()).build();
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(sslServerProvider()).build();
    SSLEngine clientEngine = null;
    SSLEngine serverEngine = null;
    try {
        clientEngine = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
        serverEngine = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
        handshake(clientEngine, serverEngine);
        ByteBuffer src = allocateBuffer(1024);
        ByteBuffer src2 = src.duplicate();
        ByteBuffer dst = allocateBuffer(src.capacity() + MAX_TLS_RECORD_OVERHEAD_LENGTH);
        SSLEngineResult result = clientEngine.wrap(new ByteBuffer[] { src, src2 }, dst);
        assertEquals(SSLEngineResult.Status.BUFFER_OVERFLOW, result.getStatus());
        assertEquals(0, src.position());
        assertEquals(0, src2.position());
        assertEquals(0, dst.position());
        assertEquals(0, result.bytesConsumed());
        assertEquals(0, result.bytesProduced());
    } finally {
        cleanupClientSslEngine(clientEngine);
        cleanupServerSslEngine(serverEngine);
    }
}
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 64 with SSLEngine

use of javax.net.ssl.SSLEngine in project camel by apache.

the class SSLEngineFactory method createServerSSLEngine.

public SSLEngine createServerSSLEngine(SSLContext sslContext) {
    SSLEngine serverEngine = sslContext.createSSLEngine();
    serverEngine.setUseClientMode(false);
    serverEngine.setNeedClientAuth(true);
    return serverEngine;
}
Also used : SSLEngine(javax.net.ssl.SSLEngine)

Example 65 with SSLEngine

use of javax.net.ssl.SSLEngine in project camel by apache.

the class SSLContextParametersTest method testSecureSocketProtocolsFilter.

public void testSecureSocketProtocolsFilter() throws Exception {
    SSLContext controlContext = SSLContext.getInstance("TLS");
    controlContext.init(null, null, null);
    SSLEngine controlEngine = controlContext.createSSLEngine();
    SSLSocket controlSocket = (SSLSocket) controlContext.getSocketFactory().createSocket();
    SSLServerSocket controlServerSocket = (SSLServerSocket) controlContext.getServerSocketFactory().createServerSocket();
    // default
    SSLContextParameters scp = new SSLContextParameters();
    SSLContext context = scp.createSSLContext();
    SSLEngine engine = context.createSSLEngine();
    SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket();
    SSLServerSocket serverSocket = (SSLServerSocket) context.getServerSocketFactory().createServerSocket();
    // default disable the SSL* protocols
    assertStartsWith(engine.getEnabledProtocols(), "TLS");
    assertStartsWith(socket.getEnabledProtocols(), "TLS");
    assertStartsWith(serverSocket.getEnabledProtocols(), "TLS");
    // empty filter
    FilterParameters filter = new FilterParameters();
    scp.setSecureSocketProtocolsFilter(filter);
    context = scp.createSSLContext();
    engine = context.createSSLEngine();
    socket = (SSLSocket) context.getSocketFactory().createSocket();
    serverSocket = (SSLServerSocket) context.getServerSocketFactory().createServerSocket();
    assertEquals(0, engine.getEnabledProtocols().length);
    assertEquals(0, socket.getEnabledProtocols().length);
    assertEquals(0, serverSocket.getEnabledProtocols().length);
    // explicit filter
    filter.getInclude().add(".*");
    context = scp.createSSLContext();
    engine = context.createSSLEngine();
    socket = (SSLSocket) context.getSocketFactory().createSocket();
    serverSocket = (SSLServerSocket) context.getServerSocketFactory().createServerSocket();
    assertTrue(Arrays.equals(controlEngine.getEnabledProtocols(), engine.getEnabledProtocols()));
    assertTrue(Arrays.equals(controlSocket.getEnabledProtocols(), socket.getEnabledProtocols()));
    checkProtocols(controlServerSocket.getEnabledProtocols(), serverSocket.getEnabledProtocols());
    // explicit filter with excludes (excludes overrides)
    filter.getExclude().add(".*");
    context = scp.createSSLContext();
    engine = context.createSSLEngine();
    socket = (SSLSocket) context.getSocketFactory().createSocket();
    serverSocket = (SSLServerSocket) context.getServerSocketFactory().createServerSocket();
    assertEquals(0, engine.getEnabledProtocols().length);
    assertEquals(0, socket.getEnabledProtocols().length);
    assertEquals(0, serverSocket.getEnabledProtocols().length);
    // explicit filter single include
    filter.getInclude().clear();
    filter.getExclude().clear();
    filter.getInclude().add("TLS.*");
    context = scp.createSSLContext();
    engine = context.createSSLEngine();
    socket = (SSLSocket) context.getSocketFactory().createSocket();
    serverSocket = (SSLServerSocket) context.getServerSocketFactory().createServerSocket();
    // not all platforms/JDKs have these cipher suites
    if (!isPlatform("aix")) {
        assertTrue(engine.getEnabledProtocols().length >= 1);
        assertStartsWith(engine.getEnabledProtocols(), "TLS");
        assertTrue(socket.getEnabledProtocols().length >= 1);
        assertStartsWith(socket.getEnabledProtocols(), "TLS");
        assertTrue(socket.getEnabledProtocols().length >= 1);
        assertStartsWith(serverSocket.getEnabledProtocols(), "TLS");
    }
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) SSLSocket(javax.net.ssl.SSLSocket) SSLContext(javax.net.ssl.SSLContext) SSLServerSocket(javax.net.ssl.SSLServerSocket)

Aggregations

SSLEngine (javax.net.ssl.SSLEngine)494 IOException (java.io.IOException)97 SSLContext (javax.net.ssl.SSLContext)97 ByteBuffer (java.nio.ByteBuffer)91 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)75 SSLException (javax.net.ssl.SSLException)71 Test (org.junit.Test)64 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)54 SslHandler (io.netty.handler.ssl.SslHandler)52 SSLEngineResult (javax.net.ssl.SSLEngineResult)50 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)47 MethodSource (org.junit.jupiter.params.provider.MethodSource)44 SSLParameters (javax.net.ssl.SSLParameters)43 InetSocketAddress (java.net.InetSocketAddress)42 KeyManagementException (java.security.KeyManagementException)42 ReadOnlyBufferException (java.nio.ReadOnlyBufferException)35 KeyStore (java.security.KeyStore)28 Test (org.junit.jupiter.api.Test)22 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)21 Socket (java.net.Socket)21