Search in sources :

Example 36 with SslHandler

use of io.netty.handler.ssl.SslHandler in project grpc-java by grpc.

the class ProtocolNegotiators method logSslEngineDetails.

@VisibleForTesting
static void logSslEngineDetails(Level level, ChannelHandlerContext ctx, String msg, @Nullable Throwable t) {
    if (!log.isLoggable(level)) {
        return;
    }
    SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
    SSLEngine engine = sslHandler.engine();
    StringBuilder builder = new StringBuilder(msg);
    builder.append("\nSSLEngine Details: [\n");
    if (engine instanceof OpenSslEngine) {
        builder.append("    OpenSSL, ");
        builder.append("Version: 0x").append(Integer.toHexString(OpenSsl.version()));
        builder.append(" (").append(OpenSsl.versionString()).append("), ");
        builder.append("ALPN supported: ").append(OpenSsl.isAlpnSupported());
    } else if (JettyTlsUtil.isJettyAlpnConfigured()) {
        builder.append("    Jetty ALPN");
    } else if (JettyTlsUtil.isJettyNpnConfigured()) {
        builder.append("    Jetty NPN");
    }
    builder.append("\n    TLS Protocol: ");
    builder.append(engine.getSession().getProtocol());
    builder.append("\n    Application Protocol: ");
    builder.append(sslHandler.applicationProtocol());
    builder.append("\n    Need Client Auth: ");
    builder.append(engine.getNeedClientAuth());
    builder.append("\n    Want Client Auth: ");
    builder.append(engine.getWantClientAuth());
    builder.append("\n    Supported protocols=");
    builder.append(Arrays.toString(engine.getSupportedProtocols()));
    builder.append("\n    Enabled protocols=");
    builder.append(Arrays.toString(engine.getEnabledProtocols()));
    builder.append("\n    Supported ciphers=");
    builder.append(Arrays.toString(engine.getSupportedCipherSuites()));
    builder.append("\n    Enabled ciphers=");
    builder.append(Arrays.toString(engine.getEnabledCipherSuites()));
    builder.append("\n]");
    log.log(level, builder.toString(), t);
}
Also used : OpenSslEngine(io.netty.handler.ssl.OpenSslEngine) SSLEngine(javax.net.ssl.SSLEngine) SslHandler(io.netty.handler.ssl.SslHandler) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 37 with SslHandler

use of io.netty.handler.ssl.SslHandler in project netty by netty.

the class SocketSslEchoTest method testSslEcho.

public void testSslEcho(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    final ExecutorService delegatedTaskExecutor = Executors.newCachedThreadPool();
    reset();
    sb.childOption(ChannelOption.AUTO_READ, autoRead);
    cb.option(ChannelOption.AUTO_READ, autoRead);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        @SuppressWarnings("deprecation")
        public void initChannel(Channel sch) throws Exception {
            serverChannel = sch;
            if (serverUsesDelegatedTaskExecutor) {
                SSLEngine sse = serverCtx.newEngine(sch.alloc());
                serverSslHandler = new SslHandler(sse, delegatedTaskExecutor);
            } else {
                serverSslHandler = serverCtx.newHandler(sch.alloc());
            }
            sch.pipeline().addLast("ssl", serverSslHandler);
            if (useChunkedWriteHandler) {
                sch.pipeline().addLast(new ChunkedWriteHandler());
            }
            sch.pipeline().addLast("handler", serverHandler);
        }
    });
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        @SuppressWarnings("deprecation")
        public void initChannel(Channel sch) throws Exception {
            clientChannel = sch;
            if (clientUsesDelegatedTaskExecutor) {
                SSLEngine cse = clientCtx.newEngine(sch.alloc());
                clientSslHandler = new SslHandler(cse, delegatedTaskExecutor);
            } else {
                clientSslHandler = clientCtx.newHandler(sch.alloc());
            }
            sch.pipeline().addLast("ssl", clientSslHandler);
            if (useChunkedWriteHandler) {
                sch.pipeline().addLast(new ChunkedWriteHandler());
            }
            sch.pipeline().addLast("handler", clientHandler);
        }
    });
    final Channel sc = sb.bind().sync().channel();
    cb.connect().sync();
    final Future<Channel> clientHandshakeFuture = clientSslHandler.handshakeFuture();
    clientChannel.writeAndFlush(Unpooled.wrappedBuffer(data, 0, FIRST_MESSAGE_SIZE));
    clientSendCounter.set(FIRST_MESSAGE_SIZE);
    clientHandshakeFuture.sync();
    boolean needsRenegotiation = renegotiation.type == RenegotiationType.CLIENT_INITIATED;
    Future<Channel> renegoFuture = null;
    while (clientSendCounter.get() < data.length) {
        int clientSendCounterVal = clientSendCounter.get();
        int length = Math.min(random.nextInt(1024 * 64), data.length - clientSendCounterVal);
        ByteBuf buf = Unpooled.wrappedBuffer(data, clientSendCounterVal, length);
        if (useCompositeByteBuf) {
            buf = Unpooled.compositeBuffer().addComponent(true, buf);
        }
        ChannelFuture future = clientChannel.writeAndFlush(buf);
        clientSendCounter.set(clientSendCounterVal += length);
        future.sync();
        if (needsRenegotiation && clientSendCounterVal >= data.length / 2) {
            needsRenegotiation = false;
            clientSslHandler.engine().setEnabledCipherSuites(new String[] { renegotiation.cipherSuite });
            renegoFuture = clientSslHandler.renegotiate();
            logStats("CLIENT RENEGOTIATES");
            assertThat(renegoFuture, is(not(sameInstance(clientHandshakeFuture))));
        }
    }
    // Ensure all data has been exchanged.
    while (clientRecvCounter.get() < data.length) {
        if (serverException.get() != null) {
            break;
        }
        if (serverException.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // Ignore.
        }
    }
    while (serverRecvCounter.get() < data.length) {
        if (serverException.get() != null) {
            break;
        }
        if (clientException.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // Ignore.
        }
    }
    // Wait until renegotiation is done.
    if (renegoFuture != null) {
        renegoFuture.sync();
    }
    if (serverHandler.renegoFuture != null) {
        serverHandler.renegoFuture.sync();
    }
    serverChannel.close().awaitUninterruptibly();
    clientChannel.close().awaitUninterruptibly();
    sc.close().awaitUninterruptibly();
    delegatedTaskExecutor.shutdown();
    if (serverException.get() != null && !(serverException.get() instanceof IOException)) {
        throw serverException.get();
    }
    if (clientException.get() != null && !(clientException.get() instanceof IOException)) {
        throw clientException.get();
    }
    if (serverException.get() != null) {
        throw serverException.get();
    }
    if (clientException.get() != null) {
        throw clientException.get();
    }
    // When renegotiation is done, at least the initiating side should be notified.
    try {
        switch(renegotiation.type) {
            case SERVER_INITIATED:
                assertThat(serverSslHandler.engine().getSession().getCipherSuite(), is(renegotiation.cipherSuite));
                assertThat(serverNegoCounter.get(), is(2));
                assertThat(clientNegoCounter.get(), anyOf(is(1), is(2)));
                break;
            case CLIENT_INITIATED:
                assertThat(serverNegoCounter.get(), anyOf(is(1), is(2)));
                assertThat(clientSslHandler.engine().getSession().getCipherSuite(), is(renegotiation.cipherSuite));
                assertThat(clientNegoCounter.get(), is(2));
                break;
            case NONE:
                assertThat(serverNegoCounter.get(), is(1));
                assertThat(clientNegoCounter.get(), is(1));
        }
    } finally {
        logStats("STATS");
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SSLEngine(javax.net.ssl.SSLEngine) Channel(io.netty.channel.Channel) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SslHandler(io.netty.handler.ssl.SslHandler) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) ExecutorService(java.util.concurrent.ExecutorService)

Example 38 with SslHandler

use of io.netty.handler.ssl.SslHandler in project netty by netty.

the class SocketSslSessionReuseTest method testSslSessionReuse.

public void testSslSessionReuse(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    final ReadAndDiscardHandler sh = new ReadAndDiscardHandler(true, true);
    final ReadAndDiscardHandler ch = new ReadAndDiscardHandler(false, true);
    final String[] protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
    sb.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel sch) throws Exception {
            SSLEngine engine = serverCtx.newEngine(sch.alloc());
            engine.setUseClientMode(false);
            engine.setEnabledProtocols(protocols);
            sch.pipeline().addLast(new SslHandler(engine));
            sch.pipeline().addLast(sh);
        }
    });
    final Channel sc = sb.bind().sync().channel();
    cb.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel sch) throws Exception {
            InetSocketAddress serverAddr = (InetSocketAddress) sc.localAddress();
            SSLEngine engine = clientCtx.newEngine(sch.alloc(), serverAddr.getHostString(), serverAddr.getPort());
            engine.setUseClientMode(true);
            engine.setEnabledProtocols(protocols);
            sch.pipeline().addLast(new SslHandler(engine));
            sch.pipeline().addLast(ch);
        }
    });
    try {
        SSLSessionContext clientSessionCtx = ((JdkSslContext) clientCtx).sessionContext();
        ByteBuf msg = Unpooled.wrappedBuffer(new byte[] { 0xa, 0xb, 0xc, 0xd }, 0, 4);
        Channel cc = cb.connect().sync().channel();
        cc.writeAndFlush(msg).sync();
        cc.closeFuture().sync();
        rethrowHandlerExceptions(sh, ch);
        Set<String> sessions = sessionIdSet(clientSessionCtx.getIds());
        msg = Unpooled.wrappedBuffer(new byte[] { 0xa, 0xb, 0xc, 0xd }, 0, 4);
        cc = cb.connect().sync().channel();
        cc.writeAndFlush(msg).sync();
        cc.closeFuture().sync();
        assertEquals("Expected no new sessions", sessions, sessionIdSet(clientSessionCtx.getIds()));
        rethrowHandlerExceptions(sh, ch);
    } finally {
        sc.close().awaitUninterruptibly();
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) JdkSslContext(io.netty.handler.ssl.JdkSslContext) SSLSessionContext(javax.net.ssl.SSLSessionContext) SSLEngine(javax.net.ssl.SSLEngine) InetSocketAddress(java.net.InetSocketAddress) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ByteBuf(io.netty.buffer.ByteBuf) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SslHandler(io.netty.handler.ssl.SslHandler)

Example 39 with SslHandler

use of io.netty.handler.ssl.SslHandler in project ratpack by ratpack.

the class RequestActionSupport method createSslHandler.

private SslHandler createSslHandler() throws NoSuchAlgorithmException {
    SSLEngine sslEngine;
    if (requestConfig.sslContext != null) {
        sslEngine = requestConfig.sslContext.createSSLEngine();
    } else {
        sslEngine = SSLContext.getDefault().createSSLEngine();
    }
    sslEngine.setUseClientMode(true);
    return new SslHandler(sslEngine);
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) SslHandler(io.netty.handler.ssl.SslHandler)

Example 40 with SslHandler

use of io.netty.handler.ssl.SslHandler in project okhttp by square.

the class NettyHttpClient method prepare.

@Override
public void prepare(final Benchmark benchmark) {
    this.concurrencyLevel = benchmark.concurrencyLevel;
    this.targetBacklog = benchmark.targetBacklog;
    ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (benchmark.tls) {
                SslClient sslClient = SslClient.localhost();
                SSLEngine engine = sslClient.sslContext.createSSLEngine();
                engine.setUseClientMode(true);
                pipeline.addLast("ssl", new SslHandler(engine));
            }
            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("inflater", new HttpContentDecompressor());
            pipeline.addLast("handler", new HttpChannel(channel));
        }
    };
    bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup(concurrencyLevel)).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).channel(NioSocketChannel.class).handler(channelInitializer);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) SslClient(okhttp3.internal.tls.SslClient) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

SslHandler (io.netty.handler.ssl.SslHandler)46 SSLEngine (javax.net.ssl.SSLEngine)21 ChannelPipeline (io.netty.channel.ChannelPipeline)18 ChannelHandler (io.netty.channel.ChannelHandler)11 SocketChannel (io.netty.channel.socket.SocketChannel)9 Channel (io.netty.channel.Channel)7 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)6 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)6 ChunkedWriteHandler (io.netty.handler.stream.ChunkedWriteHandler)6 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)6 Bootstrap (io.netty.bootstrap.Bootstrap)5 ByteBuf (io.netty.buffer.ByteBuf)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)5 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)5 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)5 LoggingHandler (io.netty.handler.logging.LoggingHandler)5 File (java.io.File)5 ServerTlsHandler (io.grpc.netty.ProtocolNegotiators.ServerTlsHandler)4 ChannelFuture (io.netty.channel.ChannelFuture)4 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)4