Search in sources :

Example 26 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 27 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 28 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 29 with SslHandler

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

the class HttpClientInitializerFactory method initChannel.

@Override
protected void initChannel(Channel ch) throws Exception {
    // create a new pipeline
    ChannelPipeline pipeline = ch.pipeline();
    SslHandler sslHandler = configureClientSSLOnDemand();
    if (sslHandler != null) {
        //TODO must close on SSL exception
        //sslHandler.setCloseOnSSLException(true);
        LOG.debug("Client SSL handler configured and added as an interceptor against the ChannelPipeline: {}", sslHandler);
        pipeline.addLast("ssl", sslHandler);
    }
    pipeline.addLast("http", new HttpClientCodec());
    List<ChannelHandler> encoders = producer.getConfiguration().getEncoders();
    for (int x = 0; x < encoders.size(); x++) {
        ChannelHandler encoder = encoders.get(x);
        if (encoder instanceof ChannelHandlerFactory) {
            // use the factory to create a new instance of the channel as it may not be shareable
            encoder = ((ChannelHandlerFactory) encoder).newChannelHandler();
        }
        pipeline.addLast("encoder-" + x, encoder);
    }
    List<ChannelHandler> decoders = producer.getConfiguration().getDecoders();
    for (int x = 0; x < decoders.size(); x++) {
        ChannelHandler decoder = decoders.get(x);
        if (decoder instanceof ChannelHandlerFactory) {
            // use the factory to create a new instance of the channel as it may not be shareable
            decoder = ((ChannelHandlerFactory) decoder).newChannelHandler();
        }
        pipeline.addLast("decoder-" + x, decoder);
    }
    pipeline.addLast("aggregator", new HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
    if (producer.getConfiguration().getRequestTimeout() > 0) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using request timeout {} millis", producer.getConfiguration().getRequestTimeout());
        }
        ChannelHandler timeout = new ReadTimeoutHandler(producer.getConfiguration().getRequestTimeout(), TimeUnit.MILLISECONDS);
        pipeline.addLast("timeout", timeout);
    }
    // handler to route Camel messages
    pipeline.addLast("handler", new HttpClientChannelHandler(producer));
}
Also used : HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) HttpClientChannelHandler(org.apache.camel.component.netty4.http.handlers.HttpClientChannelHandler) ChannelHandlerFactory(org.apache.camel.component.netty4.ChannelHandlerFactory) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpClientChannelHandler(org.apache.camel.component.netty4.http.handlers.HttpClientChannelHandler) ChannelHandler(io.netty.channel.ChannelHandler) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler)

Example 30 with SslHandler

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

the class HttpServerInitializerFactory method initChannel.

@Override
protected void initChannel(Channel ch) throws Exception {
    // create a new pipeline
    ChannelPipeline pipeline = ch.pipeline();
    SslHandler sslHandler = configureServerSSLOnDemand();
    if (sslHandler != null) {
        //TODO must close on SSL exception
        // sslHandler.setCloseOnSSLException(true);
        LOG.debug("Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}", sslHandler);
        pipeline.addLast("ssl", sslHandler);
    }
    pipeline.addLast("decoder", new HttpRequestDecoder(4096, configuration.getMaxHeaderSize(), 8192));
    List<ChannelHandler> decoders = consumer.getConfiguration().getDecoders();
    for (int x = 0; x < decoders.size(); x++) {
        ChannelHandler decoder = decoders.get(x);
        if (decoder instanceof ChannelHandlerFactory) {
            // use the factory to create a new instance of the channel as it may not be shareable
            decoder = ((ChannelHandlerFactory) decoder).newChannelHandler();
        }
        pipeline.addLast("decoder-" + x, decoder);
    }
    pipeline.addLast("encoder", new HttpResponseEncoder());
    List<ChannelHandler> encoders = consumer.getConfiguration().getEncoders();
    for (int x = 0; x < encoders.size(); x++) {
        ChannelHandler encoder = encoders.get(x);
        if (encoder instanceof ChannelHandlerFactory) {
            // use the factory to create a new instance of the channel as it may not be shareable
            encoder = ((ChannelHandlerFactory) encoder).newChannelHandler();
        }
        pipeline.addLast("encoder-" + x, encoder);
    }
    pipeline.addLast("aggregator", new HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
    if (supportCompressed()) {
        pipeline.addLast("deflater", new HttpContentCompressor());
    }
    int port = consumer.getConfiguration().getPort();
    ChannelHandler handler = consumer.getEndpoint().getComponent().getMultiplexChannelHandler(port).getChannelHandler();
    if (consumer.getConfiguration().isUsingExecutorService()) {
        EventExecutorGroup applicationExecutor = consumer.getEndpoint().getComponent().getExecutorService();
        pipeline.addLast(applicationExecutor, "handler", handler);
    } else {
        pipeline.addLast("handler", handler);
    }
}
Also used : HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) ChannelHandlerFactory(org.apache.camel.component.netty4.ChannelHandlerFactory) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpContentCompressor(io.netty.handler.codec.http.HttpContentCompressor) ChannelHandler(io.netty.channel.ChannelHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler)

Aggregations

SslHandler (io.netty.handler.ssl.SslHandler)41 SSLEngine (javax.net.ssl.SSLEngine)19 ChannelPipeline (io.netty.channel.ChannelPipeline)13 ChannelHandler (io.netty.channel.ChannelHandler)11 Channel (io.netty.channel.Channel)6 SocketChannel (io.netty.channel.socket.SocketChannel)6 ByteBuf (io.netty.buffer.ByteBuf)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)5 ChunkedWriteHandler (io.netty.handler.stream.ChunkedWriteHandler)5 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)5 ServerTlsHandler (io.grpc.netty.ProtocolNegotiators.ServerTlsHandler)4 Bootstrap (io.netty.bootstrap.Bootstrap)4 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)4 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)4 IOException (java.io.IOException)4 Test (org.junit.Test)4 ChannelFuture (io.netty.channel.ChannelFuture)3 ChannelInitializer (io.netty.channel.ChannelInitializer)3 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)3 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)3